diff --git a/CHANGELOG.md b/CHANGELOG.md index ce018227..b9e93eae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ A negative or zero value means no tests timeout. If a single API test takes more than 3s to complete it will have a log message visible when the test fails or when `go test -v` flag is used. +- Added timestamp at the beginning of the generated JSVM types file to avoid creating it everytime with the app startup. + ## v0.20.0 diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index 54fb2b71..57e1c660 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1,3 +1,4 @@ +// 1702756189 // GENERATED CODE - DO NOT MODIFY BY HAND // ------------------------------------------------------------------- @@ -1627,8 +1628,8 @@ namespace os { * than ReadFrom. This is used to permit ReadFrom to call io.Copy * without leading to a recursive call to ReadFrom. */ - type _subzZtGP = File - interface fileWithoutReadFrom extends _subzZtGP { + type _subvJZMB = File + interface fileWithoutReadFrom extends _subvJZMB { } interface fileWithoutReadFrom { /** @@ -2285,8 +2286,8 @@ namespace os { /** * File represents an open file descriptor. */ - type _subUhvjc = file - interface File extends _subUhvjc { + type _subERxvE = file + interface File extends _subERxvE { } /** * A FileInfo describes a file and is returned by Stat and Lstat. @@ -2687,6 +2688,132 @@ namespace filepath { } } +/** + * Package exec runs external commands. It wraps os.StartProcess to make it + * easier to remap stdin and stdout, connect I/O with pipes, and do other + * adjustments. + * + * Unlike the "system" library call from C and other languages, the + * os/exec package intentionally does not invoke the system shell and + * does not expand any glob patterns or handle other expansions, + * pipelines, or redirections typically done by shells. The package + * behaves more like C's "exec" family of functions. To expand glob + * patterns, either call the shell directly, taking care to escape any + * dangerous input, or use the path/filepath package's Glob function. + * To expand environment variables, use package os's ExpandEnv. + * + * Note that the examples in this package assume a Unix system. + * They may not run on Windows, and they do not run in the Go Playground + * used by golang.org and godoc.org. + * + * # Executables in the current directory + * + * The functions Command and LookPath look for a program + * in the directories listed in the current path, following the + * conventions of the host operating system. + * Operating systems have for decades included the current + * directory in this search, sometimes implicitly and sometimes + * configured explicitly that way by default. + * Modern practice is that including the current directory + * is usually unexpected and often leads to security problems. + * + * To avoid those security problems, as of Go 1.19, this package will not resolve a program + * using an implicit or explicit path entry relative to the current directory. + * That is, if you run exec.LookPath("go"), it will not successfully return + * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. + * Instead, if the usual path algorithms would result in that answer, + * these functions return an error err satisfying errors.Is(err, ErrDot). + * + * For example, consider these two program snippets: + * + * ``` + * path, err := exec.LookPath("prog") + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * These will not find and run ./prog or .\prog.exe, + * no matter how the current path is configured. + * + * Code that always wants to run a program from the current directory + * can be rewritten to say "./prog" instead of "prog". + * + * Code that insists on including results from relative path entries + * can instead override the error using an errors.Is check: + * + * ``` + * path, err := exec.LookPath("prog") + * if errors.Is(err, exec.ErrDot) { + * err = nil + * } + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if errors.Is(cmd.Err, exec.ErrDot) { + * cmd.Err = nil + * } + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * Setting the environment variable GODEBUG=execerrdot=0 + * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 + * behavior for programs that are unable to apply more targeted fixes. + * A future version of Go may remove support for this variable. + * + * Before adding such overrides, make sure you understand the + * security implications of doing so. + * See https://go.dev/blog/path-security for more information. + */ +namespace exec { + interface command { + /** + * Command returns the Cmd struct to execute the named program with + * the given arguments. + * + * It sets only the Path and Args in the returned structure. + * + * If name contains no path separators, Command uses LookPath to + * resolve name to a complete path if possible. Otherwise it uses name + * directly as Path. + * + * The returned Cmd's Args field is constructed from the command name + * followed by the elements of arg, so arg should not include the + * command name itself. For example, Command("echo", "hello"). + * Args[0] is always name, not the possibly resolved Path. + * + * On Windows, processes receive the whole command line as a single string + * and do their own parsing. Command combines and quotes Args into a command + * line string with an algorithm compatible with applications using + * CommandLineToArgvW (which is the most common way). Notable exceptions are + * msiexec.exe and cmd.exe (and thus, all batch files), which have a different + * unquoting algorithm. In these or other similar cases, you can do the + * quoting yourself and provide the full command line in SysProcAttr.CmdLine, + * leaving Args empty. + */ + (name: string, ...arg: string[]): (Cmd) + } +} + namespace security { interface s256Challenge { /** @@ -2819,6 +2946,224 @@ namespace security { } } +namespace filesystem { + /** + * FileReader defines an interface for a file resource reader. + */ + interface FileReader { + [key:string]: any; + open(): io.ReadSeekCloser + } + /** + * File defines a single file [io.ReadSeekCloser] resource. + * + * The file could be from a local path, multipipart/formdata header, etc. + */ + interface File { + reader: FileReader + name: string + originalName: string + size: number + } + interface newFileFromPath { + /** + * NewFileFromPath creates a new File instance from the provided local file path. + */ + (path: string): (File) + } + interface newFileFromBytes { + /** + * NewFileFromBytes creates a new File instance from the provided byte slice. + */ + (b: string|Array, name: string): (File) + } + interface newFileFromMultipart { + /** + * NewFileFromMultipart creates a new File from the provided multipart header. + */ + (mh: multipart.FileHeader): (File) + } + interface newFileFromUrl { + /** + * NewFileFromUrl creates a new File from the provided url by + * downloading the resource and load it as BytesReader. + * + * Example + * + * ``` + * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + * defer cancel() + * + * file, err := filesystem.NewFileFromUrl(ctx, "https://example.com/image.png") + * ``` + */ + (ctx: context.Context, url: string): (File) + } + /** + * MultipartReader defines a FileReader from [multipart.FileHeader]. + */ + interface MultipartReader { + header?: multipart.FileHeader + } + interface MultipartReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * PathReader defines a FileReader from a local file path. + */ + interface PathReader { + path: string + } + interface PathReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * BytesReader defines a FileReader from bytes content. + */ + interface BytesReader { + bytes: string|Array + } + interface BytesReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + type _subzMDax = bytes.Reader + interface bytesReadSeekCloser extends _subzMDax { + } + interface bytesReadSeekCloser { + /** + * Close implements the [io.ReadSeekCloser] interface. + */ + close(): void + } + interface System { + } + interface newS3 { + /** + * NewS3 initializes an S3 filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) + } + interface newLocal { + /** + * NewLocal initializes a new local filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (dirPath: string): (System) + } + interface System { + /** + * SetContext assigns the specified context to the current filesystem. + */ + setContext(ctx: context.Context): void + } + interface System { + /** + * Close releases any resources used for the related filesystem. + */ + close(): void + } + interface System { + /** + * Exists checks if file with fileKey path exists or not. + */ + exists(fileKey: string): boolean + } + interface System { + /** + * Attributes returns the attributes for the file with fileKey path. + */ + attributes(fileKey: string): (blob.Attributes) + } + interface System { + /** + * GetFile returns a file content reader for the given fileKey. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + getFile(fileKey: string): (blob.Reader) + } + interface System { + /** + * Copy copies the file stored at srcKey to dstKey. + * + * If dstKey file already exists, it is overwritten. + */ + copy(srcKey: string): void + } + interface System { + /** + * List returns a flat list with info for all files under the specified prefix. + */ + list(prefix: string): Array<(blob.ListObject | undefined)> + } + interface System { + /** + * Upload writes content into the fileKey location. + */ + upload(content: string|Array, fileKey: string): void + } + interface System { + /** + * UploadFile uploads the provided multipart file to the fileKey location. + */ + uploadFile(file: File, fileKey: string): void + } + interface System { + /** + * UploadMultipart uploads the provided multipart file to the fileKey location. + */ + uploadMultipart(fh: multipart.FileHeader, fileKey: string): void + } + interface System { + /** + * Delete deletes stored file at fileKey location. + */ + delete(fileKey: string): void + } + interface System { + /** + * DeletePrefix deletes everything starting with the specified prefix. + */ + deletePrefix(prefix: string): Array + } + interface System { + /** + * Serve serves the file at fileKey location to an HTTP response. + * + * If the `download` query parameter is used the file will be always served for + * download no matter of its type (aka. with "Content-Disposition: attachment"). + */ + serve(res: http.ResponseWriter, req: http.Request, fileKey: string, name: string): void + } + interface System { + /** + * CreateThumb creates a new thumb image for the file at originalKey location. + * The new thumb file is stored at thumbKey location. + * + * thumbSize is in the format: + * - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio + * - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio + * - WxH (eg. 300x100) - resize and crop to WxH viewbox (from center) + * - WxHt (eg. 300x100t) - resize and crop to WxH viewbox (from top) + * - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) + * - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping) + */ + createThumb(originalKey: string, thumbKey: string): void + } +} + /** * Package validation provides configurable and extensible rules for validating data of various types. */ @@ -3173,14 +3518,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subPlCRo = BaseBuilder - interface MssqlBuilder extends _subPlCRo { + type _subNtsYu = BaseBuilder + interface MssqlBuilder extends _subNtsYu { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subvylCI = BaseQueryBuilder - interface MssqlQueryBuilder extends _subvylCI { + type _subSdkdP = BaseQueryBuilder + interface MssqlQueryBuilder extends _subSdkdP { } interface newMssqlBuilder { /** @@ -3251,8 +3596,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subhAvEL = BaseBuilder - interface MysqlBuilder extends _subhAvEL { + type _subWKnwT = BaseBuilder + interface MysqlBuilder extends _subWKnwT { } interface newMysqlBuilder { /** @@ -3327,14 +3672,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subdCmKE = BaseBuilder - interface OciBuilder extends _subdCmKE { + type _subiivbX = BaseBuilder + interface OciBuilder extends _subiivbX { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subufmOq = BaseQueryBuilder - interface OciQueryBuilder extends _subufmOq { + type _subtiScV = BaseQueryBuilder + interface OciQueryBuilder extends _subtiScV { } interface newOciBuilder { /** @@ -3397,8 +3742,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _sububtLm = BaseBuilder - interface PgsqlBuilder extends _sububtLm { + type _subnxlos = BaseBuilder + interface PgsqlBuilder extends _subnxlos { } interface newPgsqlBuilder { /** @@ -3465,8 +3810,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subCiquj = BaseBuilder - interface SqliteBuilder extends _subCiquj { + type _subRMwTU = BaseBuilder + interface SqliteBuilder extends _subRMwTU { } interface newSqliteBuilder { /** @@ -3565,8 +3910,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subwSCdX = BaseBuilder - interface StandardBuilder extends _subwSCdX { + type _subCRXwd = BaseBuilder + interface StandardBuilder extends _subCRXwd { } interface newStandardBuilder { /** @@ -3632,8 +3977,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 _subxHWqr = Builder - interface DB extends _subxHWqr { + type _subzjzDy = Builder + interface DB extends _subzjzDy { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -4435,8 +4780,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 _subziJYp = sql.Rows - interface Rows extends _subziJYp { + type _subyhcKN = sql.Rows + interface Rows extends _subyhcKN { } interface Rows { /** @@ -4793,8 +5138,8 @@ namespace dbx { }): string } interface structInfo { } - type _subCXxiO = structInfo - interface structValue extends _subCXxiO { + type _subNcPqp = structInfo + interface structValue extends _subNcPqp { } interface fieldInfo { } @@ -4833,8 +5178,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subfTAaj = Builder - interface Tx extends _subfTAaj { + type _subNUSrp = Builder + interface Tx extends _subNUSrp { } interface Tx { /** @@ -4850,350 +5195,6 @@ namespace dbx { } } -/** - * Package exec runs external commands. It wraps os.StartProcess to make it - * easier to remap stdin and stdout, connect I/O with pipes, and do other - * adjustments. - * - * Unlike the "system" library call from C and other languages, the - * os/exec package intentionally does not invoke the system shell and - * does not expand any glob patterns or handle other expansions, - * pipelines, or redirections typically done by shells. The package - * behaves more like C's "exec" family of functions. To expand glob - * patterns, either call the shell directly, taking care to escape any - * dangerous input, or use the path/filepath package's Glob function. - * To expand environment variables, use package os's ExpandEnv. - * - * Note that the examples in this package assume a Unix system. - * They may not run on Windows, and they do not run in the Go Playground - * used by golang.org and godoc.org. - * - * # Executables in the current directory - * - * The functions Command and LookPath look for a program - * in the directories listed in the current path, following the - * conventions of the host operating system. - * Operating systems have for decades included the current - * directory in this search, sometimes implicitly and sometimes - * configured explicitly that way by default. - * Modern practice is that including the current directory - * is usually unexpected and often leads to security problems. - * - * To avoid those security problems, as of Go 1.19, this package will not resolve a program - * using an implicit or explicit path entry relative to the current directory. - * That is, if you run exec.LookPath("go"), it will not successfully return - * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. - * Instead, if the usual path algorithms would result in that answer, - * these functions return an error err satisfying errors.Is(err, ErrDot). - * - * For example, consider these two program snippets: - * - * ``` - * path, err := exec.LookPath("prog") - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * These will not find and run ./prog or .\prog.exe, - * no matter how the current path is configured. - * - * Code that always wants to run a program from the current directory - * can be rewritten to say "./prog" instead of "prog". - * - * Code that insists on including results from relative path entries - * can instead override the error using an errors.Is check: - * - * ``` - * path, err := exec.LookPath("prog") - * if errors.Is(err, exec.ErrDot) { - * err = nil - * } - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if errors.Is(cmd.Err, exec.ErrDot) { - * cmd.Err = nil - * } - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * Setting the environment variable GODEBUG=execerrdot=0 - * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 - * behavior for programs that are unable to apply more targeted fixes. - * A future version of Go may remove support for this variable. - * - * Before adding such overrides, make sure you understand the - * security implications of doing so. - * See https://go.dev/blog/path-security for more information. - */ -namespace exec { - interface command { - /** - * Command returns the Cmd struct to execute the named program with - * the given arguments. - * - * It sets only the Path and Args in the returned structure. - * - * If name contains no path separators, Command uses LookPath to - * resolve name to a complete path if possible. Otherwise it uses name - * directly as Path. - * - * The returned Cmd's Args field is constructed from the command name - * followed by the elements of arg, so arg should not include the - * command name itself. For example, Command("echo", "hello"). - * Args[0] is always name, not the possibly resolved Path. - * - * On Windows, processes receive the whole command line as a single string - * and do their own parsing. Command combines and quotes Args into a command - * line string with an algorithm compatible with applications using - * CommandLineToArgvW (which is the most common way). Notable exceptions are - * msiexec.exe and cmd.exe (and thus, all batch files), which have a different - * unquoting algorithm. In these or other similar cases, you can do the - * quoting yourself and provide the full command line in SysProcAttr.CmdLine, - * leaving Args empty. - */ - (name: string, ...arg: string[]): (Cmd) - } -} - -namespace filesystem { - /** - * FileReader defines an interface for a file resource reader. - */ - interface FileReader { - [key:string]: any; - open(): io.ReadSeekCloser - } - /** - * File defines a single file [io.ReadSeekCloser] resource. - * - * The file could be from a local path, multipipart/formdata header, etc. - */ - interface File { - reader: FileReader - name: string - originalName: string - size: number - } - interface newFileFromPath { - /** - * NewFileFromPath creates a new File instance from the provided local file path. - */ - (path: string): (File) - } - interface newFileFromBytes { - /** - * NewFileFromBytes creates a new File instance from the provided byte slice. - */ - (b: string|Array, name: string): (File) - } - interface newFileFromMultipart { - /** - * NewFileFromMultipart creates a new File from the provided multipart header. - */ - (mh: multipart.FileHeader): (File) - } - interface newFileFromUrl { - /** - * NewFileFromUrl creates a new File from the provided url by - * downloading the resource and load it as BytesReader. - * - * Example - * - * ``` - * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - * defer cancel() - * - * file, err := filesystem.NewFileFromUrl(ctx, "https://example.com/image.png") - * ``` - */ - (ctx: context.Context, url: string): (File) - } - /** - * MultipartReader defines a FileReader from [multipart.FileHeader]. - */ - interface MultipartReader { - header?: multipart.FileHeader - } - interface MultipartReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - /** - * PathReader defines a FileReader from a local file path. - */ - interface PathReader { - path: string - } - interface PathReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - /** - * BytesReader defines a FileReader from bytes content. - */ - interface BytesReader { - bytes: string|Array - } - interface BytesReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - type _subgGzhk = bytes.Reader - interface bytesReadSeekCloser extends _subgGzhk { - } - interface bytesReadSeekCloser { - /** - * Close implements the [io.ReadSeekCloser] interface. - */ - close(): void - } - interface System { - } - interface newS3 { - /** - * NewS3 initializes an S3 filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. - */ - (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) - } - interface newLocal { - /** - * NewLocal initializes a new local filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. - */ - (dirPath: string): (System) - } - interface System { - /** - * SetContext assigns the specified context to the current filesystem. - */ - setContext(ctx: context.Context): void - } - interface System { - /** - * Close releases any resources used for the related filesystem. - */ - close(): void - } - interface System { - /** - * Exists checks if file with fileKey path exists or not. - */ - exists(fileKey: string): boolean - } - interface System { - /** - * Attributes returns the attributes for the file with fileKey path. - */ - attributes(fileKey: string): (blob.Attributes) - } - interface System { - /** - * GetFile returns a file content reader for the given fileKey. - * - * NB! Make sure to call `Close()` after you are done working with it. - */ - getFile(fileKey: string): (blob.Reader) - } - interface System { - /** - * Copy copies the file stored at srcKey to dstKey. - * - * If dstKey file already exists, it is overwritten. - */ - copy(srcKey: string): void - } - interface System { - /** - * List returns a flat list with info for all files under the specified prefix. - */ - list(prefix: string): Array<(blob.ListObject | undefined)> - } - interface System { - /** - * Upload writes content into the fileKey location. - */ - upload(content: string|Array, fileKey: string): void - } - interface System { - /** - * UploadFile uploads the provided multipart file to the fileKey location. - */ - uploadFile(file: File, fileKey: string): void - } - interface System { - /** - * UploadMultipart uploads the provided multipart file to the fileKey location. - */ - uploadMultipart(fh: multipart.FileHeader, fileKey: string): void - } - interface System { - /** - * Delete deletes stored file at fileKey location. - */ - delete(fileKey: string): void - } - interface System { - /** - * DeletePrefix deletes everything starting with the specified prefix. - */ - deletePrefix(prefix: string): Array - } - interface System { - /** - * Serve serves the file at fileKey location to an HTTP response. - * - * If the `download` query parameter is used the file will be always served for - * download no matter of its type (aka. with "Content-Disposition: attachment"). - */ - serve(res: http.ResponseWriter, req: http.Request, fileKey: string, name: string): void - } - interface System { - /** - * CreateThumb creates a new thumb image for the file at originalKey location. - * The new thumb file is stored at thumbKey location. - * - * thumbSize is in the format: - * - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio - * - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio - * - WxH (eg. 300x100) - resize and crop to WxH viewbox (from center) - * - WxHt (eg. 300x100t) - resize and crop to WxH viewbox (from top) - * - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) - * - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping) - */ - createThumb(originalKey: string, thumbKey: string): void - } -} - /** * Package tokens implements various user and admin tokens generation methods. */ @@ -6196,8 +6197,8 @@ namespace forms { /** * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - type _subEKWjR = settings.Settings - interface SettingsUpsert extends _subEKWjR { + type _subZJAAL = settings.Settings + interface SettingsUpsert extends _subZJAAL { } interface newSettingsUpsert { /** @@ -6286,6 +6287,111 @@ namespace forms { } } +/** + * Package template is a thin wrapper around the standard html/template + * and text/template packages that implements a convenient registry to + * load and cache templates on the fly concurrently. + * + * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. + * + * Example: + * + * ``` + * registry := template.NewRegistry() + * + * html1, err := registry.LoadFiles( + * // the files set wil be parsed only once and then cached + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "John"}) + * + * html2, err := registry.LoadFiles( + * // reuse the already parsed and cached files set + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "Jane"}) + * ``` + */ +namespace template { + interface newRegistry { + /** + * NewRegistry creates and initializes a new templates registry with + * some defaults (eg. global "raw" template function for unescaped HTML). + * + * Use the Registry.Load* methods to load templates into the registry. + */ + (): (Registry) + } + /** + * Registry defines a templates registry that is safe to be used by multiple goroutines. + * + * Use the Registry.Load* methods to load templates into the registry. + */ + interface Registry { + } + interface Registry { + /** + * AddFuncs registers new global template functions. + * + * The key of each map entry is the function name that will be used in the templates. + * If a function with the map entry name already exists it will be replaced with the new one. + * + * The value of each map entry is a function that must have either a + * single return value, or two return values of which the second has type error. + * + * Example: + * + * r.AddFuncs(map[string]any{ + * ``` + * "toUpper": func(str string) string { + * return strings.ToUppser(str) + * }, + * ... + * ``` + * }) + */ + addFuncs(funcs: _TygojaDict): (Registry) + } + interface Registry { + /** + * LoadFiles caches (if not already) the specified filenames set as a + * single template and returns a ready to use Renderer instance. + * + * There must be at least 1 filename specified. + */ + loadFiles(...filenames: string[]): (Renderer) + } + interface Registry { + /** + * LoadString caches (if not already) the specified inline string as a + * single template and returns a ready to use Renderer instance. + */ + loadString(text: string): (Renderer) + } + interface Registry { + /** + * LoadFS caches (if not already) the specified fs and globPatterns + * pair as single template and returns a ready to use Renderer instance. + * + * There must be at least 1 file matching the provided globPattern(s) + * (note that most file names serves as glob patterns matching themselves). + */ + loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) + } + /** + * Renderer defines a single parsed template. + */ + interface Renderer { + } + interface Renderer { + /** + * Render executes the template with the specified data as the dot object + * and returns the result as plain string. + */ + render(data: any): string + } +} + /** * Package apis implements the default PocketBase api services and middlewares. */ @@ -6623,8 +6729,8 @@ namespace pocketbase { /** * appWrapper serves as a private CoreApp instance wrapper. */ - type _subPiAkl = CoreApp - interface appWrapper extends _subPiAkl { + type _subHLGcy = CoreApp + interface appWrapper extends _subHLGcy { } /** * PocketBase defines a PocketBase app launcher. @@ -6632,8 +6738,8 @@ namespace pocketbase { * It implements [CoreApp] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _subxPati = appWrapper - interface PocketBase extends _subxPati { + type _subWwBfH = appWrapper + interface PocketBase extends _subWwBfH { /** * RootCmd is the main console command */ @@ -6716,111 +6822,6 @@ namespace pocketbase { } } -/** - * Package template is a thin wrapper around the standard html/template - * and text/template packages that implements a convenient registry to - * load and cache templates on the fly concurrently. - * - * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. - * - * Example: - * - * ``` - * registry := template.NewRegistry() - * - * html1, err := registry.LoadFiles( - * // the files set wil be parsed only once and then cached - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "John"}) - * - * html2, err := registry.LoadFiles( - * // reuse the already parsed and cached files set - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "Jane"}) - * ``` - */ -namespace template { - interface newRegistry { - /** - * NewRegistry creates and initializes a new templates registry with - * some defaults (eg. global "raw" template function for unescaped HTML). - * - * Use the Registry.Load* methods to load templates into the registry. - */ - (): (Registry) - } - /** - * Registry defines a templates registry that is safe to be used by multiple goroutines. - * - * Use the Registry.Load* methods to load templates into the registry. - */ - interface Registry { - } - interface Registry { - /** - * AddFuncs registers new global template functions. - * - * The key of each map entry is the function name that will be used in the templates. - * If a function with the map entry name already exists it will be replaced with the new one. - * - * The value of each map entry is a function that must have either a - * single return value, or two return values of which the second has type error. - * - * Example: - * - * r.AddFuncs(map[string]any{ - * ``` - * "toUpper": func(str string) string { - * return strings.ToUppser(str) - * }, - * ... - * ``` - * }) - */ - addFuncs(funcs: _TygojaDict): (Registry) - } - interface Registry { - /** - * LoadFiles caches (if not already) the specified filenames set as a - * single template and returns a ready to use Renderer instance. - * - * There must be at least 1 filename specified. - */ - loadFiles(...filenames: string[]): (Renderer) - } - interface Registry { - /** - * LoadString caches (if not already) the specified inline string as a - * single template and returns a ready to use Renderer instance. - */ - loadString(text: string): (Renderer) - } - interface Registry { - /** - * LoadFS caches (if not already) the specified fs and globPatterns - * pair as single template and returns a ready to use Renderer instance. - * - * There must be at least 1 file matching the provided globPattern(s) - * (note that most file names serves as glob patterns matching themselves). - */ - loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) - } - /** - * Renderer defines a single parsed template. - */ - interface Renderer { - } - interface Renderer { - /** - * Render executes the template with the specified data as the dot object - * and returns the result as plain string. - */ - render(data: any): string - } -} - /** * Package io provides basic interfaces to I/O primitives. * Its primary job is to wrap existing implementations of such primitives, @@ -6878,91 +6879,6 @@ namespace io { } } -/** - * Package bytes implements functions for the manipulation of byte slices. - * It is analogous to the facilities of the [strings] package. - */ -namespace bytes { - /** - * A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, - * io.ByteScanner, and io.RuneScanner interfaces by reading from - * a byte slice. - * Unlike a Buffer, a Reader is read-only and supports seeking. - * The zero value for Reader operates like a Reader of an empty slice. - */ - interface Reader { - } - interface Reader { - /** - * Len returns the number of bytes of the unread portion of the - * slice. - */ - len(): number - } - interface Reader { - /** - * Size returns the original length of the underlying byte slice. - * Size is the number of bytes available for reading via ReadAt. - * The result is unaffected by any method calls except Reset. - */ - size(): number - } - interface Reader { - /** - * Read implements the io.Reader interface. - */ - read(b: string|Array): number - } - interface Reader { - /** - * ReadAt implements the io.ReaderAt interface. - */ - readAt(b: string|Array, off: number): number - } - interface Reader { - /** - * ReadByte implements the io.ByteReader interface. - */ - readByte(): number - } - interface Reader { - /** - * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the io.RuneReader interface. - */ - readRune(): [number, number] - } - interface Reader { - /** - * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. - */ - unreadRune(): void - } - interface Reader { - /** - * Seek implements the io.Seeker interface. - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * WriteTo implements the io.WriterTo interface. - */ - writeTo(w: io.Writer): number - } - interface Reader { - /** - * Reset resets the Reader to be reading from b. - */ - reset(b: string|Array): void - } -} - /** * Package syscall contains an interface to the low-level operating system * primitives. The details vary depending on the underlying system, and @@ -7669,169 +7585,6 @@ namespace time { } } -/** - * Package context defines the Context type, which carries deadlines, - * cancellation signals, and other request-scoped values across API boundaries - * and between processes. - * - * Incoming requests to a server should create a [Context], and outgoing - * calls to servers should accept a Context. The chain of function - * calls between them must propagate the Context, optionally replacing - * it with a derived Context created using [WithCancel], [WithDeadline], - * [WithTimeout], or [WithValue]. When a Context is canceled, all - * Contexts derived from it are also canceled. - * - * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a - * Context (the parent) and return a derived Context (the child) and a - * [CancelFunc]. Calling the CancelFunc cancels the child and its - * children, removes the parent's reference to the child, and stops - * any associated timers. Failing to call the CancelFunc leaks the - * child and its children until the parent is canceled or the timer - * fires. The go vet tool checks that CancelFuncs are used on all - * control-flow paths. - * - * The [WithCancelCause] function returns a [CancelCauseFunc], which - * takes an error and records it as the cancellation cause. Calling - * [Cause] on the canceled context or any of its children retrieves - * the cause. If no cause is specified, Cause(ctx) returns the same - * value as ctx.Err(). - * - * Programs that use Contexts should follow these rules to keep interfaces - * consistent across packages and enable static analysis tools to check context - * propagation: - * - * Do not store Contexts inside a struct type; instead, pass a Context - * explicitly to each function that needs it. The Context should be the first - * parameter, typically named ctx: - * - * ``` - * func DoSomething(ctx context.Context, arg Arg) error { - * // ... use ctx ... - * } - * ``` - * - * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] - * if you are unsure about which Context to use. - * - * Use context Values only for request-scoped data that transits processes and - * APIs, not for passing optional parameters to functions. - * - * The same Context may be passed to functions running in different goroutines; - * Contexts are safe for simultaneous use by multiple goroutines. - * - * See https://blog.golang.org/context for example code for a server that uses - * Contexts. - */ -namespace context { - /** - * A Context carries a deadline, a cancellation signal, and other values across - * API boundaries. - * - * Context's methods may be called by multiple goroutines simultaneously. - */ - interface Context { - [key:string]: any; - /** - * Deadline returns the time when work done on behalf of this context - * should be canceled. Deadline returns ok==false when no deadline is - * set. Successive calls to Deadline return the same results. - */ - deadline(): [time.Time, boolean] - /** - * Done returns a channel that's closed when work done on behalf of this - * context should be canceled. Done may return nil if this context can - * never be canceled. Successive calls to Done return the same value. - * The close of the Done channel may happen asynchronously, - * after the cancel function returns. - * - * WithCancel arranges for Done to be closed when cancel is called; - * WithDeadline arranges for Done to be closed when the deadline - * expires; WithTimeout arranges for Done to be closed when the timeout - * elapses. - * - * Done is provided for use in select statements: - * - * // Stream generates values with DoSomething and sends them to out - * // until DoSomething returns an error or ctx.Done is closed. - * func Stream(ctx context.Context, out chan<- Value) error { - * for { - * v, err := DoSomething(ctx) - * if err != nil { - * return err - * } - * select { - * case <-ctx.Done(): - * return ctx.Err() - * case out <- v: - * } - * } - * } - * - * See https://blog.golang.org/pipelines for more examples of how to use - * a Done channel for cancellation. - */ - done(): undefined - /** - * If Done is not yet closed, Err returns nil. - * If Done is closed, Err returns a non-nil error explaining why: - * Canceled if the context was canceled - * or DeadlineExceeded if the context's deadline passed. - * After Err returns a non-nil error, successive calls to Err return the same error. - */ - err(): void - /** - * Value returns the value associated with this context for key, or nil - * if no value is associated with key. Successive calls to Value with - * the same key returns the same result. - * - * Use context values only for request-scoped data that transits - * processes and API boundaries, not for passing optional parameters to - * functions. - * - * A key identifies a specific value in a Context. Functions that wish - * to store values in Context typically allocate a key in a global - * variable then use that key as the argument to context.WithValue and - * Context.Value. A key can be any type that supports equality; - * packages should define keys as an unexported type to avoid - * collisions. - * - * Packages that define a Context key should provide type-safe accessors - * for the values stored using that key: - * - * ``` - * // Package user defines a User type that's stored in Contexts. - * package user - * - * import "context" - * - * // User is the type of value stored in the Contexts. - * type User struct {...} - * - * // key is an unexported type for keys defined in this package. - * // This prevents collisions with keys defined in other packages. - * type key int - * - * // userKey is the key for user.User values in Contexts. It is - * // unexported; clients use user.NewContext and user.FromContext - * // instead of using this key directly. - * var userKey key - * - * // NewContext returns a new Context that carries value u. - * func NewContext(ctx context.Context, u *User) context.Context { - * return context.WithValue(ctx, userKey, u) - * } - * - * // FromContext returns the User value stored in ctx, if any. - * func FromContext(ctx context.Context) (*User, bool) { - * u, ok := ctx.Value(userKey).(*User) - * return u, ok - * } - * ``` - */ - value(key: any): any - } -} - /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -8027,2080 +7780,250 @@ namespace fs { } /** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. + * Package bytes implements functions for the manipulation of byte slices. + * It is analogous to the facilities of the [strings] package. */ -namespace cobra { - interface Command { - /** - * GenBashCompletion generates bash completion file and writes to the passed writer. - */ - genBashCompletion(w: io.Writer): void - } - interface Command { - /** - * GenBashCompletionFile generates bash completion file. - */ - genBashCompletionFile(filename: string): void - } - interface Command { - /** - * GenBashCompletionFileV2 generates Bash completion version 2. - */ - genBashCompletionFileV2(filename: string, includeDesc: boolean): void - } - interface Command { - /** - * GenBashCompletionV2 generates Bash completion file version 2 - * and writes it to the passed writer. - */ - genBashCompletionV2(w: io.Writer, includeDesc: boolean): void - } - // @ts-ignore - import flag = pflag +namespace bytes { /** - * 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. + * A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, + * io.ByteScanner, and io.RuneScanner interfaces by reading from + * a byte slice. + * Unlike a Buffer, a Reader is read-only and supports seeking. + * The zero value for Reader operates like a Reader of an empty slice. */ - interface Command { - /** - * 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 - */ - use: string - /** - * Aliases is an array of aliases that can be used instead of the first word in Use. - */ - aliases: Array - /** - * SuggestFor is an array of command names for which this command will be suggested - - * similar to aliases but only suggests. - */ - suggestFor: Array - /** - * Short is the short description shown in the 'help' output. - */ - short: string - /** - * The group id under which this subcommand is grouped in the 'help' output of its parent. - */ - groupID: string - /** - * Long is the long message shown in the 'help ' output. - */ - long: string - /** - * Example is examples of how to use the command. - */ - example: string - /** - * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions - */ - validArgs: Array - /** - * 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. - */ - validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] - /** - * Expected arguments - */ - args: PositionalArgs - /** - * ArgAliases is List of aliases for ValidArgs. - * These are not suggested to the user in the shell completion, - * but accepted if entered manually. - */ - argAliases: Array - /** - * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - * For portability with other shells, it is recommended to instead use ValidArgsFunction - */ - bashCompletionFunction: string - /** - * Deprecated defines, if this command is deprecated and should print this string when used. - */ - deprecated: string - /** - * Annotations are key/value pairs that can be used by applications to identify or - * group commands or set special options. - */ - annotations: _TygojaDict - /** - * 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. - */ - version: string - /** - * 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. - * The *PreRun and *PostRun functions will only be executed if the Run function of the current - * command has been declared. - * - * PersistentPreRun: children of this command will inherit and execute. - */ - persistentPreRun: (cmd: Command, args: Array) => void - /** - * PersistentPreRunE: PersistentPreRun but returns an error. - */ - persistentPreRunE: (cmd: Command, args: Array) => void - /** - * PreRun: children of this command will not inherit. - */ - preRun: (cmd: Command, args: Array) => void - /** - * PreRunE: PreRun but returns an error. - */ - preRunE: (cmd: Command, args: Array) => void - /** - * Run: Typically the actual work function. Most commands will only implement this. - */ - run: (cmd: Command, args: Array) => void - /** - * RunE: Run but returns an error. - */ - runE: (cmd: Command, args: Array) => void - /** - * PostRun: run after the Run command. - */ - postRun: (cmd: Command, args: Array) => void - /** - * PostRunE: PostRun but returns an error. - */ - 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 Command { - /** - * 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. - * - * 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. - */ - context(): context.Context - } - interface Command { - /** - * SetContext sets context for the command. This context will be overwritten by - * Command.ExecuteContext or Command.ExecuteContextC. - */ - setContext(ctx: context.Context): void - } - interface Command { - /** - * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden - * particularly useful when testing. - */ - setArgs(a: Array): void - } - interface Command { - /** - * SetOutput sets the destination for usage and error messages. - * If output is nil, os.Stderr is used. - * Deprecated: Use SetOut and/or SetErr instead - */ - setOutput(output: io.Writer): void - } - interface Command { - /** - * SetOut sets the destination for usage messages. - * If newOut is nil, os.Stdout is used. - */ - setOut(newOut: io.Writer): void - } - interface Command { - /** - * SetErr sets the destination for error messages. - * If newErr is nil, os.Stderr is used. - */ - setErr(newErr: io.Writer): void - } - interface Command { - /** - * SetIn sets the source for input data - * If newIn is nil, os.Stdin is used. - */ - setIn(newIn: io.Reader): void - } - interface Command { - /** - * SetUsageFunc sets usage function. Usage can be defined by application. - */ - setUsageFunc(f: (_arg0: Command) => void): void - } - interface Command { - /** - * SetUsageTemplate sets usage template. Can be defined by Application. - */ - setUsageTemplate(s: string): void - } - interface Command { - /** - * SetFlagErrorFunc sets a function to generate an error when flag parsing - * fails. - */ - setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void - } - interface Command { - /** - * SetHelpFunc sets help function. Can be defined by Application. - */ - setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void - } - interface Command { - /** - * SetHelpCommand sets help command. - */ - setHelpCommand(cmd: Command): void - } - interface Command { - /** - * SetHelpCommandGroupID sets the group id of the help command. - */ - setHelpCommandGroupID(groupID: string): void - } - interface Command { - /** - * SetCompletionCommandGroupID sets the group id of the completion command. - */ - setCompletionCommandGroupID(groupID: string): void - } - interface Command { - /** - * SetHelpTemplate sets help template to be used. Application can use it to set custom template. - */ - setHelpTemplate(s: string): void - } - interface Command { - /** - * SetVersionTemplate sets version template to be used. Application can use it to set custom template. - */ - setVersionTemplate(s: string): void - } - interface Command { - /** - * SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. - */ - setErrPrefix(s: string): void - } - interface Command { - /** - * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. - * The user should not have a cyclic dependency on commands. - */ - setGlobalNormalizationFunc(n: (f: any, name: string) => any): void - } - interface Command { - /** - * OutOrStdout returns output to stdout. - */ - outOrStdout(): io.Writer - } - interface Command { - /** - * OutOrStderr returns output to stderr - */ - outOrStderr(): io.Writer - } - interface Command { - /** - * ErrOrStderr returns output to stderr - */ - errOrStderr(): io.Writer - } - interface Command { - /** - * InOrStdin returns input to stdin - */ - inOrStdin(): io.Reader - } - interface Command { - /** - * UsageFunc returns either the function set by SetUsageFunc for this command - * or a parent, or it returns a default usage function. - */ - usageFunc(): (_arg0: Command) => void - } - interface Command { - /** - * Usage puts out the usage for the command. - * Used when a user provides invalid input. - * Can be defined by user by overriding UsageFunc. - */ - usage(): void - } - interface Command { - /** - * HelpFunc returns either the function set by SetHelpFunc for this command - * or a parent, or it returns a function with default help behavior. - */ - helpFunc(): (_arg0: Command, _arg1: Array) => void - } - interface Command { - /** - * Help puts out the help for the command. - * Used when a user calls help [command]. - * Can be defined by user by overriding HelpFunc. - */ - help(): void - } - interface Command { - /** - * UsageString returns usage string. - */ - usageString(): string - } - interface Command { - /** - * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this - * command or a parent, or it returns a function which returns the original - * error. - */ - flagErrorFunc(): (_arg0: Command, _arg1: Error) => void - } - interface Command { - /** - * UsagePadding return padding for the usage. - */ - usagePadding(): number - } - interface Command { - /** - * CommandPathPadding return padding for the command path. - */ - commandPathPadding(): number - } - interface Command { - /** - * NamePadding returns padding for the name. - */ - namePadding(): number - } - interface Command { - /** - * UsageTemplate returns usage template for the command. - */ - usageTemplate(): string - } - interface Command { - /** - * HelpTemplate return help template for the command. - */ - helpTemplate(): string - } - interface Command { - /** - * VersionTemplate return version template for the command. - */ - versionTemplate(): string - } - interface Command { - /** - * ErrPrefix return error message prefix for the command - */ - errPrefix(): string - } - interface Command { - /** - * Find the target command given the args and command tree - * Meant to be run on the highest node. Only searches down. - */ - find(args: Array): [(Command), Array] - } - interface Command { - /** - * Traverse the command tree to find the command, and parse args for - * each parent. - */ - traverse(args: Array): [(Command), Array] - } - interface Command { - /** - * SuggestionsFor provides suggestions for the typedName. - */ - suggestionsFor(typedName: string): Array - } - interface Command { - /** - * VisitParents visits all parents of the command and invokes fn on each parent. - */ - visitParents(fn: (_arg0: Command) => void): void - } - interface Command { - /** - * Root finds root command. - */ - root(): (Command) - } - interface Command { - /** - * ArgsLenAtDash will return the length of c.Flags().Args at the moment - * when a -- was found during args parsing. - */ - argsLenAtDash(): number - } - interface Command { - /** - * 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. - */ - executeContext(ctx: context.Context): void - } - interface Command { - /** - * Execute uses the args (os.Args[1:] by default) - * and run through the command tree finding appropriate matches - * for commands and then corresponding flags. - */ - execute(): void - } - interface Command { - /** - * 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. - */ - executeContextC(ctx: context.Context): (Command) - } - interface Command { - /** - * ExecuteC executes the command. - */ - executeC(): (Command) - } - interface Command { - validateArgs(args: Array): void - } - interface Command { - /** - * ValidateRequiredFlags validates all required flags are present and returns an error otherwise - */ - validateRequiredFlags(): void - } - interface Command { - /** - * 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. - */ - initDefaultHelpFlag(): void - } - interface Command { - /** - * 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. - */ - initDefaultVersionFlag(): void - } - interface Command { - /** - * 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. - */ - initDefaultHelpCmd(): void - } - interface Command { - /** - * ResetCommands delete parent, subcommand and help command from c. - */ - resetCommands(): void - } - interface Command { - /** - * Commands returns a sorted slice of child commands. - */ - commands(): Array<(Command | undefined)> - } - interface Command { - /** - * AddCommand adds one or more commands to this parent command. - */ - addCommand(...cmds: (Command | undefined)[]): void - } - interface Command { - /** - * Groups returns a slice of child command groups. - */ - groups(): Array<(Group | undefined)> - } - interface Command { - /** - * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group - */ - allChildCommandsHaveGroup(): boolean - } - interface Command { - /** - * ContainsGroup return if groupID exists in the list of command groups. - */ - containsGroup(groupID: string): boolean - } - interface Command { - /** - * AddGroup adds one or more command groups to this parent command. - */ - addGroup(...groups: (Group | undefined)[]): void - } - interface Command { - /** - * RemoveCommand removes one or more commands from a parent command. - */ - removeCommand(...cmds: (Command | undefined)[]): void - } - interface Command { - /** - * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. - */ - print(...i: { - }[]): void - } - interface Command { - /** - * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. - */ - println(...i: { - }[]): void - } - interface Command { - /** - * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. - */ - printf(format: string, ...i: { - }[]): void - } - interface Command { - /** - * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. - */ - printErr(...i: { - }[]): void - } - interface Command { - /** - * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. - */ - printErrln(...i: { - }[]): void - } - interface Command { - /** - * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. - */ - printErrf(format: string, ...i: { - }[]): void - } - interface Command { - /** - * CommandPath returns the full path to this command. - */ - commandPath(): string - } - interface Command { - /** - * UseLine puts out the full usage for a given command (including parents). - */ - useLine(): string - } - interface Command { - /** - * DebugFlags used to determine which flags have been assigned to which commands - * and which persist. - * nolint:goconst - */ - debugFlags(): void - } - interface Command { - /** - * Name returns the command's name: the first word in the use line. - */ - name(): string - } - interface Command { - /** - * HasAlias determines if a given string is an alias of the command. - */ - hasAlias(s: string): boolean - } - interface Command { - /** - * 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. - */ - calledAs(): string - } - interface Command { - /** - * NameAndAliases returns a list of the command name and all aliases - */ - nameAndAliases(): string - } - interface Command { - /** - * HasExample determines if the command has example. - */ - hasExample(): boolean - } - interface Command { - /** - * Runnable determines if the command is itself runnable. - */ - runnable(): boolean - } - interface Command { - /** - * HasSubCommands determines if the command has children commands. - */ - hasSubCommands(): boolean - } - interface Command { - /** - * IsAvailableCommand determines if a command is available as a non-help command - * (this includes all non deprecated/hidden commands). - */ - isAvailableCommand(): boolean - } - interface Command { - /** - * 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. - */ - isAdditionalHelpTopicCommand(): boolean - } - interface Command { - /** - * 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'. - */ - hasHelpSubCommands(): boolean - } - interface Command { - /** - * HasAvailableSubCommands determines if a command has available sub commands that - * need to be shown in the usage/help default template under 'available commands'. - */ - hasAvailableSubCommands(): boolean - } - interface Command { - /** - * HasParent determines if the command is a child command. - */ - hasParent(): boolean - } - interface Command { - /** - * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. - */ - globalNormalizationFunc(): (f: any, name: string) => any - } - interface Command { - /** - * Flags returns the complete FlagSet that applies - * to this command (local and persistent declared here and by all parents). - */ - flags(): (any) - } - interface Command { - /** - * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. - */ - localNonPersistentFlags(): (any) - } - interface Command { - /** - * LocalFlags returns the local FlagSet specifically set in the current command. - */ - localFlags(): (any) - } - interface Command { - /** - * InheritedFlags returns all flags which were inherited from parent commands. - */ - inheritedFlags(): (any) - } - interface Command { - /** - * NonInheritedFlags returns all flags which were not inherited from parent commands. - */ - nonInheritedFlags(): (any) - } - interface Command { - /** - * PersistentFlags returns the persistent FlagSet specifically set in the current command. - */ - persistentFlags(): (any) - } - interface Command { - /** - * ResetFlags deletes all flags from command. - */ - resetFlags(): void - } - interface Command { - /** - * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). - */ - hasFlags(): boolean - } - interface Command { - /** - * HasPersistentFlags checks if the command contains persistent flags. - */ - hasPersistentFlags(): boolean - } - interface Command { - /** - * HasLocalFlags checks if the command has flags specifically declared locally. - */ - hasLocalFlags(): boolean - } - interface Command { - /** - * HasInheritedFlags checks if the command has flags inherited from its parent command. - */ - hasInheritedFlags(): boolean - } - interface Command { - /** - * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire - * structure) which are not hidden or deprecated. - */ - hasAvailableFlags(): boolean - } - interface Command { - /** - * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. - */ - hasAvailablePersistentFlags(): boolean - } - interface Command { - /** - * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden - * or deprecated. - */ - hasAvailableLocalFlags(): boolean - } - interface Command { - /** - * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are - * not hidden or deprecated. - */ - hasAvailableInheritedFlags(): boolean - } - interface Command { - /** - * Flag climbs up the command tree looking for matching flag. - */ - flag(name: string): (any) - } - interface Command { - /** - * ParseFlags parses persistent flag tree and local flags. - */ - parseFlags(args: Array): void - } - interface Command { - /** - * Parent returns a commands parent command. - */ - parent(): (Command) - } - interface Command { - /** - * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. - */ - registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void - } - interface Command { - /** - * GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. - */ - getFlagCompletionFunc(flagName: string): [(_arg0: Command, _arg1: Array, _arg2: string) => [Array, ShellCompDirective], boolean] - } - interface Command { - /** - * 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. - */ - initDefaultCompletionCmd(): void - } - interface Command { - /** - * GenFishCompletion generates fish completion file and writes to the passed writer. - */ - genFishCompletion(w: io.Writer, includeDesc: boolean): void - } - interface Command { - /** - * GenFishCompletionFile generates fish completion file. - */ - genFishCompletionFile(filename: string, includeDesc: boolean): void - } - interface Command { - /** - * 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. - */ - markFlagsRequiredTogether(...flagNames: string[]): void - } - interface Command { - /** - * MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors - * if the command is invoked without at least one flag from the given set of flags. - */ - markFlagsOneRequired(...flagNames: string[]): void - } - interface Command { - /** - * 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. - */ - markFlagsMutuallyExclusive(...flagNames: string[]): void - } - interface Command { - /** - * ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the - * first error encountered. - */ - validateFlagGroups(): void - } - interface Command { - /** - * GenPowerShellCompletionFile generates powershell completion file without descriptions. - */ - genPowerShellCompletionFile(filename: string): void - } - interface Command { - /** - * GenPowerShellCompletion generates powershell completion file without descriptions - * and writes it to the passed writer. - */ - genPowerShellCompletion(w: io.Writer): void - } - interface Command { - /** - * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. - */ - genPowerShellCompletionFileWithDesc(filename: string): void - } - interface Command { - /** - * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions - * and writes it to the passed writer. - */ - genPowerShellCompletionWithDesc(w: io.Writer): void - } - interface Command { - /** - * 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. - */ - markFlagRequired(name: string): void - } - interface Command { - /** - * 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. - */ - markPersistentFlagRequired(name: string): void + interface Reader { } - interface Command { + interface Reader { /** - * MarkFlagFilename instructs the various shell completion implementations to - * limit completions for the named flag to the specified file extensions. + * Len returns the number of bytes of the unread portion of the + * slice. */ - markFlagFilename(name: string, ...extensions: string[]): void + len(): number } - interface Command { + interface Reader { /** - * 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. - * - * 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. + * 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. */ - markFlagCustom(name: string, f: string): void + size(): number } - interface Command { + interface Reader { /** - * MarkPersistentFlagFilename instructs the various shell completion - * implementations to limit completions for the named persistent flag to the - * specified file extensions. + * Read implements the io.Reader interface. */ - markPersistentFlagFilename(name: string, ...extensions: string[]): void + read(b: string|Array): number } - interface Command { + interface Reader { /** - * MarkFlagDirname instructs the various shell completion implementations to - * limit completions for the named flag to directory names. + * ReadAt implements the io.ReaderAt interface. */ - markFlagDirname(name: string): void + readAt(b: string|Array, off: number): number } - interface Command { + interface Reader { /** - * MarkPersistentFlagDirname instructs the various shell completion - * implementations to limit completions for the named persistent flag to - * directory names. + * ReadByte implements the io.ByteReader interface. */ - markPersistentFlagDirname(name: string): void + readByte(): number } - interface Command { + interface Reader { /** - * GenZshCompletionFile generates zsh completion file including descriptions. + * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. */ - genZshCompletionFile(filename: string): void + unreadByte(): void } - interface Command { + interface Reader { /** - * GenZshCompletion generates zsh completion file including descriptions - * and writes it to the passed writer. + * ReadRune implements the io.RuneReader interface. */ - genZshCompletion(w: io.Writer): void + readRune(): [number, number] } - interface Command { + interface Reader { /** - * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. */ - genZshCompletionFileNoDesc(filename: string): void + unreadRune(): void } - interface Command { + interface Reader { /** - * GenZshCompletionNoDesc generates zsh completion file without descriptions - * and writes it to the passed writer. + * Seek implements the io.Seeker interface. */ - genZshCompletionNoDesc(w: io.Writer): void + seek(offset: number, whence: number): number } - interface Command { + interface Reader { /** - * 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 + * WriteTo implements the io.WriterTo interface. */ - markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void + writeTo(w: io.Writer): number } - interface Command { + interface Reader { /** - * 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). - * - * Deprecated + * Reset resets the Reader to be reading from b. */ - markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void + reset(b: string|Array): void } } /** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * Package context defines the Context type, which carries deadlines, + * cancellation signals, and other request-scoped values across API boundaries + * and between processes. * - * See README.md for more info. + * Incoming requests to a server should create a [Context], and outgoing + * calls to servers should accept a Context. The chain of function + * calls between them must propagate the Context, optionally replacing + * it with a derived Context created using [WithCancel], [WithDeadline], + * [WithTimeout], or [WithValue]. When a Context is canceled, all + * Contexts derived from it are also canceled. + * + * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a + * Context (the parent) and return a derived Context (the child) and a + * [CancelFunc]. Calling the CancelFunc cancels the child and its + * children, removes the parent's reference to the child, and stops + * any associated timers. Failing to call the CancelFunc leaks the + * child and its children until the parent is canceled or the timer + * fires. The go vet tool checks that CancelFuncs are used on all + * control-flow paths. + * + * The [WithCancelCause] function returns a [CancelCauseFunc], which + * takes an error and records it as the cancellation cause. Calling + * [Cause] on the canceled context or any of its children retrieves + * the cause. If no cause is specified, Cause(ctx) returns the same + * value as ctx.Err(). + * + * Programs that use Contexts should follow these rules to keep interfaces + * consistent across packages and enable static analysis tools to check context + * propagation: + * + * Do not store Contexts inside a struct type; instead, pass a Context + * explicitly to each function that needs it. The Context should be the first + * parameter, typically named ctx: + * + * ``` + * func DoSomething(ctx context.Context, arg Arg) error { + * // ... use ctx ... + * } + * ``` + * + * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] + * if you are unsure about which Context to use. + * + * Use context Values only for request-scoped data that transits processes and + * APIs, not for passing optional parameters to functions. + * + * The same Context may be passed to functions running in different goroutines; + * Contexts are safe for simultaneous use by multiple goroutines. + * + * See https://blog.golang.org/context for example code for a server that uses + * Contexts. */ -namespace jwt { +namespace context { /** - * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. - * This is the default claims type if you don't supply one - */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { - /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyAudience(cmp: string, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. - */ - verifyExpiresAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. - */ - verifyIssuedAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. - */ - verifyNotBefore(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyIssuer(cmp: string, req: boolean): boolean - } - interface MapClaims { - /** - * Valid validates time based claims "exp, iat, nbf". - * There is no accounting for clock skew. - * As well, if any of the above claims are not in the token, it will still - * be considered a valid claim. - */ - valid(): void - } -} - -/** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - * - * # Limits - * - * To protect against malicious inputs, this package sets limits on the size - * of the MIME data it processes. - * - * Reader.NextPart and Reader.NextRawPart limit the number of headers in a - * part to 10000 and Reader.ReadForm limits the total number of headers in all - * FileHeaders to 10000. - * These limits may be adjusted with the GODEBUG=multipartmaxheaders= - * setting. - * - * Reader.ReadForm further limits the number of parts in a form to 1000. - * This limit may be adjusted with the GODEBUG=multipartmaxparts= - * setting. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -namespace multipart { - /** - * A FileHeader describes a file part of a multipart request. - */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number - } - interface FileHeader { - /** - * Open opens and returns the FileHeader's associated File. - */ - open(): File - } -} - -/** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The caller must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * # Clients and Transports - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * # Servers - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * # HTTP/2 - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG settings are - * currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { - // @ts-ignore - import mathrand = rand - // @ts-ignore - import urlpkg = url - /** - * A Request represents an HTTP request received by a server - * or to be sent by a client. + * A Context carries a deadline, a cancellation signal, and other values across + * API boundaries. * - * 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. + * Context's methods may be called by multiple goroutines simultaneously. */ - interface Request { - /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. - * - * Go's HTTP client does not support sending a request with - * the CONNECT method. See the documentation on Transport for - * details. - */ - method: string - /** - * URL specifies either the URI being requested (for server - * requests) or the URL to access (for client requests). - * - * For server requests, the URL is parsed from the URI - * supplied on the Request-Line as stored in RequestURI. For - * most requests, fields other than Path and RawQuery will be - * empty. (See RFC 7230, Section 5.3) - * - * For client requests, the URL's Host specifies the server to - * connect to, while the Request's Host field optionally - * specifies the Host header value to send in the HTTP - * request. - */ - url?: url.URL - /** - * The protocol version for incoming server requests. - * - * For client requests, these fields are ignored. The HTTP - * client code always uses either HTTP/1.1 or HTTP/2. - * See the docs on Transport for details. - */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 - /** - * Header contains the request header fields either received - * by the server or to be sent by the client. - * - * If a server received a request with header lines, - * - * ``` - * Host: example.com - * accept-encoding: gzip, deflate - * Accept-Language: en-us - * fOO: Bar - * foo: two - * ``` - * - * then - * - * ``` - * Header = map[string][]string{ - * "Accept-Encoding": {"gzip, deflate"}, - * "Accept-Language": {"en-us"}, - * "Foo": {"Bar", "two"}, - * } - * ``` - * - * For incoming requests, the Host header is promoted to the - * Request.Host field and removed from the Header map. - * - * HTTP defines that header names are case-insensitive. The - * request parser implements this by using CanonicalHeaderKey, - * making the first character and any characters following a - * hyphen uppercase and the rest lowercase. - * - * For client requests, certain headers such as Content-Length - * and Connection are automatically written when needed and - * values in Header may be ignored. See the documentation - * for the Request.Write method. - */ - header: Header - /** - * Body is the request's body. - * - * For client requests, a nil body means the request has no - * body, such as a GET request. The HTTP Client's Transport - * is responsible for calling the Close method. - * - * For server requests, the Request Body is always non-nil - * but will return EOF immediately when no body is present. - * The Server will close the request body. The ServeHTTP - * Handler does not need to. - * - * Body must allow Read to be called concurrently with Close. - * In particular, calling Close should unblock a Read waiting - * for input. - */ - body: io.ReadCloser - /** - * GetBody defines an optional func to return a new copy of - * Body. It is used for client requests when a redirect requires - * reading the body more than once. Use of GetBody still - * requires setting Body. - * - * For server requests, it is unused. - */ - getBody: () => io.ReadCloser - /** - * ContentLength records the length of the associated content. - * The value -1 indicates that the length is unknown. - * Values >= 0 indicate that the given number of bytes may - * be read from Body. - * - * For client requests, a value of 0 with a non-nil Body is - * also treated as unknown. - */ - contentLength: number - /** - * TransferEncoding lists the transfer encodings from outermost to - * innermost. An empty list denotes the "identity" encoding. - * TransferEncoding can usually be ignored; chunked encoding is - * automatically added and removed as necessary when sending and - * receiving requests. - */ - transferEncoding: Array - /** - * Close indicates whether to close the connection after - * replying to this request (for servers) or after sending this - * request and reading its response (for clients). - * - * For server requests, the HTTP server handles this automatically - * and this field is not needed by Handlers. - * - * For client requests, setting this field prevents re-use of - * TCP connections between requests to the same hosts, as if - * Transport.DisableKeepAlives were set. - */ - close: boolean - /** - * For server requests, Host specifies the host on which the - * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this - * is either the value of the "Host" header or the host name - * given in the URL itself. For HTTP/2, it is the value of the - * ":authority" pseudo-header field. - * It may be of the form "host:port". For international domain - * names, Host may be in Punycode or Unicode form. Use - * golang.org/x/net/idna to convert it to either format if - * needed. - * To prevent DNS rebinding attacks, server Handlers should - * validate that the Host header has a value for which the - * Handler considers itself authoritative. The included - * ServeMux supports patterns registered to particular host - * names and thus protects its registered Handlers. - * - * For client requests, Host optionally overrides the Host - * header to send. If empty, the Request.Write method uses - * the value of URL.Host. Host may contain an international - * domain name. - */ - host: string - /** - * Form contains the parsed form data, including both the URL - * field's query parameters and the PATCH, POST, or PUT form data. - * This field is only available after ParseForm is called. - * The HTTP client ignores Form and uses Body instead. - */ - form: url.Values - /** - * PostForm contains the parsed form data from PATCH, POST - * or PUT body parameters. - * - * This field is only available after ParseForm is called. - * The HTTP client ignores PostForm and uses Body instead. - */ - postForm: url.Values - /** - * MultipartForm is the parsed multipart form, including file uploads. - * This field is only available after ParseMultipartForm is called. - * The HTTP client ignores MultipartForm and uses Body instead. - */ - multipartForm?: multipart.Form - /** - * Trailer specifies additional headers that are sent after the request - * body. - * - * For server requests, the Trailer map initially contains only the - * trailer keys, with nil values. (The client declares which trailers it - * will later send.) While the handler is reading from Body, it must - * not reference Trailer. After reading from Body returns EOF, Trailer - * can be read again and will contain non-nil values, if they were sent - * by the client. - * - * For client requests, Trailer must be initialized to a map containing - * the trailer keys to later send. The values may be nil or their final - * values. The ContentLength must be 0 or -1, to send a chunked request. - * After the HTTP request is sent the map values can be updated while - * the request body is read. Once the body returns EOF, the caller must - * not mutate Trailer. - * - * Few HTTP clients, servers, or proxies support HTTP trailers. - */ - trailer: Header - /** - * RemoteAddr allows HTTP servers and other software to record - * the network address that sent the request, usually for - * logging. This field is not filled in by ReadRequest and - * has no defined format. The HTTP server in this package - * sets RemoteAddr to an "IP:port" address before invoking a - * handler. - * This field is ignored by the HTTP client. - */ - remoteAddr: string - /** - * RequestURI is the unmodified request-target of the - * Request-Line (RFC 7230, Section 3.1.1) as sent by the client - * to a server. Usually the URL field should be used instead. - * It is an error to set this field in an HTTP client request. - */ - requestURI: string - /** - * TLS allows HTTP servers and other software to record - * information about the TLS connection on which the request - * was received. This field is not filled in by ReadRequest. - * The HTTP server in this package sets the field for - * TLS-enabled connections before invoking a handler; - * otherwise it leaves the field nil. - * This field is ignored by the HTTP client. - */ - tls?: any - /** - * Cancel is an optional channel whose closure indicates that the client - * request should be regarded as canceled. Not all implementations of - * RoundTripper may support Cancel. - * - * For server requests, this field is not applicable. - * - * Deprecated: Set the Request's context with NewRequestWithContext - * instead. If a Request's Cancel field and context are both - * set, it is undefined whether Cancel is respected. - */ - cancel: undefined - /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. - */ - response?: Response - } - interface Request { - /** - * Context returns the request's context. To change the context, use - * Clone or WithContext. - * - * The returned context is always non-nil; it defaults to the - * background context. - * - * For outgoing client requests, the context controls cancellation. - * - * For incoming server requests, the context is canceled when the - * client's connection closes, the request is canceled (with HTTP/2), - * or when the ServeHTTP method returns. - */ - context(): context.Context - } - interface Request { - /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. - * - * For outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. - * - * To create a new request with a context, use NewRequestWithContext. - * To make a deep copy of a request with a new context, use Request.Clone. - */ - withContext(ctx: context.Context): (Request) - } - interface Request { - /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. - * - * For an outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. - */ - clone(ctx: context.Context): (Request) - } - interface Request { - /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. - */ - protoAtLeast(major: number): boolean - } - interface Request { - /** - * UserAgent returns the client's User-Agent, if sent in the request. - */ - userAgent(): string - } - interface Request { - /** - * Cookies parses and returns the HTTP cookies sent with the request. - */ - cookies(): Array<(Cookie | undefined)> - } - interface Request { - /** - * Cookie returns the named cookie provided in the request or - * ErrNoCookie if not found. - * If multiple cookies match the given name, only one cookie will - * be returned. - */ - cookie(name: string): (Cookie) - } - interface Request { - /** - * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, - * AddCookie does not attach more than one Cookie header field. That - * means all cookies, if any, are written into the same line, - * separated by semicolon. - * AddCookie only sanitizes c's name and value, and does not sanitize - * a Cookie header already present in the request. - */ - addCookie(c: Cookie): void - } - interface Request { - /** - * Referer returns the referring URL, if sent in the request. - * - * Referer is misspelled as in the request itself, a mistake from the - * earliest days of HTTP. This value can also be fetched from the - * Header map as Header["Referer"]; the benefit of making it available - * as a method is that the compiler can diagnose programs that use the - * alternate (correct English) spelling req.Referrer() but cannot - * diagnose programs that use Header["Referrer"]. - */ - referer(): string - } - interface Request { - /** - * MultipartReader returns a MIME multipart reader if this is a - * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. - * Use this function instead of ParseMultipartForm to - * process the request body as a stream. - */ - multipartReader(): (multipart.Reader) - } - interface Request { - /** - * Write writes an HTTP/1.1 request, which is the header and body, in wire format. - * This method consults the following fields of the request: - * - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` - * - * If Body is present, Content-Length is <= 0 and TransferEncoding - * hasn't been set to "identity", Write adds "Transfer-Encoding: - * chunked" to the header. Body is closed after it is sent. - */ - write(w: io.Writer): void - } - interface Request { - /** - * WriteProxy is like Write but writes the request in the form - * expected by an HTTP proxy. In particular, WriteProxy writes the - * initial Request-URI line of the request with an absolute URI, per - * section 5.3 of RFC 7230, including the scheme and host. - * In either case, WriteProxy also writes a Host header, using - * either r.Host or r.URL.Host. - */ - writeProxy(w: io.Writer): void - } - interface Request { - /** - * BasicAuth returns the username and password provided in the request's - * Authorization header, if the request uses HTTP Basic Authentication. - * See RFC 2617, Section 2. - */ - basicAuth(): [string, boolean] - } - interface Request { - /** - * SetBasicAuth sets the request's Authorization header to use HTTP - * Basic Authentication with the provided username and password. - * - * With HTTP Basic Authentication the provided username and password - * are not encrypted. It should generally only be used in an HTTPS - * request. - * - * The username may not contain a colon. Some protocols may impose - * additional requirements on pre-escaping the username and - * password. For instance, when used with OAuth2, both arguments must - * be URL encoded first with url.QueryEscape. - */ - setBasicAuth(username: string): void - } - interface Request { - /** - * ParseForm populates r.Form and r.PostForm. - * - * For all requests, ParseForm parses the raw query from the URL and updates - * r.Form. - * - * For POST, PUT, and PATCH requests, it also reads the request body, parses it - * as a form and puts the results into both r.PostForm and r.Form. Request body - * parameters take precedence over URL query string values in r.Form. - * - * If the request Body's size has not already been limited by MaxBytesReader, - * the size is capped at 10MB. - * - * For other HTTP methods, or when the Content-Type is not - * application/x-www-form-urlencoded, the request Body is not read, and - * r.PostForm is initialized to a non-nil, empty value. - * - * ParseMultipartForm calls ParseForm automatically. - * ParseForm is idempotent. - */ - parseForm(): void - } - interface Request { - /** - * ParseMultipartForm parses a request body as multipart/form-data. - * The whole request body is parsed and up to a total of maxMemory bytes of - * its file parts are stored in memory, with the remainder stored on - * disk in temporary files. - * ParseMultipartForm calls ParseForm if necessary. - * If ParseForm returns an error, ParseMultipartForm returns it but also - * continues parsing the request body. - * After one call to ParseMultipartForm, subsequent calls have no effect. - */ - parseMultipartForm(maxMemory: number): void - } - interface Request { - /** - * FormValue returns the first value for the named component of the query. - * POST and PUT body parameters take precedence over URL query string values. - * FormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, FormValue returns the empty string. - * To access multiple values of the same key, call ParseForm and - * then inspect Request.Form directly. - */ - formValue(key: string): string - } - interface Request { - /** - * PostFormValue returns the first value for the named component of the POST, - * PATCH, or PUT request body. URL query parameters are ignored. - * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, PostFormValue returns the empty string. - */ - postFormValue(key: string): string - } - interface Request { - /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. - */ - formFile(key: string): [multipart.File, (multipart.FileHeader)] - } - /** - * 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 Context { [key:string]: any; /** - * 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. + * Deadline returns the time when work done on behalf of this context + * should be canceled. Deadline returns ok==false when no deadline is + * set. Successive calls to Deadline return the same results. */ - header(): Header + deadline(): [time.Time, boolean] /** - * Write writes the data to the connection as part of an HTTP reply. + * Done returns a channel that's closed when work done on behalf of this + * context should be canceled. Done may return nil if this context can + * never be canceled. Successive calls to Done return the same value. + * The close of the Done channel may happen asynchronously, + * after the cancel function returns. * - * 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. + * WithCancel arranges for Done to be closed when cancel is called; + * WithDeadline arranges for Done to be closed when the deadline + * expires; WithTimeout arranges for Done to be closed when the timeout + * elapses. * - * Depending on the HTTP protocol version and the client, calling - * Write or WriteHeader may prevent future reads on the - * Request.Body. For HTTP/1.x requests, handlers should read any - * needed request body data before writing the response. Once the - * headers have been flushed (due to either an explicit Flusher.Flush - * call or writing enough data to trigger a flush), the request body - * may be unavailable. For HTTP/2 requests, the Go HTTP server permits - * handlers to continue to read the request body while concurrently - * writing the response. However, such behavior may not be supported - * by all HTTP/2 clients. Handlers should read before writing if - * possible to maximize compatibility. - */ - write(_arg0: string|Array): number - /** - * WriteHeader sends an HTTP response header with the provided - * status code. + * Done is provided for use in select statements: * - * 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. + * // Stream generates values with DoSomething and sends them to out + * // until DoSomething returns an error or ctx.Done is closed. + * func Stream(ctx context.Context, out chan<- Value) error { + * for { + * v, err := DoSomething(ctx) + * if err != nil { + * return err + * } + * select { + * case <-ctx.Done(): + * return ctx.Err() + * case out <- v: + * } + * } + * } * - * 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. + * See https://blog.golang.org/pipelines for more examples of how to use + * a Done channel for cancellation. + */ + done(): undefined + /** + * If Done is not yet closed, Err returns nil. + * If Done is closed, Err returns a non-nil error explaining why: + * Canceled if the context was canceled + * or DeadlineExceeded if the context's deadline passed. + * After Err returns a non-nil error, successive calls to Err return the same error. + */ + err(): void + /** + * Value returns the value associated with this context for key, or nil + * if no value is associated with key. Successive calls to Value with + * the same key returns the same result. * - * The server will automatically send a 100 (Continue) header - * on the first read from the request body if the request has - * an "Expect: 100-continue" header. - */ - writeHeader(statusCode: number): void - } - /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. - */ - interface Server { - /** - * Addr optionally specifies the TCP address for the server to listen on, - * in the form "host:port". If empty, ":http" (port 80) is used. - * The service names are defined in RFC 6335 and assigned by IANA. - * See net.Dial for details of the address format. - */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil - /** - * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, - * otherwise responds with 200 OK and Content-Length: 0. - */ - disableGeneralOptionsHandler: boolean - /** - * TLSConfig optionally provides a TLS configuration for use - * by ServeTLS and ListenAndServeTLS. Note that this value is - * cloned by ServeTLS and ListenAndServeTLS, so it's not - * possible to modify the configuration with methods like - * tls.Config.SetSessionTicketKeys. To use - * SetSessionTicketKeys, use Server.Serve with a TLS Listener - * instead. - */ - tlsConfig?: any - /** - * ReadTimeout is the maximum duration for reading the entire - * request, including the body. A zero or negative value means - * there will be no timeout. + * Use context values only for request-scoped data that transits + * processes and API boundaries, not for passing optional parameters to + * functions. * - * Because ReadTimeout does not let Handlers make per-request - * decisions on each request body's acceptable deadline or - * upload rate, most users will prefer to use - * ReadHeaderTimeout. It is valid to use them both. - */ - readTimeout: time.Duration - /** - * ReadHeaderTimeout is the amount of time allowed to read - * request headers. The connection's read deadline is reset - * after reading the headers and the Handler can decide what - * is considered too slow for the body. If ReadHeaderTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - readHeaderTimeout: time.Duration - /** - * WriteTimeout is the maximum duration before timing out - * writes of the response. It is reset whenever a new - * request's header is read. Like ReadTimeout, it does not - * let Handlers make decisions on a per-request basis. - * A zero or negative value means there will be no timeout. - */ - writeTimeout: time.Duration - /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If IdleTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - idleTimeout: time.Duration - /** - * MaxHeaderBytes controls the maximum number of bytes the - * server will read parsing the request header's keys and - * values, including the request line. It does not limit the - * size of the request body. - * If zero, DefaultMaxHeaderBytes is used. - */ - maxHeaderBytes: number - /** - * TLSNextProto optionally specifies a function to take over - * ownership of the provided TLS connection when an ALPN - * protocol upgrade has occurred. The map key is the protocol - * name negotiated. The Handler argument should be used to - * handle HTTP requests and will initialize the Request's TLS - * and RemoteAddr if not already set. The connection is - * automatically closed when the function returns. - * If TLSNextProto is not nil, HTTP/2 support is not enabled - * automatically. - */ - tlsNextProto: _TygojaDict - /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. - */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void - /** - * ErrorLog specifies an optional logger for errors accepting - * connections, unexpected behavior from handlers, and - * underlying FileSystem errors. - * If nil, logging is done via the log package's standard logger. - */ - errorLog?: any - /** - * BaseContext optionally specifies a function that returns - * the base context for incoming requests on this server. - * The provided Listener is the specific Listener that's - * about to start accepting requests. - * If BaseContext is nil, the default is context.Background(). - * If non-nil, it must return a non-nil context. - */ - baseContext: (_arg0: net.Listener) => context.Context - /** - * ConnContext optionally specifies a function that modifies - * the context used for a new connection c. The provided ctx - * is derived from the base context and has a ServerContextKey - * value. - */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context - } - interface Server { - /** - * Close immediately closes all active net.Listeners and any - * connections in state StateNew, StateActive, or StateIdle. For a - * graceful shutdown, use Shutdown. + * A key identifies a specific value in a Context. Functions that wish + * to store values in Context typically allocate a key in a global + * variable then use that key as the argument to context.WithValue and + * Context.Value. A key can be any type that supports equality; + * packages should define keys as an unexported type to avoid + * collisions. * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. + * Packages that define a Context key should provide type-safe accessors + * for the values stored using that key: * - * Close returns any error returned from closing the Server's - * underlying Listener(s). + * ``` + * // Package user defines a User type that's stored in Contexts. + * package user + * + * import "context" + * + * // User is the type of value stored in the Contexts. + * type User struct {...} + * + * // key is an unexported type for keys defined in this package. + * // This prevents collisions with keys defined in other packages. + * type key int + * + * // userKey is the key for user.User values in Contexts. It is + * // unexported; clients use user.NewContext and user.FromContext + * // instead of using this key directly. + * var userKey key + * + * // NewContext returns a new Context that carries value u. + * func NewContext(ctx context.Context, u *User) context.Context { + * return context.WithValue(ctx, userKey, u) + * } + * + * // FromContext returns the User value stored in ctx, if any. + * func FromContext(ctx context.Context) (*User, bool) { + * u, ok := ctx.Value(userKey).(*User) + * return u, ok + * } + * ``` */ - close(): void - } - interface Server { - /** - * Shutdown gracefully shuts down the server without interrupting any - * active connections. Shutdown works by first closing all open - * listeners, then closing all idle connections, and then waiting - * indefinitely for connections to return to idle and then shut down. - * If the provided context expires before the shutdown is complete, - * Shutdown returns the context's error, otherwise it returns any - * error returned from closing the Server's underlying Listener(s). - * - * When Shutdown is called, Serve, ListenAndServe, and - * ListenAndServeTLS immediately return ErrServerClosed. Make sure the - * program doesn't exit and waits instead for Shutdown to return. - * - * Shutdown does not attempt to close nor wait for hijacked - * connections such as WebSockets. The caller of Shutdown should - * separately notify such long-lived connections of shutdown and wait - * for them to close, if desired. See RegisterOnShutdown for a way to - * register shutdown notification functions. - * - * Once Shutdown has been called on a server, it may not be reused; - * future calls to methods such as Serve will return ErrServerClosed. - */ - shutdown(ctx: context.Context): void - } - interface Server { - /** - * RegisterOnShutdown registers a function to call on Shutdown. - * This can be used to gracefully shutdown connections that have - * undergone ALPN protocol upgrade or that have been hijacked. - * This function should start protocol-specific graceful shutdown, - * but should not wait for shutdown to complete. - */ - registerOnShutdown(f: () => void): void - } - interface Server { - /** - * ListenAndServe listens on the TCP network address srv.Addr and then - * calls Serve to handle requests on incoming connections. - * Accepted connections are configured to enable TCP keep-alives. - * - * If srv.Addr is blank, ":http" is used. - * - * ListenAndServe always returns a non-nil error. After Shutdown or Close, - * the returned error is ErrServerClosed. - */ - listenAndServe(): void - } - interface Server { - /** - * Serve accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines read requests and - * then call srv.Handler to reply to them. - * - * HTTP/2 support is only enabled if the Listener returns *tls.Conn - * connections and they were configured with "h2" in the TLS - * Config.NextProtos. - * - * Serve always returns a non-nil error and closes l. - * After Shutdown or Close, the returned error is ErrServerClosed. - */ - serve(l: net.Listener): void - } - interface Server { - /** - * ServeTLS accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines perform TLS - * setup and then read requests, calling srv.Handler to reply to them. - * - * Files containing a certificate and matching private key for the - * server must be provided if neither the Server's - * TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. - * If the certificate is signed by a certificate authority, the - * certFile should be the concatenation of the server's certificate, - * any intermediates, and the CA's certificate. - * - * ServeTLS always returns a non-nil error. After Shutdown or Close, the - * returned error is ErrServerClosed. - */ - serveTLS(l: net.Listener, certFile: string): void - } - interface Server { - /** - * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. - * By default, keep-alives are always enabled. Only very - * resource-constrained environments or servers in the process of - * shutting down should disable them. - */ - setKeepAlivesEnabled(v: boolean): void - } - interface Server { - /** - * ListenAndServeTLS listens on the TCP network address srv.Addr and - * then calls ServeTLS to handle requests on incoming TLS connections. - * Accepted connections are configured to enable TCP keep-alives. - * - * Filenames containing a certificate and matching private key for the - * server must be provided if neither the Server's TLSConfig.Certificates - * nor TLSConfig.GetCertificate are populated. If the certificate is - * signed by a certificate authority, the certFile should be the - * concatenation of the server's certificate, any intermediates, and - * the CA's certificate. - * - * If srv.Addr is blank, ":https" is used. - * - * ListenAndServeTLS always returns a non-nil error. After Shutdown or - * Close, the returned error is ErrServerClosed. - */ - listenAndServeTLS(certFile: string): void + value(key: any): any } } @@ -11121,6 +9044,137 @@ namespace sql { } } +namespace migrate { + /** + * MigrationsList defines a list with migration definitions + */ + interface MigrationsList { + } + interface MigrationsList { + /** + * Item returns a single migration from the list by its index. + */ + item(index: number): (Migration) + } + interface MigrationsList { + /** + * Items returns the internal migrations list slice. + */ + items(): Array<(Migration | undefined)> + } + interface MigrationsList { + /** + * Register adds new migration definition to the list. + * + * If `optFilename` is not provided, it will try to get the name from its .go file. + * + * The list will be sorted automatically based on the migrations file name. + */ + register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void + } +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + * + * # Limits + * + * To protect against malicious inputs, this package sets limits on the size + * of the MIME data it processes. + * + * Reader.NextPart and Reader.NextRawPart limit the number of headers in a + * part to 10000 and Reader.ReadForm limits the total number of headers in all + * FileHeaders to 10000. + * These limits may be adjusted with the GODEBUG=multipartmaxheaders= + * setting. + * + * Reader.ReadForm further limits the number of parts in a form to 1000. + * This limit may be adjusted with the GODEBUG=multipartmaxparts= + * setting. + */ +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace multipart { + /** + * A FileHeader describes a file part of a multipart request. + */ + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number + } + interface FileHeader { + /** + * Open opens and returns the FileHeader's associated File. + */ + open(): File + } +} + +/** + * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * + * See README.md for more info. + */ +namespace jwt { + /** + * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. + * This is the default claims type if you don't supply one + */ + interface MapClaims extends _TygojaDict{} + interface MapClaims { + /** + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset + */ + verifyAudience(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. + */ + verifyExpiresAt(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. + */ + verifyIssuedAt(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. + */ + verifyNotBefore(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset + */ + verifyIssuer(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * Valid validates time based claims "exp, iat, nbf". + * There is no accounting for clock skew. + * As well, if any of the above claims are not in the token, it will still + * be considered a valid claim. + */ + valid(): void + } +} + /** * Package types implements some commonly used db serializable types * like datetime, json, etc. @@ -11192,6 +9246,918 @@ namespace types { } } +/** + * Package http provides HTTP client and server implementations. + * + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: + * + * ``` + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) + * ``` + * + * The caller must close the response body when finished with it: + * + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` + * + * # Clients and Transports + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: + * + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... + * ``` + * + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * # Servers + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use DefaultServeMux. + * Handle and HandleFunc add handlers to DefaultServeMux: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * # HTTP/2 + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting Transport.TLSNextProto (for clients) or + * Server.TLSNextProto (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG settings are + * currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug + * + * The http package's Transport and Server both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url + /** + * A Request represents an HTTP request received by a server + * or to be sent by a client. + * + * The field semantics differ slightly between client and server + * usage. In addition to the notes on the fields below, see the + * documentation for Request.Write and RoundTripper. + */ + interface Request { + /** + * Method specifies the HTTP method (GET, POST, PUT, etc.). + * For client requests, an empty string means GET. + * + * Go's HTTP client does not support sending a request with + * the CONNECT method. See the documentation on Transport for + * details. + */ + method: string + /** + * URL specifies either the URI being requested (for server + * requests) or the URL to access (for client requests). + * + * For server requests, the URL is parsed from the URI + * supplied on the Request-Line as stored in RequestURI. For + * most requests, fields other than Path and RawQuery will be + * empty. (See RFC 7230, Section 5.3) + * + * For client requests, the URL's Host specifies the server to + * connect to, while the Request's Host field optionally + * specifies the Host header value to send in the HTTP + * request. + */ + url?: url.URL + /** + * The protocol version for incoming server requests. + * + * For client requests, these fields are ignored. The HTTP + * client code always uses either HTTP/1.1 or HTTP/2. + * See the docs on Transport for details. + */ + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 + /** + * Header contains the request header fields either received + * by the server or to be sent by the client. + * + * If a server received a request with header lines, + * + * ``` + * Host: example.com + * accept-encoding: gzip, deflate + * Accept-Language: en-us + * fOO: Bar + * foo: two + * ``` + * + * then + * + * ``` + * Header = map[string][]string{ + * "Accept-Encoding": {"gzip, deflate"}, + * "Accept-Language": {"en-us"}, + * "Foo": {"Bar", "two"}, + * } + * ``` + * + * For incoming requests, the Host header is promoted to the + * Request.Host field and removed from the Header map. + * + * HTTP defines that header names are case-insensitive. The + * request parser implements this by using CanonicalHeaderKey, + * making the first character and any characters following a + * hyphen uppercase and the rest lowercase. + * + * For client requests, certain headers such as Content-Length + * and Connection are automatically written when needed and + * values in Header may be ignored. See the documentation + * for the Request.Write method. + */ + header: Header + /** + * Body is the request's body. + * + * For client requests, a nil body means the request has no + * body, such as a GET request. The HTTP Client's Transport + * is responsible for calling the Close method. + * + * For server requests, the Request Body is always non-nil + * but will return EOF immediately when no body is present. + * The Server will close the request body. The ServeHTTP + * Handler does not need to. + * + * Body must allow Read to be called concurrently with Close. + * In particular, calling Close should unblock a Read waiting + * for input. + */ + body: io.ReadCloser + /** + * GetBody defines an optional func to return a new copy of + * Body. It is used for client requests when a redirect requires + * reading the body more than once. Use of GetBody still + * requires setting Body. + * + * For server requests, it is unused. + */ + getBody: () => io.ReadCloser + /** + * ContentLength records the length of the associated content. + * The value -1 indicates that the length is unknown. + * Values >= 0 indicate that the given number of bytes may + * be read from Body. + * + * For client requests, a value of 0 with a non-nil Body is + * also treated as unknown. + */ + contentLength: number + /** + * TransferEncoding lists the transfer encodings from outermost to + * innermost. An empty list denotes the "identity" encoding. + * TransferEncoding can usually be ignored; chunked encoding is + * automatically added and removed as necessary when sending and + * receiving requests. + */ + transferEncoding: Array + /** + * Close indicates whether to close the connection after + * replying to this request (for servers) or after sending this + * request and reading its response (for clients). + * + * For server requests, the HTTP server handles this automatically + * and this field is not needed by Handlers. + * + * For client requests, setting this field prevents re-use of + * TCP connections between requests to the same hosts, as if + * Transport.DisableKeepAlives were set. + */ + close: boolean + /** + * For server requests, Host specifies the host on which the + * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this + * is either the value of the "Host" header or the host name + * given in the URL itself. For HTTP/2, it is the value of the + * ":authority" pseudo-header field. + * It may be of the form "host:port". For international domain + * names, Host may be in Punycode or Unicode form. Use + * golang.org/x/net/idna to convert it to either format if + * needed. + * To prevent DNS rebinding attacks, server Handlers should + * validate that the Host header has a value for which the + * Handler considers itself authoritative. The included + * ServeMux supports patterns registered to particular host + * names and thus protects its registered Handlers. + * + * For client requests, Host optionally overrides the Host + * header to send. If empty, the Request.Write method uses + * the value of URL.Host. Host may contain an international + * domain name. + */ + host: string + /** + * Form contains the parsed form data, including both the URL + * field's query parameters and the PATCH, POST, or PUT form data. + * This field is only available after ParseForm is called. + * The HTTP client ignores Form and uses Body instead. + */ + form: url.Values + /** + * PostForm contains the parsed form data from PATCH, POST + * or PUT body parameters. + * + * This field is only available after ParseForm is called. + * The HTTP client ignores PostForm and uses Body instead. + */ + postForm: url.Values + /** + * MultipartForm is the parsed multipart form, including file uploads. + * This field is only available after ParseMultipartForm is called. + * The HTTP client ignores MultipartForm and uses Body instead. + */ + multipartForm?: multipart.Form + /** + * Trailer specifies additional headers that are sent after the request + * body. + * + * For server requests, the Trailer map initially contains only the + * trailer keys, with nil values. (The client declares which trailers it + * will later send.) While the handler is reading from Body, it must + * not reference Trailer. After reading from Body returns EOF, Trailer + * can be read again and will contain non-nil values, if they were sent + * by the client. + * + * For client requests, Trailer must be initialized to a map containing + * the trailer keys to later send. The values may be nil or their final + * values. The ContentLength must be 0 or -1, to send a chunked request. + * After the HTTP request is sent the map values can be updated while + * the request body is read. Once the body returns EOF, the caller must + * not mutate Trailer. + * + * Few HTTP clients, servers, or proxies support HTTP trailers. + */ + trailer: Header + /** + * RemoteAddr allows HTTP servers and other software to record + * the network address that sent the request, usually for + * logging. This field is not filled in by ReadRequest and + * has no defined format. The HTTP server in this package + * sets RemoteAddr to an "IP:port" address before invoking a + * handler. + * This field is ignored by the HTTP client. + */ + remoteAddr: string + /** + * RequestURI is the unmodified request-target of the + * Request-Line (RFC 7230, Section 3.1.1) as sent by the client + * to a server. Usually the URL field should be used instead. + * It is an error to set this field in an HTTP client request. + */ + requestURI: string + /** + * TLS allows HTTP servers and other software to record + * information about the TLS connection on which the request + * was received. This field is not filled in by ReadRequest. + * The HTTP server in this package sets the field for + * TLS-enabled connections before invoking a handler; + * otherwise it leaves the field nil. + * This field is ignored by the HTTP client. + */ + tls?: any + /** + * Cancel is an optional channel whose closure indicates that the client + * request should be regarded as canceled. Not all implementations of + * RoundTripper may support Cancel. + * + * For server requests, this field is not applicable. + * + * Deprecated: Set the Request's context with NewRequestWithContext + * instead. If a Request's Cancel field and context are both + * set, it is undefined whether Cancel is respected. + */ + cancel: undefined + /** + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. + */ + response?: Response + } + interface Request { + /** + * Context returns the request's context. To change the context, use + * Clone or WithContext. + * + * The returned context is always non-nil; it defaults to the + * background context. + * + * For outgoing client requests, the context controls cancellation. + * + * For incoming server requests, the context is canceled when the + * client's connection closes, the request is canceled (with HTTP/2), + * or when the ServeHTTP method returns. + */ + context(): context.Context + } + interface Request { + /** + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. + * + * For outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. + * + * To create a new request with a context, use NewRequestWithContext. + * To make a deep copy of a request with a new context, use Request.Clone. + */ + withContext(ctx: context.Context): (Request) + } + interface Request { + /** + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. + * + * For an outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. + */ + clone(ctx: context.Context): (Request) + } + interface Request { + /** + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. + */ + protoAtLeast(major: number): boolean + } + interface Request { + /** + * UserAgent returns the client's User-Agent, if sent in the request. + */ + userAgent(): string + } + interface Request { + /** + * Cookies parses and returns the HTTP cookies sent with the request. + */ + cookies(): Array<(Cookie | undefined)> + } + interface Request { + /** + * Cookie returns the named cookie provided in the request or + * ErrNoCookie if not found. + * If multiple cookies match the given name, only one cookie will + * be returned. + */ + cookie(name: string): (Cookie) + } + interface Request { + /** + * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, + * AddCookie does not attach more than one Cookie header field. That + * means all cookies, if any, are written into the same line, + * separated by semicolon. + * AddCookie only sanitizes c's name and value, and does not sanitize + * a Cookie header already present in the request. + */ + addCookie(c: Cookie): void + } + interface Request { + /** + * Referer returns the referring URL, if sent in the request. + * + * Referer is misspelled as in the request itself, a mistake from the + * earliest days of HTTP. This value can also be fetched from the + * Header map as Header["Referer"]; the benefit of making it available + * as a method is that the compiler can diagnose programs that use the + * alternate (correct English) spelling req.Referrer() but cannot + * diagnose programs that use Header["Referrer"]. + */ + referer(): string + } + interface Request { + /** + * MultipartReader returns a MIME multipart reader if this is a + * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. + * Use this function instead of ParseMultipartForm to + * process the request body as a stream. + */ + multipartReader(): (multipart.Reader) + } + interface Request { + /** + * Write writes an HTTP/1.1 request, which is the header and body, in wire format. + * This method consults the following fields of the request: + * + * ``` + * Host + * URL + * Method (defaults to "GET") + * Header + * ContentLength + * TransferEncoding + * Body + * ``` + * + * If Body is present, Content-Length is <= 0 and TransferEncoding + * hasn't been set to "identity", Write adds "Transfer-Encoding: + * chunked" to the header. Body is closed after it is sent. + */ + write(w: io.Writer): void + } + interface Request { + /** + * WriteProxy is like Write but writes the request in the form + * expected by an HTTP proxy. In particular, WriteProxy writes the + * initial Request-URI line of the request with an absolute URI, per + * section 5.3 of RFC 7230, including the scheme and host. + * In either case, WriteProxy also writes a Host header, using + * either r.Host or r.URL.Host. + */ + writeProxy(w: io.Writer): void + } + interface Request { + /** + * BasicAuth returns the username and password provided in the request's + * Authorization header, if the request uses HTTP Basic Authentication. + * See RFC 2617, Section 2. + */ + basicAuth(): [string, boolean] + } + interface Request { + /** + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. + * + * With HTTP Basic Authentication the provided username and password + * are not encrypted. It should generally only be used in an HTTPS + * request. + * + * The username may not contain a colon. Some protocols may impose + * additional requirements on pre-escaping the username and + * password. For instance, when used with OAuth2, both arguments must + * be URL encoded first with url.QueryEscape. + */ + setBasicAuth(username: string): void + } + interface Request { + /** + * ParseForm populates r.Form and r.PostForm. + * + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. + * + * For POST, PUT, and PATCH requests, it also reads the request body, parses it + * as a form and puts the results into both r.PostForm and r.Form. Request body + * parameters take precedence over URL query string values in r.Form. + * + * If the request Body's size has not already been limited by MaxBytesReader, + * the size is capped at 10MB. + * + * For other HTTP methods, or when the Content-Type is not + * application/x-www-form-urlencoded, the request Body is not read, and + * r.PostForm is initialized to a non-nil, empty value. + * + * ParseMultipartForm calls ParseForm automatically. + * ParseForm is idempotent. + */ + parseForm(): void + } + interface Request { + /** + * ParseMultipartForm parses a request body as multipart/form-data. + * The whole request body is parsed and up to a total of maxMemory bytes of + * its file parts are stored in memory, with the remainder stored on + * disk in temporary files. + * ParseMultipartForm calls ParseForm if necessary. + * If ParseForm returns an error, ParseMultipartForm returns it but also + * continues parsing the request body. + * After one call to ParseMultipartForm, subsequent calls have no effect. + */ + parseMultipartForm(maxMemory: number): void + } + interface Request { + /** + * FormValue returns the first value for the named component of the query. + * POST and PUT body parameters take precedence over URL query string values. + * FormValue calls ParseMultipartForm and ParseForm if necessary and ignores + * any errors returned by these functions. + * If key is not present, FormValue returns the empty string. + * To access multiple values of the same key, call ParseForm and + * then inspect Request.Form directly. + */ + formValue(key: string): string + } + interface Request { + /** + * PostFormValue returns the first value for the named component of the POST, + * PATCH, or PUT request body. URL query parameters are ignored. + * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores + * any errors returned by these functions. + * If key is not present, PostFormValue returns the empty string. + */ + postFormValue(key: string): string + } + interface Request { + /** + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. + */ + formFile(key: string): [multipart.File, (multipart.FileHeader)] + } + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after the Handler.ServeHTTP method + * has returned. + */ + interface ResponseWriter { + [key:string]: any; + /** + * Header returns the header map that will be sent by + * WriteHeader. The Header map also is the mechanism with which + * Handlers can set HTTP trailers. + * + * Changing the header map after a call to WriteHeader (or + * Write) has no effect unless the HTTP status code was of the + * 1xx class or the modified headers are trailers. + * + * There are two ways to set Trailers. The preferred way is to + * predeclare in the headers which trailers you will later + * send by setting the "Trailer" header to the names of the + * trailer keys which will come later. In this case, those + * keys of the Header map are treated as if they were + * trailers. See the example. The second way, for trailer + * keys not known to the Handler until after the first Write, + * is to prefix the Header map keys with the TrailerPrefix + * constant value. See TrailerPrefix. + * + * To suppress automatic response headers (such as "Date"), set + * their value to nil. + */ + header(): Header + /** + * Write writes the data to the connection as part of an HTTP reply. + * + * If WriteHeader has not yet been called, Write calls + * WriteHeader(http.StatusOK) before writing the data. If the Header + * does not contain a Content-Type line, Write adds a Content-Type set + * to the result of passing the initial 512 bytes of written data to + * DetectContentType. Additionally, if the total size of all written + * data is under a few KB and there are no Flush calls, the + * Content-Length header is added automatically. + * + * Depending on the HTTP protocol version and the client, calling + * Write or WriteHeader may prevent future reads on the + * Request.Body. For HTTP/1.x requests, handlers should read any + * needed request body data before writing the response. Once the + * headers have been flushed (due to either an explicit Flusher.Flush + * call or writing enough data to trigger a flush), the request body + * may be unavailable. For HTTP/2 requests, the Go HTTP server permits + * handlers to continue to read the request body while concurrently + * writing the response. However, such behavior may not be supported + * by all HTTP/2 clients. Handlers should read before writing if + * possible to maximize compatibility. + */ + write(_arg0: string|Array): number + /** + * WriteHeader sends an HTTP response header with the provided + * status code. + * + * If WriteHeader is not called explicitly, the first call to Write + * will trigger an implicit WriteHeader(http.StatusOK). + * Thus explicit calls to WriteHeader are mainly used to + * send error codes or 1xx informational responses. + * + * The provided code must be a valid HTTP 1xx-5xx status code. + * Any number of 1xx headers may be written, followed by at most + * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx + * headers may be buffered. Use the Flusher interface to send + * buffered data. The header map is cleared when 2xx-5xx headers are + * sent, but not with 1xx headers. + * + * The server will automatically send a 100 (Continue) header + * on the first read from the request body if the request has + * an "Expect: 100-continue" header. + */ + writeHeader(statusCode: number): void + } + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { + /** + * Addr optionally specifies the TCP address for the server to listen on, + * in the form "host:port". If empty, ":http" (port 80) is used. + * The service names are defined in RFC 6335 and assigned by IANA. + * See net.Dial for details of the address format. + */ + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil + /** + * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, + * otherwise responds with 200 OK and Content-Length: 0. + */ + disableGeneralOptionsHandler: boolean + /** + * TLSConfig optionally provides a TLS configuration for use + * by ServeTLS and ListenAndServeTLS. Note that this value is + * cloned by ServeTLS and ListenAndServeTLS, so it's not + * possible to modify the configuration with methods like + * tls.Config.SetSessionTicketKeys. To use + * SetSessionTicketKeys, use Server.Serve with a TLS Listener + * instead. + */ + tlsConfig?: any + /** + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. + * + * Because ReadTimeout does not let Handlers make per-request + * decisions on each request body's acceptable deadline or + * upload rate, most users will prefer to use + * ReadHeaderTimeout. It is valid to use them both. + */ + readTimeout: time.Duration + /** + * ReadHeaderTimeout is the amount of time allowed to read + * request headers. The connection's read deadline is reset + * after reading the headers and the Handler can decide what + * is considered too slow for the body. If ReadHeaderTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. + */ + readHeaderTimeout: time.Duration + /** + * WriteTimeout is the maximum duration before timing out + * writes of the response. It is reset whenever a new + * request's header is read. Like ReadTimeout, it does not + * let Handlers make decisions on a per-request basis. + * A zero or negative value means there will be no timeout. + */ + writeTimeout: time.Duration + /** + * IdleTimeout is the maximum amount of time to wait for the + * next request when keep-alives are enabled. If IdleTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. + */ + idleTimeout: time.Duration + /** + * MaxHeaderBytes controls the maximum number of bytes the + * server will read parsing the request header's keys and + * values, including the request line. It does not limit the + * size of the request body. + * If zero, DefaultMaxHeaderBytes is used. + */ + maxHeaderBytes: number + /** + * TLSNextProto optionally specifies a function to take over + * ownership of the provided TLS connection when an ALPN + * protocol upgrade has occurred. The map key is the protocol + * name negotiated. The Handler argument should be used to + * handle HTTP requests and will initialize the Request's TLS + * and RemoteAddr if not already set. The connection is + * automatically closed when the function returns. + * If TLSNextProto is not nil, HTTP/2 support is not enabled + * automatically. + */ + tlsNextProto: _TygojaDict + /** + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. + */ + connState: (_arg0: net.Conn, _arg1: ConnState) => void + /** + * ErrorLog specifies an optional logger for errors accepting + * connections, unexpected behavior from handlers, and + * underlying FileSystem errors. + * If nil, logging is done via the log package's standard logger. + */ + errorLog?: any + /** + * BaseContext optionally specifies a function that returns + * the base context for incoming requests on this server. + * The provided Listener is the specific Listener that's + * about to start accepting requests. + * If BaseContext is nil, the default is context.Background(). + * If non-nil, it must return a non-nil context. + */ + baseContext: (_arg0: net.Listener) => context.Context + /** + * ConnContext optionally specifies a function that modifies + * the context used for a new connection c. The provided ctx + * is derived from the base context and has a ServerContextKey + * value. + */ + connContext: (ctx: context.Context, c: net.Conn) => context.Context + } + interface Server { + /** + * Close immediately closes all active net.Listeners and any + * connections in state StateNew, StateActive, or StateIdle. For a + * graceful shutdown, use Shutdown. + * + * Close does not attempt to close (and does not even know about) + * any hijacked connections, such as WebSockets. + * + * Close returns any error returned from closing the Server's + * underlying Listener(s). + */ + close(): void + } + interface Server { + /** + * Shutdown gracefully shuts down the server without interrupting any + * active connections. Shutdown works by first closing all open + * listeners, then closing all idle connections, and then waiting + * indefinitely for connections to return to idle and then shut down. + * If the provided context expires before the shutdown is complete, + * Shutdown returns the context's error, otherwise it returns any + * error returned from closing the Server's underlying Listener(s). + * + * When Shutdown is called, Serve, ListenAndServe, and + * ListenAndServeTLS immediately return ErrServerClosed. Make sure the + * program doesn't exit and waits instead for Shutdown to return. + * + * Shutdown does not attempt to close nor wait for hijacked + * connections such as WebSockets. The caller of Shutdown should + * separately notify such long-lived connections of shutdown and wait + * for them to close, if desired. See RegisterOnShutdown for a way to + * register shutdown notification functions. + * + * Once Shutdown has been called on a server, it may not be reused; + * future calls to methods such as Serve will return ErrServerClosed. + */ + shutdown(ctx: context.Context): void + } + interface Server { + /** + * RegisterOnShutdown registers a function to call on Shutdown. + * This can be used to gracefully shutdown connections that have + * undergone ALPN protocol upgrade or that have been hijacked. + * This function should start protocol-specific graceful shutdown, + * but should not wait for shutdown to complete. + */ + registerOnShutdown(f: () => void): void + } + interface Server { + /** + * ListenAndServe listens on the TCP network address srv.Addr and then + * calls Serve to handle requests on incoming connections. + * Accepted connections are configured to enable TCP keep-alives. + * + * If srv.Addr is blank, ":http" is used. + * + * ListenAndServe always returns a non-nil error. After Shutdown or Close, + * the returned error is ErrServerClosed. + */ + listenAndServe(): void + } + interface Server { + /** + * Serve accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines read requests and + * then call srv.Handler to reply to them. + * + * HTTP/2 support is only enabled if the Listener returns *tls.Conn + * connections and they were configured with "h2" in the TLS + * Config.NextProtos. + * + * Serve always returns a non-nil error and closes l. + * After Shutdown or Close, the returned error is ErrServerClosed. + */ + serve(l: net.Listener): void + } + interface Server { + /** + * ServeTLS accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines perform TLS + * setup and then read requests, calling srv.Handler to reply to them. + * + * Files containing a certificate and matching private key for the + * server must be provided if neither the Server's + * TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. + * If the certificate is signed by a certificate authority, the + * certFile should be the concatenation of the server's certificate, + * any intermediates, and the CA's certificate. + * + * ServeTLS always returns a non-nil error. After Shutdown or Close, the + * returned error is ErrServerClosed. + */ + serveTLS(l: net.Listener, certFile: string): void + } + interface Server { + /** + * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. + * By default, keep-alives are always enabled. Only very + * resource-constrained environments or servers in the process of + * shutting down should disable them. + */ + setKeepAlivesEnabled(v: boolean): void + } + interface Server { + /** + * ListenAndServeTLS listens on the TCP network address srv.Addr and + * then calls ServeTLS to handle requests on incoming TLS connections. + * Accepted connections are configured to enable TCP keep-alives. + * + * Filenames containing a certificate and matching private key for the + * server must be provided if neither the Server's TLSConfig.Certificates + * nor TLSConfig.GetCertificate are populated. If the certificate is + * signed by a certificate authority, the certFile should be the + * concatenation of the server's certificate, any intermediates, and + * the CA's certificate. + * + * If srv.Addr is blank, ":https" is used. + * + * ListenAndServeTLS always returns a non-nil error. After Shutdown or + * Close, the returned error is ErrServerClosed. + */ + listenAndServeTLS(certFile: string): void + } +} + namespace auth { /** * AuthUser defines a standardized oauth2 user data structure. @@ -11320,886 +10286,6 @@ namespace auth { } } -/** - * Package blob provides an easy and portable way to interact with blobs - * within a storage location. Subpackages contain driver implementations of - * blob for supported services. - * - * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. - * - * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with - * functions in that package. - * - * # Errors - * - * The errors returned from this package can be inspected in several ways: - * - * The Code function from gocloud.dev/gcerrors will return an error code, also - * defined in that package, when invoked on an error. - * - * The Bucket.ErrorAs method can retrieve the driver error underlying the returned - * error. - * - * # OpenCensus Integration - * - * OpenCensus supports tracing and metric collection for multiple languages and - * backend providers. See https://opencensus.io. - * - * This API collects OpenCensus traces and metrics for the following methods: - * ``` - * - Attributes - * - Copy - * - Delete - * - ListPage - * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll - * are included because they call NewRangeReader.) - * - NewWriter, from creation until the call to Close. - * ``` - * - * All trace and metric names begin with the package import path. - * The traces add the method name. - * For example, "gocloud.dev/blob/Attributes". - * The metrics are "completed_calls", a count of completed method calls by driver, - * method and status (error code); and "latency", a distribution of method latency - * by driver and method. - * For example, "gocloud.dev/blob/latency". - * - * It also collects the following metrics: - * ``` - * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. - * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. - * ``` - * - * To enable trace collection in your application, see "Configure Exporter" at - * https://opencensus.io/quickstart/go/tracing. - * To enable metric collection in your application, see "Exporting stats" at - * https://opencensus.io/quickstart/go/metrics. - */ -namespace blob { - /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after - * reads are finished. - */ - interface Reader { - } - interface Reader { - /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). - */ - read(p: string|Array): number - } - interface Reader { - /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). - */ - close(): void - } - interface Reader { - /** - * ContentType returns the MIME type of the blob. - */ - contentType(): string - } - interface Reader { - /** - * ModTime returns the time the blob was last modified. - */ - modTime(): time.Time - } - interface Reader { - /** - * Size returns the size of the blob content in bytes. - */ - size(): number - } - interface Reader { - /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. - */ - as(i: { - }): boolean - } - interface Reader { - /** - * WriteTo reads from r and writes to w until there's no more data or - * an error occurs. - * The return value is the number of bytes written to w. - * - * It implements the io.WriterTo interface. - */ - writeTo(w: io.Writer): number - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { - /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control - */ - cacheControl: string - /** - * ContentDisposition specifies whether the blob content is expected to be - * displayed inline or as an attachment. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition - */ - contentDisposition: string - /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - */ - contentEncoding: string - /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language - */ - contentLanguage: string - /** - * ContentType is the MIME type of the blob. It will not be empty. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type - */ - contentType: string - /** - * Metadata holds key/value pairs associated with the blob. - * Keys are guaranteed to be in lowercase, even if the backend service - * has case-sensitive keys (although note that Metadata written via - * this package will always be lowercased). If there are duplicate - * case-insensitive keys (e.g., "foo" and "FOO"), only one value - * will be kept, and it is undefined which one. - */ - metadata: _TygojaDict - /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. - */ - createTime: time.Time - /** - * ModTime is the time the blob was last modified. - */ - modTime: time.Time - /** - * Size is the size of the blob's content in bytes. - */ - size: number - /** - * MD5 is an MD5 hash of the blob contents or nil if not available. - */ - md5: string|Array - /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. - */ - eTag: string - } - interface Attributes { - /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. - */ - as(i: { - }): boolean - } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { - /** - * Key is the key for this blob. - */ - key: string - /** - * ModTime is the time the blob was last modified. - */ - modTime: time.Time - /** - * Size is the size of the blob's content in bytes. - */ - size: number - /** - * MD5 is an MD5 hash of the blob contents or nil if not available. - */ - md5: string|Array - /** - * IsDir indicates that this result represents a "directory" in the - * hierarchical namespace, ending in ListOptions.Delimiter. Key can be - * passed as ListOptions.Prefix to list items in the "directory". - * Fields other than Key and IsDir will not be set if IsDir is true. - */ - isDir: boolean - } - interface ListObject { - /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. - */ - as(i: { - }): boolean - } -} - -/** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * Schema defines a dynamic db schema as a slice of `SchemaField`s. - */ - interface Schema { - } - interface Schema { - /** - * Fields returns the registered schema fields. - */ - fields(): Array<(SchemaField | undefined)> - } - interface Schema { - /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. - */ - initFieldsOptions(): void - } - interface Schema { - /** - * Clone creates a deep clone of the current schema. - */ - clone(): (Schema) - } - interface Schema { - /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. - */ - asMap(): _TygojaDict - } - interface Schema { - /** - * GetFieldById returns a single field by its id. - */ - getFieldById(id: string): (SchemaField) - } - interface Schema { - /** - * GetFieldByName returns a single field by its name. - */ - getFieldByName(name: string): (SchemaField) - } - interface Schema { - /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. - */ - removeField(id: string): void - } - interface Schema { - /** - * AddField registers the provided newField to the current schema. - * - * If field with `newField.Id` already exist, the existing field is - * replaced with the new one. - * - * Otherwise the new field is appended to the other schema fields. - */ - addField(newField: SchemaField): void - } - interface Schema { - /** - * Validate makes Schema validatable by implementing [validation.Validatable] interface. - * - * Internally calls each individual field's validator and additionally - * checks for invalid renamed fields and field name duplications. - */ - validate(): void - } - interface Schema { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface Schema { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * On success, all schema field options are auto initialized. - */ - unmarshalJSON(data: string|Array): void - } - interface Schema { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface Schema { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. - */ - scan(value: any): void - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - type _subCrLas = BaseModel - interface Admin extends _subCrLas { - avatar: number - email: string - tokenKey: string - passwordHash: string - lastResetSentAt: types.DateTime - } - interface Admin { - /** - * TableName returns the Admin model SQL table name. - */ - tableName(): string - } - interface Admin { - /** - * ValidatePassword validates a plain password against the model's password. - */ - validatePassword(password: string): boolean - } - interface Admin { - /** - * SetPassword sets cryptographically secure string to `model.Password`. - * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. - */ - setPassword(password: string): void - } - interface Admin { - /** - * RefreshTokenKey generates and sets new random token key. - */ - refreshTokenKey(): void - } - // @ts-ignore - import validation = ozzo_validation - type _subMdoga = BaseModel - interface Collection extends _subMdoga { - name: string - type: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray - /** - * rules - */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { - /** - * TableName returns the Collection model SQL table name. - */ - tableName(): string - } - interface Collection { - /** - * BaseFilesPath returns the storage dir path used by the collection. - */ - baseFilesPath(): string - } - interface Collection { - /** - * IsBase checks if the current collection has "base" type. - */ - isBase(): boolean - } - interface Collection { - /** - * IsAuth checks if the current collection has "auth" type. - */ - isAuth(): boolean - } - interface Collection { - /** - * IsView checks if the current collection has "view" type. - */ - isView(): boolean - } - interface Collection { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface Collection { - /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. - */ - baseOptions(): CollectionBaseOptions - } - interface Collection { - /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. - */ - authOptions(): CollectionAuthOptions - } - interface Collection { - /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. - */ - viewOptions(): CollectionViewOptions - } - interface Collection { - /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. - */ - normalizeOptions(): void - } - interface Collection { - /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). - */ - decodeOptions(result: any): void - } - interface Collection { - /** - * SetOptions normalizes and unmarshals the specified options into m.Options. - */ - setOptions(typedOptions: any): void - } - type _submwCJU = BaseModel - interface ExternalAuth extends _submwCJU { - collectionId: string - recordId: string - provider: string - providerId: string - } - interface ExternalAuth { - tableName(): string - } - type _subgVxyR = BaseModel - interface Record extends _subgVxyR { - } - interface Record { - /** - * TableName returns the table name associated to the current Record model. - */ - tableName(): string - } - interface Record { - /** - * Collection returns the Collection model associated to the current Record model. - */ - collection(): (Collection) - } - interface Record { - /** - * OriginalCopy returns a copy of the current record model populated - * with its ORIGINAL data state (aka. the initially loaded) and - * everything else reset to the defaults. - */ - originalCopy(): (Record) - } - interface Record { - /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. - */ - cleanCopy(): (Record) - } - interface Record { - /** - * Expand returns a shallow copy of the current Record model expand data. - */ - expand(): _TygojaDict - } - interface Record { - /** - * SetExpand shallow copies the provided data to the current Record model's expand. - */ - setExpand(expand: _TygojaDict): void - } - interface Record { - /** - * MergeExpand merges recursively the provided expand data into - * the current model's expand (if any). - * - * Note that if an expanded prop with the same key is a slice (old or new expand) - * then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). - * Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew). - */ - mergeExpand(expand: _TygojaDict): void - } - interface Record { - /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. - */ - schemaData(): _TygojaDict - } - interface Record { - /** - * UnknownData returns a shallow copy ONLY of the unknown record fields data, - * aka. fields that are neither one of the base and special system ones, - * nor defined by the collection schema. - */ - unknownData(): _TygojaDict - } - interface Record { - /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. - */ - ignoreEmailVisibility(state: boolean): void - } - interface Record { - /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). - */ - withUnknownData(state: boolean): void - } - interface Record { - /** - * Set sets the provided key-value data pair for the current Record model. - * - * If the record collection has field with name matching the provided "key", - * the value will be further normalized according to the field rules. - */ - set(key: string, value: any): void - } - interface Record { - /** - * Get returns a normalized single record model data value for "key". - */ - get(key: string): any - } - interface Record { - /** - * GetBool returns the data value for "key" as a bool. - */ - getBool(key: string): boolean - } - interface Record { - /** - * GetString returns the data value for "key" as a string. - */ - getString(key: string): string - } - interface Record { - /** - * GetInt returns the data value for "key" as an int. - */ - getInt(key: string): number - } - interface Record { - /** - * GetFloat returns the data value for "key" as a float64. - */ - getFloat(key: string): number - } - interface Record { - /** - * GetTime returns the data value for "key" as a [time.Time] instance. - */ - getTime(key: string): time.Time - } - interface Record { - /** - * GetDateTime returns the data value for "key" as a DateTime instance. - */ - getDateTime(key: string): types.DateTime - } - interface Record { - /** - * GetStringSlice returns the data value for "key" as a slice of unique strings. - */ - getStringSlice(key: string): Array - } - interface Record { - /** - * ExpandedOne retrieves a single relation Record from the already - * loaded expand data of the current model. - * - * If the requested expand relation is multiple, this method returns - * only first available Record from the expanded relation. - * - * Returns nil if there is no such expand relation loaded. - */ - expandedOne(relField: string): (Record) - } - interface Record { - /** - * ExpandedAll retrieves a slice of relation Records from the already - * loaded expand data of the current model. - * - * If the requested expand relation is single, this method normalizes - * the return result and will wrap the single model as a slice. - * - * Returns nil slice if there is no such expand relation loaded. - */ - expandedAll(relField: string): Array<(Record | undefined)> - } - interface Record { - /** - * Retrieves the "key" json field value and unmarshals it into "result". - * - * Example - * - * ``` - * result := struct { - * FirstName string `json:"first_name"` - * }{} - * err := m.UnmarshalJSONField("my_field_name", &result) - * ``` - */ - unmarshalJSONField(key: string, result: any): void - } - interface Record { - /** - * BaseFilesPath returns the storage dir path used by the record. - */ - baseFilesPath(): string - } - interface Record { - /** - * FindFileFieldByFile returns the first file type field for which - * any of the record's data contains the provided filename. - */ - findFileFieldByFile(filename: string): (schema.SchemaField) - } - interface Record { - /** - * Load bulk loads the provided data into the current Record model. - */ - load(data: _TygojaDict): void - } - interface Record { - /** - * ColumnValueMap implements [ColumnValueMapper] interface. - */ - columnValueMap(): _TygojaDict - } - interface Record { - /** - * PublicExport exports only the record fields that are safe to be public. - * - * For auth records, to force the export of the email field you need to set - * `m.IgnoreEmailVisibility(true)`. - */ - publicExport(): _TygojaDict - } - interface Record { - /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * Only the data exported by `PublicExport()` will be serialized. - */ - marshalJSON(): string|Array - } - interface Record { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(data: string|Array): void - } - interface Record { - /** - * ReplaceModifers returns a new map with applied modifier - * values based on the current record and the specified data. - * - * The resolved modifier keys will be removed. - * - * Multiple modifiers will be applied one after another, - * while reusing the previous base key value result (eg. 1; -5; +2 => -2). - * - * Example usage: - * - * ``` - * newData := record.ReplaceModifers(data) - * // record: {"field": 10} - * // data: {"field+": 5} - * // newData: {"field": 15} - * ``` - */ - replaceModifers(data: _TygojaDict): _TygojaDict - } - interface Record { - /** - * Username returns the "username" auth record data value. - */ - username(): string - } - interface Record { - /** - * SetUsername sets the "username" auth record data value. - * - * This method doesn't check whether the provided value is a valid username. - * - * Returns an error if the record is not from an auth collection. - */ - setUsername(username: string): void - } - interface Record { - /** - * Email returns the "email" auth record data value. - */ - email(): string - } - interface Record { - /** - * SetEmail sets the "email" auth record data value. - * - * This method doesn't check whether the provided value is a valid email. - * - * Returns an error if the record is not from an auth collection. - */ - setEmail(email: string): void - } - interface Record { - /** - * Verified returns the "emailVisibility" auth record data value. - */ - emailVisibility(): boolean - } - interface Record { - /** - * SetEmailVisibility sets the "emailVisibility" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setEmailVisibility(visible: boolean): void - } - interface Record { - /** - * Verified returns the "verified" auth record data value. - */ - verified(): boolean - } - interface Record { - /** - * SetVerified sets the "verified" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setVerified(verified: boolean): void - } - interface Record { - /** - * TokenKey returns the "tokenKey" auth record data value. - */ - tokenKey(): string - } - interface Record { - /** - * SetTokenKey sets the "tokenKey" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setTokenKey(key: string): void - } - interface Record { - /** - * RefreshTokenKey generates and sets new random auth record "tokenKey". - * - * Returns an error if the record is not from an auth collection. - */ - refreshTokenKey(): void - } - interface Record { - /** - * LastResetSentAt returns the "lastResentSentAt" auth record data value. - */ - lastResetSentAt(): types.DateTime - } - interface Record { - /** - * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setLastResetSentAt(dateTime: types.DateTime): void - } - interface Record { - /** - * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. - */ - lastVerificationSentAt(): types.DateTime - } - interface Record { - /** - * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. - */ - setLastVerificationSentAt(dateTime: types.DateTime): void - } - interface Record { - /** - * PasswordHash returns the "passwordHash" auth record data value. - */ - passwordHash(): string - } - interface Record { - /** - * ValidatePassword validates a plain password against the auth record password. - * - * Returns false if the password is incorrect or record is not from an auth collection. - */ - validatePassword(password: string): boolean - } - interface Record { - /** - * SetPassword sets cryptographically secure string to the auth record "password" field. - * This method also resets the "lastResetSentAt" and the "tokenKey" fields. - * - * Returns an error if the record is not from an auth collection or - * an empty password is provided. - */ - setPassword(password: string): void - } - /** - * RequestInfo defines a HTTP request data struct, usually used - * as part of the `@request.*` filter resolver. - */ - interface RequestInfo { - query: _TygojaDict - data: _TygojaDict - headers: _TygojaDict - authRecord?: Record - admin?: Admin - method: string - } - interface RequestInfo { - /** - * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. - */ - hasModifierDataKeys(): boolean - } -} - /** * Package echo implements high performance, minimalist Go web framework. * @@ -12776,33 +10862,234 @@ namespace echo { } } -namespace migrate { +/** + * Package blob provides an easy and portable way to interact with blobs + * within a storage location. Subpackages contain driver implementations of + * blob for supported services. + * + * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. + * + * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with + * functions in that package. + * + * # Errors + * + * The errors returned from this package can be inspected in several ways: + * + * The Code function from gocloud.dev/gcerrors will return an error code, also + * defined in that package, when invoked on an error. + * + * The Bucket.ErrorAs method can retrieve the driver error underlying the returned + * error. + * + * # OpenCensus Integration + * + * OpenCensus supports tracing and metric collection for multiple languages and + * backend providers. See https://opencensus.io. + * + * This API collects OpenCensus traces and metrics for the following methods: + * ``` + * - Attributes + * - Copy + * - Delete + * - ListPage + * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll + * are included because they call NewRangeReader.) + * - NewWriter, from creation until the call to Close. + * ``` + * + * All trace and metric names begin with the package import path. + * The traces add the method name. + * For example, "gocloud.dev/blob/Attributes". + * The metrics are "completed_calls", a count of completed method calls by driver, + * method and status (error code); and "latency", a distribution of method latency + * by driver and method. + * For example, "gocloud.dev/blob/latency". + * + * It also collects the following metrics: + * ``` + * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. + * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. + * ``` + * + * To enable trace collection in your application, see "Configure Exporter" at + * https://opencensus.io/quickstart/go/tracing. + * To enable metric collection in your application, see "Exporting stats" at + * https://opencensus.io/quickstart/go/metrics. + */ +namespace blob { /** - * MigrationsList defines a list with migration definitions + * Reader reads bytes from a blob. + * It implements io.ReadSeekCloser, and must be closed after + * reads are finished. */ - interface MigrationsList { + interface Reader { } - interface MigrationsList { + interface Reader { /** - * Item returns a single migration from the list by its index. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). */ - item(index: number): (Migration) + read(p: string|Array): number } - interface MigrationsList { + interface Reader { /** - * Items returns the internal migrations list slice. + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). */ - items(): Array<(Migration | undefined)> + seek(offset: number, whence: number): number } - interface MigrationsList { + interface Reader { /** - * Register adds new migration definition to the list. + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + */ + close(): void + } + interface Reader { + /** + * ContentType returns the MIME type of the blob. + */ + contentType(): string + } + interface Reader { + /** + * ModTime returns the time the blob was last modified. + */ + modTime(): time.Time + } + interface Reader { + /** + * Size returns the size of the blob content in bytes. + */ + size(): number + } + interface Reader { + /** + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. + */ + as(i: { + }): boolean + } + interface Reader { + /** + * WriteTo reads from r and writes to w until there's no more data or + * an error occurs. + * The return value is the number of bytes written to w. * - * If `optFilename` is not provided, it will try to get the name from its .go file. - * - * The list will be sorted automatically based on the migrations file name. + * It implements the io.WriterTo interface. */ - register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void + writeTo(w: io.Writer): number + } + /** + * Attributes contains attributes about a blob. + */ + interface Attributes { + /** + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + */ + cacheControl: string + /** + * ContentDisposition specifies whether the blob content is expected to be + * displayed inline or as an attachment. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition + */ + contentDisposition: string + /** + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + */ + contentEncoding: string + /** + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language + */ + contentLanguage: string + /** + * ContentType is the MIME type of the blob. It will not be empty. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type + */ + contentType: string + /** + * Metadata holds key/value pairs associated with the blob. + * Keys are guaranteed to be in lowercase, even if the backend service + * has case-sensitive keys (although note that Metadata written via + * this package will always be lowercased). If there are duplicate + * case-insensitive keys (e.g., "foo" and "FOO"), only one value + * will be kept, and it is undefined which one. + */ + metadata: _TygojaDict + /** + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. + */ + createTime: time.Time + /** + * ModTime is the time the blob was last modified. + */ + modTime: time.Time + /** + * Size is the size of the blob's content in bytes. + */ + size: number + /** + * MD5 is an MD5 hash of the blob contents or nil if not available. + */ + md5: string|Array + /** + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + */ + eTag: string + } + interface Attributes { + /** + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. + */ + as(i: { + }): boolean + } + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { + /** + * Key is the key for this blob. + */ + key: string + /** + * ModTime is the time the blob was last modified. + */ + modTime: time.Time + /** + * Size is the size of the blob's content in bytes. + */ + size: number + /** + * MD5 is an MD5 hash of the blob contents or nil if not available. + */ + md5: string|Array + /** + * IsDir indicates that this result represents a "directory" in the + * hierarchical namespace, ending in ListOptions.Delimiter. Key can be + * passed as ListOptions.Prefix to list items in the "directory". + * Fields other than Key and IsDir will not be set if IsDir is true. + */ + isDir: boolean + } + interface ListObject { + /** + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. + */ + as(i: { + }): boolean } } @@ -12888,6 +11175,655 @@ namespace settings { } } +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation + /** + * Schema defines a dynamic db schema as a slice of `SchemaField`s. + */ + interface Schema { + } + interface Schema { + /** + * Fields returns the registered schema fields. + */ + fields(): Array<(SchemaField | undefined)> + } + interface Schema { + /** + * InitFieldsOptions calls `InitOptions()` for all schema fields. + */ + initFieldsOptions(): void + } + interface Schema { + /** + * Clone creates a deep clone of the current schema. + */ + clone(): (Schema) + } + interface Schema { + /** + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. + */ + asMap(): _TygojaDict + } + interface Schema { + /** + * GetFieldById returns a single field by its id. + */ + getFieldById(id: string): (SchemaField) + } + interface Schema { + /** + * GetFieldByName returns a single field by its name. + */ + getFieldByName(name: string): (SchemaField) + } + interface Schema { + /** + * RemoveField removes a single schema field by its id. + * + * This method does nothing if field with `id` doesn't exist. + */ + removeField(id: string): void + } + interface Schema { + /** + * AddField registers the provided newField to the current schema. + * + * If field with `newField.Id` already exist, the existing field is + * replaced with the new one. + * + * Otherwise the new field is appended to the other schema fields. + */ + addField(newField: SchemaField): void + } + interface Schema { + /** + * Validate makes Schema validatable by implementing [validation.Validatable] interface. + * + * Internally calls each individual field's validator and additionally + * checks for invalid renamed fields and field name duplications. + */ + validate(): void + } + interface Schema { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface Schema { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * On success, all schema field options are auto initialized. + */ + unmarshalJSON(data: string|Array): void + } + interface Schema { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface Schema { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. + */ + scan(value: any): void + } +} + +/** + * Package models implements all PocketBase DB models and DTOs. + */ +namespace models { + type _subKoBLW = BaseModel + interface Admin extends _subKoBLW { + avatar: number + email: string + tokenKey: string + passwordHash: string + lastResetSentAt: types.DateTime + } + interface Admin { + /** + * TableName returns the Admin model SQL table name. + */ + tableName(): string + } + interface Admin { + /** + * ValidatePassword validates a plain password against the model's password. + */ + validatePassword(password: string): boolean + } + interface Admin { + /** + * SetPassword sets cryptographically secure string to `model.Password`. + * + * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + */ + setPassword(password: string): void + } + interface Admin { + /** + * RefreshTokenKey generates and sets new random token key. + */ + refreshTokenKey(): void + } + // @ts-ignore + import validation = ozzo_validation + type _subNsGlF = BaseModel + interface Collection extends _subNsGlF { + name: string + type: string + system: boolean + schema: schema.Schema + indexes: types.JsonArray + /** + * rules + */ + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap + } + interface Collection { + /** + * TableName returns the Collection model SQL table name. + */ + tableName(): string + } + interface Collection { + /** + * BaseFilesPath returns the storage dir path used by the collection. + */ + baseFilesPath(): string + } + interface Collection { + /** + * IsBase checks if the current collection has "base" type. + */ + isBase(): boolean + } + interface Collection { + /** + * IsAuth checks if the current collection has "auth" type. + */ + isAuth(): boolean + } + interface Collection { + /** + * IsView checks if the current collection has "view" type. + */ + isView(): boolean + } + interface Collection { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface Collection { + /** + * BaseOptions decodes the current collection options and returns them + * as new [CollectionBaseOptions] instance. + */ + baseOptions(): CollectionBaseOptions + } + interface Collection { + /** + * AuthOptions decodes the current collection options and returns them + * as new [CollectionAuthOptions] instance. + */ + authOptions(): CollectionAuthOptions + } + interface Collection { + /** + * ViewOptions decodes the current collection options and returns them + * as new [CollectionViewOptions] instance. + */ + viewOptions(): CollectionViewOptions + } + interface Collection { + /** + * NormalizeOptions updates the current collection options with a + * new normalized state based on the collection type. + */ + normalizeOptions(): void + } + interface Collection { + /** + * DecodeOptions decodes the current collection options into the + * provided "result" (must be a pointer). + */ + decodeOptions(result: any): void + } + interface Collection { + /** + * SetOptions normalizes and unmarshals the specified options into m.Options. + */ + setOptions(typedOptions: any): void + } + type _subIGAZV = BaseModel + interface ExternalAuth extends _subIGAZV { + collectionId: string + recordId: string + provider: string + providerId: string + } + interface ExternalAuth { + tableName(): string + } + type _subzBPgH = BaseModel + interface Record extends _subzBPgH { + } + interface Record { + /** + * TableName returns the table name associated to the current Record model. + */ + tableName(): string + } + interface Record { + /** + * Collection returns the Collection model associated to the current Record model. + */ + collection(): (Collection) + } + interface Record { + /** + * OriginalCopy returns a copy of the current record model populated + * with its ORIGINAL data state (aka. the initially loaded) and + * everything else reset to the defaults. + */ + originalCopy(): (Record) + } + interface Record { + /** + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. + */ + cleanCopy(): (Record) + } + interface Record { + /** + * Expand returns a shallow copy of the current Record model expand data. + */ + expand(): _TygojaDict + } + interface Record { + /** + * SetExpand shallow copies the provided data to the current Record model's expand. + */ + setExpand(expand: _TygojaDict): void + } + interface Record { + /** + * MergeExpand merges recursively the provided expand data into + * the current model's expand (if any). + * + * Note that if an expanded prop with the same key is a slice (old or new expand) + * then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). + * Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew). + */ + mergeExpand(expand: _TygojaDict): void + } + interface Record { + /** + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + */ + schemaData(): _TygojaDict + } + interface Record { + /** + * UnknownData returns a shallow copy ONLY of the unknown record fields data, + * aka. fields that are neither one of the base and special system ones, + * nor defined by the collection schema. + */ + unknownData(): _TygojaDict + } + interface Record { + /** + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + */ + ignoreEmailVisibility(state: boolean): void + } + interface Record { + /** + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). + */ + withUnknownData(state: boolean): void + } + interface Record { + /** + * Set sets the provided key-value data pair for the current Record model. + * + * If the record collection has field with name matching the provided "key", + * the value will be further normalized according to the field rules. + */ + set(key: string, value: any): void + } + interface Record { + /** + * Get returns a normalized single record model data value for "key". + */ + get(key: string): any + } + interface Record { + /** + * GetBool returns the data value for "key" as a bool. + */ + getBool(key: string): boolean + } + interface Record { + /** + * GetString returns the data value for "key" as a string. + */ + getString(key: string): string + } + interface Record { + /** + * GetInt returns the data value for "key" as an int. + */ + getInt(key: string): number + } + interface Record { + /** + * GetFloat returns the data value for "key" as a float64. + */ + getFloat(key: string): number + } + interface Record { + /** + * GetTime returns the data value for "key" as a [time.Time] instance. + */ + getTime(key: string): time.Time + } + interface Record { + /** + * GetDateTime returns the data value for "key" as a DateTime instance. + */ + getDateTime(key: string): types.DateTime + } + interface Record { + /** + * GetStringSlice returns the data value for "key" as a slice of unique strings. + */ + getStringSlice(key: string): Array + } + interface Record { + /** + * ExpandedOne retrieves a single relation Record from the already + * loaded expand data of the current model. + * + * If the requested expand relation is multiple, this method returns + * only first available Record from the expanded relation. + * + * Returns nil if there is no such expand relation loaded. + */ + expandedOne(relField: string): (Record) + } + interface Record { + /** + * ExpandedAll retrieves a slice of relation Records from the already + * loaded expand data of the current model. + * + * If the requested expand relation is single, this method normalizes + * the return result and will wrap the single model as a slice. + * + * Returns nil slice if there is no such expand relation loaded. + */ + expandedAll(relField: string): Array<(Record | undefined)> + } + interface Record { + /** + * Retrieves the "key" json field value and unmarshals it into "result". + * + * Example + * + * ``` + * result := struct { + * FirstName string `json:"first_name"` + * }{} + * err := m.UnmarshalJSONField("my_field_name", &result) + * ``` + */ + unmarshalJSONField(key: string, result: any): void + } + interface Record { + /** + * BaseFilesPath returns the storage dir path used by the record. + */ + baseFilesPath(): string + } + interface Record { + /** + * FindFileFieldByFile returns the first file type field for which + * any of the record's data contains the provided filename. + */ + findFileFieldByFile(filename: string): (schema.SchemaField) + } + interface Record { + /** + * Load bulk loads the provided data into the current Record model. + */ + load(data: _TygojaDict): void + } + interface Record { + /** + * ColumnValueMap implements [ColumnValueMapper] interface. + */ + columnValueMap(): _TygojaDict + } + interface Record { + /** + * PublicExport exports only the record fields that are safe to be public. + * + * For auth records, to force the export of the email field you need to set + * `m.IgnoreEmailVisibility(true)`. + */ + publicExport(): _TygojaDict + } + interface Record { + /** + * MarshalJSON implements the [json.Marshaler] interface. + * + * Only the data exported by `PublicExport()` will be serialized. + */ + marshalJSON(): string|Array + } + interface Record { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(data: string|Array): void + } + interface Record { + /** + * ReplaceModifers returns a new map with applied modifier + * values based on the current record and the specified data. + * + * The resolved modifier keys will be removed. + * + * Multiple modifiers will be applied one after another, + * while reusing the previous base key value result (eg. 1; -5; +2 => -2). + * + * Example usage: + * + * ``` + * newData := record.ReplaceModifers(data) + * // record: {"field": 10} + * // data: {"field+": 5} + * // newData: {"field": 15} + * ``` + */ + replaceModifers(data: _TygojaDict): _TygojaDict + } + interface Record { + /** + * Username returns the "username" auth record data value. + */ + username(): string + } + interface Record { + /** + * SetUsername sets the "username" auth record data value. + * + * This method doesn't check whether the provided value is a valid username. + * + * Returns an error if the record is not from an auth collection. + */ + setUsername(username: string): void + } + interface Record { + /** + * Email returns the "email" auth record data value. + */ + email(): string + } + interface Record { + /** + * SetEmail sets the "email" auth record data value. + * + * This method doesn't check whether the provided value is a valid email. + * + * Returns an error if the record is not from an auth collection. + */ + setEmail(email: string): void + } + interface Record { + /** + * Verified returns the "emailVisibility" auth record data value. + */ + emailVisibility(): boolean + } + interface Record { + /** + * SetEmailVisibility sets the "emailVisibility" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setEmailVisibility(visible: boolean): void + } + interface Record { + /** + * Verified returns the "verified" auth record data value. + */ + verified(): boolean + } + interface Record { + /** + * SetVerified sets the "verified" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setVerified(verified: boolean): void + } + interface Record { + /** + * TokenKey returns the "tokenKey" auth record data value. + */ + tokenKey(): string + } + interface Record { + /** + * SetTokenKey sets the "tokenKey" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setTokenKey(key: string): void + } + interface Record { + /** + * RefreshTokenKey generates and sets new random auth record "tokenKey". + * + * Returns an error if the record is not from an auth collection. + */ + refreshTokenKey(): void + } + interface Record { + /** + * LastResetSentAt returns the "lastResentSentAt" auth record data value. + */ + lastResetSentAt(): types.DateTime + } + interface Record { + /** + * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setLastResetSentAt(dateTime: types.DateTime): void + } + interface Record { + /** + * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. + */ + lastVerificationSentAt(): types.DateTime + } + interface Record { + /** + * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. + */ + setLastVerificationSentAt(dateTime: types.DateTime): void + } + interface Record { + /** + * PasswordHash returns the "passwordHash" auth record data value. + */ + passwordHash(): string + } + interface Record { + /** + * ValidatePassword validates a plain password against the auth record password. + * + * Returns false if the password is incorrect or record is not from an auth collection. + */ + validatePassword(password: string): boolean + } + interface Record { + /** + * SetPassword sets cryptographically secure string to the auth record "password" field. + * This method also resets the "lastResetSentAt" and the "tokenKey" fields. + * + * Returns an error if the record is not from an auth collection or + * an empty password is provided. + */ + setPassword(password: string): void + } + /** + * RequestInfo defines a HTTP request data struct, usually used + * as part of the `@request.*` filter resolver. + */ + interface RequestInfo { + query: _TygojaDict + data: _TygojaDict + headers: _TygojaDict + authRecord?: Record + admin?: Admin + method: string + } + interface RequestInfo { + /** + * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. + */ + hasModifierDataKeys(): boolean + } +} + /** * Package daos handles common PocketBase DB model manipulations. * @@ -14418,6 +13354,1071 @@ namespace core { } } +/** + * 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 { + /** + * GenBashCompletion generates bash completion file and writes to the passed writer. + */ + genBashCompletion(w: io.Writer): void + } + interface Command { + /** + * GenBashCompletionFile generates bash completion file. + */ + genBashCompletionFile(filename: string): void + } + interface Command { + /** + * GenBashCompletionFileV2 generates Bash completion version 2. + */ + genBashCompletionFileV2(filename: string, includeDesc: boolean): void + } + interface Command { + /** + * GenBashCompletionV2 generates Bash completion file version 2 + * and writes it to the passed writer. + */ + genBashCompletionV2(w: io.Writer, includeDesc: boolean): void + } + // @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 { + /** + * 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 + */ + use: string + /** + * Aliases is an array of aliases that can be used instead of the first word in Use. + */ + aliases: Array + /** + * SuggestFor is an array of command names for which this command will be suggested - + * similar to aliases but only suggests. + */ + suggestFor: Array + /** + * Short is the short description shown in the 'help' output. + */ + short: string + /** + * The group id under which this subcommand is grouped in the 'help' output of its parent. + */ + groupID: string + /** + * Long is the long message shown in the 'help ' output. + */ + long: string + /** + * Example is examples of how to use the command. + */ + example: string + /** + * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions + */ + validArgs: Array + /** + * 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. + */ + validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] + /** + * Expected arguments + */ + args: PositionalArgs + /** + * ArgAliases is List of aliases for ValidArgs. + * These are not suggested to the user in the shell completion, + * but accepted if entered manually. + */ + argAliases: Array + /** + * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + * For portability with other shells, it is recommended to instead use ValidArgsFunction + */ + bashCompletionFunction: string + /** + * Deprecated defines, if this command is deprecated and should print this string when used. + */ + deprecated: string + /** + * Annotations are key/value pairs that can be used by applications to identify or + * group commands or set special options. + */ + annotations: _TygojaDict + /** + * 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. + */ + version: string + /** + * 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. + * The *PreRun and *PostRun functions will only be executed if the Run function of the current + * command has been declared. + * + * PersistentPreRun: children of this command will inherit and execute. + */ + persistentPreRun: (cmd: Command, args: Array) => void + /** + * PersistentPreRunE: PersistentPreRun but returns an error. + */ + persistentPreRunE: (cmd: Command, args: Array) => void + /** + * PreRun: children of this command will not inherit. + */ + preRun: (cmd: Command, args: Array) => void + /** + * PreRunE: PreRun but returns an error. + */ + preRunE: (cmd: Command, args: Array) => void + /** + * Run: Typically the actual work function. Most commands will only implement this. + */ + run: (cmd: Command, args: Array) => void + /** + * RunE: Run but returns an error. + */ + runE: (cmd: Command, args: Array) => void + /** + * PostRun: run after the Run command. + */ + postRun: (cmd: Command, args: Array) => void + /** + * PostRunE: PostRun but returns an error. + */ + 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 Command { + /** + * 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. + * + * 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. + */ + context(): context.Context + } + interface Command { + /** + * SetContext sets context for the command. This context will be overwritten by + * Command.ExecuteContext or Command.ExecuteContextC. + */ + setContext(ctx: context.Context): void + } + interface Command { + /** + * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden + * particularly useful when testing. + */ + setArgs(a: Array): void + } + interface Command { + /** + * SetOutput sets the destination for usage and error messages. + * If output is nil, os.Stderr is used. + * Deprecated: Use SetOut and/or SetErr instead + */ + setOutput(output: io.Writer): void + } + interface Command { + /** + * SetOut sets the destination for usage messages. + * If newOut is nil, os.Stdout is used. + */ + setOut(newOut: io.Writer): void + } + interface Command { + /** + * SetErr sets the destination for error messages. + * If newErr is nil, os.Stderr is used. + */ + setErr(newErr: io.Writer): void + } + interface Command { + /** + * SetIn sets the source for input data + * If newIn is nil, os.Stdin is used. + */ + setIn(newIn: io.Reader): void + } + interface Command { + /** + * SetUsageFunc sets usage function. Usage can be defined by application. + */ + setUsageFunc(f: (_arg0: Command) => void): void + } + interface Command { + /** + * SetUsageTemplate sets usage template. Can be defined by Application. + */ + setUsageTemplate(s: string): void + } + interface Command { + /** + * SetFlagErrorFunc sets a function to generate an error when flag parsing + * fails. + */ + setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void + } + interface Command { + /** + * SetHelpFunc sets help function. Can be defined by Application. + */ + setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void + } + interface Command { + /** + * SetHelpCommand sets help command. + */ + setHelpCommand(cmd: Command): void + } + interface Command { + /** + * SetHelpCommandGroupID sets the group id of the help command. + */ + setHelpCommandGroupID(groupID: string): void + } + interface Command { + /** + * SetCompletionCommandGroupID sets the group id of the completion command. + */ + setCompletionCommandGroupID(groupID: string): void + } + interface Command { + /** + * SetHelpTemplate sets help template to be used. Application can use it to set custom template. + */ + setHelpTemplate(s: string): void + } + interface Command { + /** + * SetVersionTemplate sets version template to be used. Application can use it to set custom template. + */ + setVersionTemplate(s: string): void + } + interface Command { + /** + * SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. + */ + setErrPrefix(s: string): void + } + interface Command { + /** + * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. + * The user should not have a cyclic dependency on commands. + */ + setGlobalNormalizationFunc(n: (f: any, name: string) => any): void + } + interface Command { + /** + * OutOrStdout returns output to stdout. + */ + outOrStdout(): io.Writer + } + interface Command { + /** + * OutOrStderr returns output to stderr + */ + outOrStderr(): io.Writer + } + interface Command { + /** + * ErrOrStderr returns output to stderr + */ + errOrStderr(): io.Writer + } + interface Command { + /** + * InOrStdin returns input to stdin + */ + inOrStdin(): io.Reader + } + interface Command { + /** + * UsageFunc returns either the function set by SetUsageFunc for this command + * or a parent, or it returns a default usage function. + */ + usageFunc(): (_arg0: Command) => void + } + interface Command { + /** + * Usage puts out the usage for the command. + * Used when a user provides invalid input. + * Can be defined by user by overriding UsageFunc. + */ + usage(): void + } + interface Command { + /** + * HelpFunc returns either the function set by SetHelpFunc for this command + * or a parent, or it returns a function with default help behavior. + */ + helpFunc(): (_arg0: Command, _arg1: Array) => void + } + interface Command { + /** + * Help puts out the help for the command. + * Used when a user calls help [command]. + * Can be defined by user by overriding HelpFunc. + */ + help(): void + } + interface Command { + /** + * UsageString returns usage string. + */ + usageString(): string + } + interface Command { + /** + * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this + * command or a parent, or it returns a function which returns the original + * error. + */ + flagErrorFunc(): (_arg0: Command, _arg1: Error) => void + } + interface Command { + /** + * UsagePadding return padding for the usage. + */ + usagePadding(): number + } + interface Command { + /** + * CommandPathPadding return padding for the command path. + */ + commandPathPadding(): number + } + interface Command { + /** + * NamePadding returns padding for the name. + */ + namePadding(): number + } + interface Command { + /** + * UsageTemplate returns usage template for the command. + */ + usageTemplate(): string + } + interface Command { + /** + * HelpTemplate return help template for the command. + */ + helpTemplate(): string + } + interface Command { + /** + * VersionTemplate return version template for the command. + */ + versionTemplate(): string + } + interface Command { + /** + * ErrPrefix return error message prefix for the command + */ + errPrefix(): string + } + interface Command { + /** + * Find the target command given the args and command tree + * Meant to be run on the highest node. Only searches down. + */ + find(args: Array): [(Command), Array] + } + interface Command { + /** + * Traverse the command tree to find the command, and parse args for + * each parent. + */ + traverse(args: Array): [(Command), Array] + } + interface Command { + /** + * SuggestionsFor provides suggestions for the typedName. + */ + suggestionsFor(typedName: string): Array + } + interface Command { + /** + * VisitParents visits all parents of the command and invokes fn on each parent. + */ + visitParents(fn: (_arg0: Command) => void): void + } + interface Command { + /** + * Root finds root command. + */ + root(): (Command) + } + interface Command { + /** + * ArgsLenAtDash will return the length of c.Flags().Args at the moment + * when a -- was found during args parsing. + */ + argsLenAtDash(): number + } + interface Command { + /** + * 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. + */ + executeContext(ctx: context.Context): void + } + interface Command { + /** + * Execute uses the args (os.Args[1:] by default) + * and run through the command tree finding appropriate matches + * for commands and then corresponding flags. + */ + execute(): void + } + interface Command { + /** + * 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. + */ + executeContextC(ctx: context.Context): (Command) + } + interface Command { + /** + * ExecuteC executes the command. + */ + executeC(): (Command) + } + interface Command { + validateArgs(args: Array): void + } + interface Command { + /** + * ValidateRequiredFlags validates all required flags are present and returns an error otherwise + */ + validateRequiredFlags(): void + } + interface Command { + /** + * 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. + */ + initDefaultHelpFlag(): void + } + interface Command { + /** + * 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. + */ + initDefaultVersionFlag(): void + } + interface Command { + /** + * 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. + */ + initDefaultHelpCmd(): void + } + interface Command { + /** + * ResetCommands delete parent, subcommand and help command from c. + */ + resetCommands(): void + } + interface Command { + /** + * Commands returns a sorted slice of child commands. + */ + commands(): Array<(Command | undefined)> + } + interface Command { + /** + * AddCommand adds one or more commands to this parent command. + */ + addCommand(...cmds: (Command | undefined)[]): void + } + interface Command { + /** + * Groups returns a slice of child command groups. + */ + groups(): Array<(Group | undefined)> + } + interface Command { + /** + * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group + */ + allChildCommandsHaveGroup(): boolean + } + interface Command { + /** + * ContainsGroup return if groupID exists in the list of command groups. + */ + containsGroup(groupID: string): boolean + } + interface Command { + /** + * AddGroup adds one or more command groups to this parent command. + */ + addGroup(...groups: (Group | undefined)[]): void + } + interface Command { + /** + * RemoveCommand removes one or more commands from a parent command. + */ + removeCommand(...cmds: (Command | undefined)[]): void + } + interface Command { + /** + * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. + */ + print(...i: { + }[]): void + } + interface Command { + /** + * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. + */ + println(...i: { + }[]): void + } + interface Command { + /** + * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. + */ + printf(format: string, ...i: { + }[]): void + } + interface Command { + /** + * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. + */ + printErr(...i: { + }[]): void + } + interface Command { + /** + * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. + */ + printErrln(...i: { + }[]): void + } + interface Command { + /** + * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. + */ + printErrf(format: string, ...i: { + }[]): void + } + interface Command { + /** + * CommandPath returns the full path to this command. + */ + commandPath(): string + } + interface Command { + /** + * UseLine puts out the full usage for a given command (including parents). + */ + useLine(): string + } + interface Command { + /** + * DebugFlags used to determine which flags have been assigned to which commands + * and which persist. + * nolint:goconst + */ + debugFlags(): void + } + interface Command { + /** + * Name returns the command's name: the first word in the use line. + */ + name(): string + } + interface Command { + /** + * HasAlias determines if a given string is an alias of the command. + */ + hasAlias(s: string): boolean + } + interface Command { + /** + * 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. + */ + calledAs(): string + } + interface Command { + /** + * NameAndAliases returns a list of the command name and all aliases + */ + nameAndAliases(): string + } + interface Command { + /** + * HasExample determines if the command has example. + */ + hasExample(): boolean + } + interface Command { + /** + * Runnable determines if the command is itself runnable. + */ + runnable(): boolean + } + interface Command { + /** + * HasSubCommands determines if the command has children commands. + */ + hasSubCommands(): boolean + } + interface Command { + /** + * IsAvailableCommand determines if a command is available as a non-help command + * (this includes all non deprecated/hidden commands). + */ + isAvailableCommand(): boolean + } + interface Command { + /** + * 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. + */ + isAdditionalHelpTopicCommand(): boolean + } + interface Command { + /** + * 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'. + */ + hasHelpSubCommands(): boolean + } + interface Command { + /** + * HasAvailableSubCommands determines if a command has available sub commands that + * need to be shown in the usage/help default template under 'available commands'. + */ + hasAvailableSubCommands(): boolean + } + interface Command { + /** + * HasParent determines if the command is a child command. + */ + hasParent(): boolean + } + interface Command { + /** + * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. + */ + globalNormalizationFunc(): (f: any, name: string) => any + } + interface Command { + /** + * Flags returns the complete FlagSet that applies + * to this command (local and persistent declared here and by all parents). + */ + flags(): (any) + } + interface Command { + /** + * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. + */ + localNonPersistentFlags(): (any) + } + interface Command { + /** + * LocalFlags returns the local FlagSet specifically set in the current command. + */ + localFlags(): (any) + } + interface Command { + /** + * InheritedFlags returns all flags which were inherited from parent commands. + */ + inheritedFlags(): (any) + } + interface Command { + /** + * NonInheritedFlags returns all flags which were not inherited from parent commands. + */ + nonInheritedFlags(): (any) + } + interface Command { + /** + * PersistentFlags returns the persistent FlagSet specifically set in the current command. + */ + persistentFlags(): (any) + } + interface Command { + /** + * ResetFlags deletes all flags from command. + */ + resetFlags(): void + } + interface Command { + /** + * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). + */ + hasFlags(): boolean + } + interface Command { + /** + * HasPersistentFlags checks if the command contains persistent flags. + */ + hasPersistentFlags(): boolean + } + interface Command { + /** + * HasLocalFlags checks if the command has flags specifically declared locally. + */ + hasLocalFlags(): boolean + } + interface Command { + /** + * HasInheritedFlags checks if the command has flags inherited from its parent command. + */ + hasInheritedFlags(): boolean + } + interface Command { + /** + * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire + * structure) which are not hidden or deprecated. + */ + hasAvailableFlags(): boolean + } + interface Command { + /** + * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. + */ + hasAvailablePersistentFlags(): boolean + } + interface Command { + /** + * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden + * or deprecated. + */ + hasAvailableLocalFlags(): boolean + } + interface Command { + /** + * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are + * not hidden or deprecated. + */ + hasAvailableInheritedFlags(): boolean + } + interface Command { + /** + * Flag climbs up the command tree looking for matching flag. + */ + flag(name: string): (any) + } + interface Command { + /** + * ParseFlags parses persistent flag tree and local flags. + */ + parseFlags(args: Array): void + } + interface Command { + /** + * Parent returns a commands parent command. + */ + parent(): (Command) + } + interface Command { + /** + * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. + */ + registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void + } + interface Command { + /** + * GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. + */ + getFlagCompletionFunc(flagName: string): [(_arg0: Command, _arg1: Array, _arg2: string) => [Array, ShellCompDirective], boolean] + } + interface Command { + /** + * 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. + */ + initDefaultCompletionCmd(): void + } + interface Command { + /** + * GenFishCompletion generates fish completion file and writes to the passed writer. + */ + genFishCompletion(w: io.Writer, includeDesc: boolean): void + } + interface Command { + /** + * GenFishCompletionFile generates fish completion file. + */ + genFishCompletionFile(filename: string, includeDesc: boolean): void + } + interface Command { + /** + * 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. + */ + markFlagsRequiredTogether(...flagNames: string[]): void + } + interface Command { + /** + * MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors + * if the command is invoked without at least one flag from the given set of flags. + */ + markFlagsOneRequired(...flagNames: string[]): void + } + interface Command { + /** + * 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. + */ + markFlagsMutuallyExclusive(...flagNames: string[]): void + } + interface Command { + /** + * ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the + * first error encountered. + */ + validateFlagGroups(): void + } + interface Command { + /** + * GenPowerShellCompletionFile generates powershell completion file without descriptions. + */ + genPowerShellCompletionFile(filename: string): void + } + interface Command { + /** + * GenPowerShellCompletion generates powershell completion file without descriptions + * and writes it to the passed writer. + */ + genPowerShellCompletion(w: io.Writer): void + } + interface Command { + /** + * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. + */ + genPowerShellCompletionFileWithDesc(filename: string): void + } + interface Command { + /** + * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions + * and writes it to the passed writer. + */ + genPowerShellCompletionWithDesc(w: io.Writer): void + } + interface Command { + /** + * 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. + */ + markFlagRequired(name: string): void + } + interface Command { + /** + * 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. + */ + markPersistentFlagRequired(name: string): void + } + interface Command { + /** + * MarkFlagFilename instructs the various shell completion implementations to + * limit completions for the named flag to the specified file extensions. + */ + markFlagFilename(name: string, ...extensions: string[]): void + } + interface Command { + /** + * 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. + * + * 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. + */ + markFlagCustom(name: string, f: string): void + } + interface Command { + /** + * MarkPersistentFlagFilename instructs the various shell completion + * implementations to limit completions for the named persistent flag to the + * specified file extensions. + */ + markPersistentFlagFilename(name: string, ...extensions: string[]): void + } + interface Command { + /** + * MarkFlagDirname instructs the various shell completion implementations to + * limit completions for the named flag to directory names. + */ + markFlagDirname(name: string): void + } + interface Command { + /** + * MarkPersistentFlagDirname instructs the various shell completion + * implementations to limit completions for the named persistent flag to + * directory names. + */ + markPersistentFlagDirname(name: string): void + } + interface Command { + /** + * GenZshCompletionFile generates zsh completion file including descriptions. + */ + genZshCompletionFile(filename: string): void + } + interface Command { + /** + * GenZshCompletion generates zsh completion file including descriptions + * and writes it to the passed writer. + */ + genZshCompletion(w: io.Writer): void + } + interface Command { + /** + * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + */ + genZshCompletionFileNoDesc(filename: string): void + } + interface Command { + /** + * GenZshCompletionNoDesc generates zsh completion file without descriptions + * and writes it to the passed writer. + */ + genZshCompletionNoDesc(w: io.Writer): void + } + interface Command { + /** + * 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 + */ + markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void + } + interface Command { + /** + * 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). + * + * Deprecated + */ + 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, @@ -15795,65 +15796,6 @@ namespace oauth2 { } } -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * DateTime represents a [time.Time] instance in UTC that is wrapped - * and serialized using the app default date layout. - */ - interface DateTime { - } - interface DateTime { - /** - * Time returns the internal [time.Time] instance. - */ - time(): time.Time - } - interface DateTime { - /** - * IsZero checks whether the current DateTime instance has zero time value. - */ - isZero(): boolean - } - interface DateTime { - /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. - */ - string(): string - } - interface DateTime { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface DateTime { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string|Array): void - } - interface DateTime { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface DateTime { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. - */ - scan(value: any): void - } -} - namespace store { /** * Store defines a concurrent safe in memory key-value data store. @@ -15925,16 +15867,219 @@ namespace store { } } -namespace mailer { +/** + * 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 { /** - * Mailer defines a base mail client interface. + * IsolationLevel is the transaction isolation level used in TxOptions. */ - interface Mailer { - [key:string]: any; + interface IsolationLevel extends Number{} + interface IsolationLevel { /** - * Send sends an email with the provided Message. + * String returns the name of the transaction isolation level. */ - send(message: Message): void + string(): string + } + /** + * 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. + /** + * Counters + */ + 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 { + } + interface Conn { + /** + * PingContext verifies the connection to the database is still alive. + */ + pingContext(ctx: context.Context): void + } + interface Conn { + /** + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + */ + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Conn { + /** + * 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) + } + interface Conn { + /** + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface Conn { + /** + * PrepareContext creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's Close method + * when the statement is no longer needed. + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + */ + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface Conn { + /** + * 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. + */ + raw(f: (driverConn: any) => void): void + } + interface Conn { + /** + * BeginTx starts a transaction. + * + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. Tx.Commit will return an error if the context provided to + * BeginTx is canceled. + * + * The provided TxOptions is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. + */ + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface Conn { + /** + * 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. + */ + close(): void + } + /** + * ColumnType contains the name and type of a column. + */ + interface ColumnType { + } + interface ColumnType { + /** + * Name returns the name or alias of the column. + */ + name(): string + } + interface ColumnType { + /** + * 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. + */ + length(): [number, boolean] + } + interface ColumnType { + /** + * DecimalSize returns the scale and precision of a decimal type. + * If not applicable or if not supported ok is false. + */ + decimalSize(): [number, boolean] + } + 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(): any + } + 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 } } @@ -16395,417 +16540,61 @@ namespace echo { } /** - * 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. + * Package types implements some commonly used db serializable types + * like datetime, json, etc. */ -namespace sql { +namespace types { /** - * IsolationLevel is the transaction isolation level used in TxOptions. + * DateTime represents a [time.Time] instance in UTC that is wrapped + * and serialized using the app default date layout. */ - interface IsolationLevel extends Number{} - interface IsolationLevel { + interface DateTime { + } + interface DateTime { /** - * String returns the name of the transaction isolation level. + * Time returns the internal [time.Time] instance. + */ + time(): time.Time + } + interface DateTime { + /** + * IsZero checks whether the current DateTime instance has zero time value. + */ + isZero(): boolean + } + interface DateTime { + /** + * String serializes the current DateTime instance into a formatted + * UTC date string. + * + * The zero value is serialized to an empty string. */ string(): string } - /** - * DBStats contains database statistics. - */ - interface DBStats { - maxOpenConnections: number // Maximum number of open connections to the database. + interface DateTime { /** - * Pool Status + * MarshalJSON implements the [json.Marshaler] interface. */ - 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. + marshalJSON(): string|Array + } + interface DateTime { /** - * Counters + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - 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. + unmarshalJSON(b: string|Array): void } - /** - * 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 { + interface DateTime { /** - * PingContext verifies the connection to the database is still alive. + * Value implements the [driver.Valuer] interface. */ - pingContext(ctx: context.Context): void + value(): any } - interface Conn { + interface DateTime { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Conn { - /** - * 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) - } - interface Conn { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface Conn { - /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface Conn { - /** - * 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. - */ - raw(f: (driverConn: any) => void): void - } - interface Conn { - /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. Tx.Commit will return an error if the context provided to - * BeginTx is canceled. - * - * The provided TxOptions is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. - */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) - } - interface Conn { - /** - * 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. - */ - close(): void - } - /** - * ColumnType contains the name and type of a column. - */ - interface ColumnType { - } - interface ColumnType { - /** - * Name returns the name or alias of the column. - */ - name(): string - } - interface ColumnType { - /** - * 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. - */ - length(): [number, boolean] - } - interface ColumnType { - /** - * DecimalSize returns the scale and precision of a decimal type. - * If not applicable or if not supported ok is false. - */ - decimalSize(): [number, boolean] - } - 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(): any - } - 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 - } -} - -namespace settings { - // @ts-ignore - import validation = ozzo_validation - interface TokenConfig { - secret: string - duration: number - } - interface TokenConfig { - /** - * Validate makes TokenConfig validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface SmtpConfig { - enabled: boolean - host: string - port: number - username: string - password: string - /** - * SMTP AUTH - PLAIN (default) or LOGIN - */ - authMethod: string - /** - * 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. - */ - tls: boolean - /** - * LocalName is optional domain name or IP address used for the - * EHLO/HELO exchange (if not explicitly set, defaults to "localhost"). - * - * This is required only by some SMTP servers, such as Gmail SMTP-relay. - */ - localName: string - } - interface SmtpConfig { - /** - * Validate makes SmtpConfig validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface S3Config { - enabled: boolean - bucket: string - region: string - endpoint: string - accessKey: string - secret: string - forcePathStyle: boolean - } - interface S3Config { - /** - * Validate makes S3Config validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface BackupsConfig { - /** - * Cron is a cron expression to schedule auto backups, eg. "* * * * *". - * - * Leave it empty to disable the auto backups functionality. - */ - cron: string - /** - * 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. - */ - cronMaxKeep: number - /** - * S3 is an optional S3 storage config specifying where to store the app backups. - */ - s3: S3Config - } - interface BackupsConfig { - /** - * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface MetaConfig { - appName: string - appUrl: string - hideControls: boolean - senderName: string - senderAddress: string - verificationTemplate: EmailTemplate - resetPasswordTemplate: EmailTemplate - confirmEmailChangeTemplate: EmailTemplate - } - interface MetaConfig { - /** - * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface LogsConfig { - maxDays: number - minLevel: number - logIp: boolean - } - interface LogsConfig { - /** - * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface AuthProviderConfig { - enabled: boolean - clientId: string - clientSecret: string - authUrl: string - tokenUrl: string - userApiUrl: string - displayName: string - pkce?: boolean - } - interface AuthProviderConfig { - /** - * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface AuthProviderConfig { - /** - * SetupProvider loads the current AuthProviderConfig into the specified provider. - */ - setupProvider(provider: auth.Provider): void - } - /** - * Deprecated: Will be removed in v0.9+ - */ - interface EmailAuthConfig { - enabled: boolean - exceptDomains: Array - onlyDomains: Array - minPasswordLength: number - } - interface EmailAuthConfig { - /** - * Deprecated: Will be removed in v0.9+ - */ - validate(): void - } -} - -/** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. - */ -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag - /** - * FParseErrWhitelist configures Flag parse errors to be ignored - */ - interface FParseErrWhitelist extends _TygojaAny{} - /** - * Group Structure to manage groups for commands - */ - interface Group { - id: string - title: string - } - /** - * ShellCompDirective is a bit map representing the different behaviors the shell - * can be instructed to have once completions have been provided. - */ - interface ShellCompDirective extends Number{} - /** - * CompletionOptions are the options to control shell completion - */ - interface CompletionOptions { - /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command - */ - disableDefaultCmd: boolean - /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions - */ - disableNoDescFlag: boolean - /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them - */ - disableDescriptions: boolean - /** - * HiddenDefaultCmd makes the default 'completion' command hidden - */ - hiddenDefaultCmd: boolean + scan(value: any): void } } @@ -17044,8 +16833,8 @@ namespace models { */ validate(): void } - type _subOWyjZ = BaseModel - interface Log extends _subOWyjZ { + type _subrHCRY = BaseModel + interface Log extends _subrHCRY { data: types.JsonMap message: string level: number @@ -17053,8 +16842,8 @@ namespace models { interface Log { tableName(): string } - type _subqAcBI = BaseModel - interface Param extends _subqAcBI { + type _subdXKOM = BaseModel + interface Param extends _subdXKOM { key: string value: types.JsonRaw } @@ -17075,6 +16864,169 @@ namespace models { } } +namespace mailer { + /** + * Mailer defines a base mail client interface. + */ + interface Mailer { + [key:string]: any; + /** + * Send sends an email with the provided Message. + */ + send(message: Message): void + } +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + interface TokenConfig { + secret: string + duration: number + } + interface TokenConfig { + /** + * Validate makes TokenConfig validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface SmtpConfig { + enabled: boolean + host: string + port: number + username: string + password: string + /** + * SMTP AUTH - PLAIN (default) or LOGIN + */ + authMethod: string + /** + * 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. + */ + tls: boolean + /** + * LocalName is optional domain name or IP address used for the + * EHLO/HELO exchange (if not explicitly set, defaults to "localhost"). + * + * This is required only by some SMTP servers, such as Gmail SMTP-relay. + */ + localName: string + } + interface SmtpConfig { + /** + * Validate makes SmtpConfig validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface S3Config { + enabled: boolean + bucket: string + region: string + endpoint: string + accessKey: string + secret: string + forcePathStyle: boolean + } + interface S3Config { + /** + * Validate makes S3Config validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface BackupsConfig { + /** + * Cron is a cron expression to schedule auto backups, eg. "* * * * *". + * + * Leave it empty to disable the auto backups functionality. + */ + cron: string + /** + * 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. + */ + cronMaxKeep: number + /** + * S3 is an optional S3 storage config specifying where to store the app backups. + */ + s3: S3Config + } + interface BackupsConfig { + /** + * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface MetaConfig { + appName: string + appUrl: string + hideControls: boolean + senderName: string + senderAddress: string + verificationTemplate: EmailTemplate + resetPasswordTemplate: EmailTemplate + confirmEmailChangeTemplate: EmailTemplate + } + interface MetaConfig { + /** + * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface LogsConfig { + maxDays: number + minLevel: number + logIp: boolean + } + interface LogsConfig { + /** + * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface AuthProviderConfig { + enabled: boolean + clientId: string + clientSecret: string + authUrl: string + tokenUrl: string + userApiUrl: string + displayName: string + pkce?: boolean + } + interface AuthProviderConfig { + /** + * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface AuthProviderConfig { + /** + * SetupProvider loads the current AuthProviderConfig into the specified provider. + */ + setupProvider(provider: auth.Provider): void + } + /** + * Deprecated: Will be removed in v0.9+ + */ + interface EmailAuthConfig { + enabled: boolean + exceptDomains: Array + onlyDomains: Array + minPasswordLength: number + } + interface EmailAuthConfig { + /** + * Deprecated: Will be removed in v0.9+ + */ + validate(): void + } +} + /** * Package daos handles common PocketBase DB model manipulations. * @@ -17093,6 +17045,87 @@ namespace daos { import validation = ozzo_validation } +namespace hook { + /** + * Hook defines a concurrent safe structure for handling event hooks + * (aka. callbacks propagation). + */ + interface Hook { + } + interface Hook { + /** + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + */ + preAdd(fn: Handler): string + } + interface Hook { + /** + * Add registers a new handler to the hook by appending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + */ + add(fn: Handler): string + } + interface Hook { + /** + * Remove removes a single hook handler by its id. + */ + remove(id: string): void + } + interface Hook { + /** + * RemoveAll removes all registered handlers. + */ + removeAll(): void + } + interface Hook { + /** + * Trigger executes all registered hook handlers one by one + * with the specified `data` as an argument. + * + * Optionally, this method allows also to register additional one off + * handlers that will be temporary appended to the handlers queue. + * + * The execution stops when: + * - hook.StopPropagation is returned in one of the handlers + * - any non-nil error is returned in one of the handlers + */ + trigger(data: T, ...oneOffHandlers: Handler[]): void + } + /** + * TaggedHook defines a proxy hook which register handlers that are triggered only + * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). + */ + type _subhMjQd = mainHook + interface TaggedHook extends _subhMjQd { + } + interface TaggedHook { + /** + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. + */ + canTriggerOn(tags: Array): boolean + } + interface TaggedHook { + /** + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. + */ + preAdd(fn: Handler): string + } + interface TaggedHook { + /** + * Add registers a new handler to the hook by appending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. + */ + add(fn: Handler): string + } +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -17581,95 +17614,6 @@ namespace slog { } } -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void - } -} - -namespace hook { - /** - * Hook defines a concurrent safe structure for handling event hooks - * (aka. callbacks propagation). - */ - interface Hook { - } - interface Hook { - /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). - */ - preAdd(fn: Handler): string - } - interface Hook { - /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). - */ - add(fn: Handler): string - } - interface Hook { - /** - * Remove removes a single hook handler by its id. - */ - remove(id: string): void - } - interface Hook { - /** - * RemoveAll removes all registered handlers. - */ - removeAll(): void - } - interface Hook { - /** - * Trigger executes all registered hook handlers one by one - * with the specified `data` as an argument. - * - * Optionally, this method allows also to register additional one off - * handlers that will be temporary appended to the handlers queue. - * - * The execution stops when: - * - hook.StopPropagation is returned in one of the handlers - * - any non-nil error is returned in one of the handlers - */ - trigger(data: T, ...oneOffHandlers: Handler[]): void - } - /** - * TaggedHook defines a proxy hook which register handlers that are triggered only - * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). - */ - type _subfJVVT = mainHook - interface TaggedHook extends _subfJVVT { - } - interface TaggedHook { - /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. - */ - canTriggerOn(tags: Array): boolean - } - interface TaggedHook { - /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. - */ - preAdd(fn: Handler): string - } - interface TaggedHook { - /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. - */ - add(fn: Handler): string - } -} - namespace subscriptions { /** * Broker defines a struct for managing subscriptions clients. @@ -17730,12 +17674,12 @@ namespace core { httpContext: echo.Context error: Error } - type _subysixL = BaseModelEvent - interface ModelEvent extends _subysixL { + type _subDSdPT = BaseModelEvent + interface ModelEvent extends _subDSdPT { dao?: daos.Dao } - type _subzleRl = BaseCollectionEvent - interface MailerRecordEvent extends _subzleRl { + type _subDETis = BaseCollectionEvent + interface MailerRecordEvent extends _subDETis { mailClient: mailer.Mailer message?: mailer.Message record?: models.Record @@ -17775,50 +17719,50 @@ namespace core { oldSettings?: settings.Settings newSettings?: settings.Settings } - type _subcgdth = BaseCollectionEvent - interface RecordsListEvent extends _subcgdth { + type _subuYgfi = BaseCollectionEvent + interface RecordsListEvent extends _subuYgfi { httpContext: echo.Context records: Array<(models.Record | undefined)> result?: search.Result } - type _subDDAZm = BaseCollectionEvent - interface RecordViewEvent extends _subDDAZm { + type _subQCnMQ = BaseCollectionEvent + interface RecordViewEvent extends _subQCnMQ { httpContext: echo.Context record?: models.Record } - type _subLiCOx = BaseCollectionEvent - interface RecordCreateEvent extends _subLiCOx { + type _subizIyc = BaseCollectionEvent + interface RecordCreateEvent extends _subizIyc { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subaJmpw = BaseCollectionEvent - interface RecordUpdateEvent extends _subaJmpw { + type _subvLpbi = BaseCollectionEvent + interface RecordUpdateEvent extends _subvLpbi { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subQsPge = BaseCollectionEvent - interface RecordDeleteEvent extends _subQsPge { + type _subLSFxY = BaseCollectionEvent + interface RecordDeleteEvent extends _subLSFxY { httpContext: echo.Context record?: models.Record } - type _suboPcla = BaseCollectionEvent - interface RecordAuthEvent extends _suboPcla { + type _subCNKPC = BaseCollectionEvent + interface RecordAuthEvent extends _subCNKPC { httpContext: echo.Context record?: models.Record token: string meta: any } - type _subliZDX = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subliZDX { + type _subbmgCw = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subbmgCw { httpContext: echo.Context record?: models.Record identity: string password: string } - type _subhmcVV = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subhmcVV { + type _suboocdH = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _suboocdH { httpContext: echo.Context providerName: string providerClient: auth.Provider @@ -17826,49 +17770,49 @@ namespace core { oAuth2User?: auth.AuthUser isNewRecord: boolean } - type _subaQxYZ = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subaQxYZ { + type _subysYni = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subysYni { httpContext: echo.Context record?: models.Record } - type _subAiBwL = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subAiBwL { + type _subLdHtH = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subLdHtH { httpContext: echo.Context record?: models.Record } - type _subtaXzr = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subtaXzr { + type _subqQHmF = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _subqQHmF { httpContext: echo.Context record?: models.Record } - type _subWagiq = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subWagiq { + type _subzJnqo = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subzJnqo { httpContext: echo.Context record?: models.Record } - type _subOteTg = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subOteTg { + type _subcZHsF = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subcZHsF { httpContext: echo.Context record?: models.Record } - type _subtnUxE = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subtnUxE { + type _subGdKEM = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subGdKEM { httpContext: echo.Context record?: models.Record } - type _subTuKwK = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subTuKwK { + type _subxkRue = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subxkRue { httpContext: echo.Context record?: models.Record } - type _subFWHdN = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subFWHdN { + type _suburKkX = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _suburKkX { httpContext: echo.Context record?: models.Record externalAuths: Array<(models.ExternalAuth | undefined)> } - type _subHiJlK = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subHiJlK { + type _subadfsh = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subadfsh { httpContext: echo.Context record?: models.Record externalAuth?: models.ExternalAuth @@ -17922,33 +17866,33 @@ namespace core { collections: Array<(models.Collection | undefined)> result?: search.Result } - type _subLpBJX = BaseCollectionEvent - interface CollectionViewEvent extends _subLpBJX { + type _subJuNba = BaseCollectionEvent + interface CollectionViewEvent extends _subJuNba { httpContext: echo.Context } - type _subslQUf = BaseCollectionEvent - interface CollectionCreateEvent extends _subslQUf { + type _subgtTDO = BaseCollectionEvent + interface CollectionCreateEvent extends _subgtTDO { httpContext: echo.Context } - type _subMToFc = BaseCollectionEvent - interface CollectionUpdateEvent extends _subMToFc { + type _subTgUJG = BaseCollectionEvent + interface CollectionUpdateEvent extends _subTgUJG { httpContext: echo.Context } - type _subRvUIg = BaseCollectionEvent - interface CollectionDeleteEvent extends _subRvUIg { + type _subhIwSo = BaseCollectionEvent + interface CollectionDeleteEvent extends _subhIwSo { httpContext: echo.Context } interface CollectionsImportEvent { httpContext: echo.Context collections: Array<(models.Collection | undefined)> } - type _subJOUlk = BaseModelEvent - interface FileTokenEvent extends _subJOUlk { + type _subMyDhB = BaseModelEvent + interface FileTokenEvent extends _subMyDhB { httpContext: echo.Context token: string } - type _subRNktK = BaseCollectionEvent - interface FileDownloadEvent extends _subRNktK { + type _subpjole = BaseCollectionEvent + interface FileDownloadEvent extends _subpjole { httpContext: echo.Context record?: models.Record fileField?: schema.SchemaField @@ -17957,6 +17901,66 @@ namespace core { } } +/** + * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. + * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. + */ +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag + /** + * FParseErrWhitelist configures Flag parse errors to be ignored + */ + interface FParseErrWhitelist extends _TygojaAny{} + /** + * Group Structure to manage groups for commands + */ + interface Group { + id: string + title: string + } + /** + * ShellCompDirective is a bit map representing the different behaviors the shell + * can be instructed to have once completions have been provided. + */ + interface ShellCompDirective extends Number{} + /** + * CompletionOptions are the options to control shell completion + */ + interface CompletionOptions { + /** + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command + */ + disableDefaultCmd: boolean + /** + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions + */ + disableNoDescFlag: boolean + /** + * DisableDescriptions turns off all completion descriptions for shells + * that support them + */ + disableDescriptions: boolean + /** + * HiddenDefaultCmd makes the default 'completion' command hidden + */ + hiddenDefaultCmd: boolean + } +} + +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void + } +} + +namespace store { +} + /** * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer * object, creating another object (Reader or Writer) that also implements @@ -17967,8 +17971,8 @@ namespace bufio { * ReadWriter stores pointers to a Reader and a Writer. * It implements io.ReadWriter. */ - type _subBkluq = Reader&Writer - interface ReadWriter extends _subBkluq { + type _subQjObr = Reader&Writer + interface ReadWriter extends _subQjObr { } } @@ -18305,87 +18309,161 @@ namespace http { import urlpkg = url } -namespace subscriptions { +/** + * Package echo implements high performance, minimalist Go web framework. + * + * Example: + * + * ``` + * package main + * + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) + * + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } + * + * func main() { + * // Echo instance + * e := echo.New() + * + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) + * + * // Routes + * e.GET("/", hello) + * + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } + * ``` + * + * Learn more at https://echo.labstack.com + */ +namespace echo { + // @ts-ignore + import stdContext = context /** - * Message defines a client's channel data. + * 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 Message { + interface Route { + method: string + path: string + handler: HandlerFunc + middlewares: Array name: string - data: string|Array + } + 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 } /** - * Client is an interface for a generic subscription client. + * 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 Client { + interface RoutableContext { [key:string]: any; /** - * Id Returns the unique id of the client. + * Request returns `*http.Request`. */ - id(): string + request(): (http.Request) /** - * Channel returns the client's communication channel. + * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. */ - channel(): undefined + rawPathParams(): (PathParams) /** - * Subscriptions returns a shallow copy of the the client subscriptions matching the prefixes. - * If no prefix is specified, returns all subscriptions. + * 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. */ - subscriptions(...prefixes: string[]): _TygojaDict + setRawPathParams(params: PathParams): void /** - * Subscribe subscribes the client to the provided subscriptions list. - * - * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. - * - * Example: - * - * ``` - * Subscribe( - * "subscriptionA", - * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, - * ) - * ``` + * SetPath sets the registered path for the handler. */ - subscribe(...subs: string[]): void + setPath(p: string): void /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. + * SetRouteInfo sets the route info of this request to the context. */ - unsubscribe(...subs: string[]): void + setRouteInfo(ri: RouteInfo): void /** - * HasSubscription checks if the client is subscribed to `sub`. + * 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. */ - hasSubscription(sub: string): boolean - /** - * Set stores any value to the client's context. - */ - set(key: string, value: any): void - /** - * Unset removes a single value from the client's context. - */ - unset(key: string): void - /** - * Get retrieves the key value from the client's context. - */ - get(key: string): any - /** - * Discard marks the client as "discarded", meaning that it - * shouldn't be used anymore for sending new messages. - * - * It is safe to call Discard() multiple times. - */ - discard(): void - /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. - */ - isDiscarded(): boolean - /** - * Send sends the specified message to the client's channel (if not discarded). - */ - send(m: Message): void + set(key: string, val: { + }): void + } + /** + * PathParam is tuple pf path parameter name and its value in request path + */ + interface PathParam { + name: string + value: string } } -namespace store { +/** + * 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 Array{} + interface JsonRaw { + /** + * String returns the current JsonRaw instance as a json encoded string. + */ + string(): string + } + interface JsonRaw { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface JsonRaw { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string|Array): void + } + interface JsonRaw { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JsonRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. + */ + scan(value: any): void + } } namespace mailer { @@ -18405,6 +18483,55 @@ namespace mailer { } } +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 + } + interface EmailTemplate { + /** + * Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface EmailTemplate { + /** + * Resolve replaces the placeholder parameters in the current email + * template and returns its components as ready-to-use strings. + */ + resolve(appName: string, appUrl: string): string + } +} + +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 _subdmYLH = Hook + interface mainHook extends _subdmYLH { + } +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -18942,209 +19069,83 @@ namespace slog { import loginternal = internal } -/** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com - */ -namespace echo { - // @ts-ignore - import stdContext = context +namespace subscriptions { /** - * 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. + * Message defines a client's channel data. */ - interface Route { - method: string - path: string - handler: HandlerFunc - middlewares: Array + interface Message { 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 + data: string|Array } /** - * 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. + * Client is an interface for a generic subscription client. */ - interface RoutableContext { + interface Client { [key:string]: any; /** - * Request returns `*http.Request`. + * Id Returns the unique id of the client. */ - request(): (http.Request) + id(): string /** - * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. + * Channel returns the client's communication channel. */ - rawPathParams(): (PathParams) + channel(): 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. + * Subscriptions returns a shallow copy of the the client subscriptions matching the prefixes. + * If no prefix is specified, returns all subscriptions. */ - setRawPathParams(params: PathParams): void + subscriptions(...prefixes: string[]): _TygojaDict /** - * SetPath sets the registered path for the handler. + * Subscribe subscribes the client to the provided subscriptions list. + * + * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. + * + * Example: + * + * ``` + * Subscribe( + * "subscriptionA", + * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, + * ) + * ``` */ - setPath(p: string): void + subscribe(...subs: string[]): void /** - * SetRouteInfo sets the route info of this request to the context. + * Unsubscribe unsubscribes the client from the provided subscriptions list. */ - setRouteInfo(ri: RouteInfo): void + unsubscribe(...subs: string[]): 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. + * HasSubscription checks if the client is subscribed to `sub`. */ - set(key: string, val: { - }): void - } - /** - * PathParam is tuple pf path parameter name and its value in request path - */ - interface PathParam { - name: string - value: string - } -} - -/** - * 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 Array{} - interface JsonRaw { + hasSubscription(sub: string): boolean /** - * String returns the current JsonRaw instance as a json encoded string. + * Set stores any value to the client's context. */ - string(): string - } - interface JsonRaw { + set(key: string, value: any): void /** - * MarshalJSON implements the [json.Marshaler] interface. + * Unset removes a single value from the client's context. */ - marshalJSON(): string|Array - } - interface JsonRaw { + unset(key: string): void /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * Get retrieves the key value from the client's context. */ - unmarshalJSON(b: string|Array): void - } - interface JsonRaw { + get(key: string): any /** - * Value implements the [driver.Valuer] interface. + * 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(): any - } - interface JsonRaw { + discard(): void /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. */ - scan(value: any): void - } -} - -namespace search { - /** - * Result defines the returned search result structure. - */ - interface Result { - page: number - perPage: number - totalItems: number - totalPages: number - items: any - } -} - -namespace settings { - // @ts-ignore - import validation = ozzo_validation - interface EmailTemplate { - body: string - subject: string - actionUrl: string - } - interface EmailTemplate { + isDiscarded(): boolean /** - * Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface. + * Send sends the specified message to the client's channel (if not discarded). */ - validate(): void - } - interface EmailTemplate { - /** - * Resolve replaces the placeholder parameters in the current email - * template and returns its components as ready-to-use strings. - */ - resolve(appName: string, appUrl: string): string - } -} - -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 _subiEUJe = Hook - interface mainHook extends _subiEUJe { + send(m: Message): void } } @@ -19433,7 +19434,11 @@ namespace bufio { } } -namespace subscriptions { +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { } /** @@ -19472,6 +19477,9 @@ namespace mail { } } +namespace search { +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -20015,14 +20023,7 @@ namespace slog { } } -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { -} - -namespace search { +namespace subscriptions { } /** diff --git a/plugins/jsvm/internal/types/types.go b/plugins/jsvm/internal/types/types.go index aad528b6..2b925c86 100644 --- a/plugins/jsvm/internal/types/types.go +++ b/plugins/jsvm/internal/types/types.go @@ -1,12 +1,14 @@ package main import ( + "fmt" "log" "os" "path/filepath" "reflect" "runtime" "strings" + "time" "github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/plugins/jsvm" @@ -1095,6 +1097,10 @@ func main() { result = strings.ReplaceAll(result, "ORIGINAL_CORE_APP", "core.App") result = strings.ReplaceAll(result, "ORIGINAL_POCKETBASE", "pocketbase.PocketBase") + // prepend a timestamp with the generation time + // so that it can be compared without reading the entire file + result = fmt.Sprintf("// %d\n%s", time.Now().Unix(), result) + parentDir := filepath.Dir(filename) typesFile := filepath.Join(parentDir, "generated", "types.d.ts") diff --git a/plugins/jsvm/jsvm.go b/plugins/jsvm/jsvm.go index 6fa1c823..cd21cc09 100644 --- a/plugins/jsvm/jsvm.go +++ b/plugins/jsvm/jsvm.go @@ -9,8 +9,10 @@ package jsvm import ( + "bytes" "errors" "fmt" + "io" "io/fs" "os" "path/filepath" @@ -77,6 +79,9 @@ type Config struct { // TypeScript declarations file. // // If not set it fallbacks to "pb_data". + // + // Note: Avoid using the same directory as the HooksDir when HooksWatch is enabled + // to prevent unnecessary app restarts when the types file is initially created. TypesDir string } @@ -117,10 +122,9 @@ func Register(app core.App, config Config) error { } p.app.OnAfterBootstrap().Add(func(e *core.BootstrapEvent) error { - // always update the app types on start to ensure that - // the user has the latest generated declarations - if err := p.saveTypesFile(); err != nil { - color.Yellow("Unable to save app types file: %v", err) + // ensure that the user has the latest types declaration + if err := p.refreshTypesFile(); err != nil { + color.Yellow("Unable to refresh app types file: %v", err) } return nil @@ -423,8 +427,8 @@ func (p *plugin) relativeTypesPath(basepath string) string { return rel } -// saveTypesFile saves the embedded TS declarations as a file on the disk. -func (p *plugin) saveTypesFile() error { +// refreshTypesFile saves the embedded TS declarations as a file on the disk. +func (p *plugin) refreshTypesFile() error { fullPath := p.fullTypesPath() // ensure that the types directory exists @@ -439,11 +443,20 @@ func (p *plugin) saveTypesFile() error { return err } - if err := os.WriteFile(fullPath, data, 0644); err != nil { - return err + // read the first timestamp line of the old file (if exists) and compare it to the embedded one + // (note: ignore errors to allow always overwriting the file if it is invalid) + existingFile, err := os.Open(fullPath) + if err == nil { + timestamp := make([]byte, 13) + io.ReadFull(existingFile, timestamp) + existingFile.Close() + + if len(data) >= len(timestamp) && bytes.Equal(data[:13], timestamp) { + return nil // nothing new to save + } } - return nil + return os.WriteFile(fullPath, data, 0644) } // prependToEmptyFile prepends the specified text to an empty file. diff --git a/pocketbase.go b/pocketbase.go index 1a1d3970..9b68c254 100644 --- a/pocketbase.go +++ b/pocketbase.go @@ -203,7 +203,7 @@ func (pb *PocketBase) eagerParseFlags(config *Config) error { &pb.devFlag, "dev", config.DefaultDev, - "enable dev mode, aka. printing logs and sql statements", + "enable dev mode, aka. printing logs and sql statements to the console", ) return pb.RootCmd.ParseFlags(os.Args[1:])