diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 8b3568a8..588c29ab 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -29,10 +29,10 @@ jobs: - name: Build Admin dashboard UI run: npm --prefix=./ui ci && npm --prefix=./ui run build - # Similar to the above, the jsvm docs are pregenerated locally + # Similar to the above, the jsvm types are pregenerated locally # but its here to ensure that it wasn't forgotten to be executed. - name: Generate jsvm types - run: go run ./plugins/jsvm/internal/docs/docs.go + run: go run ./plugins/jsvm/internal/types/types.go # The prebuilt golangci-lint doesn't support go 1.18+ yet # https://github.com/golangci/golangci-lint/issues/2649 diff --git a/CHANGELOG.md b/CHANGELOG.md index 99989366..fa2dbf6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,14 +38,14 @@ - **!** Renamed `*Options` to `*Config` for consistency and replaced the unnecessary pointers with their value equivalent to keep the applied configuration defaults isolated within their function calls: ```go - old: pocketbase.NewWithConfig(config *pocketbase.Config) - new: pocketbase.NewWithConfig(config pocketbase.Config) + old: pocketbase.NewWithConfig(config *pocketbase.Config) *pocketbase.PocketBase + new: pocketbase.NewWithConfig(config pocketbase.Config) *pocketbase.PocketBase - old: core.NewBaseApp(config *core.BaseAppConfig) - new: core.NewBaseApp(config core.BaseAppConfig) + old: core.NewBaseApp(config *core.BaseAppConfig) *core.BaseApp + new: core.NewBaseApp(config core.BaseAppConfig) *core.BaseApp - old: apis.Serve(app core.App, options *apis.ServeOptions) - new: apis.Serve(app core.App, config apis.ServeConfig) + old: apis.Serve(app core.App, options *apis.ServeOptions) (*http.Server, error) + new: apis.Serve(app core.App, config apis.ServeConfig) error old: jsvm.MustRegisterMigrations(app core.App, options *jsvm.MigrationsOptions) new: jsvm.MustRegister(app core.App, config jsvm.Config) diff --git a/Makefile b/Makefile index 0dc94032..5418e1a3 100644 --- a/Makefile +++ b/Makefile @@ -4,8 +4,8 @@ lint: test: go test ./... -v --cover -jsvmdocs: - go run ./plugins/jsvm/internal/docs/docs.go +jstypes: + go run ./plugins/jsvm/internal/types/types.go test-report: go test ./... -v --cover -coverprofile=coverage.out diff --git a/examples/base/main.go b/examples/base/main.go index 3afc13ed..f523ce54 100644 --- a/examples/base/main.go +++ b/examples/base/main.go @@ -42,7 +42,7 @@ func main() { app.RootCmd.PersistentFlags().IntVar( &hooksPool, "hooksPool", - 100, + 50, "the total prewarm goja.Runtime instances for the JS app hooks execution", ) diff --git a/plugins/jsvm/binds.go b/plugins/jsvm/binds.go index fbb979e7..e9db5775 100644 --- a/plugins/jsvm/binds.go +++ b/plugins/jsvm/binds.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "io" "net/http" "reflect" @@ -104,12 +103,12 @@ func hooksBinds(app core.App, loader *goja.Runtime, executors *vmsPool) { } func cronBinds(app core.App, loader *goja.Runtime, executors *vmsPool) { - jobs := cron.New() + scheduler := cron.New() loader.Set("cronAdd", func(jobId, cronExpr, handler string) { pr := goja.MustCompile("", "{("+handler+").apply(undefined)}", true) - err := jobs.Add(jobId, cronExpr, func() { + err := scheduler.Add(jobId, cronExpr, func() { executors.run(func(executor *goja.Runtime) error { _, err := executor.RunProgram(pr) return err @@ -120,19 +119,28 @@ func cronBinds(app core.App, loader *goja.Runtime, executors *vmsPool) { } // start the ticker (if not already) - if jobs.Total() > 0 && !jobs.HasStarted() { - jobs.Start() + if app.IsBootstrapped() && scheduler.Total() > 0 && !scheduler.HasStarted() { + scheduler.Start() } }) loader.Set("cronRemove", func(jobId string) { - jobs.Remove(jobId) + scheduler.Remove(jobId) // stop the ticker if there are no other jobs - if jobs.Total() == 0 { - jobs.Stop() + if scheduler.Total() == 0 { + scheduler.Stop() } }) + + app.OnAfterBootstrap().Add(func(e *core.BootstrapEvent) error { + // start the ticker (if not already) + if scheduler.Total() > 0 && !scheduler.HasStarted() { + scheduler.Start() + } + + return nil + }) } func routerBinds(app core.App, loader *goja.Runtime, executors *vmsPool) { @@ -534,10 +542,6 @@ func httpClientBinds(vm *goja.Runtime) { } defer res.Body.Close() - if res.StatusCode < 200 || res.StatusCode >= 400 { - return nil, fmt.Errorf("request failed with status %d", res.StatusCode) - } - bodyRaw, _ := io.ReadAll(res.Body) result := &sendResult{ diff --git a/plugins/jsvm/internal/docs/generated/embed.go b/plugins/jsvm/internal/types/generated/embed.go similarity index 100% rename from plugins/jsvm/internal/docs/generated/embed.go rename to plugins/jsvm/internal/types/generated/embed.go diff --git a/plugins/jsvm/internal/docs/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts similarity index 94% rename from plugins/jsvm/internal/docs/generated/types.d.ts rename to plugins/jsvm/internal/types/generated/types.d.ts index e5f504df..2bc884fa 100644 --- a/plugins/jsvm/internal/docs/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -14,7 +14,7 @@ * * ```js * // prints "Hello world!" on every 30 minutes - * cronAdd("hello", "*/30 * * * *", (c) => { + * cronAdd("hello", "*\/30 * * * *", (c) => { * console.log("Hello world!") * }) * ``` @@ -30,7 +30,7 @@ declare function cronAdd( ): void; /** - * CronRemove removes previously registerd cron job by its name. + * CronRemove removes a single registered cron job by its name. * * Example: * @@ -147,7 +147,7 @@ declare var $app: appWithoutHooks * ```js * const records = arrayOf(new Record) * - * $app.dao().recordQuery(collection).limit(10).all(records) + * $app.dao().recordQuery("articles").limit(10).all(records) * ``` * * @group PocketBase @@ -685,13 +685,30 @@ declare namespace $apis { // httpClientBinds // ------------------------------------------------------------------- +/** + * `$http` defines common methods for working with HTTP requests. + * + * @group PocketBase + */ declare namespace $http { /** - * Sends a single HTTP request (_currently only json and plain text requests_). + * Sends a single HTTP request. * - * @group PocketBase + * Example: + * + * ```js + * const res = $http.send({ + * url: "https://example.com", + * data: {"title": "test"} + * method: "post", + * }) + * + * console.log(res.statusCode) + * console.log(res.raw) + * console.log(res.json) + * ``` */ - function send(params: { + function send(config: { url: string, method?: string, // default to "GET" data?: { [key:string]: any }, @@ -1145,14 +1162,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subRlIwi = BaseBuilder - interface MssqlBuilder extends _subRlIwi { + type _subhTwHb = BaseBuilder + interface MssqlBuilder extends _subhTwHb { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subHDxzL = BaseQueryBuilder - interface MssqlQueryBuilder extends _subHDxzL { + type _subSFdQZ = BaseQueryBuilder + interface MssqlQueryBuilder extends _subSFdQZ { } interface newMssqlBuilder { /** @@ -1223,8 +1240,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subcUaQr = BaseBuilder - interface MysqlBuilder extends _subcUaQr { + type _subyQJBY = BaseBuilder + interface MysqlBuilder extends _subyQJBY { } interface newMysqlBuilder { /** @@ -1299,14 +1316,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subHisND = BaseBuilder - interface OciBuilder extends _subHisND { + type _subQRkKI = BaseBuilder + interface OciBuilder extends _subQRkKI { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subUWMBc = BaseQueryBuilder - interface OciQueryBuilder extends _subUWMBc { + type _subZOEFS = BaseQueryBuilder + interface OciQueryBuilder extends _subZOEFS { } interface newOciBuilder { /** @@ -1369,8 +1386,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subzCBSe = BaseBuilder - interface PgsqlBuilder extends _subzCBSe { + type _subTFpHm = BaseBuilder + interface PgsqlBuilder extends _subTFpHm { } interface newPgsqlBuilder { /** @@ -1437,8 +1454,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subevtjr = BaseBuilder - interface SqliteBuilder extends _subevtjr { + type _subTCgBN = BaseBuilder + interface SqliteBuilder extends _subTCgBN { } interface newSqliteBuilder { /** @@ -1537,8 +1554,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subvJUEj = BaseBuilder - interface StandardBuilder extends _subvJUEj { + type _subaDaOx = BaseBuilder + interface StandardBuilder extends _subaDaOx { } interface newStandardBuilder { /** @@ -1604,8 +1621,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 _subzgSHa = Builder - interface DB extends _subzgSHa { + type _subgOxIk = Builder + interface DB extends _subgOxIk { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -2403,8 +2420,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 _subSxSuU = sql.Rows - interface Rows extends _subSxSuU { + type _subiXsFy = sql.Rows + interface Rows extends _subiXsFy { } interface Rows { /** @@ -2761,8 +2778,8 @@ namespace dbx { }): string } interface structInfo { } - type _subcEriY = structInfo - interface structValue extends _subcEriY { + type _subMgNPp = structInfo + interface structValue extends _subMgNPp { } interface fieldInfo { } @@ -2800,8 +2817,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subMPuUI = Builder - interface Tx extends _subMPuUI { + type _subiJXLn = Builder + interface Tx extends _subiJXLn { } interface Tx { /** @@ -2985,8 +3002,8 @@ namespace filesystem { */ open(): io.ReadSeekCloser } - type _subDwwkX = bytes.Reader - interface bytesReadSeekCloser extends _subDwwkX { + type _subxGCDv = bytes.Reader + interface bytesReadSeekCloser extends _subxGCDv { } interface bytesReadSeekCloser { /** @@ -4058,8 +4075,8 @@ namespace forms { /** * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - type _subULIJb = settings.Settings - interface SettingsUpsert extends _subULIJb { + type _subvjsVi = settings.Settings + interface SettingsUpsert extends _subvjsVi { } interface newSettingsUpsert { /** @@ -4433,11 +4450,9 @@ namespace apis { } interface serve { /** - * @todo return the server instance to allow manual shutdowns - * * Serve starts a new app web server. */ - (app: core.App, config: ServeConfig): void + (app: core.App, config: ServeConfig): (http.Server | undefined) } interface migrationsConnection { db?: dbx.DB @@ -4451,8 +4466,8 @@ namespace pocketbase { /** * appWrapper serves as a private core.App instance wrapper. */ - type _subMxIfY = core.App - interface appWrapper extends _subMxIfY { + type _subMxGWY = core.App + interface appWrapper extends _subMxGWY { } /** * PocketBase defines a PocketBase app launcher. @@ -4460,8 +4475,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 _subvDuOe = appWrapper - interface PocketBase extends _subvDuOe { + type _subQqRpc = appWrapper + interface PocketBase extends _subQqRpc { /** * RootCmd is the main console command */ @@ -4577,7 +4592,8 @@ namespace bytes { /** * Size returns the original length of the underlying byte slice. * Size is the number of bytes available for reading via ReadAt. - * The result is unaffected by any method calls except Reset. + * The returned value is always the same and is not affected by calls + * to any other method. */ size(): number } @@ -4643,7 +4659,7 @@ namespace bytes { * The calendrical calculations always assume a Gregorian calendar, with * no leap seconds. * - * # Monotonic Clocks + * Monotonic Clocks * * Operating systems provide both a “wall clock,” which is subject to * changes for clock synchronization, and a “monotonic clock,” which is @@ -4702,10 +4718,6 @@ namespace bytes { * t.UnmarshalJSON, and t.UnmarshalText always create times with * no monotonic clock reading. * - * The monotonic clock reading exists only in Time values. It is not - * a part of Duration values or the Unix times returned by t.Unix and - * friends. - * * Note that the Go == operator compares not just the time instant but * also the Location and the monotonic clock reading. See the * documentation for the Time type for a discussion of equality @@ -4785,42 +4797,6 @@ namespace time { */ round(m: Duration): Duration } - interface Duration { - /** - * Abs returns the absolute value of d. - * As a special case, math.MinInt64 is converted to math.MaxInt64. - */ - abs(): Duration - } -} - -/** - * 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 { - /** - * An FS provides access to a hierarchical file system. - * - * The FS interface is the minimum implementation required of the file system. - * A file system may implement additional interfaces, - * such as ReadFileFS, to provide additional or optimized functionality. - */ - interface FS { - /** - * Open opens the named file. - * - * When Open returns an error, it should be of type *PathError - * with the Op field set to "open", the Path field set to name, - * and the Err field describing the problem. - * - * Open should reject attempts to open names that do not satisfy - * ValidPath(name), returning a *PathError with Err set to - * ErrInvalid or ErrNotExist. - */ - open(name: string): File - } } /** @@ -4980,4601 +4956,31 @@ namespace context { } /** - * 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. + * 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 multipart { +namespace fs { /** - * A FileHeader describes a file part of a multipart request. - */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number - } - interface FileHeader { - /** - * Open opens and returns the FileHeader's associated File. - */ - open(): File - } -} - -/** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html - * - * See README.md for more info. - */ -namespace jwt { - /** - * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. - * This is the default claims type if you don't supply one - */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { - /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyAudience(cmp: string, req: boolean): boolean - } - interface MapClaims { - /** - * 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 { - /** - * 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. - */ - valid(): 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. + * An FS provides access to a hierarchical file system. * - * 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. + * The FS interface is the minimum implementation required of the file system. + * A file system may implement additional interfaces, + * such as ReadFileFS, to provide additional or optimized functionality. */ - interface Request { + interface FS { /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. + * Open opens the named file. * - * 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 - /** - * 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. - * - * Few HTTP clients, servers, or proxies support HTTP trailers. - */ - trailer: Header - /** - * RemoteAddr allows HTTP servers and other software to record - * the network address that sent the request, usually for - * logging. This field is not filled in by ReadRequest and - * has no defined format. The HTTP server in this package - * sets RemoteAddr to an "IP:port" address before invoking a - * handler. - * This field is ignored by the HTTP client. - */ - remoteAddr: string - /** - * RequestURI is the unmodified request-target of the - * Request-Line (RFC 7230, Section 3.1.1) as sent by the client - * to a server. Usually the URL field should be used instead. - * It is an error to set this field in an HTTP client request. - */ - requestURI: string - /** - * TLS allows HTTP servers and other software to record - * information about the TLS connection on which the request - * was received. This field is not filled in by ReadRequest. - * The HTTP server in this package sets the field for - * TLS-enabled connections before invoking a handler; - * otherwise it leaves the field nil. - * This field is ignored by the HTTP client. - */ - tls?: tls.ConnectionState - /** - * 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. - * - * Deprecated: Set the Request's context with NewRequestWithContext - * instead. If a Request's Cancel field and context are both - * set, it is undefined whether Cancel is respected. - */ - cancel: undefined - /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. - */ - response?: Response - } - interface Request { - /** - * Context returns the request's context. To change the context, use - * WithContext. - * - * The returned context is always non-nil; it defaults to the - * background context. - * - * 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. - */ - context(): context.Context - } - interface Request { - /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. - * - * 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. - */ - withContext(ctx: context.Context): (Request | undefined) - } - interface Request { - /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. - * - * For an outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. - */ - clone(ctx: context.Context): (Request | undefined) - } - interface Request { - /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. - */ - protoAtLeast(major: number): boolean - } - interface Request { - /** - * UserAgent returns the client's User-Agent, if sent in the request. - */ - userAgent(): string - } - interface Request { - /** - * Cookies parses and returns the HTTP cookies sent with the request. - */ - cookies(): Array<(Cookie | undefined)> - } - interface Request { - /** - * Cookie returns the named cookie provided in the request or - * ErrNoCookie if not found. - * If multiple cookies match the given name, only one cookie will - * be returned. - */ - cookie(name: string): (Cookie | undefined) - } - interface Request { - /** - * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, - * AddCookie does not attach more than one Cookie header field. That - * means all cookies, if any, are written into the same line, - * separated by semicolon. - * AddCookie only sanitizes c's name and value, and does not sanitize - * a Cookie header already present in the request. - */ - addCookie(c: Cookie): void - } - interface Request { - /** - * Referer returns the referring URL, if sent in the request. - * - * 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"]. - */ - referer(): string - } - interface Request { - /** - * 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. - */ - multipartReader(): (multipart.Reader | undefined) - } - interface Request { - /** - * Write writes an HTTP/1.1 request, which is the header and body, in wire format. - * This method consults the following fields of the request: - * - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` - * - * 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. - */ - writeProxy(w: io.Writer): void - } - interface Request { - /** - * BasicAuth returns the username and password provided in the request's - * Authorization header, if the request uses HTTP Basic Authentication. - * See RFC 2617, Section 2. - */ - basicAuth(): [string, boolean] - } - interface Request { - /** - * SetBasicAuth sets the request's Authorization header to use HTTP - * Basic Authentication with the provided username and password. - * - * With HTTP Basic Authentication the provided username and password - * are not encrypted. It should generally only be used in an HTTPS - * request. - * - * The username may not contain a colon. Some protocols may impose - * additional requirements on pre-escaping the username and - * password. For instance, when used with OAuth2, both arguments must - * be URL encoded first with url.QueryEscape. - */ - setBasicAuth(username: string): void - } - interface Request { - /** - * ParseForm populates r.Form and r.PostForm. - * - * For all requests, ParseForm parses the raw query from the URL and updates - * r.Form. - * - * For POST, PUT, and PATCH requests, it also reads the request body, parses it - * as a form and puts the results into both r.PostForm and r.Form. Request body - * parameters take precedence over URL query string values in r.Form. - * - * If the request Body's size has not already been limited by MaxBytesReader, - * the size is capped at 10MB. - * - * For other HTTP methods, or when the Content-Type is not - * application/x-www-form-urlencoded, the request Body is not read, and - * r.PostForm is initialized to a non-nil, empty value. - * - * 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. - */ - parseMultipartForm(maxMemory: number): void - } - interface Request { - /** - * 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. - */ - formValue(key: string): string - } - interface Request { - /** - * 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. - */ - postFormValue(key: string): string - } - interface Request { - /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. - */ - formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] - } - /** - * A ResponseWriter interface is used by an HTTP handler to - * construct an HTTP response. - * - * A ResponseWriter may not be used after the Handler.ServeHTTP method - * has returned. - */ - interface ResponseWriter { - /** - * 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. - * - * Changing the header map after a call to WriteHeader (or - * Write) has no effect unless the HTTP status code was of the - * 1xx class or the modified headers are trailers. - * - * 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. - */ - header(): Header - /** - * 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. - */ - write(_arg0: string): number - /** - * 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 or 1xx informational responses. - * - * The provided code must be a valid HTTP 1xx-5xx status code. - * Any number of 1xx headers may be written, followed by at most - * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx - * headers may be buffered. Use the Flusher interface to send - * buffered data. The header map is cleared when 2xx-5xx headers are - * sent, but not with 1xx headers. - * - * The server will automatically send a 100 (Continue) header - * on the first read from the request body if the request has - * an "Expect: 100-continue" header. - */ - writeHeader(statusCode: number): void - } -} - -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 { - /** - * Scopes returns the context associated with the provider (if any). - */ - context(): context.Context - /** - * SetContext assigns the specified context to the current provider. - */ - setContext(ctx: context.Context): void - /** - * Scopes returns the provider access permissions that will be requested. - */ - scopes(): Array - /** - * SetScopes sets the provider access permissions that will be requested later. - */ - setScopes(scopes: Array): void - /** - * ClientId returns the provider client's app ID. - */ - clientId(): string - /** - * SetClientId sets the provider client's ID. - */ - setClientId(clientId: string): void - /** - * ClientSecret returns the provider client's app secret. - */ - clientSecret(): string - /** - * SetClientSecret sets the provider client's app secret. - */ - setClientSecret(secret: string): void - /** - * RedirectUrl returns the end address to redirect the user - * going through the OAuth flow. - */ - redirectUrl(): string - /** - * SetRedirectUrl sets the provider's RedirectUrl. - */ - setRedirectUrl(url: string): void - /** - * AuthUrl returns the provider's authorization service url. - */ - authUrl(): string - /** - * SetAuthUrl sets the provider's AuthUrl. - */ - setAuthUrl(url: string): void - /** - * TokenUrl returns the provider's token exchange service url. - */ - tokenUrl(): string - /** - * SetTokenUrl sets the provider's TokenUrl. - */ - setTokenUrl(url: string): void - /** - * UserApiUrl returns the provider's user info api url. - */ - userApiUrl(): string - /** - * SetUserApiUrl sets the provider's UserApiUrl. - */ - setUserApiUrl(url: string): void - /** - * Client returns an http client using the provided token. - */ - client(token: oauth2.Token): (http.Client | undefined) - /** - * BuildAuthUrl returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. - */ - buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string - /** - * FetchToken converts an authorization code to token. - */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) - /** - * FetchRawUserData requests and marshalizes into `result` the - * the OAuth user api response. - */ - 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) - } -} - -/** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com - */ -namespace echo { - /** - * Context represents the context of the current HTTP request. It holds request and - * response objects, path, path parameters, data and registered handler. - */ - interface Context { - /** - * Request returns `*http.Request`. - */ - request(): (http.Request | undefined) - /** - * 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. - * - * 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.` - */ - pathParamDefault(name: string, defaultValue: string): string - /** - * PathParams returns path parameter values. - */ - pathParams(): PathParams - /** - * SetPathParams sets path parameters for current request. - */ - setPathParams(params: PathParams): void - /** - * QueryParam returns the query param for the provided name. - */ - queryParam(name: string): string - /** - * QueryParamDefault returns the query param or default value for the provided name. - */ - queryParamDefault(name: string): string - /** - * QueryParams returns the query parameters as `url.Values`. - */ - queryParams(): url.Values - /** - * QueryString returns the URL query string. - */ - queryString(): string - /** - * FormValue returns the form field value for the provided name. - */ - formValue(name: string): string - /** - * FormValueDefault returns the form field value or default value for the provided name. - */ - formValueDefault(name: string): string - /** - * FormValues returns the form field values as `url.Values`. - */ - formValues(): url.Values - /** - * FormFile returns the multipart form file for the provided name. - */ - formFile(name: string): (multipart.FileHeader | undefined) - /** - * MultipartForm returns the multipart form. - */ - multipartForm(): (multipart.Form | undefined) - /** - * Cookie returns the named cookie provided in the request. - */ - cookie(name: string): (http.Cookie | undefined) - /** - * SetCookie adds a `Set-Cookie` header in HTTP response. - */ - setCookie(cookie: http.Cookie): void - /** - * Cookies returns the HTTP cookies sent with the request. - */ - cookies(): Array<(http.Cookie | undefined)> - /** - * Get retrieves data from the context. - */ - get(key: string): { - } - /** - * Set saves data in the context. - */ - set(key: string, val: { - }): void - /** - * Bind binds the request body into provided type `i`. The default binder - * does it based on Content-Type header. - */ - 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 - /** - * HTML sends an HTTP response with status code. - */ - html(code: number, html: string): void - /** - * HTMLBlob sends an HTTP blob response with status code. - */ - htmlBlob(code: number, b: string): void - /** - * String sends a string response with status code. - */ - string(code: number, s: string): void - /** - * JSON sends a JSON response with status code. - */ - json(code: number, i: { - }): void - /** - * JSONPretty sends a pretty-print JSON with status code. - */ - jsonPretty(code: number, i: { - }, indent: string): void - /** - * JSONBlob sends a JSON blob response with status code. - */ - jsonBlob(code: number, b: string): void - /** - * JSONP sends a JSONP response with status code. It uses `callback` to construct - * the JSONP payload. - */ - jsonp(code: number, callback: string, i: { - }): void - /** - * JSONPBlob sends a JSONP blob response with status code. It uses `callback` - * to construct the JSONP payload. - */ - jsonpBlob(code: number, callback: string, b: string): void - /** - * XML sends an XML response with status code. - */ - xml(code: number, i: { - }): void - /** - * XMLPretty sends a pretty-print XML with status code. - */ - xmlPretty(code: number, i: { - }, indent: string): void - /** - * XMLBlob sends an XML blob response with status code. - */ - xmlBlob(code: number, b: string): void - /** - * Blob sends a blob response with status code and content type. - */ - blob(code: number, contentType: string, b: string): void - /** - * Stream sends a streaming response with status code and content type. - */ - stream(code: number, contentType: string, r: io.Reader): void - /** - * File sends a response with the content of the file. - */ - file(file: string): void - /** - * FileFS sends a response with the content of the file from given filesystem. - */ - fileFS(file: string, filesystem: fs.FS): void - /** - * Attachment sends a response as attachment, prompting client to save the - * file. - */ - attachment(file: string, name: string): void - /** - * Inline sends a response as inline, opening the file in the browser. - */ - inline(file: string, name: string): void - /** - * NoContent sends a response with no body and a status code. - */ - noContent(code: number): void - /** - * Redirect redirects the request to a provided URL with status code. - */ - redirect(code: number, url: string): 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) - } - // @ts-ignore - import stdContext = context - /** - * Echo is the top-level framework instance. - * - * Note: replacing/nilling public fields is not coroutine/thread-safe and can cause data-races/panics. This is very likely - * to happen when you access Echo instances through Context.Echo() method. - */ - interface Echo { - /** - * NewContextFunc allows using custom context implementations, instead of default *echo.context - */ - 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 - } - /** - * 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 { - /** - * 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. - */ - newContext(r: http.Request, w: http.ResponseWriter): Context - } - interface Echo { - /** - * Router returns the default router. - */ - router(): Router - } - interface Echo { - /** - * Routers returns the map of host => router. - */ - routers(): _TygojaDict - } - interface Echo { - /** - * RouterFor returns Router for given host. - */ - routerFor(host: string): Router - } - 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 { - /** - * HEAD registers a new HEAD route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * OPTIONS registers a new OPTIONS route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * PATCH registers a new PATCH route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * POST registers a new POST route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * PUT registers a new PUT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * TRACE registers a new TRACE route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * 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) })` - */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * Any registers a new route for all supported HTTP methods and path with matching handler - * in the router with optional route-level middleware. Panics on error. - */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { - /** - * 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. - */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { - /** - * Static registers a new route with path prefix to serve static files from the provided root directory. - */ - static(pathPrefix: string): RouteInfo - } - 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 Echo { - /** - * FileFS registers a new route with path to serve file from the provided file system. - */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. - */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * AddRoute registers a new Route with default host Router - */ - addRoute(route: Routable): RouteInfo - } - interface Echo { - /** - * Add registers a new route for an HTTP method and path with matching handler - * in the router with optional route-level middleware. - */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * Host creates a new router group for the provided host and optional host-level middleware. - */ - host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { - /** - * Group creates a new router group with prefix and optional group-level middleware. - */ - group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { - /** - * AcquireContext returns an empty `Context` instance from the pool. - * You must return the context by calling `ReleaseContext()`. - */ - acquireContext(): Context - } - interface Echo { - /** - * ReleaseContext returns the `Context` instance back to the pool. - * You must call it after `AcquireContext()`. - */ - releaseContext(c: Context): void - } - interface Echo { - /** - * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. - */ - serveHTTP(w: http.ResponseWriter, r: http.Request): void - } - interface Echo { - /** - * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by - * sending os.Interrupt signal with `ctrl+c`. - * - * 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) - * } - * ``` - */ - start(address: string): void - } -} - -/** - * Package blob provides an easy and portable way to interact with blobs - * within a storage location. Subpackages contain driver implementations of - * blob for supported services. - * - * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. - * - * # 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 { - /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). - */ - read(p: string): number - } - interface Reader { - /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). - */ - close(): void - } - interface Reader { - /** - * ContentType returns the MIME type of the blob. - */ - contentType(): string - } - interface Reader { - /** - * ModTime returns the time the blob was last modified. - */ - modTime(): time.Time - } - interface Reader { - /** - * Size returns the size of the blob content in bytes. - */ - size(): number - } - interface Reader { - /** - * 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. - */ - as(i: { - }): boolean - } - interface Reader { - /** - * 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. - */ - writeTo(w: io.Writer): number - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { - /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control - */ - cacheControl: string - /** - * 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 - */ - contentDisposition: 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 - */ - contentEncoding: string - /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language - */ - contentLanguage: string - /** - * 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 - */ - contentType: string - /** - * 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. - */ - metadata: _TygojaDict - /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. - */ - createTime: time.Time - /** - * ModTime is the time the blob was last modified. - */ - 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 - /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. - */ - eTag: string - } - interface Attributes { - /** - * 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. - */ - as(i: { - }): boolean - } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { - /** - * Key is the key for this blob. - */ - key: string - /** - * ModTime is the time the blob was last modified. - */ - 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 - /** - * 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. - */ - isDir: boolean - } - interface ListObject { - /** - * 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. - */ - as(i: { - }): boolean - } -} - -/** - * 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 { - /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. - */ - isolation: IsolationLevel - readOnly: boolean - } - /** - * DB is a database handle representing a pool of zero or more - * underlying connections. It's safe for concurrent use by multiple - * goroutines. - * - * 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 { - /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. - */ - pingContext(ctx: context.Context): void - } - interface DB { - /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. - * - * Ping uses context.Background internally; to specify the context, use - * PingContext. - */ - ping(): void - } - interface DB { - /** - * 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. - */ - close(): void - } - interface DB { - /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. - * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. - * - * If n <= 0, no idle connections are retained. - * - * The default max idle connections is currently 2. This may change in - * a future release. - */ - setMaxIdleConns(n: number): void - } - interface DB { - /** - * SetMaxOpenConns sets the maximum number of open connections to the database. - * - * 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). - */ - setMaxOpenConns(n: number): void - } - interface DB { - /** - * 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. - */ - setConnMaxLifetime(d: time.Duration): void - } - interface DB { - /** - * 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. - */ - setConnMaxIdleTime(d: time.Duration): void - } - interface DB { - /** - * Stats returns database statistics. - */ - stats(): DBStats - } - interface DB { - /** - * 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. - */ - 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. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. - */ - prepare(query: string): (Stmt | undefined) - } - interface DB { - /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface DB { - /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. - */ - exec(query: string, ...args: any[]): Result - } - interface DB { - /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) - } - interface DB { - /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. - */ - query(query: string, ...args: any[]): (Rows | undefined) - } - interface DB { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) - } - interface DB { - /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. - */ - queryRow(query: string, ...args: any[]): (Row | undefined) - } - interface DB { - /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. Tx.Commit will return an error if the context provided to - * BeginTx is canceled. - * - * The provided TxOptions is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. - */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) - } - interface DB { - /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. - * - * Begin uses context.Background internally; to specify the context, use - * BeginTx. - */ - begin(): (Tx | undefined) - } - interface DB { - /** - * Driver returns the database's underlying driver. - */ - driver(): driver.Driver - } - interface DB { - /** - * Conn returns a single connection by either opening a new connection - * or returning an existing connection from the connection pool. Conn will - * block until either a connection is returned or ctx is canceled. - * Queries run on the same Conn will be run in the same database session. - * - * Every Conn must be returned to the database pool after use by - * calling Conn.Close. - */ - conn(ctx: context.Context): (Conn | 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 { - } - interface Tx { - /** - * Commit commits the transaction. - */ - commit(): void - } - interface Tx { - /** - * Rollback aborts the transaction. - */ - rollback(): void - } - interface Tx { - /** - * PrepareContext creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. - * - * The provided context will be used for the preparation of the context, not - * for the execution of the returned statement. The returned statement - * will run in the transaction context. - */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) - } - interface Tx { - /** - * Prepare creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. - */ - prepare(query: string): (Stmt | undefined) - } - interface Tx { - /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) - * ``` - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) - } - interface Tx { - /** - * 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. - */ - stmt(stmt: Stmt): (Stmt | undefined) - } - interface Tx { - /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. - */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Tx { - /** - * 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. - */ - exec(query: string, ...args: any[]): Result - } - interface Tx { - /** - * QueryContext executes a query that returns rows, typically a SELECT. - */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) - } - interface Tx { - /** - * Query executes a query that returns rows, typically a SELECT. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. - */ - query(query: string, ...args: any[]): (Rows | undefined) - } - interface Tx { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) - } - interface Tx { - /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. - */ - queryRow(query: string, ...args: any[]): (Row | 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 { - /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. - */ - execContext(ctx: context.Context, ...args: any[]): Result - } - interface Stmt { - /** - * Exec executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. - */ - exec(...args: any[]): Result - } - interface Stmt { - /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. - */ - queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) - } - interface Stmt { - /** - * 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. - */ - query(...args: any[]): (Rows | undefined) - } - interface Stmt { - /** - * 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. - */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) - } - interface Stmt { - /** - * 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. - */ - queryRow(...args: any[]): (Row | undefined) - } - interface Stmt { - /** - * Close closes the statement. - */ - 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 { - /** - * 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. - */ - 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. - * - * 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. - */ - nextResultSet(): boolean - } - interface Rows { - /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit Close. - */ - err(): void - } - interface Rows { - /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. - */ - columns(): Array - } - interface Rows { - /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. - */ - columnTypes(): Array<(ColumnType | undefined)> - } - interface Rows { - /** - * 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. - * - * 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 - */ - scan(...dest: any[]): void - } - interface Rows { - /** - * 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. - */ - close(): void - } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - /** - * 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. - */ - 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 - } -} - -/** - * 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. - */ - marshalJSON(): string - } - interface JsonArray { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): driver.Value - } - interface JsonArray { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. - */ - scan(value: any): void - } - /** - * JsonMap defines a map that is safe for json and db read/write. - */ - interface JsonMap extends _TygojaDict{} - interface JsonMap { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string - } - interface JsonMap { - /** - * Get retrieves a single value from the current JsonMap. - * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). - */ - get(key: string): any - } - interface JsonMap { - /** - * Set sets a single value in the current JsonMap. - * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). - */ - set(key: string, value: any): void - } - interface JsonMap { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): driver.Value - } - interface JsonMap { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. - */ - scan(value: any): void - } -} - -namespace settings { - // @ts-ignore - import validation = ozzo_validation - /** - * Settings defines common app configuration options. - */ - interface Settings { - meta: MetaConfig - logs: LogsConfig - smtp: SmtpConfig - s3: S3Config - backups: BackupsConfig - adminAuthToken: TokenConfig - adminPasswordResetToken: TokenConfig - adminFileToken: TokenConfig - recordAuthToken: TokenConfig - recordPasswordResetToken: TokenConfig - recordEmailChangeToken: TokenConfig - recordVerificationToken: TokenConfig - recordFileToken: TokenConfig - /** - * Deprecated: Will be removed in v0.9+ - */ - emailAuth: EmailAuthConfig - googleAuth: AuthProviderConfig - facebookAuth: AuthProviderConfig - githubAuth: AuthProviderConfig - gitlabAuth: AuthProviderConfig - discordAuth: AuthProviderConfig - twitterAuth: AuthProviderConfig - microsoftAuth: AuthProviderConfig - spotifyAuth: AuthProviderConfig - kakaoAuth: AuthProviderConfig - twitchAuth: AuthProviderConfig - stravaAuth: AuthProviderConfig - giteeAuth: AuthProviderConfig - livechatAuth: AuthProviderConfig - giteaAuth: AuthProviderConfig - oidcAuth: AuthProviderConfig - oidc2Auth: AuthProviderConfig - oidc3Auth: AuthProviderConfig - appleAuth: AuthProviderConfig - instagramAuth: AuthProviderConfig - vkAuth: AuthProviderConfig - yandexAuth: AuthProviderConfig - } - interface Settings { - /** - * Validate makes Settings validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface Settings { - /** - * Merge merges `other` settings into the current one. - */ - merge(other: Settings): void - } - interface Settings { - /** - * Clone creates a new deep copy of the current settings. - */ - clone(): (Settings | undefined) - } - interface Settings { - /** - * RedactClone creates a new deep copy of the current settings, - * while replacing the secret values with `******`. - */ - redactClone(): (Settings | undefined) - } - interface Settings { - /** - * NamedAuthProviderConfigs returns a map with all registered OAuth2 - * provider configurations (indexed by their name identifier). - */ - namedAuthProviderConfigs(): _TygojaDict - } -} - -/** - * 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 { - /** - * Fields returns the registered schema fields. - */ - fields(): Array<(SchemaField | undefined)> - } - interface Schema { - /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. - */ - initFieldsOptions(): void - } - interface Schema { - /** - * Clone creates a deep clone of the current schema. - */ - clone(): (Schema | undefined) - } - interface Schema { - /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. - */ - asMap(): _TygojaDict - } - interface Schema { - /** - * GetFieldById returns a single field by its id. - */ - getFieldById(id: string): (SchemaField | undefined) - } - interface Schema { - /** - * GetFieldByName returns a single field by its name. - */ - getFieldByName(name: string): (SchemaField | undefined) - } - interface Schema { - /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. - */ - removeField(id: string): void - } - interface Schema { - /** - * 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. - */ - addField(newField: SchemaField): void - } - interface Schema { - /** - * 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. - */ - validate(): void - } - interface Schema { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string - } - interface Schema { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * On success, all schema field options are auto initialized. - */ - unmarshalJSON(data: string): void - } - interface Schema { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): driver.Value - } - interface Schema { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. - */ - scan(value: any): void - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - type _subGTttY = BaseModel - interface Admin extends _subGTttY { - avatar: number - email: string - tokenKey: string - passwordHash: string - lastResetSentAt: types.DateTime - } - interface Admin { - /** - * TableName returns the Admin model SQL table name. - */ - tableName(): string - } - interface Admin { - /** - * ValidatePassword validates a plain password against the model's password. - */ - validatePassword(password: string): boolean - } - interface Admin { - /** - * SetPassword sets cryptographically secure string to `model.Password`. - * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. - */ - setPassword(password: string): void - } - interface Admin { - /** - * RefreshTokenKey generates and sets new random token key. - */ - refreshTokenKey(): void - } - // @ts-ignore - import validation = ozzo_validation - type _subWOTpk = BaseModel - interface Collection extends _subWOTpk { - name: string - type: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray - /** - * rules - */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { - /** - * TableName returns the Collection model SQL table name. - */ - tableName(): string - } - interface Collection { - /** - * BaseFilesPath returns the storage dir path used by the collection. - */ - baseFilesPath(): string - } - interface Collection { - /** - * IsBase checks if the current collection has "base" type. - */ - isBase(): boolean - } - interface Collection { - /** - * IsAuth checks if the current collection has "auth" type. - */ - isAuth(): boolean - } - interface Collection { - /** - * IsView checks if the current collection has "view" type. - */ - isView(): boolean - } - interface Collection { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string - } - interface Collection { - /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. - */ - baseOptions(): CollectionBaseOptions - } - interface Collection { - /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. - */ - authOptions(): CollectionAuthOptions - } - interface Collection { - /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. - */ - viewOptions(): CollectionViewOptions - } - interface Collection { - /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. - */ - normalizeOptions(): void - } - interface Collection { - /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). - */ - decodeOptions(result: any): void - } - interface Collection { - /** - * SetOptions normalizes and unmarshals the specified options into m.Options. - */ - setOptions(typedOptions: any): void - } - type _subiWiem = BaseModel - interface ExternalAuth extends _subiWiem { - collectionId: string - recordId: string - provider: string - providerId: string - } - interface ExternalAuth { - tableName(): string - } - type _subNYOqn = BaseModel - interface Record extends _subNYOqn { - } - interface Record { - /** - * TableName returns the table name associated to the current Record model. - */ - tableName(): string - } - interface Record { - /** - * Collection returns the Collection model associated to the current Record model. - */ - collection(): (Collection | undefined) - } - interface Record { - /** - * 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. - */ - originalCopy(): (Record | undefined) - } - interface Record { - /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. - */ - cleanCopy(): (Record | undefined) - } - interface Record { - /** - * Expand returns a shallow copy of the current Record model expand data. - */ - expand(): _TygojaDict - } - interface Record { - /** - * SetExpand shallow copies the provided data to the current Record model's expand. - */ - setExpand(expand: _TygojaDict): void - } - interface Record { - /** - * 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). - */ - mergeExpand(expand: _TygojaDict): void - } - interface Record { - /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. - */ - schemaData(): _TygojaDict - } - interface Record { - /** - * 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. - */ - unknownData(): _TygojaDict - } - interface Record { - /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. - */ - ignoreEmailVisibility(state: boolean): void - } - interface Record { - /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). - */ - withUnknownData(state: boolean): void - } - interface Record { - /** - * 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, value: any): void - } - interface Record { - /** - * Get returns a single record model data value for "key". - */ - get(key: string): any - } - interface Record { - /** - * GetBool returns the data value for "key" as a bool. - */ - getBool(key: string): boolean - } - interface Record { - /** - * GetString returns the data value for "key" as a string. - */ - getString(key: string): string - } - interface Record { - /** - * GetInt returns the data value for "key" as an int. - */ - getInt(key: string): number - } - interface Record { - /** - * GetFloat returns the data value for "key" as a float64. - */ - getFloat(key: string): number - } - interface Record { - /** - * GetTime returns the data value for "key" as a [time.Time] instance. - */ - getTime(key: string): time.Time - } - interface Record { - /** - * GetDateTime returns the data value for "key" as a DateTime instance. - */ - getDateTime(key: string): types.DateTime - } - interface Record { - /** - * GetStringSlice returns the data value for "key" as a slice of unique strings. - */ - getStringSlice(key: string): Array - } - interface Record { - /** - * 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) - * ``` - */ - unmarshalJSONField(key: string, result: any): void - } - interface Record { - /** - * BaseFilesPath returns the storage dir path used by the record. - */ - baseFilesPath(): string - } - interface Record { - /** - * FindFileFieldByFile returns the first file type field for which - * any of the record's data contains the provided filename. - */ - findFileFieldByFile(filename: string): (schema.SchemaField | undefined) - } - interface Record { - /** - * Load bulk loads the provided data into the current Record model. - */ - load(data: _TygojaDict): void - } - interface Record { - /** - * ColumnValueMap implements [ColumnValueMapper] interface. - */ - columnValueMap(): _TygojaDict - } - interface Record { - /** - * PublicExport exports only the record fields that are safe to be public. - * - * Fields marked as hidden will be exported only if `m.IgnoreEmailVisibility(true)` is set. - */ - publicExport(): _TygojaDict - } - interface Record { - /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * Only the data exported by `PublicExport()` will be serialized. - */ - marshalJSON(): string - } - interface Record { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(data: string): void - } - interface Record { - /** - * 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} - * ``` - */ - replaceModifers(data: _TygojaDict): _TygojaDict - } - interface Record { - /** - * Username returns the "username" auth record data value. - */ - username(): string - } - interface Record { - /** - * 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. - */ - setUsername(username: string): void - } - interface Record { - /** - * Email returns the "email" auth record data value. - */ - email(): string - } - interface Record { - /** - * SetEmail sets the "email" auth record data value. - * - * This method doesn't check whether the provided value is a valid email. - * - * Returns an error if the record is not from an auth collection. - */ - setEmail(email: string): void - } - interface Record { - /** - * Verified returns the "emailVisibility" auth record data value. - */ - emailVisibility(): boolean - } - interface Record { - /** - * SetEmailVisibility sets the "emailVisibility" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setEmailVisibility(visible: boolean): void - } - interface Record { - /** - * Verified returns the "verified" auth record data value. - */ - verified(): boolean - } - interface Record { - /** - * SetVerified sets the "verified" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setVerified(verified: boolean): void - } - interface Record { - /** - * TokenKey returns the "tokenKey" auth record data value. - */ - tokenKey(): string - } - interface Record { - /** - * SetTokenKey sets the "tokenKey" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setTokenKey(key: string): void - } - interface Record { - /** - * RefreshTokenKey generates and sets new random auth record "tokenKey". - * - * Returns an error if the record is not from an auth collection. - */ - refreshTokenKey(): void - } - interface Record { - /** - * LastResetSentAt returns the "lastResentSentAt" auth record data value. - */ - lastResetSentAt(): types.DateTime - } - interface Record { - /** - * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setLastResetSentAt(dateTime: types.DateTime): void - } - interface Record { - /** - * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. - */ - lastVerificationSentAt(): types.DateTime - } - interface Record { - /** - * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setLastVerificationSentAt(dateTime: types.DateTime): void - } - interface Record { - /** - * PasswordHash returns the "passwordHash" auth record data value. - */ - passwordHash(): string - } - interface Record { - /** - * 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. - */ - validatePassword(password: string): boolean - } - interface Record { - /** - * 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. - */ - setPassword(password: string): void - } - /** - * RequestData defines a HTTP request data struct, usually used - * as part of the `@request.*` filter resolver. - */ - interface RequestData { - method: string - query: _TygojaDict - /** - * @todo consider changing to Body? - */ - data: _TygojaDict - headers: _TygojaDict - authRecord?: Record - admin?: Admin - } - interface RequestData { - /** - * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. - */ - hasModifierDataKeys(): boolean - } -} - -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 daos handles common PocketBase DB model manipulations. - * - * Think of daos as DB repository and service layer in one. - */ -namespace daos { - interface Dao { - /** - * AdminQuery returns a new Admin select query. - */ - adminQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindAdminById finds the admin with the provided id. - */ - findAdminById(id: string): (models.Admin | undefined) - } - interface Dao { - /** - * FindAdminByEmail finds the admin with the provided email address. - */ - findAdminByEmail(email: string): (models.Admin | undefined) - } - interface Dao { - /** - * FindAdminByToken finds the admin associated with the provided JWT token. - * - * Returns an error if the JWT token is invalid or expired. - */ - findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) - } - interface Dao { - /** - * TotalAdmins returns the number of existing admin records. - */ - totalAdmins(): number - } - interface Dao { - /** - * IsAdminEmailUnique checks if the provided email address is not - * already in use by other admins. - */ - isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean - } - interface Dao { - /** - * DeleteAdmin deletes the provided Admin model. - * - * Returns an error if there is only 1 admin. - */ - deleteAdmin(admin: models.Admin): void - } - interface Dao { - /** - * SaveAdmin upserts the provided Admin model. - */ - saveAdmin(admin: models.Admin): void - } - /** - * Dao handles various db operations. - * - * You can think of Dao as a repository and service layer in one. - */ - interface Dao { - /** - * MaxLockRetries specifies the default max "database is locked" auto retry attempts. - */ - maxLockRetries: number - /** - * ModelQueryTimeout is the default max duration of a running ModelQuery(). - * - * This field has no effect if an explicit query context is already specified. - */ - modelQueryTimeout: time.Duration - /** - * write hooks - */ - beforeCreateFunc: (eventDao: Dao, m: models.Model) => void - afterCreateFunc: (eventDao: Dao, m: models.Model) => void - beforeUpdateFunc: (eventDao: Dao, m: models.Model) => void - afterUpdateFunc: (eventDao: Dao, m: models.Model) => void - beforeDeleteFunc: (eventDao: Dao, m: models.Model) => void - afterDeleteFunc: (eventDao: Dao, m: models.Model) => void - } - interface Dao { - /** - * DB returns the default dao db builder (*dbx.DB or *dbx.TX). - * - * Currently the default db builder is dao.concurrentDB but that may change in the future. - */ - db(): dbx.Builder - } - interface Dao { - /** - * ConcurrentDB returns the dao concurrent (aka. multiple open connections) - * db builder (*dbx.DB or *dbx.TX). - * - * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. - */ - concurrentDB(): dbx.Builder - } - interface Dao { - /** - * NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) - * db builder (*dbx.DB or *dbx.TX). - * - * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. - */ - nonconcurrentDB(): dbx.Builder - } - interface Dao { - /** - * Clone returns a new Dao with the same configuration options as the current one. - */ - clone(): (Dao | undefined) - } - interface Dao { - /** - * WithoutHooks returns a new Dao with the same configuration options - * as the current one, but without create/update/delete hooks. - */ - withoutHooks(): (Dao | undefined) - } - interface Dao { - /** - * ModelQuery creates a new preconfigured select query with preset - * SELECT, FROM and other common fields based on the provided model. - */ - modelQuery(m: models.Model): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindById finds a single db record with the specified id and - * scans the result into m. - */ - findById(m: models.Model, id: string): void - } - interface Dao { - /** - * RunInTransaction wraps fn into a transaction. - * - * It is safe to nest RunInTransaction calls as long as you use the txDao. - */ - runInTransaction(fn: (txDao: Dao) => void): void - } - interface Dao { - /** - * Delete deletes the provided model. - */ - delete(m: models.Model): void - } - interface Dao { - /** - * Save persists the provided model in the database. - * - * If m.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a model for update you can use m.MarkAsNotNew(). - */ - save(m: models.Model): void - } - interface Dao { - /** - * CollectionQuery returns a new Collection select query. - */ - collectionQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindCollectionsByType finds all collections by the given type. - */ - findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> - } - interface Dao { - /** - * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. - */ - findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) - } - interface Dao { - /** - * IsCollectionNameUnique checks that there is no existing collection - * with the provided name (case insensitive!). - * - * Note: case insensitive check because the name is used also as a table name for the records. - */ - isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean - } - interface Dao { - /** - * FindCollectionReferences returns information for all - * relation schema fields referencing the provided collection. - * - * If the provided collection has reference to itself then it will be - * also included in the result. To exclude it, pass the collection id - * as the excludeId argument. - */ - findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict - } - interface Dao { - /** - * DeleteCollection deletes the provided Collection model. - * This method automatically deletes the related collection records table. - * - * NB! The collection cannot be deleted, if: - * - is system collection (aka. collection.System is true) - * - is referenced as part of a relation field in another collection - */ - deleteCollection(collection: models.Collection): void - } - interface Dao { - /** - * SaveCollection persists the provided Collection model and updates - * its related records table schema. - * - * If collecction.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a collection for update you can use collecction.MarkAsNotNew(). - */ - saveCollection(collection: models.Collection): void - } - interface Dao { - /** - * ImportCollections imports the provided collections list within a single transaction. - * - * NB1! If deleteMissing is set, all local collections and schema fields, that are not present - * in the imported configuration, WILL BE DELETED (including their related records data). - * - * NB2! This method doesn't perform validations on the imported collections data! - * If you need validations, use [forms.CollectionsImport]. - */ - importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void - } - interface Dao { - /** - * ExternalAuthQuery returns a new ExternalAuth select query. - */ - externalAuthQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindAllExternalAuthsByRecord returns all ExternalAuth models - * linked to the provided auth record. - */ - findAllExternalAuthsByRecord(authRecord: models.Record): Array<(models.ExternalAuth | undefined)> - } - interface Dao { - /** - * FindExternalAuthByProvider returns the first available - * ExternalAuth model for the specified provider and providerId. - */ - findExternalAuthByProvider(provider: string): (models.ExternalAuth | undefined) - } - interface Dao { - /** - * FindExternalAuthByRecordAndProvider returns the first available - * ExternalAuth model for the specified record data and provider. - */ - findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) - } - interface Dao { - /** - * SaveExternalAuth upserts the provided ExternalAuth model. - */ - saveExternalAuth(model: models.ExternalAuth): void - } - interface Dao { - /** - * DeleteExternalAuth deletes the provided ExternalAuth model. - */ - deleteExternalAuth(model: models.ExternalAuth): void - } - interface Dao { - /** - * ParamQuery returns a new Param select query. - */ - paramQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindParamByKey finds the first Param model with the provided key. - */ - findParamByKey(key: string): (models.Param | undefined) - } - interface Dao { - /** - * SaveParam creates or updates a Param model by the provided key-value pair. - * The value argument will be encoded as json string. - * - * If `optEncryptionKey` is provided it will encrypt the value before storing it. - */ - saveParam(key: string, value: any, ...optEncryptionKey: string[]): void - } - interface Dao { - /** - * DeleteParam deletes the provided Param model. - */ - deleteParam(param: models.Param): void - } - interface Dao { - /** - * RecordQuery returns a new Record select query. - */ - recordQuery(collection: models.Collection): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindRecordById finds the Record model by its id. - */ - findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) - } - interface Dao { - /** - * FindRecordsByIds finds all Record models by the provided ids. - * If no records are found, returns an empty slice. - */ - findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> - } - interface Dao { - /** - * FindRecordsByExpr finds all records by the specified db expression. - * - * Returns all collection records if no expressions are provided. - * - * Returns an empty slice if no records are found. - * - * Example: - * - * ``` - * expr1 := dbx.HashExp{"email": "test@example.com"} - * expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) - * dao.FindRecordsByExpr("example", expr1, expr2) - * ``` - */ - findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> - } - interface Dao { - /** - * FindFirstRecordByData returns the first found record matching - * the provided key-value pair. - */ - findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) - } - interface Dao { - /** - * FindRecordsByFilter returns limit number of records matching the - * provided string filter. - * - * The sort argument is optional and can be empty string OR the same format - * used in the web APIs, eg. "-created,title". - * - * If the limit argument is <= 0, no limit is applied to the query and - * all matching records are returned. - * - * NB! Don't put untrusted user input in the filter string as it - * practically would allow the users to inject their own custom filter. - * - * Example: - * - * ``` - * dao.FindRecordsByFilter("posts", "title ~ 'lorem ipsum' && visible = true", "-created", 10) - * ``` - */ - findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> - } - interface Dao { - /** - * FindFirstRecordByFilter returns the first available record matching the provided filter. - * - * NB! Don't put untrusted user input in the filter string as it - * practically would allow the users to inject their own custom filter. - * - * Example: - * - * ``` - * dao.FindFirstRecordByFilter("posts", "slug='test'") - * ``` - */ - findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) - } - interface Dao { - /** - * IsRecordValueUnique checks if the provided key-value pair is a unique Record value. - * - * For correctness, if the collection is "auth" and the key is "username", - * the unique check will be case insensitive. - * - * NB! Array values (eg. from multiple select fields) are matched - * as a serialized json strings (eg. `["a","b"]`), so the value uniqueness - * depends on the elements order. Or in other words the following values - * are considered different: `[]string{"a","b"}` and `[]string{"b","a"}` - */ - isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean - } - interface Dao { - /** - * FindAuthRecordByToken finds the auth record associated with the provided JWT token. - * - * Returns an error if the JWT token is invalid, expired or not associated to an auth collection record. - */ - findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) - } - interface Dao { - /** - * FindAuthRecordByEmail finds the auth record associated with the provided email. - * - * Returns an error if it is not an auth collection or the record is not found. - */ - findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) - } - interface Dao { - /** - * FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive). - * - * Returns an error if it is not an auth collection or the record is not found. - */ - findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) - } - interface Dao { - /** - * SuggestUniqueAuthRecordUsername checks if the provided username is unique - * and return a new "unique" username with appended random numeric part - * (eg. "existingName" -> "existingName583"). - * - * The same username will be returned if the provided string is already unique. - */ - suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string - } - interface Dao { - /** - * CanAccessRecord checks if a record is allowed to be accessed by the - * specified requestData and accessRule. - * - * Rule and db checks are ignored in case requestData.Admin is set. - * - * The returned error indicate that something unexpected happened during - * the check (eg. invalid rule or db error). - * - * The method always return false on invalid access rule or db error. - * - * Example: - * - * ``` - * requestData := apis.RequestData(c /* echo.Context *\/) - * record, _ := dao.FindRecordById("example", "RECORD_ID") - * rule := types.Pointer("@request.auth.id != '' || status = 'public'") - * // ... or use one of the record collection's rule, eg. record.Collection().ViewRule - * - * if ok, _ := dao.CanAccessRecord(record, requestData, rule); ok { ... } - * ``` - */ - canAccessRecord(record: models.Record, requestData: models.RequestData, accessRule: string): boolean - } - interface Dao { - /** - * SaveRecord persists the provided Record model in the database. - * - * If record.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a record for update you can use record.MarkAsNotNew(). - */ - saveRecord(record: models.Record): void - } - interface Dao { - /** - * DeleteRecord deletes the provided Record model. - * - * This method will also cascade the delete operation to all linked - * relational records (delete or unset, depending on the rel settings). - * - * The delete operation may fail if the record is part of a required - * reference in another record (aka. cannot be deleted or unset). - */ - deleteRecord(record: models.Record): void - } - interface Dao { - /** - * ExpandRecord expands the relations of a single Record model. - * - * Returns a map with the failed expand parameters and their errors. - */ - expandRecord(record: models.Record, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict - } - interface Dao { - /** - * ExpandRecords expands the relations of the provided Record models list. - * - * Returns a map with the failed expand parameters and their errors. - */ - expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict - } - // @ts-ignore - import validation = ozzo_validation - interface Dao { - /** - * SyncRecordTableSchema compares the two provided collections - * and applies the necessary related record table changes. - * - * If `oldCollection` is null, then only `newCollection` is used to create the record table. - */ - syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void - } - interface Dao { - /** - * RequestQuery returns a new Request logs select query. - */ - requestQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { - /** - * FindRequestById finds a single Request log by its id. - */ - findRequestById(id: string): (models.Request | undefined) - } - interface Dao { - /** - * RequestsStats returns hourly grouped requests logs statistics. - */ - requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> - } - interface Dao { - /** - * DeleteOldRequests delete all requests that are created before createdBefore. - */ - deleteOldRequests(createdBefore: time.Time): void - } - interface Dao { - /** - * SaveRequest upserts the provided Request model. - */ - saveRequest(request: models.Request): void - } - interface Dao { - /** - * FindSettings returns and decode the serialized app settings param value. - * - * The method will first try to decode the param value without decryption. - * If it fails and optEncryptionKey is set, it will try again by first - * decrypting the value and then decode it again. - * - * Returns an error if it fails to decode the stored serialized param value. - */ - findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) - } - interface Dao { - /** - * SaveSettings persists the specified settings configuration. - * - * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. - */ - saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void - } - interface Dao { - /** - * HasTable checks if a table (or view) with the provided name exists (case insensitive). - */ - hasTable(tableName: string): boolean - } - interface Dao { - /** - * TableColumns returns all column names of a single table by its name. - */ - tableColumns(tableName: string): Array - } - interface Dao { - /** - * TableInfo returns the `table_info` pragma result for the specified table. - */ - tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> - } - interface Dao { - /** - * TableIndexes returns a name grouped map with all non empty index of the specified table. - * - * Note: This method doesn't return an error on nonexisting table. - */ - tableIndexes(tableName: string): _TygojaDict - } - interface Dao { - /** - * DeleteTable drops the specified table. - * - * This method is a no-op if a table with the provided name doesn't exist. - * - * Be aware that this method is vulnerable to SQL injection and the - * "tableName" argument must come only from trusted input! - */ - deleteTable(tableName: string): void - } - interface Dao { - /** - * Vacuum executes VACUUM on the current dao.DB() instance in order to - * reclaim unused db disk space. - */ - vacuum(): void - } - interface Dao { - /** - * DeleteView drops the specified view name. - * - * This method is a no-op if a view with the provided name doesn't exist. - * - * Be aware that this method is vulnerable to SQL injection and the - * "name" argument must come only from trusted input! - */ - deleteView(name: string): void - } - interface Dao { - /** - * SaveView creates (or updates already existing) persistent SQL view. - * - * Be aware that this method is vulnerable to SQL injection and the - * "selectQuery" argument must come only from trusted input! - */ - saveView(name: string, selectQuery: string): void - } - interface Dao { - /** - * CreateViewSchema creates a new view schema from the provided select query. - * - * There are some caveats: - * - The select query must have an "id" column. - * - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data. - */ - createViewSchema(selectQuery: string): schema.Schema - } - interface Dao { - /** - * FindRecordByViewFile returns the original models.Record of the - * provided view collection file. - */ - findRecordByViewFile(viewCollectionNameOrId: string, fileFieldName: string, filename: string): (models.Record | undefined) - } -} - -/** - * Package core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. - */ -namespace core { - /** - * App defines the main PocketBase app interface. - */ - interface App { - /** - * Deprecated: - * This method may get removed in the near future. - * It is recommended to access the app db instance from app.Dao().DB() or - * if you want more flexibility - app.Dao().ConcurrentDB() and app.Dao().NonconcurrentDB(). - * - * DB returns the default app database instance. - */ - db(): (dbx.DB | undefined) - /** - * Dao returns the default app Dao instance. - * - * This Dao could operate only on the tables and models - * associated with the default app database. For example, - * trying to access the request logs table will result in error. - */ - dao(): (daos.Dao | undefined) - /** - * Deprecated: - * This method may get removed in the near future. - * It is recommended to access the logs db instance from app.LogsDao().DB() or - * if you want more flexibility - app.LogsDao().ConcurrentDB() and app.LogsDao().NonconcurrentDB(). - * - * LogsDB returns the app logs database instance. - */ - logsDB(): (dbx.DB | undefined) - /** - * LogsDao returns the app logs Dao instance. - * - * This Dao could operate only on the tables and models - * associated with the logs database. For example, trying to access - * the users table from LogsDao will result in error. - */ - logsDao(): (daos.Dao | undefined) - /** - * DataDir returns the app data directory path. - */ - dataDir(): string - /** - * EncryptionEnv returns the name of the app secret env key - * (used for settings encryption). - */ - encryptionEnv(): string - /** - * IsDebug returns whether the app is in debug mode - * (showing more detailed error logs, executed sql statements, etc.). - */ - isDebug(): boolean - /** - * Settings returns the loaded app settings. - */ - settings(): (settings.Settings | undefined) - /** - * Cache returns the app internal cache store. - */ - cache(): (store.Store | undefined) - /** - * SubscriptionsBroker returns the app realtime subscriptions broker instance. - */ - subscriptionsBroker(): (subscriptions.Broker | undefined) - /** - * NewMailClient creates and returns a configured app mail client. - */ - newMailClient(): mailer.Mailer - /** - * NewFilesystem creates and returns a configured filesystem.System instance - * for managing regular app files (eg. collection uploads). - * - * NB! Make sure to call Close() on the returned result - * after you are done working with it. - */ - newFilesystem(): (filesystem.System | undefined) - /** - * NewBackupsFilesystem creates and returns a configured filesystem.System instance - * for managing app backups. - * - * NB! Make sure to call Close() on the returned result - * after you are done working with it. - */ - newBackupsFilesystem(): (filesystem.System | undefined) - /** - * RefreshSettings reinitializes and reloads the stored application settings. - */ - refreshSettings(): void - /** - * IsBootstrapped checks if the application was initialized - * (aka. whether Bootstrap() was called). - */ - isBootstrapped(): boolean - /** - * Bootstrap takes care for initializing the application - * (open db connections, load settings, etc.). - * - * It will call ResetBootstrapState() if the application was already bootstrapped. - */ - bootstrap(): void - /** - * ResetBootstrapState takes care for releasing initialized app resources - * (eg. closing db connections). - */ - resetBootstrapState(): void - /** - * CreateBackup creates a new backup of the current app pb_data directory. - * - * Backups can be stored on S3 if it is configured in app.Settings().Backups. - * - * Please refer to the godoc of the specific core.App implementation - * for details on the backup procedures. - */ - createBackup(ctx: context.Context, name: string): void - /** - * RestoreBackup restores the backup with the specified name and restarts - * the current running application process. - * - * The safely perform the restore it is recommended to have free disk space - * for at least 2x the size of the restored pb_data backup. - * - * Please refer to the godoc of the specific core.App implementation - * for details on the restore procedures. - * - * NB! This feature is experimental and currently is expected to work only on UNIX based systems. - */ - restoreBackup(ctx: context.Context, name: string): void - /** - * Restart restarts the current running application process. - * - * Currently it is relying on execve so it is supported only on UNIX based systems. - */ - restart(): void - /** - * OnBeforeBootstrap hook is triggered before initializing the main - * application resources (eg. before db open and initial settings load). - */ - onBeforeBootstrap(): (hook.Hook | undefined) - /** - * OnAfterBootstrap hook is triggered after initializing the main - * application resources (eg. after db open and initial settings load). - */ - onAfterBootstrap(): (hook.Hook | undefined) - /** - * OnBeforeServe hook is triggered before serving the internal router (echo), - * allowing you to adjust its options and attach new routes or middlewares. - */ - onBeforeServe(): (hook.Hook | undefined) - /** - * OnBeforeApiError hook is triggered right before sending an error API - * response to the client, allowing you to further modify the error data - * or to return a completely different API response. - */ - onBeforeApiError(): (hook.Hook | undefined) - /** - * OnAfterApiError hook is triggered right after sending an error API - * response to the client. - * It could be used to log the final API error in external services. - */ - onAfterApiError(): (hook.Hook | undefined) - /** - * OnTerminate hook is triggered when the app is in the process - * of being terminated (eg. on SIGTERM signal). - */ - onTerminate(): (hook.Hook | undefined) - /** - * OnModelBeforeCreate hook is triggered before inserting a new - * entry in the DB, allowing you to modify or validate the stored data. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnModelAfterCreate hook is triggered after successfully - * inserting a new entry in the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnModelBeforeUpdate hook is triggered before updating existing - * entry in the DB, allowing you to modify or validate the stored data. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnModelAfterUpdate hook is triggered after successfully updating - * existing entry in the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnModelBeforeDelete hook is triggered before deleting an - * existing entry from the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnModelAfterDelete hook is triggered after successfully deleting an - * existing entry from the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. - */ - onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerBeforeAdminResetPasswordSend hook is triggered right - * before sending a password reset email to an admin, allowing you - * to inspect and customize the email message that is being sent. - */ - onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) - /** - * OnMailerAfterAdminResetPasswordSend hook is triggered after - * admin password reset email was successfully sent. - */ - onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) - /** - * OnMailerBeforeRecordResetPasswordSend hook is triggered right - * before sending a password reset email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerAfterRecordResetPasswordSend hook is triggered after - * an auth record password reset email was successfully sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerBeforeRecordVerificationSend hook is triggered right - * before sending a verification email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerAfterRecordVerificationSend hook is triggered after a - * verification email was successfully sent to an auth record. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerBeforeRecordChangeEmailSend hook is triggered right before - * sending a confirmation new address email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnMailerAfterRecordChangeEmailSend hook is triggered after a - * verification email was successfully sent to an auth record. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRealtimeConnectRequest hook is triggered right before establishing - * the SSE client connection. - */ - onRealtimeConnectRequest(): (hook.Hook | undefined) - /** - * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted - * SSE client connection. - */ - onRealtimeDisconnectRequest(): (hook.Hook | undefined) - /** - * OnRealtimeBeforeMessage hook is triggered right before sending - * an SSE message to a client. - * - * Returning [hook.StopPropagation] will prevent sending the message. - * Returning any other non-nil error will close the realtime connection. - */ - onRealtimeBeforeMessageSend(): (hook.Hook | undefined) - /** - * OnRealtimeBeforeMessage hook is triggered right after sending - * an SSE message to a client. - */ - onRealtimeAfterMessageSend(): (hook.Hook | undefined) - /** - * OnRealtimeBeforeSubscribeRequest hook is triggered before changing - * the client subscriptions, allowing you to further validate and - * modify the submitted change. - */ - onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) - /** - * OnRealtimeAfterSubscribeRequest hook is triggered after the client - * subscriptions were successfully changed. - */ - onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) - /** - * OnSettingsListRequest hook is triggered on each successful - * API Settings list request. - * - * Could be used to validate or modify the response before - * returning it to the client. - */ - onSettingsListRequest(): (hook.Hook | undefined) - /** - * OnSettingsBeforeUpdateRequest hook is triggered before each API - * Settings update request (after request data load and before settings persistence). - * - * Could be used to additionally validate the request data or - * implement completely different persistence behavior. - */ - onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) - /** - * OnSettingsAfterUpdateRequest hook is triggered after each - * successful API Settings update request. - */ - onSettingsAfterUpdateRequest(): (hook.Hook | undefined) - /** - * OnFileDownloadRequest hook is triggered before each API File download request. - * - * Could be used to validate or modify the file response before - * returning it to the client. - */ - onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnFileBeforeTokenRequest hook is triggered before each file - * token API request. - * - * If no token or model was submitted, e.Model and e.Token will be empty, - * allowing you to implement your own custom model file auth implementation. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnFileAfterTokenRequest hook is triggered after each - * successful file token API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnAdminsListRequest hook is triggered on each API Admins list request. - * - * Could be used to validate or modify the response before returning it to the client. - */ - onAdminsListRequest(): (hook.Hook | undefined) - /** - * OnAdminViewRequest hook is triggered on each API Admin view request. - * - * Could be used to validate or modify the response before returning it to the client. - */ - onAdminViewRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeCreateRequest hook is triggered before each API - * Admin create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - */ - onAdminBeforeCreateRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterCreateRequest hook is triggered after each - * successful API Admin create request. - */ - onAdminAfterCreateRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeUpdateRequest hook is triggered before each API - * Admin update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - */ - onAdminBeforeUpdateRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterUpdateRequest hook is triggered after each - * successful API Admin update request. - */ - onAdminAfterUpdateRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeDeleteRequest hook is triggered before each API - * Admin delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - */ - onAdminBeforeDeleteRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterDeleteRequest hook is triggered after each - * successful API Admin delete request. - */ - onAdminAfterDeleteRequest(): (hook.Hook | undefined) - /** - * OnAdminAuthRequest hook is triggered on each successful API Admin - * authentication request (sign-in, token refresh, etc.). - * - * Could be used to additionally validate or modify the - * authenticated admin data and token. - */ - onAdminAuthRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeAuthWithPasswordRequest hook is triggered before each Admin - * auth with password API request (after request data load and before password validation). - * - * Could be used to implement for example a custom password validation - * or to locate a different Admin identity (by assigning [AdminAuthWithPasswordEvent.Admin]). - */ - onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterAuthWithPasswordRequest hook is triggered after each - * successful Admin auth with password API request. - */ - onAdminAfterAuthWithPasswordRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeAuthRefreshRequest hook is triggered before each Admin - * auth refresh API request (right before generating a new auth token). - * - * Could be used to additionally validate the request data or implement - * completely different auth refresh behavior. - */ - onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterAuthRefreshRequest hook is triggered after each - * successful auth refresh API request (right after generating a new auth token). - */ - onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeRequestPasswordResetRequest hook is triggered before each Admin - * request password reset API request (after request data load and before sending the reset email). - * - * Could be used to additionally validate the request data or implement - * completely different password reset behavior. - */ - onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterRequestPasswordResetRequest hook is triggered after each - * successful request password reset API request. - */ - onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) - /** - * OnAdminBeforeConfirmPasswordResetRequest hook is triggered before each Admin - * confirm password reset API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - */ - onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) - /** - * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. - */ - onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) - /** - * OnRecordAuthRequest hook is triggered on each successful API - * record authentication request (sign-in, token refresh, etc.). - * - * Could be used to additionally validate or modify the authenticated - * record data and token. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeAuthWithPasswordRequest hook is triggered before each Record - * auth with password API request (after request data load and before password validation). - * - * Could be used to implement for example a custom password validation - * or to locate a different Record model (by reassigning [RecordAuthWithPasswordEvent.Record]). - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterAuthWithPasswordRequest hook is triggered after each - * successful Record auth with password API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeAuthWithOAuth2Request hook is triggered before each Record - * OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). - * - * If the [RecordAuthWithOAuth2Event.Record] is not set, then the OAuth2 - * request will try to create a new auth Record. - * - * To assign or link a different existing record model you can - * change the [RecordAuthWithOAuth2Event.Record] field. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterAuthWithOAuth2Request hook is triggered after each - * successful Record OAuth2 API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeAuthRefreshRequest hook is triggered before each Record - * auth refresh API request (right before generating a new auth token). - * - * Could be used to additionally validate the request data or implement - * completely different auth refresh behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterAuthRefreshRequest hook is triggered after each - * successful auth refresh API request (right after generating a new auth token). - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeUnlinkExternalAuthRequest hook is triggered before each API record - * external auth unlink request (after models load and before the actual relation deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterUnlinkExternalAuthRequest hook is triggered after each - * successful API record external auth unlink request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeRequestPasswordResetRequest hook is triggered before each Record - * request password reset API request (after request data load and before sending the reset email). - * - * Could be used to additionally validate the request data or implement - * completely different password reset behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterRequestPasswordResetRequest hook is triggered after each - * successful request password reset API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeConfirmPasswordResetRequest hook is triggered before each Record - * confirm password reset API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeRequestVerificationRequest hook is triggered before each Record - * request verification API request (after request data load and before sending the verification email). - * - * Could be used to additionally validate the loaded request data or implement - * completely different verification behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterRequestVerificationRequest hook is triggered after each - * successful request verification API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeConfirmVerificationRequest hook is triggered before each Record - * confirm verification API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterConfirmVerificationRequest hook is triggered after each - * successful confirm verification API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeRequestEmailChangeRequest hook is triggered before each Record request email change API request - * (after request data load and before sending the email link to confirm the change). - * - * Could be used to additionally validate the request data or implement - * completely different request email change behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterRequestEmailChangeRequest hook is triggered after each - * successful request email change API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeConfirmEmailChangeRequest hook is triggered before each Record - * confirm email change API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterConfirmEmailChangeRequest hook is triggered after each - * successful confirm email change API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordsListRequest hook is triggered on each API Records list request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordsListRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordViewRequest hook is triggered on each API Record view request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordViewRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeCreateRequest hook is triggered before each API Record - * create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterCreateRequest hook is triggered after each - * successful API Record create request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeUpdateRequest hook is triggered before each API Record - * update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterUpdateRequest hook is triggered after each - * successful API Record update request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordBeforeDeleteRequest hook is triggered before each API Record - * delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnRecordAfterDeleteRequest hook is triggered after each - * successful API Record delete request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. - */ - onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) - /** - * OnCollectionsListRequest hook is triggered on each API Collections list request. - * - * Could be used to validate or modify the response before returning it to the client. - */ - onCollectionsListRequest(): (hook.Hook | undefined) - /** - * OnCollectionViewRequest hook is triggered on each API Collection view request. - * - * Could be used to validate or modify the response before returning it to the client. - */ - onCollectionViewRequest(): (hook.Hook | undefined) - /** - * OnCollectionBeforeCreateRequest hook is triggered before each API Collection - * create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - */ - onCollectionBeforeCreateRequest(): (hook.Hook | undefined) - /** - * OnCollectionAfterCreateRequest hook is triggered after each - * successful API Collection create request. - */ - onCollectionAfterCreateRequest(): (hook.Hook | undefined) - /** - * OnCollectionBeforeUpdateRequest hook is triggered before each API Collection - * update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - */ - onCollectionBeforeUpdateRequest(): (hook.Hook | undefined) - /** - * OnCollectionAfterUpdateRequest hook is triggered after each - * successful API Collection update request. - */ - onCollectionAfterUpdateRequest(): (hook.Hook | undefined) - /** - * OnCollectionBeforeDeleteRequest hook is triggered before each API - * Collection delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - */ - onCollectionBeforeDeleteRequest(): (hook.Hook | undefined) - /** - * OnCollectionAfterDeleteRequest hook is triggered after each - * successful API Collection delete request. - */ - onCollectionAfterDeleteRequest(): (hook.Hook | undefined) - /** - * OnCollectionsBeforeImportRequest hook is triggered before each API - * collections import request (after request data load and before the actual import). + * When Open returns an error, it should be of type *PathError + * with the Op field set to "open", the Path field set to name, + * and the Err field describing the problem. * - * Could be used to additionally validate the imported collections or - * to implement completely different import behavior. - */ - onCollectionsBeforeImportRequest(): (hook.Hook | undefined) - /** - * OnCollectionsAfterImportRequest hook is triggered after each - * successful API collections import request. + * Open should reject attempts to open names that do not satisfy + * ValidPath(name), returning a *PathError with Err set to + * ErrInvalid or ErrNotExist. */ - onCollectionsAfterImportRequest(): (hook.Hook | undefined) + open(name: string): File } } @@ -10615,6 +6021,4857 @@ namespace cobra { } } +/** + * 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 { + /** + * Open opens and returns the FileHeader's associated File. + */ + 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 { + /** + * 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 + /** + * 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. + * + * Few HTTP clients, servers, or proxies support HTTP trailers. + */ + trailer: Header + /** + * RemoteAddr allows HTTP servers and other software to record + * the network address that sent the request, usually for + * logging. This field is not filled in by ReadRequest and + * has no defined format. The HTTP server in this package + * sets RemoteAddr to an "IP:port" address before invoking a + * handler. + * This field is ignored by the HTTP client. + */ + remoteAddr: string + /** + * RequestURI is the unmodified request-target of the + * Request-Line (RFC 7230, Section 3.1.1) as sent by the client + * to a server. Usually the URL field should be used instead. + * It is an error to set this field in an HTTP client request. + */ + requestURI: string + /** + * TLS allows HTTP servers and other software to record + * information about the TLS connection on which the request + * was received. This field is not filled in by ReadRequest. + * The HTTP server in this package sets the field for + * TLS-enabled connections before invoking a handler; + * otherwise it leaves the field nil. + * This field is ignored by the HTTP client. + */ + tls?: tls.ConnectionState + /** + * 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. + * + * Deprecated: Set the Request's context with NewRequestWithContext + * instead. If a Request's Cancel field and context are both + * set, it is undefined whether Cancel is respected. + */ + cancel: undefined + /** + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. + */ + response?: Response + } + interface Request { + /** + * Context returns the request's context. To change the context, use + * WithContext. + * + * The returned context is always non-nil; it defaults to the + * background context. + * + * 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. + */ + context(): context.Context + } + interface Request { + /** + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. + * + * 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. + */ + withContext(ctx: context.Context): (Request | undefined) + } + interface Request { + /** + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. + * + * For an outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. + */ + clone(ctx: context.Context): (Request | undefined) + } + interface Request { + /** + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. + */ + protoAtLeast(major: number): boolean + } + interface Request { + /** + * UserAgent returns the client's User-Agent, if sent in the request. + */ + userAgent(): string + } + interface Request { + /** + * Cookies parses and returns the HTTP cookies sent with the request. + */ + cookies(): Array<(Cookie | undefined)> + } + interface Request { + /** + * Cookie returns the named cookie provided in the request or + * ErrNoCookie if not found. + * If multiple cookies match the given name, only one cookie will + * be returned. + */ + cookie(name: string): (Cookie | undefined) + } + interface Request { + /** + * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, + * AddCookie does not attach more than one Cookie header field. That + * means all cookies, if any, are written into the same line, + * separated by semicolon. + * AddCookie only sanitizes c's name and value, and does not sanitize + * a Cookie header already present in the request. + */ + addCookie(c: Cookie): void + } + interface Request { + /** + * Referer returns the referring URL, if sent in the request. + * + * 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"]. + */ + referer(): string + } + interface Request { + /** + * 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. + */ + multipartReader(): (multipart.Reader | undefined) + } + interface Request { + /** + * Write writes an HTTP/1.1 request, which is the header and body, in wire format. + * This method consults the following fields of the request: + * ``` + * Host + * URL + * Method (defaults to "GET") + * Header + * ContentLength + * TransferEncoding + * Body + * ``` + * + * 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. + */ + writeProxy(w: io.Writer): void + } + interface Request { + /** + * BasicAuth returns the username and password provided in the request's + * Authorization header, if the request uses HTTP Basic Authentication. + * See RFC 2617, Section 2. + */ + basicAuth(): [string, boolean] + } + interface Request { + /** + * 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. + * + * 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. + */ + setBasicAuth(username: string): void + } + interface Request { + /** + * ParseForm populates r.Form and r.PostForm. + * + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. + * + * For POST, PUT, and PATCH requests, it also reads the request body, parses it + * as a form and puts the results into both r.PostForm and r.Form. Request body + * parameters take precedence over URL query string values in r.Form. + * + * If the request Body's size has not already been limited by MaxBytesReader, + * the size is capped at 10MB. + * + * For other HTTP methods, or when the Content-Type is not + * application/x-www-form-urlencoded, the request Body is not read, and + * r.PostForm is initialized to a non-nil, empty value. + * + * 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. + */ + parseMultipartForm(maxMemory: number): void + } + interface Request { + /** + * 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. + */ + formValue(key: string): string + } + interface Request { + /** + * 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. + */ + postFormValue(key: string): string + } + interface Request { + /** + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. + */ + formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] + } + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after the Handler.ServeHTTP method + * has returned. + */ + interface ResponseWriter { + /** + * 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. + * + * 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. + */ + header(): Header + /** + * 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. + */ + write(_arg0: string): number + /** + * 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. + * + * 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. + */ + writeHeader(statusCode: number): void + } + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { + /** + * Addr optionally specifies the TCP address for the server to listen on, + * in the form "host:port". If empty, ":http" (port 80) is used. + * The service names are defined in RFC 6335 and assigned by IANA. + * See net.Dial for details of the address format. + */ + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil + /** + * TLSConfig optionally provides a TLS configuration for use + * by ServeTLS and ListenAndServeTLS. Note that this value is + * cloned by ServeTLS and ListenAndServeTLS, so it's not + * possible to modify the configuration with methods like + * tls.Config.SetSessionTicketKeys. To use + * SetSessionTicketKeys, use Server.Serve with a TLS Listener + * instead. + */ + tlsConfig?: tls.Config + /** + * 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. + */ + readTimeout: time.Duration + /** + * ReadHeaderTimeout is the amount of time allowed to read + * request headers. The connection's read deadline is reset + * after reading the headers and the Handler can decide what + * is considered too slow for the body. If ReadHeaderTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. + */ + readHeaderTimeout: time.Duration + /** + * WriteTimeout is the maximum duration before timing out + * writes of the response. It is reset whenever a new + * request's header is read. Like ReadTimeout, it does not + * let Handlers make decisions on a per-request basis. + * A zero or negative value means there will be no timeout. + */ + writeTimeout: time.Duration + /** + * IdleTimeout is the maximum amount of time to wait for the + * next request when keep-alives are enabled. If IdleTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. + */ + idleTimeout: time.Duration + /** + * MaxHeaderBytes controls the maximum number of bytes the + * server will read parsing the request header's keys and + * values, including the request line. It does not limit the + * size of the request body. + * If zero, DefaultMaxHeaderBytes is used. + */ + maxHeaderBytes: number + /** + * TLSNextProto optionally specifies a function to take over + * ownership of the provided TLS connection when an ALPN + * protocol upgrade has occurred. The map key is the protocol + * name negotiated. The Handler argument should be used to + * handle HTTP requests and will initialize the Request's TLS + * and RemoteAddr if not already set. The connection is + * automatically closed when the function returns. + * If TLSNextProto is not nil, HTTP/2 support is not enabled + * automatically. + */ + tlsNextProto: _TygojaDict + /** + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. + */ + connState: (_arg0: net.Conn, _arg1: ConnState) => void + /** + * 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. + */ + errorLog?: log.Logger + /** + * 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. + */ + baseContext: (_arg0: net.Listener) => context.Context + /** + * ConnContext optionally specifies a function that modifies + * the context used for a new connection c. The provided ctx + * is derived from the base context and has a ServerContextKey + * value. + */ + connContext: (ctx: context.Context, c: net.Conn) => context.Context + } + interface Server { + /** + * Close immediately closes all active net.Listeners and any + * connections in state StateNew, StateActive, or StateIdle. For a + * graceful shutdown, use Shutdown. + * + * Close does not attempt to close (and does not even know about) + * any hijacked connections, such as WebSockets. + * + * 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). + * + * When Shutdown is called, Serve, ListenAndServe, and + * ListenAndServeTLS immediately return ErrServerClosed. Make sure the + * program doesn't exit and waits instead for Shutdown to return. + * + * Shutdown does not attempt to close nor wait for hijacked + * connections such as WebSockets. The caller of Shutdown should + * separately notify such long-lived connections of shutdown and wait + * for them to close, if desired. See RegisterOnShutdown for a way to + * register shutdown notification functions. + * + * 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. + * + * If srv.Addr is blank, ":http" is used. + * + * 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. + * + * 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. + */ + serve(l: net.Listener): void + } + interface Server { + /** + * 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. + */ + serveTLS(l: net.Listener, certFile: string): void + } + interface Server { + /** + * 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. + */ + setKeepAlivesEnabled(v: boolean): void + } + interface Server { + /** + * 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. + */ + listenAndServeTLS(certFile: string): void + } +} + +/** + * Package blob provides an easy and portable way to interact with blobs + * within a storage location. Subpackages contain driver implementations of + * blob for supported services. + * + * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. + * + * # 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 { + /** + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + */ + read(p: string): number + } + interface Reader { + /** + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + */ + seek(offset: number, whence: number): number + } + interface Reader { + /** + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + */ + close(): void + } + interface Reader { + /** + * ContentType returns the MIME type of the blob. + */ + contentType(): string + } + interface Reader { + /** + * ModTime returns the time the blob was last modified. + */ + modTime(): time.Time + } + interface Reader { + /** + * Size returns the size of the blob content in bytes. + */ + size(): number + } + interface Reader { + /** + * 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. + */ + as(i: { + }): boolean + } + interface Reader { + /** + * 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. + */ + writeTo(w: io.Writer): number + } + /** + * Attributes contains attributes about a blob. + */ + interface Attributes { + /** + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + */ + cacheControl: string + /** + * 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 + */ + contentDisposition: 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 + */ + contentEncoding: string + /** + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language + */ + contentLanguage: string + /** + * 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 + */ + contentType: string + /** + * 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. + */ + metadata: _TygojaDict + /** + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. + */ + createTime: time.Time + /** + * ModTime is the time the blob was last modified. + */ + 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 + /** + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + */ + eTag: string + } + interface Attributes { + /** + * 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. + */ + as(i: { + }): boolean + } + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { + /** + * Key is the key for this blob. + */ + key: string + /** + * ModTime is the time the blob was last modified. + */ + 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 + /** + * 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. + */ + isDir: boolean + } + interface ListObject { + /** + * 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. + */ + as(i: { + }): boolean + } +} + +/** + * Package echo implements high performance, minimalist Go web framework. + * + * Example: + * + * ``` + * package main + * + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) + * + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } + * + * func main() { + * // Echo instance + * e := echo.New() + * + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) + * + * // Routes + * e.GET("/", hello) + * + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } + * ``` + * + * Learn more at https://echo.labstack.com + */ +namespace echo { + /** + * Context represents the context of the current HTTP request. It holds request and + * response objects, path, path parameters, data and registered handler. + */ + interface Context { + /** + * Request returns `*http.Request`. + */ + request(): (http.Request | undefined) + /** + * 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. + * + * 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.` + */ + pathParamDefault(name: string, defaultValue: string): string + /** + * PathParams returns path parameter values. + */ + pathParams(): PathParams + /** + * SetPathParams sets path parameters for current request. + */ + setPathParams(params: PathParams): void + /** + * QueryParam returns the query param for the provided name. + */ + queryParam(name: string): string + /** + * QueryParamDefault returns the query param or default value for the provided name. + */ + queryParamDefault(name: string): string + /** + * QueryParams returns the query parameters as `url.Values`. + */ + queryParams(): url.Values + /** + * QueryString returns the URL query string. + */ + queryString(): string + /** + * FormValue returns the form field value for the provided name. + */ + formValue(name: string): string + /** + * FormValueDefault returns the form field value or default value for the provided name. + */ + formValueDefault(name: string): string + /** + * FormValues returns the form field values as `url.Values`. + */ + formValues(): url.Values + /** + * FormFile returns the multipart form file for the provided name. + */ + formFile(name: string): (multipart.FileHeader | undefined) + /** + * MultipartForm returns the multipart form. + */ + multipartForm(): (multipart.Form | undefined) + /** + * Cookie returns the named cookie provided in the request. + */ + cookie(name: string): (http.Cookie | undefined) + /** + * SetCookie adds a `Set-Cookie` header in HTTP response. + */ + setCookie(cookie: http.Cookie): void + /** + * Cookies returns the HTTP cookies sent with the request. + */ + cookies(): Array<(http.Cookie | undefined)> + /** + * Get retrieves data from the context. + */ + get(key: string): { + } + /** + * Set saves data in the context. + */ + set(key: string, val: { + }): void + /** + * Bind binds the request body into provided type `i`. The default binder + * does it based on Content-Type header. + */ + 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 + /** + * HTML sends an HTTP response with status code. + */ + html(code: number, html: string): void + /** + * HTMLBlob sends an HTTP blob response with status code. + */ + htmlBlob(code: number, b: string): void + /** + * String sends a string response with status code. + */ + string(code: number, s: string): void + /** + * JSON sends a JSON response with status code. + */ + json(code: number, i: { + }): void + /** + * JSONPretty sends a pretty-print JSON with status code. + */ + jsonPretty(code: number, i: { + }, indent: string): void + /** + * JSONBlob sends a JSON blob response with status code. + */ + jsonBlob(code: number, b: string): void + /** + * JSONP sends a JSONP response with status code. It uses `callback` to construct + * the JSONP payload. + */ + jsonp(code: number, callback: string, i: { + }): void + /** + * JSONPBlob sends a JSONP blob response with status code. It uses `callback` + * to construct the JSONP payload. + */ + jsonpBlob(code: number, callback: string, b: string): void + /** + * XML sends an XML response with status code. + */ + xml(code: number, i: { + }): void + /** + * XMLPretty sends a pretty-print XML with status code. + */ + xmlPretty(code: number, i: { + }, indent: string): void + /** + * XMLBlob sends an XML blob response with status code. + */ + xmlBlob(code: number, b: string): void + /** + * Blob sends a blob response with status code and content type. + */ + blob(code: number, contentType: string, b: string): void + /** + * Stream sends a streaming response with status code and content type. + */ + stream(code: number, contentType: string, r: io.Reader): void + /** + * File sends a response with the content of the file. + */ + file(file: string): void + /** + * FileFS sends a response with the content of the file from given filesystem. + */ + fileFS(file: string, filesystem: fs.FS): void + /** + * Attachment sends a response as attachment, prompting client to save the + * file. + */ + attachment(file: string, name: string): void + /** + * Inline sends a response as inline, opening the file in the browser. + */ + inline(file: string, name: string): void + /** + * NoContent sends a response with no body and a status code. + */ + noContent(code: number): void + /** + * Redirect redirects the request to a provided URL with status code. + */ + redirect(code: number, url: string): 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) + } + // @ts-ignore + import stdContext = context + /** + * Echo is the top-level framework instance. + * + * Note: replacing/nilling public fields is not coroutine/thread-safe and can cause data-races/panics. This is very likely + * to happen when you access Echo instances through Context.Echo() method. + */ + interface Echo { + /** + * NewContextFunc allows using custom context implementations, instead of default *echo.context + */ + 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 + } + /** + * 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 { + /** + * 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. + */ + newContext(r: http.Request, w: http.ResponseWriter): Context + } + interface Echo { + /** + * Router returns the default router. + */ + router(): Router + } + interface Echo { + /** + * Routers returns the map of host => router. + */ + routers(): _TygojaDict + } + interface Echo { + /** + * RouterFor returns Router for given host. + */ + routerFor(host: string): Router + } + 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 { + /** + * HEAD registers a new HEAD route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * OPTIONS registers a new OPTIONS route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * PATCH registers a new PATCH route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * POST registers a new POST route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * PUT registers a new PUT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * TRACE registers a new TRACE route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * 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) })` + */ + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * Any registers a new route for all supported HTTP methods and path with matching handler + * in the router with optional route-level middleware. Panics on error. + */ + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + } + interface Echo { + /** + * 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. + */ + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + } + interface Echo { + /** + * Static registers a new route with path prefix to serve static files from the provided root directory. + */ + static(pathPrefix: string): RouteInfo + } + 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 Echo { + /** + * FileFS registers a new route with path to serve file from the provided file system. + */ + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. + */ + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * AddRoute registers a new Route with default host Router + */ + addRoute(route: Routable): RouteInfo + } + interface Echo { + /** + * Add registers a new route for an HTTP method and path with matching handler + * in the router with optional route-level middleware. + */ + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * Host creates a new router group for the provided host and optional host-level middleware. + */ + host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) + } + interface Echo { + /** + * Group creates a new router group with prefix and optional group-level middleware. + */ + group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) + } + interface Echo { + /** + * AcquireContext returns an empty `Context` instance from the pool. + * You must return the context by calling `ReleaseContext()`. + */ + acquireContext(): Context + } + interface Echo { + /** + * ReleaseContext returns the `Context` instance back to the pool. + * You must call it after `AcquireContext()`. + */ + releaseContext(c: Context): void + } + interface Echo { + /** + * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + */ + serveHTTP(w: http.ResponseWriter, r: http.Request): void + } + interface Echo { + /** + * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by + * sending os.Interrupt signal with `ctrl+c`. + * + * 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) + * } + * ``` + */ + start(address: string): void + } +} + +/** + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. + * + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. + * + * Drivers that do not support context cancellation will not return until + * after the query is completed. + * + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. + */ +namespace sql { + /** + * TxOptions holds the transaction options to be used in DB.BeginTx. + */ + interface TxOptions { + /** + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. + */ + isolation: IsolationLevel + readOnly: boolean + } + /** + * DB is a database handle representing a pool of zero or more + * underlying connections. It's safe for concurrent use by multiple + * goroutines. + * + * 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 { + /** + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. + */ + pingContext(ctx: context.Context): void + } + interface DB { + /** + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. + * + * Ping uses context.Background internally; to specify the context, use + * PingContext. + */ + ping(): void + } + interface DB { + /** + * 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. + */ + close(): void + } + interface DB { + /** + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. + * + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * + * If n <= 0, no idle connections are retained. + * + * The default max idle connections is currently 2. This may change in + * a future release. + */ + setMaxIdleConns(n: number): void + } + interface DB { + /** + * SetMaxOpenConns sets the maximum number of open connections to the database. + * + * 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). + */ + setMaxOpenConns(n: number): void + } + interface DB { + /** + * 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. + */ + setConnMaxLifetime(d: time.Duration): void + } + interface DB { + /** + * 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. + */ + setConnMaxIdleTime(d: time.Duration): void + } + interface DB { + /** + * Stats returns database statistics. + */ + stats(): DBStats + } + interface DB { + /** + * 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. + */ + 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. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. + */ + prepare(query: string): (Stmt | undefined) + } + interface DB { + /** + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + */ + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface DB { + /** + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + * + * Exec uses context.Background internally; to specify the context, use + * ExecContext. + */ + exec(query: string, ...args: any[]): Result + } + interface DB { + /** + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. + */ + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + } + interface DB { + /** + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. + */ + query(query: string, ...args: any[]): (Rows | undefined) + } + interface DB { + /** + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + } + interface DB { + /** + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. + */ + queryRow(query: string, ...args: any[]): (Row | undefined) + } + interface DB { + /** + * BeginTx starts a transaction. + * + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. Tx.Commit will return an error if the context provided to + * BeginTx is canceled. + * + * The provided TxOptions is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. + */ + beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) + } + interface DB { + /** + * Begin starts a transaction. The default isolation level is dependent on + * the driver. + * + * Begin uses context.Background internally; to specify the context, use + * BeginTx. + */ + begin(): (Tx | undefined) + } + interface DB { + /** + * Driver returns the database's underlying driver. + */ + driver(): driver.Driver + } + interface DB { + /** + * Conn returns a single connection by either opening a new connection + * or returning an existing connection from the connection pool. Conn will + * block until either a connection is returned or ctx is canceled. + * Queries run on the same Conn will be run in the same database session. + * + * Every Conn must be returned to the database pool after use by + * calling Conn.Close. + */ + conn(ctx: context.Context): (Conn | 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 { + } + interface Tx { + /** + * Commit commits the transaction. + */ + commit(): void + } + interface Tx { + /** + * Rollback aborts the transaction. + */ + rollback(): void + } + interface Tx { + /** + * PrepareContext creates a prepared statement for use within a transaction. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * To use an existing prepared statement on this transaction, see Tx.Stmt. + * + * The provided context will be used for the preparation of the context, not + * for the execution of the returned statement. The returned statement + * will run in the transaction context. + */ + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + } + interface Tx { + /** + * Prepare creates a prepared statement for use within a transaction. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * To use an existing prepared statement on this transaction, see Tx.Stmt. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. + */ + prepare(query: string): (Stmt | undefined) + } + interface Tx { + /** + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. + * + * Example: + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + */ + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) + } + interface Tx { + /** + * 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. + */ + stmt(stmt: Stmt): (Stmt | undefined) + } + interface Tx { + /** + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. + */ + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Tx { + /** + * 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. + */ + exec(query: string, ...args: any[]): Result + } + interface Tx { + /** + * QueryContext executes a query that returns rows, typically a SELECT. + */ + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + } + interface Tx { + /** + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. + */ + query(query: string, ...args: any[]): (Rows | undefined) + } + interface Tx { + /** + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + } + interface Tx { + /** + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. + */ + queryRow(query: string, ...args: any[]): (Row | 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 { + /** + * ExecContext executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. + */ + execContext(ctx: context.Context, ...args: any[]): Result + } + interface Stmt { + /** + * Exec executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. + * + * Exec uses context.Background internally; to specify the context, use + * ExecContext. + */ + exec(...args: any[]): Result + } + interface Stmt { + /** + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. + */ + queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) + } + interface Stmt { + /** + * 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. + */ + query(...args: any[]): (Rows | undefined) + } + interface Stmt { + /** + * 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. + */ + queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) + } + interface Stmt { + /** + * 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. + */ + queryRow(...args: any[]): (Row | undefined) + } + interface Stmt { + /** + * Close closes the statement. + */ + 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 { + /** + * 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. + */ + 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. + * + * 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. + */ + nextResultSet(): boolean + } + interface Rows { + /** + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit Close. + */ + err(): void + } + interface Rows { + /** + * Columns returns the column names. + * Columns returns an error if the rows are closed. + */ + columns(): Array + } + interface Rows { + /** + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. + */ + columnTypes(): Array<(ColumnType | undefined)> + } + interface Rows { + /** + * 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. + * + * 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 + */ + scan(...dest: any[]): void + } + interface Rows { + /** + * 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. + */ + close(): void + } + /** + * A Result summarizes an executed SQL command. + */ + interface Result { + /** + * 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. + */ + 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 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 jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * + * See README.md for more info. + */ +namespace jwt { + /** + * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. + * This is the default claims type if you don't supply one + */ + interface MapClaims extends _TygojaDict{} + interface MapClaims { + /** + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset + */ + verifyAudience(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * 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 { + /** + * 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. + */ + valid(): void + } +} + +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 { + /** + * Scopes returns the context associated with the provider (if any). + */ + context(): context.Context + /** + * SetContext assigns the specified context to the current provider. + */ + setContext(ctx: context.Context): void + /** + * Scopes returns the provider access permissions that will be requested. + */ + scopes(): Array + /** + * SetScopes sets the provider access permissions that will be requested later. + */ + setScopes(scopes: Array): void + /** + * ClientId returns the provider client's app ID. + */ + clientId(): string + /** + * SetClientId sets the provider client's ID. + */ + setClientId(clientId: string): void + /** + * ClientSecret returns the provider client's app secret. + */ + clientSecret(): string + /** + * SetClientSecret sets the provider client's app secret. + */ + setClientSecret(secret: string): void + /** + * RedirectUrl returns the end address to redirect the user + * going through the OAuth flow. + */ + redirectUrl(): string + /** + * SetRedirectUrl sets the provider's RedirectUrl. + */ + setRedirectUrl(url: string): void + /** + * AuthUrl returns the provider's authorization service url. + */ + authUrl(): string + /** + * SetAuthUrl sets the provider's AuthUrl. + */ + setAuthUrl(url: string): void + /** + * TokenUrl returns the provider's token exchange service url. + */ + tokenUrl(): string + /** + * SetTokenUrl sets the provider's TokenUrl. + */ + setTokenUrl(url: string): void + /** + * UserApiUrl returns the provider's user info api url. + */ + userApiUrl(): string + /** + * SetUserApiUrl sets the provider's UserApiUrl. + */ + setUserApiUrl(url: string): void + /** + * Client returns an http client using the provided token. + */ + client(token: oauth2.Token): (http.Client | undefined) + /** + * BuildAuthUrl returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. + */ + buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string + /** + * FetchToken converts an authorization code to token. + */ + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) + /** + * FetchRawUserData requests and marshalizes into `result` the + * the OAuth user api response. + */ + 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) + } +} + +/** + * 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. + */ + marshalJSON(): string + } + interface JsonArray { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value + } + interface JsonArray { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. + */ + scan(value: any): void + } + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface JsonMap { + /** + * Get retrieves a single value from the current JsonMap. + * + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + */ + get(key: string): any + } + interface JsonMap { + /** + * Set sets a single value in the current JsonMap. + * + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + */ + set(key: string, value: any): void + } + interface JsonMap { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value + } + interface JsonMap { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. + */ + scan(value: any): void + } +} + +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation + /** + * Schema defines a dynamic db schema as a slice of `SchemaField`s. + */ + interface Schema { + } + interface Schema { + /** + * Fields returns the registered schema fields. + */ + fields(): Array<(SchemaField | undefined)> + } + interface Schema { + /** + * InitFieldsOptions calls `InitOptions()` for all schema fields. + */ + initFieldsOptions(): void + } + interface Schema { + /** + * Clone creates a deep clone of the current schema. + */ + clone(): (Schema | undefined) + } + interface Schema { + /** + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. + */ + asMap(): _TygojaDict + } + interface Schema { + /** + * GetFieldById returns a single field by its id. + */ + getFieldById(id: string): (SchemaField | undefined) + } + interface Schema { + /** + * GetFieldByName returns a single field by its name. + */ + getFieldByName(name: string): (SchemaField | undefined) + } + interface Schema { + /** + * RemoveField removes a single schema field by its id. + * + * This method does nothing if field with `id` doesn't exist. + */ + removeField(id: string): void + } + interface Schema { + /** + * 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. + */ + addField(newField: SchemaField): void + } + interface Schema { + /** + * 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. + */ + validate(): void + } + interface Schema { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface Schema { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * On success, all schema field options are auto initialized. + */ + unmarshalJSON(data: string): void + } + interface Schema { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value + } + interface Schema { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. + */ + scan(value: any): void + } +} + +/** + * Package models implements all PocketBase DB models and DTOs. + */ +namespace models { + type _subgAKbW = BaseModel + interface Admin extends _subgAKbW { + avatar: number + email: string + tokenKey: string + passwordHash: string + lastResetSentAt: types.DateTime + } + interface Admin { + /** + * TableName returns the Admin model SQL table name. + */ + tableName(): string + } + interface Admin { + /** + * ValidatePassword validates a plain password against the model's password. + */ + validatePassword(password: string): boolean + } + interface Admin { + /** + * SetPassword sets cryptographically secure string to `model.Password`. + * + * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + */ + setPassword(password: string): void + } + interface Admin { + /** + * RefreshTokenKey generates and sets new random token key. + */ + refreshTokenKey(): void + } + // @ts-ignore + import validation = ozzo_validation + type _subQOfDe = BaseModel + interface Collection extends _subQOfDe { + name: string + type: string + system: boolean + schema: schema.Schema + indexes: types.JsonArray + /** + * rules + */ + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap + } + interface Collection { + /** + * TableName returns the Collection model SQL table name. + */ + tableName(): string + } + interface Collection { + /** + * BaseFilesPath returns the storage dir path used by the collection. + */ + baseFilesPath(): string + } + interface Collection { + /** + * IsBase checks if the current collection has "base" type. + */ + isBase(): boolean + } + interface Collection { + /** + * IsAuth checks if the current collection has "auth" type. + */ + isAuth(): boolean + } + interface Collection { + /** + * IsView checks if the current collection has "view" type. + */ + isView(): boolean + } + interface Collection { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface Collection { + /** + * BaseOptions decodes the current collection options and returns them + * as new [CollectionBaseOptions] instance. + */ + baseOptions(): CollectionBaseOptions + } + interface Collection { + /** + * AuthOptions decodes the current collection options and returns them + * as new [CollectionAuthOptions] instance. + */ + authOptions(): CollectionAuthOptions + } + interface Collection { + /** + * ViewOptions decodes the current collection options and returns them + * as new [CollectionViewOptions] instance. + */ + viewOptions(): CollectionViewOptions + } + interface Collection { + /** + * NormalizeOptions updates the current collection options with a + * new normalized state based on the collection type. + */ + normalizeOptions(): void + } + interface Collection { + /** + * DecodeOptions decodes the current collection options into the + * provided "result" (must be a pointer). + */ + decodeOptions(result: any): void + } + interface Collection { + /** + * SetOptions normalizes and unmarshals the specified options into m.Options. + */ + setOptions(typedOptions: any): void + } + type _subVwUWg = BaseModel + interface ExternalAuth extends _subVwUWg { + collectionId: string + recordId: string + provider: string + providerId: string + } + interface ExternalAuth { + tableName(): string + } + type _subHvpye = BaseModel + interface Record extends _subHvpye { + } + interface Record { + /** + * TableName returns the table name associated to the current Record model. + */ + tableName(): string + } + interface Record { + /** + * Collection returns the Collection model associated to the current Record model. + */ + collection(): (Collection | undefined) + } + interface Record { + /** + * 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. + */ + originalCopy(): (Record | undefined) + } + interface Record { + /** + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. + */ + cleanCopy(): (Record | undefined) + } + interface Record { + /** + * Expand returns a shallow copy of the current Record model expand data. + */ + expand(): _TygojaDict + } + interface Record { + /** + * SetExpand shallow copies the provided data to the current Record model's expand. + */ + setExpand(expand: _TygojaDict): void + } + interface Record { + /** + * 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). + */ + mergeExpand(expand: _TygojaDict): void + } + interface Record { + /** + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + */ + schemaData(): _TygojaDict + } + interface Record { + /** + * 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. + */ + unknownData(): _TygojaDict + } + interface Record { + /** + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + */ + ignoreEmailVisibility(state: boolean): void + } + interface Record { + /** + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). + */ + withUnknownData(state: boolean): void + } + interface Record { + /** + * 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, value: any): void + } + interface Record { + /** + * Get returns a single record model data value for "key". + */ + get(key: string): any + } + interface Record { + /** + * GetBool returns the data value for "key" as a bool. + */ + getBool(key: string): boolean + } + interface Record { + /** + * GetString returns the data value for "key" as a string. + */ + getString(key: string): string + } + interface Record { + /** + * GetInt returns the data value for "key" as an int. + */ + getInt(key: string): number + } + interface Record { + /** + * GetFloat returns the data value for "key" as a float64. + */ + getFloat(key: string): number + } + interface Record { + /** + * GetTime returns the data value for "key" as a [time.Time] instance. + */ + getTime(key: string): time.Time + } + interface Record { + /** + * GetDateTime returns the data value for "key" as a DateTime instance. + */ + getDateTime(key: string): types.DateTime + } + interface Record { + /** + * GetStringSlice returns the data value for "key" as a slice of unique strings. + */ + getStringSlice(key: string): Array + } + interface Record { + /** + * 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. + */ + expandedOne(relField: string): (Record | undefined) + } + interface Record { + /** + * 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. + */ + expandedAll(relField: string): Array<(Record | undefined)> + } + interface Record { + /** + * 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) + * ``` + */ + unmarshalJSONField(key: string, result: any): void + } + interface Record { + /** + * BaseFilesPath returns the storage dir path used by the record. + */ + baseFilesPath(): string + } + interface Record { + /** + * FindFileFieldByFile returns the first file type field for which + * any of the record's data contains the provided filename. + */ + findFileFieldByFile(filename: string): (schema.SchemaField | undefined) + } + interface Record { + /** + * Load bulk loads the provided data into the current Record model. + */ + load(data: _TygojaDict): void + } + interface Record { + /** + * ColumnValueMap implements [ColumnValueMapper] interface. + */ + columnValueMap(): _TygojaDict + } + interface Record { + /** + * PublicExport exports only the record fields that are safe to be public. + * + * Fields marked as hidden will be exported only if `m.IgnoreEmailVisibility(true)` is set. + */ + publicExport(): _TygojaDict + } + interface Record { + /** + * MarshalJSON implements the [json.Marshaler] interface. + * + * Only the data exported by `PublicExport()` will be serialized. + */ + marshalJSON(): string + } + interface Record { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(data: string): void + } + interface Record { + /** + * 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} + * ``` + */ + replaceModifers(data: _TygojaDict): _TygojaDict + } + interface Record { + /** + * Username returns the "username" auth record data value. + */ + username(): string + } + interface Record { + /** + * 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. + */ + setUsername(username: string): void + } + interface Record { + /** + * Email returns the "email" auth record data value. + */ + email(): string + } + interface Record { + /** + * SetEmail sets the "email" auth record data value. + * + * This method doesn't check whether the provided value is a valid email. + * + * Returns an error if the record is not from an auth collection. + */ + setEmail(email: string): void + } + interface Record { + /** + * Verified returns the "emailVisibility" auth record data value. + */ + emailVisibility(): boolean + } + interface Record { + /** + * SetEmailVisibility sets the "emailVisibility" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setEmailVisibility(visible: boolean): void + } + interface Record { + /** + * Verified returns the "verified" auth record data value. + */ + verified(): boolean + } + interface Record { + /** + * SetVerified sets the "verified" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setVerified(verified: boolean): void + } + interface Record { + /** + * TokenKey returns the "tokenKey" auth record data value. + */ + tokenKey(): string + } + interface Record { + /** + * SetTokenKey sets the "tokenKey" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setTokenKey(key: string): void + } + interface Record { + /** + * RefreshTokenKey generates and sets new random auth record "tokenKey". + * + * Returns an error if the record is not from an auth collection. + */ + refreshTokenKey(): void + } + interface Record { + /** + * LastResetSentAt returns the "lastResentSentAt" auth record data value. + */ + lastResetSentAt(): types.DateTime + } + interface Record { + /** + * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setLastResetSentAt(dateTime: types.DateTime): void + } + interface Record { + /** + * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. + */ + lastVerificationSentAt(): types.DateTime + } + interface Record { + /** + * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setLastVerificationSentAt(dateTime: types.DateTime): void + } + interface Record { + /** + * PasswordHash returns the "passwordHash" auth record data value. + */ + passwordHash(): string + } + interface Record { + /** + * 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. + */ + validatePassword(password: string): boolean + } + interface Record { + /** + * 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. + */ + setPassword(password: string): void + } + /** + * RequestData defines a HTTP request data struct, usually used + * as part of the `@request.*` filter resolver. + */ + interface RequestData { + method: string + query: _TygojaDict + /** + * @todo consider changing to Body? + */ + data: _TygojaDict + headers: _TygojaDict + authRecord?: Record + admin?: Admin + } + interface RequestData { + /** + * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. + */ + hasModifierDataKeys(): boolean + } +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + /** + * Settings defines common app configuration options. + */ + interface Settings { + meta: MetaConfig + logs: LogsConfig + smtp: SmtpConfig + s3: S3Config + backups: BackupsConfig + adminAuthToken: TokenConfig + adminPasswordResetToken: TokenConfig + adminFileToken: TokenConfig + recordAuthToken: TokenConfig + recordPasswordResetToken: TokenConfig + recordEmailChangeToken: TokenConfig + recordVerificationToken: TokenConfig + recordFileToken: TokenConfig + /** + * Deprecated: Will be removed in v0.9+ + */ + emailAuth: EmailAuthConfig + googleAuth: AuthProviderConfig + facebookAuth: AuthProviderConfig + githubAuth: AuthProviderConfig + gitlabAuth: AuthProviderConfig + discordAuth: AuthProviderConfig + twitterAuth: AuthProviderConfig + microsoftAuth: AuthProviderConfig + spotifyAuth: AuthProviderConfig + kakaoAuth: AuthProviderConfig + twitchAuth: AuthProviderConfig + stravaAuth: AuthProviderConfig + giteeAuth: AuthProviderConfig + livechatAuth: AuthProviderConfig + giteaAuth: AuthProviderConfig + oidcAuth: AuthProviderConfig + oidc2Auth: AuthProviderConfig + oidc3Auth: AuthProviderConfig + appleAuth: AuthProviderConfig + instagramAuth: AuthProviderConfig + vkAuth: AuthProviderConfig + yandexAuth: AuthProviderConfig + } + interface Settings { + /** + * Validate makes Settings validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface Settings { + /** + * Merge merges `other` settings into the current one. + */ + merge(other: Settings): void + } + interface Settings { + /** + * Clone creates a new deep copy of the current settings. + */ + clone(): (Settings | undefined) + } + interface Settings { + /** + * RedactClone creates a new deep copy of the current settings, + * while replacing the secret values with `******`. + */ + redactClone(): (Settings | undefined) + } + interface Settings { + /** + * NamedAuthProviderConfigs returns a map with all registered OAuth2 + * provider configurations (indexed by their name identifier). + */ + namedAuthProviderConfigs(): _TygojaDict + } +} + +/** + * Package daos handles common PocketBase DB model manipulations. + * + * Think of daos as DB repository and service layer in one. + */ +namespace daos { + interface Dao { + /** + * AdminQuery returns a new Admin select query. + */ + adminQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindAdminById finds the admin with the provided id. + */ + findAdminById(id: string): (models.Admin | undefined) + } + interface Dao { + /** + * FindAdminByEmail finds the admin with the provided email address. + */ + findAdminByEmail(email: string): (models.Admin | undefined) + } + interface Dao { + /** + * FindAdminByToken finds the admin associated with the provided JWT token. + * + * Returns an error if the JWT token is invalid or expired. + */ + findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) + } + interface Dao { + /** + * TotalAdmins returns the number of existing admin records. + */ + totalAdmins(): number + } + interface Dao { + /** + * IsAdminEmailUnique checks if the provided email address is not + * already in use by other admins. + */ + isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean + } + interface Dao { + /** + * DeleteAdmin deletes the provided Admin model. + * + * Returns an error if there is only 1 admin. + */ + deleteAdmin(admin: models.Admin): void + } + interface Dao { + /** + * SaveAdmin upserts the provided Admin model. + */ + saveAdmin(admin: models.Admin): void + } + /** + * Dao handles various db operations. + * + * You can think of Dao as a repository and service layer in one. + */ + interface Dao { + /** + * MaxLockRetries specifies the default max "database is locked" auto retry attempts. + */ + maxLockRetries: number + /** + * ModelQueryTimeout is the default max duration of a running ModelQuery(). + * + * This field has no effect if an explicit query context is already specified. + */ + modelQueryTimeout: time.Duration + /** + * write hooks + */ + beforeCreateFunc: (eventDao: Dao, m: models.Model) => void + afterCreateFunc: (eventDao: Dao, m: models.Model) => void + beforeUpdateFunc: (eventDao: Dao, m: models.Model) => void + afterUpdateFunc: (eventDao: Dao, m: models.Model) => void + beforeDeleteFunc: (eventDao: Dao, m: models.Model) => void + afterDeleteFunc: (eventDao: Dao, m: models.Model) => void + } + interface Dao { + /** + * DB returns the default dao db builder (*dbx.DB or *dbx.TX). + * + * Currently the default db builder is dao.concurrentDB but that may change in the future. + */ + db(): dbx.Builder + } + interface Dao { + /** + * ConcurrentDB returns the dao concurrent (aka. multiple open connections) + * db builder (*dbx.DB or *dbx.TX). + * + * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. + */ + concurrentDB(): dbx.Builder + } + interface Dao { + /** + * NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) + * db builder (*dbx.DB or *dbx.TX). + * + * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. + */ + nonconcurrentDB(): dbx.Builder + } + interface Dao { + /** + * Clone returns a new Dao with the same configuration options as the current one. + */ + clone(): (Dao | undefined) + } + interface Dao { + /** + * WithoutHooks returns a new Dao with the same configuration options + * as the current one, but without create/update/delete hooks. + */ + withoutHooks(): (Dao | undefined) + } + interface Dao { + /** + * ModelQuery creates a new preconfigured select query with preset + * SELECT, FROM and other common fields based on the provided model. + */ + modelQuery(m: models.Model): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindById finds a single db record with the specified id and + * scans the result into m. + */ + findById(m: models.Model, id: string): void + } + interface Dao { + /** + * RunInTransaction wraps fn into a transaction. + * + * It is safe to nest RunInTransaction calls as long as you use the txDao. + */ + runInTransaction(fn: (txDao: Dao) => void): void + } + interface Dao { + /** + * Delete deletes the provided model. + */ + delete(m: models.Model): void + } + interface Dao { + /** + * Save persists the provided model in the database. + * + * If m.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a model for update you can use m.MarkAsNotNew(). + */ + save(m: models.Model): void + } + interface Dao { + /** + * CollectionQuery returns a new Collection select query. + */ + collectionQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindCollectionsByType finds all collections by the given type. + */ + findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> + } + interface Dao { + /** + * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. + */ + findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) + } + interface Dao { + /** + * IsCollectionNameUnique checks that there is no existing collection + * with the provided name (case insensitive!). + * + * Note: case insensitive check because the name is used also as a table name for the records. + */ + isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean + } + interface Dao { + /** + * FindCollectionReferences returns information for all + * relation schema fields referencing the provided collection. + * + * If the provided collection has reference to itself then it will be + * also included in the result. To exclude it, pass the collection id + * as the excludeId argument. + */ + findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict + } + interface Dao { + /** + * DeleteCollection deletes the provided Collection model. + * This method automatically deletes the related collection records table. + * + * NB! The collection cannot be deleted, if: + * - is system collection (aka. collection.System is true) + * - is referenced as part of a relation field in another collection + */ + deleteCollection(collection: models.Collection): void + } + interface Dao { + /** + * SaveCollection persists the provided Collection model and updates + * its related records table schema. + * + * If collecction.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a collection for update you can use collecction.MarkAsNotNew(). + */ + saveCollection(collection: models.Collection): void + } + interface Dao { + /** + * ImportCollections imports the provided collections list within a single transaction. + * + * NB1! If deleteMissing is set, all local collections and schema fields, that are not present + * in the imported configuration, WILL BE DELETED (including their related records data). + * + * NB2! This method doesn't perform validations on the imported collections data! + * If you need validations, use [forms.CollectionsImport]. + */ + importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void + } + interface Dao { + /** + * ExternalAuthQuery returns a new ExternalAuth select query. + */ + externalAuthQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindAllExternalAuthsByRecord returns all ExternalAuth models + * linked to the provided auth record. + */ + findAllExternalAuthsByRecord(authRecord: models.Record): Array<(models.ExternalAuth | undefined)> + } + interface Dao { + /** + * FindExternalAuthByProvider returns the first available + * ExternalAuth model for the specified provider and providerId. + */ + findExternalAuthByProvider(provider: string): (models.ExternalAuth | undefined) + } + interface Dao { + /** + * FindExternalAuthByRecordAndProvider returns the first available + * ExternalAuth model for the specified record data and provider. + */ + findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) + } + interface Dao { + /** + * SaveExternalAuth upserts the provided ExternalAuth model. + */ + saveExternalAuth(model: models.ExternalAuth): void + } + interface Dao { + /** + * DeleteExternalAuth deletes the provided ExternalAuth model. + */ + deleteExternalAuth(model: models.ExternalAuth): void + } + interface Dao { + /** + * ParamQuery returns a new Param select query. + */ + paramQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindParamByKey finds the first Param model with the provided key. + */ + findParamByKey(key: string): (models.Param | undefined) + } + interface Dao { + /** + * SaveParam creates or updates a Param model by the provided key-value pair. + * The value argument will be encoded as json string. + * + * If `optEncryptionKey` is provided it will encrypt the value before storing it. + */ + saveParam(key: string, value: any, ...optEncryptionKey: string[]): void + } + interface Dao { + /** + * DeleteParam deletes the provided Param model. + */ + deleteParam(param: models.Param): void + } + interface Dao { + /** + * RecordQuery returns a new Record select query from a collection model, id or name. + * + * In case a collection id or name is provided and that collection doesn't + * actually exists, the generated query will be created with a cancelled context + * and will fail once an executor (Row(), One(), All(), etc.) is called. + */ + recordQuery(collectionModelOrIdentifier: any): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindRecordById finds the Record model by its id. + */ + findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) + } + interface Dao { + /** + * FindRecordsByIds finds all Record models by the provided ids. + * If no records are found, returns an empty slice. + */ + findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> + } + interface Dao { + /** + * @todo consider to depricate as it may be easier to just use dao.RecordQuery() + * + * FindRecordsByExpr finds all records by the specified db expression. + * + * Returns all collection records if no expressions are provided. + * + * Returns an empty slice if no records are found. + * + * Example: + * + * ``` + * expr1 := dbx.HashExp{"email": "test@example.com"} + * expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) + * dao.FindRecordsByExpr("example", expr1, expr2) + * ``` + */ + findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> + } + interface Dao { + /** + * FindFirstRecordByData returns the first found record matching + * the provided key-value pair. + */ + findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) + } + interface Dao { + /** + * FindRecordsByFilter returns limit number of records matching the + * provided string filter. + * + * The sort argument is optional and can be empty string OR the same format + * used in the web APIs, eg. "-created,title". + * + * If the limit argument is <= 0, no limit is applied to the query and + * all matching records are returned. + * + * NB! Don't put untrusted user input in the filter string as it + * practically would allow the users to inject their own custom filter. + * + * Example: + * + * ``` + * dao.FindRecordsByFilter("posts", "title ~ 'lorem ipsum' && visible = true", "-created", 10) + * ``` + */ + findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> + } + interface Dao { + /** + * FindFirstRecordByFilter returns the first available record matching the provided filter. + * + * NB! Don't put untrusted user input in the filter string as it + * practically would allow the users to inject their own custom filter. + * + * Example: + * + * ``` + * dao.FindFirstRecordByFilter("posts", "slug='test'") + * ``` + */ + findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) + } + interface Dao { + /** + * IsRecordValueUnique checks if the provided key-value pair is a unique Record value. + * + * For correctness, if the collection is "auth" and the key is "username", + * the unique check will be case insensitive. + * + * NB! Array values (eg. from multiple select fields) are matched + * as a serialized json strings (eg. `["a","b"]`), so the value uniqueness + * depends on the elements order. Or in other words the following values + * are considered different: `[]string{"a","b"}` and `[]string{"b","a"}` + */ + isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean + } + interface Dao { + /** + * FindAuthRecordByToken finds the auth record associated with the provided JWT token. + * + * Returns an error if the JWT token is invalid, expired or not associated to an auth collection record. + */ + findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) + } + interface Dao { + /** + * FindAuthRecordByEmail finds the auth record associated with the provided email. + * + * Returns an error if it is not an auth collection or the record is not found. + */ + findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) + } + interface Dao { + /** + * FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive). + * + * Returns an error if it is not an auth collection or the record is not found. + */ + findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) + } + interface Dao { + /** + * SuggestUniqueAuthRecordUsername checks if the provided username is unique + * and return a new "unique" username with appended random numeric part + * (eg. "existingName" -> "existingName583"). + * + * The same username will be returned if the provided string is already unique. + */ + suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string + } + interface Dao { + /** + * CanAccessRecord checks if a record is allowed to be accessed by the + * specified requestData and accessRule. + * + * Rule and db checks are ignored in case requestData.Admin is set. + * + * The returned error indicate that something unexpected happened during + * the check (eg. invalid rule or db error). + * + * The method always return false on invalid access rule or db error. + * + * Example: + * + * ``` + * requestData := apis.RequestData(c /* echo.Context *\/) + * record, _ := dao.FindRecordById("example", "RECORD_ID") + * rule := types.Pointer("@request.auth.id != '' || status = 'public'") + * // ... or use one of the record collection's rule, eg. record.Collection().ViewRule + * + * if ok, _ := dao.CanAccessRecord(record, requestData, rule); ok { ... } + * ``` + */ + canAccessRecord(record: models.Record, requestData: models.RequestData, accessRule: string): boolean + } + interface Dao { + /** + * SaveRecord persists the provided Record model in the database. + * + * If record.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a record for update you can use record.MarkAsNotNew(). + */ + saveRecord(record: models.Record): void + } + interface Dao { + /** + * DeleteRecord deletes the provided Record model. + * + * This method will also cascade the delete operation to all linked + * relational records (delete or unset, depending on the rel settings). + * + * The delete operation may fail if the record is part of a required + * reference in another record (aka. cannot be deleted or unset). + */ + deleteRecord(record: models.Record): void + } + interface Dao { + /** + * ExpandRecord expands the relations of a single Record model. + * + * If fetchFunc is not set, then a default function will be used that + * returns all relation records. + * + * Returns a map with the failed expand parameters and their errors. + */ + expandRecord(record: models.Record, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict + } + interface Dao { + /** + * ExpandRecords expands the relations of the provided Record models list. + * + * If fetchFunc is not set, then a default function will be used that + * returns all relation records. + * + * Returns a map with the failed expand parameters and their errors. + */ + expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict + } + // @ts-ignore + import validation = ozzo_validation + interface Dao { + /** + * SyncRecordTableSchema compares the two provided collections + * and applies the necessary related record table changes. + * + * If `oldCollection` is null, then only `newCollection` is used to create the record table. + */ + syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void + } + interface Dao { + /** + * RequestQuery returns a new Request logs select query. + */ + requestQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { + /** + * FindRequestById finds a single Request log by its id. + */ + findRequestById(id: string): (models.Request | undefined) + } + interface Dao { + /** + * RequestsStats returns hourly grouped requests logs statistics. + */ + requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> + } + interface Dao { + /** + * DeleteOldRequests delete all requests that are created before createdBefore. + */ + deleteOldRequests(createdBefore: time.Time): void + } + interface Dao { + /** + * SaveRequest upserts the provided Request model. + */ + saveRequest(request: models.Request): void + } + interface Dao { + /** + * FindSettings returns and decode the serialized app settings param value. + * + * The method will first try to decode the param value without decryption. + * If it fails and optEncryptionKey is set, it will try again by first + * decrypting the value and then decode it again. + * + * Returns an error if it fails to decode the stored serialized param value. + */ + findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) + } + interface Dao { + /** + * SaveSettings persists the specified settings configuration. + * + * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. + */ + saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void + } + interface Dao { + /** + * HasTable checks if a table (or view) with the provided name exists (case insensitive). + */ + hasTable(tableName: string): boolean + } + interface Dao { + /** + * TableColumns returns all column names of a single table by its name. + */ + tableColumns(tableName: string): Array + } + interface Dao { + /** + * TableInfo returns the `table_info` pragma result for the specified table. + */ + tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> + } + interface Dao { + /** + * TableIndexes returns a name grouped map with all non empty index of the specified table. + * + * Note: This method doesn't return an error on nonexisting table. + */ + tableIndexes(tableName: string): _TygojaDict + } + interface Dao { + /** + * DeleteTable drops the specified table. + * + * This method is a no-op if a table with the provided name doesn't exist. + * + * Be aware that this method is vulnerable to SQL injection and the + * "tableName" argument must come only from trusted input! + */ + deleteTable(tableName: string): void + } + interface Dao { + /** + * Vacuum executes VACUUM on the current dao.DB() instance in order to + * reclaim unused db disk space. + */ + vacuum(): void + } + interface Dao { + /** + * DeleteView drops the specified view name. + * + * This method is a no-op if a view with the provided name doesn't exist. + * + * Be aware that this method is vulnerable to SQL injection and the + * "name" argument must come only from trusted input! + */ + deleteView(name: string): void + } + interface Dao { + /** + * SaveView creates (or updates already existing) persistent SQL view. + * + * Be aware that this method is vulnerable to SQL injection and the + * "selectQuery" argument must come only from trusted input! + */ + saveView(name: string, selectQuery: string): void + } + interface Dao { + /** + * CreateViewSchema creates a new view schema from the provided select query. + * + * There are some caveats: + * - The select query must have an "id" column. + * - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data. + */ + createViewSchema(selectQuery: string): schema.Schema + } + interface Dao { + /** + * FindRecordByViewFile returns the original models.Record of the + * provided view collection file. + */ + findRecordByViewFile(viewCollectionNameOrId: string, fileFieldName: string, filename: string): (models.Record | undefined) + } +} + +/** + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + /** + * App defines the main PocketBase app interface. + */ + interface App { + /** + * Deprecated: + * This method may get removed in the near future. + * It is recommended to access the app db instance from app.Dao().DB() or + * if you want more flexibility - app.Dao().ConcurrentDB() and app.Dao().NonconcurrentDB(). + * + * DB returns the default app database instance. + */ + db(): (dbx.DB | undefined) + /** + * Dao returns the default app Dao instance. + * + * This Dao could operate only on the tables and models + * associated with the default app database. For example, + * trying to access the request logs table will result in error. + */ + dao(): (daos.Dao | undefined) + /** + * Deprecated: + * This method may get removed in the near future. + * It is recommended to access the logs db instance from app.LogsDao().DB() or + * if you want more flexibility - app.LogsDao().ConcurrentDB() and app.LogsDao().NonconcurrentDB(). + * + * LogsDB returns the app logs database instance. + */ + logsDB(): (dbx.DB | undefined) + /** + * LogsDao returns the app logs Dao instance. + * + * This Dao could operate only on the tables and models + * associated with the logs database. For example, trying to access + * the users table from LogsDao will result in error. + */ + logsDao(): (daos.Dao | undefined) + /** + * DataDir returns the app data directory path. + */ + dataDir(): string + /** + * EncryptionEnv returns the name of the app secret env key + * (used for settings encryption). + */ + encryptionEnv(): string + /** + * IsDebug returns whether the app is in debug mode + * (showing more detailed error logs, executed sql statements, etc.). + */ + isDebug(): boolean + /** + * Settings returns the loaded app settings. + */ + settings(): (settings.Settings | undefined) + /** + * Cache returns the app internal cache store. + */ + cache(): (store.Store | undefined) + /** + * SubscriptionsBroker returns the app realtime subscriptions broker instance. + */ + subscriptionsBroker(): (subscriptions.Broker | undefined) + /** + * NewMailClient creates and returns a configured app mail client. + */ + newMailClient(): mailer.Mailer + /** + * NewFilesystem creates and returns a configured filesystem.System instance + * for managing regular app files (eg. collection uploads). + * + * NB! Make sure to call Close() on the returned result + * after you are done working with it. + */ + newFilesystem(): (filesystem.System | undefined) + /** + * NewBackupsFilesystem creates and returns a configured filesystem.System instance + * for managing app backups. + * + * NB! Make sure to call Close() on the returned result + * after you are done working with it. + */ + newBackupsFilesystem(): (filesystem.System | undefined) + /** + * RefreshSettings reinitializes and reloads the stored application settings. + */ + refreshSettings(): void + /** + * IsBootstrapped checks if the application was initialized + * (aka. whether Bootstrap() was called). + */ + isBootstrapped(): boolean + /** + * Bootstrap takes care for initializing the application + * (open db connections, load settings, etc.). + * + * It will call ResetBootstrapState() if the application was already bootstrapped. + */ + bootstrap(): void + /** + * ResetBootstrapState takes care for releasing initialized app resources + * (eg. closing db connections). + */ + resetBootstrapState(): void + /** + * CreateBackup creates a new backup of the current app pb_data directory. + * + * Backups can be stored on S3 if it is configured in app.Settings().Backups. + * + * Please refer to the godoc of the specific core.App implementation + * for details on the backup procedures. + */ + createBackup(ctx: context.Context, name: string): void + /** + * RestoreBackup restores the backup with the specified name and restarts + * the current running application process. + * + * The safely perform the restore it is recommended to have free disk space + * for at least 2x the size of the restored pb_data backup. + * + * Please refer to the godoc of the specific core.App implementation + * for details on the restore procedures. + * + * NB! This feature is experimental and currently is expected to work only on UNIX based systems. + */ + restoreBackup(ctx: context.Context, name: string): void + /** + * Restart restarts the current running application process. + * + * Currently it is relying on execve so it is supported only on UNIX based systems. + */ + restart(): void + /** + * OnBeforeBootstrap hook is triggered before initializing the main + * application resources (eg. before db open and initial settings load). + */ + onBeforeBootstrap(): (hook.Hook | undefined) + /** + * OnAfterBootstrap hook is triggered after initializing the main + * application resources (eg. after db open and initial settings load). + */ + onAfterBootstrap(): (hook.Hook | undefined) + /** + * OnBeforeServe hook is triggered before serving the internal router (echo), + * allowing you to adjust its options and attach new routes or middlewares. + */ + onBeforeServe(): (hook.Hook | undefined) + /** + * OnBeforeApiError hook is triggered right before sending an error API + * response to the client, allowing you to further modify the error data + * or to return a completely different API response. + */ + onBeforeApiError(): (hook.Hook | undefined) + /** + * OnAfterApiError hook is triggered right after sending an error API + * response to the client. + * It could be used to log the final API error in external services. + */ + onAfterApiError(): (hook.Hook | undefined) + /** + * OnTerminate hook is triggered when the app is in the process + * of being terminated (eg. on SIGTERM signal). + */ + onTerminate(): (hook.Hook | undefined) + /** + * OnModelBeforeCreate hook is triggered before inserting a new + * entry in the DB, allowing you to modify or validate the stored data. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnModelAfterCreate hook is triggered after successfully + * inserting a new entry in the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnModelBeforeUpdate hook is triggered before updating existing + * entry in the DB, allowing you to modify or validate the stored data. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnModelAfterUpdate hook is triggered after successfully updating + * existing entry in the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnModelBeforeDelete hook is triggered before deleting an + * existing entry from the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnModelAfterDelete hook is triggered after successfully deleting an + * existing entry from the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. + */ + onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerBeforeAdminResetPasswordSend hook is triggered right + * before sending a password reset email to an admin, allowing you + * to inspect and customize the email message that is being sent. + */ + onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) + /** + * OnMailerAfterAdminResetPasswordSend hook is triggered after + * admin password reset email was successfully sent. + */ + onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) + /** + * OnMailerBeforeRecordResetPasswordSend hook is triggered right + * before sending a password reset email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerAfterRecordResetPasswordSend hook is triggered after + * an auth record password reset email was successfully sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerBeforeRecordVerificationSend hook is triggered right + * before sending a verification email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerAfterRecordVerificationSend hook is triggered after a + * verification email was successfully sent to an auth record. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerBeforeRecordChangeEmailSend hook is triggered right before + * sending a confirmation new address email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnMailerAfterRecordChangeEmailSend hook is triggered after a + * verification email was successfully sent to an auth record. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRealtimeConnectRequest hook is triggered right before establishing + * the SSE client connection. + */ + onRealtimeConnectRequest(): (hook.Hook | undefined) + /** + * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted + * SSE client connection. + */ + onRealtimeDisconnectRequest(): (hook.Hook | undefined) + /** + * OnRealtimeBeforeMessage hook is triggered right before sending + * an SSE message to a client. + * + * Returning [hook.StopPropagation] will prevent sending the message. + * Returning any other non-nil error will close the realtime connection. + */ + onRealtimeBeforeMessageSend(): (hook.Hook | undefined) + /** + * OnRealtimeBeforeMessage hook is triggered right after sending + * an SSE message to a client. + */ + onRealtimeAfterMessageSend(): (hook.Hook | undefined) + /** + * OnRealtimeBeforeSubscribeRequest hook is triggered before changing + * the client subscriptions, allowing you to further validate and + * modify the submitted change. + */ + onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) + /** + * OnRealtimeAfterSubscribeRequest hook is triggered after the client + * subscriptions were successfully changed. + */ + onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) + /** + * OnSettingsListRequest hook is triggered on each successful + * API Settings list request. + * + * Could be used to validate or modify the response before + * returning it to the client. + */ + onSettingsListRequest(): (hook.Hook | undefined) + /** + * OnSettingsBeforeUpdateRequest hook is triggered before each API + * Settings update request (after request data load and before settings persistence). + * + * Could be used to additionally validate the request data or + * implement completely different persistence behavior. + */ + onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) + /** + * OnSettingsAfterUpdateRequest hook is triggered after each + * successful API Settings update request. + */ + onSettingsAfterUpdateRequest(): (hook.Hook | undefined) + /** + * OnFileDownloadRequest hook is triggered before each API File download request. + * + * Could be used to validate or modify the file response before + * returning it to the client. + */ + onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnFileBeforeTokenRequest hook is triggered before each file + * token API request. + * + * If no token or model was submitted, e.Model and e.Token will be empty, + * allowing you to implement your own custom model file auth implementation. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnFileAfterTokenRequest hook is triggered after each + * successful file token API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnAdminsListRequest hook is triggered on each API Admins list request. + * + * Could be used to validate or modify the response before returning it to the client. + */ + onAdminsListRequest(): (hook.Hook | undefined) + /** + * OnAdminViewRequest hook is triggered on each API Admin view request. + * + * Could be used to validate or modify the response before returning it to the client. + */ + onAdminViewRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeCreateRequest hook is triggered before each API + * Admin create request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + */ + onAdminBeforeCreateRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterCreateRequest hook is triggered after each + * successful API Admin create request. + */ + onAdminAfterCreateRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeUpdateRequest hook is triggered before each API + * Admin update request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + */ + onAdminBeforeUpdateRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterUpdateRequest hook is triggered after each + * successful API Admin update request. + */ + onAdminAfterUpdateRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeDeleteRequest hook is triggered before each API + * Admin delete request (after model load and before actual deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + */ + onAdminBeforeDeleteRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterDeleteRequest hook is triggered after each + * successful API Admin delete request. + */ + onAdminAfterDeleteRequest(): (hook.Hook | undefined) + /** + * OnAdminAuthRequest hook is triggered on each successful API Admin + * authentication request (sign-in, token refresh, etc.). + * + * Could be used to additionally validate or modify the + * authenticated admin data and token. + */ + onAdminAuthRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeAuthWithPasswordRequest hook is triggered before each Admin + * auth with password API request (after request data load and before password validation). + * + * Could be used to implement for example a custom password validation + * or to locate a different Admin identity (by assigning [AdminAuthWithPasswordEvent.Admin]). + */ + onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterAuthWithPasswordRequest hook is triggered after each + * successful Admin auth with password API request. + */ + onAdminAfterAuthWithPasswordRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeAuthRefreshRequest hook is triggered before each Admin + * auth refresh API request (right before generating a new auth token). + * + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. + */ + onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterAuthRefreshRequest hook is triggered after each + * successful auth refresh API request (right after generating a new auth token). + */ + onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeRequestPasswordResetRequest hook is triggered before each Admin + * request password reset API request (after request data load and before sending the reset email). + * + * Could be used to additionally validate the request data or implement + * completely different password reset behavior. + */ + onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterRequestPasswordResetRequest hook is triggered after each + * successful request password reset API request. + */ + onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) + /** + * OnAdminBeforeConfirmPasswordResetRequest hook is triggered before each Admin + * confirm password reset API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + */ + onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) + /** + * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each + * successful confirm password reset API request. + */ + onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) + /** + * OnRecordAuthRequest hook is triggered on each successful API + * record authentication request (sign-in, token refresh, etc.). + * + * Could be used to additionally validate or modify the authenticated + * record data and token. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeAuthWithPasswordRequest hook is triggered before each Record + * auth with password API request (after request data load and before password validation). + * + * Could be used to implement for example a custom password validation + * or to locate a different Record model (by reassigning [RecordAuthWithPasswordEvent.Record]). + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterAuthWithPasswordRequest hook is triggered after each + * successful Record auth with password API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeAuthWithOAuth2Request hook is triggered before each Record + * OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). + * + * If the [RecordAuthWithOAuth2Event.Record] is not set, then the OAuth2 + * request will try to create a new auth Record. + * + * To assign or link a different existing record model you can + * change the [RecordAuthWithOAuth2Event.Record] field. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterAuthWithOAuth2Request hook is triggered after each + * successful Record OAuth2 API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeAuthRefreshRequest hook is triggered before each Record + * auth refresh API request (right before generating a new auth token). + * + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterAuthRefreshRequest hook is triggered after each + * successful auth refresh API request (right after generating a new auth token). + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. + * + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeUnlinkExternalAuthRequest hook is triggered before each API record + * external auth unlink request (after models load and before the actual relation deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterUnlinkExternalAuthRequest hook is triggered after each + * successful API record external auth unlink request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeRequestPasswordResetRequest hook is triggered before each Record + * request password reset API request (after request data load and before sending the reset email). + * + * Could be used to additionally validate the request data or implement + * completely different password reset behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterRequestPasswordResetRequest hook is triggered after each + * successful request password reset API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeConfirmPasswordResetRequest hook is triggered before each Record + * confirm password reset API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterConfirmPasswordResetRequest hook is triggered after each + * successful confirm password reset API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeRequestVerificationRequest hook is triggered before each Record + * request verification API request (after request data load and before sending the verification email). + * + * Could be used to additionally validate the loaded request data or implement + * completely different verification behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterRequestVerificationRequest hook is triggered after each + * successful request verification API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeConfirmVerificationRequest hook is triggered before each Record + * confirm verification API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterConfirmVerificationRequest hook is triggered after each + * successful confirm verification API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeRequestEmailChangeRequest hook is triggered before each Record request email change API request + * (after request data load and before sending the email link to confirm the change). + * + * Could be used to additionally validate the request data or implement + * completely different request email change behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterRequestEmailChangeRequest hook is triggered after each + * successful request email change API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeConfirmEmailChangeRequest hook is triggered before each Record + * confirm email change API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterConfirmEmailChangeRequest hook is triggered after each + * successful confirm email change API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordsListRequest hook is triggered on each API Records list request. + * + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordsListRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordViewRequest hook is triggered on each API Record view request. + * + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordViewRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeCreateRequest hook is triggered before each API Record + * create request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterCreateRequest hook is triggered after each + * successful API Record create request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeUpdateRequest hook is triggered before each API Record + * update request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterUpdateRequest hook is triggered after each + * successful API Record update request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordBeforeDeleteRequest hook is triggered before each API Record + * delete request (after model load and before actual deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnRecordAfterDeleteRequest hook is triggered after each + * successful API Record delete request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnCollectionsListRequest hook is triggered on each API Collections list request. + * + * Could be used to validate or modify the response before returning it to the client. + */ + onCollectionsListRequest(): (hook.Hook | undefined) + /** + * OnCollectionViewRequest hook is triggered on each API Collection view request. + * + * Could be used to validate or modify the response before returning it to the client. + */ + onCollectionViewRequest(): (hook.Hook | undefined) + /** + * OnCollectionBeforeCreateRequest hook is triggered before each API Collection + * create request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + */ + onCollectionBeforeCreateRequest(): (hook.Hook | undefined) + /** + * OnCollectionAfterCreateRequest hook is triggered after each + * successful API Collection create request. + */ + onCollectionAfterCreateRequest(): (hook.Hook | undefined) + /** + * OnCollectionBeforeUpdateRequest hook is triggered before each API Collection + * update request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + */ + onCollectionBeforeUpdateRequest(): (hook.Hook | undefined) + /** + * OnCollectionAfterUpdateRequest hook is triggered after each + * successful API Collection update request. + */ + onCollectionAfterUpdateRequest(): (hook.Hook | undefined) + /** + * OnCollectionBeforeDeleteRequest hook is triggered before each API + * Collection delete request (after model load and before actual deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + */ + onCollectionBeforeDeleteRequest(): (hook.Hook | undefined) + /** + * OnCollectionAfterDeleteRequest hook is triggered after each + * successful API Collection delete request. + */ + onCollectionAfterDeleteRequest(): (hook.Hook | undefined) + /** + * OnCollectionsBeforeImportRequest hook is triggered before each API + * collections import request (after request data load and before the actual import). + * + * Could be used to additionally validate the imported collections or + * to implement completely different import behavior. + */ + onCollectionsBeforeImportRequest(): (hook.Hook | undefined) + /** + * OnCollectionsAfterImportRequest hook is triggered after each + * successful API collections import request. + */ + onCollectionsAfterImportRequest(): (hook.Hook | undefined) + } +} + /** * Package io provides basic interfaces to I/O primitives. * Its primary job is to wrap existing implementations of such primitives, @@ -10686,7 +10943,7 @@ namespace io { * The calendrical calculations always assume a Gregorian calendar, with * no leap seconds. * - * # Monotonic Clocks + * Monotonic Clocks * * Operating systems provide both a “wall clock,” which is subject to * changes for clock synchronization, and a “monotonic clock,” which is @@ -10745,10 +11002,6 @@ namespace io { * t.UnmarshalJSON, and t.UnmarshalText always create times with * no monotonic clock reading. * - * The monotonic clock reading exists only in Time values. It is not - * a part of Duration values or the Unix times returned by t.Unix and - * friends. - * * Note that the Go == operator compares not just the time instant but * also the Location and the monotonic clock reading. See the * documentation for the Time type for a discussion of equality @@ -10762,7 +11015,6 @@ namespace time { interface Time { /** * String returns the time formatted using the format string - * * ``` * "2006-01-02 15:04:05.999999999 -0700 MST" * ``` @@ -11018,16 +11270,6 @@ namespace time { */ zone(): [string, number] } - interface Time { - /** - * ZoneBounds returns the bounds of the time zone in effect at time t. - * The zone begins at start and the next zone begins at end. - * If the zone begins at the beginning of time, start will be returned as a zero Time. - * If the zone goes on forever, end will be returned as a zero Time. - * The Location of the returned times will be the same as t. - */ - zoneBounds(): Time - } interface Time { /** * Unix returns t as a Unix time, the number of seconds elapsed @@ -11224,6 +11466,770 @@ namespace fs { namespace context { } +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. + * + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the Dial, Listen, and Accept functions and the associated + * Conn and Listener interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. + * + * The Dial function connects to a server: + * + * ``` + * conn, err := net.Dial("tcp", "golang.org:80") + * if err != nil { + * // handle error + * } + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') + * // ... + * ``` + * + * The Listen function creates servers: + * + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` + * + * Name Resolution + * + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. + * + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. + * + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: + * + * ``` + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force 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 { + /** + * Conn is a generic stream-oriented network connection. + * + * Multiple goroutines may invoke methods on a Conn simultaneously. + */ + interface Conn { + /** + * Read reads data from the connection. + * Read can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetReadDeadline. + */ + read(b: string): number + /** + * Write writes data to the connection. + * Write can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetWriteDeadline. + */ + write(b: string): number + /** + * Close closes the connection. + * Any blocked Read or Write operations will be unblocked and return errors. + */ + close(): void + /** + * LocalAddr returns the local network address, if known. + */ + localAddr(): Addr + /** + * RemoteAddr returns the remote network address, if known. + */ + remoteAddr(): Addr + /** + * SetDeadline sets the read and write deadlines associated + * with the connection. It is equivalent to calling both + * SetReadDeadline and SetWriteDeadline. + * + * A deadline is an absolute time after which I/O operations + * fail instead of blocking. The deadline applies to all future + * and pending I/O, not just the immediately following call to + * Read or Write. After a deadline has been exceeded, the + * connection can be refreshed by setting a deadline in the future. + * + * If the deadline is exceeded a call to Read or Write or to other + * I/O methods will return an error that wraps os.ErrDeadlineExceeded. + * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). + * The error's Timeout method will return true, but note that there + * are other possible errors for which the Timeout method will + * return true even if the deadline has not been exceeded. + * + * An idle timeout can be implemented by repeatedly extending + * the deadline after successful Read or Write calls. + * + * A zero value for t means I/O operations will not time out. + */ + 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(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 url parses URLs and implements query escaping. + */ +namespace url { + /** + * A URL represents a parsed URL (technically, a URI reference). + * + * The general form represented is: + * + * ``` + * [scheme:][//[userinfo@]host][/]path[?query][#fragment] + * ``` + * + * URLs that do not start with a slash after the scheme are interpreted as: + * + * ``` + * scheme:opaque[?query][#fragment] + * ``` + * + * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. + * A consequence is that it is impossible to tell which slashes in the Path were + * slashes in the raw URL and which were %2f. This distinction is rarely important, + * but when it is, the code should use RawPath, an optional field which only gets + * set if the default encoding is different from Path. + * + * URL's String method uses the EscapedPath method to obtain the path. See the + * EscapedPath method for more details. + */ + interface URL { + scheme: string + opaque: string // encoded opaque data + user?: Userinfo // username and password information + host: string // host or host:port + path: string // path (relative paths may omit leading slash) + rawPath: string // encoded path hint (see EscapedPath method) + forceQuery: boolean // append a query ('?') even if RawQuery is empty + rawQuery: string // encoded query values, without '?' + fragment: string // fragment for references, without '#' + rawFragment: string // encoded fragment hint (see EscapedFragment method) + } + interface URL { + /** + * EscapedPath returns the escaped form of u.Path. + * In general there are multiple possible escaped forms of any path. + * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. + * Otherwise EscapedPath ignores u.RawPath and computes an escaped + * form on its own. + * The String and RequestURI methods use EscapedPath to construct + * their results. + * In general, code should call EscapedPath instead of + * reading u.RawPath directly. + */ + escapedPath(): string + } + interface URL { + /** + * EscapedFragment returns the escaped form of u.Fragment. + * In general there are multiple possible escaped forms of any fragment. + * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. + * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped + * form on its own. + * The String method uses EscapedFragment to construct its result. + * In general, code should call EscapedFragment instead of + * reading u.RawFragment directly. + */ + escapedFragment(): string + } + interface URL { + /** + * String reassembles the URL into a valid URL string. + * The general form of the result is one of: + * + * ``` + * scheme:opaque?query#fragment + * scheme://userinfo@host/path?query#fragment + * ``` + * + * If u.Opaque is non-empty, String uses the first form; + * otherwise it uses the second form. + * Any non-ASCII characters in host are escaped. + * To obtain the path, String uses u.EscapedPath(). + * + * In the second form, the following rules apply: + * ``` + * - if u.Scheme is empty, scheme: is omitted. + * - if u.User is nil, userinfo@ is omitted. + * - if u.Host is empty, host/ is omitted. + * - if u.Scheme and u.Host are empty and u.User is nil, + * the entire scheme://userinfo@host/ is omitted. + * - if u.Host is non-empty and u.Path begins with a /, + * the form host/path does not add its own /. + * - if u.RawQuery is empty, ?query is omitted. + * - if u.Fragment is empty, #fragment is omitted. + * ``` + */ + string(): string + } + interface URL { + /** + * Redacted is like String but replaces any password with "xxxxx". + * Only the password in u.URL is redacted. + */ + redacted(): string + } + /** + * Values maps a string key to a list of values. + * It is typically used for query parameters and form values. + * Unlike in the http.Header map, the keys in a Values map + * are case-sensitive. + */ + interface Values extends _TygojaDict{} + interface Values { + /** + * Get gets the first value associated with the given key. + * If there are no values associated with the key, Get returns + * the empty string. To access multiple values, use the map + * directly. + */ + get(key: string): string + } + interface Values { + /** + * Set sets the key to value. It replaces any existing + * values. + */ + set(key: string): void + } + interface Values { + /** + * Add adds the value to key. It appends to any existing + * values associated with key. + */ + add(key: string): void + } + interface Values { + /** + * Del deletes the values associated with key. + */ + del(key: string): void + } + interface Values { + /** + * Has checks whether a given key is set. + */ + has(key: string): boolean + } + interface Values { + /** + * Encode encodes the values into ``URL encoded'' form + * ("bar=baz&foo=quux") sorted by key. + */ + encode(): string + } + interface URL { + /** + * IsAbs reports whether the URL is absolute. + * Absolute means that it has a non-empty scheme. + */ + isAbs(): boolean + } + interface URL { + /** + * Parse parses a URL in the context of the receiver. The provided URL + * may be relative or absolute. Parse returns nil, err on parse + * failure, otherwise its return value is the same as ResolveReference. + */ + parse(ref: string): (URL | undefined) + } + interface URL { + /** + * ResolveReference resolves a URI reference to an absolute URI from + * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference + * may be relative or absolute. ResolveReference always returns a new + * URL instance, even if the returned URL is identical to either the + * base or reference. If ref is an absolute URL, then ResolveReference + * ignores base and returns a copy of ref. + */ + resolveReference(ref: URL): (URL | undefined) + } + interface URL { + /** + * Query parses RawQuery and returns the corresponding values. + * It silently discards malformed value pairs. + * To check errors use ParseQuery. + */ + query(): Values + } + interface URL { + /** + * RequestURI returns the encoded path?query or opaque?query + * string that would be used in an HTTP request for u. + */ + requestURI(): string + } + interface 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 tls partially implements TLS 1.2, as specified in RFC 5246, + * and TLS 1.3, as specified in RFC 8446. + */ +namespace tls { + /** + * ConnectionState records basic TLS details about the connection. + */ + interface ConnectionState { + /** + * Version is the TLS version used by the connection (e.g. VersionTLS12). + */ + version: number + /** + * HandshakeComplete is true if the handshake has concluded. + */ + handshakeComplete: boolean + /** + * DidResume is true if this connection was successfully resumed from a + * previous session with a session ticket or similar mechanism. + */ + didResume: boolean + /** + * CipherSuite is the cipher suite negotiated for the connection (e.g. + * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). + */ + cipherSuite: number + /** + * NegotiatedProtocol is the application protocol negotiated with ALPN. + */ + negotiatedProtocol: string + /** + * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. + * + * Deprecated: this value is always true. + */ + negotiatedProtocolIsMutual: boolean + /** + * ServerName is the value of the Server Name Indication extension sent by + * the client. It's available both on the server and on the client side. + */ + serverName: string + /** + * PeerCertificates are the parsed certificates sent by the peer, in the + * order in which they were sent. The first element is the leaf certificate + * that the connection is verified against. + * + * On the client side, it can't be empty. On the server side, it can be + * empty if Config.ClientAuth is not RequireAnyClientCert or + * RequireAndVerifyClientCert. + */ + peerCertificates: Array<(x509.Certificate | undefined)> + /** + * VerifiedChains is a list of one or more chains where the first element is + * PeerCertificates[0] and the last element is from Config.RootCAs (on the + * client side) or Config.ClientCAs (on the server side). + * + * On the client side, it's set if Config.InsecureSkipVerify is false. On + * the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven + * (and the peer provided a certificate) or RequireAndVerifyClientCert. + */ + verifiedChains: Array> + /** + * SignedCertificateTimestamps is a list of SCTs provided by the peer + * through the TLS handshake for the leaf certificate, if any. + */ + signedCertificateTimestamps: Array + /** + * OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) + * response provided by the peer for the leaf certificate, if any. + */ + ocspResponse: string + /** + * TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, + * Section 3). This value will be nil for TLS 1.3 connections and for all + * resumed connections. + * + * Deprecated: there are conditions in which this value might not be unique + * to a connection. See the Security Considerations sections of RFC 5705 and + * RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings. + */ + tlsUnique: string + } + interface ConnectionState { + /** + * ExportKeyingMaterial returns length bytes of exported key material in a new + * slice as defined in RFC 5705. If context is nil, it is not used as part of + * the seed. If the connection was set to allow renegotiation via + * Config.Renegotiation, this function will return an error. + */ + exportKeyingMaterial(label: string, context: string, length: number): string + } + /** + * A Config structure is used to configure a TLS client or server. + * After one has been passed to a TLS function it must not be + * modified. A Config may be reused; the tls package will also not + * modify it. + */ + interface Config { + /** + * Rand provides the source of entropy for nonces and RSA blinding. + * If Rand is nil, TLS uses the cryptographic random reader in package + * crypto/rand. + * The Reader must be safe for use by multiple goroutines. + */ + rand: io.Reader + /** + * Time returns the current time as the number of seconds since the epoch. + * If Time is nil, TLS uses time.Now. + */ + time: () => time.Time + /** + * Certificates contains one or more certificate chains to present to the + * other side of the connection. The first certificate compatible with the + * peer's requirements is selected automatically. + * + * Server configurations must set one of Certificates, GetCertificate or + * GetConfigForClient. Clients doing client-authentication may set either + * Certificates or GetClientCertificate. + * + * Note: if there are multiple Certificates, and they don't have the + * optional field Leaf set, certificate selection will incur a significant + * per-handshake performance cost. + */ + certificates: Array + /** + * NameToCertificate maps from a certificate name to an element of + * Certificates. Note that a certificate name can be of the form + * '*.example.com' and so doesn't have to be a domain name as such. + * + * Deprecated: NameToCertificate only allows associating a single + * certificate with a given name. Leave this field nil to let the library + * select the first compatible chain from Certificates. + */ + nameToCertificate: _TygojaDict + /** + * GetCertificate returns a Certificate based on the given + * ClientHelloInfo. It will only be called if the client supplies SNI + * information or if Certificates is empty. + * + * If GetCertificate is nil or returns nil, then the certificate is + * retrieved from NameToCertificate. If NameToCertificate is nil, the + * best element of Certificates will be used. + */ + getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) + /** + * GetClientCertificate, if not nil, is called when a server requests a + * certificate from a client. If set, the contents of Certificates will + * be ignored. + * + * If GetClientCertificate returns an error, the handshake will be + * aborted and that error will be returned. Otherwise + * GetClientCertificate must return a non-nil Certificate. If + * Certificate.Certificate is empty then no certificate will be sent to + * the server. If this is unacceptable to the server then it may abort + * the handshake. + * + * GetClientCertificate may be called multiple times for the same + * connection if renegotiation occurs or if TLS 1.3 is in use. + */ + getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) + /** + * GetConfigForClient, if not nil, is called after a ClientHello is + * received from a client. It may return a non-nil Config in order to + * change the Config that will be used to handle this connection. If + * the returned Config is nil, the original Config will be used. The + * Config returned by this callback may not be subsequently modified. + * + * If GetConfigForClient is nil, the Config passed to Server() will be + * used for all connections. + * + * If SessionTicketKey was explicitly set on the returned Config, or if + * SetSessionTicketKeys was called on the returned Config, those keys will + * be used. Otherwise, the original Config keys will be used (and possibly + * rotated if they are automatically managed). + */ + getConfigForClient: (_arg0: ClientHelloInfo) => (Config | undefined) + /** + * VerifyPeerCertificate, if not nil, is called after normal + * certificate verification by either a TLS client or server. It + * receives the raw ASN.1 certificates provided by the peer and also + * any verified chains that normal processing found. If it returns a + * non-nil error, the handshake is aborted and that error results. + * + * If normal verification fails then the handshake will abort before + * considering this callback. If normal verification is disabled by + * setting InsecureSkipVerify, or (for a server) when ClientAuth is + * RequestClientCert or RequireAnyClientCert, then this callback will + * be considered but the verifiedChains argument will always be nil. + */ + verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void + /** + * VerifyConnection, if not nil, is called after normal certificate + * verification and after VerifyPeerCertificate by either a TLS client + * or server. If it returns a non-nil error, the handshake is aborted + * and that error results. + * + * If normal verification fails then the handshake will abort before + * considering this callback. This callback will run for all connections + * regardless of InsecureSkipVerify or ClientAuth settings. + */ + verifyConnection: (_arg0: ConnectionState) => void + /** + * RootCAs defines the set of root certificate authorities + * that clients use when verifying server certificates. + * If RootCAs is nil, TLS uses the host's root CA set. + */ + rootCAs?: x509.CertPool + /** + * NextProtos is a list of supported application level protocols, in + * order of preference. If both peers support ALPN, the selected + * protocol will be one from this list, and the connection will fail + * if there is no mutually supported protocol. If NextProtos is empty + * or the peer doesn't support ALPN, the connection will succeed and + * ConnectionState.NegotiatedProtocol will be empty. + */ + nextProtos: Array + /** + * ServerName is used to verify the hostname on the returned + * certificates unless InsecureSkipVerify is given. It is also included + * in the client's handshake to support virtual hosting unless it is + * an IP address. + */ + serverName: string + /** + * ClientAuth determines the server's policy for + * TLS Client Authentication. The default is NoClientCert. + */ + clientAuth: ClientAuthType + /** + * ClientCAs defines the set of root certificate authorities + * that servers use if required to verify a client certificate + * by the policy in ClientAuth. + */ + clientCAs?: x509.CertPool + /** + * InsecureSkipVerify controls whether a client verifies the server's + * certificate chain and host name. If InsecureSkipVerify is true, crypto/tls + * accepts any certificate presented by the server and any host name in that + * certificate. In this mode, TLS is susceptible to machine-in-the-middle + * attacks unless custom verification is used. This should be used only for + * testing or in combination with VerifyConnection or VerifyPeerCertificate. + */ + insecureSkipVerify: boolean + /** + * CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of + * the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. + * + * If CipherSuites is nil, a safe default list is used. The default cipher + * suites might change over time. + */ + cipherSuites: Array + /** + * PreferServerCipherSuites is a legacy field and has no effect. + * + * It used to control whether the server would follow the client's or the + * server's preference. Servers now select the best mutually supported + * cipher suite based on logic that takes into account inferred client + * hardware, server hardware, and security. + * + * Deprecated: PreferServerCipherSuites is ignored. + */ + preferServerCipherSuites: boolean + /** + * SessionTicketsDisabled may be set to true to disable session ticket and + * PSK (resumption) support. Note that on clients, session ticket support is + * also disabled if ClientSessionCache is nil. + */ + sessionTicketsDisabled: boolean + /** + * SessionTicketKey is used by TLS servers to provide session resumption. + * See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled + * with random data before the first server handshake. + * + * Deprecated: if this field is left at zero, session ticket keys will be + * automatically rotated every day and dropped after seven days. For + * customizing the rotation schedule or synchronizing servers that are + * terminating connections for the same host, use SetSessionTicketKeys. + */ + sessionTicketKey: string + /** + * ClientSessionCache is a cache of ClientSessionState entries for TLS + * session resumption. It is only used by clients. + */ + clientSessionCache: ClientSessionCache + /** + * MinVersion contains the minimum TLS version that is acceptable. + * + * By default, TLS 1.2 is currently used as the minimum when acting as a + * client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum + * supported by this package, both as a client and as a server. + * + * The client-side default can temporarily be reverted to TLS 1.0 by + * including the value "x509sha1=1" in the GODEBUG environment variable. + * Note that this option will be removed in Go 1.19 (but it will still be + * possible to set this field to VersionTLS10 explicitly). + */ + minVersion: number + /** + * MaxVersion contains the maximum TLS version that is acceptable. + * + * By default, the maximum version supported by this package is used, + * which is currently TLS 1.3. + */ + maxVersion: number + /** + * CurvePreferences contains the elliptic curves that will be used in + * an ECDHE handshake, in preference order. If empty, the default will + * be used. The client will use the first preference as the type for + * its key share in TLS 1.3. This may change in the future. + */ + curvePreferences: Array + /** + * DynamicRecordSizingDisabled disables adaptive sizing of TLS records. + * When true, the largest possible TLS record size is always used. When + * false, the size of TLS records may be adjusted in an attempt to + * improve latency. + */ + dynamicRecordSizingDisabled: boolean + /** + * Renegotiation controls what types of renegotiation are supported. + * The default, none, is correct for the vast majority of applications. + */ + renegotiation: RenegotiationSupport + /** + * KeyLogWriter optionally specifies a destination for TLS master secrets + * in NSS key log format that can be used to allow external programs + * such as Wireshark to decrypt TLS connections. + * See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. + * Use of KeyLogWriter compromises security and should only be + * used for debugging. + */ + keyLogWriter: io.Writer + } + interface Config { + /** + * Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is + * being used concurrently by a TLS client or server. + */ + clone(): (Config | undefined) + } + interface Config { + /** + * SetSessionTicketKeys updates the session ticket keys for a server. + * + * The first key will be used when creating new tickets, while all keys can be + * used for decrypting tickets. It is safe to call this function while the + * server is running in order to rotate the session ticket keys. The function + * will panic if keys is empty. + * + * Calling this function will turn off automatic session ticket key rotation. + * + * If multiple servers are terminating connections for the same host they should + * all have the same session ticket keys. If the session ticket keys leaks, + * previously recorded and future TLS connections using those keys might be + * compromised. + */ + setSessionTicketKeys(keys: Array): void + } + interface Config { + /** + * BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate + * from the CommonName and SubjectAlternateName fields of each of the leaf + * certificates. + * + * Deprecated: NameToCertificate only allows associating a single certificate + * with a given name. Leave that field nil to let the library select the first + * compatible chain from Certificates. + */ + buildNameToCertificate(): void + } +} + /** * Package textproto implements generic support for text-based request/response * protocols in the style of HTTP, NNTP, and SMTP. @@ -11295,6 +12301,937 @@ namespace textproto { } } +/** + * 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 { + interface Reader { + /** + * ReadForm parses an entire multipart message whose parts have + * a Content-Disposition of "form-data". + * It stores up to maxMemory bytes + 10MB (reserved for non-file parts) + * in memory. File parts which can't be stored in memory will be stored on + * disk in temporary files. + * It returns ErrMessageTooLarge if all non-file parts can't be stored in + * memory. + */ + readForm(maxMemory: number): (Form | undefined) + } + /** + * Form is a parsed multipart form. + * Its File parts are stored either in memory or on disk, + * and are accessible via the *FileHeader's Open method. + * Its Value parts are stored as strings. + * Both are keyed by field name. + */ + interface Form { + value: _TygojaDict + file: _TygojaDict + } + interface Form { + /** + * RemoveAll removes any temporary files associated with a Form. + */ + removeAll(): void + } + /** + * File is an interface to access the file part of a multipart message. + * Its contents may be either stored in memory or on disk. + * If stored on disk, the File's underlying concrete type will be an *os.File. + */ + interface File { + } + /** + * Reader is an iterator over parts in a MIME multipart body. + * Reader's underlying parser consumes its input as needed. Seeking + * isn't supported. + */ + interface Reader { + } + interface Reader { + /** + * NextPart returns the next part in the multipart or an error. + * When there are no more parts, the error io.EOF is returned. + * + * As a special case, if the "Content-Transfer-Encoding" header + * has a value of "quoted-printable", that header is instead + * hidden and the body is transparently decoded during Read calls. + */ + nextPart(): (Part | undefined) + } + interface Reader { + /** + * NextRawPart returns the next part in the multipart or an error. + * When there are no more parts, the error io.EOF is returned. + * + * Unlike NextPart, it does not have special handling for + * "Content-Transfer-Encoding: quoted-printable". + */ + nextRawPart(): (Part | undefined) + } +} + +/** + * Package log implements a simple logging package. It defines a type, Logger, + * with methods for formatting output. It also has a predefined 'standard' + * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and + * Panic[f|ln], which are easier to use than creating a Logger manually. + * That logger writes to standard error and prints the date and time + * of each logged message. + * Every log message is output on a separate line: if the message being + * printed does not end in a newline, the logger will add one. + * The Fatal functions call os.Exit(1) after writing the log message. + * The Panic functions call panic after writing the log message. + */ +namespace log { + /** + * A Logger represents an active logging object that generates lines of + * output to an io.Writer. Each logging operation makes a single call to + * the Writer's Write method. A Logger can be used simultaneously from + * multiple goroutines; it guarantees to serialize access to the Writer. + */ + interface Logger { + } + interface Logger { + /** + * SetOutput sets the output destination for the logger. + */ + setOutput(w: io.Writer): void + } + interface Logger { + /** + * Output writes the output for a logging event. The string s contains + * the text to print after the prefix specified by the flags of the + * Logger. A newline is appended if the last character of s is not + * already a newline. Calldepth is used to recover the PC and is + * provided for generality, although at the moment on all pre-defined + * paths it will be 2. + */ + output(calldepth: number, s: string): void + } + interface Logger { + /** + * Printf calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Printf. + */ + printf(format: string, ...v: any[]): void + } + interface Logger { + /** + * Print calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Print. + */ + print(...v: any[]): void + } + interface Logger { + /** + * Println calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Println. + */ + println(...v: any[]): void + } + interface Logger { + /** + * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). + */ + fatal(...v: any[]): void + } + interface Logger { + /** + * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). + */ + fatalf(format: string, ...v: any[]): void + } + interface Logger { + /** + * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). + */ + fatalln(...v: any[]): void + } + interface Logger { + /** + * Panic is equivalent to l.Print() followed by a call to panic(). + */ + panic(...v: any[]): void + } + interface Logger { + /** + * Panicf is equivalent to l.Printf() followed by a call to panic(). + */ + panicf(format: string, ...v: any[]): void + } + interface Logger { + /** + * Panicln is equivalent to l.Println() followed by a call to panic(). + */ + panicln(...v: any[]): void + } + interface Logger { + /** + * Flags returns the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. + */ + flags(): number + } + interface Logger { + /** + * SetFlags sets the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. + */ + setFlags(flag: number): void + } + interface Logger { + /** + * Prefix returns the output prefix for the logger. + */ + prefix(): string + } + interface Logger { + /** + * SetPrefix sets the output prefix for the logger. + */ + setPrefix(prefix: string): void + } + interface Logger { + /** + * Writer returns the output destination for the logger. + */ + writer(): io.Writer + } +} + +/** + * 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 { + /** + * A Client is an HTTP client. Its zero value (DefaultClient) is a + * usable client that uses DefaultTransport. + * + * The Client's Transport typically has internal state (cached TCP + * connections), so Clients should be reused instead of created as + * needed. Clients are safe for concurrent use by multiple goroutines. + * + * A Client is higher-level than a RoundTripper (such as Transport) + * and additionally handles HTTP details such as cookies and + * redirects. + * + * When following redirects, the Client will forward all headers set on the + * initial Request except: + * + * • when forwarding sensitive headers like "Authorization", + * "WWW-Authenticate", and "Cookie" to untrusted targets. + * These headers will be ignored when following a redirect to a domain + * that is not a subdomain match or exact match of the initial domain. + * For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + * will forward the sensitive headers, but a redirect to "bar.com" will not. + * + * • when forwarding the "Cookie" header with a non-nil cookie Jar. + * Since each redirect may mutate the state of the cookie jar, + * a redirect may possibly alter a cookie set in the initial request. + * When forwarding the "Cookie" header, any mutated cookies will be omitted, + * with the expectation that the Jar will insert those mutated cookies + * with the updated values (assuming the origin matches). + * If Jar is nil, the initial cookies are forwarded without change. + */ + interface Client { + /** + * Transport specifies the mechanism by which individual + * HTTP requests are made. + * If nil, DefaultTransport is used. + */ + transport: RoundTripper + /** + * CheckRedirect specifies the policy for handling redirects. + * If CheckRedirect is not nil, the client calls it before + * following an HTTP redirect. The arguments req and via are + * the upcoming request and the requests made already, oldest + * first. If CheckRedirect returns an error, the Client's Get + * method returns both the previous Response (with its Body + * closed) and CheckRedirect's error (wrapped in a url.Error) + * instead of issuing the Request req. + * As a special case, if CheckRedirect returns ErrUseLastResponse, + * then the most recent response is returned with its body + * unclosed, along with a nil error. + * + * If CheckRedirect is nil, the Client uses its default policy, + * which is to stop after 10 consecutive requests. + */ + checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void + /** + * Jar specifies the cookie jar. + * + * The Jar is used to insert relevant cookies into every + * outbound Request and is updated with the cookie values + * of every inbound Response. The Jar is consulted for every + * redirect that the Client follows. + * + * If Jar is nil, cookies are only sent if they are explicitly + * set on the Request. + */ + jar: CookieJar + /** + * Timeout specifies a time limit for requests made by this + * Client. The timeout includes connection time, any + * redirects, and reading the response body. The timer remains + * running after Get, Head, Post, or Do return and will + * interrupt reading of the Response.Body. + * + * A Timeout of zero means no timeout. + * + * The Client cancels requests to the underlying Transport + * as if the Request's Context ended. + * + * For compatibility, the Client will also use the deprecated + * CancelRequest method on Transport if found. New + * RoundTripper implementations should use the Request's Context + * for cancellation instead of implementing CancelRequest. + */ + timeout: time.Duration + } + interface Client { + /** + * Get issues a GET to the specified URL. If the response is one of the + * following redirect codes, Get follows the redirect after calling the + * Client's CheckRedirect function: + * + * ``` + * 301 (Moved Permanently) + * 302 (Found) + * 303 (See Other) + * 307 (Temporary Redirect) + * 308 (Permanent Redirect) + * ``` + * + * An error is returned if the Client's CheckRedirect function fails + * or if there was an HTTP protocol error. A non-2xx response doesn't + * cause an error. Any returned error will be of type *url.Error. The + * url.Error value's Timeout method will report true if the request + * timed out. + * + * When err is nil, resp always contains a non-nil resp.Body. + * Caller should close resp.Body when done reading from it. + * + * To make a request with custom headers, use NewRequest and Client.Do. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. + */ + get(url: string): (Response | undefined) + } + interface Client { + /** + * Do sends an HTTP request and returns an HTTP response, following + * policy (such as redirects, cookies, auth) as configured on the + * client. + * + * An error is returned if caused by client policy (such as + * CheckRedirect), or failure to speak HTTP (such as a network + * connectivity problem). A non-2xx status code doesn't cause an + * error. + * + * If the returned error is nil, the Response will contain a non-nil + * Body which the user is expected to close. If the Body is not both + * read to EOF and closed, the Client's underlying RoundTripper + * (typically Transport) may not be able to re-use a persistent TCP + * connection to the server for a subsequent "keep-alive" request. + * + * The request Body, if non-nil, will be closed by the underlying + * Transport, even on errors. + * + * On error, any Response can be ignored. A non-nil Response with a + * non-nil error only occurs when CheckRedirect fails, and even then + * the returned Response.Body is already closed. + * + * Generally Get, Post, or PostForm will be used instead of Do. + * + * If the server replies with a redirect, the Client first uses the + * CheckRedirect function to determine whether the redirect should be + * followed. If permitted, a 301, 302, or 303 redirect causes + * subsequent requests to use HTTP method GET + * (or HEAD if the original request was HEAD), with no body. + * A 307 or 308 redirect preserves the original HTTP method and body, + * provided that the Request.GetBody function is defined. + * The NewRequest function automatically sets GetBody for common + * standard library body types. + * + * Any returned error will be of type *url.Error. The url.Error + * value's Timeout method will report true if the request timed out. + */ + do(req: Request): (Response | undefined) + } + interface Client { + /** + * Post issues a POST to the specified URL. + * + * Caller should close resp.Body when done reading from it. + * + * If the provided body is an io.Closer, it is closed after the + * request. + * + * To set custom headers, use NewRequest and Client.Do. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. + * + * See the Client.Do method documentation for details on how redirects + * are handled. + */ + post(url: string, body: io.Reader): (Response | undefined) + } + interface Client { + /** + * PostForm issues a POST to the specified URL, + * with data's keys and values URL-encoded as the request body. + * + * The Content-Type header is set to application/x-www-form-urlencoded. + * To set other headers, use NewRequest and Client.Do. + * + * When err is nil, resp always contains a non-nil resp.Body. + * Caller should close resp.Body when done reading from it. + * + * See the Client.Do method documentation for details on how redirects + * are handled. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. + */ + postForm(url: string, data: url.Values): (Response | undefined) + } + interface Client { + /** + * Head issues a HEAD to the specified URL. If the response is one of the + * following redirect codes, Head follows the redirect after calling the + * Client's CheckRedirect function: + * + * ``` + * 301 (Moved Permanently) + * 302 (Found) + * 303 (See Other) + * 307 (Temporary Redirect) + * 308 (Permanent Redirect) + * ``` + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. + */ + head(url: string): (Response | undefined) + } + interface Client { + /** + * CloseIdleConnections closes any connections on its Transport which + * were previously connected from previous requests but are now + * sitting idle in a "keep-alive" state. It does not interrupt any + * connections currently in use. + * + * If the Client's Transport does not have a CloseIdleConnections method + * then this method does nothing. + */ + closeIdleConnections(): void + } + /** + * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an + * HTTP response or the Cookie header of an HTTP request. + * + * See https://tools.ietf.org/html/rfc6265 for details. + */ + interface Cookie { + name: string + value: string + path: string // optional + domain: string // optional + expires: time.Time // optional + rawExpires: string // for reading cookies only + /** + * MaxAge=0 means no 'Max-Age' attribute specified. + * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' + * MaxAge>0 means Max-Age attribute present and given in seconds + */ + maxAge: number + secure: boolean + httpOnly: boolean + sameSite: SameSite + raw: string + unparsed: Array // Raw text of unparsed attribute-value pairs + } + interface Cookie { + /** + * String returns the serialization of the cookie for use in a Cookie + * header (if only Name and Value are set) or a Set-Cookie response + * header (if other fields are set). + * If c is nil or c.Name is invalid, the empty string is returned. + */ + string(): string + } + interface Cookie { + /** + * Valid reports whether the cookie is valid. + */ + valid(): void + } + // @ts-ignore + import mathrand = rand + /** + * A Header represents the key-value pairs in an HTTP header. + * + * The keys should be in canonical form, as returned by + * CanonicalHeaderKey. + */ + interface Header extends _TygojaDict{} + interface Header { + /** + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. + * The key is case insensitive; it is canonicalized by + * CanonicalHeaderKey. + */ + add(key: string): void + } + interface Header { + /** + * Set sets the header entries associated with key to the + * single element value. It replaces any existing values + * associated with key. The key is case insensitive; it is + * canonicalized by textproto.CanonicalMIMEHeaderKey. + * To use non-canonical keys, assign to the map directly. + */ + set(key: string): void + } + interface Header { + /** + * Get gets the first value associated with the given key. If + * there are no values associated with the key, Get returns "". + * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical keys, + * access the map directly. + */ + get(key: string): string + } + interface Header { + /** + * Values returns all values associated with the given key. + * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical + * keys, access the map directly. + * The returned slice is not a copy. + */ + values(key: string): Array + } + interface Header { + /** + * Del deletes the values associated with key. + * The key is case insensitive; it is canonicalized by + * CanonicalHeaderKey. + */ + del(key: string): void + } + interface Header { + /** + * Write writes a header in wire format. + */ + write(w: io.Writer): void + } + interface Header { + /** + * Clone returns a copy of h or nil if h is nil. + */ + clone(): Header + } + interface Header { + /** + * WriteSubset writes a header in wire format. + * If exclude is not nil, keys where exclude[key] == true are not written. + * Keys are not canonicalized before checking the exclude map. + */ + writeSubset(w: io.Writer, exclude: _TygojaDict): void + } + // @ts-ignore + import urlpkg = url + /** + * Response represents the response from an HTTP request. + * + * The Client and Transport return Responses from servers once + * the response headers have been received. The response body + * is streamed on demand as the Body field is read. + */ + interface Response { + status: string // e.g. "200 OK" + statusCode: number // e.g. 200 + proto: string // e.g. "HTTP/1.0" + protoMajor: number // e.g. 1 + protoMinor: number // e.g. 0 + /** + * Header maps header keys to values. If the response had multiple + * headers with the same key, they may be concatenated, with comma + * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers + * be semantically equivalent to a comma-delimited sequence.) When + * Header values are duplicated by other fields in this struct (e.g., + * ContentLength, TransferEncoding, Trailer), the field values are + * authoritative. + * + * Keys in the map are canonicalized (see CanonicalHeaderKey). + */ + header: Header + /** + * Body represents the response body. + * + * The response body is streamed on demand as the Body field + * is read. If the network connection fails or the server + * terminates the response, Body.Read calls return an error. + * + * The http Client and Transport guarantee that Body is always + * non-nil, even on responses without a body or responses with + * a zero-length body. It is the caller's responsibility to + * close Body. The default HTTP client's Transport may not + * reuse HTTP/1.x "keep-alive" TCP connections if the Body is + * not read to completion and closed. + * + * The Body is automatically dechunked if the server replied + * with a "chunked" Transfer-Encoding. + * + * As of Go 1.12, the Body will also implement io.Writer + * on a successful "101 Switching Protocols" response, + * as used by WebSockets and HTTP/2's "h2c" mode. + */ + body: io.ReadCloser + /** + * ContentLength records the length of the associated content. The + * value -1 indicates that the length is unknown. Unless Request.Method + * is "HEAD", values >= 0 indicate that the given number of bytes may + * be read from Body. + */ + contentLength: number + /** + * Contains transfer encodings from outer-most to inner-most. Value is + * nil, means that "identity" encoding is used. + */ + transferEncoding: Array + /** + * Close records whether the header directed that the connection be + * closed after reading Body. The value is advice for clients: neither + * ReadResponse nor Response.Write ever closes a connection. + */ + close: boolean + /** + * Uncompressed reports whether the response was sent compressed but + * was decompressed by the http package. When true, reading from + * Body yields the uncompressed content instead of the compressed + * content actually set from the server, ContentLength is set to -1, + * and the "Content-Length" and "Content-Encoding" fields are deleted + * from the responseHeader. To get the original response from + * the server, set Transport.DisableCompression to true. + */ + uncompressed: boolean + /** + * Trailer maps trailer keys to values in the same + * format as Header. + * + * The Trailer initially contains only nil values, one for + * each key specified in the server's "Trailer" header + * value. Those values are not added to Header. + * + * Trailer must not be accessed concurrently with Read calls + * on the Body. + * + * After Body.Read has returned io.EOF, Trailer will contain + * any trailer values sent by the server. + */ + trailer: Header + /** + * Request is the request that was sent to obtain this Response. + * Request's Body is nil (having already been consumed). + * This is only populated for Client requests. + */ + request?: Request + /** + * TLS contains information about the TLS connection on which the + * response was received. It is nil for unencrypted responses. + * The pointer is shared between responses and should not be + * modified. + */ + tls?: tls.ConnectionState + } + interface Response { + /** + * Cookies parses and returns the cookies set in the Set-Cookie headers. + */ + cookies(): Array<(Cookie | undefined)> + } + interface Response { + /** + * Location returns the URL of the response's "Location" header, + * if present. Relative redirects are resolved relative to + * the Response's Request. ErrNoLocation is returned if no + * Location header is present. + */ + location(): (url.URL | undefined) + } + interface Response { + /** + * ProtoAtLeast reports whether the HTTP protocol used + * in the response is at least major.minor. + */ + protoAtLeast(major: number): boolean + } + interface Response { + /** + * Write writes r to w in the HTTP/1.x server response format, + * including the status line, headers, body, and optional trailer. + * + * This method consults the following fields of the response r: + * + * StatusCode + * ProtoMajor + * ProtoMinor + * Request.Method + * TransferEncoding + * Trailer + * Body + * ContentLength + * Header, values for non-canonical keys will have unpredictable behavior + * + * The Response Body is closed after it is sent. + */ + write(w: io.Writer): void + } + /** + * A Handler responds to an HTTP request. + * + * ServeHTTP should write reply headers and data to the ResponseWriter + * and then return. Returning signals that the request is finished; it + * is not valid to use the ResponseWriter or read from the + * Request.Body after or concurrently with the completion of the + * ServeHTTP call. + * + * Depending on the HTTP client software, HTTP protocol version, and + * any intermediaries between the client and the Go server, it may not + * be possible to read from the Request.Body after writing to the + * ResponseWriter. Cautious handlers should read the Request.Body + * first, and then reply. + * + * Except for reading the body, handlers should not modify the + * provided Request. + * + * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes + * that the effect of the panic was isolated to the active request. + * It recovers the panic, logs a stack trace to the server error log, + * and either closes the network connection or sends an HTTP/2 + * RST_STREAM, depending on the HTTP protocol. To abort a handler so + * the client sees an interrupted response but the server doesn't log + * an error, panic with the value ErrAbortHandler. + */ + interface Handler { + serveHTTP(_arg0: ResponseWriter, _arg1: Request): void + } + /** + * A ConnState represents the state of a client connection to a server. + * It's used by the optional Server.ConnState hook. + */ + interface ConnState extends Number{} + interface ConnState { + string(): string + } +} + +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 + } +} + +namespace mailer { + /** + * Mailer defines a base mail client interface. + */ + interface Mailer { + /** + * Send sends an email with the provided Message. + */ + send(message: Message): void + } +} + /** * Package driver defines interfaces to be implemented by database * drivers as used by package sql. @@ -11337,12 +13274,12 @@ namespace driver { * interface, or an instance of one of these types: * * ``` - * int64 - * float64 - * bool - * []byte - * string - * time.Time + * int64 + * float64 + * bool + * []byte + * string + * time.Time * ``` * * If the driver supports cursors, a returned Value may also implement the Rows interface @@ -11375,293 +13312,6 @@ namespace driver { } } -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * A URL represents a parsed URL (technically, a URI reference). - * - * The general form represented is: - * - * ``` - * [scheme:][//[userinfo@]host][/]path[?query][#fragment] - * ``` - * - * URLs that do not start with a slash after the scheme are interpreted as: - * - * ``` - * scheme:opaque[?query][#fragment] - * ``` - * - * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. - * A consequence is that it is impossible to tell which slashes in the Path were - * slashes in the raw URL and which were %2f. This distinction is rarely important, - * but when it is, the code should use RawPath, an optional field which only gets - * set if the default encoding is different from Path. - * - * URL's String method uses the EscapedPath method to obtain the path. See the - * EscapedPath method for more details. - */ - interface URL { - scheme: string - opaque: string // encoded opaque data - user?: Userinfo // username and password information - host: string // host or host:port - path: string // path (relative paths may omit leading slash) - rawPath: string // encoded path hint (see EscapedPath method) - omitHost: boolean // do not emit empty host (authority) - forceQuery: boolean // append a query ('?') even if RawQuery is empty - rawQuery: string // encoded query values, without '?' - fragment: string // fragment for references, without '#' - rawFragment: string // encoded fragment hint (see EscapedFragment method) - } - interface URL { - /** - * EscapedPath returns the escaped form of u.Path. - * In general there are multiple possible escaped forms of any path. - * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. - * Otherwise EscapedPath ignores u.RawPath and computes an escaped - * form on its own. - * The String and RequestURI methods use EscapedPath to construct - * their results. - * In general, code should call EscapedPath instead of - * reading u.RawPath directly. - */ - escapedPath(): string - } - interface URL { - /** - * EscapedFragment returns the escaped form of u.Fragment. - * In general there are multiple possible escaped forms of any fragment. - * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. - * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped - * form on its own. - * The String method uses EscapedFragment to construct its result. - * In general, code should call EscapedFragment instead of - * reading u.RawFragment directly. - */ - escapedFragment(): string - } - interface URL { - /** - * String reassembles the URL into a valid URL string. - * The general form of the result is one of: - * - * ``` - * scheme:opaque?query#fragment - * scheme://userinfo@host/path?query#fragment - * ``` - * - * If u.Opaque is non-empty, String uses the first form; - * otherwise it uses the second form. - * Any non-ASCII characters in host are escaped. - * To obtain the path, String uses u.EscapedPath(). - * - * In the second form, the following rules apply: - * ``` - * - if u.Scheme is empty, scheme: is omitted. - * - if u.User is nil, userinfo@ is omitted. - * - if u.Host is empty, host/ is omitted. - * - if u.Scheme and u.Host are empty and u.User is nil, - * the entire scheme://userinfo@host/ is omitted. - * - if u.Host is non-empty and u.Path begins with a /, - * the form host/path does not add its own /. - * - if u.RawQuery is empty, ?query is omitted. - * - if u.Fragment is empty, #fragment is omitted. - * ``` - */ - string(): string - } - interface URL { - /** - * Redacted is like String but replaces any password with "xxxxx". - * Only the password in u.URL is redacted. - */ - redacted(): string - } - /** - * Values maps a string key to a list of values. - * It is typically used for query parameters and form values. - * Unlike in the http.Header map, the keys in a Values map - * are case-sensitive. - */ - interface Values extends _TygojaDict{} - interface Values { - /** - * Get gets the first value associated with the given key. - * If there are no values associated with the key, Get returns - * the empty string. To access multiple values, use the map - * directly. - */ - get(key: string): string - } - interface Values { - /** - * Set sets the key to value. It replaces any existing - * values. - */ - set(key: string): void - } - interface Values { - /** - * Add adds the value to key. It appends to any existing - * values associated with key. - */ - add(key: string): void - } - interface Values { - /** - * Del deletes the values associated with key. - */ - del(key: string): void - } - interface Values { - /** - * Has checks whether a given key is set. - */ - has(key: string): boolean - } - interface Values { - /** - * Encode encodes the values into “URL encoded” form - * ("bar=baz&foo=quux") sorted by key. - */ - encode(): string - } - interface URL { - /** - * IsAbs reports whether the URL is absolute. - * Absolute means that it has a non-empty scheme. - */ - isAbs(): boolean - } - interface URL { - /** - * Parse parses a URL in the context of the receiver. The provided URL - * may be relative or absolute. Parse returns nil, err on parse - * failure, otherwise its return value is the same as ResolveReference. - */ - parse(ref: string): (URL | undefined) - } - interface URL { - /** - * ResolveReference resolves a URI reference to an absolute URI from - * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference - * may be relative or absolute. ResolveReference always returns a new - * URL instance, even if the returned URL is identical to either the - * base or reference. If ref is an absolute URL, then ResolveReference - * ignores base and returns a copy of ref. - */ - resolveReference(ref: URL): (URL | undefined) - } - interface URL { - /** - * Query parses RawQuery and returns the corresponding values. - * It silently discards malformed value pairs. - * To check errors use ParseQuery. - */ - query(): Values - } - interface URL { - /** - * RequestURI returns the encoded path?query or opaque?query - * string that would be used in an HTTP request for u. - */ - requestURI(): string - } - interface 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 - } - interface URL { - /** - * JoinPath returns a new URL with the provided path elements joined to - * any existing path and the resulting path cleaned of any ./ or ../ elements. - * Any sequences of multiple / characters will be reduced to a single /. - */ - joinPath(...elem: string[]): (URL | undefined) - } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * DateTime represents a [time.Time] instance in UTC that is wrapped - * and serialized using the app default date layout. - */ - interface DateTime { - } - interface DateTime { - /** - * Time returns the internal [time.Time] instance. - */ - time(): time.Time - } - interface DateTime { - /** - * IsZero checks whether the current DateTime instance has zero time value. - */ - isZero(): boolean - } - interface DateTime { - /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. - */ - string(): string - } - interface DateTime { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string - } - interface DateTime { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string): void - } - interface DateTime { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): driver.Value - } - interface DateTime { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. - */ - scan(value: any): void - } -} - /** * Package sql provides a generic interface around SQL (or SQL-like) * databases. @@ -11878,782 +13528,335 @@ namespace sql { } } -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * ConnectionState records basic TLS details about the connection. - */ - interface ConnectionState { - /** - * Version is the TLS version used by the connection (e.g. VersionTLS12). - */ - version: number - /** - * HandshakeComplete is true if the handshake has concluded. - */ - handshakeComplete: boolean - /** - * DidResume is true if this connection was successfully resumed from a - * previous session with a session ticket or similar mechanism. - */ - didResume: boolean - /** - * CipherSuite is the cipher suite negotiated for the connection (e.g. - * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). - */ - cipherSuite: number - /** - * NegotiatedProtocol is the application protocol negotiated with ALPN. - */ - negotiatedProtocol: string - /** - * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. - * - * Deprecated: this value is always true. - */ - negotiatedProtocolIsMutual: boolean - /** - * ServerName is the value of the Server Name Indication extension sent by - * the client. It's available both on the server and on the client side. - */ - serverName: string - /** - * PeerCertificates are the parsed certificates sent by the peer, in the - * order in which they were sent. The first element is the leaf certificate - * that the connection is verified against. - * - * On the client side, it can't be empty. On the server side, it can be - * empty if Config.ClientAuth is not RequireAnyClientCert or - * RequireAndVerifyClientCert. - */ - peerCertificates: Array<(x509.Certificate | undefined)> - /** - * VerifiedChains is a list of one or more chains where the first element is - * PeerCertificates[0] and the last element is from Config.RootCAs (on the - * client side) or Config.ClientCAs (on the server side). - * - * On the client side, it's set if Config.InsecureSkipVerify is false. On - * the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven - * (and the peer provided a certificate) or RequireAndVerifyClientCert. - */ - verifiedChains: Array> - /** - * SignedCertificateTimestamps is a list of SCTs provided by the peer - * through the TLS handshake for the leaf certificate, if any. - */ - signedCertificateTimestamps: Array - /** - * OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) - * response provided by the peer for the leaf certificate, if any. - */ - ocspResponse: string - /** - * TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, - * Section 3). This value will be nil for TLS 1.3 connections and for all - * resumed connections. - * - * Deprecated: there are conditions in which this value might not be unique - * to a connection. See the Security Considerations sections of RFC 5705 and - * RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings. - */ - tlsUnique: string - } - interface ConnectionState { - /** - * ExportKeyingMaterial returns length bytes of exported key material in a new - * slice as defined in RFC 5705. If context is nil, it is not used as part of - * the seed. If the connection was set to allow renegotiation via - * Config.Renegotiation, this function will return an error. - */ - exportKeyingMaterial(label: string, context: string, length: number): string +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => 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. + * Package types implements some commonly used db serializable types + * like datetime, json, etc. */ -namespace multipart { - interface Reader { - /** - * ReadForm parses an entire multipart message whose parts have - * a Content-Disposition of "form-data". - * It stores up to maxMemory bytes + 10MB (reserved for non-file parts) - * in memory. File parts which can't be stored in memory will be stored on - * disk in temporary files. - * It returns ErrMessageTooLarge if all non-file parts can't be stored in - * memory. - */ - readForm(maxMemory: number): (Form | undefined) - } +namespace types { /** - * Form is a parsed multipart form. - * Its File parts are stored either in memory or on disk, - * and are accessible via the *FileHeader's Open method. - * Its Value parts are stored as strings. - * Both are keyed by field name. + * DateTime represents a [time.Time] instance in UTC that is wrapped + * and serialized using the app default date layout. */ - interface Form { - value: _TygojaDict - file: _TygojaDict + interface DateTime { } - interface Form { + interface DateTime { /** - * RemoveAll removes any temporary files associated with a Form. + * Time returns the internal [time.Time] instance. */ - removeAll(): void + time(): time.Time } - /** - * File is an interface to access the file part of a multipart message. - * Its contents may be either stored in memory or on disk. - * If stored on disk, the File's underlying concrete type will be an *os.File. - */ - interface File { + interface DateTime { + /** + * IsZero checks whether the current DateTime instance has zero time value. + */ + isZero(): boolean } - /** - * Reader is an iterator over parts in a MIME multipart body. - * Reader's underlying parser consumes its input as needed. Seeking - * isn't supported. - */ - interface Reader { - } - interface Reader { + interface DateTime { /** - * NextPart returns the next part in the multipart or an error. - * When there are no more parts, the error io.EOF is returned. + * String serializes the current DateTime instance into a formatted + * UTC date string. * - * As a special case, if the "Content-Transfer-Encoding" header - * has a value of "quoted-printable", that header is instead - * hidden and the body is transparently decoded during Read calls. - */ - nextPart(): (Part | undefined) - } - interface Reader { - /** - * NextRawPart returns the next part in the multipart or an error. - * When there are no more parts, the error io.EOF is returned. - * - * Unlike NextPart, it does not have special handling for - * "Content-Transfer-Encoding: quoted-printable". - */ - nextRawPart(): (Part | undefined) - } -} - -/** - * 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 { - /** - * A Client is an HTTP client. Its zero value (DefaultClient) is a - * usable client that uses DefaultTransport. - * - * The Client's Transport typically has internal state (cached TCP - * connections), so Clients should be reused instead of created as - * needed. Clients are safe for concurrent use by multiple goroutines. - * - * A Client is higher-level than a RoundTripper (such as Transport) - * and additionally handles HTTP details such as cookies and - * redirects. - * - * When following redirects, the Client will forward all headers set on the - * initial Request except: - * - * • when forwarding sensitive headers like "Authorization", - * "WWW-Authenticate", and "Cookie" to untrusted targets. - * These headers will be ignored when following a redirect to a domain - * that is not a subdomain match or exact match of the initial domain. - * For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" - * will forward the sensitive headers, but a redirect to "bar.com" will not. - * - * • when forwarding the "Cookie" header with a non-nil cookie Jar. - * Since each redirect may mutate the state of the cookie jar, - * a redirect may possibly alter a cookie set in the initial request. - * When forwarding the "Cookie" header, any mutated cookies will be omitted, - * with the expectation that the Jar will insert those mutated cookies - * with the updated values (assuming the origin matches). - * If Jar is nil, the initial cookies are forwarded without change. - */ - interface Client { - /** - * Transport specifies the mechanism by which individual - * HTTP requests are made. - * If nil, DefaultTransport is used. - */ - transport: RoundTripper - /** - * CheckRedirect specifies the policy for handling redirects. - * If CheckRedirect is not nil, the client calls it before - * following an HTTP redirect. The arguments req and via are - * the upcoming request and the requests made already, oldest - * first. If CheckRedirect returns an error, the Client's Get - * method returns both the previous Response (with its Body - * closed) and CheckRedirect's error (wrapped in a url.Error) - * instead of issuing the Request req. - * As a special case, if CheckRedirect returns ErrUseLastResponse, - * then the most recent response is returned with its body - * unclosed, along with a nil error. - * - * If CheckRedirect is nil, the Client uses its default policy, - * which is to stop after 10 consecutive requests. - */ - checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void - /** - * Jar specifies the cookie jar. - * - * The Jar is used to insert relevant cookies into every - * outbound Request and is updated with the cookie values - * of every inbound Response. The Jar is consulted for every - * redirect that the Client follows. - * - * If Jar is nil, cookies are only sent if they are explicitly - * set on the Request. - */ - jar: CookieJar - /** - * Timeout specifies a time limit for requests made by this - * Client. The timeout includes connection time, any - * redirects, and reading the response body. The timer remains - * running after Get, Head, Post, or Do return and will - * interrupt reading of the Response.Body. - * - * A Timeout of zero means no timeout. - * - * The Client cancels requests to the underlying Transport - * as if the Request's Context ended. - * - * For compatibility, the Client will also use the deprecated - * CancelRequest method on Transport if found. New - * RoundTripper implementations should use the Request's Context - * for cancellation instead of implementing CancelRequest. - */ - timeout: time.Duration - } - interface Client { - /** - * Get issues a GET to the specified URL. If the response is one of the - * following redirect codes, Get follows the redirect after calling the - * Client's CheckRedirect function: - * - * ``` - * 301 (Moved Permanently) - * 302 (Found) - * 303 (See Other) - * 307 (Temporary Redirect) - * 308 (Permanent Redirect) - * ``` - * - * An error is returned if the Client's CheckRedirect function fails - * or if there was an HTTP protocol error. A non-2xx response doesn't - * cause an error. Any returned error will be of type *url.Error. The - * url.Error value's Timeout method will report true if the request - * timed out. - * - * When err is nil, resp always contains a non-nil resp.Body. - * Caller should close resp.Body when done reading from it. - * - * To make a request with custom headers, use NewRequest and Client.Do. - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. - */ - get(url: string): (Response | undefined) - } - interface Client { - /** - * Do sends an HTTP request and returns an HTTP response, following - * policy (such as redirects, cookies, auth) as configured on the - * client. - * - * An error is returned if caused by client policy (such as - * CheckRedirect), or failure to speak HTTP (such as a network - * connectivity problem). A non-2xx status code doesn't cause an - * error. - * - * If the returned error is nil, the Response will contain a non-nil - * Body which the user is expected to close. If the Body is not both - * read to EOF and closed, the Client's underlying RoundTripper - * (typically Transport) may not be able to re-use a persistent TCP - * connection to the server for a subsequent "keep-alive" request. - * - * The request Body, if non-nil, will be closed by the underlying - * Transport, even on errors. - * - * On error, any Response can be ignored. A non-nil Response with a - * non-nil error only occurs when CheckRedirect fails, and even then - * the returned Response.Body is already closed. - * - * Generally Get, Post, or PostForm will be used instead of Do. - * - * If the server replies with a redirect, the Client first uses the - * CheckRedirect function to determine whether the redirect should be - * followed. If permitted, a 301, 302, or 303 redirect causes - * subsequent requests to use HTTP method GET - * (or HEAD if the original request was HEAD), with no body. - * A 307 or 308 redirect preserves the original HTTP method and body, - * provided that the Request.GetBody function is defined. - * The NewRequest function automatically sets GetBody for common - * standard library body types. - * - * Any returned error will be of type *url.Error. The url.Error - * value's Timeout method will report true if the request timed out. - */ - do(req: Request): (Response | undefined) - } - interface Client { - /** - * Post issues a POST to the specified URL. - * - * Caller should close resp.Body when done reading from it. - * - * If the provided body is an io.Closer, it is closed after the - * request. - * - * To set custom headers, use NewRequest and Client.Do. - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. - * - * See the Client.Do method documentation for details on how redirects - * are handled. - */ - post(url: string, body: io.Reader): (Response | undefined) - } - interface Client { - /** - * PostForm issues a POST to the specified URL, - * with data's keys and values URL-encoded as the request body. - * - * The Content-Type header is set to application/x-www-form-urlencoded. - * To set other headers, use NewRequest and Client.Do. - * - * When err is nil, resp always contains a non-nil resp.Body. - * Caller should close resp.Body when done reading from it. - * - * See the Client.Do method documentation for details on how redirects - * are handled. - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. - */ - postForm(url: string, data: url.Values): (Response | undefined) - } - interface Client { - /** - * Head issues a HEAD to the specified URL. If the response is one of the - * following redirect codes, Head follows the redirect after calling the - * Client's CheckRedirect function: - * - * ``` - * 301 (Moved Permanently) - * 302 (Found) - * 303 (See Other) - * 307 (Temporary Redirect) - * 308 (Permanent Redirect) - * ``` - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. - */ - head(url: string): (Response | undefined) - } - interface Client { - /** - * CloseIdleConnections closes any connections on its Transport which - * were previously connected from previous requests but are now - * sitting idle in a "keep-alive" state. It does not interrupt any - * connections currently in use. - * - * If the Client's Transport does not have a CloseIdleConnections method - * then this method does nothing. - */ - closeIdleConnections(): void - } - /** - * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an - * HTTP response or the Cookie header of an HTTP request. - * - * See https://tools.ietf.org/html/rfc6265 for details. - */ - interface Cookie { - name: string - value: string - path: string // optional - domain: string // optional - expires: time.Time // optional - rawExpires: string // for reading cookies only - /** - * MaxAge=0 means no 'Max-Age' attribute specified. - * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' - * MaxAge>0 means Max-Age attribute present and given in seconds - */ - maxAge: number - secure: boolean - httpOnly: boolean - sameSite: SameSite - raw: string - unparsed: Array // Raw text of unparsed attribute-value pairs - } - interface Cookie { - /** - * String returns the serialization of the cookie for use in a Cookie - * header (if only Name and Value are set) or a Set-Cookie response - * header (if other fields are set). - * If c is nil or c.Name is invalid, the empty string is returned. + * The zero value is serialized to an empty string. */ string(): string } - interface Cookie { + interface DateTime { /** - * Valid reports whether the cookie is valid. + * MarshalJSON implements the [json.Marshaler] interface. */ - valid(): void + marshalJSON(): string + } + interface DateTime { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string): void + } + interface DateTime { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value + } + interface DateTime { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. + */ + scan(value: any): void + } +} + +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation + /** + * SchemaField defines a single schema field structure. + */ + interface SchemaField { + system: boolean + id: string + name: string + type: string + required: boolean + /** + * Deprecated: This field is no-op and will be removed in future versions. + * Please use the collection.Indexes field to define a unique constraint. + */ + unique: boolean + options: any + } + interface SchemaField { + /** + * ColDefinition returns the field db column type definition as string. + */ + colDefinition(): string + } + interface SchemaField { + /** + * String serializes and returns the current field as string. + */ + string(): string + } + interface SchemaField { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface SchemaField { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * The schema field options are auto initialized on success. + */ + unmarshalJSON(data: string): void + } + interface SchemaField { + /** + * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface SchemaField { + /** + * InitOptions initializes the current field options based on its type. + * + * Returns error on unknown field type. + */ + initOptions(): void + } + interface SchemaField { + /** + * PrepareValue returns normalized and properly formatted field value. + */ + prepareValue(value: any): any + } + interface SchemaField { + /** + * PrepareValueWithModifier returns normalized and properly formatted field value + * by "merging" baseValue with the modifierValue based on the specified modifier (+ or -). + */ + prepareValueWithModifier(baseValue: any, modifier: string, modifierValue: any): any + } +} + +/** + * Package models implements all PocketBase DB models and DTOs. + */ +namespace models { + /** + * Model defines an interface with common methods that all db models should have. + */ + interface Model { + tableName(): string + isNew(): boolean + markAsNew(): void + markAsNotNew(): void + hasId(): boolean + getId(): string + setId(id: string): void + getCreated(): types.DateTime + getUpdated(): types.DateTime + refreshId(): void + refreshCreated(): void + refreshUpdated(): void + } + /** + * BaseModel defines common fields and methods used by all other models. + */ + interface BaseModel { + id: string + created: types.DateTime + updated: types.DateTime + } + interface BaseModel { + /** + * HasId returns whether the model has a nonzero id. + */ + hasId(): boolean + } + interface BaseModel { + /** + * GetId returns the model id. + */ + getId(): string + } + interface BaseModel { + /** + * SetId sets the model id to the provided string value. + */ + setId(id: string): void + } + interface BaseModel { + /** + * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). + */ + markAsNew(): void + } + interface BaseModel { + /** + * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) + */ + markAsNotNew(): void + } + interface BaseModel { + /** + * IsNew indicates what type of db query (insert or update) + * should be used with the model instance. + */ + isNew(): boolean + } + interface BaseModel { + /** + * GetCreated returns the model Created datetime. + */ + getCreated(): types.DateTime + } + interface BaseModel { + /** + * GetUpdated returns the model Updated datetime. + */ + getUpdated(): types.DateTime + } + interface BaseModel { + /** + * RefreshId generates and sets a new model id. + * + * The generated id is a cryptographically random 15 characters length string. + */ + refreshId(): void + } + interface BaseModel { + /** + * RefreshCreated updates the model Created field with the current datetime. + */ + refreshCreated(): void + } + interface BaseModel { + /** + * RefreshUpdated updates the model Updated field with the current datetime. + */ + refreshUpdated(): void + } + interface BaseModel { + /** + * PostScan implements the [dbx.PostScanner] interface. + * + * It is executed right after the model was populated with the db row values. + */ + postScan(): void } // @ts-ignore - import mathrand = rand + import validation = ozzo_validation /** - * A Header represents the key-value pairs in an HTTP header. - * - * The keys should be in canonical form, as returned by - * CanonicalHeaderKey. + * CollectionBaseOptions defines the "base" Collection.Options fields. */ - interface Header extends _TygojaDict{} - interface Header { - /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. - * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. - */ - add(key: string): void + interface CollectionBaseOptions { } - interface Header { + interface CollectionBaseOptions { /** - * Set sets the header entries associated with key to the - * single element value. It replaces any existing values - * associated with key. The key is case insensitive; it is - * canonicalized by textproto.CanonicalMIMEHeaderKey. - * To use non-canonical keys, assign to the map directly. + * Validate implements [validation.Validatable] interface. */ - set(key: string): void + validate(): void } - interface Header { - /** - * Get gets the first value associated with the given key. If - * there are no values associated with the key, Get returns "". - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. Get assumes that all - * keys are stored in canonical form. To use non-canonical keys, - * access the map directly. - */ - get(key: string): string - } - interface Header { - /** - * Values returns all values associated with the given key. - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. To use non-canonical - * keys, access the map directly. - * The returned slice is not a copy. - */ - values(key: string): Array - } - interface Header { - /** - * Del deletes the values associated with key. - * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. - */ - del(key: string): void - } - interface Header { - /** - * Write writes a header in wire format. - */ - write(w: io.Writer): void - } - interface Header { - /** - * Clone returns a copy of h or nil if h is nil. - */ - clone(): Header - } - interface Header { - /** - * WriteSubset writes a header in wire format. - * If exclude is not nil, keys where exclude[key] == true are not written. - * Keys are not canonicalized before checking the exclude map. - */ - writeSubset(w: io.Writer, exclude: _TygojaDict): void - } - // @ts-ignore - import urlpkg = url /** - * Response represents the response from an HTTP request. - * - * The Client and Transport return Responses from servers once - * the response headers have been received. The response body - * is streamed on demand as the Body field is read. + * CollectionAuthOptions defines the "auth" Collection.Options fields. */ - interface Response { - status: string // e.g. "200 OK" - statusCode: number // e.g. 200 - proto: string // e.g. "HTTP/1.0" - protoMajor: number // e.g. 1 - protoMinor: number // e.g. 0 - /** - * Header maps header keys to values. If the response had multiple - * headers with the same key, they may be concatenated, with comma - * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers - * be semantically equivalent to a comma-delimited sequence.) When - * Header values are duplicated by other fields in this struct (e.g., - * ContentLength, TransferEncoding, Trailer), the field values are - * authoritative. - * - * Keys in the map are canonicalized (see CanonicalHeaderKey). - */ - header: Header - /** - * Body represents the response body. - * - * The response body is streamed on demand as the Body field - * is read. If the network connection fails or the server - * terminates the response, Body.Read calls return an error. - * - * The http Client and Transport guarantee that Body is always - * non-nil, even on responses without a body or responses with - * a zero-length body. It is the caller's responsibility to - * close Body. The default HTTP client's Transport may not - * reuse HTTP/1.x "keep-alive" TCP connections if the Body is - * not read to completion and closed. - * - * The Body is automatically dechunked if the server replied - * with a "chunked" Transfer-Encoding. - * - * As of Go 1.12, the Body will also implement io.Writer - * on a successful "101 Switching Protocols" response, - * as used by WebSockets and HTTP/2's "h2c" mode. - */ - body: io.ReadCloser - /** - * ContentLength records the length of the associated content. The - * value -1 indicates that the length is unknown. Unless Request.Method - * is "HEAD", values >= 0 indicate that the given number of bytes may - * be read from Body. - */ - contentLength: number - /** - * Contains transfer encodings from outer-most to inner-most. Value is - * nil, means that "identity" encoding is used. - */ - transferEncoding: Array - /** - * Close records whether the header directed that the connection be - * closed after reading Body. The value is advice for clients: neither - * ReadResponse nor Response.Write ever closes a connection. - */ - close: boolean - /** - * Uncompressed reports whether the response was sent compressed but - * was decompressed by the http package. When true, reading from - * Body yields the uncompressed content instead of the compressed - * content actually set from the server, ContentLength is set to -1, - * and the "Content-Length" and "Content-Encoding" fields are deleted - * from the responseHeader. To get the original response from - * the server, set Transport.DisableCompression to true. - */ - uncompressed: boolean - /** - * Trailer maps trailer keys to values in the same - * format as Header. - * - * The Trailer initially contains only nil values, one for - * each key specified in the server's "Trailer" header - * value. Those values are not added to Header. - * - * Trailer must not be accessed concurrently with Read calls - * on the Body. - * - * After Body.Read has returned io.EOF, Trailer will contain - * any trailer values sent by the server. - */ - trailer: Header - /** - * Request is the request that was sent to obtain this Response. - * Request's Body is nil (having already been consumed). - * This is only populated for Client requests. - */ - request?: Request - /** - * TLS contains information about the TLS connection on which the - * response was received. It is nil for unencrypted responses. - * The pointer is shared between responses and should not be - * modified. - */ - tls?: tls.ConnectionState + interface CollectionAuthOptions { + manageRule?: string + allowOAuth2Auth: boolean + allowUsernameAuth: boolean + allowEmailAuth: boolean + requireEmail: boolean + exceptEmailDomains: Array + onlyEmailDomains: Array + minPasswordLength: number } - interface Response { + interface CollectionAuthOptions { /** - * Cookies parses and returns the cookies set in the Set-Cookie headers. + * Validate implements [validation.Validatable] interface. */ - cookies(): Array<(Cookie | undefined)> + validate(): void } - interface Response { - /** - * Location returns the URL of the response's "Location" header, - * if present. Relative redirects are resolved relative to - * the Response's Request. ErrNoLocation is returned if no - * Location header is present. - */ - location(): (url.URL | undefined) + /** + * CollectionViewOptions defines the "view" Collection.Options fields. + */ + interface CollectionViewOptions { + query: string } - interface Response { + interface CollectionViewOptions { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the response is at least major.minor. + * Validate implements [validation.Validatable] interface. */ - protoAtLeast(major: number): boolean + validate(): void } - interface Response { + type _subGRUuB = BaseModel + interface Param extends _subGRUuB { + key: string + value: types.JsonRaw + } + interface Param { + tableName(): string + } + type _subJDmVe = BaseModel + interface Request extends _subJDmVe { + url: string + method: string + status: number + auth: string + userIp: string + remoteIp: string + referer: string + userAgent: string + meta: types.JsonMap + } + interface Request { + tableName(): string + } + interface TableInfoRow { /** - * Write writes r to w in the HTTP/1.x server response format, - * including the status line, headers, body, and optional trailer. - * - * This method consults the following fields of the response r: - * - * ``` - * StatusCode - * ProtoMajor - * ProtoMinor - * Request.Method - * TransferEncoding - * Trailer - * Body - * ContentLength - * Header, values for non-canonical keys will have unpredictable behavior - * ``` - * - * The Response Body is closed after it is sent. + * the `db:"pk"` tag has special semantic so we cannot rename + * the original field without specifying a custom mapper */ - write(w: io.Writer): void + pk: number + index: number + name: string + type: string + notNull: boolean + defaultValue: types.JsonRaw } } @@ -13095,342 +14298,6 @@ namespace echo { } } -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 schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * SchemaField defines a single schema field structure. - */ - interface SchemaField { - system: boolean - id: string - name: string - type: string - required: boolean - /** - * Deprecated: This field is no-op and will be removed in future versions. - * Please use the collection.Indexes field to define a unique constraint. - */ - unique: boolean - options: any - } - interface SchemaField { - /** - * ColDefinition returns the field db column type definition as string. - */ - colDefinition(): string - } - interface SchemaField { - /** - * String serializes and returns the current field as string. - */ - string(): string - } - interface SchemaField { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string - } - interface SchemaField { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * The schema field options are auto initialized on success. - */ - unmarshalJSON(data: string): void - } - interface SchemaField { - /** - * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface SchemaField { - /** - * InitOptions initializes the current field options based on its type. - * - * Returns error on unknown field type. - */ - initOptions(): void - } - interface SchemaField { - /** - * PrepareValue returns normalized and properly formatted field value. - */ - prepareValue(value: any): any - } - interface SchemaField { - /** - * PrepareValueWithModifier returns normalized and properly formatted field value - * by "merging" baseValue with the modifierValue based on the specified modifier (+ or -). - */ - prepareValueWithModifier(baseValue: any, modifier: string, modifierValue: any): any - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - /** - * Model defines an interface with common methods that all db models should have. - */ - interface Model { - tableName(): string - isNew(): boolean - markAsNew(): void - markAsNotNew(): void - hasId(): boolean - getId(): string - setId(id: string): void - getCreated(): types.DateTime - getUpdated(): types.DateTime - refreshId(): void - refreshCreated(): void - refreshUpdated(): void - } - /** - * BaseModel defines common fields and methods used by all other models. - */ - interface BaseModel { - id: string - created: types.DateTime - updated: types.DateTime - } - interface BaseModel { - /** - * HasId returns whether the model has a nonzero id. - */ - hasId(): boolean - } - interface BaseModel { - /** - * GetId returns the model id. - */ - getId(): string - } - interface BaseModel { - /** - * SetId sets the model id to the provided string value. - */ - setId(id: string): void - } - interface BaseModel { - /** - * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). - */ - markAsNew(): void - } - interface BaseModel { - /** - * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) - */ - markAsNotNew(): void - } - interface BaseModel { - /** - * IsNew indicates what type of db query (insert or update) - * should be used with the model instance. - */ - isNew(): boolean - } - interface BaseModel { - /** - * GetCreated returns the model Created datetime. - */ - getCreated(): types.DateTime - } - interface BaseModel { - /** - * GetUpdated returns the model Updated datetime. - */ - getUpdated(): types.DateTime - } - interface BaseModel { - /** - * RefreshId generates and sets a new model id. - * - * The generated id is a cryptographically random 15 characters length string. - */ - refreshId(): void - } - interface BaseModel { - /** - * RefreshCreated updates the model Created field with the current datetime. - */ - refreshCreated(): void - } - interface BaseModel { - /** - * RefreshUpdated updates the model Updated field with the current datetime. - */ - refreshUpdated(): void - } - interface BaseModel { - /** - * PostScan implements the [dbx.PostScanner] interface. - * - * It is executed right after the model was populated with the db row values. - */ - postScan(): void - } - // @ts-ignore - import validation = ozzo_validation - /** - * CollectionBaseOptions defines the "base" Collection.Options fields. - */ - interface CollectionBaseOptions { - } - interface CollectionBaseOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - /** - * CollectionAuthOptions defines the "auth" Collection.Options fields. - */ - interface CollectionAuthOptions { - manageRule?: string - allowOAuth2Auth: boolean - allowUsernameAuth: boolean - allowEmailAuth: boolean - requireEmail: boolean - exceptEmailDomains: Array - onlyEmailDomains: Array - minPasswordLength: number - } - interface CollectionAuthOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - /** - * CollectionViewOptions defines the "view" Collection.Options fields. - */ - interface CollectionViewOptions { - query: string - } - interface CollectionViewOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - type _subNDnei = BaseModel - interface Param extends _subNDnei { - key: string - value: types.JsonRaw - } - interface Param { - tableName(): string - } - type _subcyHsJ = BaseModel - interface Request extends _subcyHsJ { - url: string - method: string - status: number - auth: string - userIp: string - remoteIp: string - referer: string - userAgent: string - meta: types.JsonMap - } - interface Request { - tableName(): string - } - interface TableInfoRow { - /** - * the `db:"pk"` tag has special semantic so we cannot rename - * the original field without specifying a custom mapper - */ - pk: number - index: number - name: string - type: string - notNull: boolean - defaultValue: types.JsonRaw - } -} - /** * Package oauth2 provides support for making * OAuth2 authorized and authenticated HTTP requests, @@ -13520,18 +14387,6 @@ namespace oauth2 { } } -namespace mailer { - /** - * Mailer defines a base mail client interface. - */ - interface Mailer { - /** - * Send sends an email with the provided Message. - */ - send(message: Message): void - } -} - namespace settings { // @ts-ignore import validation = ozzo_validation @@ -13714,14 +14569,12 @@ namespace hook { } interface Hook { /** - * @todo add also to TaggedHook * Remove removes a single hook handler by its id. */ remove(id: string): void } interface Hook { /** - * @todo add also to TaggedHook * RemoveAll removes all registered handlers. */ removeAll(): void @@ -13744,8 +14597,8 @@ namespace hook { * 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 _subHkiap = mainHook - interface TaggedHook extends _subHkiap { + type _subGNDdN = mainHook + interface TaggedHook extends _subGNDdN { } interface TaggedHook { /** @@ -13831,12 +14684,12 @@ namespace core { httpContext: echo.Context error: Error } - type _subjAEWn = BaseModelEvent - interface ModelEvent extends _subjAEWn { + type _subXskBJ = BaseModelEvent + interface ModelEvent extends _subXskBJ { dao?: daos.Dao } - type _subufDOF = BaseCollectionEvent - interface MailerRecordEvent extends _subufDOF { + type _subYlIos = BaseCollectionEvent + interface MailerRecordEvent extends _subYlIos { mailClient: mailer.Mailer message?: mailer.Message record?: models.Record @@ -13875,50 +14728,50 @@ namespace core { oldSettings?: settings.Settings newSettings?: settings.Settings } - type _submvluG = BaseCollectionEvent - interface RecordsListEvent extends _submvluG { + type _subUASMa = BaseCollectionEvent + interface RecordsListEvent extends _subUASMa { httpContext: echo.Context records: Array<(models.Record | undefined)> result?: search.Result } - type _subxveXr = BaseCollectionEvent - interface RecordViewEvent extends _subxveXr { + type _subQLlti = BaseCollectionEvent + interface RecordViewEvent extends _subQLlti { httpContext: echo.Context record?: models.Record } - type _subeiYdM = BaseCollectionEvent - interface RecordCreateEvent extends _subeiYdM { + type _subafMcU = BaseCollectionEvent + interface RecordCreateEvent extends _subafMcU { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subwBStl = BaseCollectionEvent - interface RecordUpdateEvent extends _subwBStl { + type _subAbvxm = BaseCollectionEvent + interface RecordUpdateEvent extends _subAbvxm { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subuERET = BaseCollectionEvent - interface RecordDeleteEvent extends _subuERET { + type _subezArM = BaseCollectionEvent + interface RecordDeleteEvent extends _subezArM { httpContext: echo.Context record?: models.Record } - type _subsArqi = BaseCollectionEvent - interface RecordAuthEvent extends _subsArqi { + type _subDAzkU = BaseCollectionEvent + interface RecordAuthEvent extends _subDAzkU { httpContext: echo.Context record?: models.Record token: string meta: any } - type _subpoLXf = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subpoLXf { + type _subpNCMb = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subpNCMb { httpContext: echo.Context record?: models.Record identity: string password: string } - type _subkCwTk = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subkCwTk { + type _subPFzCX = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subPFzCX { httpContext: echo.Context providerName: string providerClient: auth.Provider @@ -13926,49 +14779,49 @@ namespace core { oAuth2User?: auth.AuthUser isNewRecord: boolean } - type _subpMNVV = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subpMNVV { + type _subuVcEL = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subuVcEL { httpContext: echo.Context record?: models.Record } - type _subuvAdi = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subuvAdi { + type _subVNzno = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subVNzno { httpContext: echo.Context record?: models.Record } - type _subqBCXB = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subqBCXB { + type _sublpewg = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _sublpewg { httpContext: echo.Context record?: models.Record } - type _subdiAUX = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subdiAUX { + type _subdnBpr = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subdnBpr { httpContext: echo.Context record?: models.Record } - type _subWnwvZ = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subWnwvZ { + type _subfIECD = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subfIECD { httpContext: echo.Context record?: models.Record } - type _subIZCPR = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subIZCPR { + type _subtMMey = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subtMMey { httpContext: echo.Context record?: models.Record } - type _subIFlNc = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subIFlNc { + type _subWZErX = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subWZErX { httpContext: echo.Context record?: models.Record } - type _subUOniq = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subUOniq { + type _subQTWxd = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subQTWxd { httpContext: echo.Context record?: models.Record externalAuths: Array<(models.ExternalAuth | undefined)> } - type _subVdsut = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subVdsut { + type _subYKXBw = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subYKXBw { httpContext: echo.Context record?: models.Record externalAuth?: models.ExternalAuth @@ -14022,33 +14875,33 @@ namespace core { collections: Array<(models.Collection | undefined)> result?: search.Result } - type _subEFFpI = BaseCollectionEvent - interface CollectionViewEvent extends _subEFFpI { + type _subSEtSL = BaseCollectionEvent + interface CollectionViewEvent extends _subSEtSL { httpContext: echo.Context } - type _subuIxsH = BaseCollectionEvent - interface CollectionCreateEvent extends _subuIxsH { + type _subBEbOd = BaseCollectionEvent + interface CollectionCreateEvent extends _subBEbOd { httpContext: echo.Context } - type _subBiKuQ = BaseCollectionEvent - interface CollectionUpdateEvent extends _subBiKuQ { + type _subgybca = BaseCollectionEvent + interface CollectionUpdateEvent extends _subgybca { httpContext: echo.Context } - type _subTONlV = BaseCollectionEvent - interface CollectionDeleteEvent extends _subTONlV { + type _subzLgCr = BaseCollectionEvent + interface CollectionDeleteEvent extends _subzLgCr { httpContext: echo.Context } interface CollectionsImportEvent { httpContext: echo.Context collections: Array<(models.Collection | undefined)> } - type _subKUlLM = BaseModelEvent - interface FileTokenEvent extends _subKUlLM { + type _subGsarQ = BaseModelEvent + interface FileTokenEvent extends _subGsarQ { httpContext: echo.Context token: string } - type _subNKYxw = BaseCollectionEvent - interface FileDownloadEvent extends _subNKYxw { + type _subhNSaq = BaseCollectionEvent + interface FileDownloadEvent extends _subhNSaq { httpContext: echo.Context record?: models.Record fileField?: schema.SchemaField @@ -15665,133 +16518,6 @@ namespace cobra { } } -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void - } -} - -namespace store { -} - -/** - * Package time provides functionality for measuring and displaying time. - * - * The calendrical calculations always assume a Gregorian calendar, with - * no leap seconds. - * - * # Monotonic Clocks - * - * Operating systems provide both a “wall clock,” which is subject to - * changes for clock synchronization, and a “monotonic clock,” which is - * not. The general rule is that the wall clock is for telling time and - * the monotonic clock is for measuring time. Rather than split the API, - * in this package the Time returned by time.Now contains both a wall - * clock reading and a monotonic clock reading; later time-telling - * operations use the wall clock reading, but later time-measuring - * operations, specifically comparisons and subtractions, use the - * monotonic clock reading. - * - * For example, this code always computes a positive elapsed time of - * approximately 20 milliseconds, even if the wall clock is changed during - * the operation being timed: - * - * ``` - * start := time.Now() - * ... operation that takes 20 milliseconds ... - * t := time.Now() - * elapsed := t.Sub(start) - * ``` - * - * Other idioms, such as time.Since(start), time.Until(deadline), and - * time.Now().Before(deadline), are similarly robust against wall clock - * resets. - * - * The rest of this section gives the precise details of how operations - * use monotonic clocks, but understanding those details is not required - * to use this package. - * - * The Time returned by time.Now contains a monotonic clock reading. - * If Time t has a monotonic clock reading, t.Add adds the same duration to - * both the wall clock and monotonic clock readings to compute the result. - * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time - * computations, they always strip any monotonic clock reading from their results. - * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation - * of the wall time, they also strip any monotonic clock reading from their results. - * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). - * - * If Times t and u both contain monotonic clock readings, the operations - * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out - * using the monotonic clock readings alone, ignoring the wall clock - * readings. If either t or u contains no monotonic clock reading, these - * operations fall back to using the wall clock readings. - * - * On some systems the monotonic clock will stop if the computer goes to sleep. - * On such a system, t.Sub(u) may not accurately reflect the actual - * time that passed between t and u. - * - * Because the monotonic clock reading has no meaning outside - * the current process, the serialized forms generated by t.GobEncode, - * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic - * clock reading, and t.Format provides no format for it. Similarly, the - * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, - * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. - * t.UnmarshalJSON, and t.UnmarshalText always create times with - * no monotonic clock reading. - * - * The monotonic clock reading exists only in Time values. It is not - * a part of Duration values or the Unix times returned by t.Unix and - * friends. - * - * Note that the Go == operator compares not just the time instant but - * also the Location and the monotonic clock reading. See the - * documentation for the Time type for a discussion of equality - * testing for Time values. - * - * For debugging, the result of t.String does include the monotonic - * clock reading if present. If t != u because of different monotonic clock readings, - * that difference will be visible when printing t.String() and u.String(). - */ -namespace time { - /** - * A Month specifies a month of the year (January = 1, ...). - */ - interface Month extends Number{} - interface Month { - /** - * String returns the English name of the month ("January", "February", ...). - */ - string(): string - } - /** - * A Weekday specifies a day of the week (Sunday = 0, ...). - */ - interface Weekday extends Number{} - interface Weekday { - /** - * String returns the English name of the day ("Sunday", "Monday", ...). - */ - string(): string - } - /** - * A Location maps time instants to the zone in use at that time. - * Typically, the Location represents the collection of time offsets - * in use in a geographical area. For many Locations the time offset varies - * depending on whether daylight savings time is in use at the time instant. - */ - interface Location { - } - interface Location { - /** - * String returns a descriptive name for the time zone information, - * corresponding to the name argument to LoadLocation or FixedZone. - */ - string(): string - } -} - /** * Package reflect implements run-time reflection, allowing a program to * manipulate objects with arbitrary types. The typical use is to take a value @@ -15858,9 +16584,7 @@ namespace reflect { /** * NumMethod returns the number of methods accessible using Method. * - * For a non-interface type, it returns the number of exported methods. - * - * For an interface type, it returns the number of exported and unexported methods. + * Note that NumMethod counts unexported methods only for interface types. */ numMethod(): number /** @@ -16021,6 +16745,118 @@ namespace reflect { } } +/** + * Package time provides functionality for measuring and displaying time. + * + * The calendrical calculations always assume a Gregorian calendar, with + * no leap seconds. + * + * Monotonic Clocks + * + * Operating systems provide both a “wall clock,” which is subject to + * changes for clock synchronization, and a “monotonic clock,” which is + * not. The general rule is that the wall clock is for telling time and + * the monotonic clock is for measuring time. Rather than split the API, + * in this package the Time returned by time.Now contains both a wall + * clock reading and a monotonic clock reading; later time-telling + * operations use the wall clock reading, but later time-measuring + * operations, specifically comparisons and subtractions, use the + * monotonic clock reading. + * + * For example, this code always computes a positive elapsed time of + * approximately 20 milliseconds, even if the wall clock is changed during + * the operation being timed: + * + * ``` + * start := time.Now() + * ... operation that takes 20 milliseconds ... + * t := time.Now() + * elapsed := t.Sub(start) + * ``` + * + * Other idioms, such as time.Since(start), time.Until(deadline), and + * time.Now().Before(deadline), are similarly robust against wall clock + * resets. + * + * The rest of this section gives the precise details of how operations + * use monotonic clocks, but understanding those details is not required + * to use this package. + * + * The Time returned by time.Now contains a monotonic clock reading. + * If Time t has a monotonic clock reading, t.Add adds the same duration to + * both the wall clock and monotonic clock readings to compute the result. + * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time + * computations, they always strip any monotonic clock reading from their results. + * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation + * of the wall time, they also strip any monotonic clock reading from their results. + * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). + * + * If Times t and u both contain monotonic clock readings, the operations + * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out + * using the monotonic clock readings alone, ignoring the wall clock + * readings. If either t or u contains no monotonic clock reading, these + * operations fall back to using the wall clock readings. + * + * On some systems the monotonic clock will stop if the computer goes to sleep. + * On such a system, t.Sub(u) may not accurately reflect the actual + * time that passed between t and u. + * + * Because the monotonic clock reading has no meaning outside + * the current process, the serialized forms generated by t.GobEncode, + * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic + * clock reading, and t.Format provides no format for it. Similarly, the + * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, + * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. + * t.UnmarshalJSON, and t.UnmarshalText always create times with + * no monotonic clock reading. + * + * Note that the Go == operator compares not just the time instant but + * also the Location and the monotonic clock reading. See the + * documentation for the Time type for a discussion of equality + * testing for Time values. + * + * For debugging, the result of t.String does include the monotonic + * clock reading if present. If t != u because of different monotonic clock readings, + * that difference will be visible when printing t.String() and u.String(). + */ +namespace time { + /** + * A Month specifies a month of the year (January = 1, ...). + */ + interface Month extends Number{} + interface Month { + /** + * String returns the English name of the month ("January", "February", ...). + */ + string(): string + } + /** + * A Weekday specifies a day of the week (Sunday = 0, ...). + */ + interface Weekday extends Number{} + interface Weekday { + /** + * String returns the English name of the day ("Sunday", "Monday", ...). + */ + string(): string + } + /** + * A Location maps time instants to the zone in use at that time. + * Typically, the Location represents the collection of time offsets + * in use in a geographical area. For many Locations the time offset varies + * depending on whether daylight savings time is in use at the time instant. + */ + interface Location { + } + interface Location { + /** + * String returns a descriptive name for the time zone information, + * corresponding to the name argument to LoadLocation or FixedZone. + */ + string(): string + } +} + /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -16041,105 +16877,17 @@ namespace fs { } /** - * Package driver defines interfaces to be implemented by database - * drivers as used by package sql. - * - * Most code should use package sql. - * - * The driver interface has evolved over time. Drivers should implement - * Connector and DriverContext interfaces. - * The Connector.Connect and Driver.Open methods should never return ErrBadConn. - * ErrBadConn should only be returned from Validator, SessionResetter, or - * a query method if the connection is already in an invalid (e.g. closed) state. - * - * All Conn implementations should implement the following interfaces: - * Pinger, SessionResetter, and Validator. - * - * If named parameters or context are supported, the driver's Conn should implement: - * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. - * - * To support custom data types, implement NamedValueChecker. NamedValueChecker - * also allows queries to accept per-query options as a parameter by returning - * ErrRemoveArgument from CheckNamedValue. - * - * If multiple result sets are supported, Rows should implement RowsNextResultSet. - * If the driver knows how to describe the types present in the returned result - * it should implement the following interfaces: RowsColumnTypeScanType, - * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, - * and RowsColumnTypePrecisionScale. A given row value may also return a Rows - * type, which may represent a database cursor value. - * - * Before a connection is returned to the connection pool after use, IsValid is - * called if implemented. Before a connection is reused for another query, - * ResetSession is called if implemented. If a connection is never returned to the - * connection pool but immediately reused, then ResetSession is called prior to - * reuse but IsValid is not called. + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. */ -namespace driver { +namespace bufio { /** - * Conn is a connection to a database. It is not used concurrently - * by multiple goroutines. - * - * Conn is assumed to be stateful. + * ReadWriter stores pointers to a Reader and a Writer. + * It implements io.ReadWriter. */ - interface Conn { - /** - * Prepare returns a prepared statement, bound to this connection. - */ - prepare(query: string): Stmt - /** - * Close invalidates and potentially stops any current - * prepared statements and transactions, marking this - * connection as no longer in use. - * - * Because the sql package maintains a free pool of - * connections and only calls Close when there's a surplus of - * idle connections, it shouldn't be necessary for drivers to - * do their own connection caching. - * - * Drivers must ensure all network calls made by Close - * do not block indefinitely (e.g. apply a timeout). - */ - close(): void - /** - * Begin starts and returns a new transaction. - * - * Deprecated: Drivers should implement ConnBeginTx instead (or additionally). - */ - begin(): Tx - } -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * The Userinfo type is an immutable encapsulation of username and - * password details for a URL. An existing Userinfo value is guaranteed - * to have a username set (potentially empty, as allowed by RFC 2396), - * and optionally a password. - */ - interface Userinfo { - } - interface Userinfo { - /** - * Username returns the username. - */ - username(): string - } - interface Userinfo { - /** - * Password returns the password in case it is set, and whether it is set. - */ - password(): [string, boolean] - } - interface Userinfo { - /** - * String returns the encoded userinfo information in the standard form - * of "username[:password]". - */ - string(): string + type _subqqWpg = Reader&Writer + interface ReadWriter extends _subqqWpg { } } @@ -16181,7 +16929,7 @@ namespace url { * } * ``` * - * # Name Resolution + * Name Resolution * * The method for resolving domain names, whether indirectly with functions like Dial * or directly with functions like LookupHost and LookupAddr, varies by operating system. @@ -16207,7 +16955,7 @@ namespace url { * * ``` * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) + * export GODEBUG=netdns=cgo # force cgo resolver * ``` * * The decision can also be forced while building the Go source tree @@ -16220,8 +16968,7 @@ namespace url { * * On Plan 9, the resolver always accesses /net/cs and /net/dns. * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. + * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. */ namespace net { /** @@ -16412,74 +17159,48 @@ namespace net { string(): string } /** - * Conn is a generic stream-oriented network connection. + * Addr represents a network end point address. * - * Multiple goroutines may invoke methods on a Conn simultaneously. + * 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 Conn { + 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") + } +} + +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { + /** + * The Userinfo type is an immutable encapsulation of username and + * password details for a URL. An existing Userinfo value is guaranteed + * to have a username set (potentially empty, as allowed by RFC 2396), + * and optionally a password. + */ + interface Userinfo { + } + interface Userinfo { /** - * Read reads data from the connection. - * Read can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetReadDeadline. + * Username returns the username. */ - read(b: string): number + username(): string + } + interface Userinfo { /** - * Write writes data to the connection. - * Write can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetWriteDeadline. + * Password returns the password in case it is set, and whether it is set. */ - write(b: string): number + password(): [string, boolean] + } + interface Userinfo { /** - * Close closes the connection. - * Any blocked Read or Write operations will be unblocked and return errors. + * String returns the encoded userinfo information in the standard form + * of "username[:password]". */ - close(): void - /** - * LocalAddr returns the local network address, if known. - */ - localAddr(): Addr - /** - * RemoteAddr returns the remote network address, if known. - */ - remoteAddr(): Addr - /** - * SetDeadline sets the read and write deadlines associated - * with the connection. It is equivalent to calling both - * SetReadDeadline and SetWriteDeadline. - * - * A deadline is an absolute time after which I/O operations - * fail instead of blocking. The deadline applies to all future - * and pending I/O, not just the immediately following call to - * Read or Write. After a deadline has been exceeded, the - * connection can be refreshed by setting a deadline in the future. - * - * If the deadline is exceeded a call to Read or Write or to other - * I/O methods will return an error that wraps os.ErrDeadlineExceeded. - * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). - * The error's Timeout method will return true, but note that there - * are other possible errors for which the Timeout method will - * return true even if the deadline has not been exceeded. - * - * An idle timeout can be implemented by repeatedly extending - * the deadline after successful Read or Write calls. - * - * A zero value for t means I/O operations will not time out. - */ - 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(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 + string(): string } } @@ -16492,6 +17213,38 @@ namespace net { * Package x509 parses X.509-encoded keys and certificates. */ namespace x509 { + /** + * CertPool is a set of certificates. + */ + interface CertPool { + } + interface CertPool { + /** + * AddCert adds a certificate to a pool. + */ + addCert(cert: Certificate): void + } + interface CertPool { + /** + * AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. + * It appends any certificates found to s and reports whether any certificates + * were successfully parsed. + * + * On many Linux systems, /etc/ssl/cert.pem will contain the system wide set + * of root CAs in a format suitable for this function. + */ + appendCertsFromPEM(pemCerts: string): boolean + } + interface CertPool { + /** + * Subjects returns a list of the DER-encoded subjects of + * all of the certificates in the pool. + * + * Deprecated: if s was returned by SystemCertPool, Subjects + * will not include the system roots. + */ + subjects(): Array + } // @ts-ignore import cryptobyte_asn1 = asn1 interface Certificate { @@ -16671,8 +17424,6 @@ namespace x509 { interface Certificate { /** * CheckCRLSignature checks that the signature in crl is from c. - * - * Deprecated: Use RevocationList.CheckSignatureFrom instead. */ checkCRLSignature(crl: pkix.CertificateList): void } @@ -16681,7 +17432,7 @@ namespace x509 { * CreateCRL returns a DER encoded CRL, signed by this Certificate, that * contains the given list of revoked certificates. * - * Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL. + * Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. * To generate a standards compliant CRL, use CreateRevocationList instead. */ createCRL(rand: io.Reader, priv: any, revokedCerts: Array, now: time.Time): string @@ -16689,17 +17440,221 @@ namespace x509 { } /** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. + * Package tls partially implements TLS 1.2, as specified in RFC 5246, + * and TLS 1.3, as specified in RFC 8446. */ -namespace bufio { +namespace tls { /** - * ReadWriter stores pointers to a Reader and a Writer. - * It implements io.ReadWriter. + * CurveID is the type of a TLS identifier for an elliptic curve. See + * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. + * + * In TLS 1.3, this type is called NamedGroup, but at this time this library + * only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7. */ - type _subCXrjQ = Reader&Writer - interface ReadWriter extends _subCXrjQ { + interface CurveID extends Number{} + /** + * ClientAuthType declares the policy the server will follow for + * TLS Client Authentication. + */ + interface ClientAuthType extends Number{} + /** + * ClientSessionCache is a cache of ClientSessionState objects that can be used + * by a client to resume a TLS session with a given server. ClientSessionCache + * implementations should expect to be called concurrently from different + * goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not + * SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which + * are supported via this interface. + */ + interface ClientSessionCache { + /** + * Get searches for a ClientSessionState associated with the given key. + * On return, ok is true if one was found. + */ + get(sessionKey: string): [(ClientSessionState | undefined), boolean] + /** + * Put adds the ClientSessionState to the cache with the given key. It might + * get called multiple times in a connection if a TLS 1.3 server provides + * more than one session ticket. If called with a nil *ClientSessionState, + * it should remove the cache entry. + */ + put(sessionKey: string, cs: ClientSessionState): void + } + /** + * ClientHelloInfo contains information from a ClientHello message in order to + * guide application logic in the GetCertificate and GetConfigForClient callbacks. + */ + interface ClientHelloInfo { + /** + * CipherSuites lists the CipherSuites supported by the client (e.g. + * TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). + */ + cipherSuites: Array + /** + * ServerName indicates the name of the server requested by the client + * in order to support virtual hosting. ServerName is only set if the + * client is using SNI (see RFC 4366, Section 3.1). + */ + serverName: string + /** + * SupportedCurves lists the elliptic curves supported by the client. + * SupportedCurves is set only if the Supported Elliptic Curves + * Extension is being used (see RFC 4492, Section 5.1.1). + */ + supportedCurves: Array + /** + * SupportedPoints lists the point formats supported by the client. + * SupportedPoints is set only if the Supported Point Formats Extension + * is being used (see RFC 4492, Section 5.1.2). + */ + supportedPoints: Array + /** + * SignatureSchemes lists the signature and hash schemes that the client + * is willing to verify. SignatureSchemes is set only if the Signature + * Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). + */ + signatureSchemes: Array + /** + * SupportedProtos lists the application protocols supported by the client. + * SupportedProtos is set only if the Application-Layer Protocol + * Negotiation Extension is being used (see RFC 7301, Section 3.1). + * + * Servers can select a protocol by setting Config.NextProtos in a + * GetConfigForClient return value. + */ + supportedProtos: Array + /** + * SupportedVersions lists the TLS versions supported by the client. + * For TLS versions less than 1.3, this is extrapolated from the max + * version advertised by the client, so values other than the greatest + * might be rejected if used. + */ + supportedVersions: Array + /** + * Conn is the underlying net.Conn for the connection. Do not read + * from, or write to, this connection; that will cause the TLS + * connection to fail. + */ + conn: net.Conn + } + interface ClientHelloInfo { + /** + * Context returns the context of the handshake that is in progress. + * This context is a child of the context passed to HandshakeContext, + * if any, and is canceled when the handshake concludes. + */ + context(): context.Context + } + /** + * CertificateRequestInfo contains information from a server's + * CertificateRequest message, which is used to demand a certificate and proof + * of control from a client. + */ + interface CertificateRequestInfo { + /** + * AcceptableCAs contains zero or more, DER-encoded, X.501 + * Distinguished Names. These are the names of root or intermediate CAs + * that the server wishes the returned certificate to be signed by. An + * empty slice indicates that the server has no preference. + */ + acceptableCAs: Array + /** + * SignatureSchemes lists the signature schemes that the server is + * willing to verify. + */ + signatureSchemes: Array + /** + * Version is the TLS version that was negotiated for this connection. + */ + version: number + } + interface CertificateRequestInfo { + /** + * Context returns the context of the handshake that is in progress. + * This context is a child of the context passed to HandshakeContext, + * if any, and is canceled when the handshake concludes. + */ + context(): context.Context + } + /** + * RenegotiationSupport enumerates the different levels of support for TLS + * renegotiation. TLS renegotiation is the act of performing subsequent + * handshakes on a connection after the first. This significantly complicates + * the state machine and has been the source of numerous, subtle security + * issues. Initiating a renegotiation is not supported, but support for + * accepting renegotiation requests may be enabled. + * + * Even when enabled, the server may not change its identity between handshakes + * (i.e. the leaf certificate must be the same). Additionally, concurrent + * handshake and application data flow is not permitted so renegotiation can + * only be used with protocols that synchronise with the renegotiation, such as + * HTTPS. + * + * Renegotiation is not defined in TLS 1.3. + */ + interface RenegotiationSupport extends Number{} + interface ClientHelloInfo { + /** + * SupportsCertificate returns nil if the provided certificate is supported by + * the client that sent the ClientHello. Otherwise, it returns an error + * describing the reason for the incompatibility. + * + * If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate + * callback, this method will take into account the associated Config. Note that + * if GetConfigForClient returns a different Config, the change can't be + * accounted for by this method. + * + * This function will call x509.ParseCertificate unless c.Leaf is set, which can + * incur a significant performance cost. + */ + supportsCertificate(c: Certificate): void + } + interface CertificateRequestInfo { + /** + * SupportsCertificate returns nil if the provided certificate is supported by + * the server that sent the CertificateRequest. Otherwise, it returns an error + * describing the reason for the incompatibility. + */ + supportsCertificate(c: Certificate): void + } + /** + * A Certificate is a chain of one or more certificates, leaf first. + */ + interface Certificate { + certificate: Array + /** + * PrivateKey contains the private key corresponding to the public key in + * Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey. + * For a server up to TLS 1.2, it can also implement crypto.Decrypter with + * an RSA PublicKey. + */ + privateKey: crypto.PrivateKey + /** + * SupportedSignatureAlgorithms is an optional list restricting what + * signature algorithms the PrivateKey can be used for. + */ + supportedSignatureAlgorithms: Array + /** + * OCSPStaple contains an optional OCSP response which will be served + * to clients that request it. + */ + ocspStaple: string + /** + * SignedCertificateTimestamps contains an optional list of Signed + * Certificate Timestamps which will be served to clients that request it. + */ + signedCertificateTimestamps: Array + /** + * Leaf is the parsed form of the leaf certificate, which may be initialized + * using x509.ParseCertificate to reduce per-handshake processing. If nil, + * the leaf certificate will be parsed as needed. + */ + leaf?: x509.Certificate + } + interface CurveID { + string(): string + } + interface ClientAuthType { + string(): string } } @@ -16749,6 +17704,21 @@ namespace multipart { } } +/** + * Package log implements a simple logging package. It defines a type, Logger, + * with methods for formatting output. It also has a predefined 'standard' + * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and + * Panic[f|ln], which are easier to use than creating a Logger manually. + * That logger writes to standard error and prints the date and time + * of each logged message. + * Every log message is output on a separate line: if the message being + * printed does not end in a newline, the logger will add one. + * The Fatal functions call os.Exit(1) after writing the log message. + * The Panic functions call panic after writing the log message. + */ +namespace log { +} + /** * Package http provides HTTP client and server implementations. * @@ -16936,238 +17906,9 @@ namespace http { } // @ts-ignore import urlpkg = url - /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. - */ - interface Server { - /** - * Addr optionally specifies the TCP address for the server to listen on, - * in the form "host:port". If empty, ":http" (port 80) is used. - * The service names are defined in RFC 6335 and assigned by IANA. - * See net.Dial for details of the address format. - */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil - /** - * TLSConfig optionally provides a TLS configuration for use - * by ServeTLS and ListenAndServeTLS. Note that this value is - * cloned by ServeTLS and ListenAndServeTLS, so it's not - * possible to modify the configuration with methods like - * tls.Config.SetSessionTicketKeys. To use - * SetSessionTicketKeys, use Server.Serve with a TLS Listener - * instead. - */ - tlsConfig?: tls.Config - /** - * 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. - */ - readTimeout: time.Duration - /** - * ReadHeaderTimeout is the amount of time allowed to read - * request headers. The connection's read deadline is reset - * after reading the headers and the Handler can decide what - * is considered too slow for the body. If ReadHeaderTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - readHeaderTimeout: time.Duration - /** - * WriteTimeout is the maximum duration before timing out - * writes of the response. It is reset whenever a new - * request's header is read. Like ReadTimeout, it does not - * let Handlers make decisions on a per-request basis. - * A zero or negative value means there will be no timeout. - */ - writeTimeout: time.Duration - /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If IdleTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - idleTimeout: time.Duration - /** - * MaxHeaderBytes controls the maximum number of bytes the - * server will read parsing the request header's keys and - * values, including the request line. It does not limit the - * size of the request body. - * If zero, DefaultMaxHeaderBytes is used. - */ - maxHeaderBytes: number - /** - * TLSNextProto optionally specifies a function to take over - * ownership of the provided TLS connection when an ALPN - * protocol upgrade has occurred. The map key is the protocol - * name negotiated. The Handler argument should be used to - * handle HTTP requests and will initialize the Request's TLS - * and RemoteAddr if not already set. The connection is - * automatically closed when the function returns. - * If TLSNextProto is not nil, HTTP/2 support is not enabled - * automatically. - */ - tlsNextProto: _TygojaDict - /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. - */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void - /** - * 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. - */ - errorLog?: log.Logger - /** - * 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. - */ - baseContext: (_arg0: net.Listener) => context.Context - /** - * ConnContext optionally specifies a function that modifies - * the context used for a new connection c. The provided ctx - * is derived from the base context and has a ServerContextKey - * value. - */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context - } - interface Server { - /** - * Close immediately closes all active net.Listeners and any - * connections in state StateNew, StateActive, or StateIdle. For a - * graceful shutdown, use Shutdown. - * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. - * - * 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). - * - * When Shutdown is called, Serve, ListenAndServe, and - * ListenAndServeTLS immediately return ErrServerClosed. Make sure the - * program doesn't exit and waits instead for Shutdown to return. - * - * Shutdown does not attempt to close nor wait for hijacked - * connections such as WebSockets. The caller of Shutdown should - * separately notify such long-lived connections of shutdown and wait - * for them to close, if desired. See RegisterOnShutdown for a way to - * register shutdown notification functions. - * - * 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. - * - * If srv.Addr is blank, ":http" is used. - * - * 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. - * - * 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. - */ - serve(l: net.Listener): void - } - interface Server { - /** - * 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. - */ - serveTLS(l: net.Listener, certFile: string): void - } - interface Server { - /** - * 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. - */ - setKeepAlivesEnabled(v: boolean): void - } - interface Server { - /** - * 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. - */ - listenAndServeTLS(certFile: string): void - } +} + +namespace store { } namespace mailer { @@ -17187,6 +17928,132 @@ namespace mailer { } } +/** + * Package driver defines interfaces to be implemented by database + * drivers as used by package sql. + * + * Most code should use package sql. + * + * The driver interface has evolved over time. Drivers should implement + * Connector and DriverContext interfaces. + * The Connector.Connect and Driver.Open methods should never return ErrBadConn. + * ErrBadConn should only be returned from Validator, SessionResetter, or + * a query method if the connection is already in an invalid (e.g. closed) state. + * + * All Conn implementations should implement the following interfaces: + * Pinger, SessionResetter, and Validator. + * + * If named parameters or context are supported, the driver's Conn should implement: + * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * + * To support custom data types, implement NamedValueChecker. NamedValueChecker + * also allows queries to accept per-query options as a parameter by returning + * ErrRemoveArgument from CheckNamedValue. + * + * If multiple result sets are supported, Rows should implement RowsNextResultSet. + * If the driver knows how to describe the types present in the returned result + * it should implement the following interfaces: RowsColumnTypeScanType, + * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, + * and RowsColumnTypePrecisionScale. A given row value may also return a Rows + * type, which may represent a database cursor value. + * + * Before a connection is returned to the connection pool after use, IsValid is + * called if implemented. Before a connection is reused for another query, + * ResetSession is called if implemented. If a connection is never returned to the + * connection pool but immediately reused, then ResetSession is called prior to + * reuse but IsValid is not called. + */ +namespace driver { + /** + * Conn is a connection to a database. It is not used concurrently + * by multiple goroutines. + * + * Conn is assumed to be stateful. + */ + interface Conn { + /** + * Prepare returns a prepared statement, bound to this connection. + */ + prepare(query: string): Stmt + /** + * Close invalidates and potentially stops any current + * prepared statements and transactions, marking this + * connection as no longer in use. + * + * Because the sql package maintains a free pool of + * connections and only calls Close when there's a surplus of + * idle connections, it shouldn't be necessary for drivers to + * do their own connection caching. + * + * Drivers must ensure all network calls made by Close + * do not block indefinitely (e.g. apply a timeout). + */ + close(): void + /** + * Begin starts and returns a new transaction. + * + * Deprecated: Drivers should implement ConnBeginTx instead (or additionally). + */ + begin(): Tx + } +} + +/** + * 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(): driver.Value + } + interface JsonRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. + */ + scan(value: { + }): void + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + page: number + perPage: number + totalItems: number + totalPages: number + items: any + } +} + /** * Package echo implements high performance, minimalist Go web framework. * @@ -17301,62 +18168,6 @@ 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(): driver.Value - } - interface JsonRaw { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. - */ - scan(value: { - }): void - } -} - -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 @@ -17380,6 +18191,82 @@ namespace settings { } } +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 _subMhVBX = Hook + interface mainHook extends _subMhVBX { + } +} + +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 + } +} + /** * Package autocert provides automatic access to certificates from Let's Encrypt * and any other ACME-based CA. @@ -17547,112 +18434,90 @@ namespace autocert { } } -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 _subkuwfu = Hook - interface mainHook extends _subkuwfu { +/** + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + interface BaseModelEvent { + model: models.Model + } + interface BaseModelEvent { + tags(): Array + } + interface BaseCollectionEvent { + collection?: models.Collection + } + interface BaseCollectionEvent { + tags(): Array } } /** - * Package flag implements command-line flag parsing. - * - * # Usage - * - * Define flags using flag.String(), Bool(), Int(), etc. - * - * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: - * * ``` - * import "flag" - * var nFlag = flag.Int("n", 1234, "help message for flag n") + * Package flag implements command-line flag parsing. + * + * Usage + * + * Define flags using flag.String(), Bool(), Int(), etc. + * + * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: + * import "flag" + * var nFlag = flag.Int("n", 1234, "help message for flag n") + * If you like, you can bind the flag to a variable using the Var() functions. + * var flagvar int + * func init() { + * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + * } + * Or you can create custom flags that satisfy the Value interface (with + * pointer receivers) and couple them to flag parsing by + * flag.Var(&flagVal, "name", "help message for flagname") + * For such flags, the default value is just the initial value of the variable. + * + * After all flags are defined, call + * flag.Parse() + * to parse the command line into the defined flags. + * + * Flags may then be used directly. If you're using the flags themselves, + * they are all pointers; if you bind to variables, they're values. + * fmt.Println("ip has value ", *ip) + * fmt.Println("flagvar has value ", flagvar) + * + * After parsing, the arguments following the flags are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * Command line flag syntax + * + * The following forms are permitted: + * + * -flag + * -flag=x + * -flag x // non-boolean flags only + * One or two minus signs may be used; they are equivalent. + * The last form is not permitted for boolean flags because the + * meaning of the command + * cmd -x * + * where * is a Unix shell wildcard, will change if there is a file + * called 0, false, etc. You must use the -flag=false form to turn + * off a boolean flag. + * + * Flag parsing stops just before the first non-flag argument + * ("-" is a non-flag argument) or after the terminator "--". + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags may be: + * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False + * Duration flags accept any input valid for time.ParseDuration. + * + * The default set of command-line flags is controlled by + * top-level functions. The FlagSet type allows one to define + * independent sets of flags, such as to implement subcommands + * in a command-line interface. The methods of FlagSet are + * analogous to the top-level functions for the command-line + * flag set. * ``` - * - * If you like, you can bind the flag to a variable using the Var() functions. - * - * ``` - * var flagvar int - * func init() { - * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - * } - * ``` - * - * Or you can create custom flags that satisfy the Value interface (with - * pointer receivers) and couple them to flag parsing by - * - * ``` - * flag.Var(&flagVal, "name", "help message for flagname") - * ``` - * - * For such flags, the default value is just the initial value of the variable. - * - * After all flags are defined, call - * - * ``` - * flag.Parse() - * ``` - * - * to parse the command line into the defined flags. - * - * Flags may then be used directly. If you're using the flags themselves, - * they are all pointers; if you bind to variables, they're values. - * - * ``` - * fmt.Println("ip has value ", *ip) - * fmt.Println("flagvar has value ", flagvar) - * ``` - * - * After parsing, the arguments following the flags are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. - * - * # Command line flag syntax - * - * The following forms are permitted: - * - * ``` - * -flag - * --flag // double dashes are also permitted - * -flag=x - * -flag x // non-boolean flags only - * ``` - * - * One or two dashes may be used; they are equivalent. - * The last form is not permitted for boolean flags because the - * meaning of the command - * - * ``` - * cmd -x * - * ``` - * - * where * is a Unix shell wildcard, will change if there is a file - * called 0, false, etc. You must use the -flag=false form to turn - * off a boolean flag. - * - * Flag parsing stops just before the first non-flag argument - * ("-" is a non-flag argument) or after the terminator "--". - * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags may be: - * - * ``` - * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False - * ``` - * - * Duration flags accept any input valid for time.ParseDuration. - * - * The default set of command-line flags is controlled by - * top-level functions. The FlagSet type allows one to define - * independent sets of flags, such as to implement subcommands - * in a command-line interface. The methods of FlagSet are - * analogous to the top-level functions for the command-line - * flag set. */ namespace flag { /** @@ -17881,16 +18746,6 @@ namespace flag { */ duration(name: string, value: time.Duration, usage: string): (time.Duration | undefined) } - interface FlagSet { - /** - * TextVar defines a flag with a specified name, default value, and usage string. - * The argument p must be a pointer to a variable that will hold the value - * of the flag, and p must implement encoding.TextUnmarshaler. - * If the flag is used, the flag value will be passed to p's UnmarshalText method. - * The type of the default value must be the same as the type of p. - */ - textVar(p: encoding.TextUnmarshaler, name: string, value: encoding.TextMarshaler, usage: string): void - } interface FlagSet { /** * Func defines a flag with the specified name and usage string. @@ -18074,87 +18929,72 @@ namespace pflag { } } -namespace subscriptions { +/** + * 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 { /** - * Message defines a client's channel data. + * A FileMode represents a file's mode and permission bits. + * The bits have the same definition on all systems, so that + * information about files can be moved from one system + * to another portably. Not all bits apply to all systems. + * The only required bit is ModeDir for directories. */ - interface Message { - name: string - data: string + interface FileMode extends Number{} + interface FileMode { + string(): string } - /** - * Client is an interface for a generic subscription client. - */ - interface Client { + interface FileMode { /** - * Id Returns the unique id of the client. + * IsDir reports whether m describes a directory. + * That is, it tests for the ModeDir bit being set in m. */ - id(): string + isDir(): boolean + } + interface FileMode { /** - * Channel returns the client's communication channel. + * IsRegular reports whether m describes a regular file. + * That is, it tests that no mode type bits are set. */ - channel(): undefined + isRegular(): boolean + } + interface FileMode { /** - * Subscriptions returns all subscriptions to which the client has subscribed to. + * Perm returns the Unix permission bits in m (m & ModePerm). */ - subscriptions(): _TygojaDict + perm(): FileMode + } + interface FileMode { /** - * Subscribe subscribes the client to the provided subscriptions list. + * Type returns type bits in m (m & ModeType). */ - 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 + type(): FileMode } } /** - * Package core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. + * Package crypto collects common cryptographic constants. */ -namespace core { - interface BaseModelEvent { - model: models.Model - } - interface BaseModelEvent { - tags(): Array - } - interface BaseCollectionEvent { - collection?: models.Collection - } - interface BaseCollectionEvent { - tags(): Array - } +namespace crypto { + /** + * PrivateKey represents a private key using an unspecified algorithm. + * + * Although this type is an empty interface for backwards compatibility reasons, + * all private key types in the standard library implement the following interface + * + * ``` + * interface{ + * Public() crypto.PublicKey + * Equal(x crypto.PrivateKey) bool + * } + * ``` + * + * as well as purpose-specific interfaces such as Signer and Decrypter, which + * can be used for increased type safety within applications. + */ + interface PrivateKey extends _TygojaAny{} } /** @@ -18243,51 +19083,6 @@ namespace reflect { } } -/** - * 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 { - /** - * A FileMode represents a file's mode and permission bits. - * The bits have the same definition on all systems, so that - * information about files can be moved from one system - * to another portably. Not all bits apply to all systems. - * The only required bit is ModeDir for directories. - */ - interface FileMode extends Number{} - interface FileMode { - string(): string - } - interface FileMode { - /** - * IsDir reports whether m describes a directory. - * That is, it tests for the ModeDir bit being set in m. - */ - isDir(): boolean - } - interface FileMode { - /** - * IsRegular reports whether m describes a regular file. - * That is, it tests that no mode type bits are set. - */ - isRegular(): boolean - } - interface FileMode { - /** - * Perm returns the Unix permission bits in m (m & ModePerm). - */ - perm(): FileMode - } - interface FileMode { - /** - * Type returns type bits in m (m & ModeType). - */ - type(): FileMode - } -} - /** * Package big implements arbitrary-precision arithmetic (big numbers). * The following numeric types are supported: @@ -18537,7 +19332,7 @@ namespace big { * r = x - y*q * ``` * - * (See Daan Leijen, “Division and Modulus for Computer Scientists”.) + * (See Daan Leijen, ``Division and Modulus for Computer Scientists''.) * See DivMod for Euclidean division and modulus (unlike Go). */ quoRem(x: Int): [(Int | undefined), (Int | undefined)] @@ -18571,8 +19366,8 @@ namespace big { * m = x - y*q with 0 <= m < |y| * ``` * - * (See Raymond T. Boute, “The Euclidean definition of the functions - * div and mod”. ACM Transactions on Programming Languages and + * (See Raymond T. Boute, ``The Euclidean definition of the functions + * div and mod''. ACM Transactions on Programming Languages and * Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. * ACM press.) * See QuoRem for T-division and modulus (like Go). @@ -18584,9 +19379,9 @@ namespace big { * Cmp compares x and y and returns: * * ``` - * -1 if x < y - * 0 if x == y - * +1 if x > y + * -1 if x < y + * 0 if x == y + * +1 if x > y * ``` */ cmp(y: Int): number @@ -18596,9 +19391,9 @@ namespace big { * CmpAbs compares the absolute values of x and y and returns: * * ``` - * -1 if |x| < |y| - * 0 if |x| == |y| - * +1 if |x| > |y| + * -1 if |x| < |y| + * 0 if |x| == |y| + * +1 if |x| > |y| * ``` */ cmpAbs(y: Int): number @@ -18638,8 +19433,8 @@ namespace big { * * The base argument must be 0 or a value between 2 and MaxBase. * For base 0, the number prefix determines the actual base: A prefix of - * “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8, - * and “0x” or “0X” selects base 16. Otherwise, the selected base is 10 + * ``0b'' or ``0B'' selects base 2, ``0'', ``0o'' or ``0O'' selects base 8, + * and ``0x'' or ``0X'' selects base 16. Otherwise, the selected base is 10 * and no prefix is accepted. * * For bases <= 36, lower and upper case letters are considered the same: @@ -18647,7 +19442,7 @@ namespace big { * For bases > 36, the upper case letters 'A' to 'Z' represent the digit * values 36 to 61. * - * For base 0, an underscore character “_” may appear between a base + * For base 0, an underscore character ``_'' may appear between a base * prefix and an adjacent digit, and between successive digits; such * underscores do not change the value of the number. * Incorrect placement of underscores is reported as an error if there @@ -18735,7 +19530,7 @@ namespace big { * ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ * and returns z. If g and n are not relatively prime, g has no multiplicative * inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value - * is nil. If n == 0, a division-by-zero run-time panic occurs. + * is nil. */ modInverse(g: Int): (Int | undefined) } @@ -18744,7 +19539,7 @@ namespace big { * ModSqrt sets z to a square root of x mod p if such a square root exists, and * returns z. The modulus p must be an odd prime. If x is not a square mod p, * ModSqrt leaves z unchanged and returns nil. This function panics if p is - * not an odd integer, its behavior is undefined if p is odd but not prime. + * not an odd integer. */ modSqrt(x: Int): (Int | undefined) } @@ -18922,749 +19717,6 @@ namespace big { } } -/** - * Package asn1 implements parsing of DER-encoded ASN.1 data structures, - * as defined in ITU-T Rec X.690. - * - * See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” - * http://luca.ntop.org/Teaching/Appunti/asn1.html. - */ -namespace asn1 { - /** - * An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. - */ - interface ObjectIdentifier extends Array{} - interface ObjectIdentifier { - /** - * Equal reports whether oi and other represent the same identifier. - */ - equal(other: ObjectIdentifier): boolean - } - interface ObjectIdentifier { - string(): string - } -} - -/** - * Package pkix contains shared, low level structures used for ASN.1 parsing - * and serialization of X.509 certificates, CRL and OCSP. - */ -namespace pkix { - /** - * Extension represents the ASN.1 structure of the same name. See RFC - * 5280, section 4.2. - */ - interface Extension { - id: asn1.ObjectIdentifier - critical: boolean - value: string - } - /** - * Name represents an X.509 distinguished name. This only includes the common - * elements of a DN. Note that Name is only an approximation of the X.509 - * structure. If an accurate representation is needed, asn1.Unmarshal the raw - * subject or issuer as an RDNSequence. - */ - interface Name { - country: Array - locality: Array - streetAddress: Array - serialNumber: string - /** - * Names contains all parsed attributes. When parsing distinguished names, - * this can be used to extract non-standard attributes that are not parsed - * by this package. When marshaling to RDNSequences, the Names field is - * ignored, see ExtraNames. - */ - names: Array - /** - * ExtraNames contains attributes to be copied, raw, into any marshaled - * distinguished names. Values override any attributes with the same OID. - * The ExtraNames field is not populated when parsing, see Names. - */ - extraNames: Array - } - interface Name { - /** - * FillFromRDNSequence populates n from the provided RDNSequence. - * Multi-entry RDNs are flattened, all entries are added to the - * relevant n fields, and the grouping is not preserved. - */ - fillFromRDNSequence(rdns: RDNSequence): void - } - interface Name { - /** - * ToRDNSequence converts n into a single RDNSequence. The following - * attributes are encoded as multi-value RDNs: - * - * ``` - * - Country - * - Organization - * - OrganizationalUnit - * - Locality - * - Province - * - StreetAddress - * - PostalCode - * ``` - * - * Each ExtraNames entry is encoded as an individual RDN. - */ - toRDNSequence(): RDNSequence - } - interface Name { - /** - * String returns the string form of n, roughly following - * the RFC 2253 Distinguished Names syntax. - */ - string(): string - } - /** - * CertificateList represents the ASN.1 structure of the same name. See RFC - * 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the - * signature. - * - * Deprecated: x509.RevocationList should be used instead. - */ - interface CertificateList { - tbsCertList: TBSCertificateList - signatureAlgorithm: AlgorithmIdentifier - signatureValue: asn1.BitString - } - interface CertificateList { - /** - * HasExpired reports whether certList should have been updated by now. - */ - hasExpired(now: time.Time): boolean - } - /** - * RevokedCertificate represents the ASN.1 structure of the same name. See RFC - * 5280, section 5.1. - */ - interface RevokedCertificate { - serialNumber?: big.Int - revocationTime: time.Time - extensions: Array - } -} - -/** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * # Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. - */ -namespace net { - /** - * Addr represents a network end point address. - * - * The two methods Network and String conventionally return strings - * that can be passed as the arguments to Dial, but the exact form - * and meaning of the strings is up to the implementation. - */ - interface Addr { - 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") - } - /** - * 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 - } -} - -/** - * Copyright 2021 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -/** - * Package x509 parses X.509-encoded keys and certificates. - */ -namespace x509 { - // @ts-ignore - import cryptobyte_asn1 = asn1 - /** - * VerifyOptions contains parameters for Certificate.Verify. - */ - interface VerifyOptions { - /** - * DNSName, if set, is checked against the leaf certificate with - * Certificate.VerifyHostname or the platform verifier. - */ - dnsName: string - /** - * Intermediates is an optional pool of certificates that are not trust - * anchors, but can be used to form a chain from the leaf certificate to a - * root certificate. - */ - intermediates?: CertPool - /** - * Roots is the set of trusted root certificates the leaf certificate needs - * to chain up to. If nil, the system roots or the platform verifier are used. - */ - roots?: CertPool - /** - * CurrentTime is used to check the validity of all certificates in the - * chain. If zero, the current time is used. - */ - currentTime: time.Time - /** - * KeyUsages specifies which Extended Key Usage values are acceptable. A - * chain is accepted if it allows any of the listed values. An empty list - * means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny. - */ - keyUsages: Array - /** - * MaxConstraintComparisions is the maximum number of comparisons to - * perform when checking a given certificate's name constraints. If - * zero, a sensible default is used. This limit prevents pathological - * certificates from consuming excessive amounts of CPU time when - * validating. It does not apply to the platform verifier. - */ - maxConstraintComparisions: number - } - interface SignatureAlgorithm extends Number{} - interface SignatureAlgorithm { - string(): string - } - interface PublicKeyAlgorithm extends Number{} - interface PublicKeyAlgorithm { - string(): string - } - /** - * KeyUsage represents the set of actions that are valid for a given key. It's - * a bitmap of the KeyUsage* constants. - */ - interface KeyUsage extends Number{} - /** - * ExtKeyUsage represents an extended set of actions that are valid for a given key. - * Each of the ExtKeyUsage* constants define a unique action. - */ - interface ExtKeyUsage extends Number{} -} - -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * ClientHelloInfo contains information from a ClientHello message in order to - * guide application logic in the GetCertificate and GetConfigForClient callbacks. - */ - interface ClientHelloInfo { - /** - * CipherSuites lists the CipherSuites supported by the client (e.g. - * TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). - */ - cipherSuites: Array - /** - * ServerName indicates the name of the server requested by the client - * in order to support virtual hosting. ServerName is only set if the - * client is using SNI (see RFC 4366, Section 3.1). - */ - serverName: string - /** - * SupportedCurves lists the elliptic curves supported by the client. - * SupportedCurves is set only if the Supported Elliptic Curves - * Extension is being used (see RFC 4492, Section 5.1.1). - */ - supportedCurves: Array - /** - * SupportedPoints lists the point formats supported by the client. - * SupportedPoints is set only if the Supported Point Formats Extension - * is being used (see RFC 4492, Section 5.1.2). - */ - supportedPoints: Array - /** - * SignatureSchemes lists the signature and hash schemes that the client - * is willing to verify. SignatureSchemes is set only if the Signature - * Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). - */ - signatureSchemes: Array - /** - * SupportedProtos lists the application protocols supported by the client. - * SupportedProtos is set only if the Application-Layer Protocol - * Negotiation Extension is being used (see RFC 7301, Section 3.1). - * - * Servers can select a protocol by setting Config.NextProtos in a - * GetConfigForClient return value. - */ - supportedProtos: Array - /** - * SupportedVersions lists the TLS versions supported by the client. - * For TLS versions less than 1.3, this is extrapolated from the max - * version advertised by the client, so values other than the greatest - * might be rejected if used. - */ - supportedVersions: Array - /** - * Conn is the underlying net.Conn for the connection. Do not read - * from, or write to, this connection; that will cause the TLS - * connection to fail. - */ - conn: net.Conn - } - interface ClientHelloInfo { - /** - * Context returns the context of the handshake that is in progress. - * This context is a child of the context passed to HandshakeContext, - * if any, and is canceled when the handshake concludes. - */ - context(): context.Context - } - /** - * A Config structure is used to configure a TLS client or server. - * After one has been passed to a TLS function it must not be - * modified. A Config may be reused; the tls package will also not - * modify it. - */ - interface Config { - /** - * Rand provides the source of entropy for nonces and RSA blinding. - * If Rand is nil, TLS uses the cryptographic random reader in package - * crypto/rand. - * The Reader must be safe for use by multiple goroutines. - */ - rand: io.Reader - /** - * Time returns the current time as the number of seconds since the epoch. - * If Time is nil, TLS uses time.Now. - */ - time: () => time.Time - /** - * Certificates contains one or more certificate chains to present to the - * other side of the connection. The first certificate compatible with the - * peer's requirements is selected automatically. - * - * Server configurations must set one of Certificates, GetCertificate or - * GetConfigForClient. Clients doing client-authentication may set either - * Certificates or GetClientCertificate. - * - * Note: if there are multiple Certificates, and they don't have the - * optional field Leaf set, certificate selection will incur a significant - * per-handshake performance cost. - */ - certificates: Array - /** - * NameToCertificate maps from a certificate name to an element of - * Certificates. Note that a certificate name can be of the form - * '*.example.com' and so doesn't have to be a domain name as such. - * - * Deprecated: NameToCertificate only allows associating a single - * certificate with a given name. Leave this field nil to let the library - * select the first compatible chain from Certificates. - */ - nameToCertificate: _TygojaDict - /** - * GetCertificate returns a Certificate based on the given - * ClientHelloInfo. It will only be called if the client supplies SNI - * information or if Certificates is empty. - * - * If GetCertificate is nil or returns nil, then the certificate is - * retrieved from NameToCertificate. If NameToCertificate is nil, the - * best element of Certificates will be used. - */ - getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) - /** - * GetClientCertificate, if not nil, is called when a server requests a - * certificate from a client. If set, the contents of Certificates will - * be ignored. - * - * If GetClientCertificate returns an error, the handshake will be - * aborted and that error will be returned. Otherwise - * GetClientCertificate must return a non-nil Certificate. If - * Certificate.Certificate is empty then no certificate will be sent to - * the server. If this is unacceptable to the server then it may abort - * the handshake. - * - * GetClientCertificate may be called multiple times for the same - * connection if renegotiation occurs or if TLS 1.3 is in use. - */ - getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) - /** - * GetConfigForClient, if not nil, is called after a ClientHello is - * received from a client. It may return a non-nil Config in order to - * change the Config that will be used to handle this connection. If - * the returned Config is nil, the original Config will be used. The - * Config returned by this callback may not be subsequently modified. - * - * If GetConfigForClient is nil, the Config passed to Server() will be - * used for all connections. - * - * If SessionTicketKey was explicitly set on the returned Config, or if - * SetSessionTicketKeys was called on the returned Config, those keys will - * be used. Otherwise, the original Config keys will be used (and possibly - * rotated if they are automatically managed). - */ - getConfigForClient: (_arg0: ClientHelloInfo) => (Config | undefined) - /** - * VerifyPeerCertificate, if not nil, is called after normal - * certificate verification by either a TLS client or server. It - * receives the raw ASN.1 certificates provided by the peer and also - * any verified chains that normal processing found. If it returns a - * non-nil error, the handshake is aborted and that error results. - * - * If normal verification fails then the handshake will abort before - * considering this callback. If normal verification is disabled by - * setting InsecureSkipVerify, or (for a server) when ClientAuth is - * RequestClientCert or RequireAnyClientCert, then this callback will - * be considered but the verifiedChains argument will always be nil. - */ - verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void - /** - * VerifyConnection, if not nil, is called after normal certificate - * verification and after VerifyPeerCertificate by either a TLS client - * or server. If it returns a non-nil error, the handshake is aborted - * and that error results. - * - * If normal verification fails then the handshake will abort before - * considering this callback. This callback will run for all connections - * regardless of InsecureSkipVerify or ClientAuth settings. - */ - verifyConnection: (_arg0: ConnectionState) => void - /** - * RootCAs defines the set of root certificate authorities - * that clients use when verifying server certificates. - * If RootCAs is nil, TLS uses the host's root CA set. - */ - rootCAs?: x509.CertPool - /** - * NextProtos is a list of supported application level protocols, in - * order of preference. If both peers support ALPN, the selected - * protocol will be one from this list, and the connection will fail - * if there is no mutually supported protocol. If NextProtos is empty - * or the peer doesn't support ALPN, the connection will succeed and - * ConnectionState.NegotiatedProtocol will be empty. - */ - nextProtos: Array - /** - * ServerName is used to verify the hostname on the returned - * certificates unless InsecureSkipVerify is given. It is also included - * in the client's handshake to support virtual hosting unless it is - * an IP address. - */ - serverName: string - /** - * ClientAuth determines the server's policy for - * TLS Client Authentication. The default is NoClientCert. - */ - clientAuth: ClientAuthType - /** - * ClientCAs defines the set of root certificate authorities - * that servers use if required to verify a client certificate - * by the policy in ClientAuth. - */ - clientCAs?: x509.CertPool - /** - * InsecureSkipVerify controls whether a client verifies the server's - * certificate chain and host name. If InsecureSkipVerify is true, crypto/tls - * accepts any certificate presented by the server and any host name in that - * certificate. In this mode, TLS is susceptible to machine-in-the-middle - * attacks unless custom verification is used. This should be used only for - * testing or in combination with VerifyConnection or VerifyPeerCertificate. - */ - insecureSkipVerify: boolean - /** - * CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of - * the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. - * - * If CipherSuites is nil, a safe default list is used. The default cipher - * suites might change over time. - */ - cipherSuites: Array - /** - * PreferServerCipherSuites is a legacy field and has no effect. - * - * It used to control whether the server would follow the client's or the - * server's preference. Servers now select the best mutually supported - * cipher suite based on logic that takes into account inferred client - * hardware, server hardware, and security. - * - * Deprecated: PreferServerCipherSuites is ignored. - */ - preferServerCipherSuites: boolean - /** - * SessionTicketsDisabled may be set to true to disable session ticket and - * PSK (resumption) support. Note that on clients, session ticket support is - * also disabled if ClientSessionCache is nil. - */ - sessionTicketsDisabled: boolean - /** - * SessionTicketKey is used by TLS servers to provide session resumption. - * See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled - * with random data before the first server handshake. - * - * Deprecated: if this field is left at zero, session ticket keys will be - * automatically rotated every day and dropped after seven days. For - * customizing the rotation schedule or synchronizing servers that are - * terminating connections for the same host, use SetSessionTicketKeys. - */ - sessionTicketKey: string - /** - * ClientSessionCache is a cache of ClientSessionState entries for TLS - * session resumption. It is only used by clients. - */ - clientSessionCache: ClientSessionCache - /** - * MinVersion contains the minimum TLS version that is acceptable. - * - * By default, TLS 1.2 is currently used as the minimum when acting as a - * client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum - * supported by this package, both as a client and as a server. - * - * The client-side default can temporarily be reverted to TLS 1.0 by - * including the value "x509sha1=1" in the GODEBUG environment variable. - * Note that this option will be removed in Go 1.19 (but it will still be - * possible to set this field to VersionTLS10 explicitly). - */ - minVersion: number - /** - * MaxVersion contains the maximum TLS version that is acceptable. - * - * By default, the maximum version supported by this package is used, - * which is currently TLS 1.3. - */ - maxVersion: number - /** - * CurvePreferences contains the elliptic curves that will be used in - * an ECDHE handshake, in preference order. If empty, the default will - * be used. The client will use the first preference as the type for - * its key share in TLS 1.3. This may change in the future. - */ - curvePreferences: Array - /** - * DynamicRecordSizingDisabled disables adaptive sizing of TLS records. - * When true, the largest possible TLS record size is always used. When - * false, the size of TLS records may be adjusted in an attempt to - * improve latency. - */ - dynamicRecordSizingDisabled: boolean - /** - * Renegotiation controls what types of renegotiation are supported. - * The default, none, is correct for the vast majority of applications. - */ - renegotiation: RenegotiationSupport - /** - * KeyLogWriter optionally specifies a destination for TLS master secrets - * in NSS key log format that can be used to allow external programs - * such as Wireshark to decrypt TLS connections. - * See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. - * Use of KeyLogWriter compromises security and should only be - * used for debugging. - */ - keyLogWriter: io.Writer - } - interface Config { - /** - * Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is - * being used concurrently by a TLS client or server. - */ - clone(): (Config | undefined) - } - interface Config { - /** - * SetSessionTicketKeys updates the session ticket keys for a server. - * - * The first key will be used when creating new tickets, while all keys can be - * used for decrypting tickets. It is safe to call this function while the - * server is running in order to rotate the session ticket keys. The function - * will panic if keys is empty. - * - * Calling this function will turn off automatic session ticket key rotation. - * - * If multiple servers are terminating connections for the same host they should - * all have the same session ticket keys. If the session ticket keys leaks, - * previously recorded and future TLS connections using those keys might be - * compromised. - */ - setSessionTicketKeys(keys: Array): void - } - interface ClientHelloInfo { - /** - * SupportsCertificate returns nil if the provided certificate is supported by - * the client that sent the ClientHello. Otherwise, it returns an error - * describing the reason for the incompatibility. - * - * If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate - * callback, this method will take into account the associated Config. Note that - * if GetConfigForClient returns a different Config, the change can't be - * accounted for by this method. - * - * This function will call x509.ParseCertificate unless c.Leaf is set, which can - * incur a significant performance cost. - */ - supportsCertificate(c: Certificate): void - } - interface Config { - /** - * BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate - * from the CommonName and SubjectAlternateName fields of each of the leaf - * certificates. - * - * Deprecated: NameToCertificate only allows associating a single certificate - * with a given name. Leave that field nil to let the library select the first - * compatible chain from Certificates. - */ - buildNameToCertificate(): void - } - /** - * A Certificate is a chain of one or more certificates, leaf first. - */ - interface Certificate { - certificate: Array - /** - * PrivateKey contains the private key corresponding to the public key in - * Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey. - * For a server up to TLS 1.2, it can also implement crypto.Decrypter with - * an RSA PublicKey. - */ - privateKey: crypto.PrivateKey - /** - * SupportedSignatureAlgorithms is an optional list restricting what - * signature algorithms the PrivateKey can be used for. - */ - supportedSignatureAlgorithms: Array - /** - * OCSPStaple contains an optional OCSP response which will be served - * to clients that request it. - */ - ocspStaple: string - /** - * SignedCertificateTimestamps contains an optional list of Signed - * Certificate Timestamps which will be served to clients that request it. - */ - signedCertificateTimestamps: Array - /** - * Leaf is the parsed form of the leaf certificate, which may be initialized - * using x509.ParseCertificate to reduce per-handshake processing. If nil, - * the leaf certificate will be parsed as needed. - */ - leaf?: x509.Certificate - } -} - -/** - * Package encoding defines interfaces shared by other packages that - * convert data to and from byte-level and textual representations. - * Packages that check for these interfaces include encoding/gob, - * encoding/json, and encoding/xml. As a result, implementing an - * interface once can make a type useful in multiple encodings. - * Standard types that implement these interfaces include time.Time and net.IP. - * The interfaces come in pairs that produce and consume encoded data. - */ -namespace encoding { - /** - * TextMarshaler is the interface implemented by an object that can - * marshal itself into a textual form. - * - * MarshalText encodes the receiver into UTF-8-encoded text and returns the result. - */ - interface TextMarshaler { - marshalText(): string - } - /** - * TextUnmarshaler is the interface implemented by an object that can - * unmarshal a textual representation of itself. - * - * UnmarshalText must be able to decode the form generated by MarshalText. - * UnmarshalText must copy the text if it wishes to retain the text - * after returning. - */ - interface TextUnmarshaler { - unmarshalText(text: string): void - } -} - /** * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer * object, creating another object (Reader or Writer) that also implements @@ -19720,8 +19772,7 @@ namespace bufio { * The bytes are taken from at most one Read on the underlying Reader, * hence n may be less than len(p). * To read exactly len(p) bytes, use io.ReadFull(b, p). - * If the underlying Reader can return a non-zero count with io.EOF, - * then this Read method can do so as well; see the [io.Reader] docs. + * At EOF, the count will be zero and err will be io.EOF. */ read(p: string): number } @@ -19929,289 +19980,249 @@ namespace bufio { } /** - * Package log implements a simple logging package. It defines a type, Logger, - * with methods for formatting output. It also has a predefined 'standard' - * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and - * Panic[f|ln], which are easier to use than creating a Logger manually. - * That logger writes to standard error and prints the date and time - * of each logged message. - * Every log message is output on a separate line: if the message being - * printed does not end in a newline, the logger will add one. - * The Fatal functions call os.Exit(1) after writing the log message. - * The Panic functions call panic after writing the log message. + * Package asn1 implements parsing of DER-encoded ASN.1 data structures, + * as defined in ITU-T Rec X.690. + * + * See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' + * http://luca.ntop.org/Teaching/Appunti/asn1.html. */ -namespace log { +namespace asn1 { /** - * A Logger represents an active logging object that generates lines of - * output to an io.Writer. Each logging operation makes a single call to - * the Writer's Write method. A Logger can be used simultaneously from - * multiple goroutines; it guarantees to serialize access to the Writer. + * An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. */ - interface Logger { - } - interface Logger { + interface ObjectIdentifier extends Array{} + interface ObjectIdentifier { /** - * SetOutput sets the output destination for the logger. + * Equal reports whether oi and other represent the same identifier. */ - setOutput(w: io.Writer): void + equal(other: ObjectIdentifier): boolean } - interface Logger { - /** - * Output writes the output for a logging event. The string s contains - * the text to print after the prefix specified by the flags of the - * Logger. A newline is appended if the last character of s is not - * already a newline. Calldepth is used to recover the PC and is - * provided for generality, although at the moment on all pre-defined - * paths it will be 2. - */ - output(calldepth: number, s: string): void - } - interface Logger { - /** - * Printf calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Printf. - */ - printf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Print calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Print. - */ - print(...v: any[]): void - } - interface Logger { - /** - * Println calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Println. - */ - println(...v: any[]): void - } - interface Logger { - /** - * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). - */ - fatal(...v: any[]): void - } - interface Logger { - /** - * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). - */ - fatalf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). - */ - fatalln(...v: any[]): void - } - interface Logger { - /** - * Panic is equivalent to l.Print() followed by a call to panic(). - */ - panic(...v: any[]): void - } - interface Logger { - /** - * Panicf is equivalent to l.Printf() followed by a call to panic(). - */ - panicf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Panicln is equivalent to l.Println() followed by a call to panic(). - */ - panicln(...v: any[]): void - } - interface Logger { - /** - * Flags returns the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. - */ - flags(): number - } - interface Logger { - /** - * SetFlags sets the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. - */ - setFlags(flag: number): void - } - interface Logger { - /** - * Prefix returns the output prefix for the logger. - */ - prefix(): string - } - interface Logger { - /** - * SetPrefix sets the output prefix for the logger. - */ - setPrefix(prefix: string): void - } - interface Logger { - /** - * Writer returns the output destination for the logger. - */ - writer(): io.Writer + interface ObjectIdentifier { + string(): string } } /** - * 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. + * Package pkix contains shared, low level structures used for ASN.1 parsing + * and serialization of X.509 certificates, CRL and OCSP. */ -namespace http { - // @ts-ignore - import mathrand = rand - // @ts-ignore - import urlpkg = url +namespace pkix { /** - * A Handler responds to an HTTP request. - * - * ServeHTTP should write reply headers and data to the ResponseWriter - * and then return. Returning signals that the request is finished; it - * is not valid to use the ResponseWriter or read from the - * Request.Body after or concurrently with the completion of the - * ServeHTTP call. - * - * Depending on the HTTP client software, HTTP protocol version, and - * any intermediaries between the client and the Go server, it may not - * be possible to read from the Request.Body after writing to the - * ResponseWriter. Cautious handlers should read the Request.Body - * first, and then reply. - * - * Except for reading the body, handlers should not modify the - * provided Request. - * - * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes - * that the effect of the panic was isolated to the active request. - * It recovers the panic, logs a stack trace to the server error log, - * and either closes the network connection or sends an HTTP/2 - * RST_STREAM, depending on the HTTP protocol. To abort a handler so - * the client sees an interrupted response but the server doesn't log - * an error, panic with the value ErrAbortHandler. + * Extension represents the ASN.1 structure of the same name. See RFC + * 5280, section 4.2. */ - interface Handler { - serveHTTP(_arg0: ResponseWriter, _arg1: Request): void + interface Extension { + id: asn1.ObjectIdentifier + critical: boolean + value: string } /** - * A ConnState represents the state of a client connection to a server. - * It's used by the optional Server.ConnState hook. + * Name represents an X.509 distinguished name. This only includes the common + * elements of a DN. Note that Name is only an approximation of the X.509 + * structure. If an accurate representation is needed, asn1.Unmarshal the raw + * subject or issuer as an RDNSequence. */ - interface ConnState extends Number{} - interface ConnState { + interface Name { + country: Array + locality: Array + streetAddress: Array + serialNumber: string + /** + * Names contains all parsed attributes. When parsing distinguished names, + * this can be used to extract non-standard attributes that are not parsed + * by this package. When marshaling to RDNSequences, the Names field is + * ignored, see ExtraNames. + */ + names: Array + /** + * ExtraNames contains attributes to be copied, raw, into any marshaled + * distinguished names. Values override any attributes with the same OID. + * The ExtraNames field is not populated when parsing, see Names. + */ + extraNames: Array + } + interface Name { + /** + * FillFromRDNSequence populates n from the provided RDNSequence. + * Multi-entry RDNs are flattened, all entries are added to the + * relevant n fields, and the grouping is not preserved. + */ + fillFromRDNSequence(rdns: RDNSequence): void + } + interface Name { + /** + * ToRDNSequence converts n into a single RDNSequence. The following + * attributes are encoded as multi-value RDNs: + * + * - Country + * - Organization + * - OrganizationalUnit + * - Locality + * - Province + * - StreetAddress + * - PostalCode + * + * Each ExtraNames entry is encoded as an individual RDN. + */ + toRDNSequence(): RDNSequence + } + interface Name { + /** + * String returns the string form of n, roughly following + * the RFC 2253 Distinguished Names syntax. + */ + string(): string + } + /** + * CertificateList represents the ASN.1 structure of the same name. See RFC + * 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the + * signature. + */ + interface CertificateList { + tbsCertList: TBSCertificateList + signatureAlgorithm: AlgorithmIdentifier + signatureValue: asn1.BitString + } + interface CertificateList { + /** + * HasExpired reports whether certList should have been updated by now. + */ + hasExpired(now: time.Time): boolean + } + /** + * RevokedCertificate represents the ASN.1 structure of the same name. See RFC + * 5280, section 5.1. + */ + interface RevokedCertificate { + serialNumber?: big.Int + revocationTime: time.Time + extensions: Array + } +} + +/** + * Copyright 2021 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +/** + * Package x509 parses X.509-encoded keys and certificates. + */ +namespace x509 { + // @ts-ignore + import cryptobyte_asn1 = asn1 + /** + * VerifyOptions contains parameters for Certificate.Verify. + */ + interface VerifyOptions { + /** + * DNSName, if set, is checked against the leaf certificate with + * Certificate.VerifyHostname or the platform verifier. + */ + dnsName: string + /** + * Intermediates is an optional pool of certificates that are not trust + * anchors, but can be used to form a chain from the leaf certificate to a + * root certificate. + */ + intermediates?: CertPool + /** + * Roots is the set of trusted root certificates the leaf certificate needs + * to chain up to. If nil, the system roots or the platform verifier are used. + */ + roots?: CertPool + /** + * CurrentTime is used to check the validity of all certificates in the + * chain. If zero, the current time is used. + */ + currentTime: time.Time + /** + * KeyUsages specifies which Extended Key Usage values are acceptable. A + * chain is accepted if it allows any of the listed values. An empty list + * means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny. + */ + keyUsages: Array + /** + * MaxConstraintComparisions is the maximum number of comparisons to + * perform when checking a given certificate's name constraints. If + * zero, a sensible default is used. This limit prevents pathological + * certificates from consuming excessive amounts of CPU time when + * validating. It does not apply to the platform verifier. + */ + maxConstraintComparisions: number + } + interface SignatureAlgorithm extends Number{} + interface SignatureAlgorithm { + string(): string + } + interface PublicKeyAlgorithm extends Number{} + interface PublicKeyAlgorithm { + string(): string + } + /** + * KeyUsage represents the set of actions that are valid for a given key. It's + * a bitmap of the KeyUsage* constants. + */ + interface KeyUsage extends Number{} + /** + * ExtKeyUsage represents an extended set of actions that are valid for a given key. + * Each of the ExtKeyUsage* constants define a unique action. + */ + interface ExtKeyUsage extends Number{} +} + +/** + * Package mail implements parsing of mail messages. + * + * For the most part, this package follows the syntax as specified by RFC 5322 and + * extended by RFC 6532. + * Notable divergences: + * ``` + * * Obsolete address formats are not parsed, including addresses with + * embedded route information. + * * The full range of spacing (the CFWS syntax element) is not supported, + * such as breaking addresses across lines. + * * No unicode normalization is performed. + * * The special characters ()[]:;@\, are allowed to appear unquoted in names. + * ``` + */ +namespace mail { + /** + * Address represents a single mail address. + * An address such as "Barry Gibbs " is represented + * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. + */ + interface Address { + name: string // Proper name; may be empty. + address: string // user@domain + } + interface Address { + /** + * String formats the address as a valid RFC 5322 address. + * If the address's name contains non-ASCII characters + * the name will be rendered according to RFC 2047. + */ + string(): string + } +} + +/** + * Package tls partially implements TLS 1.2, as specified in RFC 5246, + * and TLS 1.3, as specified in RFC 8446. + */ +namespace tls { + /** + * ClientSessionState contains the state needed by clients to resume TLS + * sessions. + */ + interface ClientSessionState { + } + /** + * SignatureScheme identifies a signature algorithm supported by TLS. See + * RFC 8446, Section 4.2.3. + */ + interface SignatureScheme extends Number{} + interface SignatureScheme { string(): string } } @@ -20641,6 +20652,94 @@ namespace acme { } } +/** + * ``` + * Package flag implements command-line flag parsing. + * + * Usage + * + * Define flags using flag.String(), Bool(), Int(), etc. + * + * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: + * import "flag" + * var nFlag = flag.Int("n", 1234, "help message for flag n") + * If you like, you can bind the flag to a variable using the Var() functions. + * var flagvar int + * func init() { + * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + * } + * Or you can create custom flags that satisfy the Value interface (with + * pointer receivers) and couple them to flag parsing by + * flag.Var(&flagVal, "name", "help message for flagname") + * For such flags, the default value is just the initial value of the variable. + * + * After all flags are defined, call + * flag.Parse() + * to parse the command line into the defined flags. + * + * Flags may then be used directly. If you're using the flags themselves, + * they are all pointers; if you bind to variables, they're values. + * fmt.Println("ip has value ", *ip) + * fmt.Println("flagvar has value ", flagvar) + * + * After parsing, the arguments following the flags are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * Command line flag syntax + * + * The following forms are permitted: + * + * -flag + * -flag=x + * -flag x // non-boolean flags only + * One or two minus signs may be used; they are equivalent. + * The last form is not permitted for boolean flags because the + * meaning of the command + * cmd -x * + * where * is a Unix shell wildcard, will change if there is a file + * called 0, false, etc. You must use the -flag=false form to turn + * off a boolean flag. + * + * Flag parsing stops just before the first non-flag argument + * ("-" is a non-flag argument) or after the terminator "--". + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags may be: + * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False + * Duration flags accept any input valid for time.ParseDuration. + * + * The default set of command-line flags is controlled by + * top-level functions. The FlagSet type allows one to define + * independent sets of flags, such as to implement subcommands + * in a command-line interface. The methods of FlagSet are + * analogous to the top-level functions for the command-line + * flag set. + * ``` + */ +namespace flag { + /** + * Value is the interface to the dynamic value stored in a flag. + * (The default value is represented as a string.) + * + * If a Value has an IsBoolFlag() bool method returning true, + * the command-line parser makes -name equivalent to -name=true + * rather than using the next command-line argument. + * + * Set is called once, in command line order, for each flag present. + * The flag package may call the String method with a zero-valued receiver, + * such as a nil pointer. + */ + interface Value { + string(): string + set(_arg0: string): void + } + /** + * ErrorHandling defines how FlagSet.Parse behaves if the parse fails. + */ + interface ErrorHandling extends Number{} +} + /** * Package driver defines interfaces to be implemented by database * drivers as used by package sql. @@ -20728,6 +20827,9 @@ namespace driver { } } +namespace subscriptions { +} + /** * Package autocert provides automatic access to certificates from Let's Encrypt * and any other ACME-based CA. @@ -20774,211 +20876,6 @@ namespace autocert { namespace search { } -namespace subscriptions { -} - -/** - * Package mail implements parsing of mail messages. - * - * For the most part, this package follows the syntax as specified by RFC 5322 and - * extended by RFC 6532. - * Notable divergences: - * ``` - * - Obsolete address formats are not parsed, including addresses with - * embedded route information. - * - The full range of spacing (the CFWS syntax element) is not supported, - * such as breaking addresses across lines. - * - No unicode normalization is performed. - * - The special characters ()[]:;@\, are allowed to appear unquoted in names. - * ``` - */ -namespace mail { - /** - * Address represents a single mail address. - * An address such as "Barry Gibbs " is represented - * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. - */ - interface Address { - name: string // Proper name; may be empty. - address: string // user@domain - } - interface Address { - /** - * String formats the address as a valid RFC 5322 address. - * If the address's name contains non-ASCII characters - * the name will be rendered according to RFC 2047. - */ - string(): string - } -} - -/** - * Package flag implements command-line flag parsing. - * - * # Usage - * - * Define flags using flag.String(), Bool(), Int(), etc. - * - * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: - * - * ``` - * import "flag" - * var nFlag = flag.Int("n", 1234, "help message for flag n") - * ``` - * - * If you like, you can bind the flag to a variable using the Var() functions. - * - * ``` - * var flagvar int - * func init() { - * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - * } - * ``` - * - * Or you can create custom flags that satisfy the Value interface (with - * pointer receivers) and couple them to flag parsing by - * - * ``` - * flag.Var(&flagVal, "name", "help message for flagname") - * ``` - * - * For such flags, the default value is just the initial value of the variable. - * - * After all flags are defined, call - * - * ``` - * flag.Parse() - * ``` - * - * to parse the command line into the defined flags. - * - * Flags may then be used directly. If you're using the flags themselves, - * they are all pointers; if you bind to variables, they're values. - * - * ``` - * fmt.Println("ip has value ", *ip) - * fmt.Println("flagvar has value ", flagvar) - * ``` - * - * After parsing, the arguments following the flags are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. - * - * # Command line flag syntax - * - * The following forms are permitted: - * - * ``` - * -flag - * --flag // double dashes are also permitted - * -flag=x - * -flag x // non-boolean flags only - * ``` - * - * One or two dashes may be used; they are equivalent. - * The last form is not permitted for boolean flags because the - * meaning of the command - * - * ``` - * cmd -x * - * ``` - * - * where * is a Unix shell wildcard, will change if there is a file - * called 0, false, etc. You must use the -flag=false form to turn - * off a boolean flag. - * - * Flag parsing stops just before the first non-flag argument - * ("-" is a non-flag argument) or after the terminator "--". - * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags may be: - * - * ``` - * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False - * ``` - * - * Duration flags accept any input valid for time.ParseDuration. - * - * The default set of command-line flags is controlled by - * top-level functions. The FlagSet type allows one to define - * independent sets of flags, such as to implement subcommands - * in a command-line interface. The methods of FlagSet are - * analogous to the top-level functions for the command-line - * flag set. - */ -namespace flag { - /** - * Value is the interface to the dynamic value stored in a flag. - * (The default value is represented as a string.) - * - * If a Value has an IsBoolFlag() bool method returning true, - * the command-line parser makes -name equivalent to -name=true - * rather than using the next command-line argument. - * - * Set is called once, in command line order, for each flag present. - * The flag package may call the String method with a zero-valued receiver, - * such as a nil pointer. - */ - interface Value { - string(): string - set(_arg0: string): void - } - /** - * ErrorHandling defines how FlagSet.Parse behaves if the parse fails. - */ - interface ErrorHandling extends Number{} -} - -/** - * Package crypto collects common cryptographic constants. - */ -namespace crypto { - /** - * PrivateKey represents a private key using an unspecified algorithm. - * - * Although this type is an empty interface for backwards compatibility reasons, - * all private key types in the standard library implement the following interface - * - * ``` - * interface{ - * Public() crypto.PublicKey - * Equal(x crypto.PrivateKey) bool - * } - * ``` - * - * as well as purpose-specific interfaces such as Signer and Decrypter, which - * can be used for increased type safety within applications. - */ - interface PrivateKey extends _TygojaAny{} - /** - * Signer is an interface for an opaque private key that can be used for - * signing operations. For example, an RSA key kept in a hardware module. - */ - interface Signer { - /** - * Public returns the public key corresponding to the opaque, - * private key. - */ - public(): PublicKey - /** - * Sign signs digest with the private key, possibly using entropy from - * rand. For an RSA key, the resulting signature should be either a - * PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA - * key, it should be a DER-serialised, ASN.1 signature structure. - * - * Hash implements the SignerOpts interface and, in most cases, one can - * simply pass in the hash function used as opts. Sign may also attempt - * to type assert opts to other types in order to obtain algorithm - * specific values. See the documentation in each package for details. - * - * Note that when a signature of a hash of a larger message is needed, - * the caller is responsible for hashing the larger message and passing - * the hash (as digest) and the hash function (as opts) to Sign. - */ - sign(rand: io.Reader, digest: string, opts: SignerOpts): string - } -} - /** * Package reflect implements run-time reflection, allowing a program to * manipulate objects with arbitrary types. The typical use is to take a value @@ -21048,8 +20945,8 @@ namespace reflect { * Using == on two Values does not compare the underlying values * they represent. */ - type _subEOrhR = flag - interface Value extends _subEOrhR { + type _subSDNEa = flag + interface Value extends _subSDNEa { } interface Value { /** @@ -21071,8 +20968,7 @@ namespace reflect { interface Value { /** * Bytes returns v's underlying value. - * It panics if v's underlying value is not a slice of bytes or - * an addressable array of bytes. + * It panics if v's underlying value is not a slice of bytes. */ bytes(): string } @@ -21124,7 +21020,7 @@ namespace reflect { interface Value { /** * Cap returns v's capacity. - * It panics if v's Kind is not Array, Chan, Slice or pointer to Array. + * It panics if v's Kind is not Array, Chan, or Slice. */ cap(): number } @@ -21241,11 +21137,9 @@ namespace reflect { /** * Interface returns v's current value as an interface{}. * It is equivalent to: - * * ``` * var i interface{} = (v's underlying value) * ``` - * * It panics if the Value was obtained by accessing * unexported struct fields. */ @@ -21304,7 +21198,7 @@ namespace reflect { interface Value { /** * Len returns v's length. - * It panics if v's Kind is not Array, Chan, Map, Slice, String, or pointer to Array. + * It panics if v's Kind is not Array, Chan, Map, Slice, or String. */ len(): number } @@ -21375,11 +21269,7 @@ namespace reflect { } interface Value { /** - * NumMethod returns the number of methods in the value's method set. - * - * For a non-interface type, it returns the number of exported methods. - * - * For an interface type, it returns the number of exported and unexported methods. + * NumMethod returns the number of exported methods in the value's method set. */ numMethod(): number } @@ -21667,426 +21557,343 @@ namespace reflect { } /** - * Package fmt implements formatted I/O with functions analogous - * to C's printf and scanf. The format 'verbs' are derived from C's but - * are simpler. - * - * # Printing - * - * The verbs: - * - * General: - * * ``` - * %v the value in a default format - * when printing structs, the plus flag (%+v) adds field names - * %#v a Go-syntax representation of the value - * %T a Go-syntax representation of the type of the value - * %% a literal percent sign; consumes no value + * Package fmt implements formatted I/O with functions analogous + * to C's printf and scanf. The format 'verbs' are derived from C's but + * are simpler. + * + * Printing + * + * The verbs: + * + * General: + * %v the value in a default format + * when printing structs, the plus flag (%+v) adds field names + * %#v a Go-syntax representation of the value + * %T a Go-syntax representation of the type of the value + * %% a literal percent sign; consumes no value + * + * Boolean: + * %t the word true or false + * Integer: + * %b base 2 + * %c the character represented by the corresponding Unicode code point + * %d base 10 + * %o base 8 + * %O base 8 with 0o prefix + * %q a single-quoted character literal safely escaped with Go syntax. + * %x base 16, with lower-case letters for a-f + * %X base 16, with upper-case letters for A-F + * %U Unicode format: U+1234; same as "U+%04X" + * Floating-point and complex constituents: + * %b decimalless scientific notation with exponent a power of two, + * in the manner of strconv.FormatFloat with the 'b' format, + * e.g. -123456p-78 + * %e scientific notation, e.g. -1.234456e+78 + * %E scientific notation, e.g. -1.234456E+78 + * %f decimal point but no exponent, e.g. 123.456 + * %F synonym for %f + * %g %e for large exponents, %f otherwise. Precision is discussed below. + * %G %E for large exponents, %F otherwise + * %x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20 + * %X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20 + * String and slice of bytes (treated equivalently with these verbs): + * %s the uninterpreted bytes of the string or slice + * %q a double-quoted string safely escaped with Go syntax + * %x base 16, lower-case, two characters per byte + * %X base 16, upper-case, two characters per byte + * Slice: + * %p address of 0th element in base 16 notation, with leading 0x + * Pointer: + * %p base 16 notation, with leading 0x + * The %b, %d, %o, %x and %X verbs also work with pointers, + * formatting the value exactly as if it were an integer. + * + * The default format for %v is: + * bool: %t + * int, int8 etc.: %d + * uint, uint8 etc.: %d, %#x if printed with %#v + * float32, complex64, etc: %g + * string: %s + * chan: %p + * pointer: %p + * For compound objects, the elements are printed using these rules, recursively, + * laid out like this: + * struct: {field0 field1 ...} + * array, slice: [elem0 elem1 ...] + * maps: map[key1:value1 key2:value2 ...] + * pointer to above: &{}, &[], &map[] + * + * Width is specified by an optional decimal number immediately preceding the verb. + * If absent, the width is whatever is necessary to represent the value. + * Precision is specified after the (optional) width by a period followed by a + * decimal number. If no period is present, a default precision is used. + * A period with no following number specifies a precision of zero. + * Examples: + * %f default width, default precision + * %9f width 9, default precision + * %.2f default width, precision 2 + * %9.2f width 9, precision 2 + * %9.f width 9, precision 0 + * + * Width and precision are measured in units of Unicode code points, + * that is, runes. (This differs from C's printf where the + * units are always measured in bytes.) Either or both of the flags + * may be replaced with the character '*', causing their values to be + * obtained from the next operand (preceding the one to format), + * which must be of type int. + * + * For most values, width is the minimum number of runes to output, + * padding the formatted form with spaces if necessary. + * + * For strings, byte slices and byte arrays, however, precision + * limits the length of the input to be formatted (not the size of + * the output), truncating if necessary. Normally it is measured in + * runes, but for these types when formatted with the %x or %X format + * it is measured in bytes. + * + * For floating-point values, width sets the minimum width of the field and + * precision sets the number of places after the decimal, if appropriate, + * except that for %g/%G precision sets the maximum number of significant + * digits (trailing zeros are removed). For example, given 12.345 the format + * %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f + * and %#g is 6; for %g it is the smallest number of digits necessary to identify + * the value uniquely. + * + * For complex numbers, the width and precision apply to the two + * components independently and the result is parenthesized, so %f applied + * to 1.2+3.4i produces (1.200000+3.400000i). + * + * Other flags: + * + always print a sign for numeric values; + * guarantee ASCII-only output for %q (%+q) + * - pad with spaces on the right rather than the left (left-justify the field) + * # alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), + * 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); + * for %q, print a raw (backquoted) string if strconv.CanBackquote + * returns true; + * always print a decimal point for %e, %E, %f, %F, %g and %G; + * do not remove trailing zeros for %g and %G; + * write e.g. U+0078 'x' if the character is printable for %U (%#U). + * ' ' (space) leave a space for elided sign in numbers (% d); + * put spaces between bytes printing strings or slices in hex (% x, % X) + * 0 pad with leading zeros rather than spaces; + * for numbers, this moves the padding after the sign + * + * Flags are ignored by verbs that do not expect them. + * For example there is no alternate decimal format, so %#d and %d + * behave identically. + * + * For each Printf-like function, there is also a Print function + * that takes no format and is equivalent to saying %v for every + * operand. Another variant Println inserts blanks between + * operands and appends a newline. + * + * Regardless of the verb, if an operand is an interface value, + * the internal concrete value is used, not the interface itself. + * Thus: + * var i interface{} = 23 + * fmt.Printf("%v\n", i) + * will print 23. + * + * Except when printed using the verbs %T and %p, special + * formatting considerations apply for operands that implement + * certain interfaces. In order of application: + * + * 1. If the operand is a reflect.Value, the operand is replaced by the + * concrete value that it holds, and printing continues with the next rule. + * + * 2. If an operand implements the Formatter interface, it will + * be invoked. In this case the interpretation of verbs and flags is + * controlled by that implementation. + * + * 3. If the %v verb is used with the # flag (%#v) and the operand + * implements the GoStringer interface, that will be invoked. + * + * If the format (which is implicitly %v for Println etc.) is valid + * for a string (%s %q %v %x %X), the following two rules apply: + * + * 4. If an operand implements the error interface, the Error method + * will be invoked to convert the object to a string, which will then + * be formatted as required by the verb (if any). + * + * 5. If an operand implements method String() string, that method + * will be invoked to convert the object to a string, which will then + * be formatted as required by the verb (if any). + * + * For compound operands such as slices and structs, the format + * applies to the elements of each operand, recursively, not to the + * operand as a whole. Thus %q will quote each element of a slice + * of strings, and %6.2f will control formatting for each element + * of a floating-point array. + * + * However, when printing a byte slice with a string-like verb + * (%s %q %x %X), it is treated identically to a string, as a single item. + * + * To avoid recursion in cases such as + * type X string + * func (x X) String() string { return Sprintf("<%s>", x) } + * convert the value before recurring: + * func (x X) String() string { return Sprintf("<%s>", string(x)) } + * Infinite recursion can also be triggered by self-referential data + * structures, such as a slice that contains itself as an element, if + * that type has a String method. Such pathologies are rare, however, + * and the package does not protect against them. + * + * When printing a struct, fmt cannot and therefore does not invoke + * formatting methods such as Error or String on unexported fields. + * + * Explicit argument indexes + * + * In Printf, Sprintf, and Fprintf, the default behavior is for each + * formatting verb to format successive arguments passed in the call. + * However, the notation [n] immediately before the verb indicates that the + * nth one-indexed argument is to be formatted instead. The same notation + * before a '*' for a width or precision selects the argument index holding + * the value. After processing a bracketed expression [n], subsequent verbs + * will use arguments n+1, n+2, etc. unless otherwise directed. + * + * For example, + * fmt.Sprintf("%[2]d %[1]d\n", 11, 22) + * will yield "22 11", while + * fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6) + * equivalent to + * fmt.Sprintf("%6.2f", 12.0) + * will yield " 12.00". Because an explicit index affects subsequent verbs, + * this notation can be used to print the same values multiple times + * by resetting the index for the first argument to be repeated: + * fmt.Sprintf("%d %d %#[1]x %#x", 16, 17) + * will yield "16 17 0x10 0x11". + * + * Format errors + * + * If an invalid argument is given for a verb, such as providing + * a string to %d, the generated string will contain a + * description of the problem, as in these examples: + * + * Wrong type or unknown verb: %!verb(type=value) + * Printf("%d", "hi"): %!d(string=hi) + * Too many arguments: %!(EXTRA type=value) + * Printf("hi", "guys"): hi%!(EXTRA string=guys) + * Too few arguments: %!verb(MISSING) + * Printf("hi%d"): hi%!d(MISSING) + * Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC) + * Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi + * Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi + * Invalid or invalid use of argument index: %!(BADINDEX) + * Printf("%*[2]d", 7): %!d(BADINDEX) + * Printf("%.[2]d", 7): %!d(BADINDEX) + * + * All errors begin with the string "%!" followed sometimes + * by a single character (the verb) and end with a parenthesized + * description. + * + * If an Error or String method triggers a panic when called by a + * print routine, the fmt package reformats the error message + * from the panic, decorating it with an indication that it came + * through the fmt package. For example, if a String method + * calls panic("bad"), the resulting formatted message will look + * like + * %!s(PANIC=bad) + * + * The %!s just shows the print verb in use when the failure + * occurred. If the panic is caused by a nil receiver to an Error + * or String method, however, the output is the undecorated + * string, "". + * + * Scanning + * + * An analogous set of functions scans formatted text to yield + * values. Scan, Scanf and Scanln read from os.Stdin; Fscan, + * Fscanf and Fscanln read from a specified io.Reader; Sscan, + * Sscanf and Sscanln read from an argument string. + * + * Scan, Fscan, Sscan treat newlines in the input as spaces. + * + * Scanln, Fscanln and Sscanln stop scanning at a newline and + * require that the items be followed by a newline or EOF. + * + * Scanf, Fscanf, and Sscanf parse the arguments according to a + * format string, analogous to that of Printf. In the text that + * follows, 'space' means any Unicode whitespace character + * except newline. + * + * In the format string, a verb introduced by the % character + * consumes and parses input; these verbs are described in more + * detail below. A character other than %, space, or newline in + * the format consumes exactly that input character, which must + * be present. A newline with zero or more spaces before it in + * the format string consumes zero or more spaces in the input + * followed by a single newline or the end of the input. A space + * following a newline in the format string consumes zero or more + * spaces in the input. Otherwise, any run of one or more spaces + * in the format string consumes as many spaces as possible in + * the input. Unless the run of spaces in the format string + * appears adjacent to a newline, the run must consume at least + * one space from the input or find the end of the input. + * + * The handling of spaces and newlines differs from that of C's + * scanf family: in C, newlines are treated as any other space, + * and it is never an error when a run of spaces in the format + * string finds no spaces to consume in the input. + * + * The verbs behave analogously to those of Printf. + * For example, %x will scan an integer as a hexadecimal number, + * and %v will scan the default representation format for the value. + * The Printf verbs %p and %T and the flags # and + are not implemented. + * For floating-point and complex values, all valid formatting verbs + * (%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept + * both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") + * and digit-separating underscores (for example: "3.14159_26535_89793"). + * + * Input processed by verbs is implicitly space-delimited: the + * implementation of every verb except %c starts by discarding + * leading spaces from the remaining input, and the %s verb + * (and %v reading into a string) stops consuming input at the first + * space or newline character. + * + * The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), + * and 0x (hexadecimal) are accepted when scanning integers + * without a format or with the %v verb, as are digit-separating + * underscores. + * + * Width is interpreted in the input text but there is no + * syntax for scanning with a precision (no %5.2f, just %5f). + * If width is provided, it applies after leading spaces are + * trimmed and specifies the maximum number of runes to read + * to satisfy the verb. For example, + * Sscanf(" 1234567 ", "%5s%d", &s, &i) + * will set s to "12345" and i to 67 while + * Sscanf(" 12 34 567 ", "%5s%d", &s, &i) + * will set s to "12" and i to 34. + * + * In all the scanning functions, a carriage return followed + * immediately by a newline is treated as a plain newline + * (\r\n means the same as \n). + * + * In all the scanning functions, if an operand implements method + * Scan (that is, it implements the Scanner interface) that + * method will be used to scan the text for that operand. Also, + * if the number of arguments scanned is less than the number of + * arguments provided, an error is returned. + * + * All arguments to be scanned must be either pointers to basic + * types or implementations of the Scanner interface. + * + * Like Scanf and Fscanf, Sscanf need not consume its entire input. + * There is no way to recover how much of the input string Sscanf used. + * + * Note: Fscan etc. can read one character (rune) past the input + * they return, which means that a loop calling a scan routine + * may skip some of the input. This is usually a problem only + * when there is no space between input values. If the reader + * provided to Fscan implements ReadRune, that method will be used + * to read characters. If the reader also implements UnreadRune, + * that method will be used to save the character and successive + * calls will not lose data. To attach ReadRune and UnreadRune + * methods to a reader without that capability, use + * bufio.NewReader. * ``` - * - * Boolean: - * - * ``` - * %t the word true or false - * ``` - * - * Integer: - * - * ``` - * %b base 2 - * %c the character represented by the corresponding Unicode code point - * %d base 10 - * %o base 8 - * %O base 8 with 0o prefix - * %q a single-quoted character literal safely escaped with Go syntax. - * %x base 16, with lower-case letters for a-f - * %X base 16, with upper-case letters for A-F - * %U Unicode format: U+1234; same as "U+%04X" - * ``` - * - * Floating-point and complex constituents: - * - * ``` - * %b decimalless scientific notation with exponent a power of two, - * in the manner of strconv.FormatFloat with the 'b' format, - * e.g. -123456p-78 - * %e scientific notation, e.g. -1.234456e+78 - * %E scientific notation, e.g. -1.234456E+78 - * %f decimal point but no exponent, e.g. 123.456 - * %F synonym for %f - * %g %e for large exponents, %f otherwise. Precision is discussed below. - * %G %E for large exponents, %F otherwise - * %x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20 - * %X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20 - * ``` - * - * String and slice of bytes (treated equivalently with these verbs): - * - * ``` - * %s the uninterpreted bytes of the string or slice - * %q a double-quoted string safely escaped with Go syntax - * %x base 16, lower-case, two characters per byte - * %X base 16, upper-case, two characters per byte - * ``` - * - * Slice: - * - * ``` - * %p address of 0th element in base 16 notation, with leading 0x - * ``` - * - * Pointer: - * - * ``` - * %p base 16 notation, with leading 0x - * The %b, %d, %o, %x and %X verbs also work with pointers, - * formatting the value exactly as if it were an integer. - * ``` - * - * The default format for %v is: - * - * ``` - * bool: %t - * int, int8 etc.: %d - * uint, uint8 etc.: %d, %#x if printed with %#v - * float32, complex64, etc: %g - * string: %s - * chan: %p - * pointer: %p - * ``` - * - * For compound objects, the elements are printed using these rules, recursively, - * laid out like this: - * - * ``` - * struct: {field0 field1 ...} - * array, slice: [elem0 elem1 ...] - * maps: map[key1:value1 key2:value2 ...] - * pointer to above: &{}, &[], &map[] - * ``` - * - * Width is specified by an optional decimal number immediately preceding the verb. - * If absent, the width is whatever is necessary to represent the value. - * Precision is specified after the (optional) width by a period followed by a - * decimal number. If no period is present, a default precision is used. - * A period with no following number specifies a precision of zero. - * Examples: - * - * ``` - * %f default width, default precision - * %9f width 9, default precision - * %.2f default width, precision 2 - * %9.2f width 9, precision 2 - * %9.f width 9, precision 0 - * ``` - * - * Width and precision are measured in units of Unicode code points, - * that is, runes. (This differs from C's printf where the - * units are always measured in bytes.) Either or both of the flags - * may be replaced with the character '*', causing their values to be - * obtained from the next operand (preceding the one to format), - * which must be of type int. - * - * For most values, width is the minimum number of runes to output, - * padding the formatted form with spaces if necessary. - * - * For strings, byte slices and byte arrays, however, precision - * limits the length of the input to be formatted (not the size of - * the output), truncating if necessary. Normally it is measured in - * runes, but for these types when formatted with the %x or %X format - * it is measured in bytes. - * - * For floating-point values, width sets the minimum width of the field and - * precision sets the number of places after the decimal, if appropriate, - * except that for %g/%G precision sets the maximum number of significant - * digits (trailing zeros are removed). For example, given 12.345 the format - * %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f - * and %#g is 6; for %g it is the smallest number of digits necessary to identify - * the value uniquely. - * - * For complex numbers, the width and precision apply to the two - * components independently and the result is parenthesized, so %f applied - * to 1.2+3.4i produces (1.200000+3.400000i). - * - * When formatting a single integer code point or a rune string (type []rune) - * with %q, invalid Unicode code points are changed to the Unicode replacement - * character, U+FFFD, as in strconv.QuoteRune. - * - * Other flags: - * - * ``` - * '+' always print a sign for numeric values; - * guarantee ASCII-only output for %q (%+q) - * '-' pad with spaces on the right rather than the left (left-justify the field) - * '#' alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), - * 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); - * for %q, print a raw (backquoted) string if strconv.CanBackquote - * returns true; - * always print a decimal point for %e, %E, %f, %F, %g and %G; - * do not remove trailing zeros for %g and %G; - * write e.g. U+0078 'x' if the character is printable for %U (%#U). - * ' ' (space) leave a space for elided sign in numbers (% d); - * put spaces between bytes printing strings or slices in hex (% x, % X) - * '0' pad with leading zeros rather than spaces; - * for numbers, this moves the padding after the sign; - * ignored for strings, byte slices and byte arrays - * ``` - * - * Flags are ignored by verbs that do not expect them. - * For example there is no alternate decimal format, so %#d and %d - * behave identically. - * - * For each Printf-like function, there is also a Print function - * that takes no format and is equivalent to saying %v for every - * operand. Another variant Println inserts blanks between - * operands and appends a newline. - * - * Regardless of the verb, if an operand is an interface value, - * the internal concrete value is used, not the interface itself. - * Thus: - * - * ``` - * var i interface{} = 23 - * fmt.Printf("%v\n", i) - * ``` - * - * will print 23. - * - * Except when printed using the verbs %T and %p, special - * formatting considerations apply for operands that implement - * certain interfaces. In order of application: - * - * 1. If the operand is a reflect.Value, the operand is replaced by the - * concrete value that it holds, and printing continues with the next rule. - * - * 2. If an operand implements the Formatter interface, it will - * be invoked. In this case the interpretation of verbs and flags is - * controlled by that implementation. - * - * 3. If the %v verb is used with the # flag (%#v) and the operand - * implements the GoStringer interface, that will be invoked. - * - * If the format (which is implicitly %v for Println etc.) is valid - * for a string (%s %q %v %x %X), the following two rules apply: - * - * 4. If an operand implements the error interface, the Error method - * will be invoked to convert the object to a string, which will then - * be formatted as required by the verb (if any). - * - * 5. If an operand implements method String() string, that method - * will be invoked to convert the object to a string, which will then - * be formatted as required by the verb (if any). - * - * For compound operands such as slices and structs, the format - * applies to the elements of each operand, recursively, not to the - * operand as a whole. Thus %q will quote each element of a slice - * of strings, and %6.2f will control formatting for each element - * of a floating-point array. - * - * However, when printing a byte slice with a string-like verb - * (%s %q %x %X), it is treated identically to a string, as a single item. - * - * To avoid recursion in cases such as - * - * ``` - * type X string - * func (x X) String() string { return Sprintf("<%s>", x) } - * ``` - * - * convert the value before recurring: - * - * ``` - * func (x X) String() string { return Sprintf("<%s>", string(x)) } - * ``` - * - * Infinite recursion can also be triggered by self-referential data - * structures, such as a slice that contains itself as an element, if - * that type has a String method. Such pathologies are rare, however, - * and the package does not protect against them. - * - * When printing a struct, fmt cannot and therefore does not invoke - * formatting methods such as Error or String on unexported fields. - * - * # Explicit argument indexes - * - * In Printf, Sprintf, and Fprintf, the default behavior is for each - * formatting verb to format successive arguments passed in the call. - * However, the notation [n] immediately before the verb indicates that the - * nth one-indexed argument is to be formatted instead. The same notation - * before a '*' for a width or precision selects the argument index holding - * the value. After processing a bracketed expression [n], subsequent verbs - * will use arguments n+1, n+2, etc. unless otherwise directed. - * - * For example, - * - * ``` - * fmt.Sprintf("%[2]d %[1]d\n", 11, 22) - * ``` - * - * will yield "22 11", while - * - * ``` - * fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6) - * ``` - * - * equivalent to - * - * ``` - * fmt.Sprintf("%6.2f", 12.0) - * ``` - * - * will yield " 12.00". Because an explicit index affects subsequent verbs, - * this notation can be used to print the same values multiple times - * by resetting the index for the first argument to be repeated: - * - * ``` - * fmt.Sprintf("%d %d %#[1]x %#x", 16, 17) - * ``` - * - * will yield "16 17 0x10 0x11". - * - * # Format errors - * - * If an invalid argument is given for a verb, such as providing - * a string to %d, the generated string will contain a - * description of the problem, as in these examples: - * - * ``` - * Wrong type or unknown verb: %!verb(type=value) - * Printf("%d", "hi"): %!d(string=hi) - * Too many arguments: %!(EXTRA type=value) - * Printf("hi", "guys"): hi%!(EXTRA string=guys) - * Too few arguments: %!verb(MISSING) - * Printf("hi%d"): hi%!d(MISSING) - * Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC) - * Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi - * Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi - * Invalid or invalid use of argument index: %!(BADINDEX) - * Printf("%*[2]d", 7): %!d(BADINDEX) - * Printf("%.[2]d", 7): %!d(BADINDEX) - * ``` - * - * All errors begin with the string "%!" followed sometimes - * by a single character (the verb) and end with a parenthesized - * description. - * - * If an Error or String method triggers a panic when called by a - * print routine, the fmt package reformats the error message - * from the panic, decorating it with an indication that it came - * through the fmt package. For example, if a String method - * calls panic("bad"), the resulting formatted message will look - * like - * - * ``` - * %!s(PANIC=bad) - * ``` - * - * The %!s just shows the print verb in use when the failure - * occurred. If the panic is caused by a nil receiver to an Error - * or String method, however, the output is the undecorated - * string, "". - * - * # Scanning - * - * An analogous set of functions scans formatted text to yield - * values. Scan, Scanf and Scanln read from os.Stdin; Fscan, - * Fscanf and Fscanln read from a specified io.Reader; Sscan, - * Sscanf and Sscanln read from an argument string. - * - * Scan, Fscan, Sscan treat newlines in the input as spaces. - * - * Scanln, Fscanln and Sscanln stop scanning at a newline and - * require that the items be followed by a newline or EOF. - * - * Scanf, Fscanf, and Sscanf parse the arguments according to a - * format string, analogous to that of Printf. In the text that - * follows, 'space' means any Unicode whitespace character - * except newline. - * - * In the format string, a verb introduced by the % character - * consumes and parses input; these verbs are described in more - * detail below. A character other than %, space, or newline in - * the format consumes exactly that input character, which must - * be present. A newline with zero or more spaces before it in - * the format string consumes zero or more spaces in the input - * followed by a single newline or the end of the input. A space - * following a newline in the format string consumes zero or more - * spaces in the input. Otherwise, any run of one or more spaces - * in the format string consumes as many spaces as possible in - * the input. Unless the run of spaces in the format string - * appears adjacent to a newline, the run must consume at least - * one space from the input or find the end of the input. - * - * The handling of spaces and newlines differs from that of C's - * scanf family: in C, newlines are treated as any other space, - * and it is never an error when a run of spaces in the format - * string finds no spaces to consume in the input. - * - * The verbs behave analogously to those of Printf. - * For example, %x will scan an integer as a hexadecimal number, - * and %v will scan the default representation format for the value. - * The Printf verbs %p and %T and the flags # and + are not implemented. - * For floating-point and complex values, all valid formatting verbs - * (%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept - * both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") - * and digit-separating underscores (for example: "3.14159_26535_89793"). - * - * Input processed by verbs is implicitly space-delimited: the - * implementation of every verb except %c starts by discarding - * leading spaces from the remaining input, and the %s verb - * (and %v reading into a string) stops consuming input at the first - * space or newline character. - * - * The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), - * and 0x (hexadecimal) are accepted when scanning integers - * without a format or with the %v verb, as are digit-separating - * underscores. - * - * Width is interpreted in the input text but there is no - * syntax for scanning with a precision (no %5.2f, just %5f). - * If width is provided, it applies after leading spaces are - * trimmed and specifies the maximum number of runes to read - * to satisfy the verb. For example, - * - * ``` - * Sscanf(" 1234567 ", "%5s%d", &s, &i) - * ``` - * - * will set s to "12345" and i to 67 while - * - * ``` - * Sscanf(" 12 34 567 ", "%5s%d", &s, &i) - * ``` - * - * will set s to "12" and i to 34. - * - * In all the scanning functions, a carriage return followed - * immediately by a newline is treated as a plain newline - * (\r\n means the same as \n). - * - * In all the scanning functions, if an operand implements method - * Scan (that is, it implements the Scanner interface) that - * method will be used to scan the text for that operand. Also, - * if the number of arguments scanned is less than the number of - * arguments provided, an error is returned. - * - * All arguments to be scanned must be either pointers to basic - * types or implementations of the Scanner interface. - * - * Like Scanf and Fscanf, Sscanf need not consume its entire input. - * There is no way to recover how much of the input string Sscanf used. - * - * Note: Fscan etc. can read one character (rune) past the input - * they return, which means that a loop calling a scan routine - * may skip some of the input. This is usually a problem only - * when there is no space between input values. If the reader - * provided to Fscan implements ReadRune, that method will be used - * to read characters. If the reader also implements UnreadRune, - * that method will be used to save the character and successive - * calls will not lose data. To attach ReadRune and UnreadRune - * methods to a reader without that capability, use - * bufio.NewReader. */ namespace fmt { /** @@ -22184,9 +21991,7 @@ namespace rand { * To produce a distribution with a different rate parameter, * callers can adjust the output using: * - * ``` - * sample = ExpFloat64() / desiredRateParameter - * ``` + * sample = ExpFloat64() / desiredRateParameter */ expFloat64(): number } @@ -22198,9 +22003,7 @@ namespace rand { * To produce a different normal distribution, callers can * adjust the output using: * - * ``` - * sample = NormFloat64() * desiredStdDev + desiredMean - * ``` + * sample = NormFloat64() * desiredStdDev + desiredMean */ normFloat64(): number } @@ -22427,7 +22230,7 @@ namespace big { * Package asn1 implements parsing of DER-encoded ASN.1 data structures, * as defined in ITU-T Rec X.690. * - * See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” + * See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' * http://luca.ntop.org/Teaching/Appunti/asn1.html. */ namespace asn1 { @@ -22488,8 +22291,6 @@ namespace pkix { /** * TBSCertificateList represents the ASN.1 structure of the same name. See RFC * 5280, section 5.1. - * - * Deprecated: x509.RevocationList should be used instead. */ interface TBSCertificateList { raw: asn1.RawContent @@ -22504,187 +22305,36 @@ namespace pkix { } /** - * Copyright 2021 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. + * Package crypto collects common cryptographic constants. */ -/** - * Package x509 parses X.509-encoded keys and certificates. - */ -namespace x509 { +namespace crypto { /** - * CertPool is a set of certificates. + * Signer is an interface for an opaque private key that can be used for + * signing operations. For example, an RSA key kept in a hardware module. */ - interface CertPool { - } - interface CertPool { + interface Signer { /** - * Clone returns a copy of s. + * Public returns the public key corresponding to the opaque, + * private key. */ - clone(): (CertPool | undefined) - } - interface CertPool { + public(): PublicKey /** - * AddCert adds a certificate to a pool. - */ - addCert(cert: Certificate): void - } - interface CertPool { - /** - * AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. - * It appends any certificates found to s and reports whether any certificates - * were successfully parsed. + * Sign signs digest with the private key, possibly using entropy from + * rand. For an RSA key, the resulting signature should be either a + * PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA + * key, it should be a DER-serialised, ASN.1 signature structure. * - * On many Linux systems, /etc/ssl/cert.pem will contain the system wide set - * of root CAs in a format suitable for this function. - */ - appendCertsFromPEM(pemCerts: string): boolean - } - interface CertPool { - /** - * Subjects returns a list of the DER-encoded subjects of - * all of the certificates in the pool. + * Hash implements the SignerOpts interface and, in most cases, one can + * simply pass in the hash function used as opts. Sign may also attempt + * to type assert opts to other types in order to obtain algorithm + * specific values. See the documentation in each package for details. * - * Deprecated: if s was returned by SystemCertPool, Subjects - * will not include the system roots. + * Note that when a signature of a hash of a larger message is needed, + * the caller is responsible for hashing the larger message and passing + * the hash (as digest) and the hash function (as opts) to Sign. */ - subjects(): Array + sign(rand: io.Reader, digest: string, opts: SignerOpts): string } - interface CertPool { - /** - * Equal reports whether s and other are equal. - */ - equal(other: CertPool): boolean - } - // @ts-ignore - import cryptobyte_asn1 = asn1 -} - -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * CurveID is the type of a TLS identifier for an elliptic curve. See - * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. - * - * In TLS 1.3, this type is called NamedGroup, but at this time this library - * only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7. - */ - interface CurveID extends Number{} - /** - * ClientAuthType declares the policy the server will follow for - * TLS Client Authentication. - */ - interface ClientAuthType extends Number{} - /** - * ClientSessionCache is a cache of ClientSessionState objects that can be used - * by a client to resume a TLS session with a given server. ClientSessionCache - * implementations should expect to be called concurrently from different - * goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not - * SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which - * are supported via this interface. - */ - interface ClientSessionCache { - /** - * Get searches for a ClientSessionState associated with the given key. - * On return, ok is true if one was found. - */ - get(sessionKey: string): [(ClientSessionState | undefined), boolean] - /** - * Put adds the ClientSessionState to the cache with the given key. It might - * get called multiple times in a connection if a TLS 1.3 server provides - * more than one session ticket. If called with a nil *ClientSessionState, - * it should remove the cache entry. - */ - put(sessionKey: string, cs: ClientSessionState): void - } - /** - * SignatureScheme identifies a signature algorithm supported by TLS. See - * RFC 8446, Section 4.2.3. - */ - interface SignatureScheme extends Number{} - /** - * CertificateRequestInfo contains information from a server's - * CertificateRequest message, which is used to demand a certificate and proof - * of control from a client. - */ - interface CertificateRequestInfo { - /** - * AcceptableCAs contains zero or more, DER-encoded, X.501 - * Distinguished Names. These are the names of root or intermediate CAs - * that the server wishes the returned certificate to be signed by. An - * empty slice indicates that the server has no preference. - */ - acceptableCAs: Array - /** - * SignatureSchemes lists the signature schemes that the server is - * willing to verify. - */ - signatureSchemes: Array - /** - * Version is the TLS version that was negotiated for this connection. - */ - version: number - } - interface CertificateRequestInfo { - /** - * Context returns the context of the handshake that is in progress. - * This context is a child of the context passed to HandshakeContext, - * if any, and is canceled when the handshake concludes. - */ - context(): context.Context - } - /** - * RenegotiationSupport enumerates the different levels of support for TLS - * renegotiation. TLS renegotiation is the act of performing subsequent - * handshakes on a connection after the first. This significantly complicates - * the state machine and has been the source of numerous, subtle security - * issues. Initiating a renegotiation is not supported, but support for - * accepting renegotiation requests may be enabled. - * - * Even when enabled, the server may not change its identity between handshakes - * (i.e. the leaf certificate must be the same). Additionally, concurrent - * handshake and application data flow is not permitted so renegotiation can - * only be used with protocols that synchronise with the renegotiation, such as - * HTTPS. - * - * Renegotiation is not defined in TLS 1.3. - */ - interface RenegotiationSupport extends Number{} - interface CertificateRequestInfo { - /** - * SupportsCertificate returns nil if the provided certificate is supported by - * the server that sent the CertificateRequest. Otherwise, it returns an error - * describing the reason for the incompatibility. - */ - supportsCertificate(c: Certificate): void - } - interface SignatureScheme { - string(): string - } - interface CurveID { - string(): string - } - interface ClientAuthType { - string(): string - } -} - -/** - * Package log implements a simple logging package. It defines a type, Logger, - * with methods for formatting output. It also has a predefined 'standard' - * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and - * Panic[f|ln], which are easier to use than creating a Logger manually. - * That logger writes to standard error and prints the date and time - * of each logged message. - * Every log message is output on a separate line: if the message being - * printed does not end in a newline, the logger will add one. - * The Fatal functions call os.Exit(1) after writing the log message. - * The Panic functions call panic after writing the log message. - */ -namespace log { } /** @@ -23097,38 +22747,6 @@ namespace driver { } } -/** - * Package crypto collects common cryptographic constants. - */ -namespace crypto { - /** - * PublicKey represents a public key using an unspecified algorithm. - * - * Although this type is an empty interface for backwards compatibility reasons, - * all public key types in the standard library implement the following interface - * - * ``` - * interface{ - * Equal(x crypto.PublicKey) bool - * } - * ``` - * - * which can be used for increased type safety within applications. - */ - interface PublicKey extends _TygojaAny{} - /** - * SignerOpts contains options for signing with a Signer. - */ - interface SignerOpts { - /** - * HashFunc returns an identifier for the hash function used to produce - * the message passed to Signer.Sign, or else zero to indicate that no - * hashing was done. - */ - hashFunc(): Hash - } -} - /** * Package reflect implements run-time reflection, allowing a program to * manipulate objects with arbitrary types. The typical use is to take a value @@ -23185,7 +22803,7 @@ namespace reflect { * Package asn1 implements parsing of DER-encoded ASN.1 data structures, * as defined in ITU-T Rec X.690. * - * See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” + * See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' * http://luca.ntop.org/Teaching/Appunti/asn1.html. */ namespace asn1 { @@ -23206,6 +22824,38 @@ namespace asn1 { interface RawContent extends String{} } +/** + * Package crypto collects common cryptographic constants. + */ +namespace crypto { + /** + * PublicKey represents a public key using an unspecified algorithm. + * + * Although this type is an empty interface for backwards compatibility reasons, + * all public key types in the standard library implement the following interface + * + * ``` + * interface{ + * Equal(x crypto.PublicKey) bool + * } + * ``` + * + * which can be used for increased type safety within applications. + */ + interface PublicKey extends _TygojaAny{} + /** + * SignerOpts contains options for signing with a Signer. + */ + interface SignerOpts { + /** + * HashFunc returns an identifier for the hash function used to produce + * the message passed to Signer.Sign, or else zero to indicate that no + * hashing was done. + */ + hashFunc(): Hash + } +} + /** * Package pkix contains shared, low level structures used for ASN.1 parsing * and serialization of X.509 certificates, CRL and OCSP. @@ -23214,19 +22864,6 @@ namespace pkix { interface RelativeDistinguishedNameSET extends Array{} } -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * ClientSessionState contains the state needed by clients to resume TLS - * sessions. - */ - interface ClientSessionState { - } -} - /** * Package acme provides an implementation of the * Automatic Certificate Management Environment (ACME) spec, diff --git a/plugins/jsvm/internal/docs/docs.go b/plugins/jsvm/internal/types/types.go similarity index 97% rename from plugins/jsvm/internal/docs/docs.go rename to plugins/jsvm/internal/types/types.go index 2d109df5..07500293 100644 --- a/plugins/jsvm/internal/docs/docs.go +++ b/plugins/jsvm/internal/types/types.go @@ -29,7 +29,7 @@ const heading = ` * * ` + "```" + `js * // prints "Hello world!" on every 30 minutes - * cronAdd("hello", "*/30 * * * *", (c) => { + * cronAdd("hello", "*\/30 * * * *", (c) => { * console.log("Hello world!") * }) * ` + "```" + ` @@ -45,7 +45,7 @@ declare function cronAdd( ): void; /** - * CronRemove removes previously registerd cron job by its name. + * CronRemove removes a single registered cron job by its name. * * Example: * @@ -162,7 +162,7 @@ declare var $app: appWithoutHooks * ` + "```" + `js * const records = arrayOf(new Record) * - * $app.dao().recordQuery(collection).limit(10).all(records) + * $app.dao().recordQuery("articles").limit(10).all(records) * ` + "```" + ` * * @group PocketBase @@ -700,13 +700,30 @@ declare namespace $apis { // httpClientBinds // ------------------------------------------------------------------- +/** + * ` + "`" + `$http` + "`" + ` defines common methods for working with HTTP requests. + * + * @group PocketBase + */ declare namespace $http { /** - * Sends a single HTTP request (_currently only json and plain text requests_). + * Sends a single HTTP request. * - * @group PocketBase + * Example: + * + * ` + "```" + `js + * const res = $http.send({ + * url: "https://example.com", + * data: {"title": "test"} + * method: "post", + * }) + * + * console.log(res.statusCode) + * console.log(res.raw) + * console.log(res.json) + * ` + "```" + ` */ - function send(params: { + function send(config: { url: string, method?: string, // default to "GET" data?: { [key:string]: any }, diff --git a/plugins/jsvm/jsvm.go b/plugins/jsvm/jsvm.go index 0ace4b3a..d965ef67 100644 --- a/plugins/jsvm/jsvm.go +++ b/plugins/jsvm/jsvm.go @@ -25,7 +25,7 @@ import ( "github.com/pocketbase/dbx" "github.com/pocketbase/pocketbase/core" m "github.com/pocketbase/pocketbase/migrations" - "github.com/pocketbase/pocketbase/plugins/jsvm/internal/docs/generated" + "github.com/pocketbase/pocketbase/plugins/jsvm/internal/types/generated" ) const ( diff --git a/tools/hook/hook.go b/tools/hook/hook.go index c1acc033..eb6780ee 100644 --- a/tools/hook/hook.go +++ b/tools/hook/hook.go @@ -57,7 +57,6 @@ func (h *Hook[T]) Add(fn Handler[T]) string { return id } -// @todo add also to TaggedHook // Remove removes a single hook handler by its id. func (h *Hook[T]) Remove(id string) { h.mux.Lock() @@ -71,7 +70,6 @@ func (h *Hook[T]) Remove(id string) { } } -// @todo add also to TaggedHook // RemoveAll removes all registered handlers. func (h *Hook[T]) RemoveAll() { h.mux.Lock()