diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 8b3568a8d..588c29ab7 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 999893662..fa2dbf6b9 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 0dc94032d..5418e1a3a 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 3afc13edc..f523ce545 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 fbb979e73..e9db5775c 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 e5f504dfb..2bc884fad 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,8543 +4956,8267 @@ 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. + * 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 FileHeader { - filename: string - header: textproto.MIMEHeader - size: number - } - interface FileHeader { + interface FS { /** - * Open opens and returns the FileHeader's associated File. + * 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(): File + open(name: string): 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. + * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. + * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. */ -namespace 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 { +namespace cobra { + interface Command { /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * GenBashCompletion generates bash completion file and writes to the passed writer. */ - verifyAudience(cmp: string, req: boolean): boolean + genBashCompletion(w: io.Writer): void } - interface MapClaims { + interface Command { /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. + * GenBashCompletionFile generates bash completion file. */ - verifyExpiresAt(cmp: number, req: boolean): boolean + genBashCompletionFile(filename: string): void } - interface MapClaims { + interface Command { /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. + * GenBashCompletionFileV2 generates Bash completion version 2. */ - verifyIssuedAt(cmp: number, req: boolean): boolean + genBashCompletionFileV2(filename: string, includeDesc: boolean): void } - interface MapClaims { + interface Command { /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. + * GenBashCompletionV2 generates Bash completion file version 2 + * and writes it to the passed writer. */ - verifyNotBefore(cmp: number, req: boolean): boolean + genBashCompletionV2(w: io.Writer, includeDesc: boolean): void } - interface MapClaims { + // @ts-ignore + import flag = pflag + /** + * Command is just that, a command for your application. + * E.g. 'go run ...' - 'run' is the command. Cobra requires + * you to define the usage and description as part of your command + * definition to ensure usability. + */ + interface Command { /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * Use is the one-line usage message. + * Recommended syntax is as follows: + * ``` + * [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. + * ... indicates that you can specify multiple values for the previous argument. + * | indicates mutually exclusive information. You can use the argument to the left of the separator or the + * argument to the right of the separator. You cannot use both arguments in a single use of the command. + * { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are + * optional, they are enclosed in brackets ([ ]). + * ``` + * Example: add [-F file | -D dir]... [-f format] profile */ - verifyIssuer(cmp: string, req: boolean): boolean - } - interface MapClaims { + use: string /** - * 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. + * Aliases is an array of aliases that can be used instead of the first word in Use. */ - 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. - * - * 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 { + aliases: Array /** - * 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. + * SuggestFor is an array of command names for which this command will be suggested - + * similar to aliases but only suggests. */ - method: string + suggestFor: Array /** - * 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. + * Short is the short description shown in the 'help' output. */ - url?: url.URL + short: string /** - * 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. + * The group id under which this subcommand is grouped in the 'help' output of its parent. */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 + groupID: string /** - * 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. + * Long is the long message shown in the 'help ' output. */ - header: Header + long: string /** - * 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. + * Example is examples of how to use the command. */ - body: io.ReadCloser + example: string /** - * 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. + * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions */ - getBody: () => io.ReadCloser + validArgs: Array /** - * 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. + * ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. + * It is a dynamic version of using ValidArgs. + * Only one of ValidArgs and ValidArgsFunction can be used for a command. */ - contentLength: number + validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] /** - * 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. + * Expected arguments */ - transferEncoding: Array + args: PositionalArgs /** - * 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. + * ArgAliases is List of aliases for ValidArgs. + * These are not suggested to the user in the shell completion, + * but accepted if entered manually. */ - close: boolean + argAliases: Array /** - * 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. + * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + * For portability with other shells, it is recommended to instead use ValidArgsFunction */ - host: string + bashCompletionFunction: 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. + * Deprecated defines, if this command is deprecated and should print this string when used. */ - form: url.Values + deprecated: string /** - * 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. + * Annotations are key/value pairs that can be used by applications to identify or + * group commands. */ - postForm: url.Values + annotations: _TygojaDict /** - * 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. + * Version defines the version for this command. If this value is non-empty and the command does not + * define a "version" flag, a "version" boolean flag will be added to the command and, if specified, + * will print content of the "Version" variable. A shorthand "v" flag will also be added if the + * command does not define one. */ - multipartForm?: multipart.Form + version: string /** - * 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. + * The *Run functions are executed in the following order: + * ``` + * * PersistentPreRun() + * * PreRun() + * * Run() + * * PostRun() + * * PersistentPostRun() + * ``` + * All functions get the same args, the arguments after the command name. * - * Few HTTP clients, servers, or proxies support HTTP trailers. + * PersistentPreRun: children of this command will inherit and execute. */ - trailer: Header + persistentPreRun: (cmd: Command, args: Array) => void /** - * 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. + * PersistentPreRunE: PersistentPreRun but returns an error. */ - remoteAddr: string + persistentPreRunE: (cmd: Command, args: Array) => void /** - * 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. + * PreRun: children of this command will not inherit. */ - requestURI: string + preRun: (cmd: Command, args: Array) => void /** - * 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. + * PreRunE: PreRun but returns an error. */ - tls?: tls.ConnectionState + preRunE: (cmd: Command, args: Array) => void /** - * 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. + * Run: Typically the actual work function. Most commands will only implement this. */ - cancel: undefined + run: (cmd: Command, args: Array) => void /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. + * RunE: Run but returns an error. */ - response?: Response - } - interface Request { + runE: (cmd: Command, args: Array) => void /** - * 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. + * PostRun: run after the Run command. */ - context(): context.Context - } - interface Request { + postRun: (cmd: Command, args: Array) => void /** - * 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. + * PostRunE: PostRun but returns an error. */ - withContext(ctx: context.Context): (Request | undefined) + postRunE: (cmd: Command, args: Array) => void + /** + * PersistentPostRun: children of this command will inherit and execute after PostRun. + */ + persistentPostRun: (cmd: Command, args: Array) => void + /** + * PersistentPostRunE: PersistentPostRun but returns an error. + */ + persistentPostRunE: (cmd: Command, args: Array) => void + /** + * FParseErrWhitelist flag parse errors to be ignored + */ + fParseErrWhitelist: FParseErrWhitelist + /** + * CompletionOptions is a set of options to control the handling of shell completion + */ + completionOptions: CompletionOptions + /** + * TraverseChildren parses flags on all parents before executing child command. + */ + traverseChildren: boolean + /** + * Hidden defines, if this command is hidden and should NOT show up in the list of available commands. + */ + hidden: boolean + /** + * SilenceErrors is an option to quiet errors down stream. + */ + silenceErrors: boolean + /** + * SilenceUsage is an option to silence usage when an error occurs. + */ + silenceUsage: boolean + /** + * DisableFlagParsing disables the flag parsing. + * If this is true all flags will be passed to the command as arguments. + */ + disableFlagParsing: boolean + /** + * DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") + * will be printed by generating docs for this command. + */ + disableAutoGenTag: boolean + /** + * DisableFlagsInUseLine will disable the addition of [flags] to the usage + * line of a command when printing help or generating docs + */ + disableFlagsInUseLine: boolean + /** + * DisableSuggestions disables the suggestions based on Levenshtein distance + * that go along with 'unknown command' messages. + */ + disableSuggestions: boolean + /** + * SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. + * Must be > 0. + */ + suggestionsMinimumDistance: number } - interface Request { + interface Command { /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. + * Context returns underlying command context. If command was executed + * with ExecuteContext or the context was set with SetContext, the + * previously set context will be returned. Otherwise, nil is returned. * - * 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. + * Notice that a call to Execute and ExecuteC will replace a nil context of + * a command with a context.Background, so a background context will be + * returned by Context after one of these functions has been called. */ - clone(ctx: context.Context): (Request | undefined) + context(): context.Context } - interface Request { + interface Command { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * SetContext sets context for the command. This context will be overwritten by + * Command.ExecuteContext or Command.ExecuteContextC. */ - protoAtLeast(major: number): boolean + setContext(ctx: context.Context): void } - interface Request { + interface Command { /** - * UserAgent returns the client's User-Agent, if sent in the request. + * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden + * particularly useful when testing. */ - userAgent(): string + setArgs(a: Array): void } - interface Request { + interface Command { /** - * Cookies parses and returns the HTTP cookies sent with the request. + * SetOutput sets the destination for usage and error messages. + * If output is nil, os.Stderr is used. + * Deprecated: Use SetOut and/or SetErr instead */ - cookies(): Array<(Cookie | undefined)> + setOutput(output: io.Writer): void } - interface Request { + interface Command { /** - * 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. + * SetOut sets the destination for usage messages. + * If newOut is nil, os.Stdout is used. */ - cookie(name: string): (Cookie | undefined) + setOut(newOut: io.Writer): void } - interface Request { + interface Command { /** - * 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. + * SetErr sets the destination for error messages. + * If newErr is nil, os.Stderr is used. */ - addCookie(c: Cookie): void + setErr(newErr: io.Writer): void } - interface Request { + interface Command { /** - * 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"]. + * SetIn sets the source for input data + * If newIn is nil, os.Stdin is used. */ - referer(): string + setIn(newIn: io.Reader): void } - interface Request { + interface Command { /** - * 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. + * SetUsageFunc sets usage function. Usage can be defined by application. */ - multipartReader(): (multipart.Reader | undefined) + setUsageFunc(f: (_arg0: Command) => void): void } - interface Request { + interface Command { /** - * 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. + * SetUsageTemplate sets usage template. Can be defined by Application. */ - write(w: io.Writer): void + setUsageTemplate(s: string): void } - interface Request { + interface Command { /** - * 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. + * SetFlagErrorFunc sets a function to generate an error when flag parsing + * fails. */ - writeProxy(w: io.Writer): void + setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void } - interface Request { + interface Command { /** - * 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. + * SetHelpFunc sets help function. Can be defined by Application. */ - basicAuth(): [string, boolean] + setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void } - interface Request { + interface Command { /** - * 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. + * SetHelpCommand sets help command. */ - setBasicAuth(username: string): void + setHelpCommand(cmd: Command): void } - interface Request { + interface Command { /** - * 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. + * SetHelpCommandGroupID sets the group id of the help command. */ - parseForm(): void + setHelpCommandGroupID(groupID: string): void } - interface Request { + interface Command { /** - * 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. + * SetCompletionCommandGroupID sets the group id of the completion command. */ - parseMultipartForm(maxMemory: number): void + setCompletionCommandGroupID(groupID: string): void } - interface Request { + interface Command { /** - * 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. + * SetHelpTemplate sets help template to be used. Application can use it to set custom template. */ - formValue(key: string): string + setHelpTemplate(s: string): void } - interface Request { + interface Command { /** - * 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. + * SetVersionTemplate sets version template to be used. Application can use it to set custom template. */ - postFormValue(key: string): string + setVersionTemplate(s: string): void } - interface Request { + interface Command { /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. + * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. + * The user should not have a cyclic dependency on commands. */ - formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] + setGlobalNormalizationFunc(n: (f: flag.FlagSet, name: string) => flag.NormalizedName): void } - /** - * 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 { + interface Command { /** - * 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. + * OutOrStdout returns output to stdout. */ - header(): Header + outOrStdout(): io.Writer + } + interface Command { /** - * 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. + * OutOrStderr returns output to stderr */ - write(_arg0: string): number + outOrStderr(): io.Writer + } + interface Command { /** - * 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. + * ErrOrStderr returns output to stderr */ - 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 + errOrStderr(): io.Writer } - /** - * Provider defines a common interface for an OAuth2 client. - */ - interface Provider { + interface Command { /** - * Scopes returns the context associated with the provider (if any). + * InOrStdin returns input to stdin */ - context(): context.Context + inOrStdin(): io.Reader + } + interface Command { /** - * SetContext assigns the specified context to the current provider. + * UsageFunc returns either the function set by SetUsageFunc for this command + * or a parent, or it returns a default usage function. */ - setContext(ctx: context.Context): void + usageFunc(): (_arg0: Command) => void + } + interface Command { /** - * Scopes returns the provider access permissions that will be requested. + * Usage puts out the usage for the command. + * Used when a user provides invalid input. + * Can be defined by user by overriding UsageFunc. */ - scopes(): Array + usage(): void + } + interface Command { /** - * SetScopes sets the provider access permissions that will be requested later. + * HelpFunc returns either the function set by SetHelpFunc for this command + * or a parent, or it returns a function with default help behavior. */ - setScopes(scopes: Array): void + helpFunc(): (_arg0: Command, _arg1: Array) => void + } + interface Command { /** - * ClientId returns the provider client's app ID. + * Help puts out the help for the command. + * Used when a user calls help [command]. + * Can be defined by user by overriding HelpFunc. */ - clientId(): string + help(): void + } + interface Command { /** - * SetClientId sets the provider client's ID. + * UsageString returns usage string. */ - setClientId(clientId: string): void + usageString(): string + } + interface Command { /** - * ClientSecret returns the provider client's app secret. + * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this + * command or a parent, or it returns a function which returns the original + * error. */ - clientSecret(): string + flagErrorFunc(): (_arg0: Command, _arg1: Error) => void + } + interface Command { /** - * SetClientSecret sets the provider client's app secret. + * UsagePadding return padding for the usage. */ - setClientSecret(secret: string): void + usagePadding(): number + } + interface Command { /** - * RedirectUrl returns the end address to redirect the user - * going through the OAuth flow. + * CommandPathPadding return padding for the command path. */ - redirectUrl(): string + commandPathPadding(): number + } + interface Command { /** - * SetRedirectUrl sets the provider's RedirectUrl. + * NamePadding returns padding for the name. */ - setRedirectUrl(url: string): void + namePadding(): number + } + interface Command { /** - * AuthUrl returns the provider's authorization service url. + * UsageTemplate returns usage template for the command. */ - authUrl(): string + usageTemplate(): string + } + interface Command { /** - * SetAuthUrl sets the provider's AuthUrl. + * HelpTemplate return help template for the command. */ - setAuthUrl(url: string): void + helpTemplate(): string + } + interface Command { /** - * TokenUrl returns the provider's token exchange service url. + * VersionTemplate return version template for the command. */ - tokenUrl(): string + versionTemplate(): string + } + interface Command { /** - * SetTokenUrl sets the provider's TokenUrl. + * Find the target command given the args and command tree + * Meant to be run on the highest node. Only searches down. */ - setTokenUrl(url: string): void + find(args: Array): [(Command | undefined), Array] + } + interface Command { /** - * UserApiUrl returns the provider's user info api url. + * Traverse the command tree to find the command, and parse args for + * each parent. */ - userApiUrl(): string + traverse(args: Array): [(Command | undefined), Array] + } + interface Command { /** - * SetUserApiUrl sets the provider's UserApiUrl. + * SuggestionsFor provides suggestions for the typedName. */ - setUserApiUrl(url: string): void + suggestionsFor(typedName: string): Array + } + interface Command { /** - * Client returns an http client using the provided token. + * VisitParents visits all parents of the command and invokes fn on each parent. */ - client(token: oauth2.Token): (http.Client | undefined) + visitParents(fn: (_arg0: Command) => void): void + } + interface Command { /** - * BuildAuthUrl returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. + * Root finds root command. */ - buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string + root(): (Command | undefined) + } + interface Command { /** - * FetchToken converts an authorization code to token. + * ArgsLenAtDash will return the length of c.Flags().Args at the moment + * when a -- was found during args parsing. */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) + argsLenAtDash(): number + } + interface Command { /** - * FetchRawUserData requests and marshalizes into `result` the - * the OAuth user api response. + * ExecuteContext is the same as Execute(), but sets the ctx on the command. + * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs + * functions. */ - fetchRawUserData(token: oauth2.Token): string + executeContext(ctx: context.Context): void + } + interface Command { /** - * FetchAuthUser is similar to FetchRawUserData, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. + * Execute uses the args (os.Args[1:] by default) + * and run through the command tree finding appropriate matches + * for commands and then corresponding flags. */ - fetchAuthUser(token: oauth2.Token): (AuthUser | undefined) + execute(): void } -} - -/** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com - */ -namespace echo { - /** - * Context represents the context of the current HTTP request. It holds request and - * response objects, path, path parameters, data and registered handler. - */ - interface Context { + interface Command { /** - * Request returns `*http.Request`. + * ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. + * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs + * functions. */ - request(): (http.Request | undefined) + executeContextC(ctx: context.Context): (Command | undefined) + } + interface Command { /** - * SetRequest sets `*http.Request`. + * ExecuteC executes the command. */ - setRequest(r: http.Request): void + executeC(): (Command | undefined) + } + interface Command { + validateArgs(args: Array): void + } + interface Command { /** - * SetResponse sets `*Response`. + * ValidateRequiredFlags validates all required flags are present and returns an error otherwise */ - setResponse(r: Response): void + validateRequiredFlags(): void + } + interface Command { /** - * Response returns `*Response`. + * InitDefaultHelpFlag adds default help flag to c. + * It is called automatically by executing the c or by calling help and usage. + * If c already has help flag, it will do nothing. */ - response(): (Response | undefined) + initDefaultHelpFlag(): void + } + interface Command { /** - * IsTLS returns true if HTTP connection is TLS otherwise false. + * InitDefaultVersionFlag adds default version flag to c. + * It is called automatically by executing the c. + * If c already has a version flag, it will do nothing. + * If c.Version is empty, it will do nothing. */ - isTLS(): boolean + initDefaultVersionFlag(): void + } + interface Command { /** - * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. + * InitDefaultHelpCmd adds default help command to c. + * It is called automatically by executing the c or by calling help and usage. + * If c already has help command or c has no subcommands, it will do nothing. */ - isWebSocket(): boolean + initDefaultHelpCmd(): void + } + interface Command { /** - * Scheme returns the HTTP protocol scheme, `http` or `https`. + * ResetCommands delete parent, subcommand and help command from c. */ - scheme(): string + resetCommands(): void + } + interface Command { /** - * 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`. + * Commands returns a sorted slice of child commands. */ - realIP(): string + commands(): Array<(Command | undefined)> + } + interface Command { /** - * 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. + * AddCommand adds one or more commands to this parent command. */ - routeInfo(): RouteInfo + addCommand(...cmds: (Command | undefined)[]): void + } + interface Command { /** - * Path returns the registered path for the handler. + * Groups returns a slice of child command groups. */ - path(): string + groups(): Array<(Group | undefined)> + } + interface Command { /** - * PathParam returns path parameter by name. + * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group */ - pathParam(name: string): string + allChildCommandsHaveGroup(): boolean + } + interface Command { /** - * 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.` + * ContainsGroup return if groupID exists in the list of command groups. */ - pathParamDefault(name: string, defaultValue: string): string + containsGroup(groupID: string): boolean + } + interface Command { /** - * PathParams returns path parameter values. + * AddGroup adds one or more command groups to this parent command. */ - pathParams(): PathParams + addGroup(...groups: (Group | undefined)[]): void + } + interface Command { /** - * SetPathParams sets path parameters for current request. + * RemoveCommand removes one or more commands from a parent command. */ - setPathParams(params: PathParams): void + removeCommand(...cmds: (Command | undefined)[]): void + } + interface Command { /** - * QueryParam returns the query param for the provided name. + * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. */ - queryParam(name: string): string + print(...i: { + }[]): void + } + interface Command { /** - * QueryParamDefault returns the query param or default value for the provided name. + * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. */ - queryParamDefault(name: string): string + println(...i: { + }[]): void + } + interface Command { /** - * QueryParams returns the query parameters as `url.Values`. + * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. */ - queryParams(): url.Values + printf(format: string, ...i: { + }[]): void + } + interface Command { /** - * QueryString returns the URL query string. + * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. */ - queryString(): string + printErr(...i: { + }[]): void + } + interface Command { /** - * FormValue returns the form field value for the provided name. + * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. */ - formValue(name: string): string + printErrln(...i: { + }[]): void + } + interface Command { /** - * FormValueDefault returns the form field value or default value for the provided name. + * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. */ - formValueDefault(name: string): string + printErrf(format: string, ...i: { + }[]): void + } + interface Command { /** - * FormValues returns the form field values as `url.Values`. + * CommandPath returns the full path to this command. */ - formValues(): url.Values + commandPath(): string + } + interface Command { /** - * FormFile returns the multipart form file for the provided name. + * UseLine puts out the full usage for a given command (including parents). */ - formFile(name: string): (multipart.FileHeader | undefined) + useLine(): string + } + interface Command { /** - * MultipartForm returns the multipart form. + * DebugFlags used to determine which flags have been assigned to which commands + * and which persist. */ - multipartForm(): (multipart.Form | undefined) - /** - * Cookie returns the named cookie provided in the request. - */ - cookie(name: string): (http.Cookie | undefined) + debugFlags(): void + } + interface Command { /** - * SetCookie adds a `Set-Cookie` header in HTTP response. + * Name returns the command's name: the first word in the use line. */ - setCookie(cookie: http.Cookie): void + name(): string + } + interface Command { /** - * Cookies returns the HTTP cookies sent with the request. + * HasAlias determines if a given string is an alias of the command. */ - cookies(): Array<(http.Cookie | undefined)> + hasAlias(s: string): boolean + } + interface Command { /** - * Get retrieves data from the context. + * CalledAs returns the command name or alias that was used to invoke + * this command or an empty string if the command has not been called. */ - get(key: string): { + calledAs(): string } + interface Command { /** - * Set saves data in the context. + * NameAndAliases returns a list of the command name and all aliases */ - set(key: string, val: { - }): void + nameAndAliases(): string + } + interface Command { /** - * Bind binds the request body into provided type `i`. The default binder - * does it based on Content-Type header. + * HasExample determines if the command has example. */ - bind(i: { - }): void + hasExample(): boolean + } + interface Command { /** - * Validate validates provided `i`. It is usually called after `Context#Bind()`. - * Validator must be registered using `Echo#Validator`. + * Runnable determines if the command is itself runnable. */ - validate(i: { - }): void + runnable(): boolean + } + interface Command { /** - * Render renders a template with data and sends a text/html response with status - * code. Renderer must be registered using `Echo.Renderer`. + * HasSubCommands determines if the command has children commands. */ - render(code: number, name: string, data: { - }): void + hasSubCommands(): boolean + } + interface Command { /** - * HTML sends an HTTP response with status code. + * IsAvailableCommand determines if a command is available as a non-help command + * (this includes all non deprecated/hidden commands). */ - html(code: number, html: string): void + isAvailableCommand(): boolean + } + interface Command { /** - * HTMLBlob sends an HTTP blob response with status code. + * IsAdditionalHelpTopicCommand determines if a command is an additional + * help topic command; additional help topic command is determined by the + * fact that it is NOT runnable/hidden/deprecated, and has no sub commands that + * are runnable/hidden/deprecated. + * Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. */ - htmlBlob(code: number, b: string): void + isAdditionalHelpTopicCommand(): boolean + } + interface Command { /** - * String sends a string response with status code. + * HasHelpSubCommands determines if a command has any available 'help' sub commands + * that need to be shown in the usage/help default template under 'additional help + * topics'. */ - string(code: number, s: string): void + hasHelpSubCommands(): boolean + } + interface Command { /** - * JSON sends a JSON response with status code. + * HasAvailableSubCommands determines if a command has available sub commands that + * need to be shown in the usage/help default template under 'available commands'. */ - json(code: number, i: { - }): void + hasAvailableSubCommands(): boolean + } + interface Command { /** - * JSONPretty sends a pretty-print JSON with status code. + * HasParent determines if the command is a child command. */ - jsonPretty(code: number, i: { - }, indent: string): void + hasParent(): boolean + } + interface Command { /** - * JSONBlob sends a JSON blob response with status code. + * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. */ - jsonBlob(code: number, b: string): void + globalNormalizationFunc(): (f: flag.FlagSet, name: string) => flag.NormalizedName + } + interface Command { /** - * JSONP sends a JSONP response with status code. It uses `callback` to construct - * the JSONP payload. + * Flags returns the complete FlagSet that applies + * to this command (local and persistent declared here and by all parents). */ - jsonp(code: number, callback: string, i: { - }): void + flags(): (flag.FlagSet | undefined) + } + interface Command { /** - * JSONPBlob sends a JSONP blob response with status code. It uses `callback` - * to construct the JSONP payload. + * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. */ - jsonpBlob(code: number, callback: string, b: string): void + localNonPersistentFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * XML sends an XML response with status code. + * LocalFlags returns the local FlagSet specifically set in the current command. */ - xml(code: number, i: { - }): void + localFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * XMLPretty sends a pretty-print XML with status code. + * InheritedFlags returns all flags which were inherited from parent commands. */ - xmlPretty(code: number, i: { - }, indent: string): void + inheritedFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * XMLBlob sends an XML blob response with status code. + * NonInheritedFlags returns all flags which were not inherited from parent commands. */ - xmlBlob(code: number, b: string): void + nonInheritedFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * Blob sends a blob response with status code and content type. + * PersistentFlags returns the persistent FlagSet specifically set in the current command. */ - blob(code: number, contentType: string, b: string): void + persistentFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * Stream sends a streaming response with status code and content type. + * ResetFlags deletes all flags from command. */ - stream(code: number, contentType: string, r: io.Reader): void + resetFlags(): void + } + interface Command { /** - * File sends a response with the content of the file. + * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). */ - file(file: string): void + hasFlags(): boolean + } + interface Command { /** - * FileFS sends a response with the content of the file from given filesystem. + * HasPersistentFlags checks if the command contains persistent flags. */ - fileFS(file: string, filesystem: fs.FS): void + hasPersistentFlags(): boolean + } + interface Command { /** - * Attachment sends a response as attachment, prompting client to save the - * file. + * HasLocalFlags checks if the command has flags specifically declared locally. */ - attachment(file: string, name: string): void + hasLocalFlags(): boolean + } + interface Command { /** - * Inline sends a response as inline, opening the file in the browser. + * HasInheritedFlags checks if the command has flags inherited from its parent command. */ - inline(file: string, name: string): void + hasInheritedFlags(): boolean + } + interface Command { /** - * NoContent sends a response with no body and a status code. + * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire + * structure) which are not hidden or deprecated. */ - noContent(code: number): void + hasAvailableFlags(): boolean + } + interface Command { /** - * Redirect redirects the request to a provided URL with status code. + * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. */ - redirect(code: number, url: string): void + hasAvailablePersistentFlags(): boolean + } + interface Command { /** - * 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. + * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden + * or deprecated. */ - echo(): (Echo | undefined) + hasAvailableLocalFlags(): boolean } - // @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 { + interface Command { /** - * NewContextFunc allows using custom context implementations, instead of default *echo.context + * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are + * not hidden or deprecated. */ - newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext - debug: boolean - httpErrorHandler: HTTPErrorHandler - binder: Binder - jsonSerializer: JSONSerializer - validator: Validator - renderer: Renderer - logger: Logger - ipExtractor: IPExtractor + hasAvailableInheritedFlags(): boolean + } + interface Command { /** - * 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. + * Flag climbs up the command tree looking for matching flag. */ - filesystem: fs.FS + flag(name: string): (flag.Flag | undefined) } - /** - * HandlerFunc defines a function to serve HTTP requests. - */ - interface HandlerFunc {(c: Context): void } - /** - * MiddlewareFunc defines a function to process middleware. - */ - interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } - interface Echo { + interface Command { /** - * 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. + * ParseFlags parses persistent flag tree and local flags. */ - newContext(r: http.Request, w: http.ResponseWriter): Context + parseFlags(args: Array): void } - interface Echo { + interface Command { /** - * Router returns the default router. + * Parent returns a commands parent command. */ - router(): Router + parent(): (Command | undefined) } - interface Echo { + interface Command { /** - * Routers returns the map of host => router. + * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. */ - 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 + registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void } - interface Echo { + interface Command { /** - * CONNECT registers a new CONNECT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * InitDefaultCompletionCmd adds a default 'completion' command to c. + * This function will do nothing if any of the following is true: + * 1- the feature has been explicitly disabled by the program, + * 2- c has no subcommands (to avoid creating one), + * 3- c already has a 'completion' command provided by the program. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + initDefaultCompletionCmd(): void } - interface Echo { + interface Command { /** - * DELETE registers a new DELETE route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * GenFishCompletion generates fish completion file and writes to the passed writer. */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genFishCompletion(w: io.Writer, includeDesc: boolean): void } - interface Echo { + interface Command { /** - * GET registers a new GET route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * GenFishCompletionFile generates fish completion file. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genFishCompletionFile(filename: string, includeDesc: boolean): void } - interface Echo { + interface Command { /** - * HEAD registers a new HEAD route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors + * if the command is invoked with a subset (but not all) of the given flags. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + markFlagsRequiredTogether(...flagNames: string[]): void } - interface Echo { + interface Command { /** - * OPTIONS registers a new OPTIONS route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors + * if the command is invoked with more than one flag from the given set of flags. */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + markFlagsMutuallyExclusive(...flagNames: string[]): void } - interface Echo { + interface Command { /** - * PATCH registers a new PATCH route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the + * first error encountered. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + validateFlagGroups(): void } - interface Echo { + interface Command { /** - * POST registers a new POST route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * GenPowerShellCompletionFile generates powershell completion file without descriptions. */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genPowerShellCompletionFile(filename: string): void } - interface Echo { + interface Command { /** - * PUT registers a new PUT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * GenPowerShellCompletion generates powershell completion file without descriptions + * and writes it to the passed writer. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genPowerShellCompletion(w: io.Writer): void } - interface Echo { + interface Command { /** - * TRACE registers a new TRACE route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genPowerShellCompletionFileWithDesc(filename: string): void } - interface Echo { + interface Command { /** - * 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) })` + * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions + * and writes it to the passed writer. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + genPowerShellCompletionWithDesc(w: io.Writer): void } - interface Echo { + interface Command { /** - * 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. + * MarkFlagRequired instructs the various shell completion implementations to + * prioritize the named flag when performing completion, + * and causes your command to report an error if invoked without the flag. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + markFlagRequired(name: string): void } - interface Echo { + interface Command { /** - * 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. + * MarkPersistentFlagRequired instructs the various shell completion implementations to + * prioritize the named persistent flag when performing completion, + * and causes your command to report an error if invoked without the flag. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + markPersistentFlagRequired(name: string): void } - interface Echo { + interface Command { /** - * Static registers a new route with path prefix to serve static files from the provided root directory. + * MarkFlagFilename instructs the various shell completion implementations to + * limit completions for the named flag to the specified file extensions. */ - static(pathPrefix: string): RouteInfo + markFlagFilename(name: string, ...extensions: string[]): void } - interface Echo { + interface Command { /** - * StaticFS registers a new route with path prefix to serve static files from the provided file system. + * MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. + * The bash completion script will call the bash function f for the flag. * - * 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. + * This will only work for bash completion. + * It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows + * to register a Go function which will work across all shells. */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo + markFlagCustom(name: string, f: string): void } - interface Echo { + interface Command { /** - * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. + * MarkPersistentFlagFilename instructs the various shell completion + * implementations to limit completions for the named persistent flag to the + * specified file extensions. */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo + markPersistentFlagFilename(name: string, ...extensions: string[]): void } - interface Echo { + interface Command { /** - * AddRoute registers a new Route with default host Router + * MarkFlagDirname instructs the various shell completion implementations to + * limit completions for the named flag to directory names. */ - addRoute(route: Routable): RouteInfo + markFlagDirname(name: string): void } - interface Echo { + interface Command { /** - * Add registers a new route for an HTTP method and path with matching handler - * in the router with optional route-level middleware. + * MarkPersistentFlagDirname instructs the various shell completion + * implementations to limit completions for the named persistent flag to + * directory names. */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo + markPersistentFlagDirname(name: string): void } - interface Echo { + interface Command { /** - * Host creates a new router group for the provided host and optional host-level middleware. + * GenZshCompletionFile generates zsh completion file including descriptions. */ - host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) + genZshCompletionFile(filename: string): void } - interface Echo { + interface Command { /** - * Group creates a new router group with prefix and optional group-level middleware. + * GenZshCompletion generates zsh completion file including descriptions + * and writes it to the passed writer. */ - group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) + genZshCompletion(w: io.Writer): void } - interface Echo { + interface Command { /** - * AcquireContext returns an empty `Context` instance from the pool. - * You must return the context by calling `ReleaseContext()`. + * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. */ - acquireContext(): Context + genZshCompletionFileNoDesc(filename: string): void } - interface Echo { + interface Command { /** - * ReleaseContext returns the `Context` instance back to the pool. - * You must call it after `AcquireContext()`. + * GenZshCompletionNoDesc generates zsh completion file without descriptions + * and writes it to the passed writer. */ - releaseContext(c: Context): void + genZshCompletionNoDesc(w: io.Writer): void } - interface Echo { + interface Command { /** - * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + * MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was + * not consistent with Bash completion. It has therefore been disabled. + * Instead, when no other completion is specified, file completion is done by + * default for every argument. One can disable file completion on a per-argument + * basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. + * To achieve file extension filtering, one can use ValidArgsFunction and + * ShellCompDirectiveFilterFileExt. + * + * Deprecated */ - serveHTTP(w: http.ResponseWriter, r: http.Request): void + markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void } - interface Echo { + interface Command { /** - * 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. + * MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore + * been disabled. + * To achieve the same behavior across all shells, one can use + * ValidArgs (for the first argument only) or ValidArgsFunction for + * any argument (can include the first one also). * - * 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) - * } - * ``` + * Deprecated */ - start(address: string): void + markZshCompPositionalArgumentWords(argPosition: number, ...words: 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. + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. * - * # Errors + * 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. * - * The errors returned from this package can be inspected in several ways: + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: * - * The Code function from gocloud.dev/gcerrors will return an error code, also - * defined in that package, when invoked on an error. + * ``` + * 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 Bucket.ErrorAs method can retrieve the driver error underlying the returned - * error. + * The client must close the response body when finished with it: * - * # OpenCensus Integration + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` * - * OpenCensus supports tracing and metric collection for multiple languages and - * backend providers. See https://opencensus.io. + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: * - * 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. + * 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) + * // ... * ``` * - * 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". + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: * - * 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. + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") * ``` * - * 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. + * 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 blob { +namespace http { + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after - * reads are finished. + * 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 Reader { - } - interface Reader { + interface Request { /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * 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. */ - read(p: string): number - } - interface Reader { + method: string /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * 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. */ - seek(offset: number, whence: number): number - } - interface Reader { + url?: url.URL /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * 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. */ - close(): void - } - interface Reader { + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * ContentType returns the MIME type of the blob. + * 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. */ - contentType(): string - } - interface Reader { + header: Header /** - * ModTime returns the time the blob was last modified. - */ - modTime(): time.Time - } - interface Reader { - /** - * Size returns the size of the blob content in bytes. + * 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. */ - size(): number - } - interface Reader { + body: io.ReadCloser /** - * 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. + * 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. */ - as(i: { - }): boolean - } - interface Reader { + getBody: () => io.ReadCloser /** - * 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. + * 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. * - * It implements the io.WriterTo interface. + * For client requests, a value of 0 with a non-nil Body is + * also treated as unknown. */ - writeTo(w: io.Writer): number - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { + contentLength: number /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + * 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. */ - cacheControl: string + transferEncoding: Array /** - * 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 + * 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. */ - contentDisposition: string + close: boolean /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + * 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. */ - contentEncoding: string + host: 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 + * 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. */ - contentLanguage: string + form: url.Values /** - * 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 + * 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. */ - contentType: string + postForm: url.Values /** - * 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. + * 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. */ - metadata: _TygojaDict + multipartForm?: multipart.Form /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * 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. */ - createTime: time.Time + trailer: Header /** - * ModTime is the time the blob was last modified. + * 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. */ - modTime: time.Time + remoteAddr: string /** - * Size is the size of the blob's content in bytes. + * 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. */ - size: number + requestURI: string /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * 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. */ - md5: string + tls?: tls.ConnectionState /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * 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. */ - eTag: string - } - interface Attributes { + cancel: undefined /** - * 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. + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. */ - as(i: { - }): boolean + response?: Response } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { + interface Request { /** - * Key is the key for this blob. + * 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. */ - key: string + context(): context.Context + } + interface Request { /** - * ModTime is the time the blob was last modified. + * 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. */ - modTime: time.Time + withContext(ctx: context.Context): (Request | undefined) + } + interface Request { /** - * Size is the size of the blob's content in bytes. + * 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. */ - size: number + clone(ctx: context.Context): (Request | undefined) + } + interface Request { /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - md5: string + protoAtLeast(major: number): boolean + } + interface Request { /** - * 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. + * UserAgent returns the client's User-Agent, if sent in the request. */ - isDir: boolean + userAgent(): string } - interface ListObject { + interface Request { /** - * 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. + * Cookies parses and returns the HTTP cookies sent with the request. */ - as(i: { - }): boolean + cookies(): Array<(Cookie | undefined)> } -} - -/** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. - * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. - * - * Drivers that do not support context cancellation will not return until - * after the query is completed. - * - * For usage examples, see the wiki page at - * https://golang.org/s/sqlwiki. - */ -namespace sql { - /** - * TxOptions holds the transaction options to be used in DB.BeginTx. - */ - interface TxOptions { + interface Request { /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * 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. */ - 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 { + cookie(name: string): (Cookie | undefined) } - interface DB { + interface Request { /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * 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. */ - pingContext(ctx: context.Context): void + addCookie(c: Cookie): void } - interface DB { + interface Request { /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. + * Referer returns the referring URL, if sent in the request. * - * Ping uses context.Background internally; to specify the context, use - * PingContext. + * 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"]. */ - ping(): void + referer(): string } - interface DB { + interface Request { /** - * 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. + * 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. */ - close(): void + multipartReader(): (multipart.Reader | undefined) } - interface DB { + interface Request { /** - * 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. + * 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 + * ``` * - * The default max idle connections is currently 2. This may change in - * a future release. + * 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. */ - setMaxIdleConns(n: number): void + write(w: io.Writer): void } - interface DB { + interface Request { /** - * 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). + * 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. */ - setMaxOpenConns(n: number): void + writeProxy(w: io.Writer): void } - interface DB { + interface Request { /** - * 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. + * 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. */ - setConnMaxLifetime(d: time.Duration): void + basicAuth(): [string, boolean] } - interface DB { + interface Request { /** - * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. * - * Expired connections may be closed lazily before reuse. + * With HTTP Basic Authentication the provided username and password + * are not encrypted. * - * If d <= 0, connections are not closed due to a connection's idle time. + * 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. */ - setConnMaxIdleTime(d: time.Duration): void + setBasicAuth(username: string): void } - interface DB { + interface Request { /** - * Stats returns database statistics. + * 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. */ - stats(): DBStats + parseForm(): void } - interface DB { + interface Request { /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * 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. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + parseMultipartForm(maxMemory: number): void } - interface DB { + interface Request { /** - * 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. + * 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. */ - prepare(query: string): (Stmt | undefined) + formValue(key: string): string } - interface DB { + interface Request { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * 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. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + postFormValue(key: string): string } - interface DB { + interface Request { /** - * 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. + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. */ - exec(query: string, ...args: any[]): Result + formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] } - 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 { + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after the Handler.ServeHTTP method + * has returned. + */ + interface ResponseWriter { /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * Header returns the header map that will be sent by + * WriteHeader. The Header map also is the mechanism with which + * Handlers can set HTTP trailers. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. - */ - 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. + * Changing the header map after a call to WriteHeader (or + * Write) has no effect unless the modified headers are + * trailers. * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * 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. */ - queryRow(query: string, ...args: any[]): (Row | undefined) - } - interface DB { + header(): Header /** - * BeginTx starts a transaction. + * Write writes the data to the connection as part of an HTTP reply. * - * 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. + * If WriteHeader has not yet been called, Write calls + * WriteHeader(http.StatusOK) before writing the data. If the Header + * does not contain a Content-Type line, Write adds a Content-Type set + * to the result of passing the initial 512 bytes of written data to + * DetectContentType. Additionally, if the total size of all written + * data is under a few KB and there are no Flush calls, the + * Content-Length header is added automatically. * - * The 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. + * 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. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) - } - interface DB { + write(_arg0: string): number /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. + * WriteHeader sends an HTTP response header with the provided + * status code. * - * 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. + * 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. * - * Every Conn must be returned to the database pool after use by - * calling Conn.Close. + * 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. */ - conn(ctx: context.Context): (Conn | undefined) + writeHeader(statusCode: number): void } /** - * 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. + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. */ - interface Tx { - } - interface Tx { + interface Server { /** - * Commit commits the transaction. + * 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. */ - commit(): void - } - interface Tx { + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * Rollback aborts the transaction. + * 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. */ - rollback(): void - } - interface Tx { + tlsConfig?: tls.Config /** - * 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. + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. * - * 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. + * 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. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) - } - interface Tx { + readTimeout: time.Duration /** - * 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. + * 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. */ - prepare(query: string): (Stmt | undefined) - } - interface Tx { + readHeaderTimeout: time.Duration /** - * 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. + * 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. */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) - } - interface Tx { + writeTimeout: time.Duration /** - * 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. + * 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. */ - stmt(stmt: Stmt): (Stmt | undefined) - } - interface Tx { + idleTimeout: time.Duration /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * 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. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Tx { + maxHeaderBytes: number /** - * 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. + * 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. */ - exec(query: string, ...args: any[]): Result - } - interface Tx { + tlsNextProto: _TygojaDict /** - * QueryContext executes a query that returns rows, typically a SELECT. + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) - } - interface Tx { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * Query executes a query that returns rows, typically a SELECT. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * 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. */ - query(query: string, ...args: any[]): (Rows | undefined) - } - interface Tx { + errorLog?: log.Logger /** - * 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. + * 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. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) - } - interface Tx { + baseContext: (_arg0: net.Listener) => context.Context /** - * 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. + * 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. */ - 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 { + connContext: (ctx: context.Context, c: net.Conn) => context.Context } - interface Stmt { + interface Server { /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * 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). */ - execContext(ctx: context.Context, ...args: any[]): Result + close(): void } - interface Stmt { + interface Server { /** - * Exec executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * 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). * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * 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. */ - exec(...args: any[]): Result + shutdown(ctx: context.Context): void } - interface Stmt { + interface Server { /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * RegisterOnShutdown registers a function to call on Shutdown. + * This can be used to gracefully shutdown connections that have + * undergone ALPN protocol upgrade or that have been hijacked. + * This function should start protocol-specific graceful shutdown, + * but should not wait for shutdown to complete. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) + registerOnShutdown(f: () => void): void } - interface Stmt { + interface Server { /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * ListenAndServe listens on the TCP network address srv.Addr and then + * calls Serve to handle requests on incoming connections. + * Accepted connections are configured to enable TCP keep-alives. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * If srv.Addr is blank, ":http" is used. + * + * ListenAndServe always returns a non-nil error. After Shutdown or Close, + * the returned error is ErrServerClosed. */ - query(...args: any[]): (Rows | undefined) + listenAndServe(): void } - interface Stmt { + interface Server { /** - * 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. + * 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. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) + serve(l: net.Listener): void } - interface Stmt { + interface Server { /** - * 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: + * 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. * - * ``` - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) - * ``` + * 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. * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * ServeTLS always returns a non-nil error. After Shutdown or Close, the + * returned error is ErrServerClosed. */ - queryRow(...args: any[]): (Row | undefined) + serveTLS(l: net.Listener, certFile: string): void } - interface Stmt { + interface Server { /** - * Close closes the statement. + * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. + * By default, keep-alives are always enabled. Only very + * resource-constrained environments or servers in the process of + * shutting down should disable them. */ - close(): 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 { + setKeepAlivesEnabled(v: boolean): void } - interface Rows { + interface Server { /** - * 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. + * 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. * - * 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. + * 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. * - * 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. + * If srv.Addr is blank, ":https" is used. + * + * ListenAndServeTLS always returns a non-nil error. After Shutdown or + * Close, the returned error is ErrServerClosed. */ - err(): void + listenAndServeTLS(certFile: string): void } - interface Rows { - /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. - */ - columns(): Array +} + +/** + * 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 Rows { + interface Reader { /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). */ - columnTypes(): Array<(ColumnType | undefined)> + read(p: string): number } - interface Rows { + interface Reader { /** - * 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 + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). */ - scan(...dest: any[]): void + seek(offset: number, whence: number): number } - interface Rows { + interface Reader { /** - * 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 implements io.Closer (https://golang.org/pkg/io/#Closer). */ close(): void } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { + interface Reader { /** - * 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. + * ContentType returns the MIME type of the blob. */ - lastInsertId(): number + contentType(): string + } + interface Reader { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * ModTime returns the time the blob was last modified. */ - rowsAffected(): number + modTime(): time.Time } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * JsonArray defines a slice that is safe for json and db read/write. - */ - interface JsonArray extends Array{} - interface JsonArray { + interface Reader { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Size returns the size of the blob content in bytes. */ - marshalJSON(): string + size(): number } - interface JsonArray { + interface Reader { /** - * Value implements the [driver.Valuer] interface. + * 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. */ - value(): driver.Value + as(i: { + }): boolean } - interface JsonArray { + interface Reader { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. + * 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. */ - scan(value: any): void + writeTo(w: io.Writer): number } /** - * JsonMap defines a map that is safe for json and db read/write. + * Attributes contains attributes about a blob. */ - interface JsonMap extends _TygojaDict{} - interface JsonMap { + interface Attributes { /** - * MarshalJSON implements the [json.Marshaler] interface. + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - marshalJSON(): string - } - interface JsonMap { + cacheControl: string /** - * Get retrieves a single value from the current JsonMap. - * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + * 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 */ - get(key: string): any - } - interface JsonMap { + contentDisposition: string /** - * 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). + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - set(key: string, value: any): void - } - interface JsonMap { + contentEncoding: string /** - * Value implements the [driver.Valuer] interface. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - value(): driver.Value - } - interface JsonMap { + contentLanguage: string /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. + * 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 */ - 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 + contentType: string /** - * Deprecated: Will be removed in v0.9+ + * 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. */ - 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 { + metadata: _TygojaDict /** - * Validate makes Settings validatable by implementing [validation.Validatable] interface. + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. */ - validate(): void - } - interface Settings { + createTime: time.Time /** - * Merge merges `other` settings into the current one. + * ModTime is the time the blob was last modified. */ - merge(other: Settings): void + 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 Settings { + interface Attributes { /** - * Clone creates a new deep copy of the current settings. + * 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. */ - clone(): (Settings | undefined) + as(i: { + }): boolean } - interface Settings { + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { /** - * RedactClone creates a new deep copy of the current settings, - * while replacing the secret values with `******`. + * Key is the key for this blob. */ - redactClone(): (Settings | undefined) + 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 Settings { + interface ListObject { /** - * NamedAuthProviderConfigs returns a map with all registered OAuth2 - * provider configurations (indexed by their name identifier). + * 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. */ - namedAuthProviderConfigs(): _TygojaDict + as(i: { + }): boolean } } /** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. + * 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 schema { - // @ts-ignore - import validation = ozzo_validation +namespace echo { /** - * Schema defines a dynamic db schema as a slice of `SchemaField`s. + * Context represents the context of the current HTTP request. It holds request and + * response objects, path, path parameters, data and registered handler. */ - interface Schema { - } - interface Schema { + interface Context { /** - * Fields returns the registered schema fields. + * Request returns `*http.Request`. */ - fields(): Array<(SchemaField | undefined)> - } - interface Schema { + request(): (http.Request | undefined) /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. + * SetRequest sets `*http.Request`. */ - initFieldsOptions(): void - } - interface Schema { + setRequest(r: http.Request): void /** - * Clone creates a deep clone of the current schema. + * SetResponse sets `*Response`. */ - clone(): (Schema | undefined) - } - interface Schema { + setResponse(r: Response): void /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. + * Response returns `*Response`. */ - asMap(): _TygojaDict - } - interface Schema { + response(): (Response | undefined) /** - * GetFieldById returns a single field by its id. + * IsTLS returns true if HTTP connection is TLS otherwise false. */ - getFieldById(id: string): (SchemaField | undefined) - } - interface Schema { + isTLS(): boolean /** - * GetFieldByName returns a single field by its name. + * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. */ - getFieldByName(name: string): (SchemaField | undefined) - } - interface Schema { + isWebSocket(): boolean /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. + * Scheme returns the HTTP protocol scheme, `http` or `https`. */ - removeField(id: string): void - } - interface Schema { + scheme(): string /** - * 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. + * 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`. */ - addField(newField: SchemaField): void - } - interface Schema { + realIP(): string /** - * 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. + * 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. */ - validate(): void - } - interface Schema { + routeInfo(): RouteInfo /** - * MarshalJSON implements the [json.Marshaler] interface. + * Path returns the registered path for the handler. */ - marshalJSON(): string - } - interface Schema { + path(): string /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * PathParam returns path parameter by name. + */ + pathParam(name: string): string + /** + * PathParamDefault returns the path parameter or default value for the provided name. * - * On success, all schema field options are auto initialized. + * 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.` */ - unmarshalJSON(data: string): void - } - interface Schema { + pathParamDefault(name: string, defaultValue: string): string /** - * Value implements the [driver.Valuer] interface. + * PathParams returns path parameter values. */ - value(): driver.Value - } - interface Schema { + pathParams(): PathParams /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. + * SetPathParams sets path parameters for current request. */ - 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 { + setPathParams(params: PathParams): void /** - * TableName returns the Admin model SQL table name. + * QueryParam returns the query param for the provided name. */ - tableName(): string - } - interface Admin { + queryParam(name: string): string /** - * ValidatePassword validates a plain password against the model's password. + * QueryParamDefault returns the query param or default value for the provided name. */ - validatePassword(password: string): boolean - } - interface Admin { + queryParamDefault(name: string): string /** - * SetPassword sets cryptographically secure string to `model.Password`. - * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + * QueryParams returns the query parameters as `url.Values`. */ - setPassword(password: string): void - } - interface Admin { + queryParams(): url.Values /** - * RefreshTokenKey generates and sets new random token key. + * QueryString returns the URL query string. */ - 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 + queryString(): string /** - * rules + * FormValue returns the form field value for the provided name. */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { + formValue(name: string): string /** - * TableName returns the Collection model SQL table name. + * FormValueDefault returns the form field value or default value for the provided name. */ - tableName(): string - } - interface Collection { + formValueDefault(name: string): string /** - * BaseFilesPath returns the storage dir path used by the collection. + * FormValues returns the form field values as `url.Values`. */ - baseFilesPath(): string - } - interface Collection { + formValues(): url.Values /** - * IsBase checks if the current collection has "base" type. + * FormFile returns the multipart form file for the provided name. */ - isBase(): boolean - } - interface Collection { + formFile(name: string): (multipart.FileHeader | undefined) /** - * IsAuth checks if the current collection has "auth" type. + * MultipartForm returns the multipart form. */ - isAuth(): boolean - } - interface Collection { + multipartForm(): (multipart.Form | undefined) /** - * IsView checks if the current collection has "view" type. + * Cookie returns the named cookie provided in the request. */ - isView(): boolean - } - interface Collection { + cookie(name: string): (http.Cookie | undefined) /** - * MarshalJSON implements the [json.Marshaler] interface. + * SetCookie adds a `Set-Cookie` header in HTTP response. */ - marshalJSON(): string - } - interface Collection { + setCookie(cookie: http.Cookie): void /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. + * Cookies returns the HTTP cookies sent with the request. */ - baseOptions(): CollectionBaseOptions - } - interface Collection { + cookies(): Array<(http.Cookie | undefined)> /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. + * Get retrieves data from the context. */ - authOptions(): CollectionAuthOptions + get(key: string): { } - interface Collection { /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. + * Set saves data in the context. */ - viewOptions(): CollectionViewOptions - } - interface Collection { + set(key: string, val: { + }): void /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. + * Bind binds the request body into provided type `i`. The default binder + * does it based on Content-Type header. */ - normalizeOptions(): void - } - interface Collection { + bind(i: { + }): void /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). + * Validate validates provided `i`. It is usually called after `Context#Bind()`. + * Validator must be registered using `Echo#Validator`. */ - decodeOptions(result: any): void - } - interface Collection { + validate(i: { + }): void /** - * SetOptions normalizes and unmarshals the specified options into m.Options. + * Render renders a template with data and sends a text/html response with status + * code. Renderer must be registered using `Echo.Renderer`. */ - 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 { + render(code: number, name: string, data: { + }): void /** - * TableName returns the table name associated to the current Record model. + * HTML sends an HTTP response with status code. */ - tableName(): string - } - interface Record { + html(code: number, html: string): void /** - * Collection returns the Collection model associated to the current Record model. + * HTMLBlob sends an HTTP blob response with status code. */ - collection(): (Collection | undefined) - } - interface Record { + htmlBlob(code: number, b: string): void /** - * 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. + * String sends a string response with status code. */ - originalCopy(): (Record | undefined) - } - interface Record { + string(code: number, s: string): void /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. + * JSON sends a JSON response with status code. */ - cleanCopy(): (Record | undefined) - } - interface Record { + json(code: number, i: { + }): void /** - * Expand returns a shallow copy of the current Record model expand data. + * JSONPretty sends a pretty-print JSON with status code. */ - expand(): _TygojaDict - } - interface Record { + jsonPretty(code: number, i: { + }, indent: string): void /** - * SetExpand shallow copies the provided data to the current Record model's expand. + * JSONBlob sends a JSON blob response with status code. */ - setExpand(expand: _TygojaDict): void - } - interface Record { + jsonBlob(code: number, b: string): void /** - * 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). + * JSONP sends a JSONP response with status code. It uses `callback` to construct + * the JSONP payload. */ - mergeExpand(expand: _TygojaDict): void - } - interface Record { + jsonp(code: number, callback: string, i: { + }): void /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + * JSONPBlob sends a JSONP blob response with status code. It uses `callback` + * to construct the JSONP payload. */ - schemaData(): _TygojaDict - } - interface Record { + jsonpBlob(code: number, callback: string, b: string): void /** - * 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. + * XML sends an XML response with status code. */ - unknownData(): _TygojaDict - } - interface Record { + xml(code: number, i: { + }): void /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + * XMLPretty sends a pretty-print XML with status code. */ - ignoreEmailVisibility(state: boolean): void - } - interface Record { + xmlPretty(code: number, i: { + }, indent: string): void /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). + * XMLBlob sends an XML blob response with status code. */ - withUnknownData(state: boolean): void - } - interface Record { + xmlBlob(code: number, b: string): void /** - * 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. + * Blob sends a blob response with status code and content type. */ - set(key: string, value: any): void - } - interface Record { + blob(code: number, contentType: string, b: string): void /** - * Get returns a single record model data value for "key". + * Stream sends a streaming response with status code and content type. */ - get(key: string): any - } - interface Record { + stream(code: number, contentType: string, r: io.Reader): void /** - * GetBool returns the data value for "key" as a bool. + * File sends a response with the content of the file. */ - getBool(key: string): boolean - } - interface Record { + file(file: string): void /** - * GetString returns the data value for "key" as a string. + * FileFS sends a response with the content of the file from given filesystem. */ - getString(key: string): string - } - interface Record { + fileFS(file: string, filesystem: fs.FS): void /** - * GetInt returns the data value for "key" as an int. + * Attachment sends a response as attachment, prompting client to save the + * file. */ - getInt(key: string): number - } - interface Record { + attachment(file: string, name: string): void /** - * GetFloat returns the data value for "key" as a float64. + * Inline sends a response as inline, opening the file in the browser. */ - getFloat(key: string): number - } - interface Record { + inline(file: string, name: string): void /** - * GetTime returns the data value for "key" as a [time.Time] instance. + * NoContent sends a response with no body and a status code. */ - getTime(key: string): time.Time - } - interface Record { + noContent(code: number): void /** - * GetDateTime returns the data value for "key" as a DateTime instance. + * Redirect redirects the request to a provided URL with status code. */ - getDateTime(key: string): types.DateTime - } - interface Record { + redirect(code: number, url: string): void /** - * GetStringSlice returns the data value for "key" as a slice of unique strings. + * 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. */ - getStringSlice(key: string): Array + echo(): (Echo | undefined) } - interface Record { + // @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 { /** - * 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) - * ``` + * NewContextFunc allows using custom context implementations, instead of default *echo.context */ - unmarshalJSONField(key: string, result: any): void - } - interface Record { + newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext + debug: boolean + httpErrorHandler: HTTPErrorHandler + binder: Binder + jsonSerializer: JSONSerializer + validator: Validator + renderer: Renderer + logger: Logger + ipExtractor: IPExtractor /** - * BaseFilesPath returns the storage dir path used by the record. + * 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. */ - baseFilesPath(): string + filesystem: fs.FS } - interface Record { + /** + * HandlerFunc defines a function to serve HTTP requests. + */ + interface HandlerFunc {(c: Context): void } + /** + * MiddlewareFunc defines a function to process middleware. + */ + interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } + interface Echo { /** - * FindFileFieldByFile returns the first file type field for which - * any of the record's data contains the provided filename. + * 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. */ - findFileFieldByFile(filename: string): (schema.SchemaField | undefined) + newContext(r: http.Request, w: http.ResponseWriter): Context } - interface Record { + interface Echo { /** - * Load bulk loads the provided data into the current Record model. + * Router returns the default router. */ - load(data: _TygojaDict): void + router(): Router } - interface Record { + interface Echo { /** - * ColumnValueMap implements [ColumnValueMapper] interface. + * Routers returns the map of host => router. */ - columnValueMap(): _TygojaDict + routers(): _TygojaDict } - interface Record { + interface Echo { /** - * 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. + * RouterFor returns Router for given host. */ - publicExport(): _TygojaDict + routerFor(host: string): Router } - interface Record { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * Only the data exported by `PublicExport()` will be serialized. + * 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. */ - marshalJSON(): string + resetRouterCreator(creator: (e: Echo) => Router): void } - interface Record { + interface Echo { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * 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. */ - unmarshalJSON(data: string): void + pre(...middleware: MiddlewareFunc[]): void } - interface Record { + interface Echo { /** - * 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} - * ``` + * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. */ - replaceModifers(data: _TygojaDict): _TygojaDict + use(...middleware: MiddlewareFunc[]): void } - interface Record { + interface Echo { /** - * Username returns the "username" auth record data value. + * CONNECT registers a new CONNECT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - username(): string + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * 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. + * DELETE registers a new DELETE route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - setUsername(username: string): void + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * Email returns the "email" auth record data value. + * GET registers a new GET route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - email(): string + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * 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. + * HEAD registers a new HEAD route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - setEmail(email: string): void + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * Verified returns the "emailVisibility" auth record data value. + * OPTIONS registers a new OPTIONS route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - emailVisibility(): boolean + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * SetEmailVisibility sets the "emailVisibility" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * PATCH registers a new PATCH route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - setEmailVisibility(visible: boolean): void + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * Verified returns the "verified" auth record data value. + * POST registers a new POST route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - verified(): boolean + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * SetVerified sets the "verified" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * PUT registers a new PUT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - setVerified(verified: boolean): void + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * TokenKey returns the "tokenKey" auth record data value. + * TRACE registers a new TRACE route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - tokenKey(): string + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * SetTokenKey sets the "tokenKey" auth record data value. + * 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). * - * Returns an error if the record is not from an auth collection. + * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - setTokenKey(key: string): void + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * RefreshTokenKey generates and sets new random auth record "tokenKey". - * - * Returns an error if the record is not from an auth collection. + * 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. */ - refreshTokenKey(): void + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface Record { + interface Echo { /** - * LastResetSentAt returns the "lastResentSentAt" auth record data value. + * 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. */ - lastResetSentAt(): types.DateTime + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface Record { + interface Echo { /** - * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Static registers a new route with path prefix to serve static files from the provided root directory. */ - setLastResetSentAt(dateTime: types.DateTime): void + static(pathPrefix: string): RouteInfo } - interface Record { + interface Echo { /** - * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. + * 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. */ - lastVerificationSentAt(): types.DateTime + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface Record { + interface Echo { /** - * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * FileFS registers a new route with path to serve file from the provided file system. */ - setLastVerificationSentAt(dateTime: types.DateTime): void + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * PasswordHash returns the "passwordHash" auth record data value. + * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. */ - passwordHash(): string + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * 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. + * AddRoute registers a new Route with default host Router */ - validatePassword(password: string): boolean + addRoute(route: Routable): RouteInfo } - interface Record { + interface Echo { /** - * 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. + * Add registers a new route for an HTTP method and path with matching handler + * in the router with optional route-level middleware. */ - setPassword(password: string): void + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - /** - * RequestData defines a HTTP request data struct, usually used - * as part of the `@request.*` filter resolver. - */ - interface RequestData { - method: string - query: _TygojaDict + interface Echo { /** - * @todo consider changing to Body? + * Host creates a new router group for the provided host and optional host-level middleware. */ - data: _TygojaDict - headers: _TygojaDict - authRecord?: Record - admin?: Admin + host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) } - interface RequestData { + interface Echo { /** - * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. + * Group creates a new router group with prefix and optional group-level middleware. */ - hasModifierDataKeys(): boolean + group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) } -} - -namespace migrate { - /** - * MigrationsList defines a list with migration definitions - */ - interface MigrationsList { + interface Echo { + /** + * AcquireContext returns an empty `Context` instance from the pool. + * You must return the context by calling `ReleaseContext()`. + */ + acquireContext(): Context } - interface MigrationsList { + interface Echo { /** - * Item returns a single migration from the list by its index. + * ReleaseContext returns the `Context` instance back to the pool. + * You must call it after `AcquireContext()`. */ - item(index: number): (Migration | undefined) + releaseContext(c: Context): void } - interface MigrationsList { + interface Echo { /** - * Items returns the internal migrations list slice. + * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. */ - items(): Array<(Migration | undefined)> + serveHTTP(w: http.ResponseWriter, r: http.Request): void } - interface MigrationsList { + interface Echo { /** - * Register adds new migration definition to the list. + * 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`. * - * If `optFilename` is not provided, it will try to get the name from its .go file. + * Note: this method is created for use in examples/demos and is deliberately simple without providing configuration + * options. * - * The list will be sorted automatically based on the migrations file name. + * 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) + * } + * ``` */ - register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void + start(address: string): void } } /** - * Package daos handles common PocketBase DB model manipulations. + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. * - * Think of daos as DB repository and service layer in one. + * 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 daos { - interface Dao { +namespace sql { + /** + * TxOptions holds the transaction options to be used in DB.BeginTx. + */ + interface TxOptions { /** - * AdminQuery returns a new Admin select query. + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. */ - adminQuery(): (dbx.SelectQuery | undefined) + isolation: IsolationLevel + readOnly: boolean } - interface Dao { + /** + * 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 { /** - * FindAdminById finds the admin with the provided id. + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. */ - findAdminById(id: string): (models.Admin | undefined) + pingContext(ctx: context.Context): void } - interface Dao { + interface DB { /** - * FindAdminByEmail finds the admin with the provided email address. + * 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. */ - findAdminByEmail(email: string): (models.Admin | undefined) + ping(): void } - interface Dao { + interface DB { /** - * FindAdminByToken finds the admin associated with the provided JWT token. + * 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. * - * Returns an error if the JWT token is invalid or expired. + * It is rare to Close a DB, as the DB handle is meant to be + * long-lived and shared between many goroutines. */ - findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) + close(): void } - interface Dao { + interface DB { /** - * TotalAdmins returns the number of existing admin records. + * 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. */ - totalAdmins(): number + setMaxIdleConns(n: number): void } - interface Dao { + interface DB { /** - * IsAdminEmailUnique checks if the provided email address is not - * already in use by other admins. + * 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). */ - isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean + setMaxOpenConns(n: number): void } - interface Dao { + interface DB { /** - * DeleteAdmin deletes the provided Admin model. + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. * - * Returns an error if there is only 1 admin. + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's age. */ - deleteAdmin(admin: models.Admin): void + setConnMaxLifetime(d: time.Duration): void } - interface Dao { + interface DB { /** - * SaveAdmin upserts the provided Admin model. + * 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. */ - saveAdmin(admin: models.Admin): void + setConnMaxIdleTime(d: time.Duration): void } - /** - * Dao handles various db operations. - * - * You can think of Dao as a repository and service layer in one. - */ - interface Dao { + interface DB { /** - * 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 + * Stats returns database statistics. */ - 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 + stats(): DBStats } - interface Dao { + interface DB { /** - * DB returns the default dao db builder (*dbx.DB or *dbx.TX). + * 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. * - * Currently the default db builder is dao.concurrentDB but that may change in the future. + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. */ - db(): dbx.Builder + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) } - interface Dao { + interface DB { /** - * ConcurrentDB returns the dao concurrent (aka. multiple open connections) - * db builder (*dbx.DB or *dbx.TX). + * 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. * - * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - concurrentDB(): dbx.Builder + prepare(query: string): (Stmt | undefined) } - interface Dao { + interface DB { /** - * 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. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - nonconcurrentDB(): dbx.Builder + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Dao { + interface DB { /** - * Clone returns a new Dao with the same configuration options as the current one. + * 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. */ - clone(): (Dao | undefined) + exec(query: string, ...args: any[]): Result } - interface Dao { + interface DB { /** - * WithoutHooks returns a new Dao with the same configuration options - * as the current one, but without create/update/delete hooks. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - withoutHooks(): (Dao | undefined) + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) } - interface Dao { + interface DB { /** - * ModelQuery creates a new preconfigured select query with preset - * SELECT, FROM and other common fields based on the provided model. + * 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. */ - modelQuery(m: models.Model): (dbx.SelectQuery | undefined) + query(query: string, ...args: any[]): (Rows | undefined) } - interface Dao { + interface DB { /** - * FindById finds a single db record with the specified id and - * scans the result into m. + * 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. */ - findById(m: models.Model, id: string): void + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) } - interface Dao { + interface DB { /** - * RunInTransaction wraps fn into a transaction. + * 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. * - * It is safe to nest RunInTransaction calls as long as you use the txDao. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - runInTransaction(fn: (txDao: Dao) => void): void + queryRow(query: string, ...args: any[]): (Row | undefined) } - interface Dao { + interface DB { /** - * Delete deletes the provided model. + * 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. */ - delete(m: models.Model): void + beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) } - interface Dao { + interface DB { /** - * Save persists the provided model in the database. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. * - * 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(). + * Begin uses context.Background internally; to specify the context, use + * BeginTx. */ - save(m: models.Model): void + begin(): (Tx | undefined) } - interface Dao { + interface DB { /** - * CollectionQuery returns a new Collection select query. + * Driver returns the database's underlying driver. */ - collectionQuery(): (dbx.SelectQuery | undefined) + driver(): driver.Driver } - interface Dao { + interface DB { /** - * FindCollectionsByType finds all collections by the given type. + * 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. */ - findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> + conn(ctx: context.Context): (Conn | undefined) } - interface Dao { + /** + * 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 { /** - * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. + * Commit commits the transaction. */ - findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) + commit(): void } - interface Dao { + interface Tx { /** - * 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. + * Rollback aborts the transaction. */ - isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean + rollback(): void } - interface Dao { + interface Tx { /** - * FindCollectionReferences returns information for all - * relation schema fields referencing the provided collection. + * PrepareContext creates a prepared statement for use within a transaction. * - * 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. + * 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. */ - findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) } - interface Dao { + interface Tx { /** - * DeleteCollection deletes the provided Collection model. - * This method automatically deletes the related collection records table. + * Prepare creates a prepared statement for use within a transaction. * - * 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 + * 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. */ - deleteCollection(collection: models.Collection): void + prepare(query: string): (Stmt | undefined) } - interface Dao { + interface Tx { /** - * SaveCollection persists the provided Collection model and updates - * its related records table schema. + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. * - * 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(). + * 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. */ - saveCollection(collection: models.Collection): void + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) } - interface Dao { + interface Tx { /** - * ImportCollections imports the provided collections list within a single transaction. + * Stmt returns a transaction-specific prepared statement from + * an existing statement. * - * 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). + * 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) * - * NB2! This method doesn't perform validations on the imported collections data! - * If you need validations, use [forms.CollectionsImport]. + * 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. */ - importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void + stmt(stmt: Stmt): (Stmt | undefined) } - interface Dao { + interface Tx { /** - * 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. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Dao { + interface Tx { /** - * SaveExternalAuth upserts the provided ExternalAuth model. + * 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. */ - saveExternalAuth(model: models.ExternalAuth): void + exec(query: string, ...args: any[]): Result } - interface Dao { + interface Tx { /** - * DeleteExternalAuth deletes the provided ExternalAuth model. + * QueryContext executes a query that returns rows, typically a SELECT. */ - deleteExternalAuth(model: models.ExternalAuth): void + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) } - interface Dao { + interface Tx { /** - * ParamQuery returns a new Param select query. + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - paramQuery(): (dbx.SelectQuery | undefined) + query(query: string, ...args: any[]): (Rows | undefined) } - interface Dao { + interface Tx { /** - * FindParamByKey finds the first Param model with the provided key. + * 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. */ - findParamByKey(key: string): (models.Param | undefined) + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) } - interface Dao { + interface Tx { /** - * SaveParam creates or updates a Param model by the provided key-value pair. - * The value argument will be encoded as json string. + * 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. * - * If `optEncryptionKey` is provided it will encrypt the value before storing it. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - saveParam(key: string, value: any, ...optEncryptionKey: string[]): void + queryRow(query: string, ...args: any[]): (Row | undefined) } - interface Dao { - /** - * DeleteParam deletes the provided Param model. - */ - deleteParam(param: models.Param): void + /** + * Stmt is a prepared statement. + * A Stmt is safe for concurrent use by multiple goroutines. + * + * If a Stmt is prepared on a Tx or Conn, it will be bound to a single + * underlying connection forever. If the Tx or Conn closes, the Stmt will + * become unusable and all operations will return an error. + * If a Stmt is prepared on a DB, it will remain usable for the lifetime of the + * DB. When the Stmt needs to execute on a new underlying connection, it will + * prepare itself on the new connection automatically. + */ + interface Stmt { } - interface Dao { + interface Stmt { /** - * RecordQuery returns a new Record select query. + * ExecContext executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. */ - recordQuery(collection: models.Collection): (dbx.SelectQuery | undefined) + execContext(ctx: context.Context, ...args: any[]): Result } - interface Dao { + interface Stmt { /** - * FindRecordById finds the Record model by its id. + * 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. */ - findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) + exec(...args: any[]): Result } - interface Dao { + interface Stmt { /** - * FindRecordsByIds finds all Record models by the provided ids. - * If no records are found, returns an empty slice. + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. */ - findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> + queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) } - interface Dao { + interface Stmt { /** - * 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: + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. * - * ``` - * expr1 := dbx.HashExp{"email": "test@example.com"} - * expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) - * dao.FindRecordsByExpr("example", expr1, expr2) - * ``` + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> + query(...args: any[]): (Rows | undefined) } - interface Dao { + interface Stmt { /** - * FindFirstRecordByData returns the first found record matching - * the provided key-value pair. + * 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. */ - findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) + queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) } - interface Dao { + interface Stmt { /** - * 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. + * 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. * - * 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 usage: * - * Example: + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) * - * ``` - * dao.FindRecordsByFilter("posts", "title ~ 'lorem ipsum' && visible = true", "-created", 10) - * ``` + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> + queryRow(...args: any[]): (Row | undefined) } - interface Dao { + interface Stmt { /** - * 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'") - * ``` + * Close closes the statement. */ - findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) + close(): void } - interface Dao { + /** + * 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 { /** - * 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. + * 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. * - * 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"}` + * Every call to Scan, even the first one, must be preceded by a call to Next. */ - isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean + next(): boolean } - interface Dao { + interface Rows { /** - * FindAuthRecordByToken finds the auth record associated with the provided JWT token. + * 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. * - * Returns an error if the JWT token is invalid, expired or not associated to an auth collection record. + * 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. */ - findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) + nextResultSet(): boolean } - interface Dao { + interface Rows { /** - * 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. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit Close. */ - findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) + err(): void } - interface Dao { + interface Rows { /** - * 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. + * Columns returns the column names. + * Columns returns an error if the rows are closed. */ - findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) + columns(): Array } - interface Dao { + interface Rows { /** - * 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. + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. */ - suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string + columnTypes(): Array<(ColumnType | undefined)> } - interface Dao { + interface Rows { /** - * CanAccessRecord checks if a record is allowed to be accessed by the - * specified requestData and accessRule. + * 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. * - * Rule and db checks are ignored in case requestData.Admin is set. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * The returned error indicate that something unexpected happened during - * the check (eg. invalid rule or db error). + * ``` + * *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) + * ``` * - * The method always return false on invalid access rule or db error. + * 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. * - * Example: + * 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. * - * ``` - * 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 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 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 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. * - * 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. + * 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. * - * This method will also cascade the delete operation to all linked - * relational records (delete or unset, depending on the rel settings). + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or *RawBytes. * - * 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. + * For scanning into *bool, the source may be true, false, 1, 0, or + * string inputs parseable by strconv.ParseBool. * - * 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. + * 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. * - * Returns a map with the failed expand parameters and their errors. + * If any of the first arguments implementing Scanner returns an error, + * that error will be wrapped in the returned error */ - expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict + scan(...dest: any[]): void } - // @ts-ignore - import validation = ozzo_validation - interface Dao { + interface Rows { /** - * 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. + * 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. */ - syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void + close(): void } - interface Dao { + /** + * A Result summarizes an executed SQL command. + */ + interface Result { /** - * RequestQuery returns a new Request logs select query. + * 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. */ - requestQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + lastInsertId(): number /** - * FindRequestById finds a single Request log by its id. + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. */ - findRequestById(id: string): (models.Request | undefined) + rowsAffected(): number } - interface Dao { - /** - * RequestsStats returns hourly grouped requests logs statistics. - */ - requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> +} + +namespace migrate { + /** + * MigrationsList defines a list with migration definitions + */ + interface MigrationsList { } - interface Dao { + interface MigrationsList { /** - * DeleteOldRequests delete all requests that are created before createdBefore. + * Item returns a single migration from the list by its index. */ - deleteOldRequests(createdBefore: time.Time): void + item(index: number): (Migration | undefined) } - interface Dao { + interface MigrationsList { /** - * SaveRequest upserts the provided Request model. + * Items returns the internal migrations list slice. */ - saveRequest(request: models.Request): void + items(): Array<(Migration | undefined)> } - interface Dao { + interface MigrationsList { /** - * FindSettings returns and decode the serialized app settings param value. + * Register adds new migration definition to the list. * - * 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. + * If `optFilename` is not provided, it will try to get the name from its .go file. * - * Returns an error if it fails to decode the stored serialized param value. + * The list will be sorted automatically based on the migrations file name. */ - findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) + register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void } - interface Dao { +} + +/** + * 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 { /** - * SaveSettings persists the specified settings configuration. - * - * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void + verifyAudience(cmp: string, req: boolean): boolean } - interface Dao { + interface MapClaims { /** - * HasTable checks if a table (or view) with the provided name exists (case insensitive). + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. */ - hasTable(tableName: string): boolean + verifyExpiresAt(cmp: number, req: boolean): boolean } - interface Dao { + interface MapClaims { /** - * TableColumns returns all column names of a single table by its name. + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. */ - tableColumns(tableName: string): Array + verifyIssuedAt(cmp: number, req: boolean): boolean } - interface Dao { + interface MapClaims { /** - * TableInfo returns the `table_info` pragma result for the specified table. + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. */ - tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> + verifyNotBefore(cmp: number, req: boolean): boolean } - interface Dao { + interface MapClaims { /** - * 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. + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - tableIndexes(tableName: string): _TygojaDict + verifyIssuer(cmp: string, req: boolean): boolean } - interface Dao { + interface MapClaims { /** - * 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! + * 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. */ - deleteTable(tableName: string): void + valid(): void } - interface Dao { +} + +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 { /** - * Vacuum executes VACUUM on the current dao.DB() instance in order to - * reclaim unused db disk space. + * Scopes returns the context associated with the provider (if any). */ - vacuum(): void - } - interface Dao { + context(): context.Context /** - * 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! + * SetContext assigns the specified context to the current provider. */ - deleteView(name: string): void - } - interface Dao { + setContext(ctx: context.Context): void /** - * 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! + * Scopes returns the provider access permissions that will be requested. */ - saveView(name: string, selectQuery: string): void - } - interface Dao { + scopes(): Array /** - * 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. + * SetScopes sets the provider access permissions that will be requested later. */ - createViewSchema(selectQuery: string): schema.Schema - } - interface Dao { + setScopes(scopes: Array): void /** - * FindRecordByViewFile returns the original models.Record of the - * provided view collection file. + * ClientId returns the provider client's app ID. */ - 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 { + clientId(): string /** - * 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. + * SetClientId sets the provider client's ID. */ - db(): (dbx.DB | undefined) + setClientId(clientId: string): void /** - * 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. + * ClientSecret returns the provider client's app secret. */ - dao(): (daos.Dao | undefined) + clientSecret(): string /** - * 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. + * SetClientSecret sets the provider client's app secret. */ - logsDB(): (dbx.DB | undefined) + setClientSecret(secret: string): void /** - * 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. + * RedirectUrl returns the end address to redirect the user + * going through the OAuth flow. */ - logsDao(): (daos.Dao | undefined) + redirectUrl(): string /** - * DataDir returns the app data directory path. + * SetRedirectUrl sets the provider's RedirectUrl. */ - dataDir(): string + setRedirectUrl(url: string): void /** - * EncryptionEnv returns the name of the app secret env key - * (used for settings encryption). + * AuthUrl returns the provider's authorization service url. */ - encryptionEnv(): string + authUrl(): string /** - * IsDebug returns whether the app is in debug mode - * (showing more detailed error logs, executed sql statements, etc.). + * SetAuthUrl sets the provider's AuthUrl. */ - isDebug(): boolean + setAuthUrl(url: string): void /** - * Settings returns the loaded app settings. + * TokenUrl returns the provider's token exchange service url. */ - settings(): (settings.Settings | undefined) + tokenUrl(): string /** - * Cache returns the app internal cache store. + * SetTokenUrl sets the provider's TokenUrl. */ - cache(): (store.Store | undefined) + setTokenUrl(url: string): void /** - * SubscriptionsBroker returns the app realtime subscriptions broker instance. + * UserApiUrl returns the provider's user info api url. */ - subscriptionsBroker(): (subscriptions.Broker | undefined) + userApiUrl(): string /** - * NewMailClient creates and returns a configured app mail client. + * SetUserApiUrl sets the provider's UserApiUrl. */ - newMailClient(): mailer.Mailer + setUserApiUrl(url: string): void /** - * 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. + * Client returns an http client using the provided token. */ - newFilesystem(): (filesystem.System | undefined) + client(token: oauth2.Token): (http.Client | 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. + * BuildAuthUrl returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. */ - newBackupsFilesystem(): (filesystem.System | undefined) + buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string /** - * RefreshSettings reinitializes and reloads the stored application settings. + * FetchToken converts an authorization code to token. */ - refreshSettings(): void + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) /** - * IsBootstrapped checks if the application was initialized - * (aka. whether Bootstrap() was called). + * FetchRawUserData requests and marshalizes into `result` the + * the OAuth user api response. */ - isBootstrapped(): boolean + fetchRawUserData(token: oauth2.Token): string /** - * Bootstrap takes care for initializing the application - * (open db connections, load settings, etc.). - * - * It will call ResetBootstrapState() if the application was already bootstrapped. + * FetchAuthUser is similar to FetchRawUserData, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. */ - bootstrap(): void + 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 { /** - * ResetBootstrapState takes care for releasing initialized app resources - * (eg. closing db connections). + * MarshalJSON implements the [json.Marshaler] interface. */ - resetBootstrapState(): void + marshalJSON(): string + } + interface JsonArray { /** - * 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. + * Value implements the [driver.Valuer] interface. */ - createBackup(ctx: context.Context, name: string): void + value(): driver.Value + } + interface JsonArray { /** - * 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. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. */ - restoreBackup(ctx: context.Context, name: string): void + scan(value: any): void + } + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { /** - * Restart restarts the current running application process. - * - * Currently it is relying on execve so it is supported only on UNIX based systems. + * MarshalJSON implements the [json.Marshaler] interface. */ - restart(): void + marshalJSON(): string + } + interface JsonMap { /** - * OnBeforeBootstrap hook is triggered before initializing the main - * application resources (eg. before db open and initial settings load). + * 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). */ - onBeforeBootstrap(): (hook.Hook | undefined) + get(key: string): any + } + interface JsonMap { /** - * OnAfterBootstrap hook is triggered after initializing the main - * application resources (eg. after db open and initial settings load). + * 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). */ - onAfterBootstrap(): (hook.Hook | undefined) + set(key: string, value: any): void + } + interface JsonMap { /** - * OnBeforeServe hook is triggered before serving the internal router (echo), - * allowing you to adjust its options and attach new routes or middlewares. + * Value implements the [driver.Valuer] interface. */ - onBeforeServe(): (hook.Hook | undefined) + value(): driver.Value + } + interface JsonMap { /** - * 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. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. */ - onBeforeApiError(): (hook.Hook | undefined) + 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 { /** - * 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. + * Fields returns the registered schema fields. */ - onAfterApiError(): (hook.Hook | undefined) + fields(): Array<(SchemaField | undefined)> + } + interface Schema { /** - * OnTerminate hook is triggered when the app is in the process - * of being terminated (eg. on SIGTERM signal). + * InitFieldsOptions calls `InitOptions()` for all schema fields. */ - onTerminate(): (hook.Hook | undefined) + initFieldsOptions(): void + } + interface Schema { /** - * 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. + * Clone creates a deep clone of the current schema. */ - onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) + clone(): (Schema | undefined) + } + interface Schema { /** - * 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. + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. */ - onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) + asMap(): _TygojaDict + } + interface Schema { /** - * 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. + * GetFieldById returns a single field by its id. */ - onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) + getFieldById(id: string): (SchemaField | undefined) + } + interface Schema { /** - * 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. + * GetFieldByName returns a single field by its name. */ - onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) + getFieldByName(name: string): (SchemaField | undefined) + } + interface Schema { /** - * OnModelBeforeDelete hook is triggered before deleting an - * existing entry from the DB. + * RemoveField removes a single schema field by its id. * - * 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. + * This method does nothing if field with `id` doesn't exist. */ - onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) + removeField(id: string): void + } + interface Schema { /** - * OnModelAfterDelete hook is triggered after successfully deleting an - * existing entry from the DB. + * AddField registers the provided newField to the current schema. * - * 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. + * 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. */ - onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) + addField(newField: SchemaField): void + } + interface Schema { /** - * 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. + * 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. */ - onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) + validate(): void + } + interface Schema { /** - * OnMailerAfterAdminResetPasswordSend hook is triggered after - * admin password reset email was successfully sent. + * MarshalJSON implements the [json.Marshaler] interface. */ - onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) + marshalJSON(): string + } + interface Schema { /** - * 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. + * UnmarshalJSON implements the [json.Unmarshaler] interface. * - * 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. + * On success, all schema field options are auto initialized. */ - onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + unmarshalJSON(data: string): void + } + interface Schema { /** - * 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. + * Value implements the [driver.Valuer] interface. */ - onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + value(): driver.Value + } + interface Schema { /** - * 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. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. */ - onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + 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 { /** - * 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. + * TableName returns the Admin model SQL table name. */ - onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + tableName(): string + } + interface Admin { /** - * 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. + * ValidatePassword validates a plain password against the model's password. */ - onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + validatePassword(password: string): boolean + } + interface Admin { /** - * OnMailerAfterRecordChangeEmailSend hook is triggered after a - * verification email was successfully sent to an auth record. + * SetPassword sets cryptographically secure string to `model.Password`. * - * 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. + * Additionally this method also resets the LastResetSentAt and the TokenKey fields. */ - onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + setPassword(password: string): void + } + interface Admin { /** - * OnRealtimeConnectRequest hook is triggered right before establishing - * the SSE client connection. + * RefreshTokenKey generates and sets new random token key. */ - onRealtimeConnectRequest(): (hook.Hook | undefined) + 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 /** - * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted - * SSE client connection. + * rules */ - onRealtimeDisconnectRequest(): (hook.Hook | undefined) + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap + } + interface Collection { /** - * 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. + * TableName returns the Collection model SQL table name. */ - onRealtimeBeforeMessageSend(): (hook.Hook | undefined) + tableName(): string + } + interface Collection { /** - * OnRealtimeBeforeMessage hook is triggered right after sending - * an SSE message to a client. + * BaseFilesPath returns the storage dir path used by the collection. */ - onRealtimeAfterMessageSend(): (hook.Hook | undefined) + baseFilesPath(): string + } + interface Collection { /** - * OnRealtimeBeforeSubscribeRequest hook is triggered before changing - * the client subscriptions, allowing you to further validate and - * modify the submitted change. + * IsBase checks if the current collection has "base" type. */ - onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) + isBase(): boolean + } + interface Collection { /** - * OnRealtimeAfterSubscribeRequest hook is triggered after the client - * subscriptions were successfully changed. + * IsAuth checks if the current collection has "auth" type. */ - onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) + isAuth(): boolean + } + interface Collection { /** - * 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. + * IsView checks if the current collection has "view" type. */ - onSettingsListRequest(): (hook.Hook | undefined) + isView(): boolean + } + interface Collection { /** - * 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. + * MarshalJSON implements the [json.Marshaler] interface. */ - onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) + marshalJSON(): string + } + interface Collection { /** - * OnSettingsAfterUpdateRequest hook is triggered after each - * successful API Settings update request. + * BaseOptions decodes the current collection options and returns them + * as new [CollectionBaseOptions] instance. */ - onSettingsAfterUpdateRequest(): (hook.Hook | undefined) + baseOptions(): CollectionBaseOptions + } + interface Collection { /** - * 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. + * AuthOptions decodes the current collection options and returns them + * as new [CollectionAuthOptions] instance. */ - onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) + authOptions(): CollectionAuthOptions + } + interface Collection { /** - * 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. + * ViewOptions decodes the current collection options and returns them + * as new [CollectionViewOptions] instance. */ - onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + viewOptions(): CollectionViewOptions + } + interface Collection { /** - * 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. + * NormalizeOptions updates the current collection options with a + * new normalized state based on the collection type. */ - onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + normalizeOptions(): void + } + interface Collection { /** - * 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. + * DecodeOptions decodes the current collection options into the + * provided "result" (must be a pointer). */ - onAdminsListRequest(): (hook.Hook | undefined) + decodeOptions(result: any): void + } + interface Collection { /** - * 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. + * SetOptions normalizes and unmarshals the specified options into m.Options. */ - onAdminViewRequest(): (hook.Hook | undefined) + 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 { /** - * 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. + * TableName returns the table name associated to the current Record model. */ - onAdminBeforeCreateRequest(): (hook.Hook | undefined) + tableName(): string + } + interface Record { /** - * OnAdminAfterCreateRequest hook is triggered after each - * successful API Admin create request. + * Collection returns the Collection model associated to the current Record model. */ - onAdminAfterCreateRequest(): (hook.Hook | undefined) + collection(): (Collection | undefined) + } + interface Record { /** - * 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. + * 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. */ - onAdminBeforeUpdateRequest(): (hook.Hook | undefined) + originalCopy(): (Record | undefined) + } + interface Record { /** - * OnAdminAfterUpdateRequest hook is triggered after each - * successful API Admin update request. + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. */ - onAdminAfterUpdateRequest(): (hook.Hook | undefined) + cleanCopy(): (Record | undefined) + } + interface Record { /** - * 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. + * Expand returns a shallow copy of the current Record model expand data. */ - onAdminBeforeDeleteRequest(): (hook.Hook | undefined) + expand(): _TygojaDict + } + interface Record { /** - * OnAdminAfterDeleteRequest hook is triggered after each - * successful API Admin delete request. + * SetExpand shallow copies the provided data to the current Record model's expand. */ - onAdminAfterDeleteRequest(): (hook.Hook | undefined) + setExpand(expand: _TygojaDict): void + } + interface Record { /** - * OnAdminAuthRequest hook is triggered on each successful API Admin - * authentication request (sign-in, token refresh, etc.). + * MergeExpand merges recursively the provided expand data into + * the current model's expand (if any). * - * Could be used to additionally validate or modify the - * authenticated admin data and token. + * 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). */ - onAdminAuthRequest(): (hook.Hook | undefined) + mergeExpand(expand: _TygojaDict): void + } + interface Record { /** - * 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]). + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. */ - onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) + schemaData(): _TygojaDict + } + interface Record { /** - * OnAdminAfterAuthWithPasswordRequest hook is triggered after each - * successful Admin auth with password API request. + * 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. */ - onAdminAfterAuthWithPasswordRequest(): (hook.Hook | undefined) + unknownData(): _TygojaDict + } + interface Record { /** - * 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. + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. */ - onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) + ignoreEmailVisibility(state: boolean): void + } + interface Record { /** - * OnAdminAfterAuthRefreshRequest hook is triggered after each - * successful auth refresh API request (right after generating a new auth token). + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). */ - onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) + withUnknownData(state: boolean): void + } + interface Record { /** - * OnAdminBeforeRequestPasswordResetRequest hook is triggered before each Admin - * request password reset API request (after request data load and before sending the reset email). + * Set sets the provided key-value data pair for the current Record model. * - * Could be used to additionally validate the request data or implement - * completely different password reset behavior. + * If the record collection has field with name matching the provided "key", + * the value will be further normalized according to the field rules. */ - onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) + set(key: string, value: any): void + } + interface Record { /** - * OnAdminAfterRequestPasswordResetRequest hook is triggered after each - * successful request password reset API request. + * Get returns a single record model data value for "key". */ - onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) + get(key: string): any + } + interface Record { /** - * 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. + * GetBool returns the data value for "key" as a bool. */ - onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) + getBool(key: string): boolean + } + interface Record { /** - * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. + * GetString returns the data value for "key" as a string. */ - onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) + getString(key: string): string + } + interface Record { /** - * 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. + * GetInt returns the data value for "key" as an int. */ - onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + getInt(key: string): number + } + interface Record { /** - * 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. + * GetFloat returns the data value for "key" as a float64. */ - onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + getFloat(key: string): number + } + interface Record { /** - * 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. + * GetTime returns the data value for "key" as a [time.Time] instance. */ - onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + getTime(key: string): time.Time + } + interface Record { /** - * 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. + * GetDateTime returns the data value for "key" as a DateTime instance. */ - onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + getDateTime(key: string): types.DateTime + } + interface Record { /** - * 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. + * GetStringSlice returns the data value for "key" as a slice of unique strings. */ - onRecordAfterAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + getStringSlice(key: string): Array + } + interface Record { /** - * OnRecordBeforeAuthRefreshRequest hook is triggered before each Record - * auth refresh API request (right before generating a new auth token). + * ExpandedOne retrieves a single relation Record from the already + * loaded expand data of the current model. * - * 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 requested expand relation is multiple, this method returns + * only first available Record from the expanded relation. * - * 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. + * Returns nil if there is no such expand relation loaded. */ - onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) + expandedOne(relField: string): (Record | undefined) + } + interface Record { /** - * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. + * ExpandedAll retrieves a slice of relation Records from the already + * loaded expand data of the current model. * - * Could be used to validate or modify the response before returning it to the client. + * If the requested expand relation is single, this method normalizes + * the return result and will wrap the single model as a slice. * - * 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. + * Returns nil slice if there is no such expand relation loaded. */ - onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) + expandedAll(relField: string): Array<(Record | undefined)> + } + interface Record { /** - * OnRecordBeforeUnlinkExternalAuthRequest hook is triggered before each API record - * external auth unlink request (after models load and before the actual relation deletion). + * Retrieves the "key" json field value and unmarshals it into "result". * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. + * Example * - * 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. + * ``` + * result := struct { + * FirstName string `json:"first_name"` + * }{} + * err := m.UnmarshalJSONField("my_field_name", &result) + * ``` */ - onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + unmarshalJSONField(key: string, result: any): void + } + interface Record { /** - * 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. + * BaseFilesPath returns the storage dir path used by the record. */ - onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + baseFilesPath(): string + } + interface Record { /** - * 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. + * FindFileFieldByFile returns the first file type field for which + * any of the record's data contains the provided filename. */ - onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + findFileFieldByFile(filename: string): (schema.SchemaField | undefined) + } + interface Record { /** - * 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. + * Load bulk loads the provided data into the current Record model. */ - onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + load(data: _TygojaDict): void + } + interface Record { /** - * 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. + * ColumnValueMap implements [ColumnValueMapper] interface. */ - onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + columnValueMap(): _TygojaDict + } + interface Record { /** - * OnRecordAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. + * PublicExport exports only the record fields that are safe to be public. * - * 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. + * Fields marked as hidden will be exported only if `m.IgnoreEmailVisibility(true)` is set. */ - onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + publicExport(): _TygojaDict + } + interface Record { /** - * 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. + * MarshalJSON implements the [json.Marshaler] interface. * - * 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. + * Only the data exported by `PublicExport()` will be serialized. */ - onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + marshalJSON(): string + } + interface Record { /** - * 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. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + unmarshalJSON(data: string): void + } + interface Record { /** - * OnRecordBeforeConfirmVerificationRequest hook is triggered before each Record - * confirm verification API request (after request data load and before persistence). + * ReplaceModifers returns a new map with applied modifier + * values based on the current record and the specified data. * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * The resolved modifier keys will be removed. * - * 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. + * 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} + * ``` */ - onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + replaceModifers(data: _TygojaDict): _TygojaDict + } + interface Record { /** - * 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. + * Username returns the "username" auth record data value. */ - onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + username(): string + } + interface Record { /** - * 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). + * SetUsername sets the "username" auth record data value. * - * Could be used to additionally validate the request data or implement - * completely different request email change behavior. + * This method doesn't check whether the provided value is a valid username. * - * 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. + * Returns an error if the record is not from an auth collection. */ - onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + setUsername(username: string): void + } + interface Record { /** - * 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. + * Email returns the "email" auth record data value. */ - onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + email(): string + } + interface Record { /** - * OnRecordBeforeConfirmEmailChangeRequest hook is triggered before each Record - * confirm email change API request (after request data load and before persistence). + * SetEmail sets the "email" auth record data value. * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * This method doesn't check whether the provided value is a valid email. * - * 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. + * Returns an error if the record is not from an auth collection. */ - onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + setEmail(email: string): void + } + interface Record { /** - * 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. + * Verified returns the "emailVisibility" auth record data value. */ - onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + emailVisibility(): boolean + } + interface Record { /** - * 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. + * SetEmailVisibility sets the "emailVisibility" auth record data value. * - * 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. + * Returns an error if the record is not from an auth collection. */ - 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) + setEmailVisibility(visible: boolean): void + } + interface Record { /** - * 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. + * Verified returns the "verified" auth record data value. */ - onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + verified(): boolean + } + interface Record { /** - * OnRecordAfterCreateRequest hook is triggered after each - * successful API Record create request. + * SetVerified sets the "verified" auth record data value. * - * 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. + * Returns an error if the record is not from an auth collection. */ - onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + setVerified(verified: boolean): void + } + interface Record { /** - * 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. + * TokenKey returns the "tokenKey" auth record data value. */ - onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + tokenKey(): string + } + interface Record { /** - * OnRecordAfterUpdateRequest hook is triggered after each - * successful API Record update request. + * SetTokenKey sets the "tokenKey" auth record data value. * - * 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. + * Returns an error if the record is not from an auth collection. */ - onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + setTokenKey(key: string): void + } + interface Record { /** - * 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. + * RefreshTokenKey generates and sets new random auth record "tokenKey". * - * 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. + * Returns an error if the record is not from an auth collection. */ - onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + refreshTokenKey(): void + } + interface Record { /** - * 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. + * LastResetSentAt returns the "lastResentSentAt" auth record data value. */ - onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + lastResetSentAt(): types.DateTime + } + interface Record { /** - * OnCollectionsListRequest hook is triggered on each API Collections list request. + * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. * - * Could be used to validate or modify the response before returning it to the client. + * Returns an error if the record is not from an auth collection. */ - onCollectionsListRequest(): (hook.Hook | undefined) + setLastResetSentAt(dateTime: types.DateTime): void + } + interface Record { /** - * 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. + * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. */ - onCollectionViewRequest(): (hook.Hook | undefined) + lastVerificationSentAt(): types.DateTime + } + interface Record { /** - * OnCollectionBeforeCreateRequest hook is triggered before each API Collection - * create request (after request data load and before model persistence). + * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * Returns an error if the record is not from an auth collection. */ - onCollectionBeforeCreateRequest(): (hook.Hook | undefined) + setLastVerificationSentAt(dateTime: types.DateTime): void + } + interface Record { /** - * OnCollectionAfterCreateRequest hook is triggered after each - * successful API Collection create request. + * PasswordHash returns the "passwordHash" auth record data value. */ - onCollectionAfterCreateRequest(): (hook.Hook | undefined) + passwordHash(): string + } + interface Record { /** - * OnCollectionBeforeUpdateRequest hook is triggered before each API Collection - * update request (after request data load and before model persistence). + * ValidatePassword validates a plain password against the auth record password. * - * 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. + * Returns false if the password is incorrect or record is not from an auth collection. */ - onCollectionAfterUpdateRequest(): (hook.Hook | undefined) + validatePassword(password: string): boolean + } + interface Record { /** - * OnCollectionBeforeDeleteRequest hook is triggered before each API - * Collection delete request (after model load and before actual deletion). + * SetPassword sets cryptographically secure string to the auth record "password" field. + * This method also resets the "lastResetSentAt" and the "tokenKey" fields. * - * 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. + * Returns an error if the record is not from an auth collection or + * an empty password is provided. */ - onCollectionAfterDeleteRequest(): (hook.Hook | undefined) + 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 /** - * 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. + * @todo consider changing to Body? */ - onCollectionsBeforeImportRequest(): (hook.Hook | undefined) + data: _TygojaDict + headers: _TygojaDict + authRecord?: Record + admin?: Admin + } + interface RequestData { /** - * OnCollectionsAfterImportRequest hook is triggered after each - * successful API collections import request. + * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. */ - onCollectionsAfterImportRequest(): (hook.Hook | undefined) + hasModifierDataKeys(): boolean } } -/** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. - */ -namespace cobra { - interface Command { +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 /** - * GenBashCompletion generates bash completion file and writes to the passed writer. + * Deprecated: Will be removed in v0.9+ */ - genBashCompletion(w: io.Writer): void + 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 Command { + interface Settings { /** - * GenBashCompletionFile generates bash completion file. + * Validate makes Settings validatable by implementing [validation.Validatable] interface. */ - genBashCompletionFile(filename: string): void + validate(): void } - interface Command { + interface Settings { /** - * GenBashCompletionFileV2 generates Bash completion version 2. + * Merge merges `other` settings into the current one. */ - genBashCompletionFileV2(filename: string, includeDesc: boolean): void + merge(other: Settings): void } - interface Command { + interface Settings { /** - * GenBashCompletionV2 generates Bash completion file version 2 - * and writes it to the passed writer. + * Clone creates a new deep copy of the current settings. */ - genBashCompletionV2(w: io.Writer, includeDesc: boolean): void + clone(): (Settings | undefined) } - // @ts-ignore - import flag = pflag - /** - * Command is just that, a command for your application. - * E.g. 'go run ...' - 'run' is the command. Cobra requires - * you to define the usage and description as part of your command - * definition to ensure usability. - */ - interface Command { + interface Settings { /** - * Use is the one-line usage message. - * Recommended syntax is as follows: - * ``` - * [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. - * ... indicates that you can specify multiple values for the previous argument. - * | indicates mutually exclusive information. You can use the argument to the left of the separator or the - * argument to the right of the separator. You cannot use both arguments in a single use of the command. - * { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are - * optional, they are enclosed in brackets ([ ]). - * ``` - * Example: add [-F file | -D dir]... [-f format] profile + * RedactClone creates a new deep copy of the current settings, + * while replacing the secret values with `******`. */ - use: string + redactClone(): (Settings | undefined) + } + interface Settings { /** - * Aliases is an array of aliases that can be used instead of the first word in Use. + * NamedAuthProviderConfigs returns a map with all registered OAuth2 + * provider configurations (indexed by their name identifier). */ - aliases: Array + 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 { /** - * SuggestFor is an array of command names for which this command will be suggested - - * similar to aliases but only suggests. + * AdminQuery returns a new Admin select query. */ - suggestFor: Array + adminQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { /** - * Short is the short description shown in the 'help' output. + * FindAdminById finds the admin with the provided id. */ - short: string + findAdminById(id: string): (models.Admin | undefined) + } + interface Dao { /** - * The group id under which this subcommand is grouped in the 'help' output of its parent. + * FindAdminByEmail finds the admin with the provided email address. */ - groupID: string + findAdminByEmail(email: string): (models.Admin | undefined) + } + interface Dao { /** - * Long is the long message shown in the 'help ' output. + * FindAdminByToken finds the admin associated with the provided JWT token. + * + * Returns an error if the JWT token is invalid or expired. */ - long: string + findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) + } + interface Dao { /** - * Example is examples of how to use the command. + * TotalAdmins returns the number of existing admin records. */ - example: string + totalAdmins(): number + } + interface Dao { /** - * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions + * IsAdminEmailUnique checks if the provided email address is not + * already in use by other admins. */ - validArgs: Array + isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean + } + interface Dao { /** - * ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. - * It is a dynamic version of using ValidArgs. - * Only one of ValidArgs and ValidArgsFunction can be used for a command. + * DeleteAdmin deletes the provided Admin model. + * + * Returns an error if there is only 1 admin. */ - validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] + deleteAdmin(admin: models.Admin): void + } + interface Dao { /** - * Expected arguments + * SaveAdmin upserts the provided Admin model. */ - args: PositionalArgs + 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 { /** - * ArgAliases is List of aliases for ValidArgs. - * These are not suggested to the user in the shell completion, - * but accepted if entered manually. + * MaxLockRetries specifies the default max "database is locked" auto retry attempts. */ - argAliases: Array + maxLockRetries: number /** - * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - * For portability with other shells, it is recommended to instead use ValidArgsFunction + * ModelQueryTimeout is the default max duration of a running ModelQuery(). + * + * This field has no effect if an explicit query context is already specified. */ - bashCompletionFunction: string + modelQueryTimeout: time.Duration /** - * Deprecated defines, if this command is deprecated and should print this string when used. + * write hooks */ - deprecated: string + 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 { /** - * Annotations are key/value pairs that can be used by applications to identify or - * group commands. + * 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. */ - annotations: _TygojaDict + db(): dbx.Builder + } + interface Dao { /** - * Version defines the version for this command. If this value is non-empty and the command does not - * define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - * will print content of the "Version" variable. A shorthand "v" flag will also be added if the - * command does not define one. + * 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. */ - version: string + concurrentDB(): dbx.Builder + } + interface Dao { /** - * The *Run functions are executed in the following order: - * ``` - * * PersistentPreRun() - * * PreRun() - * * Run() - * * PostRun() - * * PersistentPostRun() - * ``` - * All functions get the same args, the arguments after the command name. + * NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) + * db builder (*dbx.DB or *dbx.TX). * - * PersistentPreRun: children of this command will inherit and execute. + * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. */ - persistentPreRun: (cmd: Command, args: Array) => void + nonconcurrentDB(): dbx.Builder + } + interface Dao { /** - * PersistentPreRunE: PersistentPreRun but returns an error. + * Clone returns a new Dao with the same configuration options as the current one. */ - persistentPreRunE: (cmd: Command, args: Array) => void + clone(): (Dao | undefined) + } + interface Dao { /** - * PreRun: children of this command will not inherit. + * WithoutHooks returns a new Dao with the same configuration options + * as the current one, but without create/update/delete hooks. */ - preRun: (cmd: Command, args: Array) => void + withoutHooks(): (Dao | undefined) + } + interface Dao { /** - * PreRunE: PreRun but returns an error. + * ModelQuery creates a new preconfigured select query with preset + * SELECT, FROM and other common fields based on the provided model. */ - preRunE: (cmd: Command, args: Array) => void + modelQuery(m: models.Model): (dbx.SelectQuery | undefined) + } + interface Dao { /** - * Run: Typically the actual work function. Most commands will only implement this. + * FindById finds a single db record with the specified id and + * scans the result into m. */ - run: (cmd: Command, args: Array) => void + findById(m: models.Model, id: string): void + } + interface Dao { /** - * RunE: Run but returns an error. + * RunInTransaction wraps fn into a transaction. + * + * It is safe to nest RunInTransaction calls as long as you use the txDao. */ - runE: (cmd: Command, args: Array) => void + runInTransaction(fn: (txDao: Dao) => void): void + } + interface Dao { /** - * PostRun: run after the Run command. + * Delete deletes the provided model. */ - postRun: (cmd: Command, args: Array) => void + delete(m: models.Model): void + } + interface Dao { /** - * PostRunE: PostRun but returns an error. + * 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(). */ - postRunE: (cmd: Command, args: Array) => void + save(m: models.Model): void + } + interface Dao { /** - * PersistentPostRun: children of this command will inherit and execute after PostRun. + * CollectionQuery returns a new Collection select query. */ - persistentPostRun: (cmd: Command, args: Array) => void + collectionQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { /** - * PersistentPostRunE: PersistentPostRun but returns an error. + * FindCollectionsByType finds all collections by the given type. */ - persistentPostRunE: (cmd: Command, args: Array) => void + findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> + } + interface Dao { /** - * FParseErrWhitelist flag parse errors to be ignored + * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. */ - fParseErrWhitelist: FParseErrWhitelist + findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) + } + interface Dao { /** - * CompletionOptions is a set of options to control the handling of shell completion + * 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. */ - completionOptions: CompletionOptions + isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean + } + interface Dao { /** - * TraverseChildren parses flags on all parents before executing child command. + * 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. */ - traverseChildren: boolean + findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict + } + interface Dao { /** - * Hidden defines, if this command is hidden and should NOT show up in the list of available commands. + * 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 */ - hidden: boolean + deleteCollection(collection: models.Collection): void + } + interface Dao { /** - * SilenceErrors is an option to quiet errors down stream. - */ - silenceErrors: boolean - /** - * SilenceUsage is an option to silence usage when an error occurs. - */ - silenceUsage: boolean - /** - * DisableFlagParsing disables the flag parsing. - * If this is true all flags will be passed to the command as arguments. - */ - disableFlagParsing: boolean - /** - * DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - * will be printed by generating docs for this command. - */ - disableAutoGenTag: boolean - /** - * DisableFlagsInUseLine will disable the addition of [flags] to the usage - * line of a command when printing help or generating docs - */ - disableFlagsInUseLine: boolean - /** - * DisableSuggestions disables the suggestions based on Levenshtein distance - * that go along with 'unknown command' messages. - */ - disableSuggestions: boolean - /** - * SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - * Must be > 0. + * 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(). */ - suggestionsMinimumDistance: number + saveCollection(collection: models.Collection): void } - interface Command { + interface Dao { /** - * Context returns underlying command context. If command was executed - * with ExecuteContext or the context was set with SetContext, the - * previously set context will be returned. Otherwise, nil is returned. + * ImportCollections imports the provided collections list within a single transaction. * - * Notice that a call to Execute and ExecuteC will replace a nil context of - * a command with a context.Background, so a background context will be - * returned by Context after one of these functions has been called. + * 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]. */ - context(): context.Context + importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void } - interface Command { + interface Dao { /** - * SetContext sets context for the command. This context will be overwritten by - * Command.ExecuteContext or Command.ExecuteContextC. + * ExternalAuthQuery returns a new ExternalAuth select query. */ - setContext(ctx: context.Context): void + externalAuthQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden - * particularly useful when testing. + * FindAllExternalAuthsByRecord returns all ExternalAuth models + * linked to the provided auth record. */ - setArgs(a: Array): void + findAllExternalAuthsByRecord(authRecord: models.Record): Array<(models.ExternalAuth | undefined)> } - interface Command { + interface Dao { /** - * SetOutput sets the destination for usage and error messages. - * If output is nil, os.Stderr is used. - * Deprecated: Use SetOut and/or SetErr instead + * FindExternalAuthByProvider returns the first available + * ExternalAuth model for the specified provider and providerId. */ - setOutput(output: io.Writer): void + findExternalAuthByProvider(provider: string): (models.ExternalAuth | undefined) } - interface Command { + interface Dao { /** - * SetOut sets the destination for usage messages. - * If newOut is nil, os.Stdout is used. + * FindExternalAuthByRecordAndProvider returns the first available + * ExternalAuth model for the specified record data and provider. */ - setOut(newOut: io.Writer): void + findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) } - interface Command { + interface Dao { /** - * SetErr sets the destination for error messages. - * If newErr is nil, os.Stderr is used. + * SaveExternalAuth upserts the provided ExternalAuth model. */ - setErr(newErr: io.Writer): void + saveExternalAuth(model: models.ExternalAuth): void } - interface Command { + interface Dao { /** - * SetIn sets the source for input data - * If newIn is nil, os.Stdin is used. + * DeleteExternalAuth deletes the provided ExternalAuth model. */ - setIn(newIn: io.Reader): void + deleteExternalAuth(model: models.ExternalAuth): void } - interface Command { + interface Dao { /** - * SetUsageFunc sets usage function. Usage can be defined by application. + * ParamQuery returns a new Param select query. */ - setUsageFunc(f: (_arg0: Command) => void): void + paramQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * SetUsageTemplate sets usage template. Can be defined by Application. + * FindParamByKey finds the first Param model with the provided key. */ - setUsageTemplate(s: string): void + findParamByKey(key: string): (models.Param | undefined) } - interface Command { + interface Dao { /** - * SetFlagErrorFunc sets a function to generate an error when flag parsing - * fails. + * 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. */ - setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void + saveParam(key: string, value: any, ...optEncryptionKey: string[]): void } - interface Command { + interface Dao { /** - * SetHelpFunc sets help function. Can be defined by Application. + * DeleteParam deletes the provided Param model. */ - setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void + deleteParam(param: models.Param): void } - interface Command { + interface Dao { /** - * SetHelpCommand sets help command. + * 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. */ - setHelpCommand(cmd: Command): void + recordQuery(collectionModelOrIdentifier: any): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * SetHelpCommandGroupID sets the group id of the help command. + * FindRecordById finds the Record model by its id. */ - setHelpCommandGroupID(groupID: string): void + findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) } - interface Command { + interface Dao { /** - * SetCompletionCommandGroupID sets the group id of the completion command. + * FindRecordsByIds finds all Record models by the provided ids. + * If no records are found, returns an empty slice. */ - setCompletionCommandGroupID(groupID: string): void + findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * SetHelpTemplate sets help template to be used. Application can use it to set custom template. + * @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) + * ``` */ - setHelpTemplate(s: string): void + findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * SetVersionTemplate sets version template to be used. Application can use it to set custom template. + * FindFirstRecordByData returns the first found record matching + * the provided key-value pair. */ - setVersionTemplate(s: string): void + findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) } - interface Command { + interface Dao { /** - * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. - * The user should not have a cyclic dependency on commands. + * 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) + * ``` */ - setGlobalNormalizationFunc(n: (f: flag.FlagSet, name: string) => flag.NormalizedName): void + findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * OutOrStdout returns output to stdout. + * 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'") + * ``` */ - outOrStdout(): io.Writer + findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * OutOrStderr returns output to stderr + * 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"}` */ - outOrStderr(): io.Writer + isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean } - interface Command { + interface Dao { /** - * ErrOrStderr returns output to stderr + * 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. */ - errOrStderr(): io.Writer + findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * InOrStdin returns input to stdin + * 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. */ - inOrStdin(): io.Reader + findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * UsageFunc returns either the function set by SetUsageFunc for this command - * or a parent, or it returns a default usage function. + * 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. */ - usageFunc(): (_arg0: Command) => void + findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * Usage puts out the usage for the command. - * Used when a user provides invalid input. - * Can be defined by user by overriding UsageFunc. + * 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. */ - usage(): void + suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string } - interface Command { + interface Dao { /** - * HelpFunc returns either the function set by SetHelpFunc for this command - * or a parent, or it returns a function with default help behavior. + * 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 { ... } + * ``` */ - helpFunc(): (_arg0: Command, _arg1: Array) => void + canAccessRecord(record: models.Record, requestData: models.RequestData, accessRule: string): boolean } - interface Command { + interface Dao { /** - * Help puts out the help for the command. - * Used when a user calls help [command]. - * Can be defined by user by overriding HelpFunc. + * 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(). */ - help(): void + saveRecord(record: models.Record): void } - interface Command { + interface Dao { /** - * UsageString returns usage string. + * 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). */ - usageString(): string + deleteRecord(record: models.Record): void } - interface Command { + interface Dao { /** - * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this - * command or a parent, or it returns a function which returns the original - * error. + * 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. */ - flagErrorFunc(): (_arg0: Command, _arg1: Error) => void + expandRecord(record: models.Record, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict } - interface Command { + interface Dao { /** - * UsagePadding return padding for the usage. + * 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. */ - usagePadding(): number + expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict } - interface Command { + // @ts-ignore + import validation = ozzo_validation + interface Dao { /** - * CommandPathPadding return padding for the command path. + * 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. */ - commandPathPadding(): number + syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void } - interface Command { + interface Dao { /** - * NamePadding returns padding for the name. + * RequestQuery returns a new Request logs select query. */ - namePadding(): number + requestQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * UsageTemplate returns usage template for the command. + * FindRequestById finds a single Request log by its id. */ - usageTemplate(): string + findRequestById(id: string): (models.Request | undefined) } - interface Command { + interface Dao { /** - * HelpTemplate return help template for the command. + * RequestsStats returns hourly grouped requests logs statistics. */ - helpTemplate(): string + requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> } - interface Command { + interface Dao { /** - * VersionTemplate return version template for the command. + * DeleteOldRequests delete all requests that are created before createdBefore. */ - versionTemplate(): string + deleteOldRequests(createdBefore: time.Time): void } - interface Command { + interface Dao { /** - * Find the target command given the args and command tree - * Meant to be run on the highest node. Only searches down. + * SaveRequest upserts the provided Request model. */ - find(args: Array): [(Command | undefined), Array] + saveRequest(request: models.Request): void } - interface Command { + interface Dao { /** - * Traverse the command tree to find the command, and parse args for - * each parent. + * 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. */ - traverse(args: Array): [(Command | undefined), Array] + findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) } - interface Command { + interface Dao { /** - * SuggestionsFor provides suggestions for the typedName. + * SaveSettings persists the specified settings configuration. + * + * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. */ - suggestionsFor(typedName: string): Array + saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void } - interface Command { + interface Dao { /** - * VisitParents visits all parents of the command and invokes fn on each parent. + * HasTable checks if a table (or view) with the provided name exists (case insensitive). */ - visitParents(fn: (_arg0: Command) => void): void + hasTable(tableName: string): boolean } - interface Command { + interface Dao { /** - * Root finds root command. + * TableColumns returns all column names of a single table by its name. */ - root(): (Command | undefined) + tableColumns(tableName: string): Array } - interface Command { + interface Dao { /** - * ArgsLenAtDash will return the length of c.Flags().Args at the moment - * when a -- was found during args parsing. + * TableInfo returns the `table_info` pragma result for the specified table. */ - argsLenAtDash(): number + tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> } - interface Command { + interface Dao { /** - * ExecuteContext is the same as Execute(), but sets the ctx on the command. - * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs - * functions. + * 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. */ - executeContext(ctx: context.Context): void + tableIndexes(tableName: string): _TygojaDict } - interface Command { + interface Dao { /** - * Execute uses the args (os.Args[1:] by default) - * and run through the command tree finding appropriate matches - * for commands and then corresponding flags. + * 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! */ - execute(): void + deleteTable(tableName: string): void } - interface Command { + interface Dao { /** - * ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. - * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs - * functions. + * Vacuum executes VACUUM on the current dao.DB() instance in order to + * reclaim unused db disk space. */ - executeContextC(ctx: context.Context): (Command | undefined) + vacuum(): void } - interface Command { + interface Dao { /** - * ExecuteC executes the command. + * 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! */ - executeC(): (Command | undefined) - } - interface Command { - validateArgs(args: Array): void + deleteView(name: string): void } - interface Command { + interface Dao { /** - * ValidateRequiredFlags validates all required flags are present and returns an error otherwise + * 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! */ - validateRequiredFlags(): void + saveView(name: string, selectQuery: string): void } - interface Command { + interface Dao { /** - * InitDefaultHelpFlag adds default help flag to c. - * It is called automatically by executing the c or by calling help and usage. - * If c already has help flag, it will do nothing. + * 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. */ - initDefaultHelpFlag(): void + createViewSchema(selectQuery: string): schema.Schema } - interface Command { + interface Dao { /** - * InitDefaultVersionFlag adds default version flag to c. - * It is called automatically by executing the c. - * If c already has a version flag, it will do nothing. - * If c.Version is empty, it will do nothing. + * FindRecordByViewFile returns the original models.Record of the + * provided view collection file. */ - initDefaultVersionFlag(): void + findRecordByViewFile(viewCollectionNameOrId: string, fileFieldName: string, filename: string): (models.Record | undefined) } - interface Command { +} + +/** + * 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 { /** - * InitDefaultHelpCmd adds default help command to c. - * It is called automatically by executing the c or by calling help and usage. - * If c already has help command or c has no subcommands, it will do nothing. + * 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. */ - initDefaultHelpCmd(): void - } - interface Command { + db(): (dbx.DB | undefined) /** - * ResetCommands delete parent, subcommand and help command from c. - */ - resetCommands(): void - } - interface Command { - /** - * Commands returns a sorted slice of child commands. + * 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. */ - commands(): Array<(Command | undefined)> - } - interface Command { + dao(): (daos.Dao | undefined) /** - * AddCommand adds one or more commands to this parent command. + * 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. */ - addCommand(...cmds: (Command | undefined)[]): void - } - interface Command { + logsDB(): (dbx.DB | undefined) /** - * Groups returns a slice of child command groups. + * 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. */ - groups(): Array<(Group | undefined)> - } - interface Command { + logsDao(): (daos.Dao | undefined) /** - * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group + * DataDir returns the app data directory path. */ - allChildCommandsHaveGroup(): boolean - } - interface Command { + dataDir(): string /** - * ContainsGroup return if groupID exists in the list of command groups. + * EncryptionEnv returns the name of the app secret env key + * (used for settings encryption). */ - containsGroup(groupID: string): boolean - } - interface Command { + encryptionEnv(): string /** - * AddGroup adds one or more command groups to this parent command. + * IsDebug returns whether the app is in debug mode + * (showing more detailed error logs, executed sql statements, etc.). */ - addGroup(...groups: (Group | undefined)[]): void - } - interface Command { + isDebug(): boolean /** - * RemoveCommand removes one or more commands from a parent command. + * Settings returns the loaded app settings. */ - removeCommand(...cmds: (Command | undefined)[]): void - } - interface Command { + settings(): (settings.Settings | undefined) /** - * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. + * Cache returns the app internal cache store. */ - print(...i: { - }[]): void - } - interface Command { + cache(): (store.Store | undefined) /** - * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. + * SubscriptionsBroker returns the app realtime subscriptions broker instance. */ - println(...i: { - }[]): void - } - interface Command { + subscriptionsBroker(): (subscriptions.Broker | undefined) /** - * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. + * NewMailClient creates and returns a configured app mail client. */ - printf(format: string, ...i: { - }[]): void - } - interface Command { + newMailClient(): mailer.Mailer /** - * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. + * 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. */ - printErr(...i: { - }[]): void - } - interface Command { + newFilesystem(): (filesystem.System | undefined) /** - * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. + * 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. */ - printErrln(...i: { - }[]): void - } - interface Command { + newBackupsFilesystem(): (filesystem.System | undefined) /** - * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. + * RefreshSettings reinitializes and reloads the stored application settings. */ - printErrf(format: string, ...i: { - }[]): void - } - interface Command { + refreshSettings(): void /** - * CommandPath returns the full path to this command. + * IsBootstrapped checks if the application was initialized + * (aka. whether Bootstrap() was called). */ - commandPath(): string - } - interface Command { + isBootstrapped(): boolean /** - * UseLine puts out the full usage for a given command (including parents). + * Bootstrap takes care for initializing the application + * (open db connections, load settings, etc.). + * + * It will call ResetBootstrapState() if the application was already bootstrapped. */ - useLine(): string - } - interface Command { + bootstrap(): void /** - * DebugFlags used to determine which flags have been assigned to which commands - * and which persist. + * ResetBootstrapState takes care for releasing initialized app resources + * (eg. closing db connections). */ - debugFlags(): void - } - interface Command { + resetBootstrapState(): void /** - * Name returns the command's name: the first word in the use line. + * 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. */ - name(): string - } - interface Command { + createBackup(ctx: context.Context, name: string): void /** - * HasAlias determines if a given string is an alias of the command. + * 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. */ - hasAlias(s: string): boolean - } - interface Command { + restoreBackup(ctx: context.Context, name: string): void /** - * CalledAs returns the command name or alias that was used to invoke - * this command or an empty string if the command has not been called. + * Restart restarts the current running application process. + * + * Currently it is relying on execve so it is supported only on UNIX based systems. */ - calledAs(): string - } - interface Command { + restart(): void /** - * NameAndAliases returns a list of the command name and all aliases + * OnBeforeBootstrap hook is triggered before initializing the main + * application resources (eg. before db open and initial settings load). */ - nameAndAliases(): string - } - interface Command { + onBeforeBootstrap(): (hook.Hook | undefined) /** - * HasExample determines if the command has example. + * OnAfterBootstrap hook is triggered after initializing the main + * application resources (eg. after db open and initial settings load). */ - hasExample(): boolean - } - interface Command { + onAfterBootstrap(): (hook.Hook | undefined) /** - * Runnable determines if the command is itself runnable. + * OnBeforeServe hook is triggered before serving the internal router (echo), + * allowing you to adjust its options and attach new routes or middlewares. */ - runnable(): boolean - } - interface Command { + onBeforeServe(): (hook.Hook | undefined) /** - * HasSubCommands determines if the command has children commands. + * 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. */ - hasSubCommands(): boolean - } - interface Command { + onBeforeApiError(): (hook.Hook | undefined) /** - * IsAvailableCommand determines if a command is available as a non-help command - * (this includes all non deprecated/hidden commands). + * 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. */ - isAvailableCommand(): boolean - } - interface Command { + onAfterApiError(): (hook.Hook | undefined) /** - * IsAdditionalHelpTopicCommand determines if a command is an additional - * help topic command; additional help topic command is determined by the - * fact that it is NOT runnable/hidden/deprecated, and has no sub commands that - * are runnable/hidden/deprecated. - * Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. + * OnTerminate hook is triggered when the app is in the process + * of being terminated (eg. on SIGTERM signal). */ - isAdditionalHelpTopicCommand(): boolean - } - interface Command { + onTerminate(): (hook.Hook | undefined) /** - * HasHelpSubCommands determines if a command has any available 'help' sub commands - * that need to be shown in the usage/help default template under 'additional help - * topics'. + * 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. */ - hasHelpSubCommands(): boolean - } - interface Command { + onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasAvailableSubCommands determines if a command has available sub commands that - * need to be shown in the usage/help default template under 'available commands'. + * 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. */ - hasAvailableSubCommands(): boolean - } - interface Command { + onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasParent determines if the command is a child command. + * 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. */ - hasParent(): boolean - } - interface Command { + onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) /** - * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. + * 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. */ - globalNormalizationFunc(): (f: flag.FlagSet, name: string) => flag.NormalizedName - } - interface Command { + onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) /** - * Flags returns the complete FlagSet that applies - * to this command (local and persistent declared here and by all parents). + * 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. */ - flags(): (flag.FlagSet | undefined) - } - interface Command { + onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) /** - * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. + * 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. */ - localNonPersistentFlags(): (flag.FlagSet | undefined) - } - interface Command { + onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) /** - * LocalFlags returns the local FlagSet specifically set in the current command. + * 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. */ - localFlags(): (flag.FlagSet | undefined) - } - interface Command { + onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) /** - * InheritedFlags returns all flags which were inherited from parent commands. + * OnMailerAfterAdminResetPasswordSend hook is triggered after + * admin password reset email was successfully sent. */ - inheritedFlags(): (flag.FlagSet | undefined) - } - interface Command { + onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) /** - * NonInheritedFlags returns all flags which were not inherited from parent commands. + * 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. */ - nonInheritedFlags(): (flag.FlagSet | undefined) - } - interface Command { + onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * PersistentFlags returns the persistent FlagSet specifically set in the current command. + * 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. */ - persistentFlags(): (flag.FlagSet | undefined) - } - interface Command { + onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * ResetFlags deletes all flags from command. + * 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. */ - resetFlags(): void - } - interface Command { + onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). + * 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. */ - hasFlags(): boolean - } - interface Command { + onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasPersistentFlags checks if the command contains persistent flags. + * 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. */ - hasPersistentFlags(): boolean - } - interface Command { + onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasLocalFlags checks if the command has flags specifically declared locally. + * 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. */ - hasLocalFlags(): boolean - } - interface Command { + onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasInheritedFlags checks if the command has flags inherited from its parent command. + * OnRealtimeConnectRequest hook is triggered right before establishing + * the SSE client connection. */ - hasInheritedFlags(): boolean - } - interface Command { + onRealtimeConnectRequest(): (hook.Hook | undefined) /** - * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire - * structure) which are not hidden or deprecated. + * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted + * SSE client connection. */ - hasAvailableFlags(): boolean - } - interface Command { + onRealtimeDisconnectRequest(): (hook.Hook | undefined) /** - * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. + * 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. */ - hasAvailablePersistentFlags(): boolean - } - interface Command { + onRealtimeBeforeMessageSend(): (hook.Hook | undefined) /** - * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden - * or deprecated. + * OnRealtimeBeforeMessage hook is triggered right after sending + * an SSE message to a client. */ - hasAvailableLocalFlags(): boolean - } - interface Command { + onRealtimeAfterMessageSend(): (hook.Hook | undefined) /** - * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are - * not hidden or deprecated. + * OnRealtimeBeforeSubscribeRequest hook is triggered before changing + * the client subscriptions, allowing you to further validate and + * modify the submitted change. */ - hasAvailableInheritedFlags(): boolean - } - interface Command { + onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) /** - * Flag climbs up the command tree looking for matching flag. + * OnRealtimeAfterSubscribeRequest hook is triggered after the client + * subscriptions were successfully changed. */ - flag(name: string): (flag.Flag | undefined) - } - interface Command { + onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) /** - * ParseFlags parses persistent flag tree and local flags. + * 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. */ - parseFlags(args: Array): void - } - interface Command { + onSettingsListRequest(): (hook.Hook | undefined) /** - * Parent returns a commands parent command. + * 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. */ - parent(): (Command | undefined) - } - interface Command { + onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) /** - * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. + * OnSettingsAfterUpdateRequest hook is triggered after each + * successful API Settings update request. */ - registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void - } - interface Command { + onSettingsAfterUpdateRequest(): (hook.Hook | undefined) /** - * InitDefaultCompletionCmd adds a default 'completion' command to c. - * This function will do nothing if any of the following is true: - * 1- the feature has been explicitly disabled by the program, - * 2- c has no subcommands (to avoid creating one), - * 3- c already has a 'completion' command provided by the program. + * 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. */ - initDefaultCompletionCmd(): void - } - interface Command { + onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenFishCompletion generates fish completion file and writes to the passed writer. + * 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. */ - genFishCompletion(w: io.Writer, includeDesc: boolean): void - } - interface Command { + onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenFishCompletionFile generates fish completion file. + * 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. */ - genFishCompletionFile(filename: string, includeDesc: boolean): void - } - interface Command { + onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors - * if the command is invoked with a subset (but not all) of the given flags. + * 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. */ - markFlagsRequiredTogether(...flagNames: string[]): void - } - interface Command { + onAdminsListRequest(): (hook.Hook | undefined) /** - * MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors - * if the command is invoked with more than one flag from the given set of flags. + * 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. */ - markFlagsMutuallyExclusive(...flagNames: string[]): void - } - interface Command { + onAdminViewRequest(): (hook.Hook | undefined) /** - * ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the - * first error encountered. - */ - validateFlagGroups(): void - } - interface Command { + * 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) /** - * GenPowerShellCompletionFile generates powershell completion file without descriptions. + * OnAdminAfterCreateRequest hook is triggered after each + * successful API Admin create request. */ - genPowerShellCompletionFile(filename: string): void - } - interface Command { + onAdminAfterCreateRequest(): (hook.Hook | undefined) /** - * GenPowerShellCompletion generates powershell completion file without descriptions - * and writes it to the passed writer. + * 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. */ - genPowerShellCompletion(w: io.Writer): void - } - interface Command { + onAdminBeforeUpdateRequest(): (hook.Hook | undefined) /** - * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. + * OnAdminAfterUpdateRequest hook is triggered after each + * successful API Admin update request. */ - genPowerShellCompletionFileWithDesc(filename: string): void - } - interface Command { + onAdminAfterUpdateRequest(): (hook.Hook | undefined) /** - * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions - * and writes it to the passed writer. + * 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. */ - genPowerShellCompletionWithDesc(w: io.Writer): void - } - interface Command { + onAdminBeforeDeleteRequest(): (hook.Hook | undefined) /** - * MarkFlagRequired instructs the various shell completion implementations to - * prioritize the named flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * OnAdminAfterDeleteRequest hook is triggered after each + * successful API Admin delete request. */ - markFlagRequired(name: string): void - } - interface Command { + onAdminAfterDeleteRequest(): (hook.Hook | undefined) /** - * MarkPersistentFlagRequired instructs the various shell completion implementations to - * prioritize the named persistent flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * 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. */ - markPersistentFlagRequired(name: string): void - } - interface Command { + onAdminAuthRequest(): (hook.Hook | undefined) /** - * MarkFlagFilename instructs the various shell completion implementations to - * limit completions for the named flag to the specified file extensions. + * 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]). */ - markFlagFilename(name: string, ...extensions: string[]): void - } - interface Command { + onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) /** - * MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. - * The bash completion script will call the bash function f for the flag. + * 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). * - * This will only work for bash completion. - * It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows - * to register a Go function which will work across all shells. + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. */ - markFlagCustom(name: string, f: string): void - } - interface Command { + onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) /** - * MarkPersistentFlagFilename instructs the various shell completion - * implementations to limit completions for the named persistent flag to the - * specified file extensions. + * OnAdminAfterAuthRefreshRequest hook is triggered after each + * successful auth refresh API request (right after generating a new auth token). */ - markPersistentFlagFilename(name: string, ...extensions: string[]): void - } - interface Command { + onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) /** - * MarkFlagDirname instructs the various shell completion implementations to - * limit completions for the named flag to directory names. + * 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. */ - markFlagDirname(name: string): void - } - interface Command { + onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) /** - * MarkPersistentFlagDirname instructs the various shell completion - * implementations to limit completions for the named persistent flag to - * directory names. + * OnAdminAfterRequestPasswordResetRequest hook is triggered after each + * successful request password reset API request. */ - markPersistentFlagDirname(name: string): void - } - interface Command { + onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) /** - * GenZshCompletionFile generates zsh completion file including descriptions. + * 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. */ - genZshCompletionFile(filename: string): void - } - interface Command { + onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) /** - * GenZshCompletion generates zsh completion file including descriptions - * and writes it to the passed writer. + * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each + * successful confirm password reset API request. */ - genZshCompletion(w: io.Writer): void - } - interface Command { + onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) /** - * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + * 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. */ - genZshCompletionFileNoDesc(filename: string): void - } - interface Command { + onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenZshCompletionNoDesc generates zsh completion file without descriptions - * and writes it to the passed writer. + * 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. */ - genZshCompletionNoDesc(w: io.Writer): void - } - interface Command { + onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was - * not consistent with Bash completion. It has therefore been disabled. - * Instead, when no other completion is specified, file completion is done by - * default for every argument. One can disable file completion on a per-argument - * basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. - * To achieve file extension filtering, one can use ValidArgsFunction and - * ShellCompDirectiveFilterFileExt. + * OnRecordAfterAuthWithPasswordRequest hook is triggered after each + * successful Record auth with password API request. * - * Deprecated + * 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. */ - markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void - } - interface Command { + onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore - * been disabled. - * To achieve the same behavior across all shells, one can use - * ValidArgs (for the first argument only) or ValidArgsFunction for - * any argument (can include the first one also). + * OnRecordBeforeAuthWithOAuth2Request hook is triggered before each Record + * OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). * - * Deprecated + * 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. */ - markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void - } -} - -/** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * Reader is the interface that wraps the basic Read method. - * - * Read reads up to len(p) bytes into p. It returns the number of bytes - * read (0 <= n <= len(p)) and any error encountered. Even if Read - * returns n < len(p), it may use all of p as scratch space during the call. - * If some data is available but not len(p) bytes, Read conventionally - * returns what is available instead of waiting for more. - * - * When Read encounters an error or end-of-file condition after - * successfully reading n > 0 bytes, it returns the number of - * bytes read. It may return the (non-nil) error from the same call - * or return the error (and n == 0) from a subsequent call. - * An instance of this general case is that a Reader returning - * a non-zero number of bytes at the end of the input stream may - * return either err == EOF or err == nil. The next Read should - * return 0, EOF. - * - * Callers should always process the n > 0 bytes returned before - * considering the error err. Doing so correctly handles I/O errors - * that happen after reading some bytes and also both of the - * allowed EOF behaviors. - * - * Implementations of Read are discouraged from returning a - * zero byte count with a nil error, except when len(p) == 0. - * Callers should treat a return of 0 and nil as indicating that - * nothing happened; in particular it does not indicate EOF. - * - * Implementations must not retain p. - */ - interface Reader { - read(p: string): number - } - /** - * Writer is the interface that wraps the basic Write method. - * - * Write writes len(p) bytes from p to the underlying data stream. - * It returns the number of bytes written from p (0 <= n <= len(p)) - * and any error encountered that caused the write to stop early. - * Write must return a non-nil error if it returns n < len(p). - * Write must not modify the slice data, even temporarily. - * - * Implementations must not retain p. - */ - interface Writer { - write(p: string): number - } - /** - * ReadCloser is the interface that groups the basic Read and Close methods. - */ - interface ReadCloser { - } -} - -/** - * 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 { - interface Time { + onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) /** - * String returns the time formatted using the format string + * OnRecordAfterAuthWithOAuth2Request hook is triggered after each + * successful Record OAuth2 API request. * - * ``` - * "2006-01-02 15:04:05.999999999 -0700 MST" - * ``` + * 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). * - * If the time has a monotonic clock reading, the returned string - * includes a final field "m=±", where value is the monotonic - * clock reading formatted as a decimal number of seconds. + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. * - * The returned string is meant for debugging; for a stable serialized - * representation, use t.MarshalText, t.MarshalBinary, or t.Format - * with an explicit format string. + * 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. */ - string(): string - } - interface Time { + onRecordBeforeAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GoString implements fmt.GoStringer and formats t to be printed in Go source - * code. + * 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. */ - goString(): string - } - interface Time { + onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Format returns a textual representation of the time value formatted according - * to the layout defined by the argument. See the documentation for the - * constant called Layout to see how to represent the layout format. + * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. * - * The executable example for Time.Format demonstrates the working - * of the layout string in detail and is a good reference. + * 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. */ - format(layout: string): string - } - interface Time { + onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * AppendFormat is like Format but appends the textual - * representation to b and returns the extended buffer. + * 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. */ - appendFormat(b: string, layout: string): string - } - /** - * A Time represents an instant in time with nanosecond precision. - * - * Programs using times should typically store and pass them as values, - * not pointers. That is, time variables and struct fields should be of - * type time.Time, not *time.Time. - * - * A Time value can be used by multiple goroutines simultaneously except - * that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and - * UnmarshalText are not concurrency-safe. - * - * Time instants can be compared using the Before, After, and Equal methods. - * The Sub method subtracts two instants, producing a Duration. - * The Add method adds a Time and a Duration, producing a Time. - * - * The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. - * As this time is unlikely to come up in practice, the IsZero method gives - * a simple way of detecting a time that has not been initialized explicitly. - * - * Each Time has associated with it a Location, consulted when computing the - * presentation form of the time, such as in the Format, Hour, and Year methods. - * The methods Local, UTC, and In return a Time with a specific location. - * Changing the location in this way changes only the presentation; it does not - * change the instant in time being denoted and therefore does not affect the - * computations described in earlier paragraphs. - * - * Representations of a Time value saved by the GobEncode, MarshalBinary, - * MarshalJSON, and MarshalText methods store the Time.Location's offset, but not - * the location name. They therefore lose information about Daylight Saving Time. - * - * In addition to the required “wall clock” reading, a Time may contain an optional - * reading of the current process's monotonic clock, to provide additional precision - * for comparison or subtraction. - * See the “Monotonic Clocks” section in the package documentation for details. - * - * Note that the Go == operator compares not just the time instant but also the - * Location and the monotonic clock reading. Therefore, Time values should not - * be used as map or database keys without first guaranteeing that the - * identical Location has been set for all values, which can be achieved - * through use of the UTC or Local method, and that the monotonic clock reading - * has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) - * to t == u, since t.Equal uses the most accurate comparison available and - * correctly handles the case when only one of its arguments has a monotonic - * clock reading. - */ - interface Time { - } - interface Time { + onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * After reports whether the time instant t is after u. + * 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. */ - after(u: Time): boolean - } - interface Time { + onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Before reports whether the time instant t is before u. + * 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. */ - before(u: Time): boolean - } - interface Time { + onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Equal reports whether t and u represent the same time instant. - * Two times can be equal even if they are in different locations. - * For example, 6:00 +0200 and 4:00 UTC are Equal. - * See the documentation on the Time type for the pitfalls of using == with - * Time values; most code should use Equal instead. + * 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. */ - equal(u: Time): boolean - } - interface Time { + onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * IsZero reports whether t represents the zero time instant, - * January 1, year 1, 00:00:00 UTC. - */ - isZero(): boolean - } - interface Time { - /** - * Date returns the year, month, and day in which t occurs. + * 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. */ - date(): [number, Month, number] - } - interface Time { + onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Year returns the year in which t occurs. + * 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. */ - year(): number - } - interface Time { + onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Month returns the month of the year specified by t. + * 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. */ - month(): Month - } - interface Time { + onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Day returns the day of the month specified by t. + * 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. */ - day(): number - } - interface Time { + onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Weekday returns the day of the week specified by t. + * 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. */ - weekday(): Weekday - } - interface Time { + onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * ISOWeek returns the ISO 8601 year and week number in which t occurs. - * Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to - * week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 - * of year n+1. + * 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. */ - isoWeek(): number - } - interface Time { + onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Clock returns the hour, minute, and second within the day specified by t. + * 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. */ - clock(): number - } - interface Time { + onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Hour returns the hour within the day specified by t, in the range [0, 23]. + * 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. */ - hour(): number - } - interface Time { + onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Minute returns the minute offset within the hour specified by t, in the range [0, 59]. + * 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. */ - minute(): number - } - interface Time { + onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Second returns the second offset within the minute specified by t, in the range [0, 59]. + * 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. */ - second(): number - } - interface Time { + onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Nanosecond returns the nanosecond offset within the second specified by t, - * in the range [0, 999999999]. + * 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. */ - nanosecond(): number - } - interface Time { + onRecordsListRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, - * and [1,366] in leap years. + * 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. */ - yearDay(): number - } - interface Time { + onRecordViewRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Add returns the time t+d. + * 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. */ - add(d: Duration): Time - } - interface Time { + onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Sub returns the duration t-u. If the result exceeds the maximum (or minimum) - * value that can be stored in a Duration, the maximum (or minimum) duration - * will be returned. - * To compute t-d for a duration d, use t.Add(-d). + * 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. */ - sub(u: Time): Duration - } - interface Time { + onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * AddDate returns the time corresponding to adding the - * given number of years, months, and days to t. - * For example, AddDate(-1, 2, 3) applied to January 1, 2011 - * returns March 4, 2010. + * OnRecordBeforeUpdateRequest hook is triggered before each API Record + * update request (after request data load and before model persistence). * - * AddDate normalizes its result in the same way that Date does, - * so, for example, adding one month to October 31 yields - * December 1, the normalized form for November 31. + * 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. */ - addDate(years: number, months: number, days: number): Time - } - interface Time { + onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * UTC returns t with the location set to UTC. + * 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. */ - utc(): Time - } - interface Time { + onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Local returns t with the location set to local time. + * 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. */ - local(): Time - } - interface Time { + onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * In returns a copy of t representing the same time instant, but - * with the copy's location information set to loc for display - * purposes. + * OnRecordAfterDeleteRequest hook is triggered after each + * successful API Record delete request. * - * In panics if loc is nil. + * 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. */ - in(loc: Location): Time - } - interface Time { + onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Location returns the time zone information associated with t. + * 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. */ - location(): (Location | undefined) - } - interface Time { + onCollectionsListRequest(): (hook.Hook | undefined) /** - * Zone computes the time zone in effect at time t, returning the abbreviated - * name of the zone (such as "CET") and its offset in seconds east of UTC. + * 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. */ - 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 - * since January 1, 1970 UTC. The result does not depend on the - * location associated with t. - * Unix-like operating systems often record time as a 32-bit - * count of seconds, but since the method here returns a 64-bit - * value it is valid for billions of years into the past or future. - */ - unix(): number - } - interface Time { - /** - * UnixMilli returns t as a Unix time, the number of milliseconds elapsed since - * January 1, 1970 UTC. The result is undefined if the Unix time in - * milliseconds cannot be represented by an int64 (a date more than 292 million - * years before or after 1970). The result does not depend on the - * location associated with t. - */ - unixMilli(): number - } - interface Time { - /** - * UnixMicro returns t as a Unix time, the number of microseconds elapsed since - * January 1, 1970 UTC. The result is undefined if the Unix time in - * microseconds cannot be represented by an int64 (a date before year -290307 or - * after year 294246). The result does not depend on the location associated - * with t. - */ - unixMicro(): number - } - interface Time { - /** - * UnixNano returns t as a Unix time, the number of nanoseconds elapsed - * since January 1, 1970 UTC. The result is undefined if the Unix time - * in nanoseconds cannot be represented by an int64 (a date before the year - * 1678 or after 2262). Note that this means the result of calling UnixNano - * on the zero Time is undefined. The result does not depend on the - * location associated with t. - */ - unixNano(): number - } - interface Time { - /** - * MarshalBinary implements the encoding.BinaryMarshaler interface. - */ - marshalBinary(): string - } - interface Time { - /** - * UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. - */ - unmarshalBinary(data: string): void - } - interface Time { - /** - * GobEncode implements the gob.GobEncoder interface. - */ - gobEncode(): string - } - interface Time { + onCollectionViewRequest(): (hook.Hook | undefined) /** - * GobDecode implements the gob.GobDecoder interface. + * 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. */ - gobDecode(data: string): void - } - interface Time { + onCollectionBeforeCreateRequest(): (hook.Hook | undefined) /** - * MarshalJSON implements the json.Marshaler interface. - * The time is a quoted string in RFC 3339 format, with sub-second precision added if present. + * OnCollectionAfterCreateRequest hook is triggered after each + * successful API Collection create request. */ - marshalJSON(): string - } - interface Time { + onCollectionAfterCreateRequest(): (hook.Hook | undefined) /** - * UnmarshalJSON implements the json.Unmarshaler interface. - * The time is expected to be a quoted string in RFC 3339 format. + * 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. */ - unmarshalJSON(data: string): void - } - interface Time { + onCollectionBeforeUpdateRequest(): (hook.Hook | undefined) /** - * MarshalText implements the encoding.TextMarshaler interface. - * The time is formatted in RFC 3339 format, with sub-second precision added if present. + * OnCollectionAfterUpdateRequest hook is triggered after each + * successful API Collection update request. */ - marshalText(): string - } - interface Time { + onCollectionAfterUpdateRequest(): (hook.Hook | undefined) /** - * UnmarshalText implements the encoding.TextUnmarshaler interface. - * The time is expected to be in RFC 3339 format. + * 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. */ - unmarshalText(data: string): void - } - interface Time { + onCollectionBeforeDeleteRequest(): (hook.Hook | undefined) /** - * IsDST reports whether the time in the configured location is in Daylight Savings Time. + * OnCollectionAfterDeleteRequest hook is triggered after each + * successful API Collection delete request. */ - isDST(): boolean - } - interface Time { + onCollectionAfterDeleteRequest(): (hook.Hook | undefined) /** - * Truncate returns the result of rounding t down to a multiple of d (since the zero time). - * If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. + * OnCollectionsBeforeImportRequest hook is triggered before each API + * collections import request (after request data load and before the actual import). * - * Truncate operates on the time as an absolute duration since the - * zero time; it does not operate on the presentation form of the - * time. Thus, Truncate(Hour) may return a time with a non-zero - * minute, depending on the time's Location. + * Could be used to additionally validate the imported collections or + * to implement completely different import behavior. */ - truncate(d: Duration): Time - } - interface Time { + onCollectionsBeforeImportRequest(): (hook.Hook | undefined) /** - * Round returns the result of rounding t to the nearest multiple of d (since the zero time). - * The rounding behavior for halfway values is to round up. - * If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. - * - * Round operates on the time as an absolute duration since the - * zero time; it does not operate on the presentation form of the - * time. Thus, Round(Hour) may return a time with a non-zero - * minute, depending on the time's Location. + * OnCollectionsAfterImportRequest hook is triggered after each + * successful API collections import request. */ - round(d: Duration): Time + onCollectionsAfterImportRequest(): (hook.Hook | undefined) } } /** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. */ -namespace fs { +namespace io { /** - * A File provides access to a single file. - * The File interface is the minimum implementation required of the file. - * Directory files should also implement ReadDirFile. - * A file may implement io.ReaderAt or io.Seeker as optimizations. + * Reader is the interface that wraps the basic Read method. + * + * Read reads up to len(p) bytes into p. It returns the number of bytes + * read (0 <= n <= len(p)) and any error encountered. Even if Read + * returns n < len(p), it may use all of p as scratch space during the call. + * If some data is available but not len(p) bytes, Read conventionally + * returns what is available instead of waiting for more. + * + * When Read encounters an error or end-of-file condition after + * successfully reading n > 0 bytes, it returns the number of + * bytes read. It may return the (non-nil) error from the same call + * or return the error (and n == 0) from a subsequent call. + * An instance of this general case is that a Reader returning + * a non-zero number of bytes at the end of the input stream may + * return either err == EOF or err == nil. The next Read should + * return 0, EOF. + * + * Callers should always process the n > 0 bytes returned before + * considering the error err. Doing so correctly handles I/O errors + * that happen after reading some bytes and also both of the + * allowed EOF behaviors. + * + * Implementations of Read are discouraged from returning a + * zero byte count with a nil error, except when len(p) == 0. + * Callers should treat a return of 0 and nil as indicating that + * nothing happened; in particular it does not indicate EOF. + * + * Implementations must not retain p. */ - interface File { - stat(): FileInfo - read(_arg0: string): number - close(): void + interface Reader { + read(p: string): number + } + /** + * Writer is the interface that wraps the basic Write method. + * + * Write writes len(p) bytes from p to the underlying data stream. + * It returns the number of bytes written from p (0 <= n <= len(p)) + * and any error encountered that caused the write to stop early. + * Write must return a non-nil error if it returns n < len(p). + * Write must not modify the slice data, even temporarily. + * + * Implementations must not retain p. + */ + interface Writer { + write(p: string): number + } + /** + * ReadCloser is the interface that groups the basic Read and Close methods. + */ + interface ReadCloser { } } /** - * Package context defines the Context type, which carries deadlines, - * cancellation signals, and other request-scoped values across API boundaries - * and between processes. + * Package time provides functionality for measuring and displaying time. * - * Incoming requests to a server should create a Context, and outgoing - * calls to servers should accept a Context. The chain of function - * calls between them must propagate the Context, optionally replacing - * it with a derived Context created using WithCancel, WithDeadline, - * WithTimeout, or WithValue. When a Context is canceled, all - * Contexts derived from it are also canceled. + * The calendrical calculations always assume a Gregorian calendar, with + * no leap seconds. * - * The WithCancel, WithDeadline, and WithTimeout functions take a - * Context (the parent) and return a derived Context (the child) and a - * CancelFunc. Calling the CancelFunc cancels the child and its - * children, removes the parent's reference to the child, and stops - * any associated timers. Failing to call the CancelFunc leaks the - * child and its children until the parent is canceled or the timer - * fires. The go vet tool checks that CancelFuncs are used on all - * control-flow paths. + * Monotonic Clocks * - * Programs that use Contexts should follow these rules to keep interfaces - * consistent across packages and enable static analysis tools to check context - * propagation: + * 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. * - * Do not store Contexts inside a struct type; instead, pass a Context - * explicitly to each function that needs it. The Context should be the first - * parameter, typically named ctx: + * 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: * * ``` - * func DoSomething(ctx context.Context, arg Arg) error { - * // ... use ctx ... - * } + * start := time.Now() + * ... operation that takes 20 milliseconds ... + * t := time.Now() + * elapsed := t.Sub(start) * ``` * - * Do not pass a nil Context, even if a function permits it. Pass context.TODO - * if you are unsure about which Context to use. - * - * Use context Values only for request-scoped data that transits processes and - * APIs, not for passing optional parameters to functions. - * - * The same Context may be passed to functions running in different goroutines; - * Contexts are safe for simultaneous use by multiple goroutines. + * Other idioms, such as time.Since(start), time.Until(deadline), and + * time.Now().Before(deadline), are similarly robust against wall clock + * resets. * - * See https://blog.golang.org/context for example code for a server that uses - * Contexts. - */ -namespace context { -} - -/** - * Package textproto implements generic support for text-based request/response - * protocols in the style of HTTP, NNTP, and SMTP. + * 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 package provides: + * 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). * - * Error, which represents a numeric error response from - * a server. + * 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. * - * Pipeline, to manage pipelined requests and responses - * in a client. + * 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. * - * Reader, to read numeric response code lines, - * key: value headers, lines wrapped with leading spaces - * on continuation lines, and whole text blocks ending - * with a dot on a line by itself. + * 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. * - * Writer, to write dot-encoded text blocks. + * 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. * - * Conn, a convenient packaging of Reader, Writer, and Pipeline for use - * with a single network connection. + * 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 textproto { - /** - * A MIMEHeader represents a MIME-style header mapping - * keys to sets of values. - */ - interface MIMEHeader extends _TygojaDict{} - interface MIMEHeader { - /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. - */ - add(key: string): void - } - interface MIMEHeader { +namespace time { + interface Time { /** - * Set sets the header entries associated with key to - * the single element value. It replaces any existing - * values associated with key. + * String returns the time formatted using the format string + * ``` + * "2006-01-02 15:04:05.999999999 -0700 MST" + * ``` + * + * If the time has a monotonic clock reading, the returned string + * includes a final field "m=±", where value is the monotonic + * clock reading formatted as a decimal number of seconds. + * + * The returned string is meant for debugging; for a stable serialized + * representation, use t.MarshalText, t.MarshalBinary, or t.Format + * with an explicit format string. */ - set(key: string): void + string(): string } - interface MIMEHeader { + interface Time { /** - * Get gets the first value associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is used - * to canonicalize the provided key. - * If there are no values associated with the key, Get returns "". - * To use non-canonical keys, access the map directly. + * GoString implements fmt.GoStringer and formats t to be printed in Go source + * code. */ - get(key: string): string + goString(): string } - interface MIMEHeader { + interface Time { /** - * Values returns all values associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. To use non-canonical - * keys, access the map directly. - * The returned slice is not a copy. + * Format returns a textual representation of the time value formatted according + * to the layout defined by the argument. See the documentation for the + * constant called Layout to see how to represent the layout format. + * + * The executable example for Time.Format demonstrates the working + * of the layout string in detail and is a good reference. */ - values(key: string): Array + format(layout: string): string } - interface MIMEHeader { + interface Time { /** - * Del deletes the values associated with key. + * AppendFormat is like Format but appends the textual + * representation to b and returns the extended buffer. */ - del(key: string): void + appendFormat(b: string, layout: string): string } -} - -/** - * 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 { /** - * Value is a value that drivers must be able to handle. - * It is either nil, a type handled by a database driver's NamedValueChecker - * interface, or an instance of one of these types: - * - * ``` - * int64 - * float64 - * bool - * []byte - * string - * time.Time - * ``` + * A Time represents an instant in time with nanosecond precision. * - * If the driver supports cursors, a returned Value may also implement the Rows interface - * in this package. This is used, for example, when a user selects a cursor - * such as "select cursor(select * from my_table) from dual". If the Rows - * from the select is closed, the cursor Rows will also be closed. - */ - interface Value extends _TygojaAny{} - /** - * Driver is the interface that must be implemented by a database - * driver. + * Programs using times should typically store and pass them as values, + * not pointers. That is, time variables and struct fields should be of + * type time.Time, not *time.Time. * - * Database drivers may implement DriverContext for access - * to contexts and to parse the name only once for a pool of connections, - * instead of once per connection. - */ - interface Driver { - /** - * Open returns a new connection to the database. - * The name is a string in a driver-specific format. - * - * Open may return a cached connection (one previously - * closed), but doing so is unnecessary; the sql package - * maintains a pool of idle connections for efficient re-use. - * - * The returned connection is only used by one goroutine at a - * time. - */ - open(name: string): Conn - } -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * A URL represents a parsed URL (technically, a URI reference). + * A Time value can be used by multiple goroutines simultaneously except + * that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and + * UnmarshalText are not concurrency-safe. * - * The general form represented is: + * Time instants can be compared using the Before, After, and Equal methods. + * The Sub method subtracts two instants, producing a Duration. + * The Add method adds a Time and a Duration, producing a Time. * - * ``` - * [scheme:][//[userinfo@]host][/]path[?query][#fragment] - * ``` + * The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. + * As this time is unlikely to come up in practice, the IsZero method gives + * a simple way of detecting a time that has not been initialized explicitly. * - * URLs that do not start with a slash after the scheme are interpreted as: + * Each Time has associated with it a Location, consulted when computing the + * presentation form of the time, such as in the Format, Hour, and Year methods. + * The methods Local, UTC, and In return a Time with a specific location. + * Changing the location in this way changes only the presentation; it does not + * change the instant in time being denoted and therefore does not affect the + * computations described in earlier paragraphs. * - * ``` - * scheme:opaque[?query][#fragment] - * ``` + * Representations of a Time value saved by the GobEncode, MarshalBinary, + * MarshalJSON, and MarshalText methods store the Time.Location's offset, but not + * the location name. They therefore lose information about Daylight Saving Time. * - * 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. + * In addition to the required “wall clock” reading, a Time may contain an optional + * reading of the current process's monotonic clock, to provide additional precision + * for comparison or subtraction. + * See the “Monotonic Clocks” section in the package documentation for details. * - * URL's String method uses the EscapedPath method to obtain the path. See the - * EscapedPath method for more details. + * Note that the Go == operator compares not just the time instant but also the + * Location and the monotonic clock reading. Therefore, Time values should not + * be used as map or database keys without first guaranteeing that the + * identical Location has been set for all values, which can be achieved + * through use of the UTC or Local method, and that the monotonic clock reading + * has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) + * to t == u, since t.Equal uses the most accurate comparison available and + * correctly handles the case when only one of its arguments has a monotonic + * clock reading. */ - 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 Time { } - interface URL { + interface Time { /** - * 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. + * After reports whether the time instant t is after u. */ - escapedPath(): string + after(u: Time): boolean } - interface URL { + interface Time { /** - * 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. + * Before reports whether the time instant t is before u. */ - escapedFragment(): string + before(u: Time): boolean } - interface URL { + interface Time { /** - * 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. - * ``` + * Equal reports whether t and u represent the same time instant. + * Two times can be equal even if they are in different locations. + * For example, 6:00 +0200 and 4:00 UTC are Equal. + * See the documentation on the Time type for the pitfalls of using == with + * Time values; most code should use Equal instead. */ - string(): string + equal(u: Time): boolean } - interface URL { + interface Time { /** - * Redacted is like String but replaces any password with "xxxxx". - * Only the password in u.URL is redacted. + * IsZero reports whether t represents the zero time instant, + * January 1, year 1, 00:00:00 UTC. */ - redacted(): string + isZero(): boolean } - /** - * 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 { + interface Time { /** - * 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. + * Date returns the year, month, and day in which t occurs. */ - get(key: string): string + date(): [number, Month, number] } - interface Values { + interface Time { /** - * Set sets the key to value. It replaces any existing - * values. + * Year returns the year in which t occurs. */ - set(key: string): void + year(): number } - interface Values { + interface Time { /** - * Add adds the value to key. It appends to any existing - * values associated with key. + * Month returns the month of the year specified by t. */ - add(key: string): void + month(): Month } - interface Values { + interface Time { /** - * Del deletes the values associated with key. + * Day returns the day of the month specified by t. */ - del(key: string): void + day(): number } - interface Values { + interface Time { /** - * Has checks whether a given key is set. + * Weekday returns the day of the week specified by t. */ - has(key: string): boolean + weekday(): Weekday } - interface Values { + interface Time { /** - * Encode encodes the values into “URL encoded” form - * ("bar=baz&foo=quux") sorted by key. + * ISOWeek returns the ISO 8601 year and week number in which t occurs. + * Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to + * week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 + * of year n+1. */ - encode(): string + isoWeek(): number } - interface URL { + interface Time { /** - * IsAbs reports whether the URL is absolute. - * Absolute means that it has a non-empty scheme. + * Clock returns the hour, minute, and second within the day specified by t. */ - isAbs(): boolean + clock(): number } - interface URL { + interface Time { /** - * 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. + * Hour returns the hour within the day specified by t, in the range [0, 23]. */ - parse(ref: string): (URL | undefined) + hour(): number } - interface URL { + interface Time { /** - * 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. + * Minute returns the minute offset within the hour specified by t, in the range [0, 59]. */ - resolveReference(ref: URL): (URL | undefined) + minute(): number } - interface URL { + interface Time { /** - * Query parses RawQuery and returns the corresponding values. - * It silently discards malformed value pairs. - * To check errors use ParseQuery. + * Second returns the second offset within the minute specified by t, in the range [0, 59]. */ - query(): Values + second(): number } - interface URL { + interface Time { /** - * RequestURI returns the encoded path?query or opaque?query - * string that would be used in an HTTP request for u. + * Nanosecond returns the nanosecond offset within the second specified by t, + * in the range [0, 999999999]. */ - requestURI(): string + nanosecond(): number } - interface URL { + interface Time { /** - * 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. + * YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, + * and [1,366] in leap years. */ - hostname(): string + yearDay(): number } - interface URL { + interface Time { /** - * 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. + * Add returns the time t+d. */ - port(): string - } - interface URL { - marshalBinary(): string - } - interface URL { - unmarshalBinary(text: string): void + add(d: Duration): Time } - interface URL { + interface Time { /** - * 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 /. + * Sub returns the duration t-u. If the result exceeds the maximum (or minimum) + * value that can be stored in a Duration, the maximum (or minimum) duration + * will be returned. + * To compute t-d for a duration d, use t.Add(-d). */ - joinPath(...elem: string[]): (URL | undefined) + sub(u: Time): Duration } -} - -/** - * 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 Time { + /** + * AddDate returns the time corresponding to adding the + * given number of years, months, and days to t. + * For example, AddDate(-1, 2, 3) applied to January 1, 2011 + * returns March 4, 2010. + * + * AddDate normalizes its result in the same way that Date does, + * so, for example, adding one month to October 31 yields + * December 1, the normalized form for November 31. + */ + addDate(years: number, months: number, days: number): Time } - interface DateTime { + interface Time { /** - * Time returns the internal [time.Time] instance. + * UTC returns t with the location set to UTC. */ - time(): time.Time + utc(): Time } - interface DateTime { + interface Time { /** - * IsZero checks whether the current DateTime instance has zero time value. + * Local returns t with the location set to local time. */ - isZero(): boolean + local(): Time } - interface DateTime { + interface Time { /** - * String serializes the current DateTime instance into a formatted - * UTC date string. + * In returns a copy of t representing the same time instant, but + * with the copy's location information set to loc for display + * purposes. * - * The zero value is serialized to an empty string. + * In panics if loc is nil. */ - string(): string + in(loc: Location): Time } - interface DateTime { + interface Time { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Location returns the time zone information associated with t. */ - marshalJSON(): string + location(): (Location | undefined) } - interface DateTime { + interface Time { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * Zone computes the time zone in effect at time t, returning the abbreviated + * name of the zone (such as "CET") and its offset in seconds east of UTC. */ - unmarshalJSON(b: string): void + zone(): [string, number] } - interface DateTime { + interface Time { /** - * Value implements the [driver.Valuer] interface. + * Unix returns t as a Unix time, the number of seconds elapsed + * since January 1, 1970 UTC. The result does not depend on the + * location associated with t. + * Unix-like operating systems often record time as a 32-bit + * count of seconds, but since the method here returns a 64-bit + * value it is valid for billions of years into the past or future. */ - value(): driver.Value + unix(): number } - interface DateTime { + interface Time { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. + * UnixMilli returns t as a Unix time, the number of milliseconds elapsed since + * January 1, 1970 UTC. The result is undefined if the Unix time in + * milliseconds cannot be represented by an int64 (a date more than 292 million + * years before or after 1970). The result does not depend on the + * location associated with t. */ - scan(value: any): void + unixMilli(): number } -} - -/** - * 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 { - /** - * IsolationLevel is the transaction isolation level used in TxOptions. - */ - interface IsolationLevel extends Number{} - interface IsolationLevel { + interface Time { /** - * String returns the name of the transaction isolation level. + * UnixMicro returns t as a Unix time, the number of microseconds elapsed since + * January 1, 1970 UTC. The result is undefined if the Unix time in + * microseconds cannot be represented by an int64 (a date before year -290307 or + * after year 294246). The result does not depend on the location associated + * with t. */ - string(): string + unixMicro(): number } - /** - * DBStats contains database statistics. - */ - interface DBStats { - maxOpenConnections: number // Maximum number of open connections to the database. - /** - * Pool Status - */ - openConnections: number // The number of established connections both in use and idle. - inUse: number // The number of connections currently in use. - idle: number // The number of idle connections. + interface Time { /** - * Counters + * UnixNano returns t as a Unix time, the number of nanoseconds elapsed + * since January 1, 1970 UTC. The result is undefined if the Unix time + * in nanoseconds cannot be represented by an int64 (a date before the year + * 1678 or after 2262). Note that this means the result of calling UnixNano + * on the zero Time is undefined. The result does not depend on the + * location associated with t. */ - waitCount: number // The total number of connections waited for. - waitDuration: time.Duration // The total time blocked waiting for a new connection. - maxIdleClosed: number // The total number of connections closed due to SetMaxIdleConns. - maxIdleTimeClosed: number // The total number of connections closed due to SetConnMaxIdleTime. - maxLifetimeClosed: number // The total number of connections closed due to SetConnMaxLifetime. - } - /** - * Conn represents a single database connection rather than a pool of database - * connections. Prefer running queries from DB unless there is a specific - * need for a continuous single database connection. - * - * A Conn must call Close to return the connection to the database pool - * and may do so concurrently with a running query. - * - * After a call to Close, all operations on the - * connection fail with ErrConnDone. - */ - interface Conn { + unixNano(): number } - interface Conn { + interface Time { /** - * PingContext verifies the connection to the database is still alive. + * MarshalBinary implements the encoding.BinaryMarshaler interface. */ - pingContext(ctx: context.Context): void + marshalBinary(): string } - interface Conn { + interface Time { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + unmarshalBinary(data: string): void } - interface Conn { + interface Time { /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * GobEncode implements the gob.GobEncoder interface. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + gobEncode(): string } - interface Conn { + interface Time { /** - * 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. + * GobDecode implements the gob.GobDecoder interface. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + gobDecode(data: string): void } - interface Conn { + interface Time { /** - * 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. + * MarshalJSON implements the json.Marshaler interface. + * The time is a quoted string in RFC 3339 format, with sub-second precision added if present. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + marshalJSON(): string } - interface Conn { + interface Time { /** - * Raw executes f exposing the underlying driver connection for the - * duration of f. The driverConn must not be used outside of f. - * - * Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable - * until Conn.Close is called. + * UnmarshalJSON implements the json.Unmarshaler interface. + * The time is expected to be a quoted string in RFC 3339 format. */ - raw(f: (driverConn: any) => void): void + unmarshalJSON(data: string): void } - interface Conn { + interface Time { /** - * 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. + * MarshalText implements the encoding.TextMarshaler interface. + * The time is formatted in RFC 3339 format, with sub-second precision added if present. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) + marshalText(): string } - interface Conn { + interface Time { /** - * Close returns the connection to the connection pool. - * All operations after a Close will return with ErrConnDone. - * Close is safe to call concurrently with other operations and will - * block until all other operations finish. It may be useful to first - * cancel any used context and then call close directly after. + * UnmarshalText implements the encoding.TextUnmarshaler interface. + * The time is expected to be in RFC 3339 format. */ - close(): void - } - /** - * ColumnType contains the name and type of a column. - */ - interface ColumnType { + unmarshalText(data: string): void } - interface ColumnType { + interface Time { /** - * Name returns the name or alias of the column. + * IsDST reports whether the time in the configured location is in Daylight Savings Time. */ - name(): string + isDST(): boolean } - interface ColumnType { + interface Time { /** - * Length returns the column type length for variable length column types such - * as text and binary field types. If the type length is unbounded the value will - * be math.MaxInt64 (any database limits will still apply). - * If the column type is not variable length, such as an int, or if not supported - * by the driver ok is false. + * Truncate returns the result of rounding t down to a multiple of d (since the zero time). + * If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. + * + * Truncate operates on the time as an absolute duration since the + * zero time; it does not operate on the presentation form of the + * time. Thus, Truncate(Hour) may return a time with a non-zero + * minute, depending on the time's Location. */ - length(): [number, boolean] + truncate(d: Duration): Time } - interface ColumnType { + interface Time { /** - * DecimalSize returns the scale and precision of a decimal type. - * If not applicable or if not supported ok is false. + * Round returns the result of rounding t to the nearest multiple of d (since the zero time). + * The rounding behavior for halfway values is to round up. + * If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. + * + * Round operates on the time as an absolute duration since the + * zero time; it does not operate on the presentation form of the + * time. Thus, Round(Hour) may return a time with a non-zero + * minute, depending on the time's Location. */ - decimalSize(): [number, boolean] + round(d: Duration): Time } - interface ColumnType { - /** - * ScanType returns a Go type suitable for scanning into using Rows.Scan. - * If a driver does not support this property ScanType will return - * the type of an empty interface. - */ - scanType(): reflect.Type - } - interface ColumnType { - /** - * Nullable reports whether the column may be null. - * If a driver does not support this property ok will be false. - */ - nullable(): boolean - } - interface ColumnType { - /** - * DatabaseTypeName returns the database system name of the column type. If an empty - * string is returned, then the driver type name is not supported. - * Consult your driver documentation for a list of driver data types. Length specifiers - * are not included. - * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", - * "INT", and "BIGINT". - */ - databaseTypeName(): string - } - /** - * Row is the result of calling QueryRow to select a single row. - */ - interface Row { - } - interface Row { - /** - * Scan copies the columns from the matched row into the values - * pointed at by dest. See the documentation on Rows.Scan for details. - * If more than one row matches the query, - * Scan uses the first row and discards the rest. If no row matches - * the query, Scan returns ErrNoRows. - */ - scan(...dest: any[]): void - } - interface Row { - /** - * Err provides a way for wrapping packages to check for - * query errors without calling Scan. - * Err returns the error, if any, that was encountered while running the query. - * If this error is not nil, this error will also be returned from Scan. - */ - err(): void +} + +/** + * 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 File provides access to a single file. + * The File interface is the minimum implementation required of the file. + * Directory files should also implement ReadDirFile. + * A file may implement io.ReaderAt or io.Seeker as optimizations. + */ + interface File { + stat(): FileInfo + read(_arg0: string): number + close(): void } } /** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. + * Package context defines the Context type, which carries deadlines, + * cancellation signals, and other request-scoped values across API boundaries + * and between processes. + * + * Incoming requests to a server should create a Context, and outgoing + * calls to servers should accept a Context. The chain of function + * calls between them must propagate the Context, optionally replacing + * it with a derived Context created using WithCancel, WithDeadline, + * WithTimeout, or WithValue. When a Context is canceled, all + * Contexts derived from it are also canceled. + * + * The WithCancel, WithDeadline, and WithTimeout functions take a + * Context (the parent) and return a derived Context (the child) and a + * CancelFunc. Calling the CancelFunc cancels the child and its + * children, removes the parent's reference to the child, and stops + * any associated timers. Failing to call the CancelFunc leaks the + * child and its children until the parent is canceled or the timer + * fires. The go vet tool checks that CancelFuncs are used on all + * control-flow paths. + * + * Programs that use Contexts should follow these rules to keep interfaces + * consistent across packages and enable static analysis tools to check context + * propagation: + * + * Do not store Contexts inside a struct type; instead, pass a Context + * explicitly to each function that needs it. The Context should be the first + * parameter, typically named ctx: + * + * ``` + * func DoSomething(ctx context.Context, arg Arg) error { + * // ... use ctx ... + * } + * ``` + * + * Do not pass a nil Context, even if a function permits it. Pass context.TODO + * if you are unsure about which Context to use. + * + * Use context Values only for request-scoped data that transits processes and + * APIs, not for passing optional parameters to functions. + * + * The same Context may be passed to functions running in different goroutines; + * Contexts are safe for simultaneous use by multiple goroutines. + * + * See https://blog.golang.org/context for example code for a server that uses + * Contexts. */ -namespace tls { +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 { /** - * ConnectionState records basic TLS details about the connection. + * Conn is a generic stream-oriented network connection. + * + * Multiple goroutines may invoke methods on a Conn simultaneously. */ - interface ConnectionState { + interface Conn { /** - * Version is the TLS version used by the connection (e.g. VersionTLS12). + * 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. */ - version: number + read(b: string): number /** - * HandshakeComplete is true if the handshake has concluded. + * 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. */ - handshakeComplete: boolean + write(b: string): number /** - * DidResume is true if this connection was successfully resumed from a - * previous session with a session ticket or similar mechanism. + * Close closes the connection. + * Any blocked Read or Write operations will be unblocked and return errors. */ - didResume: boolean + close(): void /** - * CipherSuite is the cipher suite negotiated for the connection (e.g. - * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). + * LocalAddr returns the local network address, if known. */ - cipherSuite: number + localAddr(): Addr /** - * NegotiatedProtocol is the application protocol negotiated with ALPN. + * RemoteAddr returns the remote network address, if known. */ - negotiatedProtocol: string + remoteAddr(): Addr /** - * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. + * SetDeadline sets the read and write deadlines associated + * with the connection. It is equivalent to calling both + * SetReadDeadline and SetWriteDeadline. * - * 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. + * 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. * - * 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). + * 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. * - * 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. + * 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. */ - verifiedChains: Array> + setDeadline(t: time.Time): void /** - * SignedCertificateTimestamps is a list of SCTs provided by the peer - * through the TLS handshake for the leaf certificate, if any. + * 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. */ - signedCertificateTimestamps: Array + setReadDeadline(t: time.Time): void /** - * OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) - * response provided by the peer for the leaf certificate, if any. + * 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. */ - ocspResponse: string + 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 { /** - * 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. + * Accept waits for and returns the next connection to the listener. */ - tlsUnique: string - } - interface ConnectionState { + accept(): Conn /** - * 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. + * Close closes the listener. + * Any blocked Accept operations will be unblocked and return errors. */ - exportKeyingMaterial(label: string, context: string, length: number): string + close(): void + /** + * Addr returns the listener's network address. + */ + addr(): Addr } } /** - * 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 url parses URLs and implements query escaping. */ -namespace multipart { - interface Reader { +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 { /** - * 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. + * 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. */ - readForm(maxMemory: number): (Form | undefined) + escapedPath(): string } - /** - * 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 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 Form { + interface URL { /** - * RemoveAll removes any temporary files associated with a Form. + * 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. + * ``` */ - removeAll(): void + string(): string } - /** - * 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 URL { + /** + * Redacted is like String but replaces any password with "xxxxx". + * Only the password in u.URL is redacted. + */ + redacted(): string } /** - * Reader is an iterator over parts in a MIME multipart body. - * Reader's underlying parser consumes its input as needed. Seeking - * isn't supported. + * 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 Reader { + 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 Reader { + interface Values { /** - * 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. + * Set sets the key to value. It replaces any existing + * values. */ - nextPart(): (Part | undefined) + set(key: string): void } - interface Reader { + interface Values { /** - * 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". + * Add adds the value to key. It appends to any existing + * values associated with key. */ - nextRawPart(): (Part | undefined) + add(key: string): 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 { - /** - * 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 { + interface Values { /** - * Transport specifies the mechanism by which individual - * HTTP requests are made. - * If nil, DefaultTransport is used. + * Del deletes the values associated with key. */ - transport: RoundTripper + del(key: string): void + } + interface Values { /** - * 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. + * Has checks whether a given key is set. */ - checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void + has(key: string): boolean + } + interface Values { /** - * 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. + * Encode encodes the values into ``URL encoded'' form + * ("bar=baz&foo=quux") sorted by key. */ - jar: CookieJar + encode(): string + } + interface URL { /** - * 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. + * IsAbs reports whether the URL is absolute. + * Absolute means that it has a non-empty scheme. */ - timeout: time.Duration + isAbs(): boolean } - interface Client { + interface URL { /** - * 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. + * 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. */ - get(url: string): (Response | undefined) + parse(ref: string): (URL | undefined) } - interface Client { + interface URL { /** - * 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. + * 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. */ - do(req: Request): (Response | undefined) + resolveReference(ref: URL): (URL | undefined) } - interface Client { + interface URL { /** - * 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. + * Query parses RawQuery and returns the corresponding values. + * It silently discards malformed value pairs. + * To check errors use ParseQuery. */ - post(url: string, body: io.Reader): (Response | undefined) + query(): Values } - interface Client { + interface URL { /** - * 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. + * 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. * - * 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. + * If the result is enclosed in square brackets, as literal IPv6 addresses are, + * the square brackets are removed from the result. */ - postForm(url: string, data: url.Values): (Response | undefined) + hostname(): string } - interface Client { + interface URL { /** - * 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) - * ``` + * Port returns the port part of u.Host, without the leading colon. * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. + * If u.Host doesn't contain a valid numeric port, Port returns an empty string. */ - head(url: string): (Response | undefined) + port(): string } - 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 + 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 { /** - * 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. + * ConnectionState records basic TLS details about the connection. */ - interface Cookie { - name: string - value: string - path: string // optional - domain: string // optional - expires: time.Time // optional - rawExpires: string // for reading cookies only + interface ConnectionState { /** - * 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 + * Version is the TLS version used by the connection (e.g. VersionTLS12). */ - maxAge: number - secure: boolean - httpOnly: boolean - sameSite: SameSite - raw: string - unparsed: Array // Raw text of unparsed attribute-value pairs - } - interface Cookie { + version: number /** - * 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. + * HandshakeComplete is true if the handshake has concluded. */ - string(): string - } - interface Cookie { + handshakeComplete: boolean /** - * Valid reports whether the cookie is valid. + * DidResume is true if this connection was successfully resumed from a + * previous session with a session ticket or similar mechanism. */ - 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 { + didResume: boolean /** - * 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. + * CipherSuite is the cipher suite negotiated for the connection (e.g. + * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). */ - add(key: string): void - } - interface Header { + cipherSuite: number /** - * 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. + * NegotiatedProtocol is the application protocol negotiated with ALPN. */ - set(key: string): void - } - interface Header { + negotiatedProtocol: string /** - * 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. + * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. + * + * Deprecated: this value is always true. */ - get(key: string): string - } - interface Header { + negotiatedProtocolIsMutual: boolean /** - * 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. + * 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. */ - values(key: string): Array - } - interface Header { + serverName: string /** - * Del deletes the values associated with key. - * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. + * 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. */ - del(key: string): void - } - interface Header { + peerCertificates: Array<(x509.Certificate | undefined)> /** - * Write writes a header in wire format. + * 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. */ - write(w: io.Writer): void - } - interface Header { + verifiedChains: Array> /** - * Clone returns a copy of h or nil if h is nil. + * SignedCertificateTimestamps is a list of SCTs provided by the peer + * through the TLS handshake for the leaf certificate, if any. */ - clone(): Header + 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 Header { + interface ConnectionState { /** - * 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. + * 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. */ - writeSubset(w: io.Writer, exclude: _TygojaDict): void + exportKeyingMaterial(label: string, context: string, length: number): string } - // @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. + * 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 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 + interface Config { /** - * 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). + * 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. */ - header: Header + rand: io.Reader /** - * 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. + * Time returns the current time as the number of seconds since the epoch. + * If Time is nil, TLS uses time.Now. */ - body: io.ReadCloser + time: () => time.Time /** - * 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. + * 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. */ - contentLength: number + certificates: Array /** - * Contains transfer encodings from outer-most to inner-most. Value is - * nil, means that "identity" encoding is used. + * 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. */ - transferEncoding: Array + nameToCertificate: _TygojaDict /** - * 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. + * 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. */ - close: boolean + getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) /** - * 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. + * 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. */ - uncompressed: boolean + getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) /** - * Trailer maps trailer keys to values in the same - * format as Header. + * 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. * - * 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. + * If GetConfigForClient is nil, the Config passed to Server() will be + * used for all connections. * - * Trailer must not be accessed concurrently with Read calls - * on the Body. + * 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. * - * After Body.Read has returned io.EOF, Trailer will contain - * any trailer values sent by the server. + * 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. */ - trailer: Header + verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void /** - * 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. + * 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. */ - request?: Request + verifyConnection: (_arg0: ConnectionState) => void /** - * 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. + * 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. */ - tls?: tls.ConnectionState - } - interface Response { + rootCAs?: x509.CertPool /** - * Cookies parses and returns the cookies set in the Set-Cookie headers. + * 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. */ - cookies(): Array<(Cookie | undefined)> - } - interface Response { + nextProtos: Array /** - * 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. + * 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. */ - location(): (url.URL | undefined) - } - interface Response { + serverName: string /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the response is at least major.minor. + * ClientAuth determines the server's policy for + * TLS Client Authentication. The default is NoClientCert. */ - protoAtLeast(major: number): boolean - } - interface Response { + clientAuth: ClientAuthType /** - * Write writes r to w in the HTTP/1.x server response format, - * including the status line, headers, body, and optional trailer. + * 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. * - * This method consults the following fields of the response r: + * 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. * - * ``` - * StatusCode - * ProtoMajor - * ProtoMinor - * Request.Method - * TransferEncoding - * Trailer - * Body - * ContentLength - * Header, values for non-canonical keys will have unpredictable behavior - * ``` + * 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. * - * The Response Body is closed after it is sent. + * Deprecated: PreferServerCipherSuites is ignored. */ - write(w: io.Writer): void - } -} - -/** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com - */ -namespace echo { - /** - * Binder is the interface that wraps the Bind method. - */ - interface Binder { - bind(c: Context, i: { - }): void - } - /** - * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and - * be able to be routed by Router. - */ - interface ServableContext { + preferServerCipherSuites: boolean /** - * Reset resets the context after request completes. It must be called along - * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. - * See `Echo#ServeHTTP()` + * 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. */ - reset(r: http.Request, w: http.ResponseWriter): void - } - // @ts-ignore - import stdContext = context - /** - * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. - */ - interface JSONSerializer { - serialize(c: Context, i: { - }, indent: string): void - deserialize(c: Context, i: { - }): void - } - /** - * HTTPErrorHandler is a centralized HTTP error handler. - */ - interface HTTPErrorHandler {(c: Context, err: Error): void } - /** - * Validator is the interface that wraps the Validate function. - */ - interface Validator { - validate(i: { - }): void - } - /** - * Renderer is the interface that wraps the Render function. - */ - interface Renderer { - render(_arg0: io.Writer, _arg1: string, _arg2: { - }, _arg3: Context): void - } - /** - * Group is a set of sub-routes for a specified route. It can be used for inner - * routes that share a common middleware or functionality that should be separate - * from the parent echo instance while still inheriting from it. - */ - interface Group { - } - interface Group { + sessionTicketsDisabled: boolean /** - * Use implements `Echo#Use()` for sub-routes within the Group. - * Group middlewares are not executed on request when there is no matching route found. + * 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. */ - use(...middleware: MiddlewareFunc[]): void - } - interface Group { + sessionTicketKey: string /** - * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. + * ClientSessionCache is a cache of ClientSessionState entries for TLS + * session resumption. It is only used by clients. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + clientSessionCache: ClientSessionCache /** - * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. + * 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). */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + minVersion: number /** - * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. + * 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. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + maxVersion: number /** - * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. + * 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. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + curvePreferences: Array /** - * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. + * 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. */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + dynamicRecordSizingDisabled: boolean /** - * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. + * Renegotiation controls what types of renegotiation are supported. + * The default, none, is correct for the vast majority of applications. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { + renegotiation: RenegotiationSupport /** - * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. + * 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. */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + keyLogWriter: io.Writer } - interface Group { + interface Config { /** - * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. + * 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. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + clone(): (Config | undefined) } - interface Group { + interface Config { /** - * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. + * 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. */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setSessionTicketKeys(keys: Array): void } - interface Group { + interface Config { /** - * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. + * 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. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + buildNameToCertificate(): void } - interface Group { +} + +/** + * Package textproto implements generic support for text-based request/response + * protocols in the style of HTTP, NNTP, and SMTP. + * + * The package provides: + * + * Error, which represents a numeric error response from + * a server. + * + * Pipeline, to manage pipelined requests and responses + * in a client. + * + * Reader, to read numeric response code lines, + * key: value headers, lines wrapped with leading spaces + * on continuation lines, and whole text blocks ending + * with a dot on a line by itself. + * + * Writer, to write dot-encoded text blocks. + * + * Conn, a convenient packaging of Reader, Writer, and Pipeline for use + * with a single network connection. + */ +namespace textproto { + /** + * A MIMEHeader represents a MIME-style header mapping + * keys to sets of values. + */ + interface MIMEHeader extends _TygojaDict{} + interface MIMEHeader { /** - * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + add(key: string): void } - interface Group { + interface MIMEHeader { /** - * Group creates a new sub-group with prefix and optional sub-group-level middleware. - * Important! Group middlewares are only executed in case there was exact route match and not - * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add - * a catch-all route `/*` for the group which handler returns always 404 + * Set sets the header entries associated with key to + * the single element value. It replaces any existing + * values associated with key. */ - group(prefix: string, ...middleware: MiddlewareFunc[]): (Group | undefined) + set(key: string): void } - interface Group { + interface MIMEHeader { /** - * Static implements `Echo#Static()` for sub-routes within the Group. + * Get gets the first value associated with the given key. + * It is case insensitive; CanonicalMIMEHeaderKey is used + * to canonicalize the provided key. + * If there are no values associated with the key, Get returns "". + * To use non-canonical keys, access the map directly. */ - static(pathPrefix: string): RouteInfo + get(key: string): string } - interface Group { + interface MIMEHeader { /** - * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. - * - * 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. + * Values returns all values associated with the given key. + * It is case insensitive; CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical + * keys, access the map directly. + * The returned slice is not a copy. */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo + values(key: string): Array } - interface Group { + interface MIMEHeader { /** - * FileFS implements `Echo#FileFS()` for sub-routes within the Group. + * Del deletes the values associated with key. */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo + del(key: string): void } - interface Group { +} + +/** + * 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 { /** - * File implements `Echo#File()` for sub-routes within the Group. Panics on error. + * 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. */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo + readForm(maxMemory: number): (Form | undefined) } - interface Group { - /** - * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. - * - * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` - */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { - /** - * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. - */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo + /** + * 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 Group { + interface Form { /** - * AddRoute registers a new Routable with Router + * RemoveAll removes any temporary files associated with a Form. */ - addRoute(route: Routable): RouteInfo + removeAll(): void } /** - * IPExtractor is a function to extract IP addr from http.Request. - * Set appropriate one to Echo#IPExtractor. - * See https://echo.labstack.com/guide/ip-address for more details. + * 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 IPExtractor {(_arg0: http.Request): string } + interface File { + } /** - * Logger defines the logging interface that Echo uses internally in few places. - * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. + * 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 Logger { + interface Reader { + } + interface Reader { /** - * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. - * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, - * and underlying FileSystem errors. - * `logger` middleware will use this method to write its JSON payload. + * 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. */ - write(p: string): number + nextPart(): (Part | undefined) + } + interface Reader { /** - * Error logs the error + * 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". */ - error(err: Error): void + 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 { /** - * Response wraps an http.ResponseWriter and implements its interface to be used - * by an HTTP handler to construct an HTTP response. - * See: https://golang.org/pkg/net/http/#ResponseWriter + * 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 Response { - writer: http.ResponseWriter - status: number - size: number - committed: boolean + interface Logger { } - interface Response { + interface Logger { /** - * Header returns the header map for the writer that will be sent by - * WriteHeader. Changing the header after a call to WriteHeader (or Write) has - * no effect unless the modified headers were declared as trailers by setting - * the "Trailer" header before the call to WriteHeader (see example) - * To suppress implicit response headers, set their value to nil. - * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers + * SetOutput sets the output destination for the logger. */ - header(): http.Header + setOutput(w: io.Writer): void } - interface Response { + interface Logger { /** - * Before registers a function which is called just before the response is written. + * 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. */ - before(fn: () => void): void + output(calldepth: number, s: string): void } - interface Response { + interface Logger { /** - * After registers a function which is called just after the response is written. - * If the `Content-Length` is unknown, none of the after function is executed. + * Printf calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Printf. */ - after(fn: () => void): void + printf(format: string, ...v: any[]): void } - interface Response { + interface Logger { /** - * WriteHeader sends an HTTP response header with 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. + * Print calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Print. */ - writeHeader(code: number): void + print(...v: any[]): void } - interface Response { + interface Logger { /** - * Write writes the data to the connection as part of an HTTP reply. + * Println calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Println. */ - write(b: string): number + println(...v: any[]): void } - interface Response { + interface Logger { /** - * Flush implements the http.Flusher interface to allow an HTTP handler to flush - * buffered data to the client. - * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) + * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). */ - flush(): void + fatal(...v: any[]): void } - interface Response { + interface Logger { /** - * Hijack implements the http.Hijacker interface to allow an HTTP handler to - * take over the connection. - * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) + * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). */ - hijack(): [net.Conn, (bufio.ReadWriter | undefined)] + fatalf(format: string, ...v: any[]): void } - interface Routes { + interface Logger { /** - * Reverse reverses route to URL string by replacing path parameters with given params values. + * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). */ - reverse(name: string, ...params: { - }[]): string + fatalln(...v: any[]): void } - interface Routes { + interface Logger { /** - * FindByMethodPath searched for matching route info by method and path + * Panic is equivalent to l.Print() followed by a call to panic(). */ - findByMethodPath(method: string, path: string): RouteInfo + panic(...v: any[]): void } - interface Routes { + interface Logger { /** - * FilterByMethod searched for matching route info by method + * Panicf is equivalent to l.Printf() followed by a call to panic(). */ - filterByMethod(method: string): Routes + panicf(format: string, ...v: any[]): void } - interface Routes { + interface Logger { /** - * FilterByPath searched for matching route info by path + * Panicln is equivalent to l.Println() followed by a call to panic(). */ - filterByPath(path: string): Routes + panicln(...v: any[]): void } - interface Routes { + interface Logger { /** - * FilterByName searched for matching route info by name + * Flags returns the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. */ - filterByName(name: string): Routes + flags(): number } - /** - * Router is interface for routing request contexts to registered routes. - * - * Contract between Echo/Context instance and the router: - * * all routes must be added through methods on echo.Echo instance. - * ``` - * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). - * ``` - * * Router must populate Context during Router.Route call with: - * ``` - * * RoutableContext.SetPath - * * RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) - * * RoutableContext.SetRouteInfo - * And optionally can set additional information to Context with RoutableContext.Set - * ``` - */ - interface Router { - /** - * Add registers Routable with the Router and returns registered RouteInfo - */ - add(routable: Routable): RouteInfo - /** - * Remove removes route from the Router - */ - remove(method: string, path: string): void - /** - * Routes returns information about all registered routes - */ - routes(): Routes + interface Logger { /** - * Route searches Router for matching route and applies it to the given context. In case when no matching method - * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 - * handler function. + * SetFlags sets the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. */ - route(c: RoutableContext): HandlerFunc + setFlags(flag: number): void } - /** - * Routable is interface for registering Route with Router. During route registration process the Router will - * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional - * information about registered route can be stored in Routes (i.e. privileges used with route etc.) - */ - interface Routable { + interface Logger { /** - * ToRouteInfo converts Routable to RouteInfo - * - * This method is meant to be used by Router after it parses url for path parameters, to store information about - * route just added. + * Prefix returns the output prefix for the logger. */ - toRouteInfo(params: Array): RouteInfo + prefix(): string + } + interface Logger { /** - * ToRoute converts Routable to Route which Router uses to register the method handler for path. - * - * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to - * add Route to Router. + * SetPrefix sets the output prefix for the logger. */ - toRoute(): Route + setPrefix(prefix: string): void + } + interface Logger { /** - * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. - * - * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group - * middlewares included in actually registered Route. + * Writer returns the output destination for the logger. */ - forGroup(pathPrefix: string, middlewares: Array): Routable - } - /** - * Routes is collection of RouteInfo instances with various helper methods. - */ - interface Routes extends Array{} - /** - * RouteInfo describes registered route base fields. - * Method+Path pair uniquely identifies the Route. Name can have duplicates. - */ - interface RouteInfo { - method(): string - path(): string - name(): string - params(): Array - reverse(...params: { - }[]): string - } - /** - * PathParams is collections of PathParam instances with various helper methods - */ - interface PathParams extends Array{} - interface PathParams { - /** - * Get returns path parameter value for given name or default value. - */ - get(name: string, defaultValue: string): string + writer(): io.Writer } } -namespace store { +/** + * 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 { /** - * Store defines a concurrent safe in memory key-value data store. + * 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 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 { + interface Client { /** - * RemoveAll removes all the existing store entries. + * Transport specifies the mechanism by which individual + * HTTP requests are made. + * If nil, DefaultTransport is used. */ - removeAll(): void - } - interface Store { + transport: RoundTripper /** - * Remove removes a single entry from the store. + * 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. * - * 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. + * If CheckRedirect is nil, the Client uses its default policy, + * which is to stop after 10 consecutive requests. */ - has(key: string): boolean - } - interface Store { + checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void /** - * Get returns a single element value from the store. + * Jar specifies the cookie jar. * - * If key is not set, the zero T value is returned. + * 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. */ - get(key: string): T - } - interface Store { + jar: CookieJar /** - * GetAll returns a shallow copy of the current store data. + * 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. */ - getAll(): _TygojaDict + timeout: time.Duration } - interface Store { + interface Client { /** - * Set sets (or overwrite if already exist) a new value for key. + * 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. */ - set(key: string, value: T): void + get(url: string): (Response | undefined) } - interface Store { + interface Client { /** - * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. + * Do sends an HTTP request and returns an HTTP response, following + * policy (such as redirects, cookies, auth) as configured on the + * client. * - * 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. + * 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. */ - setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean + 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 } -} - -/** - * 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. + * 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 SchemaField { - system: boolean - id: string + interface Cookie { name: string - type: string - required: boolean + value: string + path: string // optional + domain: string // optional + expires: time.Time // optional + rawExpires: string // for reading cookies only /** - * Deprecated: This field is no-op and will be removed in future versions. - * Please use the collection.Indexes field to define a unique constraint. + * 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 */ - unique: boolean - options: any + maxAge: number + secure: boolean + httpOnly: boolean + sameSite: SameSite + raw: string + unparsed: Array // Raw text of unparsed attribute-value pairs } - interface SchemaField { + interface Cookie { /** - * ColDefinition returns the field db column type definition as string. + * 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. */ - colDefinition(): string + string(): string } - interface SchemaField { + interface Cookie { /** - * String serializes and returns the current field as string. + * Valid reports whether the cookie is valid. */ - string(): string + valid(): void } - interface SchemaField { + // @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 { /** - * MarshalJSON implements the [json.Marshaler] interface. + * 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. */ - marshalJSON(): string + add(key: string): void } - interface SchemaField { + interface Header { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * The schema field options are auto initialized on success. + * 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. */ - unmarshalJSON(data: string): void + set(key: string): void } - interface SchemaField { + interface Header { /** - * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. + * 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. */ - validate(): void + get(key: string): string } - interface SchemaField { + interface Header { /** - * InitOptions initializes the current field options based on its type. - * - * Returns error on unknown field type. + * 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. */ - initOptions(): void + values(key: string): Array } - interface SchemaField { + interface Header { /** - * PrepareValue returns normalized and properly formatted field value. + * Del deletes the values associated with key. + * The key is case insensitive; it is canonicalized by + * CanonicalHeaderKey. */ - prepareValue(value: any): any + del(key: string): void } - interface SchemaField { + interface Header { /** - * PrepareValueWithModifier returns normalized and properly formatted field value - * by "merging" baseValue with the modifierValue based on the specified modifier (+ or -). + * Write writes a header in wire format. */ - prepareValueWithModifier(baseValue: any, modifier: string, modifierValue: any): any + write(w: io.Writer): void } -} - -/** - * 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 + 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 /** - * BaseModel defines common fields and methods used by all other models. + * 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 BaseModel { - id: string - created: types.DateTime - updated: types.DateTime - } - interface BaseModel { + 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 /** - * HasId returns whether the model has a nonzero id. + * 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). */ - hasId(): boolean - } - interface BaseModel { + header: Header /** - * GetId returns the model id. + * 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. */ - getId(): string - } - interface BaseModel { + body: io.ReadCloser /** - * SetId sets the model id to the provided string value. + * 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. */ - setId(id: string): void - } - interface BaseModel { + contentLength: number /** - * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). + * Contains transfer encodings from outer-most to inner-most. Value is + * nil, means that "identity" encoding is used. */ - markAsNew(): void - } - interface BaseModel { + transferEncoding: Array /** - * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) + * 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. */ - markAsNotNew(): void - } - interface BaseModel { + close: boolean /** - * IsNew indicates what type of db query (insert or update) - * should be used with the model instance. + * 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. */ - isNew(): boolean - } - interface BaseModel { + uncompressed: boolean /** - * GetCreated returns the model Created datetime. + * 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. */ - getCreated(): types.DateTime - } - interface BaseModel { + trailer: Header /** - * GetUpdated returns the model Updated datetime. + * 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. */ - getUpdated(): types.DateTime + 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 BaseModel { + interface Response { /** - * RefreshId generates and sets a new model id. - * - * The generated id is a cryptographically random 15 characters length string. + * Cookies parses and returns the cookies set in the Set-Cookie headers. */ - refreshId(): void + cookies(): Array<(Cookie | undefined)> } - interface BaseModel { + interface Response { /** - * RefreshCreated updates the model Created field with the current datetime. + * 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. */ - refreshCreated(): void + location(): (url.URL | undefined) } - interface BaseModel { + interface Response { /** - * RefreshUpdated updates the model Updated field with the current datetime. + * ProtoAtLeast reports whether the HTTP protocol used + * in the response is at least major.minor. */ - refreshUpdated(): void + protoAtLeast(major: number): boolean } - interface BaseModel { + interface Response { /** - * PostScan implements the [dbx.PostScanner] interface. + * Write writes r to w in the HTTP/1.x server response format, + * including the status line, headers, body, and optional trailer. * - * It is executed right after the model was populated with the db row values. + * 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. */ - postScan(): void + write(w: io.Writer): void } - // @ts-ignore - import validation = ozzo_validation /** - * CollectionBaseOptions defines the "base" Collection.Options fields. + * 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 CollectionBaseOptions { - } - interface CollectionBaseOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void + interface Handler { + serveHTTP(_arg0: ResponseWriter, _arg1: Request): void } /** - * CollectionAuthOptions defines the "auth" Collection.Options fields. + * A ConnState represents the state of a client connection to a server. + * It's used by the optional Server.ConnState hook. */ - 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 + interface ConnState extends Number{} + interface ConnState { + string(): string } +} + +namespace store { /** - * CollectionViewOptions defines the "view" Collection.Options fields. + * Store defines a concurrent safe in memory key-value data store. */ - interface CollectionViewOptions { - query: string + interface Store { } - interface CollectionViewOptions { + interface Store { /** - * Validate implements [validation.Validatable] interface. + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. */ - 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 + reset(newData: _TygojaDict): void } - interface TableInfoRow { + interface Store { /** - * the `db:"pk"` tag has special semantic so we cannot rename - * the original field without specifying a custom mapper + * Length returns the current number of elements in the store. */ - 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, - * as specified in RFC 6749. - * It can additionally grant authorization with Bearer JWT. - */ -namespace oauth2 { - /** - * An AuthCodeOption is passed to Config.AuthCodeURL. - */ - interface AuthCodeOption { + length(): number } - /** - * Token represents the credentials used to authorize - * the requests to access protected resources on the OAuth 2.0 - * provider's backend. - * - * Most users of this package should not access fields of Token - * directly. They're exported mostly for use by related packages - * implementing derivative OAuth2 flows. - */ - interface Token { - /** - * AccessToken is the token that authorizes and authenticates - * the requests. - */ - accessToken: string - /** - * TokenType is the type of token. - * The Type method returns either this or "Bearer", the default. - */ - tokenType: string + interface Store { /** - * RefreshToken is a token that's used by the application - * (as opposed to the user) to refresh the access token - * if it expires. + * RemoveAll removes all the existing store entries. */ - refreshToken: string + removeAll(): void + } + interface Store { /** - * Expiry is the optional expiration time of the access token. + * Remove removes a single entry from the store. * - * If zero, TokenSource implementations will reuse the same - * token forever and RefreshToken or equivalent - * mechanisms for that TokenSource will not be used. + * Remove does nothing if key doesn't exist in the store. */ - expiry: time.Time + remove(key: string): void } - interface Token { + interface Store { /** - * Type returns t.TokenType if non-empty, else "Bearer". + * Has checks if element with the specified key exist or not. */ - type(): string + has(key: string): boolean } - interface Token { + interface Store { /** - * SetAuthHeader sets the Authorization header to r using the access - * token in t. + * Get returns a single element value from the store. * - * This method is unnecessary when using Transport or an HTTP Client - * returned by this package. + * If key is not set, the zero T value is returned. */ - setAuthHeader(r: http.Request): void + get(key: string): T } - interface Token { + interface Store { /** - * WithExtra returns a new Token that's a clone of t, but using the - * provided raw extra map. This is only intended for use by packages - * implementing derivative OAuth2 flows. + * GetAll returns a shallow copy of the current store data. */ - withExtra(extra: { - }): (Token | undefined) + getAll(): _TygojaDict } - interface Token { + interface Store { /** - * Extra returns an extra field. - * Extra fields are key-value pairs returned by the server as a - * part of the token retrieval response. + * Set sets (or overwrite if already exist) a new value for key. */ - extra(key: string): { - } + set(key: string, value: T): void } - interface Token { + interface Store { /** - * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. + * + * This method is similar to Set() but **it will skip adding new elements** + * to the store if the store length has reached the specified limit. + * false is returned if maxAllowedElements limit is reached. */ - valid(): boolean + setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean } } @@ -13532,6136 +13232,6488 @@ namespace mailer { } } -namespace settings { - // @ts-ignore - import validation = ozzo_validation - interface TokenConfig { - secret: string - duration: number - } - interface TokenConfig { +/** + * 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 { + /** + * Value is a value that drivers must be able to handle. + * It is either nil, a type handled by a database driver's NamedValueChecker + * interface, or an instance of one of these types: + * + * ``` + * int64 + * float64 + * bool + * []byte + * string + * time.Time + * ``` + * + * If the driver supports cursors, a returned Value may also implement the Rows interface + * in this package. This is used, for example, when a user selects a cursor + * such as "select cursor(select * from my_table) from dual". If the Rows + * from the select is closed, the cursor Rows will also be closed. + */ + interface Value extends _TygojaAny{} + /** + * Driver is the interface that must be implemented by a database + * driver. + * + * Database drivers may implement DriverContext for access + * to contexts and to parse the name only once for a pool of connections, + * instead of once per connection. + */ + interface Driver { /** - * Validate makes TokenConfig validatable by implementing [validation.Validatable] interface. + * Open returns a new connection to the database. + * The name is a string in a driver-specific format. + * + * Open may return a cached connection (one previously + * closed), but doing so is unnecessary; the sql package + * maintains a pool of idle connections for efficient re-use. + * + * The returned connection is only used by one goroutine at a + * time. */ - validate(): void + open(name: string): Conn } - interface SmtpConfig { - enabled: boolean - host: string - port: number - username: string - password: string - /** - * SMTP AUTH - PLAIN (default) or LOGIN - */ - authMethod: string +} + +/** + * 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 { + /** + * IsolationLevel is the transaction isolation level used in TxOptions. + */ + interface IsolationLevel extends Number{} + interface IsolationLevel { /** - * Whether to enforce TLS encryption for the mail server connection. - * - * When set to false StartTLS command is send, leaving the server - * to decide whether to upgrade the connection or not. + * String returns the name of the transaction isolation level. */ - tls: boolean + string(): string } - interface SmtpConfig { + /** + * DBStats contains database statistics. + */ + interface DBStats { + maxOpenConnections: number // Maximum number of open connections to the database. /** - * Validate makes SmtpConfig validatable by implementing [validation.Validatable] interface. + * Pool Status */ - validate(): void - } - interface S3Config { - enabled: boolean - bucket: string - region: string - endpoint: string - accessKey: string - secret: string - forcePathStyle: boolean - } - interface S3Config { + openConnections: number // The number of established connections both in use and idle. + inUse: number // The number of connections currently in use. + idle: number // The number of idle connections. /** - * Validate makes S3Config validatable by implementing [validation.Validatable] interface. + * Counters */ - validate(): void + waitCount: number // The total number of connections waited for. + waitDuration: time.Duration // The total time blocked waiting for a new connection. + maxIdleClosed: number // The total number of connections closed due to SetMaxIdleConns. + maxIdleTimeClosed: number // The total number of connections closed due to SetConnMaxIdleTime. + maxLifetimeClosed: number // The total number of connections closed due to SetConnMaxLifetime. } - interface BackupsConfig { + /** + * Conn represents a single database connection rather than a pool of database + * connections. Prefer running queries from DB unless there is a specific + * need for a continuous single database connection. + * + * A Conn must call Close to return the connection to the database pool + * and may do so concurrently with a running query. + * + * After a call to Close, all operations on the + * connection fail with ErrConnDone. + */ + interface Conn { + } + interface Conn { /** - * Cron is a cron expression to schedule auto backups, eg. "* * * * *". - * - * Leave it empty to disable the auto backups functionality. + * PingContext verifies the connection to the database is still alive. */ - cron: string + pingContext(ctx: context.Context): void + } + interface Conn { /** - * CronMaxKeep is the the max number of cron generated backups to - * keep before removing older entries. - * - * This field works only when the cron config has valid cron expression. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - cronMaxKeep: number + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Conn { /** - * S3 is an optional S3 storage config specifying where to store the app backups. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - s3: S3Config + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) } - interface BackupsConfig { + interface Conn { /** - * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. + * 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. */ - validate(): void - } - interface MetaConfig { - appName: string - appUrl: string - hideControls: boolean - senderName: string - senderAddress: string - verificationTemplate: EmailTemplate - resetPasswordTemplate: EmailTemplate - confirmEmailChangeTemplate: EmailTemplate + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) } - interface MetaConfig { + interface Conn { /** - * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. + * 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. */ - validate(): void - } - interface LogsConfig { - maxDays: number + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) } - interface LogsConfig { + interface Conn { /** - * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. + * Raw executes f exposing the underlying driver connection for the + * duration of f. The driverConn must not be used outside of f. + * + * Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable + * until Conn.Close is called. */ - validate(): void - } - interface AuthProviderConfig { - enabled: boolean - clientId: string - clientSecret: string - authUrl: string - tokenUrl: string - userApiUrl: string + raw(f: (driverConn: any) => void): void } - interface AuthProviderConfig { + interface Conn { /** - * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. + * 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. */ - validate(): void + beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) } - interface AuthProviderConfig { + interface Conn { /** - * SetupProvider loads the current AuthProviderConfig into the specified provider. + * Close returns the connection to the connection pool. + * All operations after a Close will return with ErrConnDone. + * Close is safe to call concurrently with other operations and will + * block until all other operations finish. It may be useful to first + * cancel any used context and then call close directly after. */ - setupProvider(provider: auth.Provider): void + close(): void } /** - * Deprecated: Will be removed in v0.9+ + * ColumnType contains the name and type of a column. */ - interface EmailAuthConfig { - enabled: boolean - exceptDomains: Array - onlyDomains: Array - minPasswordLength: number + interface ColumnType { } - interface EmailAuthConfig { + interface ColumnType { /** - * Deprecated: Will be removed in v0.9+ + * Name returns the name or alias of the column. */ - validate(): void - } -} - -/** - * Package daos handles common PocketBase DB model manipulations. - * - * Think of daos as DB repository and service layer in one. - */ -namespace daos { - /** - * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. - */ - interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } - // @ts-ignore - import validation = ozzo_validation - interface RequestsStatsItem { - total: number - date: types.DateTime - } -} - -namespace hook { - /** - * Hook defines a concurrent safe structure for handling event hooks - * (aka. callbacks propagation). - */ - interface Hook { + name(): string } - interface Hook { + interface ColumnType { /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + * Length returns the column type length for variable length column types such + * as text and binary field types. If the type length is unbounded the value will + * be math.MaxInt64 (any database limits will still apply). + * If the column type is not variable length, such as an int, or if not supported + * by the driver ok is false. */ - preAdd(fn: Handler): string + length(): [number, boolean] } - interface Hook { + interface ColumnType { /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + * DecimalSize returns the scale and precision of a decimal type. + * If not applicable or if not supported ok is false. */ - add(fn: Handler): string + decimalSize(): [number, boolean] } - interface Hook { + interface ColumnType { /** - * @todo add also to TaggedHook - * Remove removes a single hook handler by its id. + * ScanType returns a Go type suitable for scanning into using Rows.Scan. + * If a driver does not support this property ScanType will return + * the type of an empty interface. */ - remove(id: string): void + scanType(): reflect.Type } - interface Hook { + interface ColumnType { /** - * @todo add also to TaggedHook - * RemoveAll removes all registered handlers. + * Nullable reports whether the column may be null. + * If a driver does not support this property ok will be false. */ - removeAll(): void + nullable(): boolean } - interface Hook { + interface ColumnType { /** - * Trigger executes all registered hook handlers one by one - * with the specified `data` as an argument. - * - * Optionally, this method allows also to register additional one off - * handlers that will be temporary appended to the handlers queue. - * - * The execution stops when: - * - hook.StopPropagation is returned in one of the handlers - * - any non-nil error is returned in one of the handlers + * DatabaseTypeName returns the database system name of the column type. If an empty + * string is returned, then the driver type name is not supported. + * Consult your driver documentation for a list of driver data types. Length specifiers + * are not included. + * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", + * "INT", and "BIGINT". */ - trigger(data: T, ...oneOffHandlers: Handler[]): void + databaseTypeName(): string } /** - * 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). + * Row is the result of calling QueryRow to select a single row. */ - type _subHkiap = mainHook - interface TaggedHook extends _subHkiap { + interface Row { } - interface TaggedHook { + interface Row { /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. + * Scan copies the columns from the matched row into the values + * pointed at by dest. See the documentation on Rows.Scan for details. + * If more than one row matches the query, + * Scan uses the first row and discards the rest. If no row matches + * the query, Scan returns ErrNoRows. */ - canTriggerOn(tags: Array): boolean + scan(...dest: any[]): void } - interface TaggedHook { + interface Row { /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. + * Err provides a way for wrapping packages to check for + * query errors without calling Scan. + * Err returns the error, if any, that was encountered while running the query. + * If this error is not nil, this error will also be returned from Scan. */ - preAdd(fn: Handler): string + err(): void } - interface TaggedHook { - /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. - */ - add(fn: Handler): string +} + +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void } } -namespace subscriptions { +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { /** - * Broker defines a struct for managing subscriptions clients. + * DateTime represents a [time.Time] instance in UTC that is wrapped + * and serialized using the app default date layout. */ - interface Broker { + interface DateTime { } - interface Broker { + interface DateTime { /** - * Clients returns a shallow copy of all registered clients indexed - * with their connection id. + * Time returns the internal [time.Time] instance. */ - clients(): _TygojaDict + time(): time.Time } - interface Broker { + interface DateTime { /** - * ClientById finds a registered client by its id. + * 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. * - * Returns non-nil error when client with clientId is not registered. + * The zero value is serialized to an empty string. */ - clientById(clientId: string): Client + string(): string } - interface Broker { + interface DateTime { /** - * Register adds a new client to the broker instance. + * MarshalJSON implements the [json.Marshaler] interface. */ - register(client: Client): void + marshalJSON(): string } - interface Broker { + interface DateTime { /** - * Unregister removes a single client by its id. - * - * If client with clientId doesn't exist, this method does nothing. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - unregister(clientId: string): void + 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 core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. */ -namespace core { - interface BootstrapEvent { - app: App - } - interface TerminateEvent { - app: App - } - interface ServeEvent { - app: App - router?: echo.Echo - server?: http.Server - certManager?: autocert.Manager - } - interface ApiErrorEvent { - httpContext: echo.Context - error: Error - } - type _subjAEWn = BaseModelEvent - interface ModelEvent extends _subjAEWn { - dao?: daos.Dao - } - type _subufDOF = BaseCollectionEvent - interface MailerRecordEvent extends _subufDOF { - mailClient: mailer.Mailer - message?: mailer.Message - record?: models.Record - meta: _TygojaDict - } - interface MailerAdminEvent { - mailClient: mailer.Mailer - message?: mailer.Message - admin?: models.Admin - meta: _TygojaDict - } - interface RealtimeConnectEvent { - httpContext: echo.Context - client: subscriptions.Client - } - interface RealtimeDisconnectEvent { - httpContext: echo.Context - client: subscriptions.Client - } - interface RealtimeMessageEvent { - httpContext: echo.Context - client: subscriptions.Client - message?: subscriptions.Message - } - interface RealtimeSubscribeEvent { - httpContext: echo.Context - client: subscriptions.Client - subscriptions: Array - } - interface SettingsListEvent { - httpContext: echo.Context - redactedSettings?: settings.Settings - } - interface SettingsUpdateEvent { - httpContext: echo.Context - oldSettings?: settings.Settings - newSettings?: settings.Settings - } - type _submvluG = BaseCollectionEvent - interface RecordsListEvent extends _submvluG { - httpContext: echo.Context - records: Array<(models.Record | undefined)> - result?: search.Result - } - type _subxveXr = BaseCollectionEvent - interface RecordViewEvent extends _subxveXr { - httpContext: echo.Context - record?: models.Record - } - type _subeiYdM = BaseCollectionEvent - interface RecordCreateEvent extends _subeiYdM { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict - } - type _subwBStl = BaseCollectionEvent - interface RecordUpdateEvent extends _subwBStl { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict - } - type _subuERET = BaseCollectionEvent - interface RecordDeleteEvent extends _subuERET { - httpContext: echo.Context - record?: models.Record - } - type _subsArqi = BaseCollectionEvent - interface RecordAuthEvent extends _subsArqi { - httpContext: echo.Context - record?: models.Record - token: string - meta: any - } - type _subpoLXf = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subpoLXf { - httpContext: echo.Context - record?: models.Record - identity: string - password: string - } - type _subkCwTk = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subkCwTk { - httpContext: echo.Context - providerName: string - providerClient: auth.Provider - record?: models.Record - oAuth2User?: auth.AuthUser - isNewRecord: boolean - } - type _subpMNVV = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subpMNVV { - httpContext: echo.Context - record?: models.Record - } - type _subuvAdi = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subuvAdi { - httpContext: echo.Context - record?: models.Record - } - type _subqBCXB = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subqBCXB { - httpContext: echo.Context - record?: models.Record - } - type _subdiAUX = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subdiAUX { - httpContext: echo.Context - record?: models.Record - } - type _subWnwvZ = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subWnwvZ { - httpContext: echo.Context - record?: models.Record - } - type _subIZCPR = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subIZCPR { - httpContext: echo.Context - record?: models.Record - } - type _subIFlNc = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subIFlNc { - httpContext: echo.Context - record?: models.Record - } - type _subUOniq = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subUOniq { - httpContext: echo.Context - record?: models.Record - externalAuths: Array<(models.ExternalAuth | undefined)> - } - type _subVdsut = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subVdsut { - httpContext: echo.Context - record?: models.Record - externalAuth?: models.ExternalAuth - } - interface AdminsListEvent { - httpContext: echo.Context - admins: Array<(models.Admin | undefined)> - result?: search.Result - } - interface AdminViewEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminCreateEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminUpdateEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminDeleteEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminAuthEvent { - httpContext: echo.Context - admin?: models.Admin - token: string - } - interface AdminAuthWithPasswordEvent { - httpContext: echo.Context - admin?: models.Admin - identity: string - password: string - } - interface AdminAuthRefreshEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminRequestPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminConfirmPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin +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 CollectionsListEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> - result?: search.Result + interface SchemaField { + /** + * ColDefinition returns the field db column type definition as string. + */ + colDefinition(): string } - type _subEFFpI = BaseCollectionEvent - interface CollectionViewEvent extends _subEFFpI { - httpContext: echo.Context + interface SchemaField { + /** + * String serializes and returns the current field as string. + */ + string(): string } - type _subuIxsH = BaseCollectionEvent - interface CollectionCreateEvent extends _subuIxsH { - httpContext: echo.Context + interface SchemaField { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string } - type _subBiKuQ = BaseCollectionEvent - interface CollectionUpdateEvent extends _subBiKuQ { - httpContext: echo.Context + interface SchemaField { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * The schema field options are auto initialized on success. + */ + unmarshalJSON(data: string): void } - type _subTONlV = BaseCollectionEvent - interface CollectionDeleteEvent extends _subTONlV { - httpContext: echo.Context + interface SchemaField { + /** + * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. + */ + validate(): void } - interface CollectionsImportEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> + interface SchemaField { + /** + * InitOptions initializes the current field options based on its type. + * + * Returns error on unknown field type. + */ + initOptions(): void } - type _subKUlLM = BaseModelEvent - interface FileTokenEvent extends _subKUlLM { - httpContext: echo.Context - token: string + interface SchemaField { + /** + * PrepareValue returns normalized and properly formatted field value. + */ + prepareValue(value: any): any } - type _subNKYxw = BaseCollectionEvent - interface FileDownloadEvent extends _subNKYxw { - httpContext: echo.Context - record?: models.Record - fileField?: schema.SchemaField - servedPath: string - servedName: string + 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 pflag is a drop-in replacement for Go's flag package, implementing - * POSIX/GNU-style --flags. - * - * pflag is compatible with the GNU extensions to the POSIX recommendations - * for command-line options. See - * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - * - * Usage: - * - * pflag is a drop-in replacement of Go's native flag package. If you import - * pflag under the name "flag" then all code should continue to function - * with no changes. - * - * ``` - * import flag "github.com/spf13/pflag" - * ``` - * - * There is one exception to this: if you directly instantiate the Flag struct - * there is one more field "Shorthand" that you will need to set. - * Most code never instantiates this struct directly, and instead uses - * functions such as String(), BoolVar(), and Var(), and is therefore - * unaffected. - * - * Define flags using flag.String(), Bool(), Int(), etc. - * - * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - * ``` - * var ip = flag.Int("flagname", 1234, "help message for flagname") - * ``` - * 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 after the flag are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. - * - * The pflag package also defines some new functions that are not in flag, - * that give one-letter shorthands for flags. You can use these by appending - * 'P' to the name of any function that defines a flag. - * ``` - * var ip = flag.IntP("flagname", "f", 1234, "help message") - * var flagvar bool - * func init() { - * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") - * } - * flag.VarP(&flagval, "varname", "v", "help message") - * ``` - * Shorthand letters can be used with single dashes on the command line. - * Boolean shorthand flags can be combined with other shorthand flags. - * - * Command line flag syntax: - * ``` - * --flag // boolean flags only - * --flag=x - * ``` - * - * Unlike the flag package, a single dash before an option means something - * different than a double dash. Single dashes signify a series of shorthand - * letters for flags. All but the last shorthand letter must be boolean flags. - * ``` - * // boolean flags - * -f - * -abc - * // non-boolean flags - * -n 1234 - * -Ifile - * // mixed - * -abcs "hello" - * -abcn1234 - * ``` - * - * Flag parsing stops after the terminator "--". Unlike the flag package, - * flags can be interspersed with arguments anywhere on the command line - * before this terminator. - * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags (in their long form) accept 1, 0, 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. +} + +/** + * Package models implements all PocketBase DB models and DTOs. */ -namespace pflag { - interface FlagSet { +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 { /** - * GetBool return the bool value of a flag with the given name + * HasId returns whether the model has a nonzero id. */ - getBool(name: string): boolean + hasId(): boolean } - interface FlagSet { + interface BaseModel { /** - * BoolVar defines a bool flag with specified name, default value, and usage string. - * The argument p points to a bool variable in which to store the value of the flag. + * GetId returns the model id. */ - boolVar(p: boolean, name: string, value: boolean, usage: string): void + getId(): string } - interface FlagSet { + interface BaseModel { /** - * BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. + * SetId sets the model id to the provided string value. */ - boolVarP(p: boolean, name: string, value: boolean, usage: string): void + setId(id: string): void } - interface FlagSet { + interface BaseModel { /** - * Bool defines a bool flag with specified name, default value, and usage string. - * The return value is the address of a bool variable that stores the value of the flag. + * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). */ - bool(name: string, value: boolean, usage: string): (boolean | undefined) + markAsNew(): void } - interface FlagSet { + interface BaseModel { /** - * BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. + * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) */ - boolP(name: string, value: boolean, usage: string): (boolean | undefined) + markAsNotNew(): void } - interface FlagSet { + interface BaseModel { /** - * GetBoolSlice returns the []bool value of a flag with the given name. + * IsNew indicates what type of db query (insert or update) + * should be used with the model instance. */ - getBoolSlice(name: string): Array + isNew(): boolean } - interface FlagSet { + interface BaseModel { /** - * BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. - * The argument p points to a []bool variable in which to store the value of the flag. + * GetCreated returns the model Created datetime. */ - boolSliceVar(p: Array, name: string, value: Array, usage: string): void + getCreated(): types.DateTime } - interface FlagSet { + interface BaseModel { /** - * BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. + * GetUpdated returns the model Updated datetime. */ - boolSliceVarP(p: Array, name: string, value: Array, usage: string): void + getUpdated(): types.DateTime } - interface FlagSet { + interface BaseModel { /** - * BoolSlice defines a []bool flag with specified name, default value, and usage string. - * The return value is the address of a []bool variable that stores the value of the flag. + * RefreshId generates and sets a new model id. + * + * The generated id is a cryptographically random 15 characters length string. */ - boolSlice(name: string, value: Array, usage: string): (Array | undefined) + refreshId(): void } - interface FlagSet { + interface BaseModel { /** - * BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. + * RefreshCreated updates the model Created field with the current datetime. */ - boolSliceP(name: string, value: Array, usage: string): (Array | undefined) + refreshCreated(): void } - interface FlagSet { + interface BaseModel { /** - * GetBytesHex return the []byte value of a flag with the given name + * RefreshUpdated updates the model Updated field with the current datetime. */ - getBytesHex(name: string): string + refreshUpdated(): void } - interface FlagSet { + interface BaseModel { /** - * BytesHexVar defines an []byte flag with specified name, default value, and usage string. - * The argument p points to an []byte variable in which to store the value of the flag. + * PostScan implements the [dbx.PostScanner] interface. + * + * It is executed right after the model was populated with the db row values. */ - bytesHexVar(p: string, name: string, value: string, usage: string): void + 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 _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 { + /** + * 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 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 { + /** + * Binder is the interface that wraps the Bind method. + */ + interface Binder { + bind(c: Context, i: { + }): void + } + /** + * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and + * be able to be routed by Router. + */ + interface ServableContext { + /** + * Reset resets the context after request completes. It must be called along + * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. + * See `Echo#ServeHTTP()` + */ + reset(r: http.Request, w: http.ResponseWriter): void + } + // @ts-ignore + import stdContext = context + /** + * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. + */ + interface JSONSerializer { + serialize(c: Context, i: { + }, indent: string): void + deserialize(c: Context, i: { + }): void } - interface FlagSet { - /** - * BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. - */ - bytesHexVarP(p: string, name: string, value: string, usage: string): void + /** + * HTTPErrorHandler is a centralized HTTP error handler. + */ + interface HTTPErrorHandler {(c: Context, err: Error): void } + /** + * Validator is the interface that wraps the Validate function. + */ + interface Validator { + validate(i: { + }): void } - interface FlagSet { - /** - * BytesHex defines an []byte flag with specified name, default value, and usage string. - * The return value is the address of an []byte variable that stores the value of the flag. - */ - bytesHex(name: string, value: string, usage: string): (string | undefined) + /** + * Renderer is the interface that wraps the Render function. + */ + interface Renderer { + render(_arg0: io.Writer, _arg1: string, _arg2: { + }, _arg3: Context): void } - interface FlagSet { - /** - * BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. - */ - bytesHexP(name: string, value: string, usage: string): (string | undefined) + /** + * Group is a set of sub-routes for a specified route. It can be used for inner + * routes that share a common middleware or functionality that should be separate + * from the parent echo instance while still inheriting from it. + */ + interface Group { } - interface FlagSet { + interface Group { /** - * GetBytesBase64 return the []byte value of a flag with the given name + * Use implements `Echo#Use()` for sub-routes within the Group. + * Group middlewares are not executed on request when there is no matching route found. */ - getBytesBase64(name: string): string + use(...middleware: MiddlewareFunc[]): void } - interface FlagSet { + interface Group { /** - * BytesBase64Var defines an []byte flag with specified name, default value, and usage string. - * The argument p points to an []byte variable in which to store the value of the flag. + * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. */ - bytesBase64Var(p: string, name: string, value: string, usage: string): void + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. + * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. */ - bytesBase64VarP(p: string, name: string, value: string, usage: string): void + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * BytesBase64 defines an []byte flag with specified name, default value, and usage string. - * The return value is the address of an []byte variable that stores the value of the flag. + * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. */ - bytesBase64(name: string, value: string, usage: string): (string | undefined) + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. + * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. */ - bytesBase64P(name: string, value: string, usage: string): (string | undefined) + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * GetCount return the int value of a flag with the given name + * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. */ - getCount(name: string): number + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * CountVar defines a count flag with specified name, default value, and usage string. - * The argument p points to an int variable in which to store the value of the flag. - * A count flag will add 1 to its value every time it is found on the command line + * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. */ - countVar(p: number, name: string, usage: string): void + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * CountVarP is like CountVar only take a shorthand for the flag name. + * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. */ - countVarP(p: number, name: string, usage: string): void + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * Count defines a count flag with specified name, default value, and usage string. - * The return value is the address of an int variable that stores the value of the flag. - * A count flag will add 1 to its value every time it is found on the command line + * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. */ - count(name: string, usage: string): (number | undefined) + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * CountP is like Count only takes a shorthand for the flag name. + * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. */ - countP(name: string, usage: string): (number | undefined) + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * GetDuration return the duration value of a flag with the given name + * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. */ - getDuration(name: string): time.Duration + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface FlagSet { + interface Group { /** - * DurationVar defines a time.Duration flag with specified name, default value, and usage string. - * The argument p points to a time.Duration variable in which to store the value of the flag. + * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. */ - durationVar(p: time.Duration, name: string, value: time.Duration, usage: string): void + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface FlagSet { + interface Group { /** - * DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. + * Group creates a new sub-group with prefix and optional sub-group-level middleware. + * Important! Group middlewares are only executed in case there was exact route match and not + * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add + * a catch-all route `/*` for the group which handler returns always 404 */ - durationVarP(p: time.Duration, name: string, value: time.Duration, usage: string): void + group(prefix: string, ...middleware: MiddlewareFunc[]): (Group | undefined) } - interface FlagSet { + interface Group { /** - * Duration defines a time.Duration flag with specified name, default value, and usage string. - * The return value is the address of a time.Duration variable that stores the value of the flag. + * Static implements `Echo#Static()` for sub-routes within the Group. */ - duration(name: string, value: time.Duration, usage: string): (time.Duration | undefined) + static(pathPrefix: string): RouteInfo } - interface FlagSet { + interface Group { /** - * DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. + * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. + * + * 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. */ - durationP(name: string, value: time.Duration, usage: string): (time.Duration | undefined) + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface FlagSet { + interface Group { /** - * GetDurationSlice returns the []time.Duration value of a flag with the given name + * FileFS implements `Echo#FileFS()` for sub-routes within the Group. */ - getDurationSlice(name: string): Array + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. - * The argument p points to a []time.Duration variable in which to store the value of the flag. + * File implements `Echo#File()` for sub-routes within the Group. Panics on error. */ - durationSliceVar(p: Array, name: string, value: Array, usage: string): void + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. + * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. + * + * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - durationSliceVarP(p: Array, name: string, value: Array, usage: string): void + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. - * The return value is the address of a []time.Duration variable that stores the value of the flag. + * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. */ - durationSlice(name: string, value: Array, usage: string): (Array | undefined) + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - interface FlagSet { + interface Group { /** - * DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. + * AddRoute registers a new Routable with Router */ - durationSliceP(name: string, value: Array, usage: string): (Array | undefined) + addRoute(route: Routable): RouteInfo } - // @ts-ignore - import goflag = flag - /** - * NormalizedName is a flag name that has been normalized according to rules - * for the FlagSet (e.g. making '-' and '_' equivalent). - */ - interface NormalizedName extends String{} /** - * A FlagSet represents a set of defined flags. + * IPExtractor is a function to extract IP addr from http.Request. + * Set appropriate one to Echo#IPExtractor. + * See https://echo.labstack.com/guide/ip-address for more details. */ - interface FlagSet { - /** - * Usage is the function called when an error occurs while parsing flags. - * The field is a function (not a method) that may be changed to point to - * a custom error handler. - */ - usage: () => void - /** - * SortFlags is used to indicate, if user wants to have sorted flags in - * help/usage messages. - */ - sortFlags: boolean - /** - * ParseErrorsWhitelist is used to configure a whitelist of errors - */ - parseErrorsWhitelist: ParseErrorsWhitelist - } + interface IPExtractor {(_arg0: http.Request): string } /** - * A Flag represents the state of a flag. + * Logger defines the logging interface that Echo uses internally in few places. + * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. */ - interface Flag { - name: string // name as it appears on command line - shorthand: string // one-letter abbreviated flag - usage: string // help message - value: Value // value as set - defValue: string // default value (as text); for usage message - changed: boolean // If the user set the value (or if left to default) - noOptDefVal: string // default value (as text); if the flag is on the command line without any options - deprecated: string // If this flag is deprecated, this string is the new or now thing to use - hidden: boolean // used by cobra.Command to allow flags to be hidden from help/usage text - shorthandDeprecated: string // If the shorthand of this flag is deprecated, this string is the new or now thing to use - annotations: _TygojaDict // used by cobra.Command bash autocomple code - } - interface FlagSet { - /** - * SetNormalizeFunc allows you to add a function which can translate flag names. - * Flags added to the FlagSet will be translated and then when anything tries to - * look up the flag that will also be translated. So it would be possible to create - * a flag named "getURL" and have it translated to "geturl". A user could then pass - * "--getUrl" which may also be translated to "geturl" and everything will work. - */ - setNormalizeFunc(n: (f: FlagSet, name: string) => NormalizedName): void - } - interface FlagSet { - /** - * GetNormalizeFunc returns the previously set NormalizeFunc of a function which - * does no translation, if not set previously. - */ - getNormalizeFunc(): (f: FlagSet, name: string) => NormalizedName - } - interface FlagSet { + interface Logger { /** - * SetOutput sets the destination for usage and error messages. - * If output is nil, os.Stderr is used. + * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. + * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, + * and underlying FileSystem errors. + * `logger` middleware will use this method to write its JSON payload. */ - setOutput(output: io.Writer): void - } - interface FlagSet { + write(p: string): number /** - * VisitAll visits the flags in lexicographical order or - * in primordial order if f.SortFlags is false, calling fn for each. - * It visits all flags, even those not set. + * Error logs the error */ - visitAll(fn: (_arg0: Flag) => void): void + error(err: Error): void } - interface FlagSet { + /** + * Response wraps an http.ResponseWriter and implements its interface to be used + * by an HTTP handler to construct an HTTP response. + * See: https://golang.org/pkg/net/http/#ResponseWriter + */ + interface Response { + writer: http.ResponseWriter + status: number + size: number + committed: boolean + } + interface Response { /** - * HasFlags returns a bool to indicate if the FlagSet has any flags defined. + * Header returns the header map for the writer that will be sent by + * WriteHeader. Changing the header after a call to WriteHeader (or Write) has + * no effect unless the modified headers were declared as trailers by setting + * the "Trailer" header before the call to WriteHeader (see example) + * To suppress implicit response headers, set their value to nil. + * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers */ - hasFlags(): boolean + header(): http.Header } - interface FlagSet { + interface Response { /** - * HasAvailableFlags returns a bool to indicate if the FlagSet has any flags - * that are not hidden. + * Before registers a function which is called just before the response is written. */ - hasAvailableFlags(): boolean + before(fn: () => void): void } - interface FlagSet { + interface Response { /** - * Visit visits the flags in lexicographical order or - * in primordial order if f.SortFlags is false, calling fn for each. - * It visits only those flags that have been set. + * After registers a function which is called just after the response is written. + * If the `Content-Length` is unknown, none of the after function is executed. */ - visit(fn: (_arg0: Flag) => void): void + after(fn: () => void): void } - interface FlagSet { + interface Response { /** - * Lookup returns the Flag structure of the named flag, returning nil if none exists. + * WriteHeader sends an HTTP response header with 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. */ - lookup(name: string): (Flag | undefined) + writeHeader(code: number): void } - interface FlagSet { + interface Response { /** - * ShorthandLookup returns the Flag structure of the short handed flag, - * returning nil if none exists. - * It panics, if len(name) > 1. + * Write writes the data to the connection as part of an HTTP reply. */ - shorthandLookup(name: string): (Flag | undefined) + write(b: string): number } - interface FlagSet { + interface Response { /** - * ArgsLenAtDash will return the length of f.Args at the moment when a -- was - * found during arg parsing. This allows your program to know which args were - * before the -- and which came after. + * Flush implements the http.Flusher interface to allow an HTTP handler to flush + * buffered data to the client. + * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) */ - argsLenAtDash(): number + flush(): void } - interface FlagSet { + interface Response { /** - * MarkDeprecated indicated that a flag is deprecated in your program. It will - * continue to function but will not show up in help or usage messages. Using - * this flag will also print the given usageMessage. + * Hijack implements the http.Hijacker interface to allow an HTTP handler to + * take over the connection. + * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) */ - markDeprecated(name: string, usageMessage: string): void + hijack(): [net.Conn, (bufio.ReadWriter | undefined)] } - interface FlagSet { + interface Routes { /** - * MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your - * program. It will continue to function but will not show up in help or usage - * messages. Using this flag will also print the given usageMessage. + * Reverse reverses route to URL string by replacing path parameters with given params values. */ - markShorthandDeprecated(name: string, usageMessage: string): void + reverse(name: string, ...params: { + }[]): string } - interface FlagSet { + interface Routes { /** - * MarkHidden sets a flag to 'hidden' in your program. It will continue to - * function but will not show up in help or usage messages. + * FindByMethodPath searched for matching route info by method and path */ - markHidden(name: string): void + findByMethodPath(method: string, path: string): RouteInfo } - interface FlagSet { + interface Routes { /** - * Set sets the value of the named flag. + * FilterByMethod searched for matching route info by method */ - set(name: string): void + filterByMethod(method: string): Routes } - interface FlagSet { + interface Routes { /** - * SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. - * This is sometimes used by spf13/cobra programs which want to generate additional - * bash completion information. + * FilterByPath searched for matching route info by path */ - setAnnotation(name: string, values: Array): void + filterByPath(path: string): Routes } - interface FlagSet { + interface Routes { /** - * Changed returns true if the flag was explicitly set during Parse() and false - * otherwise + * FilterByName searched for matching route info by name */ - changed(name: string): boolean + filterByName(name: string): Routes } - interface FlagSet { + /** + * Router is interface for routing request contexts to registered routes. + * + * Contract between Echo/Context instance and the router: + * * all routes must be added through methods on echo.Echo instance. + * ``` + * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). + * ``` + * * Router must populate Context during Router.Route call with: + * ``` + * * RoutableContext.SetPath + * * RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) + * * RoutableContext.SetRouteInfo + * And optionally can set additional information to Context with RoutableContext.Set + * ``` + */ + interface Router { /** - * PrintDefaults prints, to standard error unless configured - * otherwise, the default values of all defined flags in the set. + * Add registers Routable with the Router and returns registered RouteInfo */ - printDefaults(): void - } - interface FlagSet { + add(routable: Routable): RouteInfo /** - * FlagUsagesWrapped returns a string containing the usage information - * for all flags in the FlagSet. Wrapped to `cols` columns (0 for no - * wrapping) + * Remove removes route from the Router */ - flagUsagesWrapped(cols: number): string - } - interface FlagSet { + remove(method: string, path: string): void /** - * FlagUsages returns a string containing the usage information for all flags in - * the FlagSet + * Routes returns information about all registered routes */ - flagUsages(): string - } - interface FlagSet { + routes(): Routes /** - * NFlag returns the number of flags that have been set. + * Route searches Router for matching route and applies it to the given context. In case when no matching method + * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 + * handler function. */ - nFlag(): number + route(c: RoutableContext): HandlerFunc } - interface FlagSet { + /** + * Routable is interface for registering Route with Router. During route registration process the Router will + * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional + * information about registered route can be stored in Routes (i.e. privileges used with route etc.) + */ + interface Routable { /** - * Arg returns the i'th argument. Arg(0) is the first remaining argument - * after flags have been processed. + * ToRouteInfo converts Routable to RouteInfo + * + * This method is meant to be used by Router after it parses url for path parameters, to store information about + * route just added. */ - arg(i: number): string - } - interface FlagSet { + toRouteInfo(params: Array): RouteInfo /** - * NArg is the number of arguments remaining after flags have been processed. + * ToRoute converts Routable to Route which Router uses to register the method handler for path. + * + * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to + * add Route to Router. */ - nArg(): number - } - interface FlagSet { + toRoute(): Route /** - * Args returns the non-flag arguments. + * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. + * + * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group + * middlewares included in actually registered Route. */ - args(): Array + forGroup(pathPrefix: string, middlewares: Array): Routable } - interface FlagSet { + /** + * Routes is collection of RouteInfo instances with various helper methods. + */ + interface Routes extends Array{} + /** + * RouteInfo describes registered route base fields. + * Method+Path pair uniquely identifies the Route. Name can have duplicates. + */ + interface RouteInfo { + method(): string + path(): string + name(): string + params(): Array + reverse(...params: { + }[]): string + } + /** + * PathParams is collections of PathParam instances with various helper methods + */ + interface PathParams extends Array{} + interface PathParams { /** - * Var defines a flag with the specified name and usage string. The type and - * value of the flag are represented by the first argument, of type Value, which - * typically holds a user-defined implementation of Value. For instance, the - * caller could create a flag that turns a comma-separated string into a slice - * of strings by giving the slice the methods of Value; in particular, Set would - * decompose the comma-separated string into the slice. + * Get returns path parameter value for given name or default value. */ - var(value: Value, name: string, usage: string): void + get(name: string, defaultValue: string): string } - interface FlagSet { +} + +/** + * Package oauth2 provides support for making + * OAuth2 authorized and authenticated HTTP requests, + * as specified in RFC 6749. + * It can additionally grant authorization with Bearer JWT. + */ +namespace oauth2 { + /** + * An AuthCodeOption is passed to Config.AuthCodeURL. + */ + interface AuthCodeOption { + } + /** + * Token represents the credentials used to authorize + * the requests to access protected resources on the OAuth 2.0 + * provider's backend. + * + * Most users of this package should not access fields of Token + * directly. They're exported mostly for use by related packages + * implementing derivative OAuth2 flows. + */ + interface Token { /** - * VarPF is like VarP, but returns the flag created + * AccessToken is the token that authorizes and authenticates + * the requests. */ - varPF(value: Value, name: string): (Flag | undefined) - } - interface FlagSet { + accessToken: string /** - * VarP is like Var, but accepts a shorthand letter that can be used after a single dash. + * TokenType is the type of token. + * The Type method returns either this or "Bearer", the default. */ - varP(value: Value, name: string): void - } - interface FlagSet { + tokenType: string /** - * AddFlag will add the flag to the FlagSet + * RefreshToken is a token that's used by the application + * (as opposed to the user) to refresh the access token + * if it expires. */ - addFlag(flag: Flag): void - } - interface FlagSet { + refreshToken: string /** - * AddFlagSet adds one FlagSet to another. If a flag is already present in f - * the flag from newSet will be ignored. + * Expiry is the optional expiration time of the access token. + * + * If zero, TokenSource implementations will reuse the same + * token forever and RefreshToken or equivalent + * mechanisms for that TokenSource will not be used. */ - addFlagSet(newSet: FlagSet): void + expiry: time.Time } - interface FlagSet { + interface Token { /** - * Parse parses flag definitions from the argument list, which should not - * include the command name. Must be called after all flags in the FlagSet - * are defined and before flags are accessed by the program. - * The return value will be ErrHelp if -help was set but not defined. + * Type returns t.TokenType if non-empty, else "Bearer". */ - parse(arguments: Array): void + type(): string } - interface FlagSet { + interface Token { /** - * ParseAll parses flag definitions from the argument list, which should not - * include the command name. The arguments for fn are flag and value. Must be - * called after all flags in the FlagSet are defined and before flags are - * accessed by the program. The return value will be ErrHelp if -help was set - * but not defined. + * SetAuthHeader sets the Authorization header to r using the access + * token in t. + * + * This method is unnecessary when using Transport or an HTTP Client + * returned by this package. */ - parseAll(arguments: Array, fn: (flag: Flag, value: string) => void): void + setAuthHeader(r: http.Request): void } - interface FlagSet { + interface Token { /** - * Parsed reports whether f.Parse has been called. + * WithExtra returns a new Token that's a clone of t, but using the + * provided raw extra map. This is only intended for use by packages + * implementing derivative OAuth2 flows. */ - parsed(): boolean + withExtra(extra: { + }): (Token | undefined) } - interface FlagSet { + interface Token { /** - * SetInterspersed sets whether to support interspersed option/non-option arguments. + * Extra returns an extra field. + * Extra fields are key-value pairs returned by the server as a + * part of the token retrieval response. */ - setInterspersed(interspersed: boolean): void + extra(key: string): { } - interface FlagSet { + } + interface Token { /** - * Init sets the name and error handling property for a flag set. - * By default, the zero FlagSet uses an empty name and the - * ContinueOnError error handling policy. + * Valid reports whether t is non-nil, has an AccessToken, and is not expired. */ - init(name: string, errorHandling: ErrorHandling): void + valid(): boolean } - interface FlagSet { +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + interface TokenConfig { + secret: string + duration: number + } + interface TokenConfig { /** - * GetFloat32 return the float32 value of a flag with the given name + * Validate makes TokenConfig validatable by implementing [validation.Validatable] interface. */ - getFloat32(name: string): number + validate(): void } - interface FlagSet { + interface SmtpConfig { + enabled: boolean + host: string + port: number + username: string + password: string /** - * Float32Var defines a float32 flag with specified name, default value, and usage string. - * The argument p points to a float32 variable in which to store the value of the flag. + * SMTP AUTH - PLAIN (default) or LOGIN */ - float32Var(p: number, name: string, value: number, usage: string): void - } - interface FlagSet { + authMethod: string /** - * Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. + * Whether to enforce TLS encryption for the mail server connection. + * + * When set to false StartTLS command is send, leaving the server + * to decide whether to upgrade the connection or not. */ - float32VarP(p: number, name: string, value: number, usage: string): void + tls: boolean } - interface FlagSet { + interface SmtpConfig { /** - * Float32 defines a float32 flag with specified name, default value, and usage string. - * The return value is the address of a float32 variable that stores the value of the flag. + * Validate makes SmtpConfig validatable by implementing [validation.Validatable] interface. */ - float32(name: string, value: number, usage: string): (number | undefined) + validate(): void } - interface FlagSet { + interface S3Config { + enabled: boolean + bucket: string + region: string + endpoint: string + accessKey: string + secret: string + forcePathStyle: boolean + } + interface S3Config { /** - * Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. + * Validate makes S3Config validatable by implementing [validation.Validatable] interface. */ - float32P(name: string, value: number, usage: string): (number | undefined) + validate(): void } - interface FlagSet { + interface BackupsConfig { /** - * GetFloat32Slice return the []float32 value of a flag with the given name + * Cron is a cron expression to schedule auto backups, eg. "* * * * *". + * + * Leave it empty to disable the auto backups functionality. */ - getFloat32Slice(name: string): Array - } - interface FlagSet { + cron: string /** - * Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string. - * The argument p points to a []float32 variable in which to store the value of the flag. + * CronMaxKeep is the the max number of cron generated backups to + * keep before removing older entries. + * + * This field works only when the cron config has valid cron expression. */ - float32SliceVar(p: Array, name: string, value: Array, usage: string): void - } - interface FlagSet { + cronMaxKeep: number /** - * Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. + * S3 is an optional S3 storage config specifying where to store the app backups. */ - float32SliceVarP(p: Array, name: string, value: Array, usage: string): void + s3: S3Config } - interface FlagSet { + interface BackupsConfig { /** - * Float32Slice defines a []float32 flag with specified name, default value, and usage string. - * The return value is the address of a []float32 variable that stores the value of the flag. + * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. */ - float32Slice(name: string, value: Array, usage: string): (Array | undefined) + validate(): void } - interface FlagSet { + interface MetaConfig { + appName: string + appUrl: string + hideControls: boolean + senderName: string + senderAddress: string + verificationTemplate: EmailTemplate + resetPasswordTemplate: EmailTemplate + confirmEmailChangeTemplate: EmailTemplate + } + interface MetaConfig { /** - * Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. + * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. */ - float32SliceP(name: string, value: Array, usage: string): (Array | undefined) + validate(): void } - interface FlagSet { + interface LogsConfig { + maxDays: number + } + interface LogsConfig { /** - * GetFloat64 return the float64 value of a flag with the given name + * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. */ - getFloat64(name: string): number + validate(): void } - interface FlagSet { + interface AuthProviderConfig { + enabled: boolean + clientId: string + clientSecret: string + authUrl: string + tokenUrl: string + userApiUrl: string + } + interface AuthProviderConfig { /** - * Float64Var defines a float64 flag with specified name, default value, and usage string. - * The argument p points to a float64 variable in which to store the value of the flag. + * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. */ - float64Var(p: number, name: string, value: number, usage: string): void + validate(): void } - interface FlagSet { + interface AuthProviderConfig { /** - * Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. + * SetupProvider loads the current AuthProviderConfig into the specified provider. */ - float64VarP(p: number, name: string, value: number, usage: string): void + setupProvider(provider: auth.Provider): void } - interface FlagSet { + /** + * Deprecated: Will be removed in v0.9+ + */ + interface EmailAuthConfig { + enabled: boolean + exceptDomains: Array + onlyDomains: Array + minPasswordLength: number + } + interface EmailAuthConfig { /** - * Float64 defines a float64 flag with specified name, default value, and usage string. - * The return value is the address of a float64 variable that stores the value of the flag. + * Deprecated: Will be removed in v0.9+ */ - float64(name: string, value: number, usage: string): (number | undefined) + validate(): void + } +} + +/** + * Package daos handles common PocketBase DB model manipulations. + * + * Think of daos as DB repository and service layer in one. + */ +namespace daos { + /** + * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. + */ + interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } + // @ts-ignore + import validation = ozzo_validation + interface RequestsStatsItem { + total: number + date: types.DateTime + } +} + +namespace hook { + /** + * Hook defines a concurrent safe structure for handling event hooks + * (aka. callbacks propagation). + */ + interface Hook { } - interface FlagSet { + interface Hook { /** - * Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). */ - float64P(name: string, value: number, usage: string): (number | undefined) + preAdd(fn: Handler): string } - interface FlagSet { + interface Hook { /** - * GetFloat64Slice return the []float64 value of a flag with the given name + * Add registers a new handler to the hook by appending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). */ - getFloat64Slice(name: string): Array + add(fn: Handler): string } - interface FlagSet { + interface Hook { /** - * Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string. - * The argument p points to a []float64 variable in which to store the value of the flag. + * Remove removes a single hook handler by its id. */ - float64SliceVar(p: Array, name: string, value: Array, usage: string): void + remove(id: string): void } - interface FlagSet { + interface Hook { /** - * Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. + * RemoveAll removes all registered handlers. */ - float64SliceVarP(p: Array, name: string, value: Array, usage: string): void + removeAll(): void } - interface FlagSet { + interface Hook { /** - * Float64Slice defines a []float64 flag with specified name, default value, and usage string. - * The return value is the address of a []float64 variable that stores the value of the flag. + * Trigger executes all registered hook handlers one by one + * with the specified `data` as an argument. + * + * Optionally, this method allows also to register additional one off + * handlers that will be temporary appended to the handlers queue. + * + * The execution stops when: + * - hook.StopPropagation is returned in one of the handlers + * - any non-nil error is returned in one of the handlers */ - float64Slice(name: string, value: Array, usage: string): (Array | undefined) + trigger(data: T, ...oneOffHandlers: Handler[]): void } - interface FlagSet { + /** + * 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 _subGNDdN = mainHook + interface TaggedHook extends _subGNDdN { + } + interface TaggedHook { /** - * Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. */ - float64SliceP(name: string, value: Array, usage: string): (Array | undefined) + canTriggerOn(tags: Array): boolean } - interface FlagSet { + interface TaggedHook { /** - * AddGoFlag will add the given *flag.Flag to the pflag.FlagSet + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. */ - addGoFlag(goflag: goflag.Flag): void + preAdd(fn: Handler): string } - interface FlagSet { + interface TaggedHook { /** - * AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet + * Add registers a new handler to the hook by appending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. */ - addGoFlagSet(newSet: goflag.FlagSet): void + add(fn: Handler): string } - interface FlagSet { +} + +namespace subscriptions { + /** + * Broker defines a struct for managing subscriptions clients. + */ + interface Broker { + } + interface Broker { /** - * GetInt return the int value of a flag with the given name + * Clients returns a shallow copy of all registered clients indexed + * with their connection id. */ - getInt(name: string): number + clients(): _TygojaDict } - interface FlagSet { + interface Broker { /** - * IntVar defines an int flag with specified name, default value, and usage string. - * The argument p points to an int variable in which to store the value of the flag. + * ClientById finds a registered client by its id. + * + * Returns non-nil error when client with clientId is not registered. */ - intVar(p: number, name: string, value: number, usage: string): void + clientById(clientId: string): Client } - interface FlagSet { + interface Broker { /** - * IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. + * Register adds a new client to the broker instance. */ - intVarP(p: number, name: string, value: number, usage: string): void + register(client: Client): void } - interface FlagSet { + interface Broker { /** - * Int defines an int flag with specified name, default value, and usage string. - * The return value is the address of an int variable that stores the value of the flag. + * Unregister removes a single client by its id. + * + * If client with clientId doesn't exist, this method does nothing. */ - int(name: string, value: number, usage: string): (number | undefined) + unregister(clientId: string): void + } +} + +/** + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + interface BootstrapEvent { + app: App + } + interface TerminateEvent { + app: App + } + interface ServeEvent { + app: App + router?: echo.Echo + server?: http.Server + certManager?: autocert.Manager + } + interface ApiErrorEvent { + httpContext: echo.Context + error: Error + } + type _subXskBJ = BaseModelEvent + interface ModelEvent extends _subXskBJ { + dao?: daos.Dao + } + type _subYlIos = BaseCollectionEvent + interface MailerRecordEvent extends _subYlIos { + mailClient: mailer.Mailer + message?: mailer.Message + record?: models.Record + meta: _TygojaDict + } + interface MailerAdminEvent { + mailClient: mailer.Mailer + message?: mailer.Message + admin?: models.Admin + meta: _TygojaDict + } + interface RealtimeConnectEvent { + httpContext: echo.Context + client: subscriptions.Client + } + interface RealtimeDisconnectEvent { + httpContext: echo.Context + client: subscriptions.Client + } + interface RealtimeMessageEvent { + httpContext: echo.Context + client: subscriptions.Client + message?: subscriptions.Message + } + interface RealtimeSubscribeEvent { + httpContext: echo.Context + client: subscriptions.Client + subscriptions: Array + } + interface SettingsListEvent { + httpContext: echo.Context + redactedSettings?: settings.Settings + } + interface SettingsUpdateEvent { + httpContext: echo.Context + oldSettings?: settings.Settings + newSettings?: settings.Settings + } + type _subUASMa = BaseCollectionEvent + interface RecordsListEvent extends _subUASMa { + httpContext: echo.Context + records: Array<(models.Record | undefined)> + result?: search.Result + } + type _subQLlti = BaseCollectionEvent + interface RecordViewEvent extends _subQLlti { + httpContext: echo.Context + record?: models.Record + } + type _subafMcU = BaseCollectionEvent + interface RecordCreateEvent extends _subafMcU { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subAbvxm = BaseCollectionEvent + interface RecordUpdateEvent extends _subAbvxm { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subezArM = BaseCollectionEvent + interface RecordDeleteEvent extends _subezArM { + httpContext: echo.Context + record?: models.Record + } + type _subDAzkU = BaseCollectionEvent + interface RecordAuthEvent extends _subDAzkU { + httpContext: echo.Context + record?: models.Record + token: string + meta: any + } + type _subpNCMb = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subpNCMb { + httpContext: echo.Context + record?: models.Record + identity: string + password: string + } + type _subPFzCX = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subPFzCX { + httpContext: echo.Context + providerName: string + providerClient: auth.Provider + record?: models.Record + oAuth2User?: auth.AuthUser + isNewRecord: boolean + } + type _subuVcEL = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subuVcEL { + httpContext: echo.Context + record?: models.Record + } + type _subVNzno = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subVNzno { + httpContext: echo.Context + record?: models.Record + } + type _sublpewg = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _sublpewg { + httpContext: echo.Context + record?: models.Record + } + type _subdnBpr = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subdnBpr { + httpContext: echo.Context + record?: models.Record + } + type _subfIECD = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subfIECD { + httpContext: echo.Context + record?: models.Record + } + type _subtMMey = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subtMMey { + httpContext: echo.Context + record?: models.Record + } + type _subWZErX = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subWZErX { + httpContext: echo.Context + record?: models.Record + } + type _subQTWxd = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subQTWxd { + httpContext: echo.Context + record?: models.Record + externalAuths: Array<(models.ExternalAuth | undefined)> + } + type _subYKXBw = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subYKXBw { + httpContext: echo.Context + record?: models.Record + externalAuth?: models.ExternalAuth + } + interface AdminsListEvent { + httpContext: echo.Context + admins: Array<(models.Admin | undefined)> + result?: search.Result + } + interface AdminViewEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminCreateEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminUpdateEvent { + httpContext: echo.Context + admin?: models.Admin } - interface FlagSet { - /** - * IntP is like Int, but accepts a shorthand letter that can be used after a single dash. - */ - intP(name: string, value: number, usage: string): (number | undefined) + interface AdminDeleteEvent { + httpContext: echo.Context + admin?: models.Admin } - interface FlagSet { - /** - * GetInt16 returns the int16 value of a flag with the given name - */ - getInt16(name: string): number + interface AdminAuthEvent { + httpContext: echo.Context + admin?: models.Admin + token: string } - interface FlagSet { - /** - * Int16Var defines an int16 flag with specified name, default value, and usage string. - * The argument p points to an int16 variable in which to store the value of the flag. - */ - int16Var(p: number, name: string, value: number, usage: string): void + interface AdminAuthWithPasswordEvent { + httpContext: echo.Context + admin?: models.Admin + identity: string + password: string } - interface FlagSet { - /** - * Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. - */ - int16VarP(p: number, name: string, value: number, usage: string): void + interface AdminAuthRefreshEvent { + httpContext: echo.Context + admin?: models.Admin } - interface FlagSet { - /** - * Int16 defines an int16 flag with specified name, default value, and usage string. - * The return value is the address of an int16 variable that stores the value of the flag. - */ - int16(name: string, value: number, usage: string): (number | undefined) + interface AdminRequestPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin } - interface FlagSet { - /** - * Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. - */ - int16P(name: string, value: number, usage: string): (number | undefined) + interface AdminConfirmPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin } - interface FlagSet { - /** - * GetInt32 return the int32 value of a flag with the given name - */ - getInt32(name: string): number + interface CollectionsListEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> + result?: search.Result } - interface FlagSet { - /** - * Int32Var defines an int32 flag with specified name, default value, and usage string. - * The argument p points to an int32 variable in which to store the value of the flag. - */ - int32Var(p: number, name: string, value: number, usage: string): void + type _subSEtSL = BaseCollectionEvent + interface CollectionViewEvent extends _subSEtSL { + httpContext: echo.Context } - interface FlagSet { - /** - * Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. - */ - int32VarP(p: number, name: string, value: number, usage: string): void + type _subBEbOd = BaseCollectionEvent + interface CollectionCreateEvent extends _subBEbOd { + httpContext: echo.Context } - interface FlagSet { - /** - * Int32 defines an int32 flag with specified name, default value, and usage string. - * The return value is the address of an int32 variable that stores the value of the flag. - */ - int32(name: string, value: number, usage: string): (number | undefined) + type _subgybca = BaseCollectionEvent + interface CollectionUpdateEvent extends _subgybca { + httpContext: echo.Context } - interface FlagSet { - /** - * Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. - */ - int32P(name: string, value: number, usage: string): (number | undefined) + type _subzLgCr = BaseCollectionEvent + interface CollectionDeleteEvent extends _subzLgCr { + httpContext: echo.Context } - interface FlagSet { - /** - * GetInt32Slice return the []int32 value of a flag with the given name - */ - getInt32Slice(name: string): Array + interface CollectionsImportEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> } - interface FlagSet { - /** - * Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string. - * The argument p points to a []int32 variable in which to store the value of the flag. - */ - int32SliceVar(p: Array, name: string, value: Array, usage: string): void + type _subGsarQ = BaseModelEvent + interface FileTokenEvent extends _subGsarQ { + httpContext: echo.Context + token: string } - interface FlagSet { - /** - * Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. - */ - int32SliceVarP(p: Array, name: string, value: Array, usage: string): void + type _subhNSaq = BaseCollectionEvent + interface FileDownloadEvent extends _subhNSaq { + httpContext: echo.Context + record?: models.Record + fileField?: schema.SchemaField + servedPath: string + servedName: string } +} + +/** + * Package pflag is a drop-in replacement for Go's flag package, implementing + * POSIX/GNU-style --flags. + * + * pflag is compatible with the GNU extensions to the POSIX recommendations + * for command-line options. See + * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + * + * Usage: + * + * pflag is a drop-in replacement of Go's native flag package. If you import + * pflag under the name "flag" then all code should continue to function + * with no changes. + * + * ``` + * import flag "github.com/spf13/pflag" + * ``` + * + * There is one exception to this: if you directly instantiate the Flag struct + * there is one more field "Shorthand" that you will need to set. + * Most code never instantiates this struct directly, and instead uses + * functions such as String(), BoolVar(), and Var(), and is therefore + * unaffected. + * + * Define flags using flag.String(), Bool(), Int(), etc. + * + * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + * ``` + * var ip = flag.Int("flagname", 1234, "help message for flagname") + * ``` + * 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 after the flag are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * The pflag package also defines some new functions that are not in flag, + * that give one-letter shorthands for flags. You can use these by appending + * 'P' to the name of any function that defines a flag. + * ``` + * var ip = flag.IntP("flagname", "f", 1234, "help message") + * var flagvar bool + * func init() { + * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + * } + * flag.VarP(&flagval, "varname", "v", "help message") + * ``` + * Shorthand letters can be used with single dashes on the command line. + * Boolean shorthand flags can be combined with other shorthand flags. + * + * Command line flag syntax: + * ``` + * --flag // boolean flags only + * --flag=x + * ``` + * + * Unlike the flag package, a single dash before an option means something + * different than a double dash. Single dashes signify a series of shorthand + * letters for flags. All but the last shorthand letter must be boolean flags. + * ``` + * // boolean flags + * -f + * -abc + * // non-boolean flags + * -n 1234 + * -Ifile + * // mixed + * -abcs "hello" + * -abcn1234 + * ``` + * + * Flag parsing stops after the terminator "--". Unlike the flag package, + * flags can be interspersed with arguments anywhere on the command line + * before this terminator. + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags (in their long form) accept 1, 0, 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 pflag { interface FlagSet { /** - * Int32Slice defines a []int32 flag with specified name, default value, and usage string. - * The return value is the address of a []int32 variable that stores the value of the flag. + * GetBool return the bool value of a flag with the given name */ - int32Slice(name: string, value: Array, usage: string): (Array | undefined) + getBool(name: string): boolean } interface FlagSet { /** - * Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. + * BoolVar defines a bool flag with specified name, default value, and usage string. + * The argument p points to a bool variable in which to store the value of the flag. */ - int32SliceP(name: string, value: Array, usage: string): (Array | undefined) + boolVar(p: boolean, name: string, value: boolean, usage: string): void } interface FlagSet { /** - * GetInt64 return the int64 value of a flag with the given name + * BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. */ - getInt64(name: string): number + boolVarP(p: boolean, name: string, value: boolean, usage: string): void } interface FlagSet { /** - * Int64Var defines an int64 flag with specified name, default value, and usage string. - * The argument p points to an int64 variable in which to store the value of the flag. + * Bool defines a bool flag with specified name, default value, and usage string. + * The return value is the address of a bool variable that stores the value of the flag. */ - int64Var(p: number, name: string, value: number, usage: string): void + bool(name: string, value: boolean, usage: string): (boolean | undefined) } interface FlagSet { /** - * Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. + * BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. */ - int64VarP(p: number, name: string, value: number, usage: string): void + boolP(name: string, value: boolean, usage: string): (boolean | undefined) } interface FlagSet { /** - * Int64 defines an int64 flag with specified name, default value, and usage string. - * The return value is the address of an int64 variable that stores the value of the flag. + * GetBoolSlice returns the []bool value of a flag with the given name. */ - int64(name: string, value: number, usage: string): (number | undefined) + getBoolSlice(name: string): Array } interface FlagSet { /** - * Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. + * BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. + * The argument p points to a []bool variable in which to store the value of the flag. */ - int64P(name: string, value: number, usage: string): (number | undefined) + boolSliceVar(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * GetInt64Slice return the []int64 value of a flag with the given name + * BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - getInt64Slice(name: string): Array + boolSliceVarP(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string. - * The argument p points to a []int64 variable in which to store the value of the flag. + * BoolSlice defines a []bool flag with specified name, default value, and usage string. + * The return value is the address of a []bool variable that stores the value of the flag. */ - int64SliceVar(p: Array, name: string, value: Array, usage: string): void + boolSlice(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. + * BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. */ - int64SliceVarP(p: Array, name: string, value: Array, usage: string): void + boolSliceP(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Int64Slice defines a []int64 flag with specified name, default value, and usage string. - * The return value is the address of a []int64 variable that stores the value of the flag. + * GetBytesHex return the []byte value of a flag with the given name */ - int64Slice(name: string, value: Array, usage: string): (Array | undefined) + getBytesHex(name: string): string } interface FlagSet { /** - * Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. + * BytesHexVar defines an []byte flag with specified name, default value, and usage string. + * The argument p points to an []byte variable in which to store the value of the flag. */ - int64SliceP(name: string, value: Array, usage: string): (Array | undefined) + bytesHexVar(p: string, name: string, value: string, usage: string): void } interface FlagSet { /** - * GetInt8 return the int8 value of a flag with the given name + * BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. */ - getInt8(name: string): number + bytesHexVarP(p: string, name: string, value: string, usage: string): void } interface FlagSet { /** - * Int8Var defines an int8 flag with specified name, default value, and usage string. - * The argument p points to an int8 variable in which to store the value of the flag. + * BytesHex defines an []byte flag with specified name, default value, and usage string. + * The return value is the address of an []byte variable that stores the value of the flag. */ - int8Var(p: number, name: string, value: number, usage: string): void + bytesHex(name: string, value: string, usage: string): (string | undefined) } interface FlagSet { /** - * Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. + * BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. */ - int8VarP(p: number, name: string, value: number, usage: string): void + bytesHexP(name: string, value: string, usage: string): (string | undefined) } interface FlagSet { /** - * Int8 defines an int8 flag with specified name, default value, and usage string. - * The return value is the address of an int8 variable that stores the value of the flag. + * GetBytesBase64 return the []byte value of a flag with the given name */ - int8(name: string, value: number, usage: string): (number | undefined) + getBytesBase64(name: string): string } interface FlagSet { /** - * Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. + * BytesBase64Var defines an []byte flag with specified name, default value, and usage string. + * The argument p points to an []byte variable in which to store the value of the flag. */ - int8P(name: string, value: number, usage: string): (number | undefined) + bytesBase64Var(p: string, name: string, value: string, usage: string): void } interface FlagSet { /** - * GetIntSlice return the []int value of a flag with the given name + * BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. */ - getIntSlice(name: string): Array + bytesBase64VarP(p: string, name: string, value: string, usage: string): void } interface FlagSet { /** - * IntSliceVar defines a intSlice flag with specified name, default value, and usage string. - * The argument p points to a []int variable in which to store the value of the flag. + * BytesBase64 defines an []byte flag with specified name, default value, and usage string. + * The return value is the address of an []byte variable that stores the value of the flag. */ - intSliceVar(p: Array, name: string, value: Array, usage: string): void + bytesBase64(name: string, value: string, usage: string): (string | undefined) } interface FlagSet { /** - * IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. + * BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. */ - intSliceVarP(p: Array, name: string, value: Array, usage: string): void + bytesBase64P(name: string, value: string, usage: string): (string | undefined) } interface FlagSet { /** - * IntSlice defines a []int flag with specified name, default value, and usage string. - * The return value is the address of a []int variable that stores the value of the flag. + * GetCount return the int value of a flag with the given name */ - intSlice(name: string, value: Array, usage: string): (Array | undefined) + getCount(name: string): number } interface FlagSet { /** - * IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. + * CountVar defines a count flag with specified name, default value, and usage string. + * The argument p points to an int variable in which to store the value of the flag. + * A count flag will add 1 to its value every time it is found on the command line */ - intSliceP(name: string, value: Array, usage: string): (Array | undefined) + countVar(p: number, name: string, usage: string): void } interface FlagSet { /** - * GetIP return the net.IP value of a flag with the given name + * CountVarP is like CountVar only take a shorthand for the flag name. */ - getIP(name: string): net.IP + countVarP(p: number, name: string, usage: string): void } interface FlagSet { /** - * IPVar defines an net.IP flag with specified name, default value, and usage string. - * The argument p points to an net.IP variable in which to store the value of the flag. + * Count defines a count flag with specified name, default value, and usage string. + * The return value is the address of an int variable that stores the value of the flag. + * A count flag will add 1 to its value every time it is found on the command line */ - ipVar(p: net.IP, name: string, value: net.IP, usage: string): void + count(name: string, usage: string): (number | undefined) } interface FlagSet { /** - * IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. + * CountP is like Count only takes a shorthand for the flag name. */ - ipVarP(p: net.IP, name: string, value: net.IP, usage: string): void + countP(name: string, usage: string): (number | undefined) } interface FlagSet { /** - * IP defines an net.IP flag with specified name, default value, and usage string. - * The return value is the address of an net.IP variable that stores the value of the flag. + * GetDuration return the duration value of a flag with the given name */ - ip(name: string, value: net.IP, usage: string): (net.IP | undefined) + getDuration(name: string): time.Duration } interface FlagSet { /** - * IPP is like IP, but accepts a shorthand letter that can be used after a single dash. + * DurationVar defines a time.Duration flag with specified name, default value, and usage string. + * The argument p points to a time.Duration variable in which to store the value of the flag. */ - ipp(name: string, value: net.IP, usage: string): (net.IP | undefined) + durationVar(p: time.Duration, name: string, value: time.Duration, usage: string): void } interface FlagSet { /** - * GetIPSlice returns the []net.IP value of a flag with the given name + * DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. */ - getIPSlice(name: string): Array + durationVarP(p: time.Duration, name: string, value: time.Duration, usage: string): void } interface FlagSet { /** - * IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. - * The argument p points to a []net.IP variable in which to store the value of the flag. + * Duration defines a time.Duration flag with specified name, default value, and usage string. + * The return value is the address of a time.Duration variable that stores the value of the flag. */ - ipSliceVar(p: Array, name: string, value: Array, usage: string): void + duration(name: string, value: time.Duration, usage: string): (time.Duration | undefined) } interface FlagSet { /** - * IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. + * DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. */ - ipSliceVarP(p: Array, name: string, value: Array, usage: string): void + durationP(name: string, value: time.Duration, usage: string): (time.Duration | undefined) } interface FlagSet { /** - * IPSlice defines a []net.IP flag with specified name, default value, and usage string. - * The return value is the address of a []net.IP variable that stores the value of that flag. + * GetDurationSlice returns the []time.Duration value of a flag with the given name */ - ipSlice(name: string, value: Array, usage: string): (Array | undefined) + getDurationSlice(name: string): Array } interface FlagSet { /** - * IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. + * DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. + * The argument p points to a []time.Duration variable in which to store the value of the flag. */ - ipSliceP(name: string, value: Array, usage: string): (Array | undefined) + durationSliceVar(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * GetIPv4Mask return the net.IPv4Mask value of a flag with the given name + * DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - getIPv4Mask(name: string): net.IPMask + durationSliceVarP(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. - * The argument p points to an net.IPMask variable in which to store the value of the flag. + * DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. + * The return value is the address of a []time.Duration variable that stores the value of the flag. */ - ipMaskVar(p: net.IPMask, name: string, value: net.IPMask, usage: string): void + durationSlice(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. + * DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. */ - ipMaskVarP(p: net.IPMask, name: string, value: net.IPMask, usage: string): void + durationSliceP(name: string, value: Array, usage: string): (Array | undefined) } + // @ts-ignore + import goflag = flag + /** + * NormalizedName is a flag name that has been normalized according to rules + * for the FlagSet (e.g. making '-' and '_' equivalent). + */ + interface NormalizedName extends String{} + /** + * A FlagSet represents a set of defined flags. + */ interface FlagSet { /** - * IPMask defines an net.IPMask flag with specified name, default value, and usage string. - * The return value is the address of an net.IPMask variable that stores the value of the flag. + * Usage is the function called when an error occurs while parsing flags. + * The field is a function (not a method) that may be changed to point to + * a custom error handler. */ - ipMask(name: string, value: net.IPMask, usage: string): (net.IPMask | undefined) + usage: () => void + /** + * SortFlags is used to indicate, if user wants to have sorted flags in + * help/usage messages. + */ + sortFlags: boolean + /** + * ParseErrorsWhitelist is used to configure a whitelist of errors + */ + parseErrorsWhitelist: ParseErrorsWhitelist + } + /** + * A Flag represents the state of a flag. + */ + interface Flag { + name: string // name as it appears on command line + shorthand: string // one-letter abbreviated flag + usage: string // help message + value: Value // value as set + defValue: string // default value (as text); for usage message + changed: boolean // If the user set the value (or if left to default) + noOptDefVal: string // default value (as text); if the flag is on the command line without any options + deprecated: string // If this flag is deprecated, this string is the new or now thing to use + hidden: boolean // used by cobra.Command to allow flags to be hidden from help/usage text + shorthandDeprecated: string // If the shorthand of this flag is deprecated, this string is the new or now thing to use + annotations: _TygojaDict // used by cobra.Command bash autocomple code } interface FlagSet { /** - * IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. + * SetNormalizeFunc allows you to add a function which can translate flag names. + * Flags added to the FlagSet will be translated and then when anything tries to + * look up the flag that will also be translated. So it would be possible to create + * a flag named "getURL" and have it translated to "geturl". A user could then pass + * "--getUrl" which may also be translated to "geturl" and everything will work. */ - ipMaskP(name: string, value: net.IPMask, usage: string): (net.IPMask | undefined) + setNormalizeFunc(n: (f: FlagSet, name: string) => NormalizedName): void } interface FlagSet { /** - * GetIPNet return the net.IPNet value of a flag with the given name + * GetNormalizeFunc returns the previously set NormalizeFunc of a function which + * does no translation, if not set previously. */ - getIPNet(name: string): net.IPNet + getNormalizeFunc(): (f: FlagSet, name: string) => NormalizedName } interface FlagSet { /** - * IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. - * The argument p points to an net.IPNet variable in which to store the value of the flag. + * SetOutput sets the destination for usage and error messages. + * If output is nil, os.Stderr is used. */ - ipNetVar(p: net.IPNet, name: string, value: net.IPNet, usage: string): void + setOutput(output: io.Writer): void } interface FlagSet { /** - * IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. + * VisitAll visits the flags in lexicographical order or + * in primordial order if f.SortFlags is false, calling fn for each. + * It visits all flags, even those not set. */ - ipNetVarP(p: net.IPNet, name: string, value: net.IPNet, usage: string): void + visitAll(fn: (_arg0: Flag) => void): void } interface FlagSet { /** - * IPNet defines an net.IPNet flag with specified name, default value, and usage string. - * The return value is the address of an net.IPNet variable that stores the value of the flag. + * HasFlags returns a bool to indicate if the FlagSet has any flags defined. */ - ipNet(name: string, value: net.IPNet, usage: string): (net.IPNet | undefined) + hasFlags(): boolean } interface FlagSet { /** - * IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. + * HasAvailableFlags returns a bool to indicate if the FlagSet has any flags + * that are not hidden. */ - ipNetP(name: string, value: net.IPNet, usage: string): (net.IPNet | undefined) + hasAvailableFlags(): boolean } interface FlagSet { /** - * GetString return the string value of a flag with the given name + * Visit visits the flags in lexicographical order or + * in primordial order if f.SortFlags is false, calling fn for each. + * It visits only those flags that have been set. */ - getString(name: string): string + visit(fn: (_arg0: Flag) => void): void } interface FlagSet { /** - * StringVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a string variable in which to store the value of the flag. + * Lookup returns the Flag structure of the named flag, returning nil if none exists. */ - stringVar(p: string, name: string, value: string, usage: string): void + lookup(name: string): (Flag | undefined) } interface FlagSet { /** - * StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. + * ShorthandLookup returns the Flag structure of the short handed flag, + * returning nil if none exists. + * It panics, if len(name) > 1. */ - stringVarP(p: string, name: string, value: string, usage: string): void + shorthandLookup(name: string): (Flag | undefined) } interface FlagSet { /** - * String defines a string flag with specified name, default value, and usage string. - * The return value is the address of a string variable that stores the value of the flag. + * ArgsLenAtDash will return the length of f.Args at the moment when a -- was + * found during arg parsing. This allows your program to know which args were + * before the -- and which came after. */ - string(name: string, value: string, usage: string): (string | undefined) + argsLenAtDash(): number } interface FlagSet { /** - * StringP is like String, but accepts a shorthand letter that can be used after a single dash. + * MarkDeprecated indicated that a flag is deprecated in your program. It will + * continue to function but will not show up in help or usage messages. Using + * this flag will also print the given usageMessage. */ - stringP(name: string, value: string, usage: string): (string | undefined) + markDeprecated(name: string, usageMessage: string): void } interface FlagSet { /** - * GetStringArray return the []string value of a flag with the given name + * MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your + * program. It will continue to function but will not show up in help or usage + * messages. Using this flag will also print the given usageMessage. */ - getStringArray(name: string): Array + markShorthandDeprecated(name: string, usageMessage: string): void } interface FlagSet { /** - * StringArrayVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a []string variable in which to store the values of the multiple flags. - * The value of each argument will not try to be separated by comma. Use a StringSlice for that. + * MarkHidden sets a flag to 'hidden' in your program. It will continue to + * function but will not show up in help or usage messages. */ - stringArrayVar(p: Array, name: string, value: Array, usage: string): void + markHidden(name: string): void } interface FlagSet { /** - * StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. + * Set sets the value of the named flag. */ - stringArrayVarP(p: Array, name: string, value: Array, usage: string): void + set(name: string): void } interface FlagSet { /** - * StringArray defines a string flag with specified name, default value, and usage string. - * The return value is the address of a []string variable that stores the value of the flag. - * The value of each argument will not try to be separated by comma. Use a StringSlice for that. + * SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. + * This is sometimes used by spf13/cobra programs which want to generate additional + * bash completion information. */ - stringArray(name: string, value: Array, usage: string): (Array | undefined) + setAnnotation(name: string, values: Array): void } interface FlagSet { /** - * StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. + * Changed returns true if the flag was explicitly set during Parse() and false + * otherwise */ - stringArrayP(name: string, value: Array, usage: string): (Array | undefined) + changed(name: string): boolean } interface FlagSet { /** - * GetStringSlice return the []string value of a flag with the given name + * PrintDefaults prints, to standard error unless configured + * otherwise, the default values of all defined flags in the set. */ - getStringSlice(name: string): Array + printDefaults(): void } interface FlagSet { /** - * StringSliceVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a []string variable in which to store the value of the flag. - * Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. - * For example: - * ``` - * --ss="v1,v2" --ss="v3" - * ``` - * will result in - * ``` - * []string{"v1", "v2", "v3"} - * ``` + * FlagUsagesWrapped returns a string containing the usage information + * for all flags in the FlagSet. Wrapped to `cols` columns (0 for no + * wrapping) */ - stringSliceVar(p: Array, name: string, value: Array, usage: string): void + flagUsagesWrapped(cols: number): string } interface FlagSet { /** - * StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. + * FlagUsages returns a string containing the usage information for all flags in + * the FlagSet */ - stringSliceVarP(p: Array, name: string, value: Array, usage: string): void + flagUsages(): string } interface FlagSet { /** - * StringSlice defines a string flag with specified name, default value, and usage string. - * The return value is the address of a []string variable that stores the value of the flag. - * Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. - * For example: - * ``` - * --ss="v1,v2" --ss="v3" - * ``` - * will result in - * ``` - * []string{"v1", "v2", "v3"} - * ``` + * NFlag returns the number of flags that have been set. */ - stringSlice(name: string, value: Array, usage: string): (Array | undefined) + nFlag(): number } interface FlagSet { /** - * StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. + * Arg returns the i'th argument. Arg(0) is the first remaining argument + * after flags have been processed. */ - stringSliceP(name: string, value: Array, usage: string): (Array | undefined) + arg(i: number): string } interface FlagSet { /** - * GetStringToInt return the map[string]int value of a flag with the given name + * NArg is the number of arguments remaining after flags have been processed. */ - getStringToInt(name: string): _TygojaDict + nArg(): number } interface FlagSet { /** - * StringToIntVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a map[string]int variable in which to store the values of the multiple flags. - * The value of each argument will not try to be separated by comma + * Args returns the non-flag arguments. */ - stringToIntVar(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + args(): Array } interface FlagSet { /** - * StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. + * Var defines a flag with the specified name and usage string. The type and + * value of the flag are represented by the first argument, of type Value, which + * typically holds a user-defined implementation of Value. For instance, the + * caller could create a flag that turns a comma-separated string into a slice + * of strings by giving the slice the methods of Value; in particular, Set would + * decompose the comma-separated string into the slice. */ - stringToIntVarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + var(value: Value, name: string, usage: string): void } interface FlagSet { /** - * StringToInt defines a string flag with specified name, default value, and usage string. - * The return value is the address of a map[string]int variable that stores the value of the flag. - * The value of each argument will not try to be separated by comma + * VarPF is like VarP, but returns the flag created */ - stringToInt(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + varPF(value: Value, name: string): (Flag | undefined) } interface FlagSet { /** - * StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. + * VarP is like Var, but accepts a shorthand letter that can be used after a single dash. */ - stringToIntP(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + varP(value: Value, name: string): void } interface FlagSet { /** - * GetStringToInt64 return the map[string]int64 value of a flag with the given name + * AddFlag will add the flag to the FlagSet */ - getStringToInt64(name: string): _TygojaDict + addFlag(flag: Flag): void } interface FlagSet { /** - * StringToInt64Var defines a string flag with specified name, default value, and usage string. - * The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags. - * The value of each argument will not try to be separated by comma + * AddFlagSet adds one FlagSet to another. If a flag is already present in f + * the flag from newSet will be ignored. */ - stringToInt64Var(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + addFlagSet(newSet: FlagSet): void } interface FlagSet { /** - * StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. + * Parse parses flag definitions from the argument list, which should not + * include the command name. Must be called after all flags in the FlagSet + * are defined and before flags are accessed by the program. + * The return value will be ErrHelp if -help was set but not defined. */ - stringToInt64VarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + parse(arguments: Array): void } interface FlagSet { /** - * StringToInt64 defines a string flag with specified name, default value, and usage string. - * The return value is the address of a map[string]int64 variable that stores the value of the flag. - * The value of each argument will not try to be separated by comma + * ParseAll parses flag definitions from the argument list, which should not + * include the command name. The arguments for fn are flag and value. Must be + * called after all flags in the FlagSet are defined and before flags are + * accessed by the program. The return value will be ErrHelp if -help was set + * but not defined. */ - stringToInt64(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + parseAll(arguments: Array, fn: (flag: Flag, value: string) => void): void } interface FlagSet { /** - * StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. + * Parsed reports whether f.Parse has been called. */ - stringToInt64P(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + parsed(): boolean } interface FlagSet { /** - * GetStringToString return the map[string]string value of a flag with the given name + * SetInterspersed sets whether to support interspersed option/non-option arguments. */ - getStringToString(name: string): _TygojaDict + setInterspersed(interspersed: boolean): void } interface FlagSet { /** - * StringToStringVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a map[string]string variable in which to store the values of the multiple flags. - * The value of each argument will not try to be separated by comma + * Init sets the name and error handling property for a flag set. + * By default, the zero FlagSet uses an empty name and the + * ContinueOnError error handling policy. */ - stringToStringVar(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + init(name: string, errorHandling: ErrorHandling): void } interface FlagSet { /** - * StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. + * GetFloat32 return the float32 value of a flag with the given name */ - stringToStringVarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + getFloat32(name: string): number } interface FlagSet { /** - * StringToString defines a string flag with specified name, default value, and usage string. - * The return value is the address of a map[string]string variable that stores the value of the flag. - * The value of each argument will not try to be separated by comma + * Float32Var defines a float32 flag with specified name, default value, and usage string. + * The argument p points to a float32 variable in which to store the value of the flag. */ - stringToString(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + float32Var(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. + * Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. */ - stringToStringP(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + float32VarP(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * GetUint return the uint value of a flag with the given name + * Float32 defines a float32 flag with specified name, default value, and usage string. + * The return value is the address of a float32 variable that stores the value of the flag. */ - getUint(name: string): number + float32(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * UintVar defines a uint flag with specified name, default value, and usage string. - * The argument p points to a uint variable in which to store the value of the flag. + * Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. */ - uintVar(p: number, name: string, value: number, usage: string): void + float32P(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. + * GetFloat32Slice return the []float32 value of a flag with the given name */ - uintVarP(p: number, name: string, value: number, usage: string): void + getFloat32Slice(name: string): Array } interface FlagSet { /** - * Uint defines a uint flag with specified name, default value, and usage string. - * The return value is the address of a uint variable that stores the value of the flag. + * Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string. + * The argument p points to a []float32 variable in which to store the value of the flag. */ - uint(name: string, value: number, usage: string): (number | undefined) + float32SliceVar(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. + * Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. */ - uintP(name: string, value: number, usage: string): (number | undefined) + float32SliceVarP(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * GetUint16 return the uint16 value of a flag with the given name + * Float32Slice defines a []float32 flag with specified name, default value, and usage string. + * The return value is the address of a []float32 variable that stores the value of the flag. */ - getUint16(name: string): number + float32Slice(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Uint16Var defines a uint flag with specified name, default value, and usage string. - * The argument p points to a uint variable in which to store the value of the flag. + * Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. */ - uint16Var(p: number, name: string, value: number, usage: string): void + float32SliceP(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. + * GetFloat64 return the float64 value of a flag with the given name */ - uint16VarP(p: number, name: string, value: number, usage: string): void + getFloat64(name: string): number } interface FlagSet { /** - * Uint16 defines a uint flag with specified name, default value, and usage string. - * The return value is the address of a uint variable that stores the value of the flag. + * Float64Var defines a float64 flag with specified name, default value, and usage string. + * The argument p points to a float64 variable in which to store the value of the flag. */ - uint16(name: string, value: number, usage: string): (number | undefined) + float64Var(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. + * Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. */ - uint16P(name: string, value: number, usage: string): (number | undefined) + float64VarP(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * GetUint32 return the uint32 value of a flag with the given name + * Float64 defines a float64 flag with specified name, default value, and usage string. + * The return value is the address of a float64 variable that stores the value of the flag. */ - getUint32(name: string): number + float64(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * Uint32Var defines a uint32 flag with specified name, default value, and usage string. - * The argument p points to a uint32 variable in which to store the value of the flag. + * Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. */ - uint32Var(p: number, name: string, value: number, usage: string): void + float64P(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. + * GetFloat64Slice return the []float64 value of a flag with the given name */ - uint32VarP(p: number, name: string, value: number, usage: string): void + getFloat64Slice(name: string): Array } interface FlagSet { /** - * Uint32 defines a uint32 flag with specified name, default value, and usage string. - * The return value is the address of a uint32 variable that stores the value of the flag. + * Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string. + * The argument p points to a []float64 variable in which to store the value of the flag. */ - uint32(name: string, value: number, usage: string): (number | undefined) + float64SliceVar(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. + * Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. */ - uint32P(name: string, value: number, usage: string): (number | undefined) + float64SliceVarP(p: Array, name: string, value: Array, usage: string): void } interface FlagSet { /** - * GetUint64 return the uint64 value of a flag with the given name + * Float64Slice defines a []float64 flag with specified name, default value, and usage string. + * The return value is the address of a []float64 variable that stores the value of the flag. */ - getUint64(name: string): number + float64Slice(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Uint64Var defines a uint64 flag with specified name, default value, and usage string. - * The argument p points to a uint64 variable in which to store the value of the flag. + * Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. */ - uint64Var(p: number, name: string, value: number, usage: string): void + float64SliceP(name: string, value: Array, usage: string): (Array | undefined) } interface FlagSet { /** - * Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. + * AddGoFlag will add the given *flag.Flag to the pflag.FlagSet */ - uint64VarP(p: number, name: string, value: number, usage: string): void + addGoFlag(goflag: goflag.Flag): void } interface FlagSet { /** - * Uint64 defines a uint64 flag with specified name, default value, and usage string. - * The return value is the address of a uint64 variable that stores the value of the flag. + * AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet */ - uint64(name: string, value: number, usage: string): (number | undefined) + addGoFlagSet(newSet: goflag.FlagSet): void } interface FlagSet { /** - * Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. + * GetInt return the int value of a flag with the given name */ - uint64P(name: string, value: number, usage: string): (number | undefined) + getInt(name: string): number } interface FlagSet { /** - * GetUint8 return the uint8 value of a flag with the given name + * IntVar defines an int flag with specified name, default value, and usage string. + * The argument p points to an int variable in which to store the value of the flag. */ - getUint8(name: string): number + intVar(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * Uint8Var defines a uint8 flag with specified name, default value, and usage string. - * The argument p points to a uint8 variable in which to store the value of the flag. + * IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. */ - uint8Var(p: number, name: string, value: number, usage: string): void + intVarP(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. + * Int defines an int flag with specified name, default value, and usage string. + * The return value is the address of an int variable that stores the value of the flag. */ - uint8VarP(p: number, name: string, value: number, usage: string): void + int(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * Uint8 defines a uint8 flag with specified name, default value, and usage string. - * The return value is the address of a uint8 variable that stores the value of the flag. + * IntP is like Int, but accepts a shorthand letter that can be used after a single dash. */ - uint8(name: string, value: number, usage: string): (number | undefined) + intP(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. + * GetInt16 returns the int16 value of a flag with the given name */ - uint8P(name: string, value: number, usage: string): (number | undefined) + getInt16(name: string): number } interface FlagSet { /** - * GetUintSlice returns the []uint value of a flag with the given name. + * Int16Var defines an int16 flag with specified name, default value, and usage string. + * The argument p points to an int16 variable in which to store the value of the flag. */ - getUintSlice(name: string): Array + int16Var(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. - * The argument p points to a []uint variable in which to store the value of the flag. + * Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. */ - uintSliceVar(p: Array, name: string, value: Array, usage: string): void + int16VarP(p: number, name: string, value: number, usage: string): void } interface FlagSet { /** - * UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. + * Int16 defines an int16 flag with specified name, default value, and usage string. + * The return value is the address of an int16 variable that stores the value of the flag. */ - uintSliceVarP(p: Array, name: string, value: Array, usage: string): void + int16(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * UintSlice defines a []uint flag with specified name, default value, and usage string. - * The return value is the address of a []uint variable that stores the value of the flag. + * Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. */ - uintSlice(name: string, value: Array, usage: string): (Array | undefined) + int16P(name: string, value: number, usage: string): (number | undefined) } interface FlagSet { /** - * UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. + * GetInt32 return the int32 value of a flag with the given name */ - uintSliceP(name: string, value: Array, usage: string): (Array | undefined) - } -} - -/** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. - */ -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag - /** - * FParseErrWhitelist configures Flag parse errors to be ignored - */ - interface FParseErrWhitelist extends flag.ParseErrorsWhitelist{} - /** - * Group Structure to manage groups for commands - */ - interface Group { - id: string - title: string + getInt32(name: string): number } - /** - * ShellCompDirective is a bit map representing the different behaviors the shell - * can be instructed to have once completions have been provided. - */ - interface ShellCompDirective extends Number{} - /** - * CompletionOptions are the options to control shell completion - */ - interface CompletionOptions { + interface FlagSet { /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command + * Int32Var defines an int32 flag with specified name, default value, and usage string. + * The argument p points to an int32 variable in which to store the value of the flag. */ - disableDefaultCmd: boolean + int32Var(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions + * Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. */ - disableNoDescFlag: boolean + int32VarP(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them + * Int32 defines an int32 flag with specified name, default value, and usage string. + * The return value is the address of an int32 variable that stores the value of the flag. */ - disableDescriptions: boolean + int32(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * HiddenDefaultCmd makes the default 'completion' command hidden + * Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. */ - hiddenDefaultCmd: boolean - } -} - -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void + int32P(name: string, value: number, usage: string): (number | undefined) } -} - -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 { + interface FlagSet { /** - * String returns the English name of the month ("January", "February", ...). + * GetInt32Slice return the []int32 value of a flag with the given name */ - string(): string + getInt32Slice(name: string): Array } - /** - * A Weekday specifies a day of the week (Sunday = 0, ...). - */ - interface Weekday extends Number{} - interface Weekday { + interface FlagSet { /** - * String returns the English name of the day ("Sunday", "Monday", ...). + * Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string. + * The argument p points to a []int32 variable in which to store the value of the flag. */ - 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 { + int32SliceVar(p: Array, name: string, value: Array, usage: string): void } - interface Location { + interface FlagSet { /** - * String returns a descriptive name for the time zone information, - * corresponding to the name argument to LoadLocation or FixedZone. + * Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. */ - string(): string + int32SliceVarP(p: Array, name: string, value: Array, usage: string): void } -} - -/** - * Package reflect implements run-time reflection, allowing a program to - * manipulate objects with arbitrary types. The typical use is to take a value - * with static type interface{} and extract its dynamic type information by - * calling TypeOf, which returns a Type. - * - * A call to ValueOf returns a Value representing the run-time data. - * Zero takes a Type and returns a Value representing a zero value - * for that type. - * - * See "The Laws of Reflection" for an introduction to reflection in Go: - * https://golang.org/doc/articles/laws_of_reflection.html - */ -namespace reflect { - /** - * Type is the representation of a Go type. - * - * Not all methods apply to all kinds of types. Restrictions, - * if any, are noted in the documentation for each method. - * Use the Kind method to find out the kind of type before - * calling kind-specific methods. Calling a method - * inappropriate to the kind of type causes a run-time panic. - * - * Type values are comparable, such as with the == operator, - * so they can be used as map keys. - * Two Type values are equal if they represent identical types. - */ - interface Type { + interface FlagSet { /** - * Align returns the alignment in bytes of a value of - * this type when allocated in memory. + * Int32Slice defines a []int32 flag with specified name, default value, and usage string. + * The return value is the address of a []int32 variable that stores the value of the flag. */ - align(): number + int32Slice(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * FieldAlign returns the alignment in bytes of a value of - * this type when used as a field in a struct. + * Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. */ - fieldAlign(): number + int32SliceP(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * Method returns the i'th method in the type's method set. - * It panics if i is not in the range [0, NumMethod()). - * - * For a non-interface type T or *T, the returned Method's Type and Func - * fields describe a function whose first argument is the receiver, - * and only exported methods are accessible. - * - * For an interface type, the returned Method's Type field gives the - * method signature, without a receiver, and the Func field is nil. - * - * Methods are sorted in lexicographic order. + * GetInt64 return the int64 value of a flag with the given name */ - method(_arg0: number): Method + getInt64(name: string): number + } + interface FlagSet { /** - * MethodByName returns the method with that name in the type's - * method set and a boolean indicating if the method was found. - * - * For a non-interface type T or *T, the returned Method's Type and Func - * fields describe a function whose first argument is the receiver. - * - * For an interface type, the returned Method's Type field gives the - * method signature, without a receiver, and the Func field is nil. + * Int64Var defines an int64 flag with specified name, default value, and usage string. + * The argument p points to an int64 variable in which to store the value of the flag. */ - methodByName(_arg0: string): [Method, boolean] + int64Var(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * 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. + * Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. */ - numMethod(): number + int64VarP(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * Name returns the type's name within its package for a defined type. - * For other (non-defined) types it returns the empty string. + * Int64 defines an int64 flag with specified name, default value, and usage string. + * The return value is the address of an int64 variable that stores the value of the flag. */ - name(): string + int64(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * PkgPath returns a defined type's package path, that is, the import path - * that uniquely identifies the package, such as "encoding/base64". - * If the type was predeclared (string, error) or not defined (*T, struct{}, - * []int, or A where A is an alias for a non-defined type), the package path - * will be the empty string. + * Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. */ - pkgPath(): string + int64P(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * Size returns the number of bytes needed to store - * a value of the given type; it is analogous to unsafe.Sizeof. + * GetInt64Slice return the []int64 value of a flag with the given name */ - size(): number + getInt64Slice(name: string): Array + } + interface FlagSet { /** - * String returns a string representation of the type. - * The string representation may use shortened package names - * (e.g., base64 instead of "encoding/base64") and is not - * guaranteed to be unique among types. To test for type identity, - * compare the Types directly. + * Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string. + * The argument p points to a []int64 variable in which to store the value of the flag. */ - string(): string + int64SliceVar(p: Array, name: string, value: Array, usage: string): void + } + interface FlagSet { /** - * Kind returns the specific kind of this type. + * Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. */ - kind(): Kind + int64SliceVarP(p: Array, name: string, value: Array, usage: string): void + } + interface FlagSet { /** - * Implements reports whether the type implements the interface type u. + * Int64Slice defines a []int64 flag with specified name, default value, and usage string. + * The return value is the address of a []int64 variable that stores the value of the flag. */ - implements(u: Type): boolean + int64Slice(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * AssignableTo reports whether a value of the type is assignable to type u. + * Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. */ - assignableTo(u: Type): boolean + int64SliceP(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * ConvertibleTo reports whether a value of the type is convertible to type u. - * Even if ConvertibleTo returns true, the conversion may still panic. - * For example, a slice of type []T is convertible to *[N]T, - * but the conversion will panic if its length is less than N. + * GetInt8 return the int8 value of a flag with the given name */ - convertibleTo(u: Type): boolean + getInt8(name: string): number + } + interface FlagSet { /** - * Comparable reports whether values of this type are comparable. - * Even if Comparable returns true, the comparison may still panic. - * For example, values of interface type are comparable, - * but the comparison will panic if their dynamic type is not comparable. + * Int8Var defines an int8 flag with specified name, default value, and usage string. + * The argument p points to an int8 variable in which to store the value of the flag. */ - comparable(): boolean + int8Var(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * Bits returns the size of the type in bits. - * It panics if the type's Kind is not one of the - * sized or unsized Int, Uint, Float, or Complex kinds. + * Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. */ - bits(): number + int8VarP(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * ChanDir returns a channel type's direction. - * It panics if the type's Kind is not Chan. + * Int8 defines an int8 flag with specified name, default value, and usage string. + * The return value is the address of an int8 variable that stores the value of the flag. */ - chanDir(): ChanDir + int8(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * IsVariadic reports whether a function type's final input parameter - * is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's - * implicit actual type []T. - * - * For concreteness, if t represents func(x int, y ... float64), then - * - * ``` - * t.NumIn() == 2 - * t.In(0) is the reflect.Type for "int" - * t.In(1) is the reflect.Type for "[]float64" - * t.IsVariadic() == true - * ``` - * - * IsVariadic panics if the type's Kind is not Func. + * Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. */ - isVariadic(): boolean + int8P(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * Elem returns a type's element type. - * It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice. + * GetIntSlice return the []int value of a flag with the given name */ - elem(): Type + getIntSlice(name: string): Array + } + interface FlagSet { /** - * Field returns a struct type's i'th field. - * It panics if the type's Kind is not Struct. - * It panics if i is not in the range [0, NumField()). + * IntSliceVar defines a intSlice flag with specified name, default value, and usage string. + * The argument p points to a []int variable in which to store the value of the flag. */ - field(i: number): StructField + intSliceVar(p: Array, name: string, value: Array, usage: string): void + } + interface FlagSet { /** - * FieldByIndex returns the nested field corresponding - * to the index sequence. It is equivalent to calling Field - * successively for each index i. - * It panics if the type's Kind is not Struct. + * IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - fieldByIndex(index: Array): StructField + intSliceVarP(p: Array, name: string, value: Array, usage: string): void + } + interface FlagSet { /** - * FieldByName returns the struct field with the given name - * and a boolean indicating if the field was found. + * IntSlice defines a []int flag with specified name, default value, and usage string. + * The return value is the address of a []int variable that stores the value of the flag. */ - fieldByName(name: string): [StructField, boolean] + intSlice(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * FieldByNameFunc returns the struct field with a name - * that satisfies the match function and a boolean indicating if - * the field was found. - * - * FieldByNameFunc considers the fields in the struct itself - * and then the fields in any embedded structs, in breadth first order, - * stopping at the shallowest nesting depth containing one or more - * fields satisfying the match function. If multiple fields at that depth - * satisfy the match function, they cancel each other - * and FieldByNameFunc returns no match. - * This behavior mirrors Go's handling of name lookup in - * structs containing embedded fields. + * IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. */ - fieldByNameFunc(match: (_arg0: string) => boolean): [StructField, boolean] + intSliceP(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * In returns the type of a function type's i'th input parameter. - * It panics if the type's Kind is not Func. - * It panics if i is not in the range [0, NumIn()). + * GetIP return the net.IP value of a flag with the given name */ - in(i: number): Type + getIP(name: string): net.IP + } + interface FlagSet { /** - * Key returns a map type's key type. - * It panics if the type's Kind is not Map. + * IPVar defines an net.IP flag with specified name, default value, and usage string. + * The argument p points to an net.IP variable in which to store the value of the flag. */ - key(): Type + ipVar(p: net.IP, name: string, value: net.IP, usage: string): void + } + interface FlagSet { /** - * Len returns an array type's length. - * It panics if the type's Kind is not Array. + * IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. */ - len(): number + ipVarP(p: net.IP, name: string, value: net.IP, usage: string): void + } + interface FlagSet { /** - * NumField returns a struct type's field count. - * It panics if the type's Kind is not Struct. + * IP defines an net.IP flag with specified name, default value, and usage string. + * The return value is the address of an net.IP variable that stores the value of the flag. */ - numField(): number + ip(name: string, value: net.IP, usage: string): (net.IP | undefined) + } + interface FlagSet { /** - * NumIn returns a function type's input parameter count. - * It panics if the type's Kind is not Func. + * IPP is like IP, but accepts a shorthand letter that can be used after a single dash. */ - numIn(): number + ipp(name: string, value: net.IP, usage: string): (net.IP | undefined) + } + interface FlagSet { + /** + * GetIPSlice returns the []net.IP value of a flag with the given name + */ + getIPSlice(name: string): Array + } + interface FlagSet { /** - * NumOut returns a function type's output parameter count. - * It panics if the type's Kind is not Func. + * IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. + * The argument p points to a []net.IP variable in which to store the value of the flag. */ - numOut(): number + ipSliceVar(p: Array, name: string, value: Array, usage: string): void + } + interface FlagSet { /** - * Out returns the type of a function type's i'th output parameter. - * It panics if the type's Kind is not Func. - * It panics if i is not in the range [0, NumOut()). + * IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - out(i: number): Type + ipSliceVarP(p: Array, name: string, value: Array, usage: string): void } -} - -/** - * 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 FileInfo describes a file and is returned by Stat. - */ - interface FileInfo { - name(): string // base name of the file - size(): number // length in bytes for regular files; system-dependent for others - mode(): FileMode // file mode bits - modTime(): time.Time // modification time - isDir(): boolean // abbreviation for Mode().IsDir() - sys(): any // underlying data source (can return nil) + interface FlagSet { + /** + * IPSlice defines a []net.IP flag with specified name, default value, and usage string. + * The return value is the address of a []net.IP variable that stores the value of that flag. + */ + ipSlice(name: string, value: Array, usage: string): (Array | undefined) } -} - -/** - * 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 { + interface FlagSet { /** - * Prepare returns a prepared statement, bound to this connection. + * IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. */ - prepare(query: string): Stmt + ipSliceP(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { /** - * 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). + * GetIPv4Mask return the net.IPv4Mask value of a flag with the given name */ - close(): void + getIPv4Mask(name: string): net.IPMask + } + interface FlagSet { /** - * Begin starts and returns a new transaction. - * - * Deprecated: Drivers should implement ConnBeginTx instead (or additionally). + * IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. + * The argument p points to an net.IPMask variable in which to store the value of the flag. */ - begin(): Tx + ipMaskVar(p: net.IPMask, name: string, value: net.IPMask, usage: string): void } -} - -/** - * 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 FlagSet { + /** + * IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. + */ + ipMaskVarP(p: net.IPMask, name: string, value: net.IPMask, usage: string): void } - interface Userinfo { + interface FlagSet { /** - * Username returns the username. + * IPMask defines an net.IPMask flag with specified name, default value, and usage string. + * The return value is the address of an net.IPMask variable that stores the value of the flag. */ - username(): string + ipMask(name: string, value: net.IPMask, usage: string): (net.IPMask | undefined) } - interface Userinfo { + interface FlagSet { /** - * Password returns the password in case it is set, and whether it is set. + * IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. */ - password(): [string, boolean] + ipMaskP(name: string, value: net.IPMask, usage: string): (net.IPMask | undefined) } - interface Userinfo { + interface FlagSet { /** - * String returns the encoded userinfo information in the standard form - * of "username[:password]". + * GetIPNet return the net.IPNet value of a flag with the given name */ - string(): string + getIPNet(name: string): net.IPNet } -} - -/** - * 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 { - /** - * An IP is a single IP address, a slice of bytes. - * Functions in this package accept either 4-byte (IPv4) - * or 16-byte (IPv6) slices as input. - * - * Note that in this documentation, referring to an - * IP address as an IPv4 address or an IPv6 address - * is a semantic property of the address, not just the - * length of the byte slice: a 16-byte slice can still - * be an IPv4 address. - */ - interface IP extends String{} - /** - * An IPMask is a bitmask that can be used to manipulate - * IP addresses for IP addressing and routing. - * - * See type IPNet and func ParseCIDR for details. - */ - interface IPMask extends String{} - /** - * An IPNet represents an IP network. - */ - interface IPNet { - ip: IP // network number - mask: IPMask // network mask + interface FlagSet { + /** + * IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. + * The argument p points to an net.IPNet variable in which to store the value of the flag. + */ + ipNetVar(p: net.IPNet, name: string, value: net.IPNet, usage: string): void } - interface IP { + interface FlagSet { /** - * IsUnspecified reports whether ip is an unspecified address, either - * the IPv4 address "0.0.0.0" or the IPv6 address "::". + * IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. */ - isUnspecified(): boolean + ipNetVarP(p: net.IPNet, name: string, value: net.IPNet, usage: string): void } - interface IP { + interface FlagSet { /** - * IsLoopback reports whether ip is a loopback address. + * IPNet defines an net.IPNet flag with specified name, default value, and usage string. + * The return value is the address of an net.IPNet variable that stores the value of the flag. */ - isLoopback(): boolean + ipNet(name: string, value: net.IPNet, usage: string): (net.IPNet | undefined) } - interface IP { + interface FlagSet { /** - * IsPrivate reports whether ip is a private address, according to - * RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). + * IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. */ - isPrivate(): boolean + ipNetP(name: string, value: net.IPNet, usage: string): (net.IPNet | undefined) } - interface IP { + interface FlagSet { /** - * IsMulticast reports whether ip is a multicast address. + * GetString return the string value of a flag with the given name */ - isMulticast(): boolean + getString(name: string): string } - interface IP { + interface FlagSet { /** - * IsInterfaceLocalMulticast reports whether ip is - * an interface-local multicast address. + * StringVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a string variable in which to store the value of the flag. */ - isInterfaceLocalMulticast(): boolean + stringVar(p: string, name: string, value: string, usage: string): void } - interface IP { + interface FlagSet { /** - * IsLinkLocalMulticast reports whether ip is a link-local - * multicast address. + * StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. */ - isLinkLocalMulticast(): boolean + stringVarP(p: string, name: string, value: string, usage: string): void } - interface IP { + interface FlagSet { /** - * IsLinkLocalUnicast reports whether ip is a link-local - * unicast address. + * String defines a string flag with specified name, default value, and usage string. + * The return value is the address of a string variable that stores the value of the flag. */ - isLinkLocalUnicast(): boolean + string(name: string, value: string, usage: string): (string | undefined) } - interface IP { + interface FlagSet { /** - * IsGlobalUnicast reports whether ip is a global unicast - * address. - * - * The identification of global unicast addresses uses address type - * identification as defined in RFC 1122, RFC 4632 and RFC 4291 with - * the exception of IPv4 directed broadcast addresses. - * It returns true even if ip is in IPv4 private address space or - * local IPv6 unicast address space. + * StringP is like String, but accepts a shorthand letter that can be used after a single dash. */ - isGlobalUnicast(): boolean + stringP(name: string, value: string, usage: string): (string | undefined) } - interface IP { + interface FlagSet { /** - * To4 converts the IPv4 address ip to a 4-byte representation. - * If ip is not an IPv4 address, To4 returns nil. + * GetStringArray return the []string value of a flag with the given name */ - to4(): IP + getStringArray(name: string): Array } - interface IP { + interface FlagSet { /** - * To16 converts the IP address ip to a 16-byte representation. - * If ip is not an IP address (it is the wrong length), To16 returns nil. + * StringArrayVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a []string variable in which to store the values of the multiple flags. + * The value of each argument will not try to be separated by comma. Use a StringSlice for that. */ - to16(): IP + stringArrayVar(p: Array, name: string, value: Array, usage: string): void } - interface IP { + interface FlagSet { /** - * DefaultMask returns the default IP mask for the IP address ip. - * Only IPv4 addresses have default masks; DefaultMask returns - * nil if ip is not a valid IPv4 address. + * StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. */ - defaultMask(): IPMask + stringArrayVarP(p: Array, name: string, value: Array, usage: string): void } - interface IP { + interface FlagSet { /** - * Mask returns the result of masking the IP address ip with mask. + * StringArray defines a string flag with specified name, default value, and usage string. + * The return value is the address of a []string variable that stores the value of the flag. + * The value of each argument will not try to be separated by comma. Use a StringSlice for that. */ - mask(mask: IPMask): IP + stringArray(name: string, value: Array, usage: string): (Array | undefined) } - interface IP { + interface FlagSet { /** - * String returns the string form of the IP address ip. - * It returns one of 4 forms: + * StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. + */ + stringArrayP(name: string, value: Array, usage: string): (Array | undefined) + } + interface FlagSet { + /** + * GetStringSlice return the []string value of a flag with the given name + */ + getStringSlice(name: string): Array + } + interface FlagSet { + /** + * StringSliceVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a []string variable in which to store the value of the flag. + * Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. + * For example: * ``` - * - "", if ip has length 0 - * - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address - * - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address - * - the hexadecimal form of ip, without punctuation, if no other cases apply + * --ss="v1,v2" --ss="v3" + * ``` + * will result in + * ``` + * []string{"v1", "v2", "v3"} * ``` */ - string(): string + stringSliceVar(p: Array, name: string, value: Array, usage: string): void } - interface IP { + interface FlagSet { /** - * MarshalText implements the encoding.TextMarshaler interface. - * The encoding is the same as returned by String, with one exception: - * When len(ip) is zero, it returns an empty slice. + * StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - marshalText(): string + stringSliceVarP(p: Array, name: string, value: Array, usage: string): void } - interface IP { + interface FlagSet { /** - * UnmarshalText implements the encoding.TextUnmarshaler interface. - * The IP address is expected in a form accepted by ParseIP. + * StringSlice defines a string flag with specified name, default value, and usage string. + * The return value is the address of a []string variable that stores the value of the flag. + * Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. + * For example: + * ``` + * --ss="v1,v2" --ss="v3" + * ``` + * will result in + * ``` + * []string{"v1", "v2", "v3"} + * ``` */ - unmarshalText(text: string): void + stringSlice(name: string, value: Array, usage: string): (Array | undefined) } - interface IP { + interface FlagSet { /** - * Equal reports whether ip and x are the same IP address. - * An IPv4 address and that same address in IPv6 form are - * considered to be equal. + * StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. */ - equal(x: IP): boolean + stringSliceP(name: string, value: Array, usage: string): (Array | undefined) } - interface IPMask { + interface FlagSet { /** - * Size returns the number of leading ones and total bits in the mask. - * If the mask is not in the canonical form--ones followed by zeros--then - * Size returns 0, 0. + * GetStringToInt return the map[string]int value of a flag with the given name */ - size(): number + getStringToInt(name: string): _TygojaDict } - interface IPMask { + interface FlagSet { /** - * String returns the hexadecimal form of m, with no punctuation. + * StringToIntVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a map[string]int variable in which to store the values of the multiple flags. + * The value of each argument will not try to be separated by comma */ - string(): string + stringToIntVar(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void } - interface IPNet { + interface FlagSet { /** - * Contains reports whether the network includes ip. + * StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. */ - contains(ip: IP): boolean + stringToIntVarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void } - interface IPNet { + interface FlagSet { /** - * Network returns the address's network name, "ip+net". + * StringToInt defines a string flag with specified name, default value, and usage string. + * The return value is the address of a map[string]int variable that stores the value of the flag. + * The value of each argument will not try to be separated by comma */ - network(): string + stringToInt(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) } - interface IPNet { + interface FlagSet { /** - * String returns the CIDR notation of n like "192.0.2.0/24" - * or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. - * If the mask is not in the canonical form, it returns the - * string which consists of an IP address, followed by a slash - * character and a mask expressed as hexadecimal form with no - * punctuation like "198.51.100.0/c000ff00". + * StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. + */ + stringToIntP(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + } + interface FlagSet { + /** + * GetStringToInt64 return the map[string]int64 value of a flag with the given name + */ + getStringToInt64(name: string): _TygojaDict + } + interface FlagSet { + /** + * StringToInt64Var defines a string flag with specified name, default value, and usage string. + * The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags. + * The value of each argument will not try to be separated by comma + */ + stringToInt64Var(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + } + interface FlagSet { + /** + * StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. + */ + stringToInt64VarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + } + interface FlagSet { + /** + * StringToInt64 defines a string flag with specified name, default value, and usage string. + * The return value is the address of a map[string]int64 variable that stores the value of the flag. + * The value of each argument will not try to be separated by comma + */ + stringToInt64(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + } + interface FlagSet { + /** + * StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. + */ + stringToInt64P(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + } + interface FlagSet { + /** + * GetStringToString return the map[string]string value of a flag with the given name + */ + getStringToString(name: string): _TygojaDict + } + interface FlagSet { + /** + * StringToStringVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a map[string]string variable in which to store the values of the multiple flags. + * The value of each argument will not try to be separated by comma + */ + stringToStringVar(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void + } + interface FlagSet { + /** + * StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. */ - string(): string + stringToStringVarP(p: _TygojaDict, name: string, value: _TygojaDict, usage: string): void } - /** - * Conn is a generic stream-oriented network connection. - * - * Multiple goroutines may invoke methods on a Conn simultaneously. - */ - interface Conn { + interface FlagSet { /** - * 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. + * StringToString defines a string flag with specified name, default value, and usage string. + * The return value is the address of a map[string]string variable that stores the value of the flag. + * The value of each argument will not try to be separated by comma */ - read(b: string): number + stringToString(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + } + interface FlagSet { /** - * 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. + * StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. */ - write(b: string): number + stringToStringP(name: string, value: _TygojaDict, usage: string): (_TygojaDict | undefined) + } + interface FlagSet { /** - * Close closes the connection. - * Any blocked Read or Write operations will be unblocked and return errors. + * GetUint return the uint value of a flag with the given name */ - close(): void + getUint(name: string): number + } + interface FlagSet { /** - * LocalAddr returns the local network address, if known. + * UintVar defines a uint flag with specified name, default value, and usage string. + * The argument p points to a uint variable in which to store the value of the flag. */ - localAddr(): Addr + uintVar(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * RemoteAddr returns the remote network address, if known. + * UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. */ - remoteAddr(): Addr + uintVarP(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * 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. + * Uint defines a uint flag with specified name, default value, and usage string. + * The return value is the address of a uint variable that stores the value of the flag. */ - setDeadline(t: time.Time): void + uint(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * 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. + * UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. */ - setReadDeadline(t: time.Time): void + uintP(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * 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. + * GetUint16 return the uint16 value of a flag with the given name */ - setWriteDeadline(t: time.Time): void + getUint16(name: string): number } -} - -/** - * 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 - interface Certificate { + interface FlagSet { /** - * Verify attempts to verify c by building one or more chains from c to a - * certificate in opts.Roots, using certificates in opts.Intermediates if - * needed. If successful, it returns one or more chains where the first - * element of the chain is c and the last element is from opts.Roots. - * - * If opts.Roots is nil, the platform verifier might be used, and - * verification details might differ from what is described below. If system - * roots are unavailable the returned error will be of type SystemRootsError. - * - * Name constraints in the intermediates will be applied to all names claimed - * in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim - * example.com if an intermediate doesn't permit it, even if example.com is not - * the name being validated. Note that DirectoryName constraints are not - * supported. - * - * Name constraint validation follows the rules from RFC 5280, with the - * addition that DNS name constraints may use the leading period format - * defined for emails and URIs. When a constraint has a leading period - * it indicates that at least one additional label must be prepended to - * the constrained name to be considered valid. - * - * Extended Key Usage values are enforced nested down a chain, so an intermediate - * or root that enumerates EKUs prevents a leaf from asserting an EKU not in that - * list. (While this is not specified, it is common practice in order to limit - * the types of certificates a CA can issue.) - * - * Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, - * and will not be used to build chains. - * - * WARNING: this function doesn't do any revocation checking. + * Uint16Var defines a uint flag with specified name, default value, and usage string. + * The argument p points to a uint variable in which to store the value of the flag. */ - verify(opts: VerifyOptions): Array> + uint16Var(p: number, name: string, value: number, usage: string): void } - interface Certificate { + interface FlagSet { /** - * VerifyHostname returns nil if c is a valid certificate for the named host. - * Otherwise it returns an error describing the mismatch. - * - * IP addresses can be optionally enclosed in square brackets and are checked - * against the IPAddresses field. Other names are checked case insensitively - * against the DNSNames field. If the names are valid hostnames, the certificate - * fields can have a wildcard as the left-most label. - * - * Note that the legacy Common Name field is ignored. + * Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. */ - verifyHostname(h: string): void + uint16VarP(p: number, name: string, value: number, usage: string): void } - /** - * A Certificate represents an X.509 certificate. - */ - interface Certificate { - raw: string // Complete ASN.1 DER content (certificate, signature algorithm and signature). - rawTBSCertificate: string // Certificate part of raw ASN.1 DER content. - rawSubjectPublicKeyInfo: string // DER encoded SubjectPublicKeyInfo. - rawSubject: string // DER encoded Subject - rawIssuer: string // DER encoded Issuer - signature: string - signatureAlgorithm: SignatureAlgorithm - publicKeyAlgorithm: PublicKeyAlgorithm - publicKey: any - version: number - serialNumber?: big.Int - issuer: pkix.Name - subject: pkix.Name - notBefore: time.Time // Validity bounds. - keyUsage: KeyUsage + interface FlagSet { /** - * Extensions contains raw X.509 extensions. When parsing certificates, - * this can be used to extract non-critical extensions that are not - * parsed by this package. When marshaling certificates, the Extensions - * field is ignored, see ExtraExtensions. + * Uint16 defines a uint flag with specified name, default value, and usage string. + * The return value is the address of a uint variable that stores the value of the flag. */ - extensions: Array + uint16(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * ExtraExtensions contains extensions to be copied, raw, into any - * marshaled certificates. Values override any extensions that would - * otherwise be produced based on the other fields. The ExtraExtensions - * field is not populated when parsing certificates, see Extensions. + * Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. */ - extraExtensions: Array + uint16P(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * UnhandledCriticalExtensions contains a list of extension IDs that - * were not (fully) processed when parsing. Verify will fail if this - * slice is non-empty, unless verification is delegated to an OS - * library which understands all the critical extensions. - * - * Users can access these extensions using Extensions and can remove - * elements from this slice if they believe that they have been - * handled. + * GetUint32 return the uint32 value of a flag with the given name */ - unhandledCriticalExtensions: Array - extKeyUsage: Array // Sequence of extended key usages. - unknownExtKeyUsage: Array // Encountered extended key usages unknown to this package. + getUint32(name: string): number + } + interface FlagSet { /** - * BasicConstraintsValid indicates whether IsCA, MaxPathLen, - * and MaxPathLenZero are valid. + * Uint32Var defines a uint32 flag with specified name, default value, and usage string. + * The argument p points to a uint32 variable in which to store the value of the flag. */ - basicConstraintsValid: boolean - isCA: boolean + uint32Var(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * MaxPathLen and MaxPathLenZero indicate the presence and - * value of the BasicConstraints' "pathLenConstraint". - * - * When parsing a certificate, a positive non-zero MaxPathLen - * means that the field was specified, -1 means it was unset, - * and MaxPathLenZero being true mean that the field was - * explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false - * should be treated equivalent to -1 (unset). - * - * When generating a certificate, an unset pathLenConstraint - * can be requested with either MaxPathLen == -1 or using the - * zero value for both MaxPathLen and MaxPathLenZero. + * Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. */ - maxPathLen: number + uint32VarP(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * MaxPathLenZero indicates that BasicConstraintsValid==true - * and MaxPathLen==0 should be interpreted as an actual - * maximum path length of zero. Otherwise, that combination is - * interpreted as MaxPathLen not being set. + * Uint32 defines a uint32 flag with specified name, default value, and usage string. + * The return value is the address of a uint32 variable that stores the value of the flag. */ - maxPathLenZero: boolean - subjectKeyId: string - authorityKeyId: string + uint32(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * RFC 5280, 4.2.2.1 (Authority Information Access) + * Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. */ - ocspServer: Array - issuingCertificateURL: Array + uint32P(name: string, value: number, usage: string): (number | undefined) + } + interface FlagSet { /** - * Subject Alternate Name values. (Note that these values may not be valid - * if invalid values were contained within a parsed certificate. For - * example, an element of DNSNames may not be a valid DNS domain name.) + * GetUint64 return the uint64 value of a flag with the given name */ - dnsNames: Array - emailAddresses: Array - ipAddresses: Array - urIs: Array<(url.URL | undefined)> + getUint64(name: string): number + } + interface FlagSet { /** - * Name constraints + * Uint64Var defines a uint64 flag with specified name, default value, and usage string. + * The argument p points to a uint64 variable in which to store the value of the flag. */ - permittedDNSDomainsCritical: boolean // if true then the name constraints are marked critical. - permittedDNSDomains: Array - excludedDNSDomains: Array - permittedIPRanges: Array<(net.IPNet | undefined)> - excludedIPRanges: Array<(net.IPNet | undefined)> - permittedEmailAddresses: Array - excludedEmailAddresses: Array - permittedURIDomains: Array - excludedURIDomains: Array + uint64Var(p: number, name: string, value: number, usage: string): void + } + interface FlagSet { /** - * CRL Distribution Points + * Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. */ - crlDistributionPoints: Array - policyIdentifiers: Array + uint64VarP(p: number, name: string, value: number, usage: string): void } - interface Certificate { - equal(other: Certificate): boolean + interface FlagSet { + /** + * Uint64 defines a uint64 flag with specified name, default value, and usage string. + * The return value is the address of a uint64 variable that stores the value of the flag. + */ + uint64(name: string, value: number, usage: string): (number | undefined) } - interface Certificate { + interface FlagSet { /** - * CheckSignatureFrom verifies that the signature on c is a valid signature - * from parent. SHA1WithRSA and ECDSAWithSHA1 signatures are not supported. + * Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. */ - checkSignatureFrom(parent: Certificate): void + uint64P(name: string, value: number, usage: string): (number | undefined) } - interface Certificate { + interface FlagSet { /** - * CheckSignature verifies that signature is a valid signature over signed from - * c's public key. + * GetUint8 return the uint8 value of a flag with the given name */ - checkSignature(algo: SignatureAlgorithm, signed: string): void + getUint8(name: string): number } - interface Certificate { + interface FlagSet { /** - * CheckCRLSignature checks that the signature in crl is from c. - * - * Deprecated: Use RevocationList.CheckSignatureFrom instead. + * Uint8Var defines a uint8 flag with specified name, default value, and usage string. + * The argument p points to a uint8 variable in which to store the value of the flag. */ - checkCRLSignature(crl: pkix.CertificateList): void + uint8Var(p: number, name: string, value: number, usage: string): void } - interface Certificate { + interface FlagSet { /** - * 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. - * To generate a standards compliant CRL, use CreateRevocationList instead. + * Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. */ - createCRL(rand: io.Reader, priv: any, revokedCerts: Array, now: time.Time): string + uint8VarP(p: number, name: string, value: number, usage: 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 - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { - /** - * ReadWriter stores pointers to a Reader and a Writer. - * It implements io.ReadWriter. - */ - type _subCXrjQ = Reader&Writer - interface ReadWriter extends _subCXrjQ { + interface FlagSet { + /** + * Uint8 defines a uint8 flag with specified name, default value, and usage string. + * The return value is the address of a uint8 variable that stores the value of the flag. + */ + uint8(name: string, value: number, usage: string): (number | undefined) } -} - -/** - * 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 Part represents a single part in a multipart body. - */ - interface Part { + interface FlagSet { /** - * The headers of the body, if any, with the keys canonicalized - * in the same fashion that the Go http.Request headers are. - * For example, "foo-bar" changes case to "Foo-Bar" + * Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. */ - header: textproto.MIMEHeader + uint8P(name: string, value: number, usage: string): (number | undefined) } - interface Part { + interface FlagSet { /** - * FormName returns the name parameter if p has a Content-Disposition - * of type "form-data". Otherwise it returns the empty string. + * GetUintSlice returns the []uint value of a flag with the given name. */ - formName(): string + getUintSlice(name: string): Array } - interface Part { + interface FlagSet { /** - * FileName returns the filename parameter of the Part's Content-Disposition - * header. If not empty, the filename is passed through filepath.Base (which is - * platform dependent) before being returned. + * UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. + * The argument p points to a []uint variable in which to store the value of the flag. */ - fileName(): string + uintSliceVar(p: Array, name: string, value: Array, usage: string): void } - interface Part { + interface FlagSet { /** - * Read reads the body of a part, after its headers and before the - * next part (if any) begins. + * UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - read(d: string): number + uintSliceVarP(p: Array, name: string, value: Array, usage: string): void } - interface Part { - close(): void + interface FlagSet { + /** + * UintSlice defines a []uint flag with specified name, default value, and usage string. + * The return value is the address of a []uint variable that stores the value of the flag. + */ + uintSlice(name: string, value: Array, usage: string): (Array | 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. + interface FlagSet { + /** + * UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. + */ + uintSliceP(name: string, value: Array, usage: string): (Array | undefined) + } +} + +/** + * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. + * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. */ -namespace http { +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag /** - * RoundTripper is an interface representing the ability to execute a - * single HTTP transaction, obtaining the Response for a given Request. - * - * A RoundTripper must be safe for concurrent use by multiple - * goroutines. + * FParseErrWhitelist configures Flag parse errors to be ignored */ - interface RoundTripper { - /** - * RoundTrip executes a single HTTP transaction, returning - * a Response for the provided Request. - * - * RoundTrip should not attempt to interpret the response. In - * particular, RoundTrip must return err == nil if it obtained - * a response, regardless of the response's HTTP status code. - * A non-nil err should be reserved for failure to obtain a - * response. Similarly, RoundTrip should not attempt to - * handle higher-level protocol details such as redirects, - * authentication, or cookies. - * - * RoundTrip should not modify the request, except for - * consuming and closing the Request's Body. RoundTrip may - * read fields of the request in a separate goroutine. Callers - * should not mutate or reuse the request until the Response's - * Body has been closed. - * - * RoundTrip must always close the body, including on errors, - * but depending on the implementation may do so in a separate - * goroutine even after RoundTrip returns. This means that - * callers wanting to reuse the body for subsequent requests - * must arrange to wait for the Close call before doing so. - * - * The Request's URL and Header fields must be initialized. - */ - roundTrip(_arg0: Request): (Response | undefined) + interface FParseErrWhitelist extends flag.ParseErrorsWhitelist{} + /** + * Group Structure to manage groups for commands + */ + interface Group { + id: string + title: string } /** - * SameSite allows a server to define a cookie attribute making it impossible for - * the browser to send this cookie along with cross-site requests. The main - * goal is to mitigate the risk of cross-origin information leakage, and provide - * some protection against cross-site request forgery attacks. - * - * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. + * ShellCompDirective is a bit map representing the different behaviors the shell + * can be instructed to have once completions have been provided. */ - interface SameSite extends Number{} - // @ts-ignore - import mathrand = rand + interface ShellCompDirective extends Number{} /** - * A CookieJar manages storage and use of cookies in HTTP requests. - * - * Implementations of CookieJar must be safe for concurrent use by multiple - * goroutines. - * - * The net/http/cookiejar package provides a CookieJar implementation. + * CompletionOptions are the options to control shell completion */ - interface CookieJar { + interface CompletionOptions { /** - * SetCookies handles the receipt of the cookies in a reply for the - * given URL. It may or may not choose to save the cookies, depending - * on the jar's policy and implementation. + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command */ - setCookies(u: url.URL, cookies: Array<(Cookie | undefined)>): void + disableDefaultCmd: boolean /** - * Cookies returns the cookies to send in a request for the given URL. - * It is up to the implementation to honor the standard cookie use - * restrictions such as in RFC 6265. + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions */ - cookies(u: url.URL): Array<(Cookie | undefined)> + disableNoDescFlag: boolean + /** + * DisableDescriptions turns off all completion descriptions for shells + * that support them + */ + disableDescriptions: boolean + /** + * HiddenDefaultCmd makes the default 'completion' command hidden + */ + hiddenDefaultCmd: boolean } - // @ts-ignore - import urlpkg = url +} + +/** + * Package reflect implements run-time reflection, allowing a program to + * manipulate objects with arbitrary types. The typical use is to take a value + * with static type interface{} and extract its dynamic type information by + * calling TypeOf, which returns a Type. + * + * A call to ValueOf returns a Value representing the run-time data. + * Zero takes a Type and returns a Value representing a zero value + * for that type. + * + * See "The Laws of Reflection" for an introduction to reflection in Go: + * https://golang.org/doc/articles/laws_of_reflection.html + */ +namespace reflect { /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. + * Type is the representation of a Go type. + * + * Not all methods apply to all kinds of types. Restrictions, + * if any, are noted in the documentation for each method. + * Use the Kind method to find out the kind of type before + * calling kind-specific methods. Calling a method + * inappropriate to the kind of type causes a run-time panic. + * + * Type values are comparable, such as with the == operator, + * so they can be used as map keys. + * Two Type values are equal if they represent identical types. */ - interface Server { + interface Type { /** - * 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. + * Align returns the alignment in bytes of a value of + * this type when allocated in memory. */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil + align(): number /** - * 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. + * FieldAlign returns the alignment in bytes of a value of + * this type when used as a field in a struct. */ - tlsConfig?: tls.Config + fieldAlign(): number /** - * ReadTimeout is the maximum duration for reading the entire - * request, including the body. A zero or negative value means - * there will be no timeout. + * Method returns the i'th method in the type's method set. + * It panics if i is not in the range [0, NumMethod()). * - * 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. + * For a non-interface type T or *T, the returned Method's Type and Func + * fields describe a function whose first argument is the receiver, + * and only exported methods are accessible. + * + * For an interface type, the returned Method's Type field gives the + * method signature, without a receiver, and the Func field is nil. + * + * Methods are sorted in lexicographic order. */ - readTimeout: time.Duration + method(_arg0: number): Method /** - * 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. + * MethodByName returns the method with that name in the type's + * method set and a boolean indicating if the method was found. + * + * For a non-interface type T or *T, the returned Method's Type and Func + * fields describe a function whose first argument is the receiver. + * + * For an interface type, the returned Method's Type field gives the + * method signature, without a receiver, and the Func field is nil. */ - readHeaderTimeout: time.Duration + methodByName(_arg0: string): [Method, boolean] /** - * 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. + * NumMethod returns the number of methods accessible using Method. + * + * Note that NumMethod counts unexported methods only for interface types. + */ + numMethod(): number + /** + * Name returns the type's name within its package for a defined type. + * For other (non-defined) types it returns the empty string. + */ + name(): string + /** + * PkgPath returns a defined type's package path, that is, the import path + * that uniquely identifies the package, such as "encoding/base64". + * If the type was predeclared (string, error) or not defined (*T, struct{}, + * []int, or A where A is an alias for a non-defined type), the package path + * will be the empty string. + */ + pkgPath(): string + /** + * Size returns the number of bytes needed to store + * a value of the given type; it is analogous to unsafe.Sizeof. + */ + size(): number + /** + * String returns a string representation of the type. + * The string representation may use shortened package names + * (e.g., base64 instead of "encoding/base64") and is not + * guaranteed to be unique among types. To test for type identity, + * compare the Types directly. + */ + string(): string + /** + * Kind returns the specific kind of this type. + */ + kind(): Kind + /** + * Implements reports whether the type implements the interface type u. + */ + implements(u: Type): boolean + /** + * AssignableTo reports whether a value of the type is assignable to type u. + */ + assignableTo(u: Type): boolean + /** + * ConvertibleTo reports whether a value of the type is convertible to type u. + * Even if ConvertibleTo returns true, the conversion may still panic. + * For example, a slice of type []T is convertible to *[N]T, + * but the conversion will panic if its length is less than N. + */ + convertibleTo(u: Type): boolean + /** + * Comparable reports whether values of this type are comparable. + * Even if Comparable returns true, the comparison may still panic. + * For example, values of interface type are comparable, + * but the comparison will panic if their dynamic type is not comparable. + */ + comparable(): boolean + /** + * Bits returns the size of the type in bits. + * It panics if the type's Kind is not one of the + * sized or unsized Int, Uint, Float, or Complex kinds. + */ + bits(): number + /** + * ChanDir returns a channel type's direction. + * It panics if the type's Kind is not Chan. + */ + chanDir(): ChanDir + /** + * IsVariadic reports whether a function type's final input parameter + * is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's + * implicit actual type []T. + * + * For concreteness, if t represents func(x int, y ... float64), then + * + * ``` + * t.NumIn() == 2 + * t.In(0) is the reflect.Type for "int" + * t.In(1) is the reflect.Type for "[]float64" + * t.IsVariadic() == true + * ``` + * + * IsVariadic panics if the type's Kind is not Func. */ - writeTimeout: time.Duration + isVariadic(): boolean /** - * 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. + * Elem returns a type's element type. + * It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice. */ - idleTimeout: time.Duration + elem(): Type /** - * 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. + * Field returns a struct type's i'th field. + * It panics if the type's Kind is not Struct. + * It panics if i is not in the range [0, NumField()). */ - maxHeaderBytes: number + field(i: number): StructField /** - * 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. + * FieldByIndex returns the nested field corresponding + * to the index sequence. It is equivalent to calling Field + * successively for each index i. + * It panics if the type's Kind is not Struct. */ - tlsNextProto: _TygojaDict + fieldByIndex(index: Array): StructField /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. + * FieldByName returns the struct field with the given name + * and a boolean indicating if the field was found. */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void + fieldByName(name: string): [StructField, boolean] /** - * 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. + * FieldByNameFunc returns the struct field with a name + * that satisfies the match function and a boolean indicating if + * the field was found. + * + * FieldByNameFunc considers the fields in the struct itself + * and then the fields in any embedded structs, in breadth first order, + * stopping at the shallowest nesting depth containing one or more + * fields satisfying the match function. If multiple fields at that depth + * satisfy the match function, they cancel each other + * and FieldByNameFunc returns no match. + * This behavior mirrors Go's handling of name lookup in + * structs containing embedded fields. */ - errorLog?: log.Logger + fieldByNameFunc(match: (_arg0: string) => boolean): [StructField, boolean] /** - * 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. + * In returns the type of a function type's i'th input parameter. + * It panics if the type's Kind is not Func. + * It panics if i is not in the range [0, NumIn()). */ - baseContext: (_arg0: net.Listener) => context.Context + in(i: number): Type /** - * 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. + * Key returns a map type's key type. + * It panics if the type's Kind is not Map. */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context - } - interface Server { + key(): Type /** - * 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). + * Len returns an array type's length. + * It panics if the type's Kind is not Array. */ - close(): void - } - interface Server { + len(): number /** - * 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. + * NumField returns a struct type's field count. + * It panics if the type's Kind is not Struct. */ - shutdown(ctx: context.Context): void - } - interface Server { + numField(): number /** - * 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. + * NumIn returns a function type's input parameter count. + * It panics if the type's Kind is not Func. */ - registerOnShutdown(f: () => void): void - } - interface Server { + numIn(): number /** - * 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. + * NumOut returns a function type's output parameter count. + * It panics if the type's Kind is not Func. */ - listenAndServe(): void - } - interface Server { + numOut(): number /** - * 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. + * Out returns the type of a function type's i'th output parameter. + * It panics if the type's Kind is not Func. + * It panics if i is not in the range [0, NumOut()). */ - serve(l: net.Listener): void + out(i: number): Type } - interface Server { +} + +/** + * 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 { /** - * 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. + * String returns the English name of the month ("January", "February", ...). */ - serveTLS(l: net.Listener, certFile: string): void + string(): string } - interface Server { + /** + * A Weekday specifies a day of the week (Sunday = 0, ...). + */ + interface Weekday extends Number{} + interface Weekday { /** - * 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. + * String returns the English name of the day ("Sunday", "Monday", ...). */ - setKeepAlivesEnabled(v: boolean): void + string(): string } - interface Server { + /** + * 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 { /** - * 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. + * String returns a descriptive name for the time zone information, + * corresponding to the name argument to LoadLocation or FixedZone. */ - listenAndServeTLS(certFile: string): void + string(): string } } -namespace mailer { +/** + * 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 generic email message struct. + * A FileInfo describes a file and is returned by Stat. */ - interface Message { - from: mail.Address - to: Array - bcc: Array - cc: Array - subject: string - html: string - text: string - headers: _TygojaDict - attachments: _TygojaDict + interface FileInfo { + name(): string // base name of the file + size(): number // length in bytes for regular files; system-dependent for others + mode(): FileMode // file mode bits + modTime(): time.Time // modification time + isDir(): boolean // abbreviation for Mode().IsDir() + sys(): any // underlying data source (can return nil) } } /** - * Package echo implements high performance, minimalist Go web framework. + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { + /** + * ReadWriter stores pointers to a Reader and a Writer. + * It implements io.ReadWriter. + */ + type _subqqWpg = Reader&Writer + interface ReadWriter extends _subqqWpg { + } +} + +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. * - * Example: + * 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: * * ``` - * package main + * 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') + * // ... + * ``` * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) + * The Listen function creates servers: * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` * - * func main() { - * // Echo instance - * e := echo.New() + * Name Resolution * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. * - * // Routes - * e.GET("/", hello) + * 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. * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } + * 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 * ``` * - * Learn more at https://echo.labstack.com + * 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 echo { - // @ts-ignore - import stdContext = context - /** - * Route contains information to adding/registering new route with the router. - * Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields. - */ - interface Route { - method: string - path: string - handler: HandlerFunc - middlewares: Array - name: string - } - interface Route { - /** - * ToRouteInfo converts Route to RouteInfo - */ - toRouteInfo(params: Array): RouteInfo - } - interface Route { - /** - * ToRoute returns Route which Router uses to register the method handler for path. - */ - toRoute(): Route - } - interface Route { - /** - * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. - */ - forGroup(pathPrefix: string, middlewares: Array): Routable - } +namespace net { /** - * RoutableContext is additional interface that structures implementing Context must implement. Methods inside this - * interface are meant for request routing purposes and should not be used in middlewares. - */ - interface RoutableContext { - /** - * Request returns `*http.Request`. - */ - request(): (http.Request | undefined) - /** - * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. - */ - rawPathParams(): (PathParams | undefined) - /** - * SetRawPathParams replaces any existing param values with new values for this context lifetime (request). - * Do not set any other value than what you got from RawPathParams as allocation of PathParams is handled by Context. - */ - setRawPathParams(params: PathParams): void - /** - * SetPath sets the registered path for the handler. - */ - setPath(p: string): void - /** - * SetRouteInfo sets the route info of this request to the context. - */ - setRouteInfo(ri: RouteInfo): void - /** - * Set saves data in the context. Allows router to store arbitrary (that only router has access to) data in context - * for later use in middlewares/handler. - */ - set(key: string, val: { - }): void - } + * An IP is a single IP address, a slice of bytes. + * Functions in this package accept either 4-byte (IPv4) + * or 16-byte (IPv6) slices as input. + * + * Note that in this documentation, referring to an + * IP address as an IPv4 address or an IPv6 address + * is a semantic property of the address, not just the + * length of the byte slice: a 16-byte slice can still + * be an IPv4 address. + */ + interface IP extends String{} /** - * PathParam is tuple pf path parameter name and its value in request path + * An IPMask is a bitmask that can be used to manipulate + * IP addresses for IP addressing and routing. + * + * See type IPNet and func ParseCIDR for details. */ - interface PathParam { - name: string - value: string - } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { + interface IPMask extends String{} /** - * JsonRaw defines a json value type that is safe for db read/write. + * An IPNet represents an IP network. */ - interface JsonRaw extends String{} - interface JsonRaw { + interface IPNet { + ip: IP // network number + mask: IPMask // network mask + } + interface IP { /** - * String returns the current JsonRaw instance as a json encoded string. + * IsUnspecified reports whether ip is an unspecified address, either + * the IPv4 address "0.0.0.0" or the IPv6 address "::". */ - string(): string + isUnspecified(): boolean } - interface JsonRaw { + interface IP { /** - * MarshalJSON implements the [json.Marshaler] interface. + * IsLoopback reports whether ip is a loopback address. */ - marshalJSON(): string + isLoopback(): boolean } - interface JsonRaw { + interface IP { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * IsPrivate reports whether ip is a private address, according to + * RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). */ - unmarshalJSON(b: string): void + isPrivate(): boolean } - interface JsonRaw { + interface IP { /** - * Value implements the [driver.Valuer] interface. + * IsMulticast reports whether ip is a multicast address. */ - value(): driver.Value + isMulticast(): boolean } - interface JsonRaw { + interface IP { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. + * IsInterfaceLocalMulticast reports whether ip is + * an interface-local multicast address. */ - 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 - interface EmailTemplate { - body: string - subject: string - actionUrl: string + isInterfaceLocalMulticast(): boolean } - interface EmailTemplate { + interface IP { /** - * Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface. + * IsLinkLocalMulticast reports whether ip is a link-local + * multicast address. */ - validate(): void + isLinkLocalMulticast(): boolean } - interface EmailTemplate { + interface IP { /** - * Resolve replaces the placeholder parameters in the current email - * template and returns its components as ready-to-use strings. + * IsLinkLocalUnicast reports whether ip is a link-local + * unicast address. */ - resolve(appName: string, appUrl: string): string + isLinkLocalUnicast(): boolean } -} - -/** - * Package autocert provides automatic access to certificates from Let's Encrypt - * and any other ACME-based CA. - * - * This package is a work in progress and makes no API stability promises. - */ -namespace autocert { - // @ts-ignore - import mathrand = rand - /** - * Manager is a stateful certificate manager built on top of acme.Client. - * It obtains and refreshes certificates automatically using "tls-alpn-01" - * or "http-01" challenge types, as well as providing them to a TLS server - * via tls.Config. - * - * You must specify a cache implementation, such as DirCache, - * to reuse obtained certificates across program restarts. - * Otherwise your server is very likely to exceed the certificate - * issuer's request rate limits. - */ - interface Manager { + interface IP { /** - * Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). - * The registration may require the caller to agree to the CA's TOS. - * If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report - * whether the caller agrees to the terms. + * IsGlobalUnicast reports whether ip is a global unicast + * address. * - * To always accept the terms, the callers can use AcceptTOS. + * The identification of global unicast addresses uses address type + * identification as defined in RFC 1122, RFC 4632 and RFC 4291 with + * the exception of IPv4 directed broadcast addresses. + * It returns true even if ip is in IPv4 private address space or + * local IPv6 unicast address space. */ - prompt: (tosURL: string) => boolean + isGlobalUnicast(): boolean + } + interface IP { /** - * Cache optionally stores and retrieves previously-obtained certificates - * and other state. If nil, certs will only be cached for the lifetime of - * the Manager. Multiple Managers can share the same Cache. - * - * Using a persistent Cache, such as DirCache, is strongly recommended. + * To4 converts the IPv4 address ip to a 4-byte representation. + * If ip is not an IPv4 address, To4 returns nil. */ - cache: Cache + to4(): IP + } + interface IP { /** - * HostPolicy controls which domains the Manager will attempt - * to retrieve new certificates for. It does not affect cached certs. - * - * If non-nil, HostPolicy is called before requesting a new cert. - * If nil, all hosts are currently allowed. This is not recommended, - * as it opens a potential attack where clients connect to a server - * by IP address and pretend to be asking for an incorrect host name. - * Manager will attempt to obtain a certificate for that host, incorrectly, - * eventually reaching the CA's rate limit for certificate requests - * and making it impossible to obtain actual certificates. - * - * See GetCertificate for more details. + * To16 converts the IP address ip to a 16-byte representation. + * If ip is not an IP address (it is the wrong length), To16 returns nil. */ - hostPolicy: HostPolicy + to16(): IP + } + interface IP { /** - * RenewBefore optionally specifies how early certificates should - * be renewed before they expire. - * - * If zero, they're renewed 30 days before expiration. + * DefaultMask returns the default IP mask for the IP address ip. + * Only IPv4 addresses have default masks; DefaultMask returns + * nil if ip is not a valid IPv4 address. */ - renewBefore: time.Duration + defaultMask(): IPMask + } + interface IP { /** - * Client is used to perform low-level operations, such as account registration - * and requesting new certificates. - * - * If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory - * as the directory endpoint. - * If the Client.Key is nil, a new ECDSA P-256 key is generated and, - * if Cache is not nil, stored in cache. - * - * Mutating the field after the first call of GetCertificate method will have no effect. + * Mask returns the result of masking the IP address ip with mask. */ - client?: acme.Client + mask(mask: IPMask): IP + } + interface IP { /** - * Email optionally specifies a contact email address. - * This is used by CAs, such as Let's Encrypt, to notify about problems - * with issued certificates. - * - * If the Client's account key is already registered, Email is not used. + * String returns the string form of the IP address ip. + * It returns one of 4 forms: + * ``` + * - "", if ip has length 0 + * - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address + * - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address + * - the hexadecimal form of ip, without punctuation, if no other cases apply + * ``` */ - email: string + string(): string + } + interface IP { /** - * ForceRSA used to make the Manager generate RSA certificates. It is now ignored. - * - * Deprecated: the Manager will request the correct type of certificate based - * on what each client supports. + * MarshalText implements the encoding.TextMarshaler interface. + * The encoding is the same as returned by String, with one exception: + * When len(ip) is zero, it returns an empty slice. */ - forceRSA: boolean + marshalText(): string + } + interface IP { /** - * ExtraExtensions are used when generating a new CSR (Certificate Request), - * thus allowing customization of the resulting certificate. - * For instance, TLS Feature Extension (RFC 7633) can be used - * to prevent an OCSP downgrade attack. - * - * The field value is passed to crypto/x509.CreateCertificateRequest - * in the template's ExtraExtensions field as is. + * UnmarshalText implements the encoding.TextUnmarshaler interface. + * The IP address is expected in a form accepted by ParseIP. */ - extraExtensions: Array + unmarshalText(text: string): void + } + interface IP { /** - * ExternalAccountBinding optionally represents an arbitrary binding to an - * account of the CA to which the ACME server is tied. - * See RFC 8555, Section 7.3.4 for more details. + * Equal reports whether ip and x are the same IP address. + * An IPv4 address and that same address in IPv6 form are + * considered to be equal. + */ + equal(x: IP): boolean + } + interface IPMask { + /** + * Size returns the number of leading ones and total bits in the mask. + * If the mask is not in the canonical form--ones followed by zeros--then + * Size returns 0, 0. */ - externalAccountBinding?: acme.ExternalAccountBinding + size(): number } - interface Manager { + interface IPMask { /** - * TLSConfig creates a new TLS config suitable for net/http.Server servers, - * supporting HTTP/2 and the tls-alpn-01 ACME challenge type. + * String returns the hexadecimal form of m, with no punctuation. */ - tlsConfig(): (tls.Config | undefined) + string(): string } - interface Manager { + interface IPNet { /** - * GetCertificate implements the tls.Config.GetCertificate hook. - * It provides a TLS certificate for hello.ServerName host, including answering - * tls-alpn-01 challenges. - * All other fields of hello are ignored. - * - * If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting - * a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. - * The error is propagated back to the caller of GetCertificate and is user-visible. - * This does not affect cached certs. See HostPolicy field description for more details. - * - * If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will - * also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. + * Contains reports whether the network includes ip. */ - getCertificate(hello: tls.ClientHelloInfo): (tls.Certificate | undefined) + contains(ip: IP): boolean } - interface Manager { + interface IPNet { /** - * HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. - * It returns an http.Handler that responds to the challenges and must be - * running on port 80. If it receives a request that is not an ACME challenge, - * it delegates the request to the optional fallback handler. - * - * If fallback is nil, the returned handler redirects all GET and HEAD requests - * to the default TLS port 443 with 302 Found status code, preserving the original - * request path and query. It responds with 400 Bad Request to all other HTTP methods. - * The fallback is not protected by the optional HostPolicy. - * - * Because the fallback handler is run with unencrypted port 80 requests, - * the fallback should not serve TLS-only requests. - * - * If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" - * challenge for domain verification. + * Network returns the address's network name, "ip+net". */ - httpHandler(fallback: http.Handler): http.Handler + network(): string } - interface Manager { + interface IPNet { /** - * Listener listens on the standard TLS port (443) on all interfaces - * and returns a net.Listener returning *tls.Conn connections. - * - * The returned listener uses a *tls.Config that enables HTTP/2, and - * should only be used with servers that support HTTP/2. - * - * The returned Listener also enables TCP keep-alives on the accepted - * connections. The returned *tls.Conn are returned before their TLS - * handshake has completed. - * - * Unlike NewListener, it is the caller's responsibility to initialize - * the Manager m's Prompt, Cache, HostPolicy, and other desired options. + * String returns the CIDR notation of n like "192.0.2.0/24" + * or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. + * If the mask is not in the canonical form, it returns the + * string which consists of an IP address, followed by a slash + * character and a mask expressed as hexadecimal form with no + * punctuation like "198.51.100.0/c000ff00". */ - listener(): net.Listener + string(): string } -} - -namespace hook { /** - * Handler defines a hook handler function. + * 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 Handler {(e: T): void } + 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 { /** - * wrapped local Hook embedded struct to limit the public API surface. + * 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. */ - type _subkuwfu = Hook - interface mainHook extends _subkuwfu { + interface Userinfo { + } + interface Userinfo { + /** + * Username returns the username. + */ + username(): string + } + interface Userinfo { + /** + * Password returns the password in case it is set, and whether it is set. + */ + password(): [string, boolean] + } + interface Userinfo { + /** + * String returns the encoded userinfo information in the standard form + * of "username[:password]". + */ + string(): string } } /** - * Package 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. + * 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. */ -namespace flag { +/** + * Package x509 parses X.509-encoded keys and certificates. + */ +namespace x509 { /** - * A FlagSet represents a set of defined flags. The zero value of a FlagSet - * has no name and has ContinueOnError error handling. - * - * Flag names must be unique within a FlagSet. An attempt to define a flag whose - * name is already in use will cause a panic. + * CertPool is a set of certificates. */ - interface FlagSet { + 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 { + /** + * Verify attempts to verify c by building one or more chains from c to a + * certificate in opts.Roots, using certificates in opts.Intermediates if + * needed. If successful, it returns one or more chains where the first + * element of the chain is c and the last element is from opts.Roots. + * + * If opts.Roots is nil, the platform verifier might be used, and + * verification details might differ from what is described below. If system + * roots are unavailable the returned error will be of type SystemRootsError. + * + * Name constraints in the intermediates will be applied to all names claimed + * in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim + * example.com if an intermediate doesn't permit it, even if example.com is not + * the name being validated. Note that DirectoryName constraints are not + * supported. + * + * Name constraint validation follows the rules from RFC 5280, with the + * addition that DNS name constraints may use the leading period format + * defined for emails and URIs. When a constraint has a leading period + * it indicates that at least one additional label must be prepended to + * the constrained name to be considered valid. + * + * Extended Key Usage values are enforced nested down a chain, so an intermediate + * or root that enumerates EKUs prevents a leaf from asserting an EKU not in that + * list. (While this is not specified, it is common practice in order to limit + * the types of certificates a CA can issue.) + * + * Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, + * and will not be used to build chains. + * + * WARNING: this function doesn't do any revocation checking. + */ + verify(opts: VerifyOptions): Array> + } + interface Certificate { /** - * Usage is the function called when an error occurs while parsing flags. - * The field is a function (not a method) that may be changed to point to - * a custom error handler. What happens after Usage is called depends - * on the ErrorHandling setting; for the command line, this defaults - * to ExitOnError, which exits the program after calling Usage. + * VerifyHostname returns nil if c is a valid certificate for the named host. + * Otherwise it returns an error describing the mismatch. + * + * IP addresses can be optionally enclosed in square brackets and are checked + * against the IPAddresses field. Other names are checked case insensitively + * against the DNSNames field. If the names are valid hostnames, the certificate + * fields can have a wildcard as the left-most label. + * + * Note that the legacy Common Name field is ignored. */ - usage: () => void + verifyHostname(h: string): void } /** - * A Flag represents the state of a flag. + * A Certificate represents an X.509 certificate. */ - interface Flag { - name: string // name as it appears on command line - usage: string // help message - value: Value // value as set - defValue: string // default value (as text); for usage message - } - interface FlagSet { + interface Certificate { + raw: string // Complete ASN.1 DER content (certificate, signature algorithm and signature). + rawTBSCertificate: string // Certificate part of raw ASN.1 DER content. + rawSubjectPublicKeyInfo: string // DER encoded SubjectPublicKeyInfo. + rawSubject: string // DER encoded Subject + rawIssuer: string // DER encoded Issuer + signature: string + signatureAlgorithm: SignatureAlgorithm + publicKeyAlgorithm: PublicKeyAlgorithm + publicKey: any + version: number + serialNumber?: big.Int + issuer: pkix.Name + subject: pkix.Name + notBefore: time.Time // Validity bounds. + keyUsage: KeyUsage /** - * Output returns the destination for usage and error messages. os.Stderr is returned if - * output was not set or was set to nil. + * Extensions contains raw X.509 extensions. When parsing certificates, + * this can be used to extract non-critical extensions that are not + * parsed by this package. When marshaling certificates, the Extensions + * field is ignored, see ExtraExtensions. */ - output(): io.Writer - } - interface FlagSet { + extensions: Array /** - * Name returns the name of the flag set. + * ExtraExtensions contains extensions to be copied, raw, into any + * marshaled certificates. Values override any extensions that would + * otherwise be produced based on the other fields. The ExtraExtensions + * field is not populated when parsing certificates, see Extensions. */ - name(): string - } - interface FlagSet { + extraExtensions: Array /** - * ErrorHandling returns the error handling behavior of the flag set. + * UnhandledCriticalExtensions contains a list of extension IDs that + * were not (fully) processed when parsing. Verify will fail if this + * slice is non-empty, unless verification is delegated to an OS + * library which understands all the critical extensions. + * + * Users can access these extensions using Extensions and can remove + * elements from this slice if they believe that they have been + * handled. */ - errorHandling(): ErrorHandling - } - interface FlagSet { + unhandledCriticalExtensions: Array + extKeyUsage: Array // Sequence of extended key usages. + unknownExtKeyUsage: Array // Encountered extended key usages unknown to this package. /** - * SetOutput sets the destination for usage and error messages. - * If output is nil, os.Stderr is used. + * BasicConstraintsValid indicates whether IsCA, MaxPathLen, + * and MaxPathLenZero are valid. */ - setOutput(output: io.Writer): void - } - interface FlagSet { + basicConstraintsValid: boolean + isCA: boolean /** - * VisitAll visits the flags in lexicographical order, calling fn for each. - * It visits all flags, even those not set. + * MaxPathLen and MaxPathLenZero indicate the presence and + * value of the BasicConstraints' "pathLenConstraint". + * + * When parsing a certificate, a positive non-zero MaxPathLen + * means that the field was specified, -1 means it was unset, + * and MaxPathLenZero being true mean that the field was + * explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false + * should be treated equivalent to -1 (unset). + * + * When generating a certificate, an unset pathLenConstraint + * can be requested with either MaxPathLen == -1 or using the + * zero value for both MaxPathLen and MaxPathLenZero. */ - visitAll(fn: (_arg0: Flag) => void): void - } - interface FlagSet { + maxPathLen: number /** - * Visit visits the flags in lexicographical order, calling fn for each. - * It visits only those flags that have been set. + * MaxPathLenZero indicates that BasicConstraintsValid==true + * and MaxPathLen==0 should be interpreted as an actual + * maximum path length of zero. Otherwise, that combination is + * interpreted as MaxPathLen not being set. */ - visit(fn: (_arg0: Flag) => void): void - } - interface FlagSet { + maxPathLenZero: boolean + subjectKeyId: string + authorityKeyId: string /** - * Lookup returns the Flag structure of the named flag, returning nil if none exists. + * RFC 5280, 4.2.2.1 (Authority Information Access) */ - lookup(name: string): (Flag | undefined) - } - interface FlagSet { + ocspServer: Array + issuingCertificateURL: Array /** - * Set sets the value of the named flag. + * Subject Alternate Name values. (Note that these values may not be valid + * if invalid values were contained within a parsed certificate. For + * example, an element of DNSNames may not be a valid DNS domain name.) */ - set(name: string): void + dnsNames: Array + emailAddresses: Array + ipAddresses: Array + urIs: Array<(url.URL | undefined)> + /** + * Name constraints + */ + permittedDNSDomainsCritical: boolean // if true then the name constraints are marked critical. + permittedDNSDomains: Array + excludedDNSDomains: Array + permittedIPRanges: Array<(net.IPNet | undefined)> + excludedIPRanges: Array<(net.IPNet | undefined)> + permittedEmailAddresses: Array + excludedEmailAddresses: Array + permittedURIDomains: Array + excludedURIDomains: Array + /** + * CRL Distribution Points + */ + crlDistributionPoints: Array + policyIdentifiers: Array } - interface FlagSet { + interface Certificate { + equal(other: Certificate): boolean + } + interface Certificate { /** - * PrintDefaults prints, to standard error unless configured otherwise, the - * default values of all defined command-line flags in the set. See the - * documentation for the global function PrintDefaults for more information. + * CheckSignatureFrom verifies that the signature on c is a valid signature + * from parent. SHA1WithRSA and ECDSAWithSHA1 signatures are not supported. */ - printDefaults(): void + checkSignatureFrom(parent: Certificate): void } - interface FlagSet { + interface Certificate { /** - * NFlag returns the number of flags that have been set. + * CheckSignature verifies that signature is a valid signature over signed from + * c's public key. */ - nFlag(): number + checkSignature(algo: SignatureAlgorithm, signed: string): void } - interface FlagSet { + interface Certificate { /** - * Arg returns the i'th argument. Arg(0) is the first remaining argument - * after flags have been processed. Arg returns an empty string if the - * requested element does not exist. + * CheckCRLSignature checks that the signature in crl is from c. */ - arg(i: number): string + checkCRLSignature(crl: pkix.CertificateList): void } - interface FlagSet { + interface Certificate { /** - * NArg is the number of arguments remaining after flags have been processed. + * CreateCRL returns a DER encoded CRL, signed by this Certificate, that + * contains the given list of revoked certificates. + * + * Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. + * To generate a standards compliant CRL, use CreateRevocationList instead. */ - nArg(): number + createCRL(rand: io.Reader, priv: any, revokedCerts: Array, now: time.Time): string } - interface FlagSet { +} + +/** + * 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 { /** - * Args returns the non-flag arguments. + * Get searches for a ClientSessionState associated with the given key. + * On return, ok is true if one was found. */ - args(): Array + 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 } - interface FlagSet { + /** + * ClientHelloInfo contains information from a ClientHello message in order to + * guide application logic in the GetCertificate and GetConfigForClient callbacks. + */ + interface ClientHelloInfo { /** - * BoolVar defines a bool flag with specified name, default value, and usage string. - * The argument p points to a bool variable in which to store the value of the flag. + * 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). */ - boolVar(p: boolean, name: string, value: boolean, usage: string): void - } - interface FlagSet { + supportedCurves: Array /** - * Bool defines a bool flag with specified name, default value, and usage string. - * The return value is the address of a bool variable that stores the value of the flag. + * 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). */ - bool(name: string, value: boolean, usage: string): (boolean | undefined) - } - interface FlagSet { + supportedPoints: Array /** - * IntVar defines an int flag with specified name, default value, and usage string. - * The argument p points to an int variable in which to store the value of the flag. + * 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). */ - intVar(p: number, name: string, value: number, usage: string): void - } - interface FlagSet { + signatureSchemes: Array /** - * Int defines an int flag with specified name, default value, and usage string. - * The return value is the address of an int variable that stores the value of the flag. + * 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. */ - int(name: string, value: number, usage: string): (number | undefined) - } - interface FlagSet { + supportedProtos: Array /** - * Int64Var defines an int64 flag with specified name, default value, and usage string. - * The argument p points to an int64 variable in which to store the value of the flag. + * 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. */ - int64Var(p: number, name: string, value: number, usage: string): void - } - interface FlagSet { + supportedVersions: Array /** - * Int64 defines an int64 flag with specified name, default value, and usage string. - * The return value is the address of an int64 variable that stores the value of the flag. + * 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. */ - int64(name: string, value: number, usage: string): (number | undefined) + conn: net.Conn } - interface FlagSet { + interface ClientHelloInfo { /** - * UintVar defines a uint flag with specified name, default value, and usage string. - * The argument p points to a uint variable in which to store the value of the flag. + * 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. */ - uintVar(p: number, name: string, value: number, usage: string): void + context(): context.Context } - interface FlagSet { + /** + * 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 { /** - * Uint defines a uint flag with specified name, default value, and usage string. - * The return value is the address of a uint variable that stores the value of the flag. + * 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. */ - uint(name: string, value: number, usage: string): (number | undefined) - } - interface FlagSet { + acceptableCAs: Array /** - * Uint64Var defines a uint64 flag with specified name, default value, and usage string. - * The argument p points to a uint64 variable in which to store the value of the flag. + * SignatureSchemes lists the signature schemes that the server is + * willing to verify. */ - uint64Var(p: number, name: string, value: number, usage: string): void - } - interface FlagSet { + signatureSchemes: Array /** - * Uint64 defines a uint64 flag with specified name, default value, and usage string. - * The return value is the address of a uint64 variable that stores the value of the flag. + * Version is the TLS version that was negotiated for this connection. */ - uint64(name: string, value: number, usage: string): (number | undefined) + version: number } - interface FlagSet { + interface CertificateRequestInfo { /** - * StringVar defines a string flag with specified name, default value, and usage string. - * The argument p points to a string variable in which to store the value of the flag. + * 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. */ - stringVar(p: string, name: string, value: string, usage: string): void + context(): context.Context } - interface FlagSet { + /** + * 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 { /** - * String defines a string flag with specified name, default value, and usage string. - * The return value is the address of a string variable that stores the value of the flag. + * 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. */ - string(name: string, value: string, usage: string): (string | undefined) + supportsCertificate(c: Certificate): void } - interface FlagSet { + interface CertificateRequestInfo { /** - * Float64Var defines a float64 flag with specified name, default value, and usage string. - * The argument p points to a float64 variable in which to store the value of the flag. + * 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. */ - float64Var(p: number, name: string, value: number, usage: string): void + supportsCertificate(c: Certificate): void } - interface FlagSet { + /** + * A Certificate is a chain of one or more certificates, leaf first. + */ + interface Certificate { + certificate: Array /** - * Float64 defines a float64 flag with specified name, default value, and usage string. - * The return value is the address of a float64 variable that stores the value of the flag. + * 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. */ - float64(name: string, value: number, usage: string): (number | undefined) - } - interface FlagSet { + privateKey: crypto.PrivateKey /** - * DurationVar defines a time.Duration flag with specified name, default value, and usage string. - * The argument p points to a time.Duration variable in which to store the value of the flag. - * The flag accepts a value acceptable to time.ParseDuration. + * SupportedSignatureAlgorithms is an optional list restricting what + * signature algorithms the PrivateKey can be used for. */ - durationVar(p: time.Duration, name: string, value: time.Duration, usage: string): void - } - interface FlagSet { + supportedSignatureAlgorithms: Array /** - * Duration defines a time.Duration flag with specified name, default value, and usage string. - * The return value is the address of a time.Duration variable that stores the value of the flag. - * The flag accepts a value acceptable to time.ParseDuration. + * OCSPStaple contains an optional OCSP response which will be served + * to clients that request it. */ - duration(name: string, value: time.Duration, usage: string): (time.Duration | undefined) - } - interface FlagSet { + ocspStaple: string /** - * 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. + * SignedCertificateTimestamps contains an optional list of Signed + * Certificate Timestamps which will be served to clients that request it. */ - textVar(p: encoding.TextUnmarshaler, name: string, value: encoding.TextMarshaler, usage: string): void - } - interface FlagSet { + signedCertificateTimestamps: Array /** - * Func defines a flag with the specified name and usage string. - * Each time the flag is seen, fn is called with the value of the flag. - * If fn returns a non-nil error, it will be treated as a flag value parsing error. + * 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. */ - func(name: string, fn: (_arg0: string) => void): void + leaf?: x509.Certificate } - interface FlagSet { + interface CurveID { + string(): string + } + interface ClientAuthType { + string(): string + } +} + +/** + * 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 Part represents a single part in a multipart body. + */ + interface Part { /** - * Var defines a flag with the specified name and usage string. The type and - * value of the flag are represented by the first argument, of type Value, which - * typically holds a user-defined implementation of Value. For instance, the - * caller could create a flag that turns a comma-separated string into a slice - * of strings by giving the slice the methods of Value; in particular, Set would - * decompose the comma-separated string into the slice. + * The headers of the body, if any, with the keys canonicalized + * in the same fashion that the Go http.Request headers are. + * For example, "foo-bar" changes case to "Foo-Bar" */ - var(value: Value, name: string, usage: string): void + header: textproto.MIMEHeader } - interface FlagSet { + interface Part { /** - * Parse parses flag definitions from the argument list, which should not - * include the command name. Must be called after all flags in the FlagSet - * are defined and before flags are accessed by the program. - * The return value will be ErrHelp if -help or -h were set but not defined. + * FormName returns the name parameter if p has a Content-Disposition + * of type "form-data". Otherwise it returns the empty string. */ - parse(arguments: Array): void + formName(): string } - interface FlagSet { + interface Part { /** - * Parsed reports whether f.Parse has been called. + * FileName returns the filename parameter of the Part's Content-Disposition + * header. If not empty, the filename is passed through filepath.Base (which is + * platform dependent) before being returned. */ - parsed(): boolean + fileName(): string } - interface FlagSet { + interface Part { /** - * Init sets the name and error handling property for a flag set. - * By default, the zero FlagSet uses an empty name and the - * ContinueOnError error handling policy. + * Read reads the body of a part, after its headers and before the + * next part (if any) begins. */ - init(name: string, errorHandling: ErrorHandling): void + read(d: string): number } + interface Part { + close(): void + } +} + +/** + * 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 pflag is a drop-in replacement for Go's flag package, implementing - * POSIX/GNU-style --flags. - * - * pflag is compatible with the GNU extensions to the POSIX recommendations - * for command-line options. See - * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - * - * Usage: + * Package http provides HTTP client and server implementations. * - * pflag is a drop-in replacement of Go's native flag package. If you import - * pflag under the name "flag" then all code should continue to function - * with no changes. + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: * * ``` - * import flag "github.com/spf13/pflag" + * 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"}}) * ``` * - * There is one exception to this: if you directly instantiate the Flag struct - * there is one more field "Shorthand" that you will need to set. - * Most code never instantiates this struct directly, and instead uses - * functions such as String(), BoolVar(), and Var(), and is therefore - * unaffected. - * - * Define flags using flag.String(), Bool(), Int(), etc. + * The client must close the response body when finished with it: * - * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - * ``` - * var ip = flag.Int("flagname", 1234, "help message for flagname") - * ``` - * 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") + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... * ``` - * Or you can create custom flags that satisfy the Value interface (with - * pointer receivers) and couple them to flag parsing by + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: + * * ``` - * flag.Var(&flagVal, "name", "help message for flagname") + * 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 such flags, the default value is just the initial value of the variable. * - * After all flags are defined, call + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: + * * ``` - * flag.Parse() + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") * ``` - * 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. + * 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: + * * ``` - * fmt.Println("ip has value ", *ip) - * fmt.Println("flagvar has value ", flagvar) + * 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)) * ``` * - * After parsing, the arguments after the flag are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. + * More control over the server's behavior is available by creating a + * custom Server: * - * The pflag package also defines some new functions that are not in flag, - * that give one-letter shorthands for flags. You can use these by appending - * 'P' to the name of any function that defines a flag. * ``` - * var ip = flag.IntP("flagname", "f", 1234, "help message") - * var flagvar bool - * func init() { - * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, * } - * flag.VarP(&flagval, "varname", "v", "help message") + * log.Fatal(s.ListenAndServe()) * ``` - * Shorthand letters can be used with single dashes on the command line. - * Boolean shorthand flags can be combined with other shorthand flags. * - * Command line flag syntax: - * ``` - * --flag // boolean flags only - * --flag=x - * ``` + * 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: * - * Unlike the flag package, a single dash before an option means something - * different than a double dash. Single dashes signify a series of shorthand - * letters for flags. All but the last shorthand letter must be boolean flags. * ``` - * // boolean flags - * -f - * -abc - * // non-boolean flags - * -n 1234 - * -Ifile - * // mixed - * -abcs "hello" - * -abcn1234 + * 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 * ``` * - * Flag parsing stops after the terminator "--". Unlike the flag package, - * flags can be interspersed with arguments anywhere on the command line - * before this terminator. - * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags (in their long form) accept 1, 0, t, f, true, false, - * TRUE, FALSE, True, False. - * Duration flags accept any input valid for time.ParseDuration. + * 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 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. + * 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 pflag { - // @ts-ignore - import goflag = flag - /** - * ErrorHandling defines how to handle flag parsing errors. - */ - interface ErrorHandling extends Number{} +namespace http { /** - * ParseErrorsWhitelist defines the parsing errors that can be ignored + * RoundTripper is an interface representing the ability to execute a + * single HTTP transaction, obtaining the Response for a given Request. + * + * A RoundTripper must be safe for concurrent use by multiple + * goroutines. */ - interface ParseErrorsWhitelist { + interface RoundTripper { /** - * UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags + * RoundTrip executes a single HTTP transaction, returning + * a Response for the provided Request. + * + * RoundTrip should not attempt to interpret the response. In + * particular, RoundTrip must return err == nil if it obtained + * a response, regardless of the response's HTTP status code. + * A non-nil err should be reserved for failure to obtain a + * response. Similarly, RoundTrip should not attempt to + * handle higher-level protocol details such as redirects, + * authentication, or cookies. + * + * RoundTrip should not modify the request, except for + * consuming and closing the Request's Body. RoundTrip may + * read fields of the request in a separate goroutine. Callers + * should not mutate or reuse the request until the Response's + * Body has been closed. + * + * RoundTrip must always close the body, including on errors, + * but depending on the implementation may do so in a separate + * goroutine even after RoundTrip returns. This means that + * callers wanting to reuse the body for subsequent requests + * must arrange to wait for the Close call before doing so. + * + * The Request's URL and Header fields must be initialized. */ - unknownFlags: boolean + roundTrip(_arg0: Request): (Response | undefined) } /** - * Value is the interface to the dynamic value stored in a flag. - * (The default value is represented as a string.) + * SameSite allows a server to define a cookie attribute making it impossible for + * the browser to send this cookie along with cross-site requests. The main + * goal is to mitigate the risk of cross-origin information leakage, and provide + * some protection against cross-site request forgery attacks. + * + * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. */ - interface Value { - string(): string - set(_arg0: string): void - type(): string + interface SameSite extends Number{} + // @ts-ignore + import mathrand = rand + /** + * A CookieJar manages storage and use of cookies in HTTP requests. + * + * Implementations of CookieJar must be safe for concurrent use by multiple + * goroutines. + * + * The net/http/cookiejar package provides a CookieJar implementation. + */ + interface CookieJar { + /** + * SetCookies handles the receipt of the cookies in a reply for the + * given URL. It may or may not choose to save the cookies, depending + * on the jar's policy and implementation. + */ + setCookies(u: url.URL, cookies: Array<(Cookie | undefined)>): void + /** + * Cookies returns the cookies to send in a request for the given URL. + * It is up to the implementation to honor the standard cookie use + * restrictions such as in RFC 6265. + */ + cookies(u: url.URL): Array<(Cookie | undefined)> } + // @ts-ignore + import urlpkg = url } -namespace subscriptions { +namespace store { +} + +namespace mailer { /** - * Message defines a client's channel data. + * Message defines a generic email message struct. */ interface Message { - name: string - data: string + from: mail.Address + to: Array + bcc: Array + cc: Array + subject: string + html: string + text: string + headers: _TygojaDict + attachments: _TygojaDict } +} + +/** + * 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 { /** - * Client is an interface for a generic subscription client. + * Conn is a connection to a database. It is not used concurrently + * by multiple goroutines. + * + * Conn is assumed to be stateful. */ - 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 + interface Conn { /** - * Subscribe subscribes the client to the provided subscriptions list. + * Prepare returns a prepared statement, bound to this connection. */ - subscribe(...subs: string[]): void + prepare(query: string): Stmt /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. + * 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). */ - unsubscribe(...subs: string[]): void + close(): void /** - * HasSubscription checks if the client is subscribed to `sub`. + * Begin starts and returns a new transaction. + * + * Deprecated: Drivers should implement ConnBeginTx instead (or additionally). */ - hasSubscription(sub: string): boolean + 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 { /** - * Set stores any value to the client's context. + * String returns the current JsonRaw instance as a json encoded string. */ - set(key: string, value: any): void + string(): string + } + interface JsonRaw { /** - * Unset removes a single value from the client's context. + * MarshalJSON implements the [json.Marshaler] interface. */ - unset(key: string): void + marshalJSON(): string + } + interface JsonRaw { /** - * Get retrieves the key value from the client's context. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - get(key: string): any + unmarshalJSON(b: string): void + } + interface JsonRaw { /** - * 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. + * Value implements the [driver.Valuer] interface. */ - discard(): void + value(): driver.Value + } + interface JsonRaw { /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. */ - isDiscarded(): boolean + scan(value: { + }): void } } -/** - * 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 +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + page: number + perPage: number + totalItems: number + totalPages: number + items: any } } /** - * Package reflect implements run-time reflection, allowing a program to - * manipulate objects with arbitrary types. The typical use is to take a value - * with static type interface{} and extract its dynamic type information by - * calling TypeOf, which returns a Type. + * Package echo implements high performance, minimalist Go web framework. * - * A call to ValueOf returns a Value representing the run-time data. - * Zero takes a Type and returns a Value representing a zero value - * for that type. + * Example: * - * See "The Laws of Reflection" for an introduction to reflection in Go: - * https://golang.org/doc/articles/laws_of_reflection.html + * ``` + * 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 reflect { - /** - * A Kind represents the specific kind of type that a Type represents. - * The zero Kind is not a valid kind. - */ - interface Kind extends Number{} - /** - * ChanDir represents a channel type's direction. - */ - interface ChanDir extends Number{} +namespace echo { + // @ts-ignore + import stdContext = context /** - * Method represents a single method. + * Route contains information to adding/registering new route with the router. + * Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields. */ - interface Method { - /** - * Name is the method name. - */ - name: string - /** - * PkgPath is the package path that qualifies a lower case (unexported) - * method name. It is empty for upper case (exported) method names. - * The combination of PkgPath and Name uniquely identifies a method - * in a method set. - * See https://golang.org/ref/spec#Uniqueness_of_identifiers - */ - pkgPath: string - type: Type // method type - func: Value // func with receiver as first argument - index: number // index for Type.Method + interface Route { + method: string + path: string + handler: HandlerFunc + middlewares: Array + name: string } - interface Method { + interface Route { /** - * IsExported reports whether the method is exported. + * ToRouteInfo converts Route to RouteInfo */ - isExported(): boolean + toRouteInfo(params: Array): RouteInfo } - interface Kind { + interface Route { /** - * String returns the name of k. + * ToRoute returns Route which Router uses to register the method handler for path. */ - string(): string + toRoute(): Route } - interface ChanDir { - string(): string + interface Route { + /** + * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. + */ + forGroup(pathPrefix: string, middlewares: Array): Routable } /** - * A StructField describes a single field in a struct. + * RoutableContext is additional interface that structures implementing Context must implement. Methods inside this + * interface are meant for request routing purposes and should not be used in middlewares. */ - interface StructField { + interface RoutableContext { /** - * Name is the field name. + * Request returns `*http.Request`. */ - name: string + request(): (http.Request | undefined) /** - * PkgPath is the package path that qualifies a lower case (unexported) - * field name. It is empty for upper case (exported) field names. - * See https://golang.org/ref/spec#Uniqueness_of_identifiers + * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. */ - pkgPath: string - type: Type // field type - tag: StructTag // field tag string - offset: number // offset within struct, in bytes - index: Array // index sequence for Type.FieldByIndex - anonymous: boolean // is an embedded field - } - interface StructField { + rawPathParams(): (PathParams | undefined) /** - * IsExported reports whether the field is exported. + * SetRawPathParams replaces any existing param values with new values for this context lifetime (request). + * Do not set any other value than what you got from RawPathParams as allocation of PathParams is handled by Context. */ - isExported(): boolean + setRawPathParams(params: PathParams): void + /** + * SetPath sets the registered path for the handler. + */ + setPath(p: string): void + /** + * SetRouteInfo sets the route info of this request to the context. + */ + setRouteInfo(ri: RouteInfo): void + /** + * Set saves data in the context. Allows router to store arbitrary (that only router has access to) data in context + * for later use in middlewares/handler. + */ + set(key: string, val: { + }): void } -} - -/** - * 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. + * PathParam is tuple pf path parameter name and its value in request path */ - interface FileMode extends Number{} - interface FileMode { - string(): string + interface PathParam { + name: string + value: string } - interface FileMode { - /** - * IsDir reports whether m describes a directory. - * That is, it tests for the ModeDir bit being set in m. - */ - isDir(): boolean +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + interface EmailTemplate { + body: string + subject: string + actionUrl: string } - interface FileMode { + interface EmailTemplate { /** - * IsRegular reports whether m describes a regular file. - * That is, it tests that no mode type bits are set. + * Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface. */ - isRegular(): boolean + validate(): void } - interface FileMode { + interface EmailTemplate { /** - * Perm returns the Unix permission bits in m (m & ModePerm). + * Resolve replaces the placeholder parameters in the current email + * template and returns its components as ready-to-use strings. */ - perm(): FileMode + resolve(appName: string, appUrl: string): string } - interface FileMode { - /** - * Type returns type bits in m (m & ModeType). - */ - type(): FileMode +} + +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 { } } -/** - * Package big implements arbitrary-precision arithmetic (big numbers). - * The following numeric types are supported: - * - * ``` - * Int signed integers - * Rat rational numbers - * Float floating-point numbers - * ``` - * - * The zero value for an Int, Rat, or Float correspond to 0. Thus, new - * values can be declared in the usual ways and denote 0 without further - * initialization: - * - * ``` - * var x Int // &x is an *Int of value 0 - * var r = &Rat{} // r is a *Rat of value 0 - * y := new(Float) // y is a *Float of value 0 - * ``` - * - * Alternatively, new values can be allocated and initialized with factory - * functions of the form: - * - * ``` - * func NewT(v V) *T - * ``` - * - * For instance, NewInt(x) returns an *Int set to the value of the int64 - * argument x, NewRat(a, b) returns a *Rat set to the fraction a/b where - * a and b are int64 values, and NewFloat(f) returns a *Float initialized - * to the float64 argument f. More flexibility is provided with explicit - * setters, for instance: - * - * ``` - * var z1 Int - * z1.SetUint64(123) // z1 := 123 - * z2 := new(Rat).SetFloat64(1.25) // z2 := 5/4 - * z3 := new(Float).SetInt(z1) // z3 := 123.0 - * ``` - * - * Setters, numeric operations and predicates are represented as methods of - * the form: - * - * ``` - * func (z *T) SetV(v V) *T // z = v - * func (z *T) Unary(x *T) *T // z = unary x - * func (z *T) Binary(x, y *T) *T // z = x binary y - * func (x *T) Pred() P // p = pred(x) - * ``` - * - * with T one of Int, Rat, or Float. For unary and binary operations, the - * result is the receiver (usually named z in that case; see below); if it - * is one of the operands x or y it may be safely overwritten (and its memory - * reused). - * - * Arithmetic expressions are typically written as a sequence of individual - * method calls, with each call corresponding to an operation. The receiver - * denotes the result and the method arguments are the operation's operands. - * For instance, given three *Int values a, b and c, the invocation - * - * ``` - * c.Add(a, b) - * ``` - * - * computes the sum a + b and stores the result in c, overwriting whatever - * value was held in c before. Unless specified otherwise, operations permit - * aliasing of parameters, so it is perfectly ok to write - * - * ``` - * sum.Add(sum, x) - * ``` - * - * to accumulate values x in a sum. - * - * (By always passing in a result value via the receiver, memory use can be - * much better controlled. Instead of having to allocate new memory for each - * result, an operation can reuse the space allocated for the result value, - * and overwrite that value with the new result in the process.) - * - * Notational convention: Incoming method parameters (including the receiver) - * are named consistently in the API to clarify their use. Incoming operands - * are usually named x, y, a, b, and so on, but never z. A parameter specifying - * the result is named z (typically the receiver). - * - * For instance, the arguments for (*Int).Add are named x and y, and because - * the receiver specifies the result destination, it is called z: - * - * ``` - * func (z *Int) Add(x, y *Int) *Int - * ``` - * - * Methods of this form typically return the incoming receiver as well, to - * enable simple call chaining. - * - * Methods which don't require a result value to be passed in (for instance, - * Int.Sign), simply return the result. In this case, the receiver is typically - * the first operand, named x: - * - * ``` - * func (x *Int) Sign() int - * ``` - * - * Various methods support conversions between strings and corresponding - * numeric values, and vice versa: *Int, *Rat, and *Float values implement - * the Stringer interface for a (default) string representation of the value, - * but also provide SetString methods to initialize a value from a string in - * a variety of supported formats (see the respective SetString documentation). - * - * Finally, *Int, *Rat, and *Float satisfy the fmt package's Scanner interface - * for scanning and (except for *Rat) the Formatter interface for formatted - * printing. - */ -namespace big { +namespace subscriptions { /** - * An Int represents a signed multi-precision integer. - * The zero value for an Int represents the value 0. - * - * Operations always take pointer arguments (*Int) rather - * than Int values, and each unique Int value requires - * its own unique *Int pointer. To "copy" an Int value, - * an existing (or newly allocated) Int must be set to - * a new value using the Int.Set method; shallow copies - * of Ints are not supported and may lead to errors. + * Message defines a client's channel data. */ - interface Int { + interface Message { + name: string + data: string } - interface Int { + /** + * Client is an interface for a generic subscription client. + */ + interface Client { /** - * Sign returns: - * - * ``` - * -1 if x < 0 - * 0 if x == 0 - * +1 if x > 0 - * ``` + * Id Returns the unique id of the client. */ - sign(): number - } - interface Int { + id(): string /** - * SetInt64 sets z to x and returns z. + * Channel returns the client's communication channel. */ - setInt64(x: number): (Int | undefined) - } - interface Int { + channel(): undefined /** - * SetUint64 sets z to x and returns z. + * Subscriptions returns all subscriptions to which the client has subscribed to. */ - setUint64(x: number): (Int | undefined) - } - interface Int { + subscriptions(): _TygojaDict /** - * Set sets z to x and returns z. + * Subscribe subscribes the client to the provided subscriptions list. */ - set(x: Int): (Int | undefined) - } - interface Int { + subscribe(...subs: string[]): void /** - * Bits provides raw (unchecked but fast) access to x by returning its - * absolute value as a little-endian Word slice. The result and x share - * the same underlying array. - * Bits is intended to support implementation of missing low-level Int - * functionality outside this package; it should be avoided otherwise. + * Unsubscribe unsubscribes the client from the provided subscriptions list. */ - bits(): Array - } - interface Int { + unsubscribe(...subs: string[]): void /** - * SetBits provides raw (unchecked but fast) access to z by setting its - * value to abs, interpreted as a little-endian Word slice, and returning - * z. The result and abs share the same underlying array. - * SetBits is intended to support implementation of missing low-level Int - * functionality outside this package; it should be avoided otherwise. + * HasSubscription checks if the client is subscribed to `sub`. */ - setBits(abs: Array): (Int | undefined) - } - interface Int { + hasSubscription(sub: string): boolean /** - * Abs sets z to |x| (the absolute value of x) and returns z. + * Set stores any value to the client's context. */ - abs(x: Int): (Int | undefined) - } - interface Int { + set(key: string, value: any): void /** - * Neg sets z to -x and returns z. + * Unset removes a single value from the client's context. */ - neg(x: Int): (Int | undefined) - } - interface Int { + unset(key: string): void /** - * Add sets z to the sum x+y and returns z. + * Get retrieves the key value from the client's context. */ - add(x: Int): (Int | undefined) - } - interface Int { + get(key: string): any /** - * Sub sets z to the difference x-y and returns z. + * 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. */ - sub(x: Int): (Int | undefined) - } - interface Int { + discard(): void /** - * Mul sets z to the product x*y and returns z. + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. */ - mul(x: Int): (Int | undefined) + isDiscarded(): boolean } - interface Int { +} + +/** + * Package autocert provides automatic access to certificates from Let's Encrypt + * and any other ACME-based CA. + * + * This package is a work in progress and makes no API stability promises. + */ +namespace autocert { + // @ts-ignore + import mathrand = rand + /** + * Manager is a stateful certificate manager built on top of acme.Client. + * It obtains and refreshes certificates automatically using "tls-alpn-01" + * or "http-01" challenge types, as well as providing them to a TLS server + * via tls.Config. + * + * You must specify a cache implementation, such as DirCache, + * to reuse obtained certificates across program restarts. + * Otherwise your server is very likely to exceed the certificate + * issuer's request rate limits. + */ + interface Manager { /** - * MulRange sets z to the product of all integers - * in the range [a, b] inclusively and returns z. - * If a > b (empty range), the result is 1. + * Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). + * The registration may require the caller to agree to the CA's TOS. + * If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report + * whether the caller agrees to the terms. + * + * To always accept the terms, the callers can use AcceptTOS. */ - mulRange(a: number): (Int | undefined) - } - interface Int { + prompt: (tosURL: string) => boolean /** - * Binomial sets z to the binomial coefficient of (n, k) and returns z. + * Cache optionally stores and retrieves previously-obtained certificates + * and other state. If nil, certs will only be cached for the lifetime of + * the Manager. Multiple Managers can share the same Cache. + * + * Using a persistent Cache, such as DirCache, is strongly recommended. */ - binomial(n: number): (Int | undefined) + cache: Cache + /** + * HostPolicy controls which domains the Manager will attempt + * to retrieve new certificates for. It does not affect cached certs. + * + * If non-nil, HostPolicy is called before requesting a new cert. + * If nil, all hosts are currently allowed. This is not recommended, + * as it opens a potential attack where clients connect to a server + * by IP address and pretend to be asking for an incorrect host name. + * Manager will attempt to obtain a certificate for that host, incorrectly, + * eventually reaching the CA's rate limit for certificate requests + * and making it impossible to obtain actual certificates. + * + * See GetCertificate for more details. + */ + hostPolicy: HostPolicy + /** + * RenewBefore optionally specifies how early certificates should + * be renewed before they expire. + * + * If zero, they're renewed 30 days before expiration. + */ + renewBefore: time.Duration + /** + * Client is used to perform low-level operations, such as account registration + * and requesting new certificates. + * + * If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory + * as the directory endpoint. + * If the Client.Key is nil, a new ECDSA P-256 key is generated and, + * if Cache is not nil, stored in cache. + * + * Mutating the field after the first call of GetCertificate method will have no effect. + */ + client?: acme.Client + /** + * Email optionally specifies a contact email address. + * This is used by CAs, such as Let's Encrypt, to notify about problems + * with issued certificates. + * + * If the Client's account key is already registered, Email is not used. + */ + email: string + /** + * ForceRSA used to make the Manager generate RSA certificates. It is now ignored. + * + * Deprecated: the Manager will request the correct type of certificate based + * on what each client supports. + */ + forceRSA: boolean + /** + * ExtraExtensions are used when generating a new CSR (Certificate Request), + * thus allowing customization of the resulting certificate. + * For instance, TLS Feature Extension (RFC 7633) can be used + * to prevent an OCSP downgrade attack. + * + * The field value is passed to crypto/x509.CreateCertificateRequest + * in the template's ExtraExtensions field as is. + */ + extraExtensions: Array + /** + * ExternalAccountBinding optionally represents an arbitrary binding to an + * account of the CA to which the ACME server is tied. + * See RFC 8555, Section 7.3.4 for more details. + */ + externalAccountBinding?: acme.ExternalAccountBinding } - interface Int { + interface Manager { /** - * Quo sets z to the quotient x/y for y != 0 and returns z. - * If y == 0, a division-by-zero run-time panic occurs. - * Quo implements truncated division (like Go); see QuoRem for more details. + * TLSConfig creates a new TLS config suitable for net/http.Server servers, + * supporting HTTP/2 and the tls-alpn-01 ACME challenge type. */ - quo(x: Int): (Int | undefined) + tlsConfig(): (tls.Config | undefined) } - interface Int { + interface Manager { /** - * Rem sets z to the remainder x%y for y != 0 and returns z. - * If y == 0, a division-by-zero run-time panic occurs. - * Rem implements truncated modulus (like Go); see QuoRem for more details. + * GetCertificate implements the tls.Config.GetCertificate hook. + * It provides a TLS certificate for hello.ServerName host, including answering + * tls-alpn-01 challenges. + * All other fields of hello are ignored. + * + * If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting + * a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. + * The error is propagated back to the caller of GetCertificate and is user-visible. + * This does not affect cached certs. See HostPolicy field description for more details. + * + * If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will + * also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. */ - rem(x: Int): (Int | undefined) + getCertificate(hello: tls.ClientHelloInfo): (tls.Certificate | undefined) } - interface Int { + interface Manager { /** - * QuoRem sets z to the quotient x/y and r to the remainder x%y - * and returns the pair (z, r) for y != 0. - * If y == 0, a division-by-zero run-time panic occurs. + * HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. + * It returns an http.Handler that responds to the challenges and must be + * running on port 80. If it receives a request that is not an ACME challenge, + * it delegates the request to the optional fallback handler. * - * QuoRem implements T-division and modulus (like Go): + * If fallback is nil, the returned handler redirects all GET and HEAD requests + * to the default TLS port 443 with 302 Found status code, preserving the original + * request path and query. It responds with 400 Bad Request to all other HTTP methods. + * The fallback is not protected by the optional HostPolicy. * - * ``` - * q = x/y with the result truncated to zero - * r = x - y*q - * ``` + * Because the fallback handler is run with unencrypted port 80 requests, + * the fallback should not serve TLS-only requests. + * + * If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" + * challenge for domain verification. + */ + httpHandler(fallback: http.Handler): http.Handler + } + interface Manager { + /** + * Listener listens on the standard TLS port (443) on all interfaces + * and returns a net.Listener returning *tls.Conn connections. + * + * The returned listener uses a *tls.Config that enables HTTP/2, and + * should only be used with servers that support HTTP/2. * - * (See Daan Leijen, “Division and Modulus for Computer Scientists”.) - * See DivMod for Euclidean division and modulus (unlike Go). + * The returned Listener also enables TCP keep-alives on the accepted + * connections. The returned *tls.Conn are returned before their TLS + * handshake has completed. + * + * Unlike NewListener, it is the caller's responsibility to initialize + * the Manager m's Prompt, Cache, HostPolicy, and other desired options. */ - quoRem(x: Int): [(Int | undefined), (Int | undefined)] + listener(): net.Listener } - interface Int { +} + +/** + * 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") + * 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 { + /** + * A FlagSet represents a set of defined flags. The zero value of a FlagSet + * has no name and has ContinueOnError error handling. + * + * Flag names must be unique within a FlagSet. An attempt to define a flag whose + * name is already in use will cause a panic. + */ + interface FlagSet { /** - * Div sets z to the quotient x/y for y != 0 and returns z. - * If y == 0, a division-by-zero run-time panic occurs. - * Div implements Euclidean division (unlike Go); see DivMod for more details. + * Usage is the function called when an error occurs while parsing flags. + * The field is a function (not a method) that may be changed to point to + * a custom error handler. What happens after Usage is called depends + * on the ErrorHandling setting; for the command line, this defaults + * to ExitOnError, which exits the program after calling Usage. */ - div(x: Int): (Int | undefined) + usage: () => void } - interface Int { + /** + * A Flag represents the state of a flag. + */ + interface Flag { + name: string // name as it appears on command line + usage: string // help message + value: Value // value as set + defValue: string // default value (as text); for usage message + } + interface FlagSet { /** - * Mod sets z to the modulus x%y for y != 0 and returns z. - * If y == 0, a division-by-zero run-time panic occurs. - * Mod implements Euclidean modulus (unlike Go); see DivMod for more details. + * Output returns the destination for usage and error messages. os.Stderr is returned if + * output was not set or was set to nil. */ - mod(x: Int): (Int | undefined) + output(): io.Writer } - interface Int { + interface FlagSet { /** - * DivMod sets z to the quotient x div y and m to the modulus x mod y - * and returns the pair (z, m) for y != 0. - * If y == 0, a division-by-zero run-time panic occurs. - * - * DivMod implements Euclidean division and modulus (unlike Go): - * - * ``` - * q = x div y such that - * 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 - * Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. - * ACM press.) - * See QuoRem for T-division and modulus (like Go). + * Name returns the name of the flag set. */ - divMod(x: Int): [(Int | undefined), (Int | undefined)] + name(): string } - interface Int { + interface FlagSet { /** - * Cmp compares x and y and returns: - * - * ``` - * -1 if x < y - * 0 if x == y - * +1 if x > y - * ``` + * ErrorHandling returns the error handling behavior of the flag set. */ - cmp(y: Int): number + errorHandling(): ErrorHandling } - interface Int { + interface FlagSet { /** - * CmpAbs compares the absolute values of x and y and returns: - * - * ``` - * -1 if |x| < |y| - * 0 if |x| == |y| - * +1 if |x| > |y| - * ``` + * SetOutput sets the destination for usage and error messages. + * If output is nil, os.Stderr is used. */ - cmpAbs(y: Int): number + setOutput(output: io.Writer): void } - interface Int { + interface FlagSet { /** - * Int64 returns the int64 representation of x. - * If x cannot be represented in an int64, the result is undefined. + * VisitAll visits the flags in lexicographical order, calling fn for each. + * It visits all flags, even those not set. */ - int64(): number + visitAll(fn: (_arg0: Flag) => void): void } - interface Int { + interface FlagSet { /** - * Uint64 returns the uint64 representation of x. - * If x cannot be represented in a uint64, the result is undefined. + * Visit visits the flags in lexicographical order, calling fn for each. + * It visits only those flags that have been set. */ - uint64(): number + visit(fn: (_arg0: Flag) => void): void } - interface Int { + interface FlagSet { /** - * IsInt64 reports whether x can be represented as an int64. + * Lookup returns the Flag structure of the named flag, returning nil if none exists. */ - isInt64(): boolean + lookup(name: string): (Flag | undefined) } - interface Int { + interface FlagSet { /** - * IsUint64 reports whether x can be represented as a uint64. + * Set sets the value of the named flag. */ - isUint64(): boolean + set(name: string): void } - interface Int { + interface FlagSet { /** - * SetString sets z to the value of s, interpreted in the given base, - * and returns z and a boolean indicating success. The entire string - * (not just a prefix) must be valid for success. If SetString fails, - * the value of z is undefined but the returned value is nil. - * - * 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 - * and no prefix is accepted. - * - * For bases <= 36, lower and upper case letters are considered the same: - * The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. - * 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 - * 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 - * are no other errors. If base != 0, underscores are not recognized - * and act like any other character that is not a valid digit. + * PrintDefaults prints, to standard error unless configured otherwise, the + * default values of all defined command-line flags in the set. See the + * documentation for the global function PrintDefaults for more information. */ - setString(s: string, base: number): [(Int | undefined), boolean] + printDefaults(): void } - interface Int { + interface FlagSet { /** - * SetBytes interprets buf as the bytes of a big-endian unsigned - * integer, sets z to that value, and returns z. + * NFlag returns the number of flags that have been set. */ - setBytes(buf: string): (Int | undefined) + nFlag(): number } - interface Int { + interface FlagSet { /** - * Bytes returns the absolute value of x as a big-endian byte slice. - * - * To use a fixed length slice, or a preallocated one, use FillBytes. + * Arg returns the i'th argument. Arg(0) is the first remaining argument + * after flags have been processed. Arg returns an empty string if the + * requested element does not exist. */ - bytes(): string + arg(i: number): string } - interface Int { + interface FlagSet { /** - * FillBytes sets buf to the absolute value of x, storing it as a zero-extended - * big-endian byte slice, and returns buf. - * - * If the absolute value of x doesn't fit in buf, FillBytes will panic. + * NArg is the number of arguments remaining after flags have been processed. */ - fillBytes(buf: string): string + nArg(): number } - interface Int { + interface FlagSet { /** - * BitLen returns the length of the absolute value of x in bits. - * The bit length of 0 is 0. + * Args returns the non-flag arguments. */ - bitLen(): number + args(): Array } - interface Int { + interface FlagSet { /** - * TrailingZeroBits returns the number of consecutive least significant zero - * bits of |x|. + * BoolVar defines a bool flag with specified name, default value, and usage string. + * The argument p points to a bool variable in which to store the value of the flag. */ - trailingZeroBits(): number + boolVar(p: boolean, name: string, value: boolean, usage: string): void } - interface Int { + interface FlagSet { /** - * Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. - * If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, - * and x and m are not relatively prime, z is unchanged and nil is returned. - * - * Modular exponentiation of inputs of a particular size is not a - * cryptographically constant-time operation. + * Bool defines a bool flag with specified name, default value, and usage string. + * The return value is the address of a bool variable that stores the value of the flag. */ - exp(x: Int): (Int | undefined) + bool(name: string, value: boolean, usage: string): (boolean | undefined) } - interface Int { + interface FlagSet { /** - * GCD sets z to the greatest common divisor of a and b and returns z. - * If x or y are not nil, GCD sets their value such that z = a*x + b*y. - * - * a and b may be positive, zero or negative. (Before Go 1.14 both had - * to be > 0.) Regardless of the signs of a and b, z is always >= 0. - * - * If a == b == 0, GCD sets z = x = y = 0. - * - * If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1. - * - * If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. + * IntVar defines an int flag with specified name, default value, and usage string. + * The argument p points to an int variable in which to store the value of the flag. */ - gcd(x: Int): (Int | undefined) + intVar(p: number, name: string, value: number, usage: string): void } - interface Int { + interface FlagSet { /** - * Rand sets z to a pseudo-random number in [0, n) and returns z. - * - * As this uses the math/rand package, it must not be used for - * security-sensitive work. Use crypto/rand.Int instead. + * Int defines an int flag with specified name, default value, and usage string. + * The return value is the address of an int variable that stores the value of the flag. */ - rand(rnd: rand.Rand, n: Int): (Int | undefined) + int(name: string, value: number, usage: string): (number | undefined) } - interface Int { + interface FlagSet { /** - * 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. + * Int64Var defines an int64 flag with specified name, default value, and usage string. + * The argument p points to an int64 variable in which to store the value of the flag. */ - modInverse(g: Int): (Int | undefined) + int64Var(p: number, name: string, value: number, usage: string): void } - interface Int { + interface FlagSet { /** - * 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. + * Int64 defines an int64 flag with specified name, default value, and usage string. + * The return value is the address of an int64 variable that stores the value of the flag. */ - modSqrt(x: Int): (Int | undefined) + int64(name: string, value: number, usage: string): (number | undefined) } - interface Int { + interface FlagSet { /** - * Lsh sets z = x << n and returns z. + * UintVar defines a uint flag with specified name, default value, and usage string. + * The argument p points to a uint variable in which to store the value of the flag. */ - lsh(x: Int, n: number): (Int | undefined) + uintVar(p: number, name: string, value: number, usage: string): void } - interface Int { + interface FlagSet { /** - * Rsh sets z = x >> n and returns z. + * Uint defines a uint flag with specified name, default value, and usage string. + * The return value is the address of a uint variable that stores the value of the flag. */ - rsh(x: Int, n: number): (Int | undefined) + uint(name: string, value: number, usage: string): (number | undefined) } - interface Int { + interface FlagSet { /** - * Bit returns the value of the i'th bit of x. That is, it - * returns (x>>i)&1. The bit index i must be >= 0. + * Uint64Var defines a uint64 flag with specified name, default value, and usage string. + * The argument p points to a uint64 variable in which to store the value of the flag. */ - bit(i: number): number + uint64Var(p: number, name: string, value: number, usage: string): void } - interface Int { + interface FlagSet { /** - * SetBit sets z to x, with x's i'th bit set to b (0 or 1). - * That is, if b is 1 SetBit sets z = x | (1 << i); - * if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, - * SetBit will panic. + * Uint64 defines a uint64 flag with specified name, default value, and usage string. + * The return value is the address of a uint64 variable that stores the value of the flag. */ - setBit(x: Int, i: number, b: number): (Int | undefined) + uint64(name: string, value: number, usage: string): (number | undefined) } - interface Int { + interface FlagSet { /** - * And sets z = x & y and returns z. + * StringVar defines a string flag with specified name, default value, and usage string. + * The argument p points to a string variable in which to store the value of the flag. */ - and(x: Int): (Int | undefined) + stringVar(p: string, name: string, value: string, usage: string): void } - interface Int { + interface FlagSet { /** - * AndNot sets z = x &^ y and returns z. + * String defines a string flag with specified name, default value, and usage string. + * The return value is the address of a string variable that stores the value of the flag. */ - andNot(x: Int): (Int | undefined) + string(name: string, value: string, usage: string): (string | undefined) } - interface Int { + interface FlagSet { /** - * Or sets z = x | y and returns z. + * Float64Var defines a float64 flag with specified name, default value, and usage string. + * The argument p points to a float64 variable in which to store the value of the flag. */ - or(x: Int): (Int | undefined) + float64Var(p: number, name: string, value: number, usage: string): void } - interface Int { + interface FlagSet { /** - * Xor sets z = x ^ y and returns z. + * Float64 defines a float64 flag with specified name, default value, and usage string. + * The return value is the address of a float64 variable that stores the value of the flag. */ - xor(x: Int): (Int | undefined) + float64(name: string, value: number, usage: string): (number | undefined) } - interface Int { + interface FlagSet { /** - * Not sets z = ^x and returns z. + * DurationVar defines a time.Duration flag with specified name, default value, and usage string. + * The argument p points to a time.Duration variable in which to store the value of the flag. + * The flag accepts a value acceptable to time.ParseDuration. */ - not(x: Int): (Int | undefined) + durationVar(p: time.Duration, name: string, value: time.Duration, usage: string): void } - interface Int { + interface FlagSet { /** - * Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. - * It panics if x is negative. + * Duration defines a time.Duration flag with specified name, default value, and usage string. + * The return value is the address of a time.Duration variable that stores the value of the flag. + * The flag accepts a value acceptable to time.ParseDuration. */ - sqrt(x: Int): (Int | undefined) + duration(name: string, value: time.Duration, usage: string): (time.Duration | undefined) } - interface Int { + interface FlagSet { /** - * Text returns the string representation of x in the given base. - * Base must be between 2 and 62, inclusive. The result uses the - * lower-case letters 'a' to 'z' for digit values 10 to 35, and - * the upper-case letters 'A' to 'Z' for digit values 36 to 61. - * No prefix (such as "0x") is added to the string. If x is a nil - * pointer it returns "". + * Func defines a flag with the specified name and usage string. + * Each time the flag is seen, fn is called with the value of the flag. + * If fn returns a non-nil error, it will be treated as a flag value parsing error. */ - text(base: number): string + func(name: string, fn: (_arg0: string) => void): void } - interface Int { + interface FlagSet { /** - * Append appends the string representation of x, as generated by - * x.Text(base), to buf and returns the extended buffer. + * Var defines a flag with the specified name and usage string. The type and + * value of the flag are represented by the first argument, of type Value, which + * typically holds a user-defined implementation of Value. For instance, the + * caller could create a flag that turns a comma-separated string into a slice + * of strings by giving the slice the methods of Value; in particular, Set would + * decompose the comma-separated string into the slice. */ - append(buf: string, base: number): string + var(value: Value, name: string, usage: string): void } - interface Int { + interface FlagSet { /** - * String returns the decimal representation of x as generated by - * x.Text(10). + * Parse parses flag definitions from the argument list, which should not + * include the command name. Must be called after all flags in the FlagSet + * are defined and before flags are accessed by the program. + * The return value will be ErrHelp if -help or -h were set but not defined. */ - string(): string + parse(arguments: Array): void } - interface Int { + interface FlagSet { /** - * Format implements fmt.Formatter. It accepts the formats - * 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix), - * 'd' (decimal), 'x' (lowercase hexadecimal), and - * 'X' (uppercase hexadecimal). - * Also supported are the full suite of package fmt's format - * flags for integral types, including '+' and ' ' for sign - * control, '#' for leading zero in octal and for hexadecimal, - * a leading "0x" or "0X" for "%#x" and "%#X" respectively, - * specification of minimum digits precision, output field - * width, space or zero padding, and '-' for left or right - * justification. + * Parsed reports whether f.Parse has been called. */ - format(s: fmt.State, ch: string): void + parsed(): boolean } - interface Int { + interface FlagSet { /** - * Scan is a support routine for fmt.Scanner; it sets z to the value of - * the scanned number. It accepts the formats 'b' (binary), 'o' (octal), - * 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). + * Init sets the name and error handling property for a flag set. + * By default, the zero FlagSet uses an empty name and the + * ContinueOnError error handling policy. */ - scan(s: fmt.ScanState, ch: string): void + init(name: string, errorHandling: ErrorHandling): void } - interface Int { +} + +/** + * Package pflag is a drop-in replacement for Go's flag package, implementing + * POSIX/GNU-style --flags. + * + * pflag is compatible with the GNU extensions to the POSIX recommendations + * for command-line options. See + * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + * + * Usage: + * + * pflag is a drop-in replacement of Go's native flag package. If you import + * pflag under the name "flag" then all code should continue to function + * with no changes. + * + * ``` + * import flag "github.com/spf13/pflag" + * ``` + * + * There is one exception to this: if you directly instantiate the Flag struct + * there is one more field "Shorthand" that you will need to set. + * Most code never instantiates this struct directly, and instead uses + * functions such as String(), BoolVar(), and Var(), and is therefore + * unaffected. + * + * Define flags using flag.String(), Bool(), Int(), etc. + * + * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + * ``` + * var ip = flag.Int("flagname", 1234, "help message for flagname") + * ``` + * 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 after the flag are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * The pflag package also defines some new functions that are not in flag, + * that give one-letter shorthands for flags. You can use these by appending + * 'P' to the name of any function that defines a flag. + * ``` + * var ip = flag.IntP("flagname", "f", 1234, "help message") + * var flagvar bool + * func init() { + * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + * } + * flag.VarP(&flagval, "varname", "v", "help message") + * ``` + * Shorthand letters can be used with single dashes on the command line. + * Boolean shorthand flags can be combined with other shorthand flags. + * + * Command line flag syntax: + * ``` + * --flag // boolean flags only + * --flag=x + * ``` + * + * Unlike the flag package, a single dash before an option means something + * different than a double dash. Single dashes signify a series of shorthand + * letters for flags. All but the last shorthand letter must be boolean flags. + * ``` + * // boolean flags + * -f + * -abc + * // non-boolean flags + * -n 1234 + * -Ifile + * // mixed + * -abcs "hello" + * -abcn1234 + * ``` + * + * Flag parsing stops after the terminator "--". Unlike the flag package, + * flags can be interspersed with arguments anywhere on the command line + * before this terminator. + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags (in their long form) accept 1, 0, 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 pflag { + // @ts-ignore + import goflag = flag + /** + * ErrorHandling defines how to handle flag parsing errors. + */ + interface ErrorHandling extends Number{} + /** + * ParseErrorsWhitelist defines the parsing errors that can be ignored + */ + interface ParseErrorsWhitelist { /** - * GobEncode implements the gob.GobEncoder interface. + * UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags */ - gobEncode(): string + unknownFlags: boolean } - interface Int { - /** - * GobDecode implements the gob.GobDecoder interface. - */ - gobDecode(buf: string): void + /** + * Value is the interface to the dynamic value stored in a flag. + * (The default value is represented as a string.) + */ + interface Value { + string(): string + set(_arg0: string): void + type(): string } - interface Int { - /** - * MarshalText implements the encoding.TextMarshaler interface. - */ - marshalText(): string +} + +/** + * 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 Int { + interface FileMode { /** - * UnmarshalText implements the encoding.TextUnmarshaler interface. + * IsDir reports whether m describes a directory. + * That is, it tests for the ModeDir bit being set in m. */ - unmarshalText(text: string): void + isDir(): boolean } - interface Int { + interface FileMode { /** - * MarshalJSON implements the json.Marshaler interface. + * IsRegular reports whether m describes a regular file. + * That is, it tests that no mode type bits are set. */ - marshalJSON(): string + isRegular(): boolean } - interface Int { + interface FileMode { /** - * UnmarshalJSON implements the json.Unmarshaler interface. + * Perm returns the Unix permission bits in m (m & ModePerm). */ - unmarshalJSON(text: string): void + perm(): FileMode } - interface Int { + interface FileMode { /** - * ProbablyPrime reports whether x is probably prime, - * applying the Miller-Rabin test with n pseudorandomly chosen bases - * as well as a Baillie-PSW test. - * - * If x is prime, ProbablyPrime returns true. - * If x is chosen randomly and not prime, ProbablyPrime probably returns false. - * The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ. - * - * ProbablyPrime is 100% accurate for inputs less than 2⁶⁴. - * See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149, - * and FIPS 186-4 Appendix F for further discussion of the error probabilities. - * - * ProbablyPrime is not suitable for judging primes that an adversary may - * have crafted to fool the test. - * - * As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test. - * Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked. + * Type returns type bits in m (m & ModeType). */ - probablyPrime(n: number): boolean + type(): FileMode } } /** - * 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. + * Package crypto collects common cryptographic constants. */ -namespace asn1 { +namespace crypto { /** - * An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. + * 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 ObjectIdentifier extends Array{} - interface ObjectIdentifier { - /** - * Equal reports whether oi and other represent the same identifier. - */ - equal(other: ObjectIdentifier): boolean - } - interface ObjectIdentifier { - string(): string - } + interface PrivateKey extends _TygojaAny{} } /** - * Package pkix contains shared, low level structures used for ASN.1 parsing - * and serialization of X.509 certificates, CRL and OCSP. + * Package reflect implements run-time reflection, allowing a program to + * manipulate objects with arbitrary types. The typical use is to take a value + * with static type interface{} and extract its dynamic type information by + * calling TypeOf, which returns a Type. + * + * A call to ValueOf returns a Value representing the run-time data. + * Zero takes a Type and returns a Value representing a zero value + * for that type. + * + * See "The Laws of Reflection" for an introduction to reflection in Go: + * https://golang.org/doc/articles/laws_of_reflection.html */ -namespace pkix { +namespace reflect { /** - * Extension represents the ASN.1 structure of the same name. See RFC - * 5280, section 4.2. + * A Kind represents the specific kind of type that a Type represents. + * The zero Kind is not a valid kind. */ - interface Extension { - id: asn1.ObjectIdentifier - critical: boolean - value: string - } + interface Kind extends Number{} /** - * 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. + * ChanDir represents a channel type's direction. */ - interface Name { - country: Array - locality: Array - streetAddress: Array - serialNumber: string + interface ChanDir extends Number{} + /** + * Method represents a single method. + */ + interface Method { /** - * 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. + * Name is the method name. */ - names: Array + name: string /** - * 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. + * PkgPath is the package path that qualifies a lower case (unexported) + * method name. It is empty for upper case (exported) method names. + * The combination of PkgPath and Name uniquely identifies a method + * in a method set. + * See https://golang.org/ref/spec#Uniqueness_of_identifiers */ - extraNames: Array + pkgPath: string + type: Type // method type + func: Value // func with receiver as first argument + index: number // index for Type.Method } - interface Name { + interface Method { /** - * 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. + * IsExported reports whether the method is exported. */ - fillFromRDNSequence(rdns: RDNSequence): void + isExported(): boolean } - interface Name { + interface Kind { /** - * 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. + * String returns the name of k. */ - toRDNSequence(): RDNSequence + string(): string } - interface Name { - /** - * String returns the string form of n, roughly following - * the RFC 2253 Distinguished Names syntax. - */ + interface ChanDir { 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. + * A StructField describes a single field in a struct. */ - interface CertificateList { - tbsCertList: TBSCertificateList - signatureAlgorithm: AlgorithmIdentifier - signatureValue: asn1.BitString - } - interface CertificateList { + interface StructField { /** - * HasExpired reports whether certList should have been updated by now. + * Name is the field name. */ - hasExpired(now: time.Time): boolean + name: string + /** + * PkgPath is the package path that qualifies a lower case (unexported) + * field name. It is empty for upper case (exported) field names. + * See https://golang.org/ref/spec#Uniqueness_of_identifiers + */ + pkgPath: string + type: Type // field type + tag: StructTag // field tag string + offset: number // offset within struct, in bytes + index: Array // index sequence for Type.FieldByIndex + anonymous: boolean // is an embedded field } - /** - * 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 + interface StructField { + /** + * IsExported reports whether the field is exported. + */ + isExported(): boolean } } /** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. + * Package big implements arbitrary-precision arithmetic (big numbers). + * The following numeric types are supported: * - * 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. + * ``` + * Int signed integers + * Rat rational numbers + * Float floating-point numbers + * ``` * - * The Dial function connects to a server: + * The zero value for an Int, Rat, or Float correspond to 0. Thus, new + * values can be declared in the usual ways and denote 0 without further + * initialization: * * ``` - * 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') - * // ... + * var x Int // &x is an *Int of value 0 + * var r = &Rat{} // r is a *Rat of value 0 + * y := new(Float) // y is a *Float of value 0 * ``` * - * The Listen function creates servers: + * Alternatively, new values can be allocated and initialized with factory + * functions of the form: * * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } + * func NewT(v V) *T * ``` * - * # Name Resolution + * For instance, NewInt(x) returns an *Int set to the value of the int64 + * argument x, NewRat(a, b) returns a *Rat set to the fraction a/b where + * a and b are int64 values, and NewFloat(f) returns a *Float initialized + * to the float64 argument f. More flexibility is provided with explicit + * setters, for instance: * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * ``` + * var z1 Int + * z1.SetUint64(123) // z1 := 123 + * z2 := new(Rat).SetFloat64(1.25) // z2 := 5/4 + * z3 := new(Float).SetInt(z1) // z3 := 123.0 + * ``` * - * 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. + * Setters, numeric operations and predicates are represented as methods of + * the form: * - * 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. + * ``` + * func (z *T) SetV(v V) *T // z = v + * func (z *T) Unary(x *T) *T // z = unary x + * func (z *T) Binary(x, y *T) *T // z = x binary y + * func (x *T) Pred() P // p = pred(x) + * ``` * - * 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: + * with T one of Int, Rat, or Float. For unary and binary operations, the + * result is the receiver (usually named z in that case; see below); if it + * is one of the operands x or y it may be safely overwritten (and its memory + * reused). + * + * Arithmetic expressions are typically written as a sequence of individual + * method calls, with each call corresponding to an operation. The receiver + * denotes the result and the method arguments are the operation's operands. + * For instance, given three *Int values a, b and c, the invocation * * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) + * c.Add(a, b) * ``` * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. + * computes the sum a + b and stores the result in c, overwriting whatever + * value was held in c before. Unless specified otherwise, operations permit + * aliasing of parameters, so it is perfectly ok to write * - * 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. + * ``` + * sum.Add(sum, x) + * ``` * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. + * to accumulate values x in a sum. + * + * (By always passing in a result value via the receiver, memory use can be + * much better controlled. Instead of having to allocate new memory for each + * result, an operation can reuse the space allocated for the result value, + * and overwrite that value with the new result in the process.) + * + * Notational convention: Incoming method parameters (including the receiver) + * are named consistently in the API to clarify their use. Incoming operands + * are usually named x, y, a, b, and so on, but never z. A parameter specifying + * the result is named z (typically the receiver). + * + * For instance, the arguments for (*Int).Add are named x and y, and because + * the receiver specifies the result destination, it is called z: + * + * ``` + * func (z *Int) Add(x, y *Int) *Int + * ``` + * + * Methods of this form typically return the incoming receiver as well, to + * enable simple call chaining. + * + * Methods which don't require a result value to be passed in (for instance, + * Int.Sign), simply return the result. In this case, the receiver is typically + * the first operand, named x: + * + * ``` + * func (x *Int) Sign() int + * ``` + * + * Various methods support conversions between strings and corresponding + * numeric values, and vice versa: *Int, *Rat, and *Float values implement + * the Stringer interface for a (default) string representation of the value, + * but also provide SetString methods to initialize a value from a string in + * a variety of supported formats (see the respective SetString documentation). * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. + * Finally, *Int, *Rat, and *Float satisfy the fmt package's Scanner interface + * for scanning and (except for *Rat) the Formatter interface for formatted + * printing. */ -namespace net { +namespace big { /** - * Addr represents a network end point address. + * An Int represents a signed multi-precision integer. + * The zero value for an Int represents the value 0. * - * 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. + * Operations always take pointer arguments (*Int) rather + * than Int values, and each unique Int value requires + * its own unique *Int pointer. To "copy" an Int value, + * an existing (or newly allocated) Int must be set to + * a new value using the Int.Set method; shallow copies + * of Ints are not supported and may lead to errors. */ - 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") + interface Int { } - /** - * 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 + interface Int { /** - * Addr returns the listener's network address. + * Sign returns: + * + * ``` + * -1 if x < 0 + * 0 if x == 0 + * +1 if x > 0 + * ``` */ - addr(): Addr + sign(): number } -} - -/** - * 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 + interface Int { /** - * 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. + * SetInt64 sets z to x and returns z. */ - roots?: CertPool + setInt64(x: number): (Int | undefined) + } + interface Int { /** - * CurrentTime is used to check the validity of all certificates in the - * chain. If zero, the current time is used. + * SetUint64 sets z to x and returns z. */ - currentTime: time.Time + setUint64(x: number): (Int | undefined) + } + interface Int { /** - * 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. + * Set sets z to x and returns z. */ - keyUsages: Array + set(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Bits provides raw (unchecked but fast) access to x by returning its + * absolute value as a little-endian Word slice. The result and x share + * the same underlying array. + * Bits is intended to support implementation of missing low-level Int + * functionality outside this package; it should be avoided otherwise. */ - maxConstraintComparisions: number + bits(): Array } - interface SignatureAlgorithm extends Number{} - interface SignatureAlgorithm { - string(): string + interface Int { + /** + * SetBits provides raw (unchecked but fast) access to z by setting its + * value to abs, interpreted as a little-endian Word slice, and returning + * z. The result and abs share the same underlying array. + * SetBits is intended to support implementation of missing low-level Int + * functionality outside this package; it should be avoided otherwise. + */ + setBits(abs: Array): (Int | undefined) } - interface PublicKeyAlgorithm extends Number{} - interface PublicKeyAlgorithm { - string(): string + interface Int { + /** + * Abs sets z to |x| (the absolute value of x) and returns z. + */ + abs(x: Int): (Int | undefined) } - /** - * 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 { + interface Int { /** - * CipherSuites lists the CipherSuites supported by the client (e.g. - * TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). + * Neg sets z to -x and returns z. */ - cipherSuites: Array + neg(x: Int): (Int | undefined) + } + interface Int { /** - * 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). + * Add sets z to the sum x+y and returns z. */ - serverName: string + add(x: Int): (Int | undefined) + } + interface Int { /** - * 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). + * Sub sets z to the difference x-y and returns z. */ - supportedCurves: Array + sub(x: Int): (Int | undefined) + } + interface Int { /** - * 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). + * Mul sets z to the product x*y and returns z. */ - supportedPoints: Array + mul(x: Int): (Int | undefined) + } + interface Int { /** - * 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). + * MulRange sets z to the product of all integers + * in the range [a, b] inclusively and returns z. + * If a > b (empty range), the result is 1. */ - signatureSchemes: Array + mulRange(a: number): (Int | undefined) + } + interface Int { /** - * 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. + * Binomial sets z to the binomial coefficient of (n, k) and returns z. */ - supportedProtos: Array + binomial(n: number): (Int | undefined) + } + interface Int { /** - * 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. + * Quo sets z to the quotient x/y for y != 0 and returns z. + * If y == 0, a division-by-zero run-time panic occurs. + * Quo implements truncated division (like Go); see QuoRem for more details. */ - supportedVersions: Array + quo(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Rem sets z to the remainder x%y for y != 0 and returns z. + * If y == 0, a division-by-zero run-time panic occurs. + * Rem implements truncated modulus (like Go); see QuoRem for more details. */ - conn: net.Conn + rem(x: Int): (Int | undefined) } - interface ClientHelloInfo { + interface Int { /** - * 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. + * QuoRem sets z to the quotient x/y and r to the remainder x%y + * and returns the pair (z, r) for y != 0. + * If y == 0, a division-by-zero run-time panic occurs. + * + * QuoRem implements T-division and modulus (like Go): + * + * ``` + * q = x/y with the result truncated to zero + * r = x - y*q + * ``` + * + * (See Daan Leijen, ``Division and Modulus for Computer Scientists''.) + * See DivMod for Euclidean division and modulus (unlike Go). */ - context(): context.Context + quoRem(x: Int): [(Int | undefined), (Int | undefined)] } - /** - * 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 { + interface Int { /** - * 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. + * Div sets z to the quotient x/y for y != 0 and returns z. + * If y == 0, a division-by-zero run-time panic occurs. + * Div implements Euclidean division (unlike Go); see DivMod for more details. */ - rand: io.Reader + div(x: Int): (Int | undefined) + } + interface Int { /** - * Time returns the current time as the number of seconds since the epoch. - * If Time is nil, TLS uses time.Now. + * Mod sets z to the modulus x%y for y != 0 and returns z. + * If y == 0, a division-by-zero run-time panic occurs. + * Mod implements Euclidean modulus (unlike Go); see DivMod for more details. */ - time: () => time.Time + mod(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * DivMod sets z to the quotient x div y and m to the modulus x mod y + * and returns the pair (z, m) for y != 0. + * If y == 0, a division-by-zero run-time panic occurs. * - * Server configurations must set one of Certificates, GetCertificate or - * GetConfigForClient. Clients doing client-authentication may set either - * Certificates or GetClientCertificate. + * DivMod implements Euclidean division and modulus (unlike Go): * - * 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. + * ``` + * q = x div y such that + * 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 + * Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. + * ACM press.) + * See QuoRem for T-division and modulus (like Go). */ - certificates: Array + divMod(x: Int): [(Int | undefined), (Int | undefined)] + } + interface Int { /** - * 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. + * Cmp compares x and y and returns: * - * 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. + * ``` + * -1 if x < y + * 0 if x == y + * +1 if x > y + * ``` */ - nameToCertificate: _TygojaDict + cmp(y: Int): number + } + interface Int { /** - * 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. + * CmpAbs compares the absolute values of x and y and returns: * - * 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. + * ``` + * -1 if |x| < |y| + * 0 if |x| == |y| + * +1 if |x| > |y| + * ``` */ - getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) + cmpAbs(y: Int): number + } + interface Int { /** - * 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. + * Int64 returns the int64 representation of x. + * If x cannot be represented in an int64, the result is undefined. */ - getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) + int64(): number + } + interface Int { /** - * 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. + * Uint64 returns the uint64 representation of x. + * If x cannot be represented in a uint64, the result is undefined. + */ + uint64(): number + } + interface Int { + /** + * IsInt64 reports whether x can be represented as an int64. + */ + isInt64(): boolean + } + interface Int { + /** + * IsUint64 reports whether x can be represented as a uint64. + */ + isUint64(): boolean + } + interface Int { + /** + * SetString sets z to the value of s, interpreted in the given base, + * and returns z and a boolean indicating success. The entire string + * (not just a prefix) must be valid for success. If SetString fails, + * the value of z is undefined but the returned value is nil. + * + * 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 + * and no prefix is accepted. * - * If GetConfigForClient is nil, the Config passed to Server() will be - * used for all connections. + * For bases <= 36, lower and upper case letters are considered the same: + * The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. + * For bases > 36, the upper case letters 'A' to 'Z' represent the digit + * values 36 to 61. * - * 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). + * 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 + * are no other errors. If base != 0, underscores are not recognized + * and act like any other character that is not a valid digit. */ - getConfigForClient: (_arg0: ClientHelloInfo) => (Config | undefined) + setString(s: string, base: number): [(Int | undefined), boolean] + } + interface Int { /** - * 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. + * SetBytes interprets buf as the bytes of a big-endian unsigned + * integer, sets z to that value, and returns z. + */ + setBytes(buf: string): (Int | undefined) + } + interface Int { + /** + * Bytes returns the absolute value of x as a big-endian byte slice. * - * 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. + * To use a fixed length slice, or a preallocated one, use FillBytes. */ - verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void + bytes(): string + } + interface Int { /** - * 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. + * FillBytes sets buf to the absolute value of x, storing it as a zero-extended + * big-endian byte slice, and returns buf. * - * 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. + * If the absolute value of x doesn't fit in buf, FillBytes will panic. */ - verifyConnection: (_arg0: ConnectionState) => void + fillBytes(buf: string): string + } + interface Int { /** - * 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. + * BitLen returns the length of the absolute value of x in bits. + * The bit length of 0 is 0. */ - rootCAs?: x509.CertPool + bitLen(): number + } + interface Int { /** - * 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. + * TrailingZeroBits returns the number of consecutive least significant zero + * bits of |x|. */ - nextProtos: Array + trailingZeroBits(): number + } + interface Int { /** - * 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. + * Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. + * If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, + * and x and m are not relatively prime, z is unchanged and nil is returned. + * + * Modular exponentiation of inputs of a particular size is not a + * cryptographically constant-time operation. */ - serverName: string + exp(x: Int): (Int | undefined) + } + interface Int { /** - * ClientAuth determines the server's policy for - * TLS Client Authentication. The default is NoClientCert. + * GCD sets z to the greatest common divisor of a and b and returns z. + * If x or y are not nil, GCD sets their value such that z = a*x + b*y. + * + * a and b may be positive, zero or negative. (Before Go 1.14 both had + * to be > 0.) Regardless of the signs of a and b, z is always >= 0. + * + * If a == b == 0, GCD sets z = x = y = 0. + * + * If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1. + * + * If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. */ - clientAuth: ClientAuthType + gcd(x: Int): (Int | undefined) + } + interface Int { /** - * ClientCAs defines the set of root certificate authorities - * that servers use if required to verify a client certificate - * by the policy in ClientAuth. + * Rand sets z to a pseudo-random number in [0, n) and returns z. + * + * As this uses the math/rand package, it must not be used for + * security-sensitive work. Use crypto/rand.Int instead. */ - clientCAs?: x509.CertPool + rand(rnd: rand.Rand, n: Int): (Int | undefined) + } + interface Int { /** - * 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. + * 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. */ - insecureSkipVerify: boolean + modInverse(g: Int): (Int | undefined) + } + interface Int { /** - * 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. + * 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. */ - cipherSuites: Array + modSqrt(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Lsh sets z = x << n and returns z. */ - preferServerCipherSuites: boolean + lsh(x: Int, n: number): (Int | undefined) + } + interface Int { /** - * 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. + * Rsh sets z = x >> n and returns z. */ - sessionTicketsDisabled: boolean + rsh(x: Int, n: number): (Int | undefined) + } + interface Int { /** - * 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. + * Bit returns the value of the i'th bit of x. That is, it + * returns (x>>i)&1. The bit index i must be >= 0. */ - sessionTicketKey: string + bit(i: number): number + } + interface Int { /** - * ClientSessionCache is a cache of ClientSessionState entries for TLS - * session resumption. It is only used by clients. + * SetBit sets z to x, with x's i'th bit set to b (0 or 1). + * That is, if b is 1 SetBit sets z = x | (1 << i); + * if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, + * SetBit will panic. */ - clientSessionCache: ClientSessionCache + setBit(x: Int, i: number, b: number): (Int | undefined) + } + interface Int { /** - * 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). + * And sets z = x & y and returns z. */ - minVersion: number + and(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * AndNot sets z = x &^ y and returns z. */ - maxVersion: number + andNot(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Or sets z = x | y and returns z. */ - curvePreferences: Array + or(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Xor sets z = x ^ y and returns z. */ - dynamicRecordSizingDisabled: boolean + xor(x: Int): (Int | undefined) + } + interface Int { /** - * Renegotiation controls what types of renegotiation are supported. - * The default, none, is correct for the vast majority of applications. + * Not sets z = ^x and returns z. */ - renegotiation: RenegotiationSupport + not(x: Int): (Int | undefined) + } + interface Int { /** - * 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. + * Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. + * It panics if x is negative. + */ + sqrt(x: Int): (Int | undefined) + } + interface Int { + /** + * Text returns the string representation of x in the given base. + * Base must be between 2 and 62, inclusive. The result uses the + * lower-case letters 'a' to 'z' for digit values 10 to 35, and + * the upper-case letters 'A' to 'Z' for digit values 36 to 61. + * No prefix (such as "0x") is added to the string. If x is a nil + * pointer it returns "". */ - keyLogWriter: io.Writer + text(base: number): string } - interface Config { + interface Int { /** - * 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. + * Append appends the string representation of x, as generated by + * x.Text(base), to buf and returns the extended buffer. */ - clone(): (Config | undefined) + append(buf: string, base: number): string } - interface Config { + interface Int { /** - * 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. + * String returns the decimal representation of x as generated by + * x.Text(10). */ - setSessionTicketKeys(keys: Array): void + string(): string } - interface ClientHelloInfo { + interface Int { /** - * 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. + * Format implements fmt.Formatter. It accepts the formats + * 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix), + * 'd' (decimal), 'x' (lowercase hexadecimal), and + * 'X' (uppercase hexadecimal). + * Also supported are the full suite of package fmt's format + * flags for integral types, including '+' and ' ' for sign + * control, '#' for leading zero in octal and for hexadecimal, + * a leading "0x" or "0X" for "%#x" and "%#X" respectively, + * specification of minimum digits precision, output field + * width, space or zero padding, and '-' for left or right + * justification. */ - supportsCertificate(c: Certificate): void + format(s: fmt.State, ch: string): void } - interface Config { + interface Int { /** - * 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. + * Scan is a support routine for fmt.Scanner; it sets z to the value of + * the scanned number. It accepts the formats 'b' (binary), 'o' (octal), + * 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). */ - buildNameToCertificate(): void + scan(s: fmt.ScanState, ch: string): void } - /** - * A Certificate is a chain of one or more certificates, leaf first. - */ - interface Certificate { - certificate: Array + interface Int { /** - * 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. + * GobEncode implements the gob.GobEncoder interface. */ - privateKey: crypto.PrivateKey + gobEncode(): string + } + interface Int { /** - * SupportedSignatureAlgorithms is an optional list restricting what - * signature algorithms the PrivateKey can be used for. + * GobDecode implements the gob.GobDecoder interface. */ - supportedSignatureAlgorithms: Array + gobDecode(buf: string): void + } + interface Int { /** - * OCSPStaple contains an optional OCSP response which will be served - * to clients that request it. + * MarshalText implements the encoding.TextMarshaler interface. */ - ocspStaple: string + marshalText(): string + } + interface Int { /** - * SignedCertificateTimestamps contains an optional list of Signed - * Certificate Timestamps which will be served to clients that request it. + * UnmarshalText implements the encoding.TextUnmarshaler interface. */ - signedCertificateTimestamps: Array + unmarshalText(text: string): void + } + interface Int { /** - * 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. + * MarshalJSON implements the json.Marshaler interface. */ - leaf?: x509.Certificate + marshalJSON(): string } -} - -/** - * 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 + interface Int { + /** + * UnmarshalJSON implements the json.Unmarshaler interface. + */ + unmarshalJSON(text: string): void } - /** - * 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 + interface Int { + /** + * ProbablyPrime reports whether x is probably prime, + * applying the Miller-Rabin test with n pseudorandomly chosen bases + * as well as a Baillie-PSW test. + * + * If x is prime, ProbablyPrime returns true. + * If x is chosen randomly and not prime, ProbablyPrime probably returns false. + * The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ. + * + * ProbablyPrime is 100% accurate for inputs less than 2⁶⁴. + * See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149, + * and FIPS 186-4 Appendix F for further discussion of the error probabilities. + * + * ProbablyPrime is not suitable for judging primes that an adversary may + * have crafted to fool the test. + * + * As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test. + * Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked. + */ + probablyPrime(n: number): boolean } } @@ -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 { - /** - * SetOutput sets the output destination for the logger. - */ - setOutput(w: io.Writer): void - } - interface Logger { + interface ObjectIdentifier extends Array{} + interface ObjectIdentifier { /** - * 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. + * Equal reports whether oi and other represent the same identifier. */ - output(calldepth: number, s: string): void + equal(other: ObjectIdentifier): boolean } - 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 ObjectIdentifier { + string(): string } - interface Logger { - /** - * Print calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Print. - */ - print(...v: any[]): void +} + +/** + * 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 } - interface Logger { + /** + * 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 /** - * Println calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Println. + * 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. */ - println(...v: any[]): void - } - interface Logger { + names: Array /** - * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). + * 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. */ - fatal(...v: any[]): void + extraNames: Array } - interface Logger { + interface Name { /** - * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). + * 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. */ - fatalf(format: string, ...v: any[]): void + fillFromRDNSequence(rdns: RDNSequence): void } - interface Logger { + interface Name { /** - * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). + * 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. */ - fatalln(...v: any[]): void + toRDNSequence(): RDNSequence } - interface Logger { + interface Name { /** - * Panic is equivalent to l.Print() followed by a call to panic(). + * String returns the string form of n, roughly following + * the RFC 2253 Distinguished Names syntax. */ - panic(...v: any[]): void + string(): string } - interface Logger { + /** + * 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 { /** - * Panicf is equivalent to l.Printf() followed by a call to panic(). + * HasExpired reports whether certList should have been updated by now. */ - panicf(format: string, ...v: any[]): void + hasExpired(now: time.Time): boolean } - interface Logger { + /** + * 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 { /** - * Panicln is equivalent to l.Println() followed by a call to panic(). + * DNSName, if set, is checked against the leaf certificate with + * Certificate.VerifyHostname or the platform verifier. */ - panicln(...v: any[]): void - } - interface Logger { + dnsName: string /** - * Flags returns the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. + * 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. */ - flags(): number - } - interface Logger { + intermediates?: CertPool /** - * SetFlags sets the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. + * 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. */ - setFlags(flag: number): void - } - interface Logger { + roots?: CertPool /** - * Prefix returns the output prefix for the logger. + * CurrentTime is used to check the validity of all certificates in the + * chain. If zero, the current time is used. */ - prefix(): string - } - interface Logger { + currentTime: time.Time /** - * SetPrefix sets the output prefix for the logger. + * 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. */ - setPrefix(prefix: string): void - } - interface Logger { + keyUsages: Array /** - * Writer returns the output destination for the logger. + * 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. */ - writer(): io.Writer + 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 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: + * 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: * ``` - * 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 + * * 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. * ``` - * - * 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 +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 { /** - * 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. + * ClientSessionState contains the state needed by clients to resume TLS + * sessions. */ - interface Handler { - serveHTTP(_arg0: ResponseWriter, _arg1: Request): void + interface ClientSessionState { } /** - * A ConnState represents the state of a client connection to a server. - * It's used by the optional Server.ConnState hook. + * SignatureScheme identifies a signature algorithm supported by TLS. See + * RFC 8446, Section 4.2.3. */ - interface ConnState extends Number{} - interface ConnState { + 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. @@ -20749,236 +20851,31 @@ namespace autocert { * and other account data as opaque blobs. * * Cache implementations should not rely on the key naming pattern. Keys can - * include any printable ASCII characters, except the following: \/:*?"<>| - */ - interface Cache { - /** - * Get returns a certificate data for the specified key. - * If there's no such key, Get returns ErrCacheMiss. - */ - get(ctx: context.Context, key: string): string - /** - * Put stores the data in the cache under the specified key. - * Underlying implementations may use any data storage format, - * as long as the reverse operation, Get, results in the original data. - */ - put(ctx: context.Context, key: string, data: string): void - /** - * Delete removes a certificate data from the cache under the specified key. - * If there's no such key in the cache, Delete returns nil. - */ - delete(ctx: context.Context, key: string): void - } -} - -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. + * include any printable ASCII characters, except the following: \/:*?"<>| */ - interface Signer { + interface Cache { /** - * Public returns the public key corresponding to the opaque, - * private key. + * Get returns a certificate data for the specified key. + * If there's no such key, Get returns ErrCacheMiss. */ - public(): PublicKey + get(ctx: context.Context, key: string): string /** - * 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. + * Put stores the data in the cache under the specified key. + * Underlying implementations may use any data storage format, + * as long as the reverse operation, Get, results in the original data. */ - sign(rand: io.Reader, digest: string, opts: SignerOpts): string + put(ctx: context.Context, key: string, data: string): void + /** + * Delete removes a certificate data from the cache under the specified key. + * If there's no such key in the cache, Delete returns nil. + */ + delete(ctx: context.Context, key: string): void } } +namespace search { +} + /** * 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 - * ``` - * - * 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) + * 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. * ``` - * - * 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 { @@ -22438,255 +22241,102 @@ namespace asn1 { */ interface BitString { bytes: string // bits packed into bytes. - bitLength: number // length in bits. - } - interface BitString { - /** - * At returns the bit at the given index. If the index is out of range it - * returns false. - */ - at(i: number): number - } - interface BitString { - /** - * RightAlign returns a slice where the padding bits are at the beginning. The - * slice may share memory with the BitString. - */ - rightAlign(): string - } -} - -/** - * Package pkix contains shared, low level structures used for ASN.1 parsing - * and serialization of X.509 certificates, CRL and OCSP. - */ -namespace pkix { - /** - * AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC - * 5280, section 4.1.1.2. - */ - interface AlgorithmIdentifier { - algorithm: asn1.ObjectIdentifier - parameters: asn1.RawValue - } - interface RDNSequence extends Array{} - interface RDNSequence { - /** - * String returns a string representation of the sequence r, - * roughly following the RFC 2253 Distinguished Names syntax. - */ - string(): string - } - /** - * AttributeTypeAndValue mirrors the ASN.1 structure of the same name in - * RFC 5280, Section 4.1.2.4. - */ - interface AttributeTypeAndValue { - type: asn1.ObjectIdentifier - value: any - } - /** - * 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 - version: number - signature: AlgorithmIdentifier - issuer: RDNSequence - thisUpdate: time.Time - nextUpdate: time.Time - revokedCertificates: Array - 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 { - /** - * CertPool is a set of certificates. - */ - interface CertPool { - } - interface CertPool { - /** - * Clone returns a copy of s. - */ - clone(): (CertPool | undefined) - } - 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 + bitLength: number // length in bits. } - interface CertPool { + interface BitString { /** - * 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. + * At returns the bit at the given index. If the index is out of range it + * returns false. */ - subjects(): Array + at(i: number): number } - interface CertPool { + interface BitString { /** - * Equal reports whether s and other are equal. + * RightAlign returns a slice where the padding bits are at the beginning. The + * slice may share memory with the BitString. */ - equal(other: CertPool): boolean + rightAlign(): string } - // @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. + * Package pkix contains shared, low level structures used for ASN.1 parsing + * and serialization of X.509 certificates, CRL and OCSP. */ -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{} +namespace pkix { /** - * 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. + * AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC + * 5280, section 4.1.1.2. */ - 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] + interface AlgorithmIdentifier { + algorithm: asn1.ObjectIdentifier + parameters: asn1.RawValue + } + interface RDNSequence extends Array{} + interface RDNSequence { /** - * 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. + * String returns a string representation of the sequence r, + * roughly following the RFC 2253 Distinguished Names syntax. */ - put(sessionKey: string, cs: ClientSessionState): void + string(): string } /** - * SignatureScheme identifies a signature algorithm supported by TLS. See - * RFC 8446, Section 4.2.3. + * AttributeTypeAndValue mirrors the ASN.1 structure of the same name in + * RFC 5280, Section 4.1.2.4. */ - interface SignatureScheme extends Number{} + interface AttributeTypeAndValue { + type: asn1.ObjectIdentifier + value: any + } /** - * CertificateRequestInfo contains information from a server's - * CertificateRequest message, which is used to demand a certificate and proof - * of control from a client. + * TBSCertificateList represents the ASN.1 structure of the same name. See RFC + * 5280, section 5.1. */ - 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. - */ + interface TBSCertificateList { + raw: asn1.RawContent version: number + signature: AlgorithmIdentifier + issuer: RDNSequence + thisUpdate: time.Time + nextUpdate: time.Time + revokedCertificates: Array + extensions: Array } - 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 - } +} + +/** + * Package crypto collects common cryptographic constants. + */ +namespace crypto { /** - * 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. + * 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 RenegotiationSupport extends Number{} - interface CertificateRequestInfo { + interface Signer { /** - * 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. + * Public returns the public key corresponding to the opaque, + * private key. */ - supportsCertificate(c: Certificate): void - } - interface SignatureScheme { - string(): string - } - interface CurveID { - string(): string - } - interface ClientAuthType { - string(): string + 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 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 acme provides an implementation of the * Automatic Certificate Management Environment (ACME) spec, @@ -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 { @@ -23207,24 +22825,43 @@ namespace asn1 { } /** - * Package pkix contains shared, low level structures used for ASN.1 parsing - * and serialization of X.509 certificates, CRL and OCSP. + * Package crypto collects common cryptographic constants. */ -namespace pkix { - interface RelativeDistinguishedNameSET extends Array{} +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 tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. + * Package pkix contains shared, low level structures used for ASN.1 parsing + * and serialization of X.509 certificates, CRL and OCSP. */ -namespace tls { - /** - * ClientSessionState contains the state needed by clients to resume TLS - * sessions. - */ - interface ClientSessionState { - } +namespace pkix { + interface RelativeDistinguishedNameSET extends Array{} } /** 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 2d109df53..07500293e 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. + * + * Example: + * + * ` + "```" + `js + * const res = $http.send({ + * url: "https://example.com", + * data: {"title": "test"} + * method: "post", + * }) * - * @group PocketBase + * 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 0ace4b3ae..d965ef677 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 c1acc0339..eb6780eea 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()