diff --git a/go.mod b/go.mod index 0bf5d2a8e..31b4b5d88 100644 --- a/go.mod +++ b/go.mod @@ -25,6 +25,7 @@ require ( golang.org/x/crypto v0.11.0 golang.org/x/net v0.12.0 golang.org/x/oauth2 v0.10.0 + golang.org/x/sync v0.3.0 modernc.org/sqlite v1.23.1 ) diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index 1bc7958de..5b8bdc03b 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -874,145 +874,417 @@ declare function migrate( type _TygojaDict = { [key:string | number | symbol]: any; } type _TygojaAny = any -/** - * Package validation provides configurable and extensible rules for validating data of various types. - */ -namespace ozzo_validation { - /** - * Error interface represents an validation error - */ - interface Error { - error(): string - code(): string - message(): string - setMessage(_arg0: string): Error - params(): _TygojaDict - setParams(_arg0: _TygojaDict): Error - } -} - -/** - * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. - */ -namespace dbx { - /** - * Builder supports building SQL statements in a DB-agnostic way. - * Builder mainly provides two sets of query building methods: those building SELECT statements - * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). - */ - interface Builder { +namespace security { + // @ts-ignore + import crand = rand + interface s256Challenge { /** - * NewQuery creates a new Query object with the given SQL statement. - * The SQL statement may contain parameter placeholders which can be bound with actual parameter - * values before the statement is executed. + * S256Challenge creates base64 encoded sha256 challenge string derived from code. + * The padding of the result base64 string is stripped per [RFC 7636]. + * + * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 */ - newQuery(_arg0: string): (Query | undefined) + (code: string): string + } + interface encrypt { /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * Encrypt encrypts data with key (must be valid 32 char aes key). */ - select(..._arg0: string[]): (SelectQuery | undefined) + (data: string, key: string): string + } + interface decrypt { /** - * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. - * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. + * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). */ - model(_arg0: { - }): (ModelQuery | undefined) + (cipherText: string, key: string): string + } + interface parseUnverifiedJWT { /** - * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. + * ParseUnverifiedJWT parses JWT token and returns its claims + * but DOES NOT verify the signature. + * + * It verifies only the exp, iat and nbf claims. */ - generatePlaceholder(_arg0: number): string + (token: string): jwt.MapClaims + } + interface parseJWT { /** - * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + * ParseJWT verifies and parses JWT token and returns its claims. */ - quote(_arg0: string): string + (token: string, verificationKey: string): jwt.MapClaims + } + interface newJWT { /** - * QuoteSimpleTableName quotes a simple table name. - * A simple table name does not contain any schema prefix. + * NewJWT generates and returns new HS256 signed JWT token. */ - quoteSimpleTableName(_arg0: string): string + (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + } + interface newToken { /** - * QuoteSimpleColumnName quotes a simple column name. - * A simple column name does not contain any table prefix. + * Deprecated: + * Consider replacing with NewJWT(). + * + * NewToken is a legacy alias for NewJWT that generates a HS256 signed JWT token. */ - quoteSimpleColumnName(_arg0: string): string + (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + } + // @ts-ignore + import cryptoRand = rand + // @ts-ignore + import mathRand = rand + interface randomString { /** - * QueryBuilder returns the query builder supporting the current DB. + * RandomString generates a cryptographically random string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. */ - queryBuilder(): QueryBuilder + (length: number): string + } + interface randomStringWithAlphabet { /** - * Insert creates a Query that represents an INSERT SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * RandomStringWithAlphabet generates a cryptographically random string + * with the specified length and characters set. + * + * It panics if for some reason rand.Int returns a non-nil error. */ - insert(table: string, cols: Params): (Query | undefined) + (length: number, alphabet: string): string + } + interface pseudorandomString { /** - * Upsert creates a Query that represents an UPSERT SQL statement. - * Upsert inserts a row into the table if the primary key or unique index is not found. - * Otherwise it will update the row with the new values. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * PseudorandomString generates a pseudorandom string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * + * For a cryptographically random string (but a little bit slower) use RandomString instead. */ - upsert(table: string, cols: Params, ...constraints: string[]): (Query | undefined) + (length: number): string + } + interface pseudorandomStringWithAlphabet { /** - * Update creates a Query that represents an UPDATE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding new column - * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will update ALL rows in the table). + * PseudorandomStringWithAlphabet generates a pseudorandom string + * with the specified length and characters set. + * + * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. */ - update(table: string, cols: Params, where: Expression): (Query | undefined) + (length: number, alphabet: string): string + } +} + +namespace filesystem { + /** + * FileReader defines an interface for a file resource reader. + */ + interface FileReader { + 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 { + name: string + originalName: string + size: number + reader: FileReader + } + interface newFileFromPath { /** - * Delete creates a Query that represents a DELETE SQL statement. - * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will delete ALL rows in the table). + * NewFileFromPath creates a new File instance from the provided local file path. */ - delete(table: string, where: Expression): (Query | undefined) + (path: string): (File | undefined) + } + interface newFileFromBytes { /** - * CreateTable creates a Query that represents a CREATE TABLE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column types. - * The optional "options" parameters will be appended to the generated SQL statement. + * NewFileFromBytes creates a new File instance from the provided byte slice. */ - createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query | undefined) + (b: string, name: string): (File | undefined) + } + interface newFileFromMultipart { /** - * RenameTable creates a Query that can be used to rename a table. + * NewFileFromMultipart creates a new File instace from the provided multipart header. */ - renameTable(oldName: string): (Query | undefined) + (mh: multipart.FileHeader): (File | undefined) + } + /** + * MultipartReader defines a FileReader from [multipart.FileHeader]. + */ + interface MultipartReader { + header?: multipart.FileHeader + } + interface MultipartReader { /** - * DropTable creates a Query that can be used to drop a table. + * Open implements the [filesystem.FileReader] interface. */ - dropTable(table: string): (Query | undefined) + open(): io.ReadSeekCloser + } + /** + * PathReader defines a FileReader from a local file path. + */ + interface PathReader { + path: string + } + interface PathReader { /** - * TruncateTable creates a Query that can be used to truncate a table. + * Open implements the [filesystem.FileReader] interface. */ - truncateTable(table: string): (Query | undefined) + open(): io.ReadSeekCloser + } + /** + * BytesReader defines a FileReader from bytes content. + */ + interface BytesReader { + bytes: string + } + interface BytesReader { /** - * AddColumn creates a Query that can be used to add a column to a table. + * Open implements the [filesystem.FileReader] interface. */ - addColumn(table: string): (Query | undefined) + open(): io.ReadSeekCloser + } + type _subFxgVq = bytes.Reader + interface bytesReadSeekCloser extends _subFxgVq { + } + interface bytesReadSeekCloser { /** - * DropColumn creates a Query that can be used to drop a column from a table. + * Close implements the [io.ReadSeekCloser] interface. */ - dropColumn(table: string): (Query | undefined) + close(): void + } + interface System { + } + interface newS3 { /** - * RenameColumn creates a Query that can be used to rename a column in a table. + * NewS3 initializes an S3 filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. */ - renameColumn(table: string): (Query | undefined) + (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System | undefined) + } + interface newLocal { /** - * AlterColumn creates a Query that can be used to change the definition of a table column. + * NewLocal initializes a new local filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. */ - alterColumn(table: string): (Query | undefined) + (dirPath: string): (System | undefined) + } + interface System { /** - * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. - * The "name" parameter specifies the name of the primary key constraint. + * SetContext assigns the specified context to the current filesystem. */ - addPrimaryKey(table: string, ...cols: string[]): (Query | undefined) + setContext(ctx: context.Context): void + } + interface System { /** - * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + * Close releases any resources used for the related filesystem. */ - dropPrimaryKey(table: string): (Query | undefined) + close(): void + } + interface System { /** - * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. + * 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 | undefined) + } + 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 | undefined) + } + 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, 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 dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. + */ +namespace dbx { + /** + * Builder supports building SQL statements in a DB-agnostic way. + * Builder mainly provides two sets of query building methods: those building SELECT statements + * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). + */ + interface Builder { + /** + * NewQuery creates a new Query object with the given SQL statement. + * The SQL statement may contain parameter placeholders which can be bound with actual parameter + * values before the statement is executed. + */ + newQuery(_arg0: string): (Query | undefined) + /** + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + */ + select(..._arg0: string[]): (SelectQuery | undefined) + /** + * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. + * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. + */ + model(_arg0: { + }): (ModelQuery | undefined) + /** + * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. + */ + generatePlaceholder(_arg0: number): string + /** + * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + */ + quote(_arg0: string): string + /** + * QuoteSimpleTableName quotes a simple table name. + * A simple table name does not contain any schema prefix. + */ + quoteSimpleTableName(_arg0: string): string + /** + * QuoteSimpleColumnName quotes a simple column name. + * A simple column name does not contain any table prefix. + */ + quoteSimpleColumnName(_arg0: string): string + /** + * QueryBuilder returns the query builder supporting the current DB. + */ + queryBuilder(): QueryBuilder + /** + * Insert creates a Query that represents an INSERT SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. + */ + insert(table: string, cols: Params): (Query | undefined) + /** + * Upsert creates a Query that represents an UPSERT SQL statement. + * Upsert inserts a row into the table if the primary key or unique index is not found. + * Otherwise it will update the row with the new values. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. + */ + upsert(table: string, cols: Params, ...constraints: string[]): (Query | undefined) + /** + * Update creates a Query that represents an UPDATE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding new column + * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will update ALL rows in the table). + */ + update(table: string, cols: Params, where: Expression): (Query | undefined) + /** + * Delete creates a Query that represents a DELETE SQL statement. + * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will delete ALL rows in the table). + */ + delete(table: string, where: Expression): (Query | undefined) + /** + * CreateTable creates a Query that represents a CREATE TABLE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column types. + * The optional "options" parameters will be appended to the generated SQL statement. + */ + createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query | undefined) + /** + * RenameTable creates a Query that can be used to rename a table. + */ + renameTable(oldName: string): (Query | undefined) + /** + * DropTable creates a Query that can be used to drop a table. + */ + dropTable(table: string): (Query | undefined) + /** + * TruncateTable creates a Query that can be used to truncate a table. + */ + truncateTable(table: string): (Query | undefined) + /** + * AddColumn creates a Query that can be used to add a column to a table. + */ + addColumn(table: string): (Query | undefined) + /** + * DropColumn creates a Query that can be used to drop a column from a table. + */ + dropColumn(table: string): (Query | undefined) + /** + * RenameColumn creates a Query that can be used to rename a column in a table. + */ + renameColumn(table: string): (Query | undefined) + /** + * AlterColumn creates a Query that can be used to change the definition of a table column. + */ + alterColumn(table: string): (Query | undefined) + /** + * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. + * The "name" parameter specifies the name of the primary key constraint. + */ + addPrimaryKey(table: string, ...cols: string[]): (Query | undefined) + /** + * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + */ + dropPrimaryKey(table: string): (Query | undefined) + /** + * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. * The length of cols and refCols must be the same as they refer to the primary and referential columns. * The optional "options" parameters will be appended to the SQL statement. They can be used to * specify options such as "ON DELETE CASCADE". @@ -1226,14 +1498,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subkdSxo = BaseBuilder - interface MssqlBuilder extends _subkdSxo { + type _subIyvJX = BaseBuilder + interface MssqlBuilder extends _subIyvJX { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subecIan = BaseQueryBuilder - interface MssqlQueryBuilder extends _subecIan { + type _subeTnPU = BaseQueryBuilder + interface MssqlQueryBuilder extends _subeTnPU { } interface newMssqlBuilder { /** @@ -1304,8 +1576,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _suboVrza = BaseBuilder - interface MysqlBuilder extends _suboVrza { + type _subEKFMM = BaseBuilder + interface MysqlBuilder extends _subEKFMM { } interface newMysqlBuilder { /** @@ -1380,14 +1652,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subueOxX = BaseBuilder - interface OciBuilder extends _subueOxX { + type _subykazj = BaseBuilder + interface OciBuilder extends _subykazj { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subKDwab = BaseQueryBuilder - interface OciQueryBuilder extends _subKDwab { + type _subaYfNx = BaseQueryBuilder + interface OciQueryBuilder extends _subaYfNx { } interface newOciBuilder { /** @@ -1450,8 +1722,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subkShHb = BaseBuilder - interface PgsqlBuilder extends _subkShHb { + type _subwPFGV = BaseBuilder + interface PgsqlBuilder extends _subwPFGV { } interface newPgsqlBuilder { /** @@ -1518,8 +1790,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subgqpyP = BaseBuilder - interface SqliteBuilder extends _subgqpyP { + type _subYRYyh = BaseBuilder + interface SqliteBuilder extends _subYRYyh { } interface newSqliteBuilder { /** @@ -1618,8 +1890,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subOHWmL = BaseBuilder - interface StandardBuilder extends _subOHWmL { + type _subVUxmj = BaseBuilder + interface StandardBuilder extends _subVUxmj { } interface newStandardBuilder { /** @@ -1685,8 +1957,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 _subtlJPz = Builder - interface DB extends _subtlJPz { + type _subyYqXH = Builder + interface DB extends _subyYqXH { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -2484,8 +2756,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 _subzQJfr = sql.Rows - interface Rows extends _subzQJfr { + type _subjvDLd = sql.Rows + interface Rows extends _subjvDLd { } interface Rows { /** @@ -2842,8 +3114,8 @@ namespace dbx { }): string } interface structInfo { } - type _subDgmtt = structInfo - interface structValue extends _subDgmtt { + type _subIdlNx = structInfo + interface structValue extends _subIdlNx { } interface fieldInfo { } @@ -2881,8 +3153,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subYRKhR = Builder - interface Tx extends _subYRKhR { + type _subGGVKV = Builder + interface Tx extends _subGGVKV { } interface Tx { /** @@ -2898,1389 +3170,1117 @@ namespace dbx { } } -namespace security { - // @ts-ignore - import crand = rand - interface s256Challenge { +/** + * Package validation provides configurable and extensible rules for validating data of various types. + */ +namespace ozzo_validation { + /** + * Error interface represents an validation error + */ + interface Error { + error(): string + code(): string + message(): string + setMessage(_arg0: string): Error + params(): _TygojaDict + setParams(_arg0: _TygojaDict): Error + } +} + +/** + * Package tokens implements various user and admin tokens generation methods. + */ +namespace tokens { + interface newAdminAuthToken { /** - * S256Challenge creates base64 encoded sha256 challenge string derived from code. - * The padding of the result base64 string is stripped per [RFC 7636]. - * - * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 + * NewAdminAuthToken generates and returns a new admin authentication token. */ - (code: string): string + (app: core.App, admin: models.Admin): string } - interface encrypt { + interface newAdminResetPasswordToken { /** - * Encrypt encrypts data with key (must be valid 32 char aes key). + * NewAdminResetPasswordToken generates and returns a new admin password reset request token. */ - (data: string, key: string): string + (app: core.App, admin: models.Admin): string } - interface decrypt { + interface newAdminFileToken { /** - * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). + * NewAdminFileToken generates and returns a new admin private file access token. */ - (cipherText: string, key: string): string + (app: core.App, admin: models.Admin): string } - interface parseUnverifiedJWT { + interface newRecordAuthToken { /** - * ParseUnverifiedJWT parses JWT token and returns its claims - * but DOES NOT verify the signature. - * - * It verifies only the exp, iat and nbf claims. + * NewRecordAuthToken generates and returns a new auth record authentication token. */ - (token: string): jwt.MapClaims + (app: core.App, record: models.Record): string } - interface parseJWT { + interface newRecordVerifyToken { /** - * ParseJWT verifies and parses JWT token and returns its claims. + * NewRecordVerifyToken generates and returns a new record verification token. */ - (token: string, verificationKey: string): jwt.MapClaims + (app: core.App, record: models.Record): string } - interface newJWT { + interface newRecordResetPasswordToken { /** - * NewJWT generates and returns new HS256 signed JWT token. + * NewRecordResetPasswordToken generates and returns a new auth record password reset request token. */ - (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + (app: core.App, record: models.Record): string } - interface newToken { + interface newRecordChangeEmailToken { /** - * Deprecated: - * Consider replacing with NewJWT(). - * - * NewToken is a legacy alias for NewJWT that generates a HS256 signed JWT token. + * NewRecordChangeEmailToken generates and returns a new auth record change email request token. */ - (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + (app: core.App, record: models.Record, newEmail: string): string } + interface newRecordFileToken { + /** + * NewRecordFileToken generates and returns a new record private file access token. + */ + (app: core.App, record: models.Record): string + } +} + +/** + * Package models implements various services used for request data + * validation and applying changes to existing DB models through the app Dao. + */ +namespace forms { // @ts-ignore - import cryptoRand = rand - // @ts-ignore - import mathRand = rand - interface randomString { + import validation = ozzo_validation + /** + * AdminLogin is an admin email/pass login form. + */ + interface AdminLogin { + identity: string + password: string + } + interface newAdminLogin { /** - * RandomString generates a cryptographically random string with the specified length. + * NewAdminLogin creates a new [AdminLogin] form initialized with + * the provided [core.App] instance. * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. */ - (length: number): string + (app: core.App): (AdminLogin | undefined) } - interface randomStringWithAlphabet { + interface AdminLogin { /** - * RandomStringWithAlphabet generates a cryptographically random string - * with the specified length and characters set. - * - * It panics if for some reason rand.Int returns a non-nil error. + * SetDao replaces the default form Dao instance with the provided one. */ - (length: number, alphabet: string): string + setDao(dao: daos.Dao): void } - interface pseudorandomString { + interface AdminLogin { /** - * PseudorandomString generates a pseudorandom string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - * - * For a cryptographically random string (but a little bit slower) use RandomString instead. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - (length: number): string + validate(): void } - interface pseudorandomStringWithAlphabet { + interface AdminLogin { /** - * PseudorandomStringWithAlphabet generates a pseudorandom string - * with the specified length and characters set. + * Submit validates and submits the admin form. + * On success returns the authorized admin model. * - * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. + * You can optionally provide a list of InterceptorFunc to + * further modify the form behavior before persisting it. */ - (length: number, alphabet: string): string - } -} - -namespace filesystem { - /** - * FileReader defines an interface for a file resource reader. - */ - interface FileReader { - open(): io.ReadSeekCloser + submit(...interceptors: InterceptorFunc[]): (models.Admin | undefined) } /** - * File defines a single file [io.ReadSeekCloser] resource. - * - * The file could be from a local path, multipipart/formdata header, etc. + * AdminPasswordResetConfirm is an admin password reset confirmation form. */ - interface File { - name: string - originalName: string - size: number - reader: FileReader - } - interface newFileFromPath { - /** - * NewFileFromPath creates a new File instance from the provided local file path. - */ - (path: string): (File | undefined) + interface AdminPasswordResetConfirm { + token: string + password: string + passwordConfirm: string } - interface newFileFromBytes { + interface newAdminPasswordResetConfirm { /** - * NewFileFromBytes creates a new File instance from the provided byte slice. + * NewAdminPasswordResetConfirm creates a new [AdminPasswordResetConfirm] + * form initialized with from the provided [core.App] instance. + * + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. */ - (b: string, name: string): (File | undefined) + (app: core.App): (AdminPasswordResetConfirm | undefined) } - interface newFileFromMultipart { + interface AdminPasswordResetConfirm { /** - * NewFileFromMultipart creates a new File instace from the provided multipart header. + * SetDao replaces the form Dao instance with the provided one. + * + * This is useful if you want to use a specific transaction Dao instance + * instead of the default app.Dao(). */ - (mh: multipart.FileHeader): (File | undefined) - } - /** - * MultipartReader defines a FileReader from [multipart.FileHeader]. - */ - interface MultipartReader { - header?: multipart.FileHeader + setDao(dao: daos.Dao): void } - interface MultipartReader { + interface AdminPasswordResetConfirm { /** - * Open implements the [filesystem.FileReader] interface. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - open(): io.ReadSeekCloser - } - /** - * PathReader defines a FileReader from a local file path. - */ - interface PathReader { - path: string + validate(): void } - interface PathReader { + interface AdminPasswordResetConfirm { /** - * Open implements the [filesystem.FileReader] interface. + * Submit validates and submits the admin password reset confirmation form. + * On success returns the updated admin model associated to `form.Token`. + * + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - open(): io.ReadSeekCloser + submit(...interceptors: InterceptorFunc[]): (models.Admin | undefined) } /** - * BytesReader defines a FileReader from bytes content. + * AdminPasswordResetRequest is an admin password reset request form. */ - interface BytesReader { - bytes: string + interface AdminPasswordResetRequest { + email: string } - interface BytesReader { + interface newAdminPasswordResetRequest { /** - * Open implements the [filesystem.FileReader] interface. + * NewAdminPasswordResetRequest creates a new [AdminPasswordResetRequest] + * form initialized with from the provided [core.App] instance. + * + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. */ - open(): io.ReadSeekCloser - } - type _subcRZMp = bytes.Reader - interface bytesReadSeekCloser extends _subcRZMp { + (app: core.App): (AdminPasswordResetRequest | undefined) } - interface bytesReadSeekCloser { + interface AdminPasswordResetRequest { /** - * Close implements the [io.ReadSeekCloser] interface. + * SetDao replaces the default form Dao instance with the provided one. */ - close(): void - } - interface System { + setDao(dao: daos.Dao): void } - interface newS3 { + interface AdminPasswordResetRequest { /** - * NewS3 initializes an S3 filesystem instance. + * Validate makes the form validatable by implementing [validation.Validatable] interface. * - * NB! Make sure to call `Close()` after you are done working with it. + * This method doesn't verify that admin with `form.Email` exists (this is done on Submit). */ - (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System | undefined) + validate(): void } - interface newLocal { + interface AdminPasswordResetRequest { /** - * NewLocal initializes a new local filesystem instance. + * Submit validates and submits the form. + * On success sends a password reset email to the `form.Email` admin. * - * NB! Make sure to call `Close()` after you are done working with it. + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - (dirPath: string): (System | undefined) + submit(...interceptors: InterceptorFunc[]): void } - interface System { - /** - * SetContext assigns the specified context to the current filesystem. - */ - setContext(ctx: context.Context): void + /** + * AdminUpsert is a [models.Admin] upsert (create/update) form. + */ + interface AdminUpsert { + id: string + avatar: number + email: string + password: string + passwordConfirm: string } - interface System { + interface newAdminUpsert { /** - * Close releases any resources used for the related filesystem. + * NewAdminUpsert creates a new [AdminUpsert] form with initializer + * config created from the provided [core.App] and [models.Admin] instances + * (for create you could pass a pointer to an empty Admin - `&models.Admin{}`). + * + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. */ - close(): void + (app: core.App, admin: models.Admin): (AdminUpsert | undefined) } - interface System { + interface AdminUpsert { /** - * Exists checks if file with fileKey path exists or not. + * SetDao replaces the default form Dao instance with the provided one. */ - exists(fileKey: string): boolean + setDao(dao: daos.Dao): void } - interface System { + interface AdminUpsert { /** - * Attributes returns the attributes for the file with fileKey path. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - attributes(fileKey: string): (blob.Attributes | undefined) + validate(): void } - interface System { + interface AdminUpsert { /** - * GetFile returns a file content reader for the given fileKey. + * Submit validates the form and upserts the form admin model. * - * NB! Make sure to call `Close()` after you are done working with it. + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - getFile(fileKey: string): (blob.Reader | undefined) + submit(...interceptors: InterceptorFunc[]): void } - interface System { + /** + * AppleClientSecretCreate is a [models.Admin] upsert (create/update) form. + * + * Reference: https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens + */ + interface AppleClientSecretCreate { /** - * 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, 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. + * ClientId is the identifier of your app (aka. Service ID). */ - uploadMultipart(fh: multipart.FileHeader, fileKey: string): void - } - interface System { + clientId: string /** - * Delete deletes stored file at fileKey location. + * TeamId is a 10-character string associated with your developer account + * (usually could be found next to your name in the Apple Developer site). */ - delete(fileKey: string): void - } - interface System { + teamId: string /** - * DeletePrefix deletes everything starting with the specified prefix. + * KeyId is a 10-character key identifier generated for the "Sign in with Apple" + * private key associated with your developer account. */ - deletePrefix(prefix: string): Array - } - interface System { + keyId: string /** - * 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"). + * PrivateKey is the private key associated to your app. + * Usually wrapped within -----BEGIN PRIVATE KEY----- X -----END PRIVATE KEY-----. */ - serve(res: http.ResponseWriter, req: http.Request, fileKey: string, name: string): void - } - interface System { + privateKey: string /** - * 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) + * Duration specifies how long the generated JWT token should be considered valid. + * The specified value must be in seconds and max 15777000 (~6months). */ - createThumb(originalKey: string, thumbKey: string): void + duration: number } -} - -/** - * Package tokens implements various user and admin tokens generation methods. - */ -namespace tokens { - interface newAdminAuthToken { + interface newAppleClientSecretCreate { /** - * NewAdminAuthToken generates and returns a new admin authentication token. + * NewAppleClientSecretCreate creates a new [AppleClientSecretCreate] form with initializer + * config created from the provided [core.App] instances. */ - (app: core.App, admin: models.Admin): string + (app: core.App): (AppleClientSecretCreate | undefined) } - interface newAdminResetPasswordToken { + interface AppleClientSecretCreate { /** - * NewAdminResetPasswordToken generates and returns a new admin password reset request token. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - (app: core.App, admin: models.Admin): string + validate(): void } - interface newAdminFileToken { + interface AppleClientSecretCreate { /** - * NewAdminFileToken generates and returns a new admin private file access token. + * Submit validates the form and returns a new Apple Client Secret JWT. */ - (app: core.App, admin: models.Admin): string + submit(): string } - interface newRecordAuthToken { - /** - * NewRecordAuthToken generates and returns a new auth record authentication token. - */ - (app: core.App, record: models.Record): string + /** + * BackupCreate is a request form for creating a new app backup. + */ + interface BackupCreate { + name: string } - interface newRecordVerifyToken { + interface newBackupCreate { /** - * NewRecordVerifyToken generates and returns a new record verification token. + * NewBackupCreate creates new BackupCreate request form. */ - (app: core.App, record: models.Record): string + (app: core.App): (BackupCreate | undefined) } - interface newRecordResetPasswordToken { + interface BackupCreate { /** - * NewRecordResetPasswordToken generates and returns a new auth record password reset request token. + * SetContext replaces the default form context with the provided one. */ - (app: core.App, record: models.Record): string + setContext(ctx: context.Context): void } - interface newRecordChangeEmailToken { + interface BackupCreate { /** - * NewRecordChangeEmailToken generates and returns a new auth record change email request token. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - (app: core.App, record: models.Record, newEmail: string): string + validate(): void } - interface newRecordFileToken { + interface BackupCreate { /** - * NewRecordFileToken generates and returns a new record private file access token. + * Submit validates the form and creates the app backup. + * + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before creating the backup. */ - (app: core.App, record: models.Record): string + submit(...interceptors: InterceptorFunc[]): void } -} - -/** - * Package models implements various services used for request data - * validation and applying changes to existing DB models through the app Dao. - */ -namespace forms { - // @ts-ignore - import validation = ozzo_validation /** - * AdminLogin is an admin email/pass login form. + * InterceptorNextFunc is a interceptor handler function. + * Usually used in combination with InterceptorFunc. */ - interface AdminLogin { - identity: string - password: string + interface InterceptorNextFunc {(t: T): void } + /** + * InterceptorFunc defines a single interceptor function that + * will execute the provided next func handler. + */ + interface InterceptorFunc {(next: InterceptorNextFunc): InterceptorNextFunc } + /** + * CollectionUpsert is a [models.Collection] upsert (create/update) form. + */ + interface CollectionUpsert { + id: string + type: string + name: string + system: boolean + schema: schema.Schema + indexes: types.JsonArray + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap } - interface newAdminLogin { + interface newCollectionUpsert { /** - * NewAdminLogin creates a new [AdminLogin] form initialized with - * the provided [core.App] instance. + * NewCollectionUpsert creates a new [CollectionUpsert] form with initializer + * config created from the provided [core.App] and [models.Collection] instances + * (for create you could pass a pointer to an empty Collection - `&models.Collection{}`). * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App): (AdminLogin | undefined) + (app: core.App, collection: models.Collection): (CollectionUpsert | undefined) } - interface AdminLogin { + interface CollectionUpsert { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface AdminLogin { + interface CollectionUpsert { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface AdminLogin { + interface CollectionUpsert { /** - * Submit validates and submits the admin form. - * On success returns the authorized admin model. + * Submit validates the form and upserts the form's Collection model. * - * You can optionally provide a list of InterceptorFunc to - * further modify the form behavior before persisting it. + * On success the related record table schema will be auto updated. + * + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): (models.Admin | undefined) + submit(...interceptors: InterceptorFunc[]): void } /** - * AdminPasswordResetConfirm is an admin password reset confirmation form. + * CollectionsImport is a form model to bulk import + * (create, replace and delete) collections from a user provided list. */ - interface AdminPasswordResetConfirm { - token: string - password: string - passwordConfirm: string + interface CollectionsImport { + collections: Array<(models.Collection | undefined)> + deleteMissing: boolean } - interface newAdminPasswordResetConfirm { + interface newCollectionsImport { /** - * NewAdminPasswordResetConfirm creates a new [AdminPasswordResetConfirm] - * form initialized with from the provided [core.App] instance. + * NewCollectionsImport creates a new [CollectionsImport] form with + * initialized with from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App): (AdminPasswordResetConfirm | undefined) + (app: core.App): (CollectionsImport | undefined) } - interface AdminPasswordResetConfirm { + interface CollectionsImport { /** - * SetDao replaces the form Dao instance with the provided one. - * - * This is useful if you want to use a specific transaction Dao instance - * instead of the default app.Dao(). + * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface AdminPasswordResetConfirm { + interface CollectionsImport { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface AdminPasswordResetConfirm { + interface CollectionsImport { /** - * Submit validates and submits the admin password reset confirmation form. - * On success returns the updated admin model associated to `form.Token`. + * Submit applies the import, aka.: + * - imports the form collections (create or replace) + * - sync the collection changes with their related records table + * - ensures the integrity of the imported structure (aka. run validations for each collection) + * - if [form.DeleteMissing] is set, deletes all local collections that are not found in the imports list + * + * All operations are wrapped in a single transaction that are + * rollbacked on the first encountered error. * * You can optionally provide a list of InterceptorFunc to further * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): (models.Admin | undefined) + submit(...interceptors: InterceptorFunc>[]): void } /** - * AdminPasswordResetRequest is an admin password reset request form. + * RealtimeSubscribe is a realtime subscriptions request form. */ - interface AdminPasswordResetRequest { - email: string - } - interface newAdminPasswordResetRequest { - /** - * NewAdminPasswordResetRequest creates a new [AdminPasswordResetRequest] - * form initialized with from the provided [core.App] instance. - * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. - */ - (app: core.App): (AdminPasswordResetRequest | undefined) + interface RealtimeSubscribe { + clientId: string + subscriptions: Array } - interface AdminPasswordResetRequest { + interface newRealtimeSubscribe { /** - * SetDao replaces the default form Dao instance with the provided one. + * NewRealtimeSubscribe creates new RealtimeSubscribe request form. */ - setDao(dao: daos.Dao): void + (): (RealtimeSubscribe | undefined) } - interface AdminPasswordResetRequest { + interface RealtimeSubscribe { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. - * - * This method doesn't verify that admin with `form.Email` exists (this is done on Submit). */ validate(): void } - interface AdminPasswordResetRequest { - /** - * Submit validates and submits the form. - * On success sends a password reset email to the `form.Email` admin. - * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. - */ - submit(...interceptors: InterceptorFunc[]): void - } /** - * AdminUpsert is a [models.Admin] upsert (create/update) form. + * RecordEmailChangeConfirm is an auth record email change confirmation form. */ - interface AdminUpsert { - id: string - avatar: number - email: string + interface RecordEmailChangeConfirm { + token: string password: string - passwordConfirm: string } - interface newAdminUpsert { + interface newRecordEmailChangeConfirm { /** - * NewAdminUpsert creates a new [AdminUpsert] form with initializer - * config created from the provided [core.App] and [models.Admin] instances - * (for create you could pass a pointer to an empty Admin - `&models.Admin{}`). + * NewRecordEmailChangeConfirm creates a new [RecordEmailChangeConfirm] form + * initialized with from the provided [core.App] and [models.Collection] instances. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, admin: models.Admin): (AdminUpsert | undefined) + (app: core.App, collection: models.Collection): (RecordEmailChangeConfirm | undefined) } - interface AdminUpsert { + interface RecordEmailChangeConfirm { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface AdminUpsert { + interface RecordEmailChangeConfirm { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface AdminUpsert { + interface RecordEmailChangeConfirm { /** - * Submit validates the form and upserts the form admin model. + * Submit validates and submits the auth record email change confirmation form. + * On success returns the updated auth record associated to `form.Token`. * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. + * You can optionally provide a list of InterceptorFunc to + * further modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): void + submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) } /** - * AppleClientSecretCreate is a [models.Admin] upsert (create/update) form. - * - * Reference: https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens + * RecordEmailChangeRequest is an auth record email change request form. */ - interface AppleClientSecretCreate { + interface RecordEmailChangeRequest { + newEmail: string + } + interface newRecordEmailChangeRequest { /** - * ClientId is the identifier of your app (aka. Service ID). + * NewRecordEmailChangeRequest creates a new [RecordEmailChangeRequest] form + * initialized with from the provided [core.App] and [models.Record] instances. + * + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. */ - clientId: string + (app: core.App, record: models.Record): (RecordEmailChangeRequest | undefined) + } + interface RecordEmailChangeRequest { /** - * TeamId is a 10-character string associated with your developer account - * (usually could be found next to your name in the Apple Developer site). + * SetDao replaces the default form Dao instance with the provided one. */ - teamId: string + setDao(dao: daos.Dao): void + } + interface RecordEmailChangeRequest { /** - * KeyId is a 10-character key identifier generated for the "Sign in with Apple" - * private key associated with your developer account. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - keyId: string + validate(): void + } + interface RecordEmailChangeRequest { /** - * PrivateKey is the private key associated to your app. - * Usually wrapped within -----BEGIN PRIVATE KEY----- X -----END PRIVATE KEY-----. + * Submit validates and sends the change email request. + * + * You can optionally provide a list of InterceptorFunc to + * further modify the form behavior before persisting it. */ - privateKey: string + submit(...interceptors: InterceptorFunc[]): void + } + /** + * RecordOAuth2LoginData defines the OA + */ + interface RecordOAuth2LoginData { + externalAuth?: models.ExternalAuth + record?: models.Record + oAuth2User?: auth.AuthUser + providerClient: auth.Provider + } + /** + * BeforeOAuth2RecordCreateFunc defines a callback function that will + * be called before OAuth2 new Record creation. + */ + interface BeforeOAuth2RecordCreateFunc {(createForm: RecordUpsert, authRecord: models.Record, authUser: auth.AuthUser): void } + /** + * RecordOAuth2Login is an auth record OAuth2 login form. + */ + interface RecordOAuth2Login { /** - * Duration specifies how long the generated JWT token should be considered valid. - * The specified value must be in seconds and max 15777000 (~6months). + * The name of the OAuth2 client provider (eg. "google") */ - duration: number - } - interface newAppleClientSecretCreate { + provider: string /** - * NewAppleClientSecretCreate creates a new [AppleClientSecretCreate] form with initializer - * config created from the provided [core.App] instances. + * The authorization code returned from the initial request. */ - (app: core.App): (AppleClientSecretCreate | undefined) - } - interface AppleClientSecretCreate { + code: string /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. + * The code verifier sent with the initial request as part of the code_challenge. */ - validate(): void - } - interface AppleClientSecretCreate { + codeVerifier: string /** - * Submit validates the form and returns a new Apple Client Secret JWT. + * The redirect url sent with the initial request. */ - submit(): string + redirectUrl: string + /** + * Additional data that will be used for creating a new auth record + * if an existing OAuth2 account doesn't exist. + */ + createData: _TygojaDict } - /** - * BackupCreate is a request form for creating a new app backup. - */ - interface BackupCreate { - name: string + interface newRecordOAuth2Login { + /** + * NewRecordOAuth2Login creates a new [RecordOAuth2Login] form with + * initialized with from the provided [core.App] instance. + * + * If you want to submit the form as part of a transaction, + * you can change the default Dao via [SetDao()]. + */ + (app: core.App, collection: models.Collection, optAuthRecord: models.Record): (RecordOAuth2Login | undefined) } - interface newBackupCreate { + interface RecordOAuth2Login { /** - * NewBackupCreate creates new BackupCreate request form. + * SetDao replaces the default form Dao instance with the provided one. */ - (app: core.App): (BackupCreate | undefined) + setDao(dao: daos.Dao): void } - interface BackupCreate { + interface RecordOAuth2Login { /** - * SetContext replaces the default form context with the provided one. + * SetBeforeNewRecordCreateFunc sets a before OAuth2 record create callback handler. */ - setContext(ctx: context.Context): void + setBeforeNewRecordCreateFunc(f: BeforeOAuth2RecordCreateFunc): void } - interface BackupCreate { + interface RecordOAuth2Login { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface BackupCreate { + interface RecordOAuth2Login { /** - * Submit validates the form and creates the app backup. + * Submit validates and submits the form. * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before creating the backup. + * If an auth record doesn't exist, it will make an attempt to create it + * based on the fetched OAuth2 profile data via a local [RecordUpsert] form. + * You can intercept/modify the Record create form with [form.SetBeforeNewRecordCreateFunc()]. + * + * You can also optionally provide a list of InterceptorFunc to + * further modify the form behavior before persisting it. + * + * On success returns the authorized record model and the fetched provider's data. */ - submit(...interceptors: InterceptorFunc[]): void + submit(...interceptors: InterceptorFunc[]): [(models.Record | undefined), (auth.AuthUser | undefined)] } /** - * InterceptorNextFunc is a interceptor handler function. - * Usually used in combination with InterceptorFunc. - */ - interface InterceptorNextFunc {(t: T): void } - /** - * InterceptorFunc defines a single interceptor function that - * will execute the provided next func handler. - */ - interface InterceptorFunc {(next: InterceptorNextFunc): InterceptorNextFunc } - /** - * CollectionUpsert is a [models.Collection] upsert (create/update) form. + * RecordPasswordLogin is record username/email + password login form. */ - interface CollectionUpsert { - id: string - type: string - name: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap + interface RecordPasswordLogin { + identity: string + password: string } - interface newCollectionUpsert { + interface newRecordPasswordLogin { /** - * NewCollectionUpsert creates a new [CollectionUpsert] form with initializer - * config created from the provided [core.App] and [models.Collection] instances - * (for create you could pass a pointer to an empty Collection - `&models.Collection{}`). + * NewRecordPasswordLogin creates a new [RecordPasswordLogin] form initialized + * with from the provided [core.App] and [models.Collection] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, collection: models.Collection): (CollectionUpsert | undefined) + (app: core.App, collection: models.Collection): (RecordPasswordLogin | undefined) } - interface CollectionUpsert { + interface RecordPasswordLogin { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface CollectionUpsert { + interface RecordPasswordLogin { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface CollectionUpsert { + interface RecordPasswordLogin { /** - * Submit validates the form and upserts the form's Collection model. - * - * On success the related record table schema will be auto updated. + * Submit validates and submits the form. + * On success returns the authorized record model. * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. + * You can optionally provide a list of InterceptorFunc to + * further modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): void + submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) } /** - * CollectionsImport is a form model to bulk import - * (create, replace and delete) collections from a user provided list. + * RecordPasswordResetConfirm is an auth record password reset confirmation form. */ - interface CollectionsImport { - collections: Array<(models.Collection | undefined)> - deleteMissing: boolean + interface RecordPasswordResetConfirm { + token: string + password: string + passwordConfirm: string } - interface newCollectionsImport { + interface newRecordPasswordResetConfirm { /** - * NewCollectionsImport creates a new [CollectionsImport] form with - * initialized with from the provided [core.App] instance. + * NewRecordPasswordResetConfirm creates a new [RecordPasswordResetConfirm] + * form initialized with from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App): (CollectionsImport | undefined) + (app: core.App, collection: models.Collection): (RecordPasswordResetConfirm | undefined) } - interface CollectionsImport { + interface RecordPasswordResetConfirm { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface CollectionsImport { + interface RecordPasswordResetConfirm { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface CollectionsImport { + interface RecordPasswordResetConfirm { /** - * Submit applies the import, aka.: - * - imports the form collections (create or replace) - * - sync the collection changes with their related records table - * - ensures the integrity of the imported structure (aka. run validations for each collection) - * - if [form.DeleteMissing] is set, deletes all local collections that are not found in the imports list - * - * All operations are wrapped in a single transaction that are - * rollbacked on the first encountered error. + * Submit validates and submits the form. + * On success returns the updated auth record associated to `form.Token`. * * You can optionally provide a list of InterceptorFunc to further * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc>[]): void - } - /** - * RealtimeSubscribe is a realtime subscriptions request form. - */ - interface RealtimeSubscribe { - clientId: string - subscriptions: Array - } - interface newRealtimeSubscribe { - /** - * NewRealtimeSubscribe creates new RealtimeSubscribe request form. - */ - (): (RealtimeSubscribe | undefined) - } - interface RealtimeSubscribe { - /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. - */ - validate(): void + submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) } /** - * RecordEmailChangeConfirm is an auth record email change confirmation form. + * RecordPasswordResetRequest is an auth record reset password request form. */ - interface RecordEmailChangeConfirm { - token: string - password: string + interface RecordPasswordResetRequest { + email: string } - interface newRecordEmailChangeConfirm { + interface newRecordPasswordResetRequest { /** - * NewRecordEmailChangeConfirm creates a new [RecordEmailChangeConfirm] form - * initialized with from the provided [core.App] and [models.Collection] instances. + * NewRecordPasswordResetRequest creates a new [RecordPasswordResetRequest] + * form initialized with from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, collection: models.Collection): (RecordEmailChangeConfirm | undefined) + (app: core.App, collection: models.Collection): (RecordPasswordResetRequest | undefined) } - interface RecordEmailChangeConfirm { + interface RecordPasswordResetRequest { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface RecordEmailChangeConfirm { + interface RecordPasswordResetRequest { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. + * + * This method doesn't checks whether auth record with `form.Email` exists (this is done on Submit). */ validate(): void } - interface RecordEmailChangeConfirm { + interface RecordPasswordResetRequest { /** - * Submit validates and submits the auth record email change confirmation form. - * On success returns the updated auth record associated to `form.Token`. + * Submit validates and submits the form. + * On success, sends a password reset email to the `form.Email` auth record. * - * You can optionally provide a list of InterceptorFunc to - * further modify the form behavior before persisting it. + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) + submit(...interceptors: InterceptorFunc[]): void } /** - * RecordEmailChangeRequest is an auth record email change request form. + * RecordUpsert is a [models.Record] upsert (create/update) form. */ - interface RecordEmailChangeRequest { - newEmail: string + interface RecordUpsert { + /** + * base model fields + */ + id: string + /** + * auth collection fields + * --- + */ + username: string + email: string + emailVisibility: boolean + verified: boolean + password: string + passwordConfirm: string + oldPassword: string } - interface newRecordEmailChangeRequest { + interface newRecordUpsert { /** - * NewRecordEmailChangeRequest creates a new [RecordEmailChangeRequest] form - * initialized with from the provided [core.App] and [models.Record] instances. + * NewRecordUpsert creates a new [RecordUpsert] form with initializer + * config created from the provided [core.App] and [models.Record] instances + * (for create you could pass a pointer to an empty Record - models.NewRecord(collection)). * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, record: models.Record): (RecordEmailChangeRequest | undefined) + (app: core.App, record: models.Record): (RecordUpsert | undefined) } - interface RecordEmailChangeRequest { + interface RecordUpsert { /** - * SetDao replaces the default form Dao instance with the provided one. + * Data returns the loaded form's data. */ - setDao(dao: daos.Dao): void + data(): _TygojaDict } - interface RecordEmailChangeRequest { + interface RecordUpsert { /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. + * SetFullManageAccess sets the manageAccess bool flag of the current + * form to enable/disable directly changing some system record fields + * (often used with auth collection records). */ - validate(): void + setFullManageAccess(fullManageAccess: boolean): void } - interface RecordEmailChangeRequest { + interface RecordUpsert { /** - * Submit validates and sends the change email request. - * - * You can optionally provide a list of InterceptorFunc to - * further modify the form behavior before persisting it. + * SetDao replaces the default form Dao instance with the provided one. */ - submit(...interceptors: InterceptorFunc[]): void - } - /** - * RecordOAuth2LoginData defines the OA - */ - interface RecordOAuth2LoginData { - externalAuth?: models.ExternalAuth - record?: models.Record - oAuth2User?: auth.AuthUser - providerClient: auth.Provider + setDao(dao: daos.Dao): void } - /** - * BeforeOAuth2RecordCreateFunc defines a callback function that will - * be called before OAuth2 new Record creation. - */ - interface BeforeOAuth2RecordCreateFunc {(createForm: RecordUpsert, authRecord: models.Record, authUser: auth.AuthUser): void } - /** - * RecordOAuth2Login is an auth record OAuth2 login form. - */ - interface RecordOAuth2Login { - /** - * The name of the OAuth2 client provider (eg. "google") - */ - provider: string - /** - * The authorization code returned from the initial request. - */ - code: string + interface RecordUpsert { /** - * The code verifier sent with the initial request as part of the code_challenge. + * LoadRequest extracts the json or multipart/form-data request data + * and lods it into the form. + * + * File upload is supported only via multipart/form-data. */ - codeVerifier: string + loadRequest(r: http.Request, keyPrefix: string): void + } + interface RecordUpsert { /** - * The redirect url sent with the initial request. + * FilesToUpload returns the parsed request files ready for upload. */ - redirectUrl: string + filesToUpload(): _TygojaDict + } + interface RecordUpsert { /** - * Additional data that will be used for creating a new auth record - * if an existing OAuth2 account doesn't exist. + * FilesToUpload returns the parsed request filenames ready to be deleted. */ - createData: _TygojaDict + filesToDelete(): Array } - interface newRecordOAuth2Login { + interface RecordUpsert { /** - * NewRecordOAuth2Login creates a new [RecordOAuth2Login] form with - * initialized with from the provided [core.App] instance. + * AddFiles adds the provided file(s) to the specified file field. * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. + * If the file field is a SINGLE-value file field (aka. "Max Select = 1"), + * then the newly added file will REPLACE the existing one. + * In this case if you pass more than 1 files only the first one will be assigned. + * + * If the file field is a MULTI-value file field (aka. "Max Select > 1"), + * then the newly added file(s) will be APPENDED to the existing one(s). + * + * Example + * + * ``` + * f1, _ := filesystem.NewFileFromPath("/path/to/file1.txt") + * f2, _ := filesystem.NewFileFromPath("/path/to/file2.txt") + * form.AddFiles("documents", f1, f2) + * ``` */ - (app: core.App, collection: models.Collection, optAuthRecord: models.Record): (RecordOAuth2Login | undefined) + addFiles(key: string, ...files: (filesystem.File | undefined)[]): void } - interface RecordOAuth2Login { + interface RecordUpsert { /** - * SetDao replaces the default form Dao instance with the provided one. + * RemoveFiles removes a single or multiple file from the specified file field. + * + * NB! If filesToDelete is not set it will remove all existing files + * assigned to the file field (including those assigned with AddFiles)! + * + * Example + * + * ``` + * // mark only only 2 files for removal + * form.AddFiles("documents", "file1_aw4bdrvws6.txt", "file2_xwbs36bafv.txt") + * + * // mark all "documents" files for removal + * form.AddFiles("documents") + * ``` */ - setDao(dao: daos.Dao): void + removeFiles(key: string, ...toDelete: string[]): void } - interface RecordOAuth2Login { + interface RecordUpsert { /** - * SetBeforeNewRecordCreateFunc sets a before OAuth2 record create callback handler. + * LoadData loads and normalizes the provided regular record data fields into the form. */ - setBeforeNewRecordCreateFunc(f: BeforeOAuth2RecordCreateFunc): void + loadData(requestInfo: _TygojaDict): void } - interface RecordOAuth2Login { + interface RecordUpsert { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface RecordOAuth2Login { + interface RecordUpsert { + validateAndFill(): void + } + interface RecordUpsert { /** - * Submit validates and submits the form. - * - * If an auth record doesn't exist, it will make an attempt to create it - * based on the fetched OAuth2 profile data via a local [RecordUpsert] form. - * You can intercept/modify the Record create form with [form.SetBeforeNewRecordCreateFunc()]. + * DrySubmit performs a form submit within a transaction and reverts it. + * For actual record persistence, check the `form.Submit()` method. * - * You can also optionally provide a list of InterceptorFunc to - * further modify the form behavior before persisting it. + * This method doesn't handle file uploads/deletes or trigger any app events! + */ + drySubmit(callback: (txDao: daos.Dao) => void): void + } + interface RecordUpsert { + /** + * Submit validates the form and upserts the form Record model. * - * On success returns the authorized record model and the fetched provider's data. + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): [(models.Record | undefined), (auth.AuthUser | undefined)] + submit(...interceptors: InterceptorFunc[]): void } /** - * RecordPasswordLogin is record username/email + password login form. + * RecordVerificationConfirm is an auth record email verification confirmation form. */ - interface RecordPasswordLogin { - identity: string - password: string + interface RecordVerificationConfirm { + token: string } - interface newRecordPasswordLogin { + interface newRecordVerificationConfirm { /** - * NewRecordPasswordLogin creates a new [RecordPasswordLogin] form initialized - * with from the provided [core.App] and [models.Collection] instance. + * NewRecordVerificationConfirm creates a new [RecordVerificationConfirm] + * form initialized with from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, collection: models.Collection): (RecordPasswordLogin | undefined) + (app: core.App, collection: models.Collection): (RecordVerificationConfirm | undefined) } - interface RecordPasswordLogin { + interface RecordVerificationConfirm { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface RecordPasswordLogin { + interface RecordVerificationConfirm { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. */ validate(): void } - interface RecordPasswordLogin { + interface RecordVerificationConfirm { /** * Submit validates and submits the form. - * On success returns the authorized record model. + * On success returns the verified auth record associated to `form.Token`. * - * You can optionally provide a list of InterceptorFunc to - * further modify the form behavior before persisting it. + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before persisting it. */ submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) } /** - * RecordPasswordResetConfirm is an auth record password reset confirmation form. + * RecordVerificationRequest is an auth record email verification request form. */ - interface RecordPasswordResetConfirm { - token: string - password: string - passwordConfirm: string + interface RecordVerificationRequest { + email: string } - interface newRecordPasswordResetConfirm { + interface newRecordVerificationRequest { /** - * NewRecordPasswordResetConfirm creates a new [RecordPasswordResetConfirm] + * NewRecordVerificationRequest creates a new [RecordVerificationRequest] * form initialized with from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, collection: models.Collection): (RecordPasswordResetConfirm | undefined) + (app: core.App, collection: models.Collection): (RecordVerificationRequest | undefined) } - interface RecordPasswordResetConfirm { + interface RecordVerificationRequest { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface RecordPasswordResetConfirm { + interface RecordVerificationRequest { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. + * + * // This method doesn't verify that auth record with `form.Email` exists (this is done on Submit). */ validate(): void } - interface RecordPasswordResetConfirm { + interface RecordVerificationRequest { /** - * Submit validates and submits the form. - * On success returns the updated auth record associated to `form.Token`. + * Submit validates and sends a verification request email + * to the `form.Email` auth record. * * You can optionally provide a list of InterceptorFunc to further * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) + submit(...interceptors: InterceptorFunc[]): void } /** - * RecordPasswordResetRequest is an auth record reset password request form. + * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - interface RecordPasswordResetRequest { - email: string + type _subNMRgV = settings.Settings + interface SettingsUpsert extends _subNMRgV { } - interface newRecordPasswordResetRequest { + interface newSettingsUpsert { /** - * NewRecordPasswordResetRequest creates a new [RecordPasswordResetRequest] - * form initialized with from the provided [core.App] instance. + * NewSettingsUpsert creates a new [SettingsUpsert] form with initializer + * config created from the provided [core.App] instance. * * If you want to submit the form as part of a transaction, * you can change the default Dao via [SetDao()]. */ - (app: core.App, collection: models.Collection): (RecordPasswordResetRequest | undefined) + (app: core.App): (SettingsUpsert | undefined) } - interface RecordPasswordResetRequest { + interface SettingsUpsert { /** * SetDao replaces the default form Dao instance with the provided one. */ setDao(dao: daos.Dao): void } - interface RecordPasswordResetRequest { + interface SettingsUpsert { /** * Validate makes the form validatable by implementing [validation.Validatable] interface. - * - * This method doesn't checks whether auth record with `form.Email` exists (this is done on Submit). */ validate(): void } - interface RecordPasswordResetRequest { + interface SettingsUpsert { /** - * Submit validates and submits the form. - * On success, sends a password reset email to the `form.Email` auth record. + * Submit validates the form and upserts the loaded settings. + * + * On success the app settings will be refreshed with the form ones. * * You can optionally provide a list of InterceptorFunc to further * modify the form behavior before persisting it. */ - submit(...interceptors: InterceptorFunc[]): void + submit(...interceptors: InterceptorFunc[]): void } /** - * RecordUpsert is a [models.Record] upsert (create/update) form. + * TestEmailSend is a email template test request form. */ - interface RecordUpsert { - /** - * base model fields - */ - id: string - /** - * auth collection fields - * --- - */ - username: string + interface TestEmailSend { + template: string email: string - emailVisibility: boolean - verified: boolean - password: string - passwordConfirm: string - oldPassword: string } - interface newRecordUpsert { + interface newTestEmailSend { /** - * NewRecordUpsert creates a new [RecordUpsert] form with initializer - * config created from the provided [core.App] and [models.Record] instances - * (for create you could pass a pointer to an empty Record - models.NewRecord(collection)). - * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. + * NewTestEmailSend creates and initializes new TestEmailSend form. */ - (app: core.App, record: models.Record): (RecordUpsert | undefined) + (app: core.App): (TestEmailSend | undefined) } - interface RecordUpsert { + interface TestEmailSend { /** - * Data returns the loaded form's data. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - data(): _TygojaDict + validate(): void } - interface RecordUpsert { + interface TestEmailSend { /** - * SetFullManageAccess sets the manageAccess bool flag of the current - * form to enable/disable directly changing some system record fields - * (often used with auth collection records). + * Submit validates and sends a test email to the form.Email address. */ - setFullManageAccess(fullManageAccess: boolean): void + submit(): void } - interface RecordUpsert { + /** + * TestS3Filesystem defines a S3 filesystem connection test. + */ + interface TestS3Filesystem { /** - * SetDao replaces the default form Dao instance with the provided one. + * The name of the filesystem - storage or backups */ - setDao(dao: daos.Dao): void + filesystem: string } - interface RecordUpsert { + interface newTestS3Filesystem { /** - * LoadRequest extracts the json or multipart/form-data request data - * and lods it into the form. - * - * File upload is supported only via multipart/form-data. + * NewTestS3Filesystem creates and initializes new TestS3Filesystem form. */ - loadRequest(r: http.Request, keyPrefix: string): void + (app: core.App): (TestS3Filesystem | undefined) } - interface RecordUpsert { + interface TestS3Filesystem { /** - * FilesToUpload returns the parsed request files ready for upload. + * Validate makes the form validatable by implementing [validation.Validatable] interface. */ - filesToUpload(): _TygojaDict + validate(): void } - interface RecordUpsert { + interface TestS3Filesystem { /** - * FilesToUpload returns the parsed request filenames ready to be deleted. + * Submit validates and performs a S3 filesystem connection test. */ - filesToDelete(): Array + submit(): void } - interface RecordUpsert { - /** - * AddFiles adds the provided file(s) to the specified file field. - * - * If the file field is a SINGLE-value file field (aka. "Max Select = 1"), - * then the newly added file will REPLACE the existing one. - * In this case if you pass more than 1 files only the first one will be assigned. - * - * If the file field is a MULTI-value file field (aka. "Max Select > 1"), - * then the newly added file(s) will be APPENDED to the existing one(s). - * - * Example - * - * ``` - * f1, _ := filesystem.NewFileFromPath("/path/to/file1.txt") - * f2, _ := filesystem.NewFileFromPath("/path/to/file2.txt") - * form.AddFiles("documents", f1, f2) - * ``` - */ - addFiles(key: string, ...files: (filesystem.File | undefined)[]): void +} + +/** + * Package apis implements the default PocketBase api services and middlewares. + */ +namespace apis { + interface adminApi { } - interface RecordUpsert { + // @ts-ignore + import validation = ozzo_validation + /** + * ApiError defines the struct for a basic api error response. + */ + interface ApiError { + code: number + message: string + data: _TygojaDict + } + interface ApiError { /** - * RemoveFiles removes a single or multiple file from the specified file field. - * - * NB! If filesToDelete is not set it will remove all existing files - * assigned to the file field (including those assigned with AddFiles)! - * - * Example - * - * ``` - * // mark only only 2 files for removal - * form.AddFiles("documents", "file1_aw4bdrvws6.txt", "file2_xwbs36bafv.txt") - * - * // mark all "documents" files for removal - * form.AddFiles("documents") - * ``` + * Error makes it compatible with the `error` interface. */ - removeFiles(key: string, ...toDelete: string[]): void + error(): string } - interface RecordUpsert { + interface ApiError { /** - * LoadData loads and normalizes the provided regular record data fields into the form. + * RawData returns the unformatted error data (could be an internal error, text, etc.) */ - loadData(requestInfo: _TygojaDict): void + rawData(): any } - interface RecordUpsert { + interface newNotFoundError { /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. + * NewNotFoundError creates and returns 404 `ApiError`. */ - validate(): void - } - interface RecordUpsert { - validateAndFill(): void + (message: string, data: any): (ApiError | undefined) } - interface RecordUpsert { + interface newBadRequestError { /** - * DrySubmit performs a form submit within a transaction and reverts it. - * For actual record persistence, check the `form.Submit()` method. - * - * This method doesn't handle file uploads/deletes or trigger any app events! + * NewBadRequestError creates and returns 400 `ApiError`. */ - drySubmit(callback: (txDao: daos.Dao) => void): void + (message: string, data: any): (ApiError | undefined) } - interface RecordUpsert { + interface newForbiddenError { /** - * Submit validates the form and upserts the form Record model. - * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. + * NewForbiddenError creates and returns 403 `ApiError`. */ - submit(...interceptors: InterceptorFunc[]): void - } - /** - * RecordVerificationConfirm is an auth record email verification confirmation form. - */ - interface RecordVerificationConfirm { - token: string + (message: string, data: any): (ApiError | undefined) } - interface newRecordVerificationConfirm { + interface newUnauthorizedError { /** - * NewRecordVerificationConfirm creates a new [RecordVerificationConfirm] - * form initialized with from the provided [core.App] instance. - * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. + * NewUnauthorizedError creates and returns 401 `ApiError`. */ - (app: core.App, collection: models.Collection): (RecordVerificationConfirm | undefined) + (message: string, data: any): (ApiError | undefined) } - interface RecordVerificationConfirm { + interface newApiError { /** - * SetDao replaces the default form Dao instance with the provided one. + * NewApiError creates and returns new normalized `ApiError` instance. */ - setDao(dao: daos.Dao): void + (status: number, message: string, data: any): (ApiError | undefined) } - interface RecordVerificationConfirm { + interface backupApi { + } + interface initApi { /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. + * InitApi creates a configured echo instance with registered + * system and app specific routes and middlewares. */ - validate(): void - } - interface RecordVerificationConfirm { - /** - * Submit validates and submits the form. - * On success returns the verified auth record associated to `form.Token`. - * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. - */ - submit(...interceptors: InterceptorFunc[]): (models.Record | undefined) - } - /** - * RecordVerificationRequest is an auth record email verification request form. - */ - interface RecordVerificationRequest { - email: string - } - interface newRecordVerificationRequest { - /** - * NewRecordVerificationRequest creates a new [RecordVerificationRequest] - * form initialized with from the provided [core.App] instance. - * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. - */ - (app: core.App, collection: models.Collection): (RecordVerificationRequest | undefined) - } - interface RecordVerificationRequest { - /** - * SetDao replaces the default form Dao instance with the provided one. - */ - setDao(dao: daos.Dao): void - } - interface RecordVerificationRequest { - /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. - * - * // This method doesn't verify that auth record with `form.Email` exists (this is done on Submit). - */ - validate(): void - } - interface RecordVerificationRequest { - /** - * Submit validates and sends a verification request email - * to the `form.Email` auth record. - * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. - */ - submit(...interceptors: InterceptorFunc[]): void - } - /** - * SettingsUpsert is a [settings.Settings] upsert (create/update) form. - */ - type _subUBtfT = settings.Settings - interface SettingsUpsert extends _subUBtfT { - } - interface newSettingsUpsert { - /** - * NewSettingsUpsert creates a new [SettingsUpsert] form with initializer - * config created from the provided [core.App] instance. - * - * If you want to submit the form as part of a transaction, - * you can change the default Dao via [SetDao()]. - */ - (app: core.App): (SettingsUpsert | undefined) - } - interface SettingsUpsert { - /** - * SetDao replaces the default form Dao instance with the provided one. - */ - setDao(dao: daos.Dao): void - } - interface SettingsUpsert { - /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface SettingsUpsert { - /** - * Submit validates the form and upserts the loaded settings. - * - * On success the app settings will be refreshed with the form ones. - * - * You can optionally provide a list of InterceptorFunc to further - * modify the form behavior before persisting it. - */ - submit(...interceptors: InterceptorFunc[]): void - } - /** - * TestEmailSend is a email template test request form. - */ - interface TestEmailSend { - template: string - email: string - } - interface newTestEmailSend { - /** - * NewTestEmailSend creates and initializes new TestEmailSend form. - */ - (app: core.App): (TestEmailSend | undefined) - } - interface TestEmailSend { - /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface TestEmailSend { - /** - * Submit validates and sends a test email to the form.Email address. - */ - submit(): void - } - /** - * TestS3Filesystem defines a S3 filesystem connection test. - */ - interface TestS3Filesystem { - /** - * The name of the filesystem - storage or backups - */ - filesystem: string - } - interface newTestS3Filesystem { - /** - * NewTestS3Filesystem creates and initializes new TestS3Filesystem form. - */ - (app: core.App): (TestS3Filesystem | undefined) - } - interface TestS3Filesystem { - /** - * Validate makes the form validatable by implementing [validation.Validatable] interface. - */ - validate(): void - } - interface TestS3Filesystem { - /** - * Submit validates and performs a S3 filesystem connection test. - */ - submit(): void - } -} - -/** - * Package apis implements the default PocketBase api services and middlewares. - */ -namespace apis { - interface adminApi { - } - // @ts-ignore - import validation = ozzo_validation - /** - * ApiError defines the struct for a basic api error response. - */ - interface ApiError { - code: number - message: string - data: _TygojaDict - } - interface ApiError { - /** - * Error makes it compatible with the `error` interface. - */ - error(): string - } - interface ApiError { - /** - * RawData returns the unformatted error data (could be an internal error, text, etc.) - */ - rawData(): any - } - interface newNotFoundError { - /** - * NewNotFoundError creates and returns 404 `ApiError`. - */ - (message: string, data: any): (ApiError | undefined) - } - interface newBadRequestError { - /** - * NewBadRequestError creates and returns 400 `ApiError`. - */ - (message: string, data: any): (ApiError | undefined) - } - interface newForbiddenError { - /** - * NewForbiddenError creates and returns 403 `ApiError`. - */ - (message: string, data: any): (ApiError | undefined) - } - interface newUnauthorizedError { - /** - * NewUnauthorizedError creates and returns 401 `ApiError`. - */ - (message: string, data: any): (ApiError | undefined) - } - interface newApiError { - /** - * NewApiError creates and returns new normalized `ApiError` instance. - */ - (status: number, message: string, data: any): (ApiError | undefined) - } - interface backupApi { - } - interface initApi { - /** - * InitApi creates a configured echo instance with registered - * system and app specific routes and middlewares. - */ - (app: core.App): (echo.Echo | undefined) + (app: core.App): (echo.Echo | undefined) } interface staticDirectoryHandler { /** @@ -4522,8 +4522,8 @@ namespace pocketbase { /** * appWrapper serves as a private core.App instance wrapper. */ - type _subhhaEi = core.App - interface appWrapper extends _subhhaEi { + type _subyGiyC = core.App + interface appWrapper extends _subyGiyC { } /** * PocketBase defines a PocketBase app launcher. @@ -4531,8 +4531,8 @@ namespace pocketbase { * It implements [core.App] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _suboKUrN = appWrapper - interface PocketBase extends _suboKUrN { + type _subAhjFj = appWrapper + interface PocketBase extends _subAhjFj { /** * RootCmd is the main console command */ @@ -4605,112 +4605,7 @@ namespace pocketbase { } /** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * ReadSeekCloser is the interface that groups the basic Read, Seek and Close - * methods. - */ - interface ReadSeekCloser { - } -} - -/** - * Package bytes implements functions for the manipulation of byte slices. - * It is analogous to the facilities of the strings package. - */ -namespace bytes { - /** - * A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, - * io.ByteScanner, and io.RuneScanner interfaces by reading from - * a byte slice. - * Unlike a Buffer, a Reader is read-only and supports seeking. - * The zero value for Reader operates like a Reader of an empty slice. - */ - interface Reader { - } - interface Reader { - /** - * Len returns the number of bytes of the unread portion of the - * slice. - */ - len(): number - } - interface Reader { - /** - * Size returns the original length of the underlying byte slice. - * Size is the number of bytes available for reading via ReadAt. - * The returned value is always the same and is not affected by calls - * to any other method. - */ - size(): number - } - interface Reader { - /** - * Read implements the io.Reader interface. - */ - read(b: string): number - } - interface Reader { - /** - * ReadAt implements the io.ReaderAt interface. - */ - readAt(b: string, off: number): number - } - interface Reader { - /** - * ReadByte implements the io.ByteReader interface. - */ - readByte(): string - } - interface Reader { - /** - * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the io.RuneReader interface. - */ - readRune(): [string, number] - } - interface Reader { - /** - * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. - */ - unreadRune(): void - } - interface Reader { - /** - * Seek implements the io.Seeker interface. - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * WriteTo implements the io.WriterTo interface. - */ - writeTo(w: io.Writer): number - } - interface Reader { - /** - * Reset resets the Reader to be reading from b. - */ - reset(b: string): void - } -} - -/** - * Package time provides functionality for measuring and displaying time. + * Package time provides functionality for measuring and displaying time. * * The calendrical calculations always assume a Gregorian calendar, with * no leap seconds. @@ -4855,35 +4750,6 @@ namespace time { } } -/** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. - */ -namespace fs { - /** - * An FS provides access to a hierarchical file system. - * - * The FS interface is the minimum implementation required of the file system. - * A file system may implement additional interfaces, - * such as ReadFileFS, to provide additional or optimized functionality. - */ - interface FS { - /** - * Open opens the named file. - * - * When Open returns an error, it should be of type *PathError - * with the Op field set to "open", the Path field set to name, - * and the Err field describing the problem. - * - * Open should reject attempts to open names that do not satisfy - * ValidPath(name), returning a *PathError with Err set to - * ErrInvalid or ErrNotExist. - */ - open(name: string): File - } -} - /** * Package context defines the Context type, which carries deadlines, * cancellation signals, and other request-scoped values across API boundaries @@ -5041,3019 +4907,2934 @@ namespace context { } /** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. * - * See README.md for more info. + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. */ -namespace jwt { +namespace io { /** - * 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 + * ReadSeekCloser is the interface that groups the basic Read, Seek and Close + * methods. */ - 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 ReadSeekCloser { } - interface MapClaims { +} + +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + */ +namespace fs { + /** + * An FS provides access to a hierarchical file system. + * + * The FS interface is the minimum implementation required of the file system. + * A file system may implement additional interfaces, + * such as ReadFileFS, to provide additional or optimized functionality. + */ + interface FS { /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. + * Open opens the named file. + * + * When Open returns an error, it should be of type *PathError + * with the Op field set to "open", the Path field set to name, + * and the Err field describing the problem. + * + * Open should reject attempts to open names that do not satisfy + * ValidPath(name), returning a *PathError with Err set to + * ErrInvalid or ErrNotExist. */ - verifyExpiresAt(cmp: number, req: boolean): boolean + open(name: string): File } - interface MapClaims { +} + +/** + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. + * + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. + * + * Drivers that do not support context cancellation will not return until + * after the query is completed. + * + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. + */ +namespace sql { + /** + * TxOptions holds the transaction options to be used in DB.BeginTx. + */ + interface TxOptions { /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. */ - verifyIssuedAt(cmp: number, req: boolean): boolean + isolation: IsolationLevel + readOnly: boolean } - interface MapClaims { + /** + * DB is a database handle representing a pool of zero or more + * underlying connections. It's safe for concurrent use by multiple + * goroutines. + * + * The sql package creates and frees connections automatically; it + * also maintains a free pool of idle connections. If the database has + * a concept of per-connection state, such state can be reliably observed + * within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the + * returned Tx is bound to a single connection. Once Commit or + * Rollback is called on the transaction, that transaction's + * connection is returned to DB's idle connection pool. The pool size + * can be controlled with SetMaxIdleConns. + */ + interface DB { + } + interface DB { /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. */ - verifyNotBefore(cmp: number, req: boolean): boolean + pingContext(ctx: context.Context): void } - interface MapClaims { + interface DB { /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. + * + * Ping uses context.Background internally; to specify the context, use + * PingContext. */ - verifyIssuer(cmp: string, req: boolean): boolean + ping(): void } - interface MapClaims { + interface DB { /** - * 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. + * Close closes the database and prevents new queries from starting. + * Close then waits for all queries that have started processing on the server + * to finish. + * + * It is rare to Close a DB, as the DB handle is meant to be + * long-lived and shared between many goroutines. */ - 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. - */ -namespace multipart { - /** - * A FileHeader describes a file part of a multipart request. - */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number + close(): void } - interface FileHeader { + interface DB { /** - * Open opens and returns the FileHeader's associated File. + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. + * + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * + * If n <= 0, no idle connections are retained. + * + * The default max idle connections is currently 2. This may change in + * a future release. */ - open(): File + setMaxIdleConns(n: number): void } -} - -/** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The client must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG environment variables are - * currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * The GODEBUG variables are not covered by Go's API compatibility - * promise. Please report any issues before disabling HTTP/2 - * support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { - // @ts-ignore - import mathrand = rand - // @ts-ignore - import urlpkg = url - /** - * A Request represents an HTTP request received by a server - * or to be sent by a client. - * - * The field semantics differ slightly between client and server - * usage. In addition to the notes on the fields below, see the - * documentation for Request.Write and RoundTripper. - */ - interface Request { + interface DB { /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. + * SetMaxOpenConns sets the maximum number of open connections to the database. * - * Go's HTTP client does not support sending a request with - * the CONNECT method. See the documentation on Transport for - * details. + * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than + * MaxIdleConns, then MaxIdleConns will be reduced to match the new + * MaxOpenConns limit. + * + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). */ - method: string + setMaxOpenConns(n: number): void + } + interface DB { /** - * URL specifies either the URI being requested (for server - * requests) or the URL to access (for client requests). + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. * - * 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) + * Expired connections may be closed lazily before reuse. * - * 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. + * If d <= 0, connections are not closed due to a connection's age. */ - url?: url.URL + setConnMaxLifetime(d: time.Duration): void + } + interface DB { /** - * The protocol version for incoming server requests. + * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. * - * 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. + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's idle time. */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 + setConnMaxIdleTime(d: time.Duration): void + } + interface DB { /** - * Header contains the request header fields either received - * by the server or to be sent by the client. - * - * If a server received a request with header lines, - * - * ``` - * Host: example.com - * accept-encoding: gzip, deflate - * Accept-Language: en-us - * fOO: Bar - * foo: two - * ``` - * - * then - * - * ``` - * Header = map[string][]string{ - * "Accept-Encoding": {"gzip, deflate"}, - * "Accept-Language": {"en-us"}, - * "Foo": {"Bar", "two"}, - * } - * ``` - * - * For incoming requests, the Host header is promoted to the - * Request.Host field and removed from the Header map. - * - * HTTP defines that header names are case-insensitive. The - * request parser implements this by using CanonicalHeaderKey, - * making the first character and any characters following a - * hyphen uppercase and the rest lowercase. - * - * 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. + * Stats returns database statistics. */ - header: Header + stats(): DBStats + } + interface DB { /** - * Body is the request's body. - * - * For client requests, a nil body means the request has no - * body, such as a GET request. The HTTP Client's Transport - * is responsible for calling the Close method. - * - * For server requests, the Request Body is always non-nil - * but will return EOF immediately when no body is present. - * The Server will close the request body. The ServeHTTP - * Handler does not need to. + * 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. * - * Body must allow Read to be called concurrently with Close. - * In particular, calling Close should unblock a Read waiting - * for input. + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. */ - body: io.ReadCloser + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + } + interface DB { /** - * GetBody defines an optional func to return a new copy of - * Body. It is used for client requests when a redirect requires - * reading the body more than once. Use of GetBody still - * requires setting Body. + * Prepare creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's Close method + * when the statement is no longer needed. * - * For server requests, it is unused. + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - getBody: () => io.ReadCloser + prepare(query: string): (Stmt | undefined) + } + interface DB { /** - * ContentLength records the length of the associated content. - * The value -1 indicates that the length is unknown. - * Values >= 0 indicate that the given number of bytes may - * be read from Body. - * - * For client requests, a value of 0 with a non-nil Body is - * also treated as unknown. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - contentLength: number + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface DB { /** - * TransferEncoding lists the transfer encodings from outermost to - * innermost. An empty list denotes the "identity" encoding. - * TransferEncoding can usually be ignored; chunked encoding is - * automatically added and removed as necessary when sending and - * receiving requests. + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + * + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - transferEncoding: Array + exec(query: string, ...args: any[]): Result + } + interface DB { /** - * Close indicates whether to close the connection after - * replying to this request (for servers) or after sending this - * request and reading its response (for clients). - * - * 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. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - close: boolean + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + } + interface DB { /** - * For server requests, Host specifies the host on which the - * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this - * is either the value of the "Host" header or the host name - * given in the URL itself. For HTTP/2, it is the value of the - * ":authority" pseudo-header field. - * It may be of the form "host:port". For international domain - * names, Host may be in Punycode or Unicode form. Use - * golang.org/x/net/idna to convert it to either format if - * needed. - * To prevent DNS rebinding attacks, server Handlers should - * validate that the Host header has a value for which the - * Handler considers itself authoritative. The included - * ServeMux supports patterns registered to particular host - * names and thus protects its registered Handlers. + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. * - * 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. + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - host: string + query(query: string, ...args: any[]): (Rows | undefined) + } + interface DB { /** - * Form contains the parsed form data, including both the URL - * field's query parameters and the PATCH, POST, or PUT form data. - * This field is only available after ParseForm is called. - * The HTTP client ignores Form and uses Body instead. + * 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. */ - form: url.Values + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + } + interface DB { /** - * PostForm contains the parsed form data from PATCH, POST - * or PUT body parameters. + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. * - * 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. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - multipartForm?: multipart.Form + queryRow(query: string, ...args: any[]): (Row | undefined) + } + interface DB { /** - * Trailer specifies additional headers that are sent after the request - * body. - * - * For server requests, the Trailer map initially contains only the - * trailer keys, with nil values. (The client declares which trailers it - * will later send.) While the handler is reading from Body, it must - * not reference Trailer. After reading from Body returns EOF, Trailer - * can be read again and will contain non-nil values, if they were sent - * by the client. + * BeginTx starts a transaction. * - * For client requests, Trailer must be initialized to a map containing - * the trailer keys to later send. The values may be nil or their final - * values. The ContentLength must be 0 or -1, to send a chunked request. - * After the HTTP request is sent the map values can be updated while - * the request body is read. Once the body returns EOF, the caller must - * not mutate Trailer. + * The 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. * - * Few HTTP clients, servers, or proxies support HTTP trailers. + * 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. */ - trailer: Header + beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) + } + interface DB { /** - * 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. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. + * + * Begin uses context.Background internally; to specify the context, use + * BeginTx. */ - remoteAddr: string + begin(): (Tx | undefined) + } + interface DB { /** - * 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. + * Driver returns the database's underlying driver. */ - requestURI: string + driver(): driver.Driver + } + interface DB { /** - * 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. + * Conn returns a single connection by either opening a new connection + * or returning an existing connection from the connection pool. Conn will + * block until either a connection is returned or ctx is canceled. + * Queries run on the same Conn will be run in the same database session. + * + * Every Conn must be returned to the database pool after use by + * calling Conn.Close. */ - tls?: tls.ConnectionState + conn(ctx: context.Context): (Conn | undefined) + } + /** + * Tx is an in-progress database transaction. + * + * A transaction must end with a call to Commit or Rollback. + * + * After a call to Commit or Rollback, all operations on the + * transaction fail with ErrTxDone. + * + * The statements prepared for a transaction by calling + * the transaction's Prepare or Stmt methods are closed + * by the call to Commit or Rollback. + */ + interface Tx { + } + interface Tx { /** - * 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. + * Commit commits the transaction. */ - cancel: undefined + commit(): void + } + interface Tx { /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. + * Rollback aborts the transaction. */ - response?: Response + rollback(): void } - interface Request { + interface Tx { /** - * Context returns the request's context. To change the context, use - * WithContext. + * PrepareContext creates a prepared statement for use within a transaction. * - * The returned context is always non-nil; it defaults to the - * background context. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * For outgoing client requests, the context controls cancellation. + * To use an existing prepared statement on this transaction, see Tx.Stmt. * - * For incoming server requests, the context is canceled when the - * client's connection closes, the request is canceled (with HTTP/2), - * or when the ServeHTTP method returns. + * The provided context will be used for the preparation of the context, not + * for the execution of the returned statement. The returned statement + * will run in the transaction context. */ - context(): context.Context + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) } - interface Request { + interface Tx { /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. + * Prepare creates a prepared statement for use within a transaction. * - * 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. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * To create a new request with a context, use NewRequestWithContext. - * To change the context of a request, such as an incoming request you - * want to modify before sending back out, use Request.Clone. Between - * those two uses, it's rare to need WithContext. + * To use an existing prepared statement on this transaction, see Tx.Stmt. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - withContext(ctx: context.Context): (Request | undefined) + prepare(query: string): (Stmt | undefined) } - interface Request { + interface Tx { /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. * - * 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. + * Example: + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. */ - clone(ctx: context.Context): (Request | undefined) + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) } - interface Request { + interface Tx { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * Stmt returns a transaction-specific prepared statement from + * an existing statement. + * + * Example: + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * Stmt uses context.Background internally; to specify the context, use + * StmtContext. */ - protoAtLeast(major: number): boolean + stmt(stmt: Stmt): (Stmt | undefined) } - interface Request { + interface Tx { /** - * UserAgent returns the client's User-Agent, if sent in the request. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - userAgent(): string + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Request { + interface Tx { /** - * Cookies parses and returns the HTTP cookies sent with the request. + * Exec executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. + * + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - cookies(): Array<(Cookie | undefined)> + exec(query: string, ...args: any[]): Result } - interface Request { + interface Tx { /** - * 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. + * QueryContext executes a query that returns rows, typically a SELECT. */ - cookie(name: string): (Cookie | undefined) + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) } - interface Request { + interface Tx { /** - * 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. + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - addCookie(c: Cookie): void + query(query: string, ...args: any[]): (Rows | undefined) } - interface Request { + interface Tx { /** - * Referer returns the referring URL, if sent in the request. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + } + interface Tx { + /** + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * Row's Scan method is called. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. * - * 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"]. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - referer(): string + queryRow(query: string, ...args: any[]): (Row | undefined) } - interface Request { + /** + * Stmt is a prepared statement. + * A Stmt is safe for concurrent use by multiple goroutines. + * + * If a Stmt is prepared on a Tx or Conn, it will be bound to a single + * underlying connection forever. If the Tx or Conn closes, the Stmt will + * become unusable and all operations will return an error. + * If a Stmt is prepared on a DB, it will remain usable for the lifetime of the + * DB. When the Stmt needs to execute on a new underlying connection, it will + * prepare itself on the new connection automatically. + */ + interface Stmt { + } + interface Stmt { /** - * 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. + * ExecContext executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. */ - multipartReader(): (multipart.Reader | undefined) + execContext(ctx: context.Context, ...args: any[]): Result } - interface Request { + interface Stmt { /** - * Write writes an HTTP/1.1 request, which is the header and body, in wire format. - * This method consults the following fields of the request: - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` + * Exec executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. * - * 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. + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - write(w: io.Writer): void + exec(...args: any[]): Result } - interface Request { + interface Stmt { /** - * WriteProxy is like Write but writes the request in the form - * expected by an HTTP proxy. In particular, WriteProxy writes the - * initial Request-URI line of the request with an absolute URI, per - * section 5.3 of RFC 7230, including the scheme and host. - * In either case, WriteProxy also writes a Host header, using - * either r.Host or r.URL.Host. + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. */ - writeProxy(w: io.Writer): void + queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) } - interface Request { + interface Stmt { /** - * 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. + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - basicAuth(): [string, boolean] + query(...args: any[]): (Rows | undefined) } - interface Request { + interface Stmt { /** - * SetBasicAuth sets the request's Authorization header to use HTTP - * Basic Authentication with the provided username and password. - * - * With HTTP Basic Authentication the provided username and password - * are not encrypted. - * - * Some protocols may impose additional requirements on pre-escaping the - * username and password. For instance, when used with OAuth2, both arguments - * must be URL encoded first with url.QueryEscape. + * QueryRowContext executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned *Row, which is always non-nil. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. */ - setBasicAuth(username: string): void + queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) } - interface Request { + interface Stmt { /** - * 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. + * QueryRow executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned *Row, which is always non-nil. + * If the query selects no rows, the *Row's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. * - * If the request Body's size has not already been limited by MaxBytesReader, - * the size is capped at 10MB. + * Example usage: * - * 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. + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) * - * ParseMultipartForm calls ParseForm automatically. - * ParseForm is idempotent. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - parseForm(): void + queryRow(...args: any[]): (Row | undefined) } - interface Request { + interface Stmt { /** - * 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. + * Close closes the statement. */ - parseMultipartForm(maxMemory: number): void + close(): 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 + /** + * Rows is the result of a query. Its cursor starts before the first row + * of the result set. Use Next to advance from row to row. + */ + interface Rows { } - interface Request { + interface Rows { /** - * PostFormValue returns the first value for the named component of the POST, - * PATCH, or PUT request body. URL query parameters are ignored. - * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, PostFormValue returns the empty string. + * Next prepares the next result row for reading with the Scan method. It + * returns true on success, or false if there is no next result row or an error + * happened while preparing it. Err should be consulted to distinguish between + * the two cases. + * + * Every call to Scan, even the first one, must be preceded by a call to Next. */ - postFormValue(key: string): string + next(): boolean } - interface Request { + interface Rows { /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. + * NextResultSet prepares the next result set for reading. It reports whether + * there is further result sets, or false if there is no further result set + * or if there is an error advancing to it. The Err method should be consulted + * to distinguish between the two cases. + * + * After calling NextResultSet, the Next method should always be called before + * scanning. If there are further result sets they may not have rows in the result + * set. */ - formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] + nextResultSet(): boolean } - /** - * 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 Rows { /** - * Header returns the header map that will be sent by - * WriteHeader. The Header map also is the mechanism with which - * Handlers can set HTTP trailers. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit Close. + */ + err(): void + } + interface Rows { + /** + * Columns returns the column names. + * Columns returns an error if the rows are closed. + */ + columns(): Array + } + interface Rows { + /** + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. + */ + columnTypes(): Array<(ColumnType | undefined)> + } + interface Rows { + /** + * Scan copies the columns in the current row into the values pointed + * at by dest. The number of values in dest must be the same as the + * number of columns in Rows. * - * Changing the header map after a call to WriteHeader (or - * Write) has no effect unless the modified headers are - * trailers. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * There are two ways to set Trailers. The preferred way is to - * predeclare in the headers which trailers you will later - * send by setting the "Trailer" header to the names of the - * trailer keys which will come later. In this case, those - * keys of the Header map are treated as if they were - * trailers. See the example. The second way, for trailer - * keys not known to the Handler until after the first Write, - * is to prefix the Header map keys with the TrailerPrefix - * constant value. See TrailerPrefix. + * ``` + * *string + * *[]byte + * *int, *int8, *int16, *int32, *int64 + * *uint, *uint8, *uint16, *uint32, *uint64 + * *bool + * *float32, *float64 + * *interface{} + * *RawBytes + * *Rows (cursor value) + * any type implementing Scanner (see Scanner docs) + * ``` * - * To suppress automatic response headers (such as "Date"), set - * their value to nil. - */ - header(): Header - /** - * Write writes the data to the connection as part of an HTTP reply. + * In the most simple case, if the type of the value from the source + * column is an integer, bool or string type T and dest is of type *T, + * Scan simply assigns the value through the pointer. * - * If WriteHeader has not yet been called, Write calls - * WriteHeader(http.StatusOK) before writing the data. If the Header - * does not contain a Content-Type line, Write adds a Content-Type set - * to the result of passing the initial 512 bytes of written data to - * DetectContentType. Additionally, if the total size of all written - * data is under a few KB and there are no Flush calls, the - * Content-Length header is added automatically. + * Scan also converts between string and numeric types, as long as no + * information would be lost. While Scan stringifies all numbers + * scanned from numeric database columns into *string, scans into + * numeric types are checked for overflow. For example, a float64 with + * value 300 or a string with value "300" can scan into a uint16, but + * not into a uint8, though float64(255) or "255" can scan into a + * uint8. One exception is that scans of some float64 numbers to + * strings may lose information when stringifying. In general, scan + * floating point columns into *float64. * - * Depending on the HTTP protocol version and the client, calling - * Write or WriteHeader may prevent future reads on the - * Request.Body. For HTTP/1.x requests, handlers should read any - * needed request body data before writing the response. Once the - * headers have been flushed (due to either an explicit Flusher.Flush - * call or writing enough data to trigger a flush), the request body - * may be unavailable. For HTTP/2 requests, the Go HTTP server permits - * handlers to continue to read the request body while concurrently - * writing the response. However, such behavior may not be supported - * by all HTTP/2 clients. Handlers should read before writing if - * possible to maximize compatibility. - */ - write(_arg0: string): number - /** - * WriteHeader sends an HTTP response header with the provided - * status code. + * If a dest argument has type *[]byte, Scan saves in that argument a + * copy of the corresponding data. The copy is owned by the caller and + * can be modified and held indefinitely. The copy can be avoided by + * using an argument of type *RawBytes instead; see the documentation + * for RawBytes for restrictions on its use. * - * If WriteHeader is not called explicitly, the first call to Write - * will trigger an implicit WriteHeader(http.StatusOK). - * Thus explicit calls to WriteHeader are mainly used to - * send error codes. + * If an argument has type *interface{}, Scan copies the value + * provided by the underlying driver without conversion. When scanning + * from a source value of type []byte to *interface{}, a copy of the + * slice is made and the caller owns the result. * - * The provided code must be a valid HTTP 1xx-5xx status code. - * Only one header may be written. Go does not currently - * support sending user-defined 1xx informational headers, - * with the exception of 100-continue response header that the - * Server sends automatically when the Request.Body is read. + * Source values of type time.Time may be scanned into values of type + * *time.Time, *interface{}, *string, or *[]byte. When converting to + * the latter two, time.RFC3339Nano is used. + * + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or *RawBytes. + * + * For scanning into *bool, the source may be true, false, 1, 0, or + * string inputs parseable by strconv.ParseBool. + * + * Scan can also convert a cursor returned from a query, such as + * "select cursor(select * from my_table) from dual", into a + * *Rows value that can itself be scanned from. The parent + * select query will close any cursor *Rows if the parent *Rows is closed. + * + * If any of the first arguments implementing Scanner returns an error, + * that error will be wrapped in the returned error */ - writeHeader(statusCode: number): void + scan(...dest: any[]): void + } + interface Rows { + /** + * Close closes the Rows, preventing further enumeration. If Next is called + * and returns false and there are no further result sets, + * the Rows are closed automatically and it will suffice to check the + * result of Err. Close is idempotent and does not affect the result of Err. + */ + close(): void } /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. + * A Result summarizes an executed SQL command. */ - interface Server { + interface Result { /** - * 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. + * LastInsertId returns the integer generated by the database + * in response to a command. Typically this will be from an + * "auto increment" column when inserting a new row. Not all + * databases support this feature, and the syntax of such + * statements varies. */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil + lastInsertId(): number /** - * TLSConfig optionally provides a TLS configuration for use - * by ServeTLS and ListenAndServeTLS. Note that this value is - * cloned by ServeTLS and ListenAndServeTLS, so it's not - * possible to modify the configuration with methods like - * tls.Config.SetSessionTicketKeys. To use - * SetSessionTicketKeys, use Server.Serve with a TLS Listener - * instead. + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. */ - tlsConfig?: tls.Config + rowsAffected(): number + } +} + +/** + * 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 { /** - * 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. + * Len returns the number of bytes of the unread portion of the + * slice. */ - readTimeout: time.Duration + len(): number + } + interface Reader { /** - * 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. + * Size returns the original length of the underlying byte slice. + * Size is the number of bytes available for reading via ReadAt. + * The returned value is always the same and is not affected by calls + * to any other method. */ - readHeaderTimeout: time.Duration + size(): number + } + interface Reader { /** - * 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. + * Read implements the io.Reader interface. */ - writeTimeout: time.Duration - /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If IdleTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - idleTimeout: time.Duration - /** - * MaxHeaderBytes controls the maximum number of bytes the - * server will read parsing the request header's keys and - * values, including the request line. It does not limit the - * size of the request body. - * If zero, DefaultMaxHeaderBytes is used. - */ - maxHeaderBytes: number - /** - * TLSNextProto optionally specifies a function to take over - * ownership of the provided TLS connection when an ALPN - * protocol upgrade has occurred. The map key is the protocol - * name negotiated. The Handler argument should be used to - * handle HTTP requests and will initialize the Request's TLS - * and RemoteAddr if not already set. The connection is - * automatically closed when the function returns. - * If TLSNextProto is not nil, HTTP/2 support is not enabled - * automatically. - */ - tlsNextProto: _TygojaDict - /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. - */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void - /** - * ErrorLog specifies an optional logger for errors accepting - * connections, unexpected behavior from handlers, and - * underlying FileSystem errors. - * If nil, logging is done via the log package's standard logger. - */ - errorLog?: log.Logger - /** - * BaseContext optionally specifies a function that returns - * the base context for incoming requests on this server. - * The provided Listener is the specific Listener that's - * about to start accepting requests. - * If BaseContext is nil, the default is context.Background(). - * If non-nil, it must return a non-nil context. - */ - baseContext: (_arg0: net.Listener) => context.Context - /** - * ConnContext optionally specifies a function that modifies - * the context used for a new connection c. The provided ctx - * is derived from the base context and has a ServerContextKey - * value. - */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context + read(b: string): number } - interface Server { + interface Reader { /** - * 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). + * ReadAt implements the io.ReaderAt interface. */ - close(): void + readAt(b: string, off: number): number } - interface Server { + interface Reader { /** - * 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. + * ReadByte implements the io.ByteReader interface. */ - shutdown(ctx: context.Context): void + readByte(): string } - interface Server { + interface Reader { /** - * 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. + * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. */ - registerOnShutdown(f: () => void): void + unreadByte(): void } - interface Server { + interface Reader { /** - * 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. + * ReadRune implements the io.RuneReader interface. */ - listenAndServe(): void + readRune(): [string, number] } - interface Server { + interface Reader { /** - * Serve accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines read requests and - * then call srv.Handler to reply to them. - * - * 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. + * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. */ - serve(l: net.Listener): void + unreadRune(): void } - interface Server { + interface Reader { /** - * 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. + * Seek implements the io.Seeker interface. */ - serveTLS(l: net.Listener, certFile: string): void + seek(offset: number, whence: number): number } - interface Server { + interface Reader { /** - * 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. + * WriteTo implements the io.WriterTo interface. */ - setKeepAlivesEnabled(v: boolean): void + writeTo(w: io.Writer): number } - interface Server { + interface Reader { /** - * 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. + * Reset resets the Reader to be reading from b. */ - listenAndServeTLS(certFile: string): void + reset(b: string): void } } -namespace auth { +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + */ +namespace multipart { /** - * AuthUser defines a standardized oauth2 user data structure. + * A FileHeader describes a file part of a multipart request. */ - interface AuthUser { - id: string - name: string - username: string - email: string - avatarUrl: string - rawUser: _TygojaDict - accessToken: string - refreshToken: string + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number } - /** - * Provider defines a common interface for an OAuth2 client. - */ - interface Provider { - /** - * Scopes returns the context associated with the provider (if any). - */ - context(): context.Context - /** - * SetContext assigns the specified context to the current provider. - */ - setContext(ctx: context.Context): void - /** - * Scopes returns the provider access permissions that will be requested. - */ - scopes(): Array - /** - * SetScopes sets the provider access permissions that will be requested later. - */ - setScopes(scopes: Array): void - /** - * ClientId returns the provider client's app ID. - */ - clientId(): string - /** - * SetClientId sets the provider client's ID. - */ - setClientId(clientId: string): void - /** - * ClientSecret returns the provider client's app secret. - */ - clientSecret(): string - /** - * SetClientSecret sets the provider client's app secret. - */ - setClientSecret(secret: string): void - /** - * RedirectUrl returns the end address to redirect the user - * going through the OAuth flow. - */ - redirectUrl(): string - /** - * SetRedirectUrl sets the provider's RedirectUrl. - */ - setRedirectUrl(url: string): void + interface FileHeader { /** - * AuthUrl returns the provider's authorization service url. + * Open opens and returns the FileHeader's associated File. */ - authUrl(): string - /** - * SetAuthUrl sets the provider's AuthUrl. - */ - setAuthUrl(url: string): void - /** - * TokenUrl returns the provider's token exchange service url. - */ - tokenUrl(): string - /** - * SetTokenUrl sets the provider's TokenUrl. - */ - setTokenUrl(url: string): void - /** - * UserApiUrl returns the provider's user info api url. - */ - userApiUrl(): string - /** - * SetUserApiUrl sets the provider's UserApiUrl. - */ - setUserApiUrl(url: string): void - /** - * Client returns an http client using the provided token. - */ - client(token: oauth2.Token): (http.Client | undefined) - /** - * BuildAuthUrl returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. - */ - buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string - /** - * FetchToken converts an authorization code to token. - */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) - /** - * FetchRawUserData requests and marshalizes into `result` the - * the OAuth user api response. - */ - fetchRawUserData(token: oauth2.Token): string - /** - * FetchAuthUser is similar to FetchRawUserData, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. - */ - fetchAuthUser(token: oauth2.Token): (AuthUser | undefined) + open(): File } } /** - * Package echo implements high performance, minimalist Go web framework. + * Package http provides HTTP client and server implementations. * - * Example: + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: * * ``` - * package main + * 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"}}) + * ``` * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) + * The client must close the response body when finished with it: * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` * - * func main() { - * // Echo instance - * e := echo.New() + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } * - * // Routes - * e.GET("/", hello) + * resp, err := client.Get("http://example.com") + * // ... * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... * ``` * - * Learn more at https://echo.labstack.com + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use DefaultServeMux. + * Handle and HandleFunc add handlers to DefaultServeMux: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting Transport.TLSNextProto (for clients) or + * Server.TLSNextProto (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG environment variables are + * currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * The GODEBUG variables are not covered by Go's API compatibility + * promise. Please report any issues before disabling HTTP/2 + * support: https://golang.org/s/http2bug + * + * The http package's Transport and Server both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. */ -namespace echo { +namespace http { + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url /** - * Context represents the context of the current HTTP request. It holds request and - * response objects, path, path parameters, data and registered handler. + * 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 Context { - /** - * Request returns `*http.Request`. - */ - request(): (http.Request | undefined) - /** - * SetRequest sets `*http.Request`. - */ - setRequest(r: http.Request): void - /** - * SetResponse sets `*Response`. - */ - setResponse(r: Response): void - /** - * Response returns `*Response`. - */ - response(): (Response | undefined) - /** - * IsTLS returns true if HTTP connection is TLS otherwise false. - */ - isTLS(): boolean - /** - * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. - */ - isWebSocket(): boolean - /** - * Scheme returns the HTTP protocol scheme, `http` or `https`. - */ - scheme(): string - /** - * RealIP returns the client's network address based on `X-Forwarded-For` - * or `X-Real-IP` request header. - * The behavior can be configured using `Echo#IPExtractor`. - */ - realIP(): string + interface Request { /** - * RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route. - * In case of 404 (route not found) and 405 (method not allowed) RouteInfo returns generic struct for these cases. + * 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. */ - routeInfo(): RouteInfo + method: string /** - * Path returns the registered path for the handler. + * 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. */ - path(): string + url?: url.URL /** - * PathParam returns path parameter by name. + * 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. */ - pathParam(name: string): string + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * PathParamDefault returns the path parameter or default value for the provided name. + * Header contains the request header fields either received + * by the server or to be sent by the client. * - * Notes for DefaultRouter implementation: - * Path parameter could be empty for cases like that: - * * route `/release-:version/bin` and request URL is `/release-/bin` - * * route `/api/:version/image.jpg` and request URL is `/api//image.jpg` - * but not when path parameter is last part of route path - * * route `/download/file.:ext` will not match request `/download/file.` + * 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. */ - pathParamDefault(name: string, defaultValue: string): string + header: Header /** - * PathParams returns path parameter values. + * 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. */ - pathParams(): PathParams + body: io.ReadCloser /** - * SetPathParams sets path parameters for current request. + * 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. */ - setPathParams(params: PathParams): void + getBody: () => io.ReadCloser /** - * QueryParam returns the query param for the provided name. + * 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. */ - queryParam(name: string): string + contentLength: number /** - * QueryParamDefault returns the query param or default value for the provided name. + * 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. */ - queryParamDefault(name: string): string + transferEncoding: Array /** - * QueryParams returns the query parameters as `url.Values`. + * 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. */ - queryParams(): url.Values + close: boolean /** - * QueryString returns the URL query string. + * 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. */ - queryString(): string + host: string /** - * FormValue returns the form field value for the provided name. + * 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. */ - formValue(name: string): string + form: url.Values /** - * FormValueDefault returns the form field value or default value for the provided name. + * 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. */ - formValueDefault(name: string): string + postForm: url.Values /** - * FormValues returns the form field values as `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. */ - formValues(): url.Values + multipartForm?: multipart.Form /** - * FormFile returns the multipart form file for the provided name. + * 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. */ - formFile(name: string): (multipart.FileHeader | undefined) + trailer: Header /** - * MultipartForm returns the multipart form. + * 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. */ - multipartForm(): (multipart.Form | undefined) + remoteAddr: string /** - * Cookie returns the named cookie provided in the request. + * 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. */ - cookie(name: string): (http.Cookie | undefined) + requestURI: string /** - * SetCookie adds a `Set-Cookie` header in HTTP response. + * 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. */ - setCookie(cookie: http.Cookie): void + tls?: tls.ConnectionState /** - * Cookies returns the HTTP cookies sent with the request. + * 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. */ - cookies(): Array<(http.Cookie | undefined)> + cancel: undefined /** - * Get retrieves data from the context. + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. */ - get(key: string): { + response?: Response } + interface Request { /** - * Set saves data in the context. + * Context returns the request's context. To change the context, use + * WithContext. + * + * The returned context is always non-nil; it defaults to the + * background context. + * + * For outgoing client requests, the context controls cancellation. + * + * For incoming server requests, the context is canceled when the + * client's connection closes, the request is canceled (with HTTP/2), + * or when the ServeHTTP method returns. */ - set(key: string, val: { - }): void + context(): context.Context + } + interface Request { /** - * Bind binds the request body into provided type `i`. The default binder - * does it based on Content-Type header. + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. + * + * For outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. + * + * To create a new request with a context, use NewRequestWithContext. + * To change the context of a request, such as an incoming request you + * want to modify before sending back out, use Request.Clone. Between + * those two uses, it's rare to need WithContext. */ - bind(i: { - }): void + withContext(ctx: context.Context): (Request | undefined) + } + interface Request { /** - * Validate validates provided `i`. It is usually called after `Context#Bind()`. - * Validator must be registered using `Echo#Validator`. + * 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. */ - validate(i: { - }): void - /** - * Render renders a template with data and sends a text/html response with status - * code. Renderer must be registered using `Echo.Renderer`. - */ - render(code: number, name: string, data: { - }): void - /** - * HTML sends an HTTP response with status code. - */ - html(code: number, html: string): void - /** - * HTMLBlob sends an HTTP blob response with status code. - */ - htmlBlob(code: number, b: string): void - /** - * String sends a string response with status code. - */ - string(code: number, s: string): void - /** - * JSON sends a JSON response with status code. - */ - json(code: number, i: { - }): void + clone(ctx: context.Context): (Request | undefined) + } + interface Request { /** - * JSONPretty sends a pretty-print JSON with status code. + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - jsonPretty(code: number, i: { - }, indent: string): void + protoAtLeast(major: number): boolean + } + interface Request { /** - * JSONBlob sends a JSON blob response with status code. + * UserAgent returns the client's User-Agent, if sent in the request. */ - jsonBlob(code: number, b: string): void + userAgent(): string + } + interface Request { /** - * JSONP sends a JSONP response with status code. It uses `callback` to construct - * the JSONP payload. + * Cookies parses and returns the HTTP cookies sent with the request. */ - jsonp(code: number, callback: string, i: { - }): void + cookies(): Array<(Cookie | undefined)> + } + interface Request { /** - * JSONPBlob sends a JSONP blob response with status code. It uses `callback` - * to construct the JSONP payload. + * 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. */ - jsonpBlob(code: number, callback: string, b: string): void + cookie(name: string): (Cookie | undefined) + } + interface Request { /** - * XML sends an XML response with status code. + * 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. */ - xml(code: number, i: { - }): void + addCookie(c: Cookie): void + } + interface Request { /** - * XMLPretty sends a pretty-print XML with status code. + * 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"]. */ - xmlPretty(code: number, i: { - }, indent: string): void + referer(): string + } + interface Request { /** - * XMLBlob sends an XML blob response with status code. + * 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. */ - xmlBlob(code: number, b: string): void + multipartReader(): (multipart.Reader | undefined) + } + interface Request { /** - * Blob sends a blob response with status code and content type. + * 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. */ - blob(code: number, contentType: string, b: string): void + write(w: io.Writer): void + } + interface Request { /** - * Stream sends a streaming response with status code and content type. + * 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. */ - stream(code: number, contentType: string, r: io.Reader): void + writeProxy(w: io.Writer): void + } + interface Request { /** - * File sends a response with the content of the file. + * 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. */ - file(file: string): void + basicAuth(): [string, boolean] + } + interface Request { /** - * FileFS sends a response with the content of the file from given filesystem. + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. + * + * With HTTP Basic Authentication the provided username and password + * are not encrypted. + * + * Some protocols may impose additional requirements on pre-escaping the + * username and password. For instance, when used with OAuth2, both arguments + * must be URL encoded first with url.QueryEscape. */ - fileFS(file: string, filesystem: fs.FS): void + setBasicAuth(username: string): void + } + interface Request { /** - * Attachment sends a response as attachment, prompting client to save the - * file. + * 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. */ - attachment(file: string, name: string): void + parseForm(): void + } + interface Request { /** - * Inline sends a response as inline, opening the file in the browser. + * 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. */ - inline(file: string, name: string): void + parseMultipartForm(maxMemory: number): void + } + interface Request { /** - * NoContent sends a response with no body and a status code. + * 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. */ - noContent(code: number): void + formValue(key: string): string + } + interface Request { /** - * Redirect redirects the request to a provided URL with status code. + * 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. */ - redirect(code: number, url: string): void + postFormValue(key: string): string + } + interface Request { /** - * Echo returns the `Echo` instance. - * - * WARNING: Remember that Echo public fields and methods are coroutine safe ONLY when you are NOT mutating them - * anywhere in your code after Echo server has started. + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. */ - echo(): (Echo | undefined) + formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] } - // @ts-ignore - import stdContext = context /** - * Echo is the top-level framework instance. + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. * - * Note: replacing/nilling public fields is not coroutine/thread-safe and can cause data-races/panics. This is very likely - * to happen when you access Echo instances through Context.Echo() method. + * A ResponseWriter may not be used after the Handler.ServeHTTP method + * has returned. */ - interface Echo { + interface ResponseWriter { /** - * NewContextFunc allows using custom context implementations, instead of default *echo.context + * Header returns the header map that will be sent by + * WriteHeader. The Header map also is the mechanism with which + * Handlers can set HTTP trailers. + * + * Changing the header map after a call to WriteHeader (or + * Write) has no effect unless the modified headers are + * trailers. + * + * There are two ways to set Trailers. The preferred way is to + * predeclare in the headers which trailers you will later + * send by setting the "Trailer" header to the names of the + * trailer keys which will come later. In this case, those + * keys of the Header map are treated as if they were + * trailers. See the example. The second way, for trailer + * keys not known to the Handler until after the first Write, + * is to prefix the Header map keys with the TrailerPrefix + * constant value. See TrailerPrefix. + * + * To suppress automatic response headers (such as "Date"), set + * their value to nil. */ - newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext - debug: boolean - httpErrorHandler: HTTPErrorHandler - binder: Binder - jsonSerializer: JSONSerializer - validator: Validator - renderer: Renderer - logger: Logger - ipExtractor: IPExtractor + header(): Header /** - * Filesystem is file system used by Static and File handlers to access files. - * Defaults to os.DirFS(".") + * Write writes the data to the connection as part of an HTTP reply. * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. + * 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. */ - filesystem: fs.FS - } - /** - * HandlerFunc defines a function to serve HTTP requests. - */ - interface HandlerFunc {(c: Context): void } - /** - * MiddlewareFunc defines a function to process middleware. - */ - interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } - interface Echo { + write(_arg0: string): number /** - * NewContext returns a new Context instance. + * WriteHeader sends an HTTP response header with the provided + * status code. * - * Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway - * these arguments are useful when creating context for tests and cases like that. + * If WriteHeader is not called explicitly, the first call to Write + * will trigger an implicit WriteHeader(http.StatusOK). + * Thus explicit calls to WriteHeader are mainly used to + * send error codes. + * + * The provided code must be a valid HTTP 1xx-5xx status code. + * Only one header may be written. Go does not currently + * support sending user-defined 1xx informational headers, + * with the exception of 100-continue response header that the + * Server sends automatically when the Request.Body is read. */ - newContext(r: http.Request, w: http.ResponseWriter): Context + writeHeader(statusCode: number): void } - interface Echo { + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { /** - * Router returns the default router. + * 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. */ - router(): Router - } - interface Echo { + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * Routers returns the map of host => router. + * 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. */ - routers(): _TygojaDict - } - interface Echo { + tlsConfig?: tls.Config /** - * RouterFor returns Router for given host. + * 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. */ - routerFor(host: string): Router - } - interface Echo { + readTimeout: time.Duration /** - * ResetRouterCreator resets callback for creating new router instances. - * Note: current (default) router is immediately replaced with router created with creator func and vhost routers are cleared. + * 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. */ - resetRouterCreator(creator: (e: Echo) => Router): void - } - interface Echo { + readHeaderTimeout: time.Duration /** - * Pre adds middleware to the chain which is run before router tries to find matching route. - * Meaning middleware is executed even for 404 (not found) cases. + * 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. */ - pre(...middleware: MiddlewareFunc[]): void - } - interface Echo { + writeTimeout: time.Duration /** - * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. + * 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. */ - use(...middleware: MiddlewareFunc[]): void - } - interface Echo { + idleTimeout: time.Duration /** - * CONNECT registers a new CONNECT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + maxHeaderBytes: number /** - * DELETE registers a new DELETE route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * 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. */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + tlsNextProto: _TygojaDict /** - * GET registers a new GET route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * HEAD registers a new HEAD route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + errorLog?: log.Logger /** - * OPTIONS registers a new OPTIONS route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + baseContext: (_arg0: net.Listener) => context.Context /** - * PATCH registers a new PATCH route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + connContext: (ctx: context.Context, c: net.Conn) => context.Context } - interface Echo { + interface Server { /** - * POST registers a new POST route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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). */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + close(): void } - interface Echo { + interface Server { /** - * PUT registers a new PUT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + shutdown(ctx: context.Context): void } - interface Echo { + interface Server { /** - * TRACE registers a new TRACE route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * 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. */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + registerOnShutdown(f: () => void): void } - interface Echo { + interface Server { /** - * RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases) - * for current request URL. - * Path supports static and named/any parameters just like other http method is defined. Generally path is ended with - * wildcard/match-any character (`/*`, `/download/*` etc). + * 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. * - * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` + * If srv.Addr is blank, ":http" is used. + * + * ListenAndServe always returns a non-nil error. After Shutdown or Close, + * the returned error is ErrServerClosed. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * Any registers a new route for all supported HTTP methods and path with matching handler - * in the router with optional route-level middleware. Panics on error. - */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { - /** - * Match registers a new route for multiple HTTP methods and path with matching - * handler in the router with optional route-level middleware. Panics on error. - */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { - /** - * Static registers a new route with path prefix to serve static files from the provided root directory. - */ - static(pathPrefix: string): RouteInfo + listenAndServe(): void } - interface Echo { + interface Server { /** - * StaticFS registers a new route with path prefix to serve static files from the provided file system. + * 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. * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. - */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo - } - interface Echo { - /** - * FileFS registers a new route with path to serve file from the provided file system. - */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. - */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * AddRoute registers a new Route with default host Router - */ - addRoute(route: Routable): RouteInfo - } - interface Echo { - /** - * Add registers a new route for an HTTP method and path with matching handler - * in the router with optional route-level middleware. - */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { - /** - * Host creates a new router group for the provided host and optional host-level middleware. - */ - host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { - /** - * Group creates a new router group with prefix and optional group-level middleware. - */ - group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { - /** - * AcquireContext returns an empty `Context` instance from the pool. - * You must return the context by calling `ReleaseContext()`. + * 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. */ - acquireContext(): Context + serve(l: net.Listener): void } - interface Echo { + interface Server { /** - * ReleaseContext returns the `Context` instance back to the pool. - * You must call it after `AcquireContext()`. + * 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. */ - releaseContext(c: Context): void + serveTLS(l: net.Listener, certFile: string): void } - interface Echo { + interface Server { /** - * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + * 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. */ - serveHTTP(w: http.ResponseWriter, r: http.Request): void + setKeepAlivesEnabled(v: boolean): void } - interface Echo { + interface Server { /** - * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by - * sending os.Interrupt signal with `ctrl+c`. + * 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. * - * Note: this method is created for use in examples/demos and is deliberately simple without providing configuration - * options. + * 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. * - * In need of customization use: - * ``` - * sc := echo.StartConfig{Address: ":8080"} - * if err := sc.Start(e); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * ``` - * // or standard library `http.Server` - * ``` - * s := http.Server{Addr: ":8080", Handler: e} - * if err := s.ListenAndServe(); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * ``` + * If srv.Addr is blank, ":https" is used. + * + * ListenAndServeTLS always returns a non-nil error. After Shutdown or + * Close, the returned error is ErrServerClosed. */ - start(address: string): void + listenAndServeTLS(certFile: string): void } } /** - * Package blob provides an easy and portable way to interact with blobs - * within a storage location. Subpackages contain driver implementations of - * blob for supported services. - * - * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. - * - * # Errors + * Package echo implements high performance, minimalist Go web framework. * - * The errors returned from this package can be inspected in several ways: + * Example: * - * The Code function from gocloud.dev/gcerrors will return an error code, also - * defined in that package, when invoked on an error. + * ``` + * package main * - * The Bucket.ErrorAs method can retrieve the driver error underlying the returned - * error. + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) * - * # OpenCensus Integration + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } * - * OpenCensus supports tracing and metric collection for multiple languages and - * backend providers. See https://opencensus.io. + * func main() { + * // Echo instance + * e := echo.New() * - * 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. - * ``` + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) * - * 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". + * // Routes + * e.GET("/", hello) * - * 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. + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } * ``` * - * 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. + * Learn more at https://echo.labstack.com */ -namespace blob { +namespace echo { /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after - * reads are finished. + * Context represents the context of the current HTTP request. It holds request and + * response objects, path, path parameters, data and registered handler. */ - interface Reader { - } - interface Reader { + interface Context { /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * Request returns `*http.Request`. */ - read(p: string): number - } - interface Reader { + request(): (http.Request | undefined) /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * SetRequest sets `*http.Request`. */ - seek(offset: number, whence: number): number - } - interface Reader { + setRequest(r: http.Request): void /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * SetResponse sets `*Response`. */ - close(): void - } - interface Reader { + setResponse(r: Response): void /** - * ContentType returns the MIME type of the blob. + * Response returns `*Response`. */ - contentType(): string - } - interface Reader { + response(): (Response | undefined) /** - * ModTime returns the time the blob was last modified. + * IsTLS returns true if HTTP connection is TLS otherwise false. */ - modTime(): time.Time - } - interface Reader { + isTLS(): boolean /** - * Size returns the size of the blob content in bytes. + * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. */ - size(): number - } - interface Reader { + isWebSocket(): boolean /** - * 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. + * Scheme returns the HTTP protocol scheme, `http` or `https`. */ - as(i: { - }): boolean - } - interface Reader { + scheme(): string /** - * 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. + * RealIP returns the client's network address based on `X-Forwarded-For` + * or `X-Real-IP` request header. + * The behavior can be configured using `Echo#IPExtractor`. */ - writeTo(w: io.Writer): number - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { + realIP(): string /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + * RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route. + * In case of 404 (route not found) and 405 (method not allowed) RouteInfo returns generic struct for these cases. */ - cacheControl: string + routeInfo(): RouteInfo /** - * 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 + * Path returns the registered path for the handler. */ - contentDisposition: string + path(): 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 + * PathParam returns path parameter by name. */ - contentEncoding: string + pathParam(name: string): 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 + * PathParamDefault returns the path parameter or default value for the provided name. + * + * Notes for DefaultRouter implementation: + * Path parameter could be empty for cases like that: + * * route `/release-:version/bin` and request URL is `/release-/bin` + * * route `/api/:version/image.jpg` and request URL is `/api//image.jpg` + * but not when path parameter is last part of route path + * * route `/download/file.:ext` will not match request `/download/file.` */ - contentLanguage: string + pathParamDefault(name: string, defaultValue: string): 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 + * PathParams returns path parameter values. */ - contentType: string + pathParams(): PathParams /** - * 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. + * SetPathParams sets path parameters for current request. */ - metadata: _TygojaDict + setPathParams(params: PathParams): void /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * QueryParam returns the query param for the provided name. */ - createTime: time.Time + queryParam(name: string): string /** - * ModTime is the time the blob was last modified. + * QueryParamDefault returns the query param or default value for the provided name. */ - modTime: time.Time + queryParamDefault(name: string): string /** - * Size is the size of the blob's content in bytes. + * QueryParams returns the query parameters as `url.Values`. */ - size: number + queryParams(): url.Values /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * QueryString returns the URL query string. */ - md5: string + queryString(): string /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * FormValue returns the form field value for the provided name. */ - eTag: string - } - interface Attributes { + formValue(name: string): string /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * FormValueDefault returns the form field value or default value for the provided name. */ - as(i: { - }): boolean - } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { + formValueDefault(name: string): string /** - * Key is the key for this blob. + * FormValues returns the form field values as `url.Values`. */ - key: string + formValues(): url.Values /** - * ModTime is the time the blob was last modified. + * FormFile returns the multipart form file for the provided name. */ - modTime: time.Time + formFile(name: string): (multipart.FileHeader | undefined) /** - * Size is the size of the blob's content in bytes. + * MultipartForm returns the multipart form. */ - size: number + multipartForm(): (multipart.Form | undefined) /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * Cookie returns the named cookie provided in the request. */ - md5: string + cookie(name: string): (http.Cookie | undefined) /** - * 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. + * SetCookie adds a `Set-Cookie` header in HTTP response. */ - isDir: boolean - } - interface ListObject { + setCookie(cookie: http.Cookie): void /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * Cookies returns the HTTP cookies sent with the request. */ - as(i: { - }): boolean - } -} - -/** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. - * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. - * - * Drivers that do not support context cancellation will not return until - * after the query is completed. - * - * For usage examples, see the wiki page at - * https://golang.org/s/sqlwiki. - */ -namespace sql { - /** - * TxOptions holds the transaction options to be used in DB.BeginTx. - */ - interface TxOptions { + cookies(): Array<(http.Cookie | undefined)> /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * Get retrieves data from the context. */ - isolation: IsolationLevel - readOnly: boolean - } - /** - * DB is a database handle representing a pool of zero or more - * underlying connections. It's safe for concurrent use by multiple - * goroutines. - * - * The sql package creates and frees connections automatically; it - * also maintains a free pool of idle connections. If the database has - * a concept of per-connection state, such state can be reliably observed - * within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the - * returned Tx is bound to a single connection. Once Commit or - * Rollback is called on the transaction, that transaction's - * connection is returned to DB's idle connection pool. The pool size - * can be controlled with SetMaxIdleConns. - */ - interface DB { + get(key: string): { } - interface DB { /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * Set saves data in the context. */ - pingContext(ctx: context.Context): void - } - interface DB { + set(key: string, val: { + }): void /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. - * - * Ping uses context.Background internally; to specify the context, use - * PingContext. + * Bind binds the request body into provided type `i`. The default binder + * does it based on Content-Type header. */ - ping(): void - } - interface DB { + bind(i: { + }): void /** - * Close closes the database and prevents new queries from starting. - * Close then waits for all queries that have started processing on the server - * to finish. - * - * It is rare to Close a DB, as the DB handle is meant to be - * long-lived and shared between many goroutines. + * Validate validates provided `i`. It is usually called after `Context#Bind()`. + * Validator must be registered using `Echo#Validator`. */ - close(): void - } - interface DB { + validate(i: { + }): void /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. - * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. - * - * If n <= 0, no idle connections are retained. - * - * The default max idle connections is currently 2. This may change in - * a future release. + * Render renders a template with data and sends a text/html response with status + * code. Renderer must be registered using `Echo.Renderer`. */ - setMaxIdleConns(n: number): void - } - interface DB { + render(code: number, name: string, data: { + }): void /** - * SetMaxOpenConns sets the maximum number of open connections to the database. - * - * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than - * MaxIdleConns, then MaxIdleConns will be reduced to match the new - * MaxOpenConns limit. - * - * If n <= 0, then there is no limit on the number of open connections. - * The default is 0 (unlimited). + * HTML sends an HTTP response with status code. */ - setMaxOpenConns(n: number): void - } - interface DB { + html(code: number, html: string): void /** - * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. - * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's age. + * HTMLBlob sends an HTTP blob response with status code. */ - setConnMaxLifetime(d: time.Duration): void - } - interface DB { + htmlBlob(code: number, b: string): void /** - * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. - * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's idle time. + * String sends a string response with status code. */ - setConnMaxIdleTime(d: time.Duration): void - } - interface DB { + string(code: number, s: string): void /** - * Stats returns database statistics. + * JSON sends a JSON response with status code. */ - stats(): DBStats - } - interface DB { + json(code: number, i: { + }): void /** - * 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. + * JSONPretty sends a pretty-print JSON with status code. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) - } - interface DB { + jsonPretty(code: number, i: { + }, indent: string): void /** - * Prepare creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * JSONBlob sends a JSON blob response with status code. */ - prepare(query: string): (Stmt | undefined) - } - interface DB { + jsonBlob(code: number, b: string): void /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * JSONP sends a JSONP response with status code. It uses `callback` to construct + * the JSONP payload. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface DB { + jsonp(code: number, callback: string, i: { + }): void /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * JSONPBlob sends a JSONP blob response with status code. It uses `callback` + * to construct the JSONP payload. */ - exec(query: string, ...args: any[]): Result - } - interface DB { + jsonpBlob(code: number, callback: string, b: string): void /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * XML sends an XML response with status code. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) - } - interface DB { + xml(code: number, i: { + }): void /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * XMLPretty sends a pretty-print XML with status code. */ - query(query: string, ...args: any[]): (Rows | undefined) - } - interface DB { + xmlPretty(code: number, i: { + }, indent: string): void /** - * 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. + * XMLBlob sends an XML blob response with status code. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) - } - interface DB { + xmlBlob(code: number, b: string): void /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * Blob sends a blob response with status code and content type. */ - queryRow(query: string, ...args: any[]): (Row | undefined) - } - interface DB { + blob(code: number, contentType: string, b: string): void /** - * 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. + * Stream sends a streaming response with status code and content type. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) - } - interface DB { + stream(code: number, contentType: string, r: io.Reader): void /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. - * - * Begin uses context.Background internally; to specify the context, use - * BeginTx. + * File sends a response with the content of the file. */ - begin(): (Tx | undefined) - } - interface DB { + file(file: string): void /** - * Driver returns the database's underlying driver. + * FileFS sends a response with the content of the file from given filesystem. */ - driver(): driver.Driver - } - interface DB { + fileFS(file: string, filesystem: fs.FS): void /** - * Conn returns a single connection by either opening a new connection - * or returning an existing connection from the connection pool. Conn will - * block until either a connection is returned or ctx is canceled. - * Queries run on the same Conn will be run in the same database session. + * Attachment sends a response as attachment, prompting client to save the + * file. + */ + attachment(file: string, name: string): void + /** + * Inline sends a response as inline, opening the file in the browser. + */ + inline(file: string, name: string): void + /** + * NoContent sends a response with no body and a status code. + */ + noContent(code: number): void + /** + * Redirect redirects the request to a provided URL with status code. + */ + redirect(code: number, url: string): void + /** + * Echo returns the `Echo` instance. * - * Every Conn must be returned to the database pool after use by - * calling Conn.Close. + * WARNING: Remember that Echo public fields and methods are coroutine safe ONLY when you are NOT mutating them + * anywhere in your code after Echo server has started. */ - conn(ctx: context.Context): (Conn | undefined) + echo(): (Echo | undefined) } + // @ts-ignore + import stdContext = context /** - * Tx is an in-progress database transaction. - * - * A transaction must end with a call to Commit or Rollback. - * - * After a call to Commit or Rollback, all operations on the - * transaction fail with ErrTxDone. + * Echo is the top-level framework instance. * - * The statements prepared for a transaction by calling - * the transaction's Prepare or Stmt methods are closed - * by the call to Commit or Rollback. + * Note: replacing/nilling public fields is not coroutine/thread-safe and can cause data-races/panics. This is very likely + * to happen when you access Echo instances through Context.Echo() method. */ - interface Tx { - } - interface Tx { + interface Echo { /** - * Commit commits the transaction. + * NewContextFunc allows using custom context implementations, instead of default *echo.context */ - commit(): void - } - interface Tx { + newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext + debug: boolean + httpErrorHandler: HTTPErrorHandler + binder: Binder + jsonSerializer: JSONSerializer + validator: Validator + renderer: Renderer + logger: Logger + ipExtractor: IPExtractor /** - * Rollback aborts the transaction. + * Filesystem is file system used by Static and File handlers to access files. + * Defaults to os.DirFS(".") + * + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. */ - rollback(): void + filesystem: fs.FS } - interface Tx { + /** + * HandlerFunc defines a function to serve HTTP requests. + */ + interface HandlerFunc {(c: Context): void } + /** + * MiddlewareFunc defines a function to process middleware. + */ + interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } + interface Echo { /** - * PrepareContext creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. + * NewContext returns a new Context instance. * - * The provided context will be used for the preparation of the context, not - * for the execution of the returned statement. The returned statement - * will run in the transaction context. + * Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway + * these arguments are useful when creating context for tests and cases like that. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + newContext(r: http.Request, w: http.ResponseWriter): Context } - interface Tx { + interface Echo { /** - * Prepare creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * Router returns the default router. */ - prepare(query: string): (Stmt | undefined) + router(): Router } - interface Tx { + interface Echo { /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. + * Routers returns the map of host => router. */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) + routers(): _TygojaDict } - interface Tx { + interface Echo { /** - * Stmt returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * Stmt uses context.Background internally; to specify the context, use - * StmtContext. + * RouterFor returns Router for given host. */ - stmt(stmt: Stmt): (Stmt | undefined) + routerFor(host: string): Router } - interface Tx { + interface Echo { /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * ResetRouterCreator resets callback for creating new router instances. + * Note: current (default) router is immediately replaced with router created with creator func and vhost routers are cleared. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + resetRouterCreator(creator: (e: Echo) => Router): void } - interface Tx { + interface Echo { /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * Pre adds middleware to the chain which is run before router tries to find matching route. + * Meaning middleware is executed even for 404 (not found) cases. */ - exec(query: string, ...args: any[]): Result + pre(...middleware: MiddlewareFunc[]): void } - interface Tx { + interface Echo { /** - * QueryContext executes a query that returns rows, typically a SELECT. + * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + use(...middleware: MiddlewareFunc[]): void } - interface Tx { + interface Echo { /** - * Query executes a query that returns rows, typically a SELECT. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * CONNECT registers a new CONNECT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - query(query: string, ...args: any[]): (Rows | undefined) + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Tx { + interface Echo { /** - * 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. + * DELETE registers a new DELETE route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Tx { + interface Echo { /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * GET registers a new GET route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - queryRow(query: string, ...args: any[]): (Row | undefined) + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - /** - * Stmt is a prepared statement. - * A Stmt is safe for concurrent use by multiple goroutines. - * - * If a Stmt is prepared on a Tx or Conn, it will be bound to a single - * underlying connection forever. If the Tx or Conn closes, the Stmt will - * become unusable and all operations will return an error. - * If a Stmt is prepared on a DB, it will remain usable for the lifetime of the - * DB. When the Stmt needs to execute on a new underlying connection, it will - * prepare itself on the new connection automatically. - */ - interface Stmt { + interface Echo { + /** + * HEAD registers a new HEAD route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * OPTIONS registers a new OPTIONS route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - execContext(ctx: context.Context, ...args: any[]): Result + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * Exec executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * PATCH registers a new PATCH route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - exec(...args: any[]): Result + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * POST registers a new POST route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * PUT registers a new PUT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - query(...args: any[]): (Rows | undefined) + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * QueryRowContext executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned *Row, which is always non-nil. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * TRACE registers a new TRACE route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * QueryRow executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned *Row, which is always non-nil. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * Example usage: - * - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases) + * for current request URL. + * Path supports static and named/any parameters just like other http method is defined. Generally path is ended with + * wildcard/match-any character (`/*`, `/download/*` etc). * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - queryRow(...args: any[]): (Row | undefined) + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Stmt { + interface Echo { /** - * Close closes the statement. + * Any registers a new route for all supported HTTP methods and path with matching handler + * in the router with optional route-level middleware. Panics on error. */ - close(): void + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - /** - * Rows is the result of a query. Its cursor starts before the first row - * of the result set. Use Next to advance from row to row. - */ - interface Rows { + interface Echo { + /** + * Match registers a new route for multiple HTTP methods and path with matching + * handler in the router with optional route-level middleware. Panics on error. + */ + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface Rows { + interface Echo { /** - * Next prepares the next result row for reading with the Scan method. It - * returns true on success, or false if there is no next result row or an error - * happened while preparing it. Err should be consulted to distinguish between - * the two cases. - * - * Every call to Scan, even the first one, must be preceded by a call to Next. + * Static registers a new route with path prefix to serve static files from the provided root directory. */ - next(): boolean + static(pathPrefix: string): RouteInfo } - interface Rows { + interface Echo { /** - * NextResultSet prepares the next result set for reading. It reports whether - * there is further result sets, or false if there is no further result set - * or if there is an error advancing to it. The Err method should be consulted - * to distinguish between the two cases. + * StaticFS registers a new route with path prefix to serve static files from the provided file system. * - * After calling NextResultSet, the Next method should always be called before - * scanning. If there are further result sets they may not have rows in the result - * set. + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. */ - nextResultSet(): boolean + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface Rows { + interface Echo { /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit Close. + * FileFS registers a new route with path to serve file from the provided file system. */ - err(): void + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface Rows { + interface Echo { /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. + * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. */ - columns(): Array + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Rows { + interface Echo { /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * AddRoute registers a new Route with default host Router */ - columnTypes(): Array<(ColumnType | undefined)> + addRoute(route: Routable): RouteInfo } - interface Rows { + interface Echo { /** - * Scan copies the columns in the current row into the values pointed - * at by dest. The number of values in dest must be the same as the - * number of columns in Rows. - * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: - * - * ``` - * *string - * *[]byte - * *int, *int8, *int16, *int32, *int64 - * *uint, *uint8, *uint16, *uint32, *uint64 - * *bool - * *float32, *float64 - * *interface{} - * *RawBytes - * *Rows (cursor value) - * any type implementing Scanner (see Scanner docs) - * ``` - * - * In the most simple case, if the type of the value from the source - * column is an integer, bool or string type T and dest is of type *T, - * Scan simply assigns the value through the pointer. - * - * Scan also converts between string and numeric types, as long as no - * information would be lost. While Scan stringifies all numbers - * scanned from numeric database columns into *string, scans into - * numeric types are checked for overflow. For example, a float64 with - * value 300 or a string with value "300" can scan into a uint16, but - * not into a uint8, though float64(255) or "255" can scan into a - * uint8. One exception is that scans of some float64 numbers to - * strings may lose information when stringifying. In general, scan - * floating point columns into *float64. - * - * If a dest argument has type *[]byte, Scan saves in that argument a - * copy of the corresponding data. The copy is owned by the caller and - * can be modified and held indefinitely. The copy can be avoided by - * using an argument of type *RawBytes instead; see the documentation - * for RawBytes for restrictions on its use. - * - * If an argument has type *interface{}, Scan copies the value - * provided by the underlying driver without conversion. When scanning - * from a source value of type []byte to *interface{}, a copy of the - * slice is made and the caller owns the result. - * - * Source values of type time.Time may be scanned into values of type - * *time.Time, *interface{}, *string, or *[]byte. When converting to - * the latter two, time.RFC3339Nano is used. - * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or *RawBytes. - * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by strconv.ParseBool. - * - * Scan can also convert a cursor returned from a query, such as - * "select cursor(select * from my_table) from dual", into a - * *Rows value that can itself be scanned from. The parent - * select query will close any cursor *Rows if the parent *Rows is closed. - * - * If any of the first arguments implementing Scanner returns an error, - * that error will be wrapped in the returned error - */ - scan(...dest: any[]): void - } - interface Rows { - /** - * Close closes the Rows, preventing further enumeration. If Next is called - * and returns false and there are no further result sets, - * the Rows are closed automatically and it will suffice to check the - * result of Err. Close is idempotent and does not affect the result of Err. + * Add registers a new route for an HTTP method and path with matching handler + * in the router with optional route-level middleware. */ - close(): void + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - /** - * LastInsertId returns the integer generated by the database - * in response to a command. Typically this will be from an - * "auto increment" column when inserting a new row. Not all - * databases support this feature, and the syntax of such - * statements varies. - */ - lastInsertId(): number + interface Echo { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * Host creates a new router group for the provided host and optional host-level middleware. */ - rowsAffected(): number + host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * JsonArray defines a slice that is safe for json and db read/write. - */ - interface JsonArray extends Array{} - interface JsonArray { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Group creates a new router group with prefix and optional group-level middleware. */ - marshalJSON(): string + group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) } - interface JsonArray { + interface Echo { /** - * Value implements the [driver.Valuer] interface. + * AcquireContext returns an empty `Context` instance from the pool. + * You must return the context by calling `ReleaseContext()`. */ - value(): driver.Value + acquireContext(): Context } - interface JsonArray { + interface Echo { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. + * ReleaseContext returns the `Context` instance back to the pool. + * You must call it after `AcquireContext()`. */ - scan(value: any): void + releaseContext(c: Context): void } - /** - * JsonMap defines a map that is safe for json and db read/write. - */ - interface JsonMap extends _TygojaDict{} - interface JsonMap { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. + * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. */ - marshalJSON(): string + serveHTTP(w: http.ResponseWriter, r: http.Request): void } - interface JsonMap { + interface Echo { /** - * Get retrieves a single value from the current JsonMap. + * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by + * sending os.Interrupt signal with `ctrl+c`. * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). - */ - get(key: string): any - } - interface JsonMap { - /** - * Set sets a single value in the current JsonMap. + * Note: this method is created for use in examples/demos and is deliberately simple without providing configuration + * options. * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). - */ - set(key: string, value: any): void - } - interface JsonMap { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): driver.Value - } - interface JsonMap { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. + * In need of customization use: + * ``` + * sc := echo.StartConfig{Address: ":8080"} + * if err := sc.Start(e); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * ``` + * // or standard library `http.Server` + * ``` + * s := http.Server{Addr: ":8080", Handler: e} + * if err := s.ListenAndServe(); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * ``` */ - scan(value: any): void + start(address: string): void } } -namespace settings { - // @ts-ignore - import validation = ozzo_validation +/** + * 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 { /** - * Settings defines common app configuration options. + * 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 Settings { - meta: MetaConfig - logs: LogsConfig - smtp: SmtpConfig - s3: S3Config - backups: BackupsConfig - adminAuthToken: TokenConfig - adminPasswordResetToken: TokenConfig - adminFileToken: TokenConfig - recordAuthToken: TokenConfig - recordPasswordResetToken: TokenConfig - recordEmailChangeToken: TokenConfig - recordVerificationToken: TokenConfig - recordFileToken: TokenConfig + interface MapClaims extends _TygojaDict{} + interface MapClaims { /** - * Deprecated: Will be removed in v0.9+ + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - emailAuth: EmailAuthConfig - googleAuth: AuthProviderConfig - facebookAuth: AuthProviderConfig - githubAuth: AuthProviderConfig - gitlabAuth: AuthProviderConfig - discordAuth: AuthProviderConfig - twitterAuth: AuthProviderConfig - microsoftAuth: AuthProviderConfig - spotifyAuth: AuthProviderConfig - kakaoAuth: AuthProviderConfig - twitchAuth: AuthProviderConfig - stravaAuth: AuthProviderConfig - giteeAuth: AuthProviderConfig - livechatAuth: AuthProviderConfig - giteaAuth: AuthProviderConfig - oidcAuth: AuthProviderConfig - oidc2Auth: AuthProviderConfig - oidc3Auth: AuthProviderConfig - appleAuth: AuthProviderConfig - instagramAuth: AuthProviderConfig - vkAuth: AuthProviderConfig - yandexAuth: AuthProviderConfig + verifyAudience(cmp: string, req: boolean): boolean } - interface Settings { + interface MapClaims { /** - * Validate makes Settings validatable by implementing [validation.Validatable] interface. + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. */ - validate(): void + verifyExpiresAt(cmp: number, req: boolean): boolean } - interface Settings { + interface MapClaims { /** - * Merge merges `other` settings into the current one. + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. */ - merge(other: Settings): void + verifyIssuedAt(cmp: number, req: boolean): boolean } - interface Settings { + interface MapClaims { /** - * Clone creates a new deep copy of the current settings. + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. */ - clone(): (Settings | undefined) + verifyNotBefore(cmp: number, req: boolean): boolean } - interface Settings { + interface MapClaims { /** - * RedactClone creates a new deep copy of the current settings, - * while replacing the secret values with `******`. + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - redactClone(): (Settings | undefined) + verifyIssuer(cmp: string, req: boolean): boolean } - interface Settings { + interface MapClaims { /** - * NamedAuthProviderConfigs returns a map with all registered OAuth2 - * provider configurations (indexed by their name identifier). + * 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. */ - namedAuthProviderConfigs(): _TygojaDict + valid(): void } } -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. + * + * # 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 | undefined) + read(p: string): 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. - * - * 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. + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). */ - register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void - } -} - -/** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * Schema defines a dynamic db schema as a slice of `SchemaField`s. - */ - interface Schema { + close(): void } - interface Schema { + interface Reader { /** - * Fields returns the registered schema fields. + * ContentType returns the MIME type of the blob. */ - fields(): Array<(SchemaField | undefined)> + contentType(): string } - interface Schema { + interface Reader { /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. + * ModTime returns the time the blob was last modified. */ - initFieldsOptions(): void + modTime(): time.Time } - interface Schema { + interface Reader { /** - * Clone creates a deep clone of the current schema. + * Size returns the size of the blob content in bytes. */ - clone(): (Schema | undefined) + size(): number } - interface Schema { + interface Reader { /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. + * 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. */ - asMap(): _TygojaDict + as(i: { + }): boolean } - interface Schema { + interface Reader { /** - * GetFieldById returns a single field by its id. + * 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. */ - getFieldById(id: string): (SchemaField | undefined) + writeTo(w: io.Writer): number } - interface Schema { + /** + * Attributes contains attributes about a blob. + */ + interface Attributes { /** - * GetFieldByName returns a single field by its name. + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - getFieldByName(name: string): (SchemaField | undefined) - } - interface Schema { + cacheControl: string /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. + * 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 */ - removeField(id: string): void - } - interface Schema { + contentDisposition: string /** - * AddField registers the provided newField to the current schema. - * - * If field with `newField.Id` already exist, the existing field is - * replaced with the new one. - * - * Otherwise the new field is appended to the other schema fields. + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - addField(newField: SchemaField): void - } - interface Schema { + contentEncoding: string /** - * Validate makes Schema validatable by implementing [validation.Validatable] interface. - * - * Internally calls each individual field's validator and additionally - * checks for invalid renamed fields and field name duplications. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - validate(): void - } - interface Schema { + contentLanguage: string /** - * MarshalJSON implements the [json.Marshaler] interface. + * 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 */ - marshalJSON(): string - } - interface Schema { + contentType: string /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * On success, all schema field options are auto initialized. + * 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. */ - unmarshalJSON(data: string): void - } - interface Schema { + metadata: _TygojaDict /** - * Value implements the [driver.Valuer] interface. + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. */ - value(): driver.Value - } - interface Schema { + createTime: time.Time /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. + * ModTime is the time the blob was last modified. */ - scan(value: any): void - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - type _subyDIdo = BaseModel - interface Admin extends _subyDIdo { - avatar: number - email: string - tokenKey: string - passwordHash: string - lastResetSentAt: types.DateTime - } - interface Admin { + modTime: time.Time /** - * TableName returns the Admin model SQL table name. + * Size is the size of the blob's content in bytes. */ - tableName(): string - } - interface Admin { + size: number /** - * ValidatePassword validates a plain password against the model's password. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - validatePassword(password: string): boolean - } - interface Admin { + md5: string /** - * SetPassword sets cryptographically secure string to `model.Password`. - * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. */ - setPassword(password: string): void + eTag: string } - interface Admin { + interface Attributes { /** - * RefreshTokenKey generates and sets new random token key. + * 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. */ - refreshTokenKey(): void + as(i: { + }): boolean } - // @ts-ignore - import validation = ozzo_validation - type _subRiCQv = BaseModel - interface Collection extends _subRiCQv { - name: string - type: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { /** - * rules + * Key is the key for this blob. */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { + key: string /** - * TableName returns the Collection model SQL table name. + * ModTime is the time the blob was last modified. */ - tableName(): string - } - interface Collection { + modTime: time.Time /** - * BaseFilesPath returns the storage dir path used by the collection. + * Size is the size of the blob's content in bytes. */ - baseFilesPath(): string - } - interface Collection { + size: number /** - * IsBase checks if the current collection has "base" type. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - isBase(): boolean - } - interface Collection { + md5: string /** - * IsAuth checks if the current collection has "auth" type. + * 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. */ - isAuth(): boolean + isDir: boolean } - interface Collection { + interface ListObject { /** - * IsView checks if the current collection has "view" type. + * 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. */ - isView(): boolean + as(i: { + }): boolean } - interface Collection { +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { + /** + * JsonArray defines a slice that is safe for json and db read/write. + */ + interface JsonArray extends Array{} + interface JsonArray { /** * MarshalJSON implements the [json.Marshaler] interface. */ marshalJSON(): string } - interface Collection { + interface JsonArray { /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. + * Value implements the [driver.Valuer] interface. */ - baseOptions(): CollectionBaseOptions + value(): driver.Value } - interface Collection { + interface JsonArray { /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. */ - authOptions(): CollectionAuthOptions + scan(value: any): void } - interface Collection { + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. + * MarshalJSON implements the [json.Marshaler] interface. */ - viewOptions(): CollectionViewOptions + marshalJSON(): string } - interface Collection { + interface JsonMap { /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. + * Get retrieves a single value from the current JsonMap. + * + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - normalizeOptions(): void + get(key: string): any } - interface Collection { + interface JsonMap { /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). + * Set sets a single value in the current JsonMap. + * + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - decodeOptions(result: any): void + set(key: string, value: any): void } - interface Collection { + interface JsonMap { /** - * SetOptions normalizes and unmarshals the specified options into m.Options. + * Value implements the [driver.Valuer] interface. */ - setOptions(typedOptions: any): void + value(): driver.Value } - type _subFLVQG = BaseModel - interface ExternalAuth extends _subFLVQG { - collectionId: string - recordId: string - provider: string - providerId: string + interface JsonMap { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. + */ + scan(value: any): void } - interface ExternalAuth { - tableName(): string +} + +/** + * 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 { } - type _subprLxA = BaseModel - interface Record extends _subprLxA { + interface Schema { + /** + * Fields returns the registered schema fields. + */ + fields(): Array<(SchemaField | undefined)> } - interface Record { + interface Schema { /** - * TableName returns the table name associated to the current Record model. + * InitFieldsOptions calls `InitOptions()` for all schema fields. */ - tableName(): string + initFieldsOptions(): void } - interface Record { + interface Schema { /** - * Collection returns the Collection model associated to the current Record model. + * Clone creates a deep clone of the current schema. */ - collection(): (Collection | undefined) + clone(): (Schema | undefined) } - interface Record { + interface Schema { /** - * 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. + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. */ - originalCopy(): (Record | undefined) + asMap(): _TygojaDict } - interface Record { + interface Schema { /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. + * GetFieldById returns a single field by its id. */ - cleanCopy(): (Record | undefined) + getFieldById(id: string): (SchemaField | undefined) } - interface Record { + interface Schema { /** - * Expand returns a shallow copy of the current Record model expand data. + * GetFieldByName returns a single field by its name. */ - expand(): _TygojaDict + getFieldByName(name: string): (SchemaField | undefined) } - interface Record { + interface Schema { /** - * SetExpand shallow copies the provided data to the current Record model's expand. + * RemoveField removes a single schema field by its id. + * + * This method does nothing if field with `id` doesn't exist. */ - setExpand(expand: _TygojaDict): void + removeField(id: string): void } - interface Record { + interface Schema { /** - * MergeExpand merges recursively the provided expand data into - * the current model's expand (if any). + * AddField registers the provided newField to the current schema. * - * 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). + * 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. */ - mergeExpand(expand: _TygojaDict): void + addField(newField: SchemaField): void } - interface Record { + interface Schema { /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + * 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. */ - schemaData(): _TygojaDict + validate(): void } - interface Record { + interface Schema { /** - * 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. + * MarshalJSON implements the [json.Marshaler] interface. */ - unknownData(): _TygojaDict + marshalJSON(): string } - interface Record { + interface Schema { /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * On success, all schema field options are auto initialized. */ - ignoreEmailVisibility(state: boolean): void + unmarshalJSON(data: string): void } - interface Record { + interface Schema { /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). + * Value implements the [driver.Valuer] interface. */ - withUnknownData(state: boolean): void + value(): driver.Value } - interface Record { + 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 _subLrLQM = BaseModel + interface Admin extends _subLrLQM { + 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 _subgUvDe = BaseModel + interface Collection extends _subgUvDe { + name: string + type: string + system: boolean + schema: schema.Schema + indexes: types.JsonArray + /** + * rules + */ + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap + } + interface Collection { + /** + * TableName returns the Collection model SQL table name. + */ + tableName(): string + } + interface Collection { + /** + * BaseFilesPath returns the storage dir path used by the collection. + */ + baseFilesPath(): string + } + interface Collection { + /** + * IsBase checks if the current collection has "base" type. + */ + isBase(): boolean + } + interface Collection { + /** + * IsAuth checks if the current collection has "auth" type. + */ + isAuth(): boolean + } + interface Collection { + /** + * IsView checks if the current collection has "view" type. + */ + isView(): boolean + } + interface Collection { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface Collection { + /** + * BaseOptions decodes the current collection options and returns them + * as new [CollectionBaseOptions] instance. + */ + baseOptions(): CollectionBaseOptions + } + interface Collection { + /** + * AuthOptions decodes the current collection options and returns them + * as new [CollectionAuthOptions] instance. + */ + authOptions(): CollectionAuthOptions + } + interface Collection { + /** + * ViewOptions decodes the current collection options and returns them + * as new [CollectionViewOptions] instance. + */ + viewOptions(): CollectionViewOptions + } + interface Collection { + /** + * NormalizeOptions updates the current collection options with a + * new normalized state based on the collection type. + */ + normalizeOptions(): void + } + interface Collection { + /** + * DecodeOptions decodes the current collection options into the + * provided "result" (must be a pointer). + */ + decodeOptions(result: any): void + } + interface Collection { + /** + * SetOptions normalizes and unmarshals the specified options into m.Options. + */ + setOptions(typedOptions: any): void + } + type _subjXWqu = BaseModel + interface ExternalAuth extends _subjXWqu { + collectionId: string + recordId: string + provider: string + providerId: string + } + interface ExternalAuth { + tableName(): string + } + type _subjCdil = BaseModel + interface Record extends _subjCdil { + } + interface Record { + /** + * TableName returns the table name associated to the current Record model. + */ + tableName(): string + } + interface Record { + /** + * Collection returns the Collection model associated to the current Record model. + */ + collection(): (Collection | undefined) + } + interface Record { + /** + * OriginalCopy returns a copy of the current record model populated + * with its ORIGINAL data state (aka. the initially loaded) and + * everything else reset to the defaults. + */ + originalCopy(): (Record | undefined) + } + interface Record { + /** + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. + */ + cleanCopy(): (Record | undefined) + } + interface Record { + /** + * Expand returns a shallow copy of the current Record model expand data. + */ + expand(): _TygojaDict + } + interface Record { + /** + * SetExpand shallow copies the provided data to the current Record model's expand. + */ + setExpand(expand: _TygojaDict): void + } + interface Record { + /** + * MergeExpand merges recursively the provided expand data into + * the current model's expand (if any). + * + * Note that if an expanded prop with the same key is a slice (old or new expand) + * then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). + * Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew). + */ + mergeExpand(expand: _TygojaDict): void + } + interface Record { + /** + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + */ + schemaData(): _TygojaDict + } + interface Record { + /** + * UnknownData returns a shallow copy ONLY of the unknown record fields data, + * aka. fields that are neither one of the base and special system ones, + * nor defined by the collection schema. + */ + unknownData(): _TygojaDict + } + interface Record { + /** + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + */ + ignoreEmailVisibility(state: boolean): void + } + interface Record { + /** + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). + */ + withUnknownData(state: boolean): void + } + interface Record { /** * Set sets the provided key-value data pair for the current Record model. * @@ -8371,3070 +8152,2779 @@ namespace models { } } -/** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. - */ -namespace cobra { - interface Command { - /** - * GenBashCompletion generates bash completion file and writes to the passed writer. - */ - genBashCompletion(w: io.Writer): void +namespace auth { + /** + * AuthUser defines a standardized oauth2 user data structure. + */ + interface AuthUser { + id: string + name: string + username: string + email: string + avatarUrl: string + rawUser: _TygojaDict + accessToken: string + refreshToken: string } - interface Command { + /** + * Provider defines a common interface for an OAuth2 client. + */ + interface Provider { /** - * GenBashCompletionFile generates bash completion file. + * Scopes returns the context associated with the provider (if any). */ - genBashCompletionFile(filename: string): void - } - interface Command { + context(): context.Context /** - * GenBashCompletionFileV2 generates Bash completion version 2. + * SetContext assigns the specified context to the current provider. */ - genBashCompletionFileV2(filename: string, includeDesc: boolean): void - } - interface Command { + setContext(ctx: context.Context): void /** - * GenBashCompletionV2 generates Bash completion file version 2 - * and writes it to the passed writer. + * Scopes returns the provider access permissions that will be requested. */ - 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 { + scopes(): Array /** - * 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 + * SetScopes sets the provider access permissions that will be requested later. */ - use: string + setScopes(scopes: Array): void /** - * Aliases is an array of aliases that can be used instead of the first word in Use. + * ClientId returns the provider client's app ID. */ - aliases: Array + clientId(): string /** - * SuggestFor is an array of command names for which this command will be suggested - - * similar to aliases but only suggests. + * SetClientId sets the provider client's ID. */ - suggestFor: Array + setClientId(clientId: string): void /** - * Short is the short description shown in the 'help' output. + * ClientSecret returns the provider client's app secret. */ - short: string + clientSecret(): string /** - * The group id under which this subcommand is grouped in the 'help' output of its parent. + * SetClientSecret sets the provider client's app secret. */ - groupID: string + setClientSecret(secret: string): void /** - * Long is the long message shown in the 'help ' output. + * RedirectUrl returns the end address to redirect the user + * going through the OAuth flow. */ - long: string + redirectUrl(): string /** - * Example is examples of how to use the command. + * SetRedirectUrl sets the provider's RedirectUrl. */ - example: string + setRedirectUrl(url: string): void /** - * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions + * AuthUrl returns the provider's authorization service url. */ - validArgs: Array + authUrl(): string /** - * 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. + * SetAuthUrl sets the provider's AuthUrl. */ - validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] + setAuthUrl(url: string): void /** - * Expected arguments + * TokenUrl returns the provider's token exchange service url. */ - args: PositionalArgs + tokenUrl(): string /** - * ArgAliases is List of aliases for ValidArgs. - * These are not suggested to the user in the shell completion, - * but accepted if entered manually. + * SetTokenUrl sets the provider's TokenUrl. */ - argAliases: Array + setTokenUrl(url: string): void /** - * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - * For portability with other shells, it is recommended to instead use ValidArgsFunction + * UserApiUrl returns the provider's user info api url. */ - bashCompletionFunction: string + userApiUrl(): string /** - * Deprecated defines, if this command is deprecated and should print this string when used. + * SetUserApiUrl sets the provider's UserApiUrl. */ - deprecated: string + setUserApiUrl(url: string): void /** - * Annotations are key/value pairs that can be used by applications to identify or - * group commands. + * Client returns an http client using the provided token. */ - annotations: _TygojaDict + client(token: oauth2.Token): (http.Client | undefined) /** - * 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. + * BuildAuthUrl returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. */ - version: string + buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): 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. - * - * PersistentPreRun: children of this command will inherit and execute. + * FetchToken converts an authorization code to token. */ - persistentPreRun: (cmd: Command, args: Array) => void + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) /** - * PersistentPreRunE: PersistentPreRun but returns an error. + * FetchRawUserData requests and marshalizes into `result` the + * the OAuth user api response. */ - persistentPreRunE: (cmd: Command, args: Array) => void + fetchRawUserData(token: oauth2.Token): string /** - * PreRun: children of this command will not inherit. + * FetchAuthUser is similar to FetchRawUserData, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. */ - preRun: (cmd: Command, args: Array) => void + fetchAuthUser(token: oauth2.Token): (AuthUser | undefined) + } +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + /** + * Settings defines common app configuration options. + */ + interface Settings { + meta: MetaConfig + logs: LogsConfig + smtp: SmtpConfig + s3: S3Config + backups: BackupsConfig + adminAuthToken: TokenConfig + adminPasswordResetToken: TokenConfig + adminFileToken: TokenConfig + recordAuthToken: TokenConfig + recordPasswordResetToken: TokenConfig + recordEmailChangeToken: TokenConfig + recordVerificationToken: TokenConfig + recordFileToken: TokenConfig /** - * PreRunE: PreRun but returns an error. + * Deprecated: Will be removed in v0.9+ */ - preRunE: (cmd: Command, args: Array) => void + emailAuth: EmailAuthConfig + googleAuth: AuthProviderConfig + facebookAuth: AuthProviderConfig + githubAuth: AuthProviderConfig + gitlabAuth: AuthProviderConfig + discordAuth: AuthProviderConfig + twitterAuth: AuthProviderConfig + microsoftAuth: AuthProviderConfig + spotifyAuth: AuthProviderConfig + kakaoAuth: AuthProviderConfig + twitchAuth: AuthProviderConfig + stravaAuth: AuthProviderConfig + giteeAuth: AuthProviderConfig + livechatAuth: AuthProviderConfig + giteaAuth: AuthProviderConfig + oidcAuth: AuthProviderConfig + oidc2Auth: AuthProviderConfig + oidc3Auth: AuthProviderConfig + appleAuth: AuthProviderConfig + instagramAuth: AuthProviderConfig + vkAuth: AuthProviderConfig + yandexAuth: AuthProviderConfig + } + interface Settings { /** - * Run: Typically the actual work function. Most commands will only implement this. + * Validate makes Settings validatable by implementing [validation.Validatable] interface. */ - run: (cmd: Command, args: Array) => void + validate(): void + } + interface Settings { /** - * RunE: Run but returns an error. + * Merge merges `other` settings into the current one. */ - runE: (cmd: Command, args: Array) => void + merge(other: Settings): void + } + interface Settings { /** - * PostRun: run after the Run command. + * Clone creates a new deep copy of the current settings. */ - postRun: (cmd: Command, args: Array) => void + clone(): (Settings | undefined) + } + interface Settings { /** - * PostRunE: PostRun but returns an error. + * RedactClone creates a new deep copy of the current settings, + * while replacing the secret values with `******`. */ - postRunE: (cmd: Command, args: Array) => void + redactClone(): (Settings | undefined) + } + interface Settings { /** - * PersistentPostRun: children of this command will inherit and execute after PostRun. + * NamedAuthProviderConfigs returns a map with all registered OAuth2 + * provider configurations (indexed by their name identifier). */ - persistentPostRun: (cmd: Command, args: Array) => void + namedAuthProviderConfigs(): _TygojaDict + } +} + +/** + * Package daos handles common PocketBase DB model manipulations. + * + * Think of daos as DB repository and service layer in one. + */ +namespace daos { + interface Dao { /** - * PersistentPostRunE: PersistentPostRun but returns an error. + * AdminQuery returns a new Admin select query. */ - persistentPostRunE: (cmd: Command, args: Array) => void + adminQuery(): (dbx.SelectQuery | undefined) + } + interface Dao { /** - * FParseErrWhitelist flag parse errors to be ignored + * FindAdminById finds the admin with the provided id. */ - fParseErrWhitelist: FParseErrWhitelist + findAdminById(id: string): (models.Admin | undefined) + } + interface Dao { /** - * CompletionOptions is a set of options to control the handling of shell completion + * FindAdminByEmail finds the admin with the provided email address. */ - completionOptions: CompletionOptions + findAdminByEmail(email: string): (models.Admin | undefined) + } + interface Dao { /** - * TraverseChildren parses flags on all parents before executing child command. + * FindAdminByToken finds the admin associated with the provided JWT token. + * + * Returns an error if the JWT token is invalid or expired. */ - traverseChildren: boolean + findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) + } + interface Dao { /** - * Hidden defines, if this command is hidden and should NOT show up in the list of available commands. + * TotalAdmins returns the number of existing admin records. */ - hidden: boolean + totalAdmins(): number + } + interface Dao { /** - * SilenceErrors is an option to quiet errors down stream. + * IsAdminEmailUnique checks if the provided email address is not + * already in use by other admins. */ - silenceErrors: boolean + isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean + } + interface Dao { /** - * SilenceUsage is an option to silence usage when an error occurs. + * DeleteAdmin deletes the provided Admin model. + * + * Returns an error if there is only 1 admin. */ - silenceUsage: boolean + deleteAdmin(admin: models.Admin): void + } + interface Dao { /** - * DisableFlagParsing disables the flag parsing. - * If this is true all flags will be passed to the command as arguments. + * SaveAdmin upserts the provided Admin model. */ - disableFlagParsing: boolean + saveAdmin(admin: models.Admin): void + } + /** + * Dao handles various db operations. + * + * You can think of Dao as a repository and service layer in one. + */ + interface Dao { /** - * DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - * will be printed by generating docs for this command. + * MaxLockRetries specifies the default max "database is locked" auto retry attempts. */ - disableAutoGenTag: boolean + maxLockRetries: number /** - * DisableFlagsInUseLine will disable the addition of [flags] to the usage - * line of a command when printing help or generating docs + * ModelQueryTimeout is the default max duration of a running ModelQuery(). + * + * This field has no effect if an explicit query context is already specified. */ - disableFlagsInUseLine: boolean + modelQueryTimeout: time.Duration /** - * DisableSuggestions disables the suggestions based on Levenshtein distance - * that go along with 'unknown command' messages. + * write hooks */ - disableSuggestions: boolean + beforeCreateFunc: (eventDao: Dao, m: models.Model) => void + afterCreateFunc: (eventDao: Dao, m: models.Model) => void + beforeUpdateFunc: (eventDao: Dao, m: models.Model) => void + afterUpdateFunc: (eventDao: Dao, m: models.Model) => void + beforeDeleteFunc: (eventDao: Dao, m: models.Model) => void + afterDeleteFunc: (eventDao: Dao, m: models.Model) => void + } + interface Dao { /** - * SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - * Must be > 0. + * DB returns the default dao db builder (*dbx.DB or *dbx.TX). + * + * Currently the default db builder is dao.concurrentDB but that may change in the future. */ - suggestionsMinimumDistance: number + db(): dbx.Builder } - interface Command { + interface Dao { /** - * Context returns underlying command context. If command was executed - * with ExecuteContext or the context was set with SetContext, the - * previously set context will be returned. Otherwise, nil is returned. + * ConcurrentDB returns the dao concurrent (aka. multiple open connections) + * db builder (*dbx.DB or *dbx.TX). * - * 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. + * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. */ - context(): context.Context + concurrentDB(): dbx.Builder } - interface Command { + interface Dao { /** - * SetContext sets context for the command. This context will be overwritten by - * Command.ExecuteContext or Command.ExecuteContextC. + * NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) + * db builder (*dbx.DB or *dbx.TX). + * + * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. */ - setContext(ctx: context.Context): void + nonconcurrentDB(): dbx.Builder } - interface Command { + interface Dao { /** - * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden - * particularly useful when testing. + * Clone returns a new Dao with the same configuration options as the current one. */ - setArgs(a: Array): void + clone(): (Dao | undefined) } - interface Command { + interface Dao { /** - * SetOutput sets the destination for usage and error messages. - * If output is nil, os.Stderr is used. - * Deprecated: Use SetOut and/or SetErr instead + * WithoutHooks returns a new Dao with the same configuration options + * as the current one, but without create/update/delete hooks. */ - setOutput(output: io.Writer): void + withoutHooks(): (Dao | undefined) } - interface Command { + interface Dao { /** - * SetOut sets the destination for usage messages. - * If newOut is nil, os.Stdout is used. + * ModelQuery creates a new preconfigured select query with preset + * SELECT, FROM and other common fields based on the provided model. */ - setOut(newOut: io.Writer): void + modelQuery(m: models.Model): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * SetErr sets the destination for error messages. - * If newErr is nil, os.Stderr is used. + * FindById finds a single db record with the specified id and + * scans the result into m. */ - setErr(newErr: io.Writer): void + findById(m: models.Model, id: string): void } - interface Command { + interface Dao { /** - * SetIn sets the source for input data - * If newIn is nil, os.Stdin is used. + * RunInTransaction wraps fn into a transaction. + * + * It is safe to nest RunInTransaction calls as long as you use the txDao. */ - setIn(newIn: io.Reader): void + runInTransaction(fn: (txDao: Dao) => void): void } - interface Command { + interface Dao { /** - * SetUsageFunc sets usage function. Usage can be defined by application. + * Delete deletes the provided model. */ - setUsageFunc(f: (_arg0: Command) => void): void + delete(m: models.Model): void } - interface Command { + interface Dao { /** - * SetUsageTemplate sets usage template. Can be defined by Application. + * Save persists the provided model in the database. + * + * If m.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a model for update you can use m.MarkAsNotNew(). */ - setUsageTemplate(s: string): void + save(m: models.Model): void } - interface Command { + interface Dao { /** - * SetFlagErrorFunc sets a function to generate an error when flag parsing - * fails. + * CollectionQuery returns a new Collection select query. */ - setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void + collectionQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * SetHelpFunc sets help function. Can be defined by Application. + * FindCollectionsByType finds all collections by the given type. */ - setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void + findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> } - interface Command { + interface Dao { /** - * SetHelpCommand sets help command. + * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. */ - setHelpCommand(cmd: Command): void + findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) } - interface Command { + interface Dao { /** - * SetHelpCommandGroupID sets the group id of the help command. + * IsCollectionNameUnique checks that there is no existing collection + * with the provided name (case insensitive!). + * + * Note: case insensitive check because the name is used also as a table name for the records. */ - setHelpCommandGroupID(groupID: string): void + isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean } - interface Command { + interface Dao { /** - * SetCompletionCommandGroupID sets the group id of the completion command. + * FindCollectionReferences returns information for all + * relation schema fields referencing the provided collection. + * + * If the provided collection has reference to itself then it will be + * also included in the result. To exclude it, pass the collection id + * as the excludeId argument. */ - setCompletionCommandGroupID(groupID: string): void + findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict } - interface Command { + interface Dao { /** - * SetHelpTemplate sets help template to be used. Application can use it to set custom template. + * DeleteCollection deletes the provided Collection model. + * This method automatically deletes the related collection records table. + * + * NB! The collection cannot be deleted, if: + * - is system collection (aka. collection.System is true) + * - is referenced as part of a relation field in another collection */ - setHelpTemplate(s: string): void + deleteCollection(collection: models.Collection): void } - interface Command { + interface Dao { /** - * SetVersionTemplate sets version template to be used. Application can use it to set custom template. + * SaveCollection persists the provided Collection model and updates + * its related records table schema. + * + * If collecction.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a collection for update you can use collecction.MarkAsNotNew(). */ - setVersionTemplate(s: string): void + saveCollection(collection: models.Collection): void } - interface Command { + interface Dao { /** - * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. - * The user should not have a cyclic dependency on commands. + * ImportCollections imports the provided collections list within a single transaction. + * + * NB1! If deleteMissing is set, all local collections and schema fields, that are not present + * in the imported configuration, WILL BE DELETED (including their related records data). + * + * NB2! This method doesn't perform validations on the imported collections data! + * If you need validations, use [forms.CollectionsImport]. */ - setGlobalNormalizationFunc(n: (f: flag.FlagSet, name: string) => flag.NormalizedName): void + importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void } - interface Command { + interface Dao { /** - * OutOrStdout returns output to stdout. + * ExternalAuthQuery returns a new ExternalAuth select query. */ - outOrStdout(): io.Writer + externalAuthQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * OutOrStderr returns output to stderr + * FindAllExternalAuthsByRecord returns all ExternalAuth models + * linked to the provided auth record. */ - outOrStderr(): io.Writer + findAllExternalAuthsByRecord(authRecord: models.Record): Array<(models.ExternalAuth | undefined)> } - interface Command { + interface Dao { /** - * ErrOrStderr returns output to stderr + * FindExternalAuthByProvider returns the first available + * ExternalAuth model for the specified provider and providerId. */ - errOrStderr(): io.Writer + findExternalAuthByProvider(provider: string): (models.ExternalAuth | undefined) } - interface Command { + interface Dao { /** - * InOrStdin returns input to stdin + * FindExternalAuthByRecordAndProvider returns the first available + * ExternalAuth model for the specified record data and provider. */ - inOrStdin(): io.Reader + findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) } - interface Command { + interface Dao { /** - * UsageFunc returns either the function set by SetUsageFunc for this command - * or a parent, or it returns a default usage function. + * SaveExternalAuth upserts the provided ExternalAuth model. */ - usageFunc(): (_arg0: Command) => void + saveExternalAuth(model: models.ExternalAuth): void } - interface Command { + interface Dao { /** - * Usage puts out the usage for the command. - * Used when a user provides invalid input. - * Can be defined by user by overriding UsageFunc. + * DeleteExternalAuth deletes the provided ExternalAuth model. */ - usage(): void + deleteExternalAuth(model: models.ExternalAuth): void } - interface Command { + interface Dao { /** - * HelpFunc returns either the function set by SetHelpFunc for this command - * or a parent, or it returns a function with default help behavior. + * ParamQuery returns a new Param select query. */ - helpFunc(): (_arg0: Command, _arg1: Array) => void + paramQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * Help puts out the help for the command. - * Used when a user calls help [command]. - * Can be defined by user by overriding HelpFunc. + * FindParamByKey finds the first Param model with the provided key. */ - help(): void + findParamByKey(key: string): (models.Param | undefined) } - interface Command { + interface Dao { /** - * UsageString returns usage string. + * SaveParam creates or updates a Param model by the provided key-value pair. + * The value argument will be encoded as json string. + * + * If `optEncryptionKey` is provided it will encrypt the value before storing it. */ - usageString(): string + saveParam(key: string, value: any, ...optEncryptionKey: string[]): void } - interface Command { + interface Dao { /** - * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this - * command or a parent, or it returns a function which returns the original - * error. + * DeleteParam deletes the provided Param model. */ - flagErrorFunc(): (_arg0: Command, _arg1: Error) => void + deleteParam(param: models.Param): void } - interface Command { + interface Dao { /** - * UsagePadding return padding for the usage. + * RecordQuery returns a new Record select query from a collection model, id or name. + * + * In case a collection id or name is provided and that collection doesn't + * actually exists, the generated query will be created with a cancelled context + * and will fail once an executor (Row(), One(), All(), etc.) is called. */ - usagePadding(): number + recordQuery(collectionModelOrIdentifier: any): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * CommandPathPadding return padding for the command path. + * FindRecordById finds the Record model by its id. */ - commandPathPadding(): number + findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) } - interface Command { + interface Dao { /** - * NamePadding returns padding for the name. + * FindRecordsByIds finds all Record models by the provided ids. + * If no records are found, returns an empty slice. */ - namePadding(): number + findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * UsageTemplate returns usage template for the command. + * @todo consider to depricate as it may be easier to just use dao.RecordQuery() + * + * FindRecordsByExpr finds all records by the specified db expression. + * + * Returns all collection records if no expressions are provided. + * + * Returns an empty slice if no records are found. + * + * Example: + * + * ``` + * expr1 := dbx.HashExp{"email": "test@example.com"} + * expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) + * dao.FindRecordsByExpr("example", expr1, expr2) + * ``` */ - usageTemplate(): string + findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * HelpTemplate return help template for the command. + * FindFirstRecordByData returns the first found record matching + * the provided key-value pair. */ - helpTemplate(): string + findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) } - interface Command { + interface Dao { /** - * VersionTemplate return version template for the command. + * FindRecordsByFilter returns limit number of records matching the + * provided string filter. + * + * The sort argument is optional and can be empty string OR the same format + * used in the web APIs, eg. "-created,title". + * + * If the limit argument is <= 0, no limit is applied to the query and + * all matching records are returned. + * + * NB! Don't put untrusted user input in the filter string as it + * practically would allow the users to inject their own custom filter. + * + * Example: + * + * ``` + * dao.FindRecordsByFilter("posts", "title ~ 'lorem ipsum' && visible = true", "-created", 10) + * ``` */ - versionTemplate(): string + findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> } - interface Command { + interface Dao { /** - * Find the target command given the args and command tree - * Meant to be run on the highest node. Only searches down. + * FindFirstRecordByFilter returns the first available record matching the provided filter. + * + * NB! Don't put untrusted user input in the filter string as it + * practically would allow the users to inject their own custom filter. + * + * Example: + * + * ``` + * dao.FindFirstRecordByFilter("posts", "slug='test'") + * ``` */ - find(args: Array): [(Command | undefined), Array] + findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * Traverse the command tree to find the command, and parse args for - * each parent. + * IsRecordValueUnique checks if the provided key-value pair is a unique Record value. + * + * For correctness, if the collection is "auth" and the key is "username", + * the unique check will be case insensitive. + * + * NB! Array values (eg. from multiple select fields) are matched + * as a serialized json strings (eg. `["a","b"]`), so the value uniqueness + * depends on the elements order. Or in other words the following values + * are considered different: `[]string{"a","b"}` and `[]string{"b","a"}` */ - traverse(args: Array): [(Command | undefined), Array] + isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean } - interface Command { + interface Dao { /** - * SuggestionsFor provides suggestions for the typedName. + * FindAuthRecordByToken finds the auth record associated with the provided JWT token. + * + * Returns an error if the JWT token is invalid, expired or not associated to an auth collection record. */ - suggestionsFor(typedName: string): Array + findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * VisitParents visits all parents of the command and invokes fn on each parent. + * FindAuthRecordByEmail finds the auth record associated with the provided email. + * + * Returns an error if it is not an auth collection or the record is not found. */ - visitParents(fn: (_arg0: Command) => void): void + findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * Root finds root command. + * FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive). + * + * Returns an error if it is not an auth collection or the record is not found. */ - root(): (Command | undefined) + findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) } - interface Command { + interface Dao { /** - * ArgsLenAtDash will return the length of c.Flags().Args at the moment - * when a -- was found during args parsing. + * SuggestUniqueAuthRecordUsername checks if the provided username is unique + * and return a new "unique" username with appended random numeric part + * (eg. "existingName" -> "existingName583"). + * + * The same username will be returned if the provided string is already unique. */ - argsLenAtDash(): number + suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string } - interface Command { + interface Dao { /** - * ExecuteContext is the same as Execute(), but sets the ctx on the command. - * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs - * functions. + * CanAccessRecord checks if a record is allowed to be accessed by the + * specified requestInfo and accessRule. + * + * Rule and db checks are ignored in case requestInfo.Admin is set. + * + * The returned error indicate that something unexpected happened during + * the check (eg. invalid rule or db error). + * + * The method always return false on invalid access rule or db error. + * + * Example: + * + * ``` + * requestInfo := apis.RequestInfo(c /* echo.Context *\/) + * record, _ := dao.FindRecordById("example", "RECORD_ID") + * rule := types.Pointer("@request.auth.id != '' || status = 'public'") + * // ... or use one of the record collection's rule, eg. record.Collection().ViewRule + * + * if ok, _ := dao.CanAccessRecord(record, requestInfo, rule); ok { ... } + * ``` */ - executeContext(ctx: context.Context): void + canAccessRecord(record: models.Record, requestInfo: models.RequestInfo, accessRule: string): boolean } - interface Command { + interface Dao { /** - * Execute uses the args (os.Args[1:] by default) - * and run through the command tree finding appropriate matches - * for commands and then corresponding flags. + * SaveRecord persists the provided Record model in the database. + * + * If record.IsNew() is true, the method will perform a create, otherwise an update. + * To explicitly mark a record for update you can use record.MarkAsNotNew(). */ - execute(): void + saveRecord(record: models.Record): void } - interface Command { + interface Dao { /** - * ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. - * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs - * functions. + * DeleteRecord deletes the provided Record model. + * + * This method will also cascade the delete operation to all linked + * relational records (delete or unset, depending on the rel settings). + * + * The delete operation may fail if the record is part of a required + * reference in another record (aka. cannot be deleted or unset). */ - executeContextC(ctx: context.Context): (Command | undefined) + deleteRecord(record: models.Record): void } - interface Command { + interface Dao { /** - * ExecuteC executes the command. + * ExpandRecord expands the relations of a single Record model. + * + * If fetchFunc is not set, then a default function will be used that + * returns all relation records. + * + * Returns a map with the failed expand parameters and their errors. */ - executeC(): (Command | undefined) - } - interface Command { - validateArgs(args: Array): void + expandRecord(record: models.Record, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict } - interface Command { + interface Dao { /** - * ValidateRequiredFlags validates all required flags are present and returns an error otherwise + * ExpandRecords expands the relations of the provided Record models list. + * + * If fetchFunc is not set, then a default function will be used that + * returns all relation records. + * + * Returns a map with the failed expand parameters and their errors. */ - validateRequiredFlags(): void + expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict } - interface Command { + // @ts-ignore + import validation = ozzo_validation + interface Dao { /** - * InitDefaultHelpFlag adds default help flag to c. - * It is called automatically by executing the c or by calling help and usage. - * If c already has help flag, it will do nothing. + * SyncRecordTableSchema compares the two provided collections + * and applies the necessary related record table changes. + * + * If `oldCollection` is null, then only `newCollection` is used to create the record table. */ - initDefaultHelpFlag(): void + syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void } - interface Command { + interface Dao { /** - * InitDefaultVersionFlag adds default version flag to c. - * It is called automatically by executing the c. - * If c already has a version flag, it will do nothing. - * If c.Version is empty, it will do nothing. + * RequestQuery returns a new Request logs select query. */ - initDefaultVersionFlag(): void + requestQuery(): (dbx.SelectQuery | undefined) } - interface Command { + interface Dao { /** - * 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. + * FindRequestById finds a single Request log by its id. */ - initDefaultHelpCmd(): void + findRequestById(id: string): (models.Request | undefined) } - interface Command { + interface Dao { /** - * ResetCommands delete parent, subcommand and help command from c. + * RequestsStats returns hourly grouped requests logs statistics. */ - resetCommands(): void + requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> } - interface Command { + interface Dao { /** - * Commands returns a sorted slice of child commands. + * DeleteOldRequests delete all requests that are created before createdBefore. */ - commands(): Array<(Command | undefined)> + deleteOldRequests(createdBefore: time.Time): void } - interface Command { + interface Dao { /** - * AddCommand adds one or more commands to this parent command. + * SaveRequest upserts the provided Request model. */ - addCommand(...cmds: (Command | undefined)[]): void + saveRequest(request: models.Request): void } - interface Command { + interface Dao { /** - * Groups returns a slice of child command groups. + * FindSettings returns and decode the serialized app settings param value. + * + * The method will first try to decode the param value without decryption. + * If it fails and optEncryptionKey is set, it will try again by first + * decrypting the value and then decode it again. + * + * Returns an error if it fails to decode the stored serialized param value. */ - groups(): Array<(Group | undefined)> + findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) } - interface Command { + interface Dao { /** - * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group + * SaveSettings persists the specified settings configuration. + * + * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. */ - allChildCommandsHaveGroup(): boolean + saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void } - interface Command { + interface Dao { /** - * ContainsGroup return if groupID exists in the list of command groups. + * HasTable checks if a table (or view) with the provided name exists (case insensitive). */ - containsGroup(groupID: string): boolean + hasTable(tableName: string): boolean } - interface Command { + interface Dao { /** - * AddGroup adds one or more command groups to this parent command. + * TableColumns returns all column names of a single table by its name. */ - addGroup(...groups: (Group | undefined)[]): void + tableColumns(tableName: string): Array } - interface Command { + interface Dao { /** - * RemoveCommand removes one or more commands from a parent command. + * TableInfo returns the `table_info` pragma result for the specified table. */ - removeCommand(...cmds: (Command | undefined)[]): void + tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> } - interface Command { + interface Dao { /** - * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. + * TableIndexes returns a name grouped map with all non empty index of the specified table. + * + * Note: This method doesn't return an error on nonexisting table. */ - print(...i: { - }[]): void + tableIndexes(tableName: string): _TygojaDict } - interface Command { + interface Dao { /** - * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. + * DeleteTable drops the specified table. + * + * This method is a no-op if a table with the provided name doesn't exist. + * + * Be aware that this method is vulnerable to SQL injection and the + * "tableName" argument must come only from trusted input! */ - println(...i: { - }[]): void + deleteTable(tableName: string): void } - interface Command { + interface Dao { /** - * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. + * Vacuum executes VACUUM on the current dao.DB() instance in order to + * reclaim unused db disk space. */ - printf(format: string, ...i: { - }[]): void + vacuum(): void } - interface Command { + interface Dao { /** - * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. + * DeleteView drops the specified view name. + * + * This method is a no-op if a view with the provided name doesn't exist. + * + * Be aware that this method is vulnerable to SQL injection and the + * "name" argument must come only from trusted input! */ - printErr(...i: { - }[]): void + deleteView(name: string): void } - interface Command { + interface Dao { /** - * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. + * SaveView creates (or updates already existing) persistent SQL view. + * + * Be aware that this method is vulnerable to SQL injection and the + * "selectQuery" argument must come only from trusted input! */ - printErrln(...i: { - }[]): void + saveView(name: string, selectQuery: string): void } - interface Command { + interface Dao { /** - * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. + * CreateViewSchema creates a new view schema from the provided select query. + * + * There are some caveats: + * - The select query must have an "id" column. + * - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data. */ - printErrf(format: string, ...i: { - }[]): void + createViewSchema(selectQuery: string): schema.Schema } - interface Command { + interface Dao { /** - * CommandPath returns the full path to this command. + * FindRecordByViewFile returns the original models.Record of the + * provided view collection file. */ - commandPath(): string + findRecordByViewFile(viewCollectionNameOrId: string, fileFieldName: string, filename: string): (models.Record | undefined) } - interface Command { +} + +/** + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + /** + * App defines the main PocketBase app interface. + */ + interface App { /** - * UseLine puts out the full usage for a given command (including parents). + * Deprecated: + * This method may get removed in the near future. + * It is recommended to access the app db instance from app.Dao().DB() or + * if you want more flexibility - app.Dao().ConcurrentDB() and app.Dao().NonconcurrentDB(). + * + * DB returns the default app database instance. */ - useLine(): string - } - interface Command { + db(): (dbx.DB | undefined) /** - * DebugFlags used to determine which flags have been assigned to which commands - * and which persist. + * Dao returns the default app Dao instance. + * + * This Dao could operate only on the tables and models + * associated with the default app database. For example, + * trying to access the request logs table will result in error. */ - debugFlags(): void - } - interface Command { + dao(): (daos.Dao | undefined) /** - * Name returns the command's name: the first word in the use line. + * Deprecated: + * This method may get removed in the near future. + * It is recommended to access the logs db instance from app.LogsDao().DB() or + * if you want more flexibility - app.LogsDao().ConcurrentDB() and app.LogsDao().NonconcurrentDB(). + * + * LogsDB returns the app logs database instance. */ - name(): string - } - interface Command { + logsDB(): (dbx.DB | undefined) /** - * HasAlias determines if a given string is an alias of the command. + * LogsDao returns the app logs Dao instance. + * + * This Dao could operate only on the tables and models + * associated with the logs database. For example, trying to access + * the users table from LogsDao will result in error. */ - hasAlias(s: string): boolean - } - interface Command { + logsDao(): (daos.Dao | undefined) /** - * 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. + * DataDir returns the app data directory path. */ - calledAs(): string - } - interface Command { + dataDir(): string /** - * NameAndAliases returns a list of the command name and all aliases + * EncryptionEnv returns the name of the app secret env key + * (used for settings encryption). */ - nameAndAliases(): string - } - interface Command { + encryptionEnv(): string /** - * HasExample determines if the command has example. + * IsDebug returns whether the app is in debug mode + * (showing more detailed error logs, executed sql statements, etc.). */ - hasExample(): boolean - } - interface Command { + isDebug(): boolean /** - * Runnable determines if the command is itself runnable. + * Settings returns the loaded app settings. */ - runnable(): boolean - } - interface Command { + settings(): (settings.Settings | undefined) /** - * HasSubCommands determines if the command has children commands. + * Cache returns the app internal cache store. */ - hasSubCommands(): boolean - } - interface Command { + cache(): (store.Store | undefined) /** - * IsAvailableCommand determines if a command is available as a non-help command - * (this includes all non deprecated/hidden commands). + * SubscriptionsBroker returns the app realtime subscriptions broker instance. */ - isAvailableCommand(): boolean - } - interface Command { + subscriptionsBroker(): (subscriptions.Broker | undefined) /** - * IsAdditionalHelpTopicCommand determines if a command is an additional - * help topic command; additional help topic command is determined by the - * fact that it is NOT runnable/hidden/deprecated, and has no sub commands that - * are runnable/hidden/deprecated. - * Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. + * NewMailClient creates and returns a configured app mail client. */ - isAdditionalHelpTopicCommand(): boolean - } - interface Command { + newMailClient(): mailer.Mailer /** - * 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'. + * NewFilesystem creates and returns a configured filesystem.System instance + * for managing regular app files (eg. collection uploads). + * + * NB! Make sure to call Close() on the returned result + * after you are done working with it. */ - hasHelpSubCommands(): boolean - } - interface Command { + newFilesystem(): (filesystem.System | undefined) /** - * HasAvailableSubCommands determines if a command has available sub commands that - * need to be shown in the usage/help default template under 'available commands'. + * NewBackupsFilesystem creates and returns a configured filesystem.System instance + * for managing app backups. + * + * NB! Make sure to call Close() on the returned result + * after you are done working with it. */ - hasAvailableSubCommands(): boolean - } - interface Command { + newBackupsFilesystem(): (filesystem.System | undefined) /** - * HasParent determines if the command is a child command. + * RefreshSettings reinitializes and reloads the stored application settings. */ - hasParent(): boolean - } - interface Command { + refreshSettings(): void /** - * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. + * IsBootstrapped checks if the application was initialized + * (aka. whether Bootstrap() was called). */ - globalNormalizationFunc(): (f: flag.FlagSet, name: string) => flag.NormalizedName - } - interface Command { + isBootstrapped(): boolean /** - * Flags returns the complete FlagSet that applies - * to this command (local and persistent declared here and by all parents). + * Bootstrap takes care for initializing the application + * (open db connections, load settings, etc.). + * + * It will call ResetBootstrapState() if the application was already bootstrapped. */ - flags(): (flag.FlagSet | undefined) - } - interface Command { + bootstrap(): void /** - * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. + * ResetBootstrapState takes care for releasing initialized app resources + * (eg. closing db connections). */ - localNonPersistentFlags(): (flag.FlagSet | undefined) - } - interface Command { + resetBootstrapState(): void /** - * LocalFlags returns the local FlagSet specifically set in the current command. + * CreateBackup creates a new backup of the current app pb_data directory. + * + * Backups can be stored on S3 if it is configured in app.Settings().Backups. + * + * Please refer to the godoc of the specific core.App implementation + * for details on the backup procedures. */ - localFlags(): (flag.FlagSet | undefined) - } - interface Command { + createBackup(ctx: context.Context, name: string): void /** - * InheritedFlags returns all flags which were inherited from parent commands. + * RestoreBackup restores the backup with the specified name and restarts + * the current running application process. + * + * The safely perform the restore it is recommended to have free disk space + * for at least 2x the size of the restored pb_data backup. + * + * Please refer to the godoc of the specific core.App implementation + * for details on the restore procedures. + * + * NB! This feature is experimental and currently is expected to work only on UNIX based systems. */ - inheritedFlags(): (flag.FlagSet | undefined) - } - interface Command { + restoreBackup(ctx: context.Context, name: string): void /** - * NonInheritedFlags returns all flags which were not inherited from parent commands. + * Restart restarts the current running application process. + * + * Currently it is relying on execve so it is supported only on UNIX based systems. */ - nonInheritedFlags(): (flag.FlagSet | undefined) - } - interface Command { + restart(): void /** - * PersistentFlags returns the persistent FlagSet specifically set in the current command. + * OnBeforeBootstrap hook is triggered before initializing the main + * application resources (eg. before db open and initial settings load). */ - persistentFlags(): (flag.FlagSet | undefined) - } - interface Command { + onBeforeBootstrap(): (hook.Hook | undefined) /** - * ResetFlags deletes all flags from command. + * OnAfterBootstrap hook is triggered after initializing the main + * application resources (eg. after db open and initial settings load). */ - resetFlags(): void - } - interface Command { + onAfterBootstrap(): (hook.Hook | undefined) /** - * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). + * OnBeforeServe hook is triggered before serving the internal router (echo), + * allowing you to adjust its options and attach new routes or middlewares. */ - hasFlags(): boolean - } - interface Command { + onBeforeServe(): (hook.Hook | undefined) /** - * HasPersistentFlags checks if the command contains persistent flags. + * OnBeforeApiError hook is triggered right before sending an error API + * response to the client, allowing you to further modify the error data + * or to return a completely different API response. */ - hasPersistentFlags(): boolean - } - interface Command { + onBeforeApiError(): (hook.Hook | undefined) /** - * HasLocalFlags checks if the command has flags specifically declared locally. + * OnAfterApiError hook is triggered right after sending an error API + * response to the client. + * It could be used to log the final API error in external services. */ - hasLocalFlags(): boolean - } - interface Command { + onAfterApiError(): (hook.Hook | undefined) /** - * HasInheritedFlags checks if the command has flags inherited from its parent command. + * OnTerminate hook is triggered when the app is in the process + * of being terminated (eg. on SIGTERM signal). */ - hasInheritedFlags(): boolean - } - interface Command { + onTerminate(): (hook.Hook | undefined) /** - * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire - * structure) which are not hidden or deprecated. + * OnModelBeforeCreate hook is triggered before inserting a new + * model in the DB, allowing you to modify or validate the stored data. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - hasAvailableFlags(): boolean - } - interface Command { + onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. + * OnModelAfterCreate hook is triggered after successfully + * inserting a new model in the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - hasAvailablePersistentFlags(): boolean - } - interface Command { + onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden - * or deprecated. + * OnModelBeforeUpdate hook is triggered before updating existing + * model in the DB, allowing you to modify or validate the stored data. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - hasAvailableLocalFlags(): boolean - } - interface Command { + onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) /** - * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are - * not hidden or deprecated. + * OnModelAfterUpdate hook is triggered after successfully updating + * existing model in the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - hasAvailableInheritedFlags(): boolean - } - interface Command { + onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) /** - * Flag climbs up the command tree looking for matching flag. + * OnModelBeforeDelete hook is triggered before deleting an + * existing model from the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - flag(name: string): (flag.Flag | undefined) - } - interface Command { + onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) /** - * ParseFlags parses persistent flag tree and local flags. + * OnModelAfterDelete hook is triggered after successfully deleting an + * existing model from the DB. + * + * If the optional "tags" list (table names and/or the Collection id for Record models) + * is specified, then all event handlers registered via the created hook + * will be triggered and called only if their event data origin matches the tags. */ - parseFlags(args: Array): void - } - interface Command { + onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) /** - * Parent returns a commands parent command. + * OnMailerBeforeAdminResetPasswordSend hook is triggered right + * before sending a password reset email to an admin, allowing you + * to inspect and customize the email message that is being sent. */ - parent(): (Command | undefined) - } - interface Command { + onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) /** - * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. + * OnMailerAfterAdminResetPasswordSend hook is triggered after + * admin password reset email was successfully sent. */ - registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void - } - interface Command { + onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) /** - * InitDefaultCompletionCmd adds a default 'completion' command to c. - * This function will do nothing if any of the following is true: - * 1- the feature has been explicitly disabled by the program, - * 2- c has no subcommands (to avoid creating one), - * 3- c already has a 'completion' command provided by the program. + * OnMailerBeforeRecordResetPasswordSend hook is triggered right + * before sending a password reset email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - initDefaultCompletionCmd(): void - } - interface Command { + onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenFishCompletion generates fish completion file and writes to the passed writer. + * OnMailerAfterRecordResetPasswordSend hook is triggered after + * an auth record password reset email was successfully sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - genFishCompletion(w: io.Writer, includeDesc: boolean): void - } - interface Command { + onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenFishCompletionFile generates fish completion file. + * OnMailerBeforeRecordVerificationSend hook is triggered right + * before sending a verification email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - genFishCompletionFile(filename: string, includeDesc: boolean): void - } - interface Command { + onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors - * if the command is invoked with a subset (but not all) of the given flags. + * OnMailerAfterRecordVerificationSend hook is triggered after a + * verification email was successfully sent to an auth record. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - markFlagsRequiredTogether(...flagNames: string[]): void - } - interface Command { + onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors - * if the command is invoked with more than one flag from the given set of flags. + * OnMailerBeforeRecordChangeEmailSend hook is triggered right before + * sending a confirmation new address email to an auth record, allowing + * you to inspect and customize the email message that is being sent. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - markFlagsMutuallyExclusive(...flagNames: string[]): void - } - interface Command { + onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the - * first error encountered. + * OnMailerAfterRecordChangeEmailSend hook is triggered after a + * verification email was successfully sent to an auth record. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - validateFlagGroups(): void - } - interface Command { + onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenPowerShellCompletionFile generates powershell completion file without descriptions. + * OnRealtimeConnectRequest hook is triggered right before establishing + * the SSE client connection. */ - genPowerShellCompletionFile(filename: string): void - } - interface Command { + onRealtimeConnectRequest(): (hook.Hook | undefined) /** - * GenPowerShellCompletion generates powershell completion file without descriptions - * and writes it to the passed writer. + * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted + * SSE client connection. */ - genPowerShellCompletion(w: io.Writer): void - } - interface Command { + onRealtimeDisconnectRequest(): (hook.Hook | undefined) /** - * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. + * OnRealtimeBeforeMessage hook is triggered right before sending + * an SSE message to a client. + * + * Returning [hook.StopPropagation] will prevent sending the message. + * Returning any other non-nil error will close the realtime connection. */ - genPowerShellCompletionFileWithDesc(filename: string): void - } - interface Command { + onRealtimeBeforeMessageSend(): (hook.Hook | undefined) /** - * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions - * and writes it to the passed writer. + * OnRealtimeBeforeMessage hook is triggered right after sending + * an SSE message to a client. */ - genPowerShellCompletionWithDesc(w: io.Writer): void - } - interface Command { + onRealtimeAfterMessageSend(): (hook.Hook | undefined) /** - * MarkFlagRequired instructs the various shell completion implementations to - * prioritize the named flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * OnRealtimeBeforeSubscribeRequest hook is triggered before changing + * the client subscriptions, allowing you to further validate and + * modify the submitted change. */ - markFlagRequired(name: string): void - } - interface Command { + onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) /** - * MarkPersistentFlagRequired instructs the various shell completion implementations to - * prioritize the named persistent flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * OnRealtimeAfterSubscribeRequest hook is triggered after the client + * subscriptions were successfully changed. */ - markPersistentFlagRequired(name: string): void - } - interface Command { + onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) /** - * MarkFlagFilename instructs the various shell completion implementations to - * limit completions for the named flag to the specified file extensions. + * OnSettingsListRequest hook is triggered on each successful + * API Settings list request. + * + * Could be used to validate or modify the response before + * returning it to the client. */ - markFlagFilename(name: string, ...extensions: string[]): void - } - interface Command { + onSettingsListRequest(): (hook.Hook | undefined) /** - * MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. - * The bash completion script will call the bash function f for the flag. + * OnSettingsBeforeUpdateRequest hook is triggered before each API + * Settings update request (after request data load and before settings persistence). * - * This will only work for bash completion. - * It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows - * to register a Go function which will work across all shells. + * Could be used to additionally validate the request data or + * implement completely different persistence behavior. */ - markFlagCustom(name: string, f: string): void - } - interface Command { + onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) /** - * MarkPersistentFlagFilename instructs the various shell completion - * implementations to limit completions for the named persistent flag to the - * specified file extensions. + * OnSettingsAfterUpdateRequest hook is triggered after each + * successful API Settings update request. */ - markPersistentFlagFilename(name: string, ...extensions: string[]): void - } - interface Command { + onSettingsAfterUpdateRequest(): (hook.Hook | undefined) /** - * MarkFlagDirname instructs the various shell completion implementations to - * limit completions for the named flag to directory names. + * OnFileDownloadRequest hook is triggered before each API File download request. + * + * Could be used to validate or modify the file response before + * returning it to the client. */ - markFlagDirname(name: string): void - } - interface Command { + onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * MarkPersistentFlagDirname instructs the various shell completion - * implementations to limit completions for the named persistent flag to - * directory names. + * OnFileBeforeTokenRequest hook is triggered before each file + * token API request. + * + * If no token or model was submitted, e.Model and e.Token will be empty, + * allowing you to implement your own custom model file auth implementation. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - markPersistentFlagDirname(name: string): void - } - interface Command { + onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenZshCompletionFile generates zsh completion file including descriptions. + * OnFileAfterTokenRequest hook is triggered after each + * successful file token API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - genZshCompletionFile(filename: string): void - } - interface Command { + onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * GenZshCompletion generates zsh completion file including descriptions - * and writes it to the passed writer. + * OnAdminsListRequest hook is triggered on each API Admins list request. + * + * Could be used to validate or modify the response before returning it to the client. */ - genZshCompletion(w: io.Writer): void - } - interface Command { + onAdminsListRequest(): (hook.Hook | undefined) /** - * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + * OnAdminViewRequest hook is triggered on each API Admin view request. + * + * Could be used to validate or modify the response before returning it to the client. */ - genZshCompletionFileNoDesc(filename: string): void - } - interface Command { + onAdminViewRequest(): (hook.Hook | undefined) /** - * GenZshCompletionNoDesc generates zsh completion file without descriptions - * and writes it to the passed writer. + * OnAdminBeforeCreateRequest hook is triggered before each API + * Admin create request (after request data load and before model persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. */ - genZshCompletionNoDesc(w: io.Writer): void - } - interface Command { + onAdminBeforeCreateRequest(): (hook.Hook | undefined) /** - * MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was - * not consistent with Bash completion. It has therefore been disabled. - * Instead, when no other completion is specified, file completion is done by - * default for every argument. One can disable file completion on a per-argument - * basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. - * To achieve file extension filtering, one can use ValidArgsFunction and - * ShellCompDirectiveFilterFileExt. - * - * Deprecated + * OnAdminAfterCreateRequest hook is triggered after each + * successful API Admin create request. */ - markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void - } - interface Command { + onAdminAfterCreateRequest(): (hook.Hook | undefined) /** - * MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore - * been disabled. - * To achieve the same behavior across all shells, one can use - * ValidArgs (for the first argument only) or ValidArgsFunction for - * any argument (can include the first one also). + * OnAdminBeforeUpdateRequest hook is triggered before each API + * Admin update request (after request data load and before model persistence). * - * Deprecated + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. */ - markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void - } -} - -/** - * Package daos handles common PocketBase DB model manipulations. - * - * Think of daos as DB repository and service layer in one. - */ -namespace daos { - interface Dao { + onAdminBeforeUpdateRequest(): (hook.Hook | undefined) /** - * AdminQuery returns a new Admin select query. + * OnAdminAfterUpdateRequest hook is triggered after each + * successful API Admin update request. */ - adminQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + onAdminAfterUpdateRequest(): (hook.Hook | undefined) /** - * FindAdminById finds the admin with the provided id. + * OnAdminBeforeDeleteRequest hook is triggered before each API + * Admin delete request (after model load and before actual deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. */ - findAdminById(id: string): (models.Admin | undefined) - } - interface Dao { + onAdminBeforeDeleteRequest(): (hook.Hook | undefined) /** - * FindAdminByEmail finds the admin with the provided email address. + * OnAdminAfterDeleteRequest hook is triggered after each + * successful API Admin delete request. */ - findAdminByEmail(email: string): (models.Admin | undefined) - } - interface Dao { + onAdminAfterDeleteRequest(): (hook.Hook | undefined) /** - * FindAdminByToken finds the admin associated with the provided JWT token. + * OnAdminAuthRequest hook is triggered on each successful API Admin + * authentication request (sign-in, token refresh, etc.). * - * Returns an error if the JWT token is invalid or expired. + * Could be used to additionally validate or modify the + * authenticated admin data and token. */ - findAdminByToken(token: string, baseTokenKey: string): (models.Admin | undefined) - } - interface Dao { + onAdminAuthRequest(): (hook.Hook | undefined) /** - * TotalAdmins returns the number of existing admin records. + * OnAdminBeforeAuthWithPasswordRequest hook is triggered before each Admin + * auth with password API request (after request data load and before password validation). + * + * Could be used to implement for example a custom password validation + * or to locate a different Admin identity (by assigning [AdminAuthWithPasswordEvent.Admin]). */ - totalAdmins(): number - } - interface Dao { + onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) /** - * IsAdminEmailUnique checks if the provided email address is not - * already in use by other admins. + * OnAdminAfterAuthWithPasswordRequest hook is triggered after each + * successful Admin auth with password API request. */ - isAdminEmailUnique(email: string, ...excludeIds: string[]): boolean - } - interface Dao { + onAdminAfterAuthWithPasswordRequest(): (hook.Hook | undefined) /** - * DeleteAdmin deletes the provided Admin model. + * OnAdminBeforeAuthRefreshRequest hook is triggered before each Admin + * auth refresh API request (right before generating a new auth token). * - * Returns an error if there is only 1 admin. - */ - deleteAdmin(admin: models.Admin): void - } - interface Dao { - /** - * SaveAdmin upserts the provided Admin model. + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. */ - saveAdmin(admin: models.Admin): void - } - /** - * Dao handles various db operations. - * - * You can think of Dao as a repository and service layer in one. - */ - interface Dao { + onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) /** - * MaxLockRetries specifies the default max "database is locked" auto retry attempts. + * OnAdminAfterAuthRefreshRequest hook is triggered after each + * successful auth refresh API request (right after generating a new auth token). */ - maxLockRetries: number + onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) /** - * ModelQueryTimeout is the default max duration of a running ModelQuery(). + * OnAdminBeforeRequestPasswordResetRequest hook is triggered before each Admin + * request password reset API request (after request data load and before sending the reset email). * - * This field has no effect if an explicit query context is already specified. + * Could be used to additionally validate the request data or implement + * completely different password reset behavior. */ - modelQueryTimeout: time.Duration + onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) /** - * write hooks + * OnAdminAfterRequestPasswordResetRequest hook is triggered after each + * successful request password reset API request. */ - beforeCreateFunc: (eventDao: Dao, m: models.Model) => void - afterCreateFunc: (eventDao: Dao, m: models.Model) => void - beforeUpdateFunc: (eventDao: Dao, m: models.Model) => void - afterUpdateFunc: (eventDao: Dao, m: models.Model) => void - beforeDeleteFunc: (eventDao: Dao, m: models.Model) => void - afterDeleteFunc: (eventDao: Dao, m: models.Model) => void - } - interface Dao { + onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) /** - * DB returns the default dao db builder (*dbx.DB or *dbx.TX). + * OnAdminBeforeConfirmPasswordResetRequest hook is triggered before each Admin + * confirm password reset API request (after request data load and before persistence). * - * Currently the default db builder is dao.concurrentDB but that may change in the future. + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. */ - db(): dbx.Builder - } - interface Dao { + onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) /** - * ConcurrentDB returns the dao concurrent (aka. multiple open connections) - * db builder (*dbx.DB or *dbx.TX). - * - * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. + * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each + * successful confirm password reset API request. */ - concurrentDB(): dbx.Builder - } - interface Dao { + onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) /** - * NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) - * db builder (*dbx.DB or *dbx.TX). + * OnRecordAuthRequest hook is triggered on each successful API + * record authentication request (sign-in, token refresh, etc.). * - * In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance. + * Could be used to additionally validate or modify the authenticated + * record data and token. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - nonconcurrentDB(): dbx.Builder - } - interface Dao { + onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Clone returns a new Dao with the same configuration options as the current one. + * OnRecordBeforeAuthWithPasswordRequest hook is triggered before each Record + * auth with password API request (after request data load and before password validation). + * + * Could be used to implement for example a custom password validation + * or to locate a different Record model (by reassigning [RecordAuthWithPasswordEvent.Record]). + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - clone(): (Dao | undefined) - } - interface Dao { + onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * WithoutHooks returns a new Dao with the same configuration options - * as the current one, but without create/update/delete hooks. + * OnRecordAfterAuthWithPasswordRequest hook is triggered after each + * successful Record auth with password API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - withoutHooks(): (Dao | undefined) - } - interface Dao { + onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * ModelQuery creates a new preconfigured select query with preset - * SELECT, FROM and other common fields based on the provided model. + * OnRecordBeforeAuthWithOAuth2Request hook is triggered before each Record + * OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). + * + * If the [RecordAuthWithOAuth2Event.Record] is not set, then the OAuth2 + * request will try to create a new auth Record. + * + * To assign or link a different existing record model you can + * change the [RecordAuthWithOAuth2Event.Record] field. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - modelQuery(m: models.Model): (dbx.SelectQuery | undefined) - } - interface Dao { + onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindById finds a single db record with the specified id and - * scans the result into m. + * OnRecordAfterAuthWithOAuth2Request hook is triggered after each + * successful Record OAuth2 API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findById(m: models.Model, id: string): void - } - interface Dao { + onRecordAfterAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) /** - * RunInTransaction wraps fn into a transaction. + * OnRecordBeforeAuthRefreshRequest hook is triggered before each Record + * auth refresh API request (right before generating a new auth token). * - * It is safe to nest RunInTransaction calls as long as you use the txDao. + * Could be used to additionally validate the request data or implement + * completely different auth refresh behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - runInTransaction(fn: (txDao: Dao) => void): void - } - interface Dao { + onRecordBeforeAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Delete deletes the provided model. + * OnRecordAfterAuthRefreshRequest hook is triggered after each + * successful auth refresh API request (right after generating a new auth token). + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - delete(m: models.Model): void - } - interface Dao { + onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * Save persists the provided model in the database. + * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. * - * If m.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a model for update you can use m.MarkAsNotNew(). + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - save(m: models.Model): void - } - interface Dao { + onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * CollectionQuery returns a new Collection select query. + * OnRecordBeforeUnlinkExternalAuthRequest hook is triggered before each API record + * external auth unlink request (after models load and before the actual relation deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - collectionQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindCollectionsByType finds all collections by the given type. + * OnRecordAfterUnlinkExternalAuthRequest hook is triggered after each + * successful API record external auth unlink request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findCollectionsByType(collectionType: string): Array<(models.Collection | undefined)> - } - interface Dao { + onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id. + * OnRecordBeforeRequestPasswordResetRequest hook is triggered before each Record + * request password reset API request (after request data load and before sending the reset email). + * + * Could be used to additionally validate the request data or implement + * completely different password reset behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findCollectionByNameOrId(nameOrId: string): (models.Collection | undefined) - } - interface Dao { + onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * IsCollectionNameUnique checks that there is no existing collection - * with the provided name (case insensitive!). + * OnRecordAfterRequestPasswordResetRequest hook is triggered after each + * successful request password reset API request. * - * Note: case insensitive check because the name is used also as a table name for the records. + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - isCollectionNameUnique(name: string, ...excludeIds: string[]): boolean - } - interface Dao { + onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindCollectionReferences returns information for all - * relation schema fields referencing the provided collection. + * OnRecordBeforeConfirmPasswordResetRequest hook is triggered before each Record + * confirm password reset API request (after request data load and before persistence). * - * If the provided collection has reference to itself then it will be - * also included in the result. To exclude it, pass the collection id - * as the excludeId argument. + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findCollectionReferences(collection: models.Collection, ...excludeIds: string[]): _TygojaDict - } - interface Dao { + onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * DeleteCollection deletes the provided Collection model. - * This method automatically deletes the related collection records table. + * OnRecordAfterConfirmPasswordResetRequest hook is triggered after each + * successful confirm password reset API request. * - * NB! The collection cannot be deleted, if: - * - is system collection (aka. collection.System is true) - * - is referenced as part of a relation field in another collection + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - deleteCollection(collection: models.Collection): void - } - interface Dao { + onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * SaveCollection persists the provided Collection model and updates - * its related records table schema. + * OnRecordBeforeRequestVerificationRequest hook is triggered before each Record + * request verification API request (after request data load and before sending the verification email). * - * If collecction.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a collection for update you can use collecction.MarkAsNotNew(). + * Could be used to additionally validate the loaded request data or implement + * completely different verification behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - saveCollection(collection: models.Collection): void - } - interface Dao { + onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * ImportCollections imports the provided collections list within a single transaction. - * - * NB1! If deleteMissing is set, all local collections and schema fields, that are not present - * in the imported configuration, WILL BE DELETED (including their related records data). + * OnRecordAfterRequestVerificationRequest hook is triggered after each + * successful request verification API request. * - * NB2! This method doesn't perform validations on the imported collections data! - * If you need validations, use [forms.CollectionsImport]. + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - importCollections(importedCollections: Array<(models.Collection | undefined)>, deleteMissing: boolean, afterSync: (txDao: Dao, mappedImported: _TygojaDict) => void): void - } - interface Dao { + onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * ExternalAuthQuery returns a new ExternalAuth select query. + * OnRecordBeforeConfirmVerificationRequest hook is triggered before each Record + * confirm verification API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - externalAuthQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindAllExternalAuthsByRecord returns all ExternalAuth models - * linked to the provided auth record. + * OnRecordAfterConfirmVerificationRequest hook is triggered after each + * successful confirm verification API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findAllExternalAuthsByRecord(authRecord: models.Record): Array<(models.ExternalAuth | undefined)> - } - interface Dao { + onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindExternalAuthByProvider returns the first available - * ExternalAuth model for the specified provider and providerId. + * OnRecordBeforeRequestEmailChangeRequest hook is triggered before each Record request email change API request + * (after request data load and before sending the email link to confirm the change). + * + * Could be used to additionally validate the request data or implement + * completely different request email change behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findExternalAuthByProvider(provider: string): (models.ExternalAuth | undefined) - } - interface Dao { + onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindExternalAuthByRecordAndProvider returns the first available - * ExternalAuth model for the specified record data and provider. + * OnRecordAfterRequestEmailChangeRequest hook is triggered after each + * successful request email change API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findExternalAuthByRecordAndProvider(authRecord: models.Record, provider: string): (models.ExternalAuth | undefined) - } - interface Dao { + onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * SaveExternalAuth upserts the provided ExternalAuth model. + * OnRecordBeforeConfirmEmailChangeRequest hook is triggered before each Record + * confirm email change API request (after request data load and before persistence). + * + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - saveExternalAuth(model: models.ExternalAuth): void - } - interface Dao { + onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * DeleteExternalAuth deletes the provided ExternalAuth model. + * OnRecordAfterConfirmEmailChangeRequest hook is triggered after each + * successful confirm email change API request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - deleteExternalAuth(model: models.ExternalAuth): void - } - interface Dao { + onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * ParamQuery returns a new Param select query. + * OnRecordsListRequest hook is triggered on each API Records list request. + * + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - paramQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + onRecordsListRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindParamByKey finds the first Param model with the provided key. + * OnRecordViewRequest hook is triggered on each API Record view request. + * + * Could be used to validate or modify the response before returning it to the client. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findParamByKey(key: string): (models.Param | undefined) - } - interface Dao { + onRecordViewRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * SaveParam creates or updates a Param model by the provided key-value pair. - * The value argument will be encoded as json string. + * OnRecordBeforeCreateRequest hook is triggered before each API Record + * create request (after request data load and before model persistence). * - * If `optEncryptionKey` is provided it will encrypt the value before storing it. + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - saveParam(key: string, value: any, ...optEncryptionKey: string[]): void - } - interface Dao { + onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * DeleteParam deletes the provided Param model. + * OnRecordAfterCreateRequest hook is triggered after each + * successful API Record create request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - deleteParam(param: models.Param): void - } - interface Dao { + onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * RecordQuery returns a new Record select query from a collection model, id or name. + * OnRecordBeforeUpdateRequest hook is triggered before each API Record + * update request (after request data load and before model persistence). * - * In case a collection id or name is provided and that collection doesn't - * actually exists, the generated query will be created with a cancelled context - * and will fail once an executor (Row(), One(), All(), etc.) is called. + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - recordQuery(collectionModelOrIdentifier: any): (dbx.SelectQuery | undefined) - } - interface Dao { + onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindRecordById finds the Record model by its id. + * OnRecordAfterUpdateRequest hook is triggered after each + * successful API Record update request. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findRecordById(collectionNameOrId: string, recordId: string, ...optFilters: ((q: dbx.SelectQuery) => void)[]): (models.Record | undefined) - } - interface Dao { + onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * FindRecordsByIds finds all Record models by the provided ids. - * If no records are found, returns an empty slice. + * OnRecordBeforeDeleteRequest hook is triggered before each API Record + * delete request (after model load and before actual deletion). + * + * Could be used to additionally validate the request data or implement + * completely different delete behavior. + * + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. */ - findRecordsByIds(collectionNameOrId: string, recordIds: Array, ...optFilters: ((q: dbx.SelectQuery) => void)[]): Array<(models.Record | undefined)> - } - interface Dao { + onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) /** - * @todo consider to depricate as it may be easier to just use dao.RecordQuery() - * - * FindRecordsByExpr finds all records by the specified db expression. + * OnRecordAfterDeleteRequest hook is triggered after each + * successful API Record delete request. * - * Returns all collection records if no expressions are provided. + * If the optional "tags" list (Collection ids or names) is specified, + * then all event handlers registered via the created hook will be + * triggered and called only if their event data origin matches the tags. + */ + onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + /** + * OnCollectionsListRequest hook is triggered on each API Collections list request. * - * Returns an empty slice if no records are found. + * Could be used to validate or modify the response before returning it to the client. + */ + onCollectionsListRequest(): (hook.Hook | undefined) + /** + * OnCollectionViewRequest hook is triggered on each API Collection view request. * - * Example: + * Could be used to validate or modify the response before returning it to the client. + */ + onCollectionViewRequest(): (hook.Hook | undefined) + /** + * OnCollectionBeforeCreateRequest hook is triggered before each API Collection + * create request (after request data load and before model persistence). * - * ``` - * expr1 := dbx.HashExp{"email": "test@example.com"} - * expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) - * dao.FindRecordsByExpr("example", expr1, expr2) - * ``` + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. */ - findRecordsByExpr(collectionNameOrId: string, ...exprs: dbx.Expression[]): Array<(models.Record | undefined)> - } - interface Dao { + onCollectionBeforeCreateRequest(): (hook.Hook | undefined) /** - * FindFirstRecordByData returns the first found record matching - * the provided key-value pair. + * OnCollectionAfterCreateRequest hook is triggered after each + * successful API Collection create request. */ - findFirstRecordByData(collectionNameOrId: string, key: string, value: any): (models.Record | undefined) - } - interface Dao { + onCollectionAfterCreateRequest(): (hook.Hook | undefined) /** - * FindRecordsByFilter returns limit number of records matching the - * provided string filter. - * - * The sort argument is optional and can be empty string OR the same format - * used in the web APIs, eg. "-created,title". - * - * If the limit argument is <= 0, no limit is applied to the query and - * all matching records are returned. - * - * NB! Don't put untrusted user input in the filter string as it - * practically would allow the users to inject their own custom filter. - * - * Example: + * OnCollectionBeforeUpdateRequest hook is triggered before each API Collection + * update request (after request data load and before model persistence). * - * ``` - * dao.FindRecordsByFilter("posts", "title ~ 'lorem ipsum' && visible = true", "-created", 10) - * ``` + * Could be used to additionally validate the request data or implement + * completely different persistence behavior. */ - findRecordsByFilter(collectionNameOrId: string, filter: string, sort: string, limit: number): Array<(models.Record | undefined)> - } - interface Dao { + onCollectionBeforeUpdateRequest(): (hook.Hook | undefined) /** - * FindFirstRecordByFilter returns the first available record matching the provided filter. - * - * NB! Don't put untrusted user input in the filter string as it - * practically would allow the users to inject their own custom filter. - * - * Example: - * - * ``` - * dao.FindFirstRecordByFilter("posts", "slug='test'") - * ``` + * OnCollectionAfterUpdateRequest hook is triggered after each + * successful API Collection update request. */ - findFirstRecordByFilter(collectionNameOrId: string, filter: string): (models.Record | undefined) - } - interface Dao { + onCollectionAfterUpdateRequest(): (hook.Hook | undefined) /** - * IsRecordValueUnique checks if the provided key-value pair is a unique Record value. - * - * For correctness, if the collection is "auth" and the key is "username", - * the unique check will be case insensitive. + * OnCollectionBeforeDeleteRequest hook is triggered before each API + * Collection delete request (after model load and before actual deletion). * - * NB! Array values (eg. from multiple select fields) are matched - * as a serialized json strings (eg. `["a","b"]`), so the value uniqueness - * depends on the elements order. Or in other words the following values - * are considered different: `[]string{"a","b"}` and `[]string{"b","a"}` + * Could be used to additionally validate the request data or implement + * completely different delete behavior. */ - isRecordValueUnique(collectionNameOrId: string, key: string, value: any, ...excludeIds: string[]): boolean - } - interface Dao { + onCollectionBeforeDeleteRequest(): (hook.Hook | undefined) /** - * FindAuthRecordByToken finds the auth record associated with the provided JWT token. - * - * Returns an error if the JWT token is invalid, expired or not associated to an auth collection record. + * OnCollectionAfterDeleteRequest hook is triggered after each + * successful API Collection delete request. */ - findAuthRecordByToken(token: string, baseTokenKey: string): (models.Record | undefined) - } - interface Dao { + onCollectionAfterDeleteRequest(): (hook.Hook | undefined) /** - * FindAuthRecordByEmail finds the auth record associated with the provided email. + * OnCollectionsBeforeImportRequest hook is triggered before each API + * collections import request (after request data load and before the actual import). * - * Returns an error if it is not an auth collection or the record is not found. + * Could be used to additionally validate the imported collections or + * to implement completely different import behavior. */ - findAuthRecordByEmail(collectionNameOrId: string, email: string): (models.Record | undefined) - } - interface Dao { + onCollectionsBeforeImportRequest(): (hook.Hook | undefined) /** - * FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive). - * - * Returns an error if it is not an auth collection or the record is not found. + * OnCollectionsAfterImportRequest hook is triggered after each + * successful API collections import request. */ - findAuthRecordByUsername(collectionNameOrId: string, username: string): (models.Record | undefined) + onCollectionsAfterImportRequest(): (hook.Hook | undefined) } - interface Dao { +} + +/** + * 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 { /** - * SuggestUniqueAuthRecordUsername checks if the provided username is unique - * and return a new "unique" username with appended random numeric part - * (eg. "existingName" -> "existingName583"). - * - * The same username will be returned if the provided string is already unique. + * GenBashCompletion generates bash completion file and writes to the passed writer. */ - suggestUniqueAuthRecordUsername(collectionNameOrId: string, baseUsername: string, ...excludeIds: string[]): string + genBashCompletion(w: io.Writer): void } - interface Dao { + interface Command { /** - * CanAccessRecord checks if a record is allowed to be accessed by the - * specified requestInfo and accessRule. - * - * Rule and db checks are ignored in case requestInfo.Admin is set. - * - * The returned error indicate that something unexpected happened during - * the check (eg. invalid rule or db error). - * - * The method always return false on invalid access rule or db error. - * - * Example: - * - * ``` - * requestInfo := apis.RequestInfo(c /* echo.Context *\/) - * record, _ := dao.FindRecordById("example", "RECORD_ID") - * rule := types.Pointer("@request.auth.id != '' || status = 'public'") - * // ... or use one of the record collection's rule, eg. record.Collection().ViewRule - * - * if ok, _ := dao.CanAccessRecord(record, requestInfo, rule); ok { ... } - * ``` + * GenBashCompletionFile generates bash completion file. */ - canAccessRecord(record: models.Record, requestInfo: models.RequestInfo, accessRule: string): boolean + genBashCompletionFile(filename: string): void } - interface Dao { + interface Command { /** - * SaveRecord persists the provided Record model in the database. - * - * If record.IsNew() is true, the method will perform a create, otherwise an update. - * To explicitly mark a record for update you can use record.MarkAsNotNew(). + * GenBashCompletionFileV2 generates Bash completion version 2. */ - saveRecord(record: models.Record): void + genBashCompletionFileV2(filename: string, includeDesc: boolean): void } - interface Dao { + interface Command { /** - * DeleteRecord deletes the provided Record model. - * - * This method will also cascade the delete operation to all linked - * relational records (delete or unset, depending on the rel settings). - * - * The delete operation may fail if the record is part of a required - * reference in another record (aka. cannot be deleted or unset). + * GenBashCompletionV2 generates Bash completion file version 2 + * and writes it to the passed writer. */ - deleteRecord(record: models.Record): void + genBashCompletionV2(w: io.Writer, includeDesc: boolean): void } - interface Dao { + // @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 { /** - * ExpandRecord expands the relations of a single Record model. - * - * If fetchFunc is not set, then a default function will be used that - * returns all relation records. - * - * Returns a map with the failed expand parameters and their errors. + * 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 */ - expandRecord(record: models.Record, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict - } - interface Dao { + use: string /** - * ExpandRecords expands the relations of the provided Record models list. - * - * If fetchFunc is not set, then a default function will be used that - * returns all relation records. - * - * Returns a map with the failed expand parameters and their errors. + * Aliases is an array of aliases that can be used instead of the first word in Use. */ - expandRecords(records: Array<(models.Record | undefined)>, expands: Array, fetchFunc: ExpandFetchFunc): _TygojaDict - } - // @ts-ignore - import validation = ozzo_validation - interface Dao { + aliases: Array /** - * SyncRecordTableSchema compares the two provided collections - * and applies the necessary related record table changes. - * - * If `oldCollection` is null, then only `newCollection` is used to create the record table. + * SuggestFor is an array of command names for which this command will be suggested - + * similar to aliases but only suggests. */ - syncRecordTableSchema(newCollection: models.Collection, oldCollection: models.Collection): void - } - interface Dao { + suggestFor: Array /** - * RequestQuery returns a new Request logs select query. + * Short is the short description shown in the 'help' output. */ - requestQuery(): (dbx.SelectQuery | undefined) - } - interface Dao { + short: string /** - * FindRequestById finds a single Request log by its id. + * The group id under which this subcommand is grouped in the 'help' output of its parent. */ - findRequestById(id: string): (models.Request | undefined) - } - interface Dao { + groupID: string /** - * RequestsStats returns hourly grouped requests logs statistics. + * Long is the long message shown in the 'help ' output. */ - requestsStats(expr: dbx.Expression): Array<(RequestsStatsItem | undefined)> - } - interface Dao { + long: string /** - * DeleteOldRequests delete all requests that are created before createdBefore. + * Example is examples of how to use the command. */ - deleteOldRequests(createdBefore: time.Time): void - } - interface Dao { + example: string /** - * SaveRequest upserts the provided Request model. + * ValidArgs is list of all valid non-flag arguments that are accepted in shell completions */ - saveRequest(request: models.Request): void - } - interface Dao { + validArgs: Array /** - * FindSettings returns and decode the serialized app settings param value. - * - * The method will first try to decode the param value without decryption. - * If it fails and optEncryptionKey is set, it will try again by first - * decrypting the value and then decode it again. - * - * Returns an error if it fails to decode the stored serialized param value. + * 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. */ - findSettings(...optEncryptionKey: string[]): (settings.Settings | undefined) - } - interface Dao { + validArgsFunction: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective] /** - * SaveSettings persists the specified settings configuration. - * - * If optEncryptionKey is set, then the stored serialized value will be encrypted with it. + * Expected arguments */ - saveSettings(newSettings: settings.Settings, ...optEncryptionKey: string[]): void - } - interface Dao { + args: PositionalArgs /** - * HasTable checks if a table (or view) with the provided name exists (case insensitive). + * ArgAliases is List of aliases for ValidArgs. + * These are not suggested to the user in the shell completion, + * but accepted if entered manually. */ - hasTable(tableName: string): boolean - } - interface Dao { - /** - * TableColumns returns all column names of a single table by its name. - */ - tableColumns(tableName: string): Array - } - interface Dao { + argAliases: Array /** - * TableInfo returns the `table_info` pragma result for the specified table. + * BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + * For portability with other shells, it is recommended to instead use ValidArgsFunction */ - tableInfo(tableName: string): Array<(models.TableInfoRow | undefined)> - } - interface Dao { + bashCompletionFunction: string /** - * TableIndexes returns a name grouped map with all non empty index of the specified table. - * - * Note: This method doesn't return an error on nonexisting table. + * Deprecated defines, if this command is deprecated and should print this string when used. */ - tableIndexes(tableName: string): _TygojaDict - } - interface Dao { + deprecated: string /** - * DeleteTable drops the specified table. - * - * This method is a no-op if a table with the provided name doesn't exist. - * - * Be aware that this method is vulnerable to SQL injection and the - * "tableName" argument must come only from trusted input! + * Annotations are key/value pairs that can be used by applications to identify or + * group commands. */ - deleteTable(tableName: string): void - } - interface Dao { + annotations: _TygojaDict /** - * Vacuum executes VACUUM on the current dao.DB() instance in order to - * reclaim unused db disk space. + * 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. */ - vacuum(): void - } - interface Dao { + version: string /** - * DeleteView drops the specified view name. - * - * This method is a no-op if a view with the provided name doesn't exist. + * 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. * - * Be aware that this method is vulnerable to SQL injection and the - * "name" argument must come only from trusted input! + * PersistentPreRun: children of this command will inherit and execute. */ - deleteView(name: string): void - } - interface Dao { + persistentPreRun: (cmd: Command, args: Array) => void /** - * SaveView creates (or updates already existing) persistent SQL view. - * - * Be aware that this method is vulnerable to SQL injection and the - * "selectQuery" argument must come only from trusted input! + * PersistentPreRunE: PersistentPreRun but returns an error. */ - saveView(name: string, selectQuery: string): void - } - interface Dao { + persistentPreRunE: (cmd: Command, args: Array) => void /** - * CreateViewSchema creates a new view schema from the provided select query. - * - * There are some caveats: - * - The select query must have an "id" column. - * - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data. + * PreRun: children of this command will not inherit. */ - createViewSchema(selectQuery: string): schema.Schema - } - interface Dao { + preRun: (cmd: Command, args: Array) => void /** - * FindRecordByViewFile returns the original models.Record of the - * provided view collection file. + * PreRunE: PreRun but returns an error. */ - findRecordByViewFile(viewCollectionNameOrId: string, fileFieldName: string, filename: string): (models.Record | undefined) - } -} - -/** - * Package core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. - */ -namespace core { - /** - * App defines the main PocketBase app interface. - */ - interface App { + preRunE: (cmd: Command, args: Array) => void /** - * Deprecated: - * This method may get removed in the near future. - * It is recommended to access the app db instance from app.Dao().DB() or - * if you want more flexibility - app.Dao().ConcurrentDB() and app.Dao().NonconcurrentDB(). - * - * DB returns the default app database instance. + * Run: Typically the actual work function. Most commands will only implement this. */ - db(): (dbx.DB | undefined) + run: (cmd: Command, args: Array) => void /** - * Dao returns the default app Dao instance. - * - * This Dao could operate only on the tables and models - * associated with the default app database. For example, - * trying to access the request logs table will result in error. + * RunE: Run but returns an error. */ - dao(): (daos.Dao | undefined) + runE: (cmd: Command, args: Array) => void /** - * Deprecated: - * This method may get removed in the near future. - * It is recommended to access the logs db instance from app.LogsDao().DB() or - * if you want more flexibility - app.LogsDao().ConcurrentDB() and app.LogsDao().NonconcurrentDB(). - * - * LogsDB returns the app logs database instance. + * PostRun: run after the Run command. */ - logsDB(): (dbx.DB | undefined) + postRun: (cmd: Command, args: Array) => void /** - * LogsDao returns the app logs Dao instance. - * - * This Dao could operate only on the tables and models - * associated with the logs database. For example, trying to access - * the users table from LogsDao will result in error. + * PostRunE: PostRun but returns an error. */ - logsDao(): (daos.Dao | undefined) + postRunE: (cmd: Command, args: Array) => void /** - * DataDir returns the app data directory path. + * PersistentPostRun: children of this command will inherit and execute after PostRun. */ - dataDir(): string + persistentPostRun: (cmd: Command, args: Array) => void /** - * EncryptionEnv returns the name of the app secret env key - * (used for settings encryption). + * PersistentPostRunE: PersistentPostRun but returns an error. */ - encryptionEnv(): string + persistentPostRunE: (cmd: Command, args: Array) => void /** - * IsDebug returns whether the app is in debug mode - * (showing more detailed error logs, executed sql statements, etc.). + * FParseErrWhitelist flag parse errors to be ignored */ - isDebug(): boolean + fParseErrWhitelist: FParseErrWhitelist /** - * Settings returns the loaded app settings. + * CompletionOptions is a set of options to control the handling of shell completion */ - settings(): (settings.Settings | undefined) + completionOptions: CompletionOptions /** - * Cache returns the app internal cache store. + * TraverseChildren parses flags on all parents before executing child command. */ - cache(): (store.Store | undefined) + traverseChildren: boolean /** - * SubscriptionsBroker returns the app realtime subscriptions broker instance. + * Hidden defines, if this command is hidden and should NOT show up in the list of available commands. */ - subscriptionsBroker(): (subscriptions.Broker | undefined) + hidden: boolean /** - * NewMailClient creates and returns a configured app mail client. + * SilenceErrors is an option to quiet errors down stream. */ - newMailClient(): mailer.Mailer + silenceErrors: boolean /** - * NewFilesystem creates and returns a configured filesystem.System instance - * for managing regular app files (eg. collection uploads). - * - * NB! Make sure to call Close() on the returned result - * after you are done working with it. + * SilenceUsage is an option to silence usage when an error occurs. */ - newFilesystem(): (filesystem.System | undefined) + silenceUsage: boolean /** - * NewBackupsFilesystem creates and returns a configured filesystem.System instance - * for managing app backups. - * - * NB! Make sure to call Close() on the returned result - * after you are done working with it. + * DisableFlagParsing disables the flag parsing. + * If this is true all flags will be passed to the command as arguments. */ - newBackupsFilesystem(): (filesystem.System | undefined) + disableFlagParsing: boolean /** - * RefreshSettings reinitializes and reloads the stored application settings. + * DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") + * will be printed by generating docs for this command. */ - refreshSettings(): void + disableAutoGenTag: boolean /** - * IsBootstrapped checks if the application was initialized - * (aka. whether Bootstrap() was called). + * DisableFlagsInUseLine will disable the addition of [flags] to the usage + * line of a command when printing help or generating docs */ - isBootstrapped(): boolean + disableFlagsInUseLine: boolean /** - * Bootstrap takes care for initializing the application - * (open db connections, load settings, etc.). - * - * It will call ResetBootstrapState() if the application was already bootstrapped. + * DisableSuggestions disables the suggestions based on Levenshtein distance + * that go along with 'unknown command' messages. */ - bootstrap(): void + disableSuggestions: boolean /** - * ResetBootstrapState takes care for releasing initialized app resources - * (eg. closing db connections). + * SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. + * Must be > 0. */ - resetBootstrapState(): void + suggestionsMinimumDistance: number + } + interface Command { /** - * CreateBackup creates a new backup of the current app pb_data directory. - * - * Backups can be stored on S3 if it is configured in app.Settings().Backups. + * 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. * - * Please refer to the godoc of the specific core.App implementation - * for details on the backup procedures. + * 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. */ - createBackup(ctx: context.Context, name: string): void + context(): context.Context + } + interface Command { /** - * RestoreBackup restores the backup with the specified name and restarts - * the current running application process. - * - * The safely perform the restore it is recommended to have free disk space - * for at least 2x the size of the restored pb_data backup. - * - * Please refer to the godoc of the specific core.App implementation - * for details on the restore procedures. - * - * NB! This feature is experimental and currently is expected to work only on UNIX based systems. + * SetContext sets context for the command. This context will be overwritten by + * Command.ExecuteContext or Command.ExecuteContextC. */ - restoreBackup(ctx: context.Context, name: string): void + setContext(ctx: context.Context): void + } + interface Command { /** - * Restart restarts the current running application process. - * - * Currently it is relying on execve so it is supported only on UNIX based systems. + * SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden + * particularly useful when testing. */ - restart(): void + setArgs(a: Array): void + } + interface Command { /** - * OnBeforeBootstrap hook is triggered before initializing the main - * application resources (eg. before db open and initial settings load). + * SetOutput sets the destination for usage and error messages. + * If output is nil, os.Stderr is used. + * Deprecated: Use SetOut and/or SetErr instead */ - onBeforeBootstrap(): (hook.Hook | undefined) - /** - * OnAfterBootstrap hook is triggered after initializing the main - * application resources (eg. after db open and initial settings load). - */ - onAfterBootstrap(): (hook.Hook | undefined) + setOutput(output: io.Writer): void + } + interface Command { /** - * OnBeforeServe hook is triggered before serving the internal router (echo), - * allowing you to adjust its options and attach new routes or middlewares. + * SetOut sets the destination for usage messages. + * If newOut is nil, os.Stdout is used. */ - onBeforeServe(): (hook.Hook | undefined) + setOut(newOut: io.Writer): void + } + interface Command { /** - * OnBeforeApiError hook is triggered right before sending an error API - * response to the client, allowing you to further modify the error data - * or to return a completely different API response. + * SetErr sets the destination for error messages. + * If newErr is nil, os.Stderr is used. */ - onBeforeApiError(): (hook.Hook | undefined) + setErr(newErr: io.Writer): void + } + interface Command { /** - * OnAfterApiError hook is triggered right after sending an error API - * response to the client. - * It could be used to log the final API error in external services. + * SetIn sets the source for input data + * If newIn is nil, os.Stdin is used. */ - onAfterApiError(): (hook.Hook | undefined) + setIn(newIn: io.Reader): void + } + interface Command { /** - * OnTerminate hook is triggered when the app is in the process - * of being terminated (eg. on SIGTERM signal). + * SetUsageFunc sets usage function. Usage can be defined by application. */ - onTerminate(): (hook.Hook | undefined) + setUsageFunc(f: (_arg0: Command) => void): void + } + interface Command { /** - * OnModelBeforeCreate hook is triggered before inserting a new - * model in the DB, allowing you to modify or validate the stored data. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetUsageTemplate sets usage template. Can be defined by Application. */ - onModelBeforeCreate(...tags: string[]): (hook.TaggedHook | undefined) + setUsageTemplate(s: string): void + } + interface Command { /** - * OnModelAfterCreate hook is triggered after successfully - * inserting a new model in the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetFlagErrorFunc sets a function to generate an error when flag parsing + * fails. */ - onModelAfterCreate(...tags: string[]): (hook.TaggedHook | undefined) + setFlagErrorFunc(f: (_arg0: Command, _arg1: Error) => void): void + } + interface Command { /** - * OnModelBeforeUpdate hook is triggered before updating existing - * model in the DB, allowing you to modify or validate the stored data. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetHelpFunc sets help function. Can be defined by Application. */ - onModelBeforeUpdate(...tags: string[]): (hook.TaggedHook | undefined) + setHelpFunc(f: (_arg0: Command, _arg1: Array) => void): void + } + interface Command { /** - * OnModelAfterUpdate hook is triggered after successfully updating - * existing model in the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetHelpCommand sets help command. */ - onModelAfterUpdate(...tags: string[]): (hook.TaggedHook | undefined) + setHelpCommand(cmd: Command): void + } + interface Command { /** - * OnModelBeforeDelete hook is triggered before deleting an - * existing model from the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetHelpCommandGroupID sets the group id of the help command. */ - onModelBeforeDelete(...tags: string[]): (hook.TaggedHook | undefined) + setHelpCommandGroupID(groupID: string): void + } + interface Command { /** - * OnModelAfterDelete hook is triggered after successfully deleting an - * existing model from the DB. - * - * If the optional "tags" list (table names and/or the Collection id for Record models) - * is specified, then all event handlers registered via the created hook - * will be triggered and called only if their event data origin matches the tags. + * SetCompletionCommandGroupID sets the group id of the completion command. */ - onModelAfterDelete(...tags: string[]): (hook.TaggedHook | undefined) + setCompletionCommandGroupID(groupID: string): void + } + interface Command { /** - * OnMailerBeforeAdminResetPasswordSend hook is triggered right - * before sending a password reset email to an admin, allowing you - * to inspect and customize the email message that is being sent. + * SetHelpTemplate sets help template to be used. Application can use it to set custom template. */ - onMailerBeforeAdminResetPasswordSend(): (hook.Hook | undefined) + setHelpTemplate(s: string): void + } + interface Command { /** - * OnMailerAfterAdminResetPasswordSend hook is triggered after - * admin password reset email was successfully sent. + * SetVersionTemplate sets version template to be used. Application can use it to set custom template. */ - onMailerAfterAdminResetPasswordSend(): (hook.Hook | undefined) + setVersionTemplate(s: string): void + } + interface Command { /** - * OnMailerBeforeRecordResetPasswordSend hook is triggered right - * before sending a password reset email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. + * The user should not have a cyclic dependency on commands. */ - onMailerBeforeRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + setGlobalNormalizationFunc(n: (f: flag.FlagSet, name: string) => flag.NormalizedName): void + } + interface Command { /** - * OnMailerAfterRecordResetPasswordSend hook is triggered after - * an auth record password reset email was successfully sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * OutOrStdout returns output to stdout. */ - onMailerAfterRecordResetPasswordSend(...tags: string[]): (hook.TaggedHook | undefined) + outOrStdout(): io.Writer + } + interface Command { /** - * OnMailerBeforeRecordVerificationSend hook is triggered right - * before sending a verification email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * OutOrStderr returns output to stderr */ - onMailerBeforeRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + outOrStderr(): io.Writer + } + interface Command { /** - * OnMailerAfterRecordVerificationSend hook is triggered after a - * verification email was successfully sent to an auth record. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * ErrOrStderr returns output to stderr */ - onMailerAfterRecordVerificationSend(...tags: string[]): (hook.TaggedHook | undefined) + errOrStderr(): io.Writer + } + interface Command { /** - * OnMailerBeforeRecordChangeEmailSend hook is triggered right before - * sending a confirmation new address email to an auth record, allowing - * you to inspect and customize the email message that is being sent. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * InOrStdin returns input to stdin */ - onMailerBeforeRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + inOrStdin(): io.Reader + } + interface Command { /** - * OnMailerAfterRecordChangeEmailSend hook is triggered after a - * verification email was successfully sent to an auth record. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * UsageFunc returns either the function set by SetUsageFunc for this command + * or a parent, or it returns a default usage function. */ - onMailerAfterRecordChangeEmailSend(...tags: string[]): (hook.TaggedHook | undefined) + usageFunc(): (_arg0: Command) => void + } + interface Command { /** - * OnRealtimeConnectRequest hook is triggered right before establishing - * the SSE client connection. + * Usage puts out the usage for the command. + * Used when a user provides invalid input. + * Can be defined by user by overriding UsageFunc. */ - onRealtimeConnectRequest(): (hook.Hook | undefined) + usage(): void + } + interface Command { /** - * OnRealtimeDisconnectRequest hook is triggered on disconnected/interrupted - * SSE client connection. + * HelpFunc returns either the function set by SetHelpFunc for this command + * or a parent, or it returns a function with default help behavior. */ - onRealtimeDisconnectRequest(): (hook.Hook | undefined) + helpFunc(): (_arg0: Command, _arg1: Array) => void + } + interface Command { /** - * OnRealtimeBeforeMessage hook is triggered right before sending - * an SSE message to a client. - * - * Returning [hook.StopPropagation] will prevent sending the message. - * Returning any other non-nil error will close the realtime connection. + * Help puts out the help for the command. + * Used when a user calls help [command]. + * Can be defined by user by overriding HelpFunc. */ - onRealtimeBeforeMessageSend(): (hook.Hook | undefined) + help(): void + } + interface Command { /** - * OnRealtimeBeforeMessage hook is triggered right after sending - * an SSE message to a client. + * UsageString returns usage string. */ - onRealtimeAfterMessageSend(): (hook.Hook | undefined) + usageString(): string + } + interface Command { /** - * OnRealtimeBeforeSubscribeRequest hook is triggered before changing - * the client subscriptions, allowing you to further validate and - * modify the submitted change. + * FlagErrorFunc returns either the function set by SetFlagErrorFunc for this + * command or a parent, or it returns a function which returns the original + * error. */ - onRealtimeBeforeSubscribeRequest(): (hook.Hook | undefined) + flagErrorFunc(): (_arg0: Command, _arg1: Error) => void + } + interface Command { /** - * OnRealtimeAfterSubscribeRequest hook is triggered after the client - * subscriptions were successfully changed. + * UsagePadding return padding for the usage. */ - onRealtimeAfterSubscribeRequest(): (hook.Hook | undefined) + usagePadding(): number + } + interface Command { /** - * OnSettingsListRequest hook is triggered on each successful - * API Settings list request. - * - * Could be used to validate or modify the response before - * returning it to the client. + * CommandPathPadding return padding for the command path. */ - onSettingsListRequest(): (hook.Hook | undefined) + commandPathPadding(): number + } + interface Command { /** - * OnSettingsBeforeUpdateRequest hook is triggered before each API - * Settings update request (after request data load and before settings persistence). - * - * Could be used to additionally validate the request data or - * implement completely different persistence behavior. + * NamePadding returns padding for the name. */ - onSettingsBeforeUpdateRequest(): (hook.Hook | undefined) + namePadding(): number + } + interface Command { /** - * OnSettingsAfterUpdateRequest hook is triggered after each - * successful API Settings update request. + * UsageTemplate returns usage template for the command. */ - onSettingsAfterUpdateRequest(): (hook.Hook | undefined) + usageTemplate(): string + } + interface Command { /** - * OnFileDownloadRequest hook is triggered before each API File download request. - * - * Could be used to validate or modify the file response before - * returning it to the client. + * HelpTemplate return help template for the command. */ - onFileDownloadRequest(...tags: string[]): (hook.TaggedHook | undefined) + helpTemplate(): string + } + interface Command { /** - * OnFileBeforeTokenRequest hook is triggered before each file - * token API request. - * - * If no token or model was submitted, e.Model and e.Token will be empty, - * allowing you to implement your own custom model file auth implementation. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * VersionTemplate return version template for the command. */ - onFileBeforeTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + versionTemplate(): string + } + interface Command { /** - * OnFileAfterTokenRequest hook is triggered after each - * successful file token API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Find the target command given the args and command tree + * Meant to be run on the highest node. Only searches down. */ - onFileAfterTokenRequest(...tags: string[]): (hook.TaggedHook | undefined) + find(args: Array): [(Command | undefined), Array] + } + interface Command { /** - * OnAdminsListRequest hook is triggered on each API Admins list request. - * - * Could be used to validate or modify the response before returning it to the client. + * Traverse the command tree to find the command, and parse args for + * each parent. */ - onAdminsListRequest(): (hook.Hook | undefined) + traverse(args: Array): [(Command | undefined), Array] + } + interface Command { /** - * OnAdminViewRequest hook is triggered on each API Admin view request. - * - * Could be used to validate or modify the response before returning it to the client. + * SuggestionsFor provides suggestions for the typedName. */ - onAdminViewRequest(): (hook.Hook | undefined) + suggestionsFor(typedName: string): Array + } + interface Command { /** - * OnAdminBeforeCreateRequest hook is triggered before each API - * Admin create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * VisitParents visits all parents of the command and invokes fn on each parent. */ - onAdminBeforeCreateRequest(): (hook.Hook | undefined) + visitParents(fn: (_arg0: Command) => void): void + } + interface Command { /** - * OnAdminAfterCreateRequest hook is triggered after each - * successful API Admin create request. + * Root finds root command. */ - onAdminAfterCreateRequest(): (hook.Hook | undefined) + root(): (Command | undefined) + } + interface Command { /** - * OnAdminBeforeUpdateRequest hook is triggered before each API - * Admin update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * ArgsLenAtDash will return the length of c.Flags().Args at the moment + * when a -- was found during args parsing. */ - onAdminBeforeUpdateRequest(): (hook.Hook | undefined) + argsLenAtDash(): number + } + interface Command { /** - * OnAdminAfterUpdateRequest hook is triggered after each - * successful API Admin update request. + * 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. */ - onAdminAfterUpdateRequest(): (hook.Hook | undefined) + executeContext(ctx: context.Context): void + } + interface Command { /** - * OnAdminBeforeDeleteRequest hook is triggered before each API - * Admin delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. + * Execute uses the args (os.Args[1:] by default) + * and run through the command tree finding appropriate matches + * for commands and then corresponding flags. */ - onAdminBeforeDeleteRequest(): (hook.Hook | undefined) + execute(): void + } + interface Command { /** - * OnAdminAfterDeleteRequest hook is triggered after each - * successful API Admin delete request. + * ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. + * Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs + * functions. */ - onAdminAfterDeleteRequest(): (hook.Hook | undefined) + executeContextC(ctx: context.Context): (Command | undefined) + } + interface Command { /** - * OnAdminAuthRequest hook is triggered on each successful API Admin - * authentication request (sign-in, token refresh, etc.). - * - * Could be used to additionally validate or modify the - * authenticated admin data and token. + * ExecuteC executes the command. */ - onAdminAuthRequest(): (hook.Hook | undefined) + executeC(): (Command | undefined) + } + interface Command { + validateArgs(args: Array): void + } + interface Command { /** - * OnAdminBeforeAuthWithPasswordRequest hook is triggered before each Admin - * auth with password API request (after request data load and before password validation). - * - * Could be used to implement for example a custom password validation - * or to locate a different Admin identity (by assigning [AdminAuthWithPasswordEvent.Admin]). + * ValidateRequiredFlags validates all required flags are present and returns an error otherwise */ - onAdminBeforeAuthWithPasswordRequest(): (hook.Hook | undefined) + validateRequiredFlags(): void + } + interface Command { /** - * OnAdminAfterAuthWithPasswordRequest hook is triggered after each - * successful Admin auth with password API request. + * 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. */ - onAdminAfterAuthWithPasswordRequest(): (hook.Hook | undefined) + initDefaultHelpFlag(): void + } + interface Command { /** - * OnAdminBeforeAuthRefreshRequest hook is triggered before each Admin - * auth refresh API request (right before generating a new auth token). - * - * Could be used to additionally validate the request data or implement - * completely different auth refresh behavior. + * 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. */ - onAdminBeforeAuthRefreshRequest(): (hook.Hook | undefined) + initDefaultVersionFlag(): void + } + interface Command { /** - * OnAdminAfterAuthRefreshRequest hook is triggered after each - * successful auth refresh API request (right after generating a new auth token). + * 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. */ - onAdminAfterAuthRefreshRequest(): (hook.Hook | undefined) + initDefaultHelpCmd(): void + } + interface Command { /** - * OnAdminBeforeRequestPasswordResetRequest hook is triggered before each Admin - * request password reset API request (after request data load and before sending the reset email). - * - * Could be used to additionally validate the request data or implement - * completely different password reset behavior. + * ResetCommands delete parent, subcommand and help command from c. */ - onAdminBeforeRequestPasswordResetRequest(): (hook.Hook | undefined) + resetCommands(): void + } + interface Command { /** - * OnAdminAfterRequestPasswordResetRequest hook is triggered after each - * successful request password reset API request. + * Commands returns a sorted slice of child commands. */ - onAdminAfterRequestPasswordResetRequest(): (hook.Hook | undefined) + commands(): Array<(Command | undefined)> + } + interface Command { /** - * OnAdminBeforeConfirmPasswordResetRequest hook is triggered before each Admin - * confirm password reset API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * AddCommand adds one or more commands to this parent command. */ - onAdminBeforeConfirmPasswordResetRequest(): (hook.Hook | undefined) + addCommand(...cmds: (Command | undefined)[]): void + } + interface Command { /** - * OnAdminAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. + * Groups returns a slice of child command groups. */ - onAdminAfterConfirmPasswordResetRequest(): (hook.Hook | undefined) + groups(): Array<(Group | undefined)> + } + interface Command { /** - * OnRecordAuthRequest hook is triggered on each successful API - * record authentication request (sign-in, token refresh, etc.). - * - * Could be used to additionally validate or modify the authenticated - * record data and token. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * AllChildCommandsHaveGroup returns if all subcommands are assigned to a group */ - onRecordAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + allChildCommandsHaveGroup(): boolean + } + interface Command { /** - * OnRecordBeforeAuthWithPasswordRequest hook is triggered before each Record - * auth with password API request (after request data load and before password validation). - * - * Could be used to implement for example a custom password validation - * or to locate a different Record model (by reassigning [RecordAuthWithPasswordEvent.Record]). - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * ContainsGroup return if groupID exists in the list of command groups. */ - onRecordBeforeAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + containsGroup(groupID: string): boolean + } + interface Command { /** - * OnRecordAfterAuthWithPasswordRequest hook is triggered after each - * successful Record auth with password API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * AddGroup adds one or more command groups to this parent command. */ - onRecordAfterAuthWithPasswordRequest(...tags: string[]): (hook.TaggedHook | undefined) + addGroup(...groups: (Group | undefined)[]): void + } + interface Command { /** - * OnRecordBeforeAuthWithOAuth2Request hook is triggered before each Record - * OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). - * - * If the [RecordAuthWithOAuth2Event.Record] is not set, then the OAuth2 - * request will try to create a new auth Record. - * - * To assign or link a different existing record model you can - * change the [RecordAuthWithOAuth2Event.Record] field. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * RemoveCommand removes one or more commands from a parent command. */ - onRecordBeforeAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + removeCommand(...cmds: (Command | undefined)[]): void + } + interface Command { /** - * OnRecordAfterAuthWithOAuth2Request hook is triggered after each - * successful Record OAuth2 API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Print is a convenience method to Print to the defined output, fallback to Stderr if not set. */ - onRecordAfterAuthWithOAuth2Request(...tags: string[]): (hook.TaggedHook | undefined) + print(...i: { + }[]): void + } + interface Command { /** - * OnRecordBeforeAuthRefreshRequest hook is triggered before each Record - * auth refresh API request (right before generating a new auth token). - * - * Could be used to additionally validate the request data or implement - * completely different auth refresh behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Println is a convenience method to Println to the defined output, fallback to Stderr if not set. */ - onRecordBeforeAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) + println(...i: { + }[]): void + } + interface Command { /** - * OnRecordAfterAuthRefreshRequest hook is triggered after each - * successful auth refresh API request (right after generating a new auth token). - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. */ - onRecordAfterAuthRefreshRequest(...tags: string[]): (hook.TaggedHook | undefined) + printf(format: string, ...i: { + }[]): void + } + interface Command { /** - * OnRecordListExternalAuthsRequest hook is triggered on each API record external auths list request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. */ - onRecordListExternalAuthsRequest(...tags: string[]): (hook.TaggedHook | undefined) + printErr(...i: { + }[]): void + } + interface Command { /** - * OnRecordBeforeUnlinkExternalAuthRequest hook is triggered before each API record - * external auth unlink request (after models load and before the actual relation deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. */ - onRecordBeforeUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + printErrln(...i: { + }[]): void + } + interface Command { /** - * OnRecordAfterUnlinkExternalAuthRequest hook is triggered after each - * successful API record external auth unlink request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. */ - onRecordAfterUnlinkExternalAuthRequest(...tags: string[]): (hook.TaggedHook | undefined) + printErrf(format: string, ...i: { + }[]): void + } + interface Command { /** - * OnRecordBeforeRequestPasswordResetRequest hook is triggered before each Record - * request password reset API request (after request data load and before sending the reset email). - * - * Could be used to additionally validate the request data or implement - * completely different password reset behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * CommandPath returns the full path to this command. */ - onRecordBeforeRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + commandPath(): string + } + interface Command { /** - * OnRecordAfterRequestPasswordResetRequest hook is triggered after each - * successful request password reset API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * UseLine puts out the full usage for a given command (including parents). */ - onRecordAfterRequestPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + useLine(): string + } + interface Command { /** - * OnRecordBeforeConfirmPasswordResetRequest hook is triggered before each Record - * confirm password reset API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * DebugFlags used to determine which flags have been assigned to which commands + * and which persist. */ - onRecordBeforeConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + debugFlags(): void + } + interface Command { /** - * OnRecordAfterConfirmPasswordResetRequest hook is triggered after each - * successful confirm password reset API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Name returns the command's name: the first word in the use line. */ - onRecordAfterConfirmPasswordResetRequest(...tags: string[]): (hook.TaggedHook | undefined) + name(): string + } + interface Command { /** - * OnRecordBeforeRequestVerificationRequest hook is triggered before each Record - * request verification API request (after request data load and before sending the verification email). - * - * Could be used to additionally validate the loaded request data or implement - * completely different verification behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * HasAlias determines if a given string is an alias of the command. */ - onRecordBeforeRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasAlias(s: string): boolean + } + interface Command { /** - * OnRecordAfterRequestVerificationRequest hook is triggered after each - * successful request verification API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * 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. */ - onRecordAfterRequestVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + calledAs(): string + } + interface Command { /** - * OnRecordBeforeConfirmVerificationRequest hook is triggered before each Record - * confirm verification API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * NameAndAliases returns a list of the command name and all aliases */ - onRecordBeforeConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + nameAndAliases(): string + } + interface Command { /** - * OnRecordAfterConfirmVerificationRequest hook is triggered after each - * successful confirm verification API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * HasExample determines if the command has example. */ - onRecordAfterConfirmVerificationRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasExample(): boolean + } + interface Command { /** - * OnRecordBeforeRequestEmailChangeRequest hook is triggered before each Record request email change API request - * (after request data load and before sending the email link to confirm the change). - * - * Could be used to additionally validate the request data or implement - * completely different request email change behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Runnable determines if the command is itself runnable. */ - onRecordBeforeRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + runnable(): boolean + } + interface Command { /** - * OnRecordAfterRequestEmailChangeRequest hook is triggered after each - * successful request email change API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * HasSubCommands determines if the command has children commands. */ - onRecordAfterRequestEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasSubCommands(): boolean + } + interface Command { /** - * OnRecordBeforeConfirmEmailChangeRequest hook is triggered before each Record - * confirm email change API request (after request data load and before persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * IsAvailableCommand determines if a command is available as a non-help command + * (this includes all non deprecated/hidden commands). */ - onRecordBeforeConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + isAvailableCommand(): boolean + } + interface Command { /** - * OnRecordAfterConfirmEmailChangeRequest hook is triggered after each - * successful confirm email change API request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * 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. */ - onRecordAfterConfirmEmailChangeRequest(...tags: string[]): (hook.TaggedHook | undefined) + isAdditionalHelpTopicCommand(): boolean + } + interface Command { /** - * OnRecordsListRequest hook is triggered on each API Records list request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * 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'. */ - onRecordsListRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasHelpSubCommands(): boolean + } + interface Command { /** - * OnRecordViewRequest hook is triggered on each API Record view request. - * - * Could be used to validate or modify the response before returning it to the client. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * HasAvailableSubCommands determines if a command has available sub commands that + * need to be shown in the usage/help default template under 'available commands'. */ - onRecordViewRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasAvailableSubCommands(): boolean + } + interface Command { /** - * OnRecordBeforeCreateRequest hook is triggered before each API Record - * create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * HasParent determines if the command is a child command. */ - onRecordBeforeCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + hasParent(): boolean + } + interface Command { /** - * OnRecordAfterCreateRequest hook is triggered after each - * successful API Record create request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. */ - onRecordAfterCreateRequest(...tags: string[]): (hook.TaggedHook | undefined) + globalNormalizationFunc(): (f: flag.FlagSet, name: string) => flag.NormalizedName + } + interface Command { /** - * OnRecordBeforeUpdateRequest hook is triggered before each API Record - * update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * Flags returns the complete FlagSet that applies + * to this command (local and persistent declared here and by all parents). */ - onRecordBeforeUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + flags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnRecordAfterUpdateRequest hook is triggered after each - * successful API Record update request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. */ - onRecordAfterUpdateRequest(...tags: string[]): (hook.TaggedHook | undefined) + localNonPersistentFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnRecordBeforeDeleteRequest hook is triggered before each API Record - * delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * LocalFlags returns the local FlagSet specifically set in the current command. */ - onRecordBeforeDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + localFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnRecordAfterDeleteRequest hook is triggered after each - * successful API Record delete request. - * - * If the optional "tags" list (Collection ids or names) is specified, - * then all event handlers registered via the created hook will be - * triggered and called only if their event data origin matches the tags. + * InheritedFlags returns all flags which were inherited from parent commands. */ - onRecordAfterDeleteRequest(...tags: string[]): (hook.TaggedHook | undefined) + inheritedFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnCollectionsListRequest hook is triggered on each API Collections list request. - * - * Could be used to validate or modify the response before returning it to the client. + * NonInheritedFlags returns all flags which were not inherited from parent commands. */ - onCollectionsListRequest(): (hook.Hook | undefined) + nonInheritedFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnCollectionViewRequest hook is triggered on each API Collection view request. - * - * Could be used to validate or modify the response before returning it to the client. + * PersistentFlags returns the persistent FlagSet specifically set in the current command. */ - onCollectionViewRequest(): (hook.Hook | undefined) + persistentFlags(): (flag.FlagSet | undefined) + } + interface Command { /** - * OnCollectionBeforeCreateRequest hook is triggered before each API Collection - * create request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * ResetFlags deletes all flags from command. */ - onCollectionBeforeCreateRequest(): (hook.Hook | undefined) + resetFlags(): void + } + interface Command { /** - * OnCollectionAfterCreateRequest hook is triggered after each - * successful API Collection create request. + * HasFlags checks if the command contains any flags (local plus persistent from the entire structure). */ - onCollectionAfterCreateRequest(): (hook.Hook | undefined) + hasFlags(): boolean + } + interface Command { /** - * OnCollectionBeforeUpdateRequest hook is triggered before each API Collection - * update request (after request data load and before model persistence). - * - * Could be used to additionally validate the request data or implement - * completely different persistence behavior. + * HasPersistentFlags checks if the command contains persistent flags. */ - onCollectionBeforeUpdateRequest(): (hook.Hook | undefined) + hasPersistentFlags(): boolean + } + interface Command { /** - * OnCollectionAfterUpdateRequest hook is triggered after each - * successful API Collection update request. + * HasLocalFlags checks if the command has flags specifically declared locally. */ - onCollectionAfterUpdateRequest(): (hook.Hook | undefined) + hasLocalFlags(): boolean + } + interface Command { /** - * OnCollectionBeforeDeleteRequest hook is triggered before each API - * Collection delete request (after model load and before actual deletion). - * - * Could be used to additionally validate the request data or implement - * completely different delete behavior. + * HasInheritedFlags checks if the command has flags inherited from its parent command. */ - onCollectionBeforeDeleteRequest(): (hook.Hook | undefined) + hasInheritedFlags(): boolean + } + interface Command { /** - * OnCollectionAfterDeleteRequest hook is triggered after each - * successful API Collection delete request. + * HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire + * structure) which are not hidden or deprecated. */ - onCollectionAfterDeleteRequest(): (hook.Hook | undefined) + hasAvailableFlags(): boolean + } + interface Command { /** - * OnCollectionsBeforeImportRequest hook is triggered before each API - * collections import request (after request data load and before the actual import). - * - * Could be used to additionally validate the imported collections or - * to implement completely different import behavior. + * HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. */ - onCollectionsBeforeImportRequest(): (hook.Hook | undefined) + hasAvailablePersistentFlags(): boolean + } + interface Command { /** - * OnCollectionsAfterImportRequest hook is triggered after each - * successful API collections import request. + * HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden + * or deprecated. */ - onCollectionsAfterImportRequest(): (hook.Hook | undefined) + hasAvailableLocalFlags(): boolean } -} - -/** - * Package time provides functionality for measuring and displaying time. - * - * The calendrical calculations always assume a Gregorian calendar, with - * no leap seconds. - * - * Monotonic Clocks - * - * Operating systems provide both a “wall clock,” which is subject to - * changes for clock synchronization, and a “monotonic clock,” which is - * not. The general rule is that the wall clock is for telling time and - * the monotonic clock is for measuring time. Rather than split the API, - * in this package the Time returned by time.Now contains both a wall - * clock reading and a monotonic clock reading; later time-telling - * operations use the wall clock reading, but later time-measuring - * operations, specifically comparisons and subtractions, use the - * monotonic clock reading. - * - * For example, this code always computes a positive elapsed time of - * approximately 20 milliseconds, even if the wall clock is changed during - * the operation being timed: - * - * ``` - * start := time.Now() - * ... operation that takes 20 milliseconds ... - * t := time.Now() - * elapsed := t.Sub(start) - * ``` - * - * Other idioms, such as time.Since(start), time.Until(deadline), and - * time.Now().Before(deadline), are similarly robust against wall clock - * resets. - * - * The rest of this section gives the precise details of how operations - * use monotonic clocks, but understanding those details is not required - * to use this package. - * - * The Time returned by time.Now contains a monotonic clock reading. - * If Time t has a monotonic clock reading, t.Add adds the same duration to - * both the wall clock and monotonic clock readings to compute the result. - * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time - * computations, they always strip any monotonic clock reading from their results. - * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation - * of the wall time, they also strip any monotonic clock reading from their results. - * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). - * - * If Times t and u both contain monotonic clock readings, the operations - * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out - * using the monotonic clock readings alone, ignoring the wall clock - * readings. If either t or u contains no monotonic clock reading, these - * operations fall back to using the wall clock readings. - * - * On some systems the monotonic clock will stop if the computer goes to sleep. - * On such a system, t.Sub(u) may not accurately reflect the actual - * time that passed between t and u. - * - * Because the monotonic clock reading has no meaning outside - * the current process, the serialized forms generated by t.GobEncode, - * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic - * clock reading, and t.Format provides no format for it. Similarly, the - * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, - * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. - * t.UnmarshalJSON, and t.UnmarshalText always create times with - * no monotonic clock reading. - * - * Note that the Go == operator compares not just the time instant but - * also the Location and the monotonic clock reading. See the - * documentation for the Time type for a discussion of equality - * testing for Time values. - * - * For debugging, the result of t.String does include the monotonic - * clock reading if present. If t != u because of different monotonic clock readings, - * that difference will be visible when printing t.String() and u.String(). - */ -namespace time { - interface Time { + interface Command { /** - * String returns the time formatted using the format string - * ``` - * "2006-01-02 15:04:05.999999999 -0700 MST" - * ``` - * - * If the time has a monotonic clock reading, the returned string - * includes a final field "m=±", where value is the monotonic - * clock reading formatted as a decimal number of seconds. - * - * The returned string is meant for debugging; for a stable serialized - * representation, use t.MarshalText, t.MarshalBinary, or t.Format - * with an explicit format string. + * HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are + * not hidden or deprecated. */ - string(): string + hasAvailableInheritedFlags(): boolean } - interface Time { + interface Command { /** - * GoString implements fmt.GoStringer and formats t to be printed in Go source - * code. + * Flag climbs up the command tree looking for matching flag. */ - goString(): string + flag(name: string): (flag.Flag | undefined) } - interface Time { + interface Command { /** - * Format returns a textual representation of the time value formatted according - * to the layout defined by the argument. See the documentation for the - * constant called Layout to see how to represent the layout format. - * - * The executable example for Time.Format demonstrates the working - * of the layout string in detail and is a good reference. + * ParseFlags parses persistent flag tree and local flags. */ - format(layout: string): string + parseFlags(args: Array): void } - interface Time { + interface Command { /** - * AppendFormat is like Format but appends the textual - * representation to b and returns the extended buffer. + * Parent returns a commands parent command. */ - appendFormat(b: string, layout: string): string - } - /** - * A Time represents an instant in time with nanosecond precision. - * - * Programs using times should typically store and pass them as values, - * not pointers. That is, time variables and struct fields should be of - * type time.Time, not *time.Time. - * - * A Time value can be used by multiple goroutines simultaneously except - * that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and - * UnmarshalText are not concurrency-safe. - * - * Time instants can be compared using the Before, After, and Equal methods. - * The Sub method subtracts two instants, producing a Duration. - * The Add method adds a Time and a Duration, producing a Time. - * - * The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. - * As this time is unlikely to come up in practice, the IsZero method gives - * a simple way of detecting a time that has not been initialized explicitly. - * - * Each Time has associated with it a Location, consulted when computing the - * presentation form of the time, such as in the Format, Hour, and Year methods. - * The methods Local, UTC, and In return a Time with a specific location. - * Changing the location in this way changes only the presentation; it does not - * change the instant in time being denoted and therefore does not affect the - * computations described in earlier paragraphs. - * - * Representations of a Time value saved by the GobEncode, MarshalBinary, - * MarshalJSON, and MarshalText methods store the Time.Location's offset, but not - * the location name. They therefore lose information about Daylight Saving Time. - * - * In addition to the required “wall clock” reading, a Time may contain an optional - * reading of the current process's monotonic clock, to provide additional precision - * for comparison or subtraction. - * See the “Monotonic Clocks” section in the package documentation for details. - * - * Note that the Go == operator compares not just the time instant but also the - * Location and the monotonic clock reading. Therefore, Time values should not - * be used as map or database keys without first guaranteeing that the - * identical Location has been set for all values, which can be achieved - * through use of the UTC or Local method, and that the monotonic clock reading - * has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) - * to t == u, since t.Equal uses the most accurate comparison available and - * correctly handles the case when only one of its arguments has a monotonic - * clock reading. - */ - interface Time { + parent(): (Command | undefined) } - interface Time { + interface Command { /** - * After reports whether the time instant t is after u. + * RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. */ - after(u: Time): boolean + registerFlagCompletionFunc(flagName: string, f: (cmd: Command, args: Array, toComplete: string) => [Array, ShellCompDirective]): void } - interface Time { + interface Command { /** - * Before reports whether the time instant t is before u. + * 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. */ - before(u: Time): boolean + initDefaultCompletionCmd(): void } - interface Time { + interface Command { /** - * Equal reports whether t and u represent the same time instant. - * Two times can be equal even if they are in different locations. - * For example, 6:00 +0200 and 4:00 UTC are Equal. - * See the documentation on the Time type for the pitfalls of using == with - * Time values; most code should use Equal instead. + * GenFishCompletion generates fish completion file and writes to the passed writer. */ - equal(u: Time): boolean + genFishCompletion(w: io.Writer, includeDesc: boolean): void } - interface Time { + interface Command { /** - * IsZero reports whether t represents the zero time instant, - * January 1, year 1, 00:00:00 UTC. + * GenFishCompletionFile generates fish completion file. */ - isZero(): boolean + genFishCompletionFile(filename: string, includeDesc: boolean): void } - interface Time { + interface Command { /** - * Date returns the year, month, and day in which t occurs. + * 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. */ - date(): [number, Month, number] + markFlagsRequiredTogether(...flagNames: string[]): void } - interface Time { + interface Command { /** - * Year returns the year in which t occurs. + * 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. */ - year(): number + markFlagsMutuallyExclusive(...flagNames: string[]): void } - interface Time { + interface Command { /** - * Month returns the month of the year specified by t. + * ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the + * first error encountered. */ - month(): Month + validateFlagGroups(): void } - interface Time { + interface Command { /** - * Day returns the day of the month specified by t. + * GenPowerShellCompletionFile generates powershell completion file without descriptions. */ - day(): number + genPowerShellCompletionFile(filename: string): void } - interface Time { + interface Command { /** - * Weekday returns the day of the week specified by t. + * GenPowerShellCompletion generates powershell completion file without descriptions + * and writes it to the passed writer. */ - weekday(): Weekday + genPowerShellCompletion(w: io.Writer): void } - interface Time { + interface Command { /** - * ISOWeek returns the ISO 8601 year and week number in which t occurs. - * Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to - * week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 - * of year n+1. + * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. */ - isoWeek(): number + genPowerShellCompletionFileWithDesc(filename: string): void } - interface Time { + interface Command { /** - * Clock returns the hour, minute, and second within the day specified by t. + * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions + * and writes it to the passed writer. */ - clock(): number + genPowerShellCompletionWithDesc(w: io.Writer): void } - interface Time { + interface Command { /** - * Hour returns the hour within the day specified by t, in the range [0, 23]. + * 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. */ - hour(): number + markFlagRequired(name: string): void } - interface Time { + interface Command { /** - * Minute returns the minute offset within the hour specified by t, in the range [0, 59]. + * 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. */ - minute(): number + markPersistentFlagRequired(name: string): void } - interface Time { + interface Command { /** - * Second returns the second offset within the minute specified by t, in the range [0, 59]. + * MarkFlagFilename instructs the various shell completion implementations to + * limit completions for the named flag to the specified file extensions. */ - second(): number + markFlagFilename(name: string, ...extensions: string[]): void } - interface Time { + interface Command { /** - * Nanosecond returns the nanosecond offset within the second specified by t, - * in the range [0, 999999999]. + * 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. */ - nanosecond(): number + markFlagCustom(name: string, f: string): void } - interface Time { + interface Command { /** - * YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, - * and [1,366] in leap years. + * MarkPersistentFlagFilename instructs the various shell completion + * implementations to limit completions for the named persistent flag to the + * specified file extensions. */ - yearDay(): number + markPersistentFlagFilename(name: string, ...extensions: string[]): void } - interface Time { + interface Command { /** - * Add returns the time t+d. + * MarkFlagDirname instructs the various shell completion implementations to + * limit completions for the named flag to directory names. */ - add(d: Duration): Time + markFlagDirname(name: string): void } - interface Time { + interface Command { /** - * Sub returns the duration t-u. If the result exceeds the maximum (or minimum) - * value that can be stored in a Duration, the maximum (or minimum) duration - * will be returned. - * To compute t-d for a duration d, use t.Add(-d). + * MarkPersistentFlagDirname instructs the various shell completion + * implementations to limit completions for the named persistent flag to + * directory names. */ - sub(u: Time): Duration + markPersistentFlagDirname(name: string): void } - interface Time { + interface Command { /** - * AddDate returns the time corresponding to adding the - * given number of years, months, and days to t. - * For example, AddDate(-1, 2, 3) applied to January 1, 2011 - * returns March 4, 2010. - * - * AddDate normalizes its result in the same way that Date does, - * so, for example, adding one month to October 31 yields - * December 1, the normalized form for November 31. + * GenZshCompletionFile generates zsh completion file including descriptions. */ - addDate(years: number, months: number, days: number): Time + genZshCompletionFile(filename: string): void } - interface Time { + interface Command { /** - * UTC returns t with the location set to UTC. + * GenZshCompletion generates zsh completion file including descriptions + * and writes it to the passed writer. */ - utc(): Time - } - interface Time { - /** - * Local returns t with the location set to local time. - */ - local(): Time - } - interface Time { - /** - * In returns a copy of t representing the same time instant, but - * with the copy's location information set to loc for display - * purposes. - * - * In panics if loc is nil. - */ - in(loc: Location): Time - } - interface Time { - /** - * Location returns the time zone information associated with t. - */ - location(): (Location | undefined) - } - interface Time { - /** - * Zone computes the time zone in effect at time t, returning the abbreviated - * name of the zone (such as "CET") and its offset in seconds east of UTC. - */ - zone(): [string, number] - } - interface Time { - /** - * Unix returns t as a Unix time, the number of seconds elapsed - * since January 1, 1970 UTC. The result does not depend on the - * location associated with t. - * Unix-like operating systems often record time as a 32-bit - * count of seconds, but since the method here returns a 64-bit - * value it is valid for billions of years into the past or future. - */ - unix(): number - } - interface Time { - /** - * UnixMilli returns t as a Unix time, the number of milliseconds elapsed since - * January 1, 1970 UTC. The result is undefined if the Unix time in - * milliseconds cannot be represented by an int64 (a date more than 292 million - * years before or after 1970). The result does not depend on the - * location associated with t. - */ - unixMilli(): number - } - interface Time { - /** - * UnixMicro returns t as a Unix time, the number of microseconds elapsed since - * January 1, 1970 UTC. The result is undefined if the Unix time in - * microseconds cannot be represented by an int64 (a date before year -290307 or - * after year 294246). The result does not depend on the location associated - * with t. - */ - unixMicro(): number - } - interface Time { - /** - * UnixNano returns t as a Unix time, the number of nanoseconds elapsed - * since January 1, 1970 UTC. The result is undefined if the Unix time - * in nanoseconds cannot be represented by an int64 (a date before the year - * 1678 or after 2262). Note that this means the result of calling UnixNano - * on the zero Time is undefined. The result does not depend on the - * location associated with t. - */ - unixNano(): number - } - interface Time { - /** - * MarshalBinary implements the encoding.BinaryMarshaler interface. - */ - marshalBinary(): string - } - interface Time { - /** - * UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. - */ - unmarshalBinary(data: string): void + genZshCompletion(w: io.Writer): void } - interface Time { + interface Command { /** - * GobEncode implements the gob.GobEncoder interface. + * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. */ - gobEncode(): string + genZshCompletionFileNoDesc(filename: string): void } - interface Time { + interface Command { /** - * GobDecode implements the gob.GobDecoder interface. + * GenZshCompletionNoDesc generates zsh completion file without descriptions + * and writes it to the passed writer. */ - gobDecode(data: string): void + genZshCompletionNoDesc(w: io.Writer): void } - interface Time { + interface Command { /** - * MarshalJSON implements the json.Marshaler interface. - * The time is a quoted string in RFC 3339 format, with sub-second precision added if present. + * 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 */ - marshalJSON(): string + markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void } - interface Time { + interface Command { /** - * UnmarshalJSON implements the json.Unmarshaler interface. - * The time is expected to be a quoted string in RFC 3339 format. + * 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 */ - unmarshalJSON(data: string): void + markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void } - interface Time { - /** - * MarshalText implements the encoding.TextMarshaler interface. - * The time is formatted in RFC 3339 format, with sub-second precision added if present. - */ - marshalText(): string +} + +namespace migrate { + /** + * MigrationsList defines a list with migration definitions + */ + interface MigrationsList { } - interface Time { + interface MigrationsList { /** - * UnmarshalText implements the encoding.TextUnmarshaler interface. - * The time is expected to be in RFC 3339 format. + * Item returns a single migration from the list by its index. */ - unmarshalText(data: string): void + item(index: number): (Migration | undefined) } - interface Time { + interface MigrationsList { /** - * IsDST reports whether the time in the configured location is in Daylight Savings Time. + * Items returns the internal migrations list slice. */ - isDST(): boolean + items(): Array<(Migration | undefined)> } - interface Time { + interface MigrationsList { /** - * Truncate returns the result of rounding t down to a multiple of d (since the zero time). - * If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. + * Register adds new migration definition to the list. * - * Truncate operates on the time as an absolute duration since the - * zero time; it does not operate on the presentation form of the - * time. Thus, Truncate(Hour) may return a time with a non-zero - * minute, depending on the time's Location. - */ - truncate(d: Duration): Time - } - interface Time { - /** - * Round returns the result of rounding t to the nearest multiple of d (since the zero time). - * The rounding behavior for halfway values is to round up. - * If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. + * If `optFilename` is not provided, it will try to get the name from its .go file. * - * Round operates on the time as an absolute duration since the - * zero time; it does not operate on the presentation form of the - * time. Thus, Round(Hour) may return a time with a non-zero - * minute, depending on the time's Location. + * The list will be sorted automatically based on the migrations file name. */ - round(d: Duration): Time + register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void } } -/** - * Package context defines the Context type, which carries deadlines, - * cancellation signals, and other request-scoped values across API boundaries - * and between processes. - * - * Incoming requests to a server should create a Context, and outgoing - * calls to servers should accept a Context. The chain of function - * calls between them must propagate the Context, optionally replacing - * it with a derived Context created using WithCancel, WithDeadline, - * WithTimeout, or WithValue. When a Context is canceled, all - * Contexts derived from it are also canceled. - * - * The WithCancel, WithDeadline, and WithTimeout functions take a - * Context (the parent) and return a derived Context (the child) and a - * CancelFunc. Calling the CancelFunc cancels the child and its - * children, removes the parent's reference to the child, and stops - * any associated timers. Failing to call the CancelFunc leaks the - * child and its children until the parent is canceled or the timer - * fires. The go vet tool checks that CancelFuncs are used on all - * control-flow paths. - * - * Programs that use Contexts should follow these rules to keep interfaces - * consistent across packages and enable static analysis tools to check context - * propagation: - * - * Do not store Contexts inside a struct type; instead, pass a Context - * explicitly to each function that needs it. The Context should be the first - * parameter, typically named ctx: - * - * ``` - * func DoSomething(ctx context.Context, arg Arg) error { - * // ... use ctx ... - * } - * ``` - * - * Do not pass a nil Context, even if a function permits it. Pass context.TODO - * if you are unsure about which Context to use. - * - * Use context Values only for request-scoped data that transits processes and - * APIs, not for passing optional parameters to functions. - * - * The same Context may be passed to functions running in different goroutines; - * Contexts are safe for simultaneous use by multiple goroutines. - * - * See https://blog.golang.org/context for example code for a server that uses - * Contexts. - */ -namespace context { -} - /** * Package io provides basic interfaces to I/O primitives. * Its primary job is to wrap existing implementations of such primitives, @@ -11501,2505 +10991,2294 @@ namespace io { } /** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. - */ -namespace fs { - /** - * A File provides access to a single file. - * The File interface is the minimum implementation required of the file. - * Directory files should also implement ReadDirFile. - * A file may implement io.ReaderAt or io.Seeker as optimizations. - */ - interface File { - stat(): FileInfo - read(_arg0: string): number - close(): void - } -} - -/** - * Package driver defines interfaces to be implemented by database - * drivers as used by package sql. + * Package time provides functionality for measuring and displaying time. * - * Most code should use package sql. + * The calendrical calculations always assume a Gregorian calendar, with + * no leap seconds. * - * The driver interface has evolved over time. Drivers should implement - * Connector and DriverContext interfaces. - * The Connector.Connect and Driver.Open methods should never return ErrBadConn. - * ErrBadConn should only be returned from Validator, SessionResetter, or - * a query method if the connection is already in an invalid (e.g. closed) state. + * Monotonic Clocks * - * All Conn implementations should implement the following interfaces: - * Pinger, SessionResetter, and Validator. + * Operating systems provide both a “wall clock,” which is subject to + * changes for clock synchronization, and a “monotonic clock,” which is + * not. The general rule is that the wall clock is for telling time and + * the monotonic clock is for measuring time. Rather than split the API, + * in this package the Time returned by time.Now contains both a wall + * clock reading and a monotonic clock reading; later time-telling + * operations use the wall clock reading, but later time-measuring + * operations, specifically comparisons and subtractions, use the + * monotonic clock reading. * - * If named parameters or context are supported, the driver's Conn should implement: - * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * For example, this code always computes a positive elapsed time of + * approximately 20 milliseconds, even if the wall clock is changed during + * the operation being timed: * - * To support custom data types, implement NamedValueChecker. NamedValueChecker - * also allows queries to accept per-query options as a parameter by returning - * ErrRemoveArgument from CheckNamedValue. + * ``` + * start := time.Now() + * ... operation that takes 20 milliseconds ... + * t := time.Now() + * elapsed := t.Sub(start) + * ``` * - * If multiple result sets are supported, Rows should implement RowsNextResultSet. - * If the driver knows how to describe the types present in the returned result - * it should implement the following interfaces: RowsColumnTypeScanType, - * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, - * and RowsColumnTypePrecisionScale. A given row value may also return a Rows - * type, which may represent a database cursor value. + * Other idioms, such as time.Since(start), time.Until(deadline), and + * time.Now().Before(deadline), are similarly robust against wall clock + * resets. * - * Before a connection is returned to the connection pool after use, IsValid is - * called if implemented. Before a connection is reused for another query, - * ResetSession is called if implemented. If a connection is never returned to the - * connection pool but immediately reused, then ResetSession is called prior to - * reuse but IsValid is not called. + * The rest of this section gives the precise details of how operations + * use monotonic clocks, but understanding those details is not required + * to use this package. + * + * The Time returned by time.Now contains a monotonic clock reading. + * If Time t has a monotonic clock reading, t.Add adds the same duration to + * both the wall clock and monotonic clock readings to compute the result. + * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time + * computations, they always strip any monotonic clock reading from their results. + * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation + * of the wall time, they also strip any monotonic clock reading from their results. + * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). + * + * If Times t and u both contain monotonic clock readings, the operations + * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out + * using the monotonic clock readings alone, ignoring the wall clock + * readings. If either t or u contains no monotonic clock reading, these + * operations fall back to using the wall clock readings. + * + * On some systems the monotonic clock will stop if the computer goes to sleep. + * On such a system, t.Sub(u) may not accurately reflect the actual + * time that passed between t and u. + * + * Because the monotonic clock reading has no meaning outside + * the current process, the serialized forms generated by t.GobEncode, + * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic + * clock reading, and t.Format provides no format for it. Similarly, the + * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, + * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. + * t.UnmarshalJSON, and t.UnmarshalText always create times with + * no monotonic clock reading. + * + * Note that the Go == operator compares not just the time instant but + * also the Location and the monotonic clock reading. See the + * documentation for the Time type for a discussion of equality + * testing for Time values. + * + * For debugging, the result of t.String does include the monotonic + * clock reading if present. If t != u because of different monotonic clock readings, + * that difference will be visible when printing t.String() and u.String(). */ -namespace driver { - /** - * Value is a value that drivers must be able to handle. - * It is either nil, a type handled by a database driver's NamedValueChecker - * interface, or an instance of one of these types: - * - * ``` - * int64 - * float64 - * bool - * []byte - * string - * time.Time - * ``` - * - * If the driver supports cursors, a returned Value may also implement the Rows interface - * in this package. This is used, for example, when a user selects a cursor - * such as "select cursor(select * from my_table) from dual". If the Rows - * from the select is closed, the cursor Rows will also be closed. - */ - interface Value extends _TygojaAny{} - /** - * Driver is the interface that must be implemented by a database - * driver. - * - * Database drivers may implement DriverContext for access - * to contexts and to parse the name only once for a pool of connections, - * instead of once per connection. - */ - interface Driver { +namespace time { + interface Time { /** - * Open returns a new connection to the database. - * The name is a string in a driver-specific format. + * String returns the time formatted using the format string + * ``` + * "2006-01-02 15:04:05.999999999 -0700 MST" + * ``` * - * Open may return a cached connection (one previously - * closed), but doing so is unnecessary; the sql package - * maintains a pool of idle connections for efficient re-use. + * If the time has a monotonic clock reading, the returned string + * includes a final field "m=±", where value is the monotonic + * clock reading formatted as a decimal number of seconds. * - * The returned connection is only used by one goroutine at a - * time. + * The returned string is meant for debugging; for a stable serialized + * representation, use t.MarshalText, t.MarshalBinary, or t.Format + * with an explicit format string. */ - open(name: string): Conn + string(): string } -} - -/** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. - * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. - * - * Drivers that do not support context cancellation will not return until - * after the query is completed. - * - * For usage examples, see the wiki page at - * https://golang.org/s/sqlwiki. - */ -namespace sql { - /** - * IsolationLevel is the transaction isolation level used in TxOptions. - */ - interface IsolationLevel extends Number{} - interface IsolationLevel { + interface Time { /** - * String returns the name of the transaction isolation level. + * GoString implements fmt.GoStringer and formats t to be printed in Go source + * code. */ - string(): string + goString(): string } - /** - * DBStats contains database statistics. - */ - interface DBStats { - maxOpenConnections: number // Maximum number of open connections to the database. + interface Time { /** - * Pool Status + * Format returns a textual representation of the time value formatted according + * to the layout defined by the argument. See the documentation for the + * constant called Layout to see how to represent the layout format. + * + * The executable example for Time.Format demonstrates the working + * of the layout string in detail and is a good reference. */ - 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. + format(layout: string): string + } + interface Time { /** - * Counters + * AppendFormat is like Format but appends the textual + * representation to b and returns the extended buffer. */ - 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. + appendFormat(b: string, layout: string): string } /** - * 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 Time represents an instant in time with nanosecond precision. * - * A Conn must call Close to return the connection to the database pool - * and may do so concurrently with a running query. + * Programs using times should typically store and pass them as values, + * not pointers. That is, time variables and struct fields should be of + * type time.Time, not *time.Time. * - * After a call to Close, all operations on the - * connection fail with ErrConnDone. + * A Time value can be used by multiple goroutines simultaneously except + * that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and + * UnmarshalText are not concurrency-safe. + * + * Time instants can be compared using the Before, After, and Equal methods. + * The Sub method subtracts two instants, producing a Duration. + * The Add method adds a Time and a Duration, producing a Time. + * + * The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. + * As this time is unlikely to come up in practice, the IsZero method gives + * a simple way of detecting a time that has not been initialized explicitly. + * + * Each Time has associated with it a Location, consulted when computing the + * presentation form of the time, such as in the Format, Hour, and Year methods. + * The methods Local, UTC, and In return a Time with a specific location. + * Changing the location in this way changes only the presentation; it does not + * change the instant in time being denoted and therefore does not affect the + * computations described in earlier paragraphs. + * + * Representations of a Time value saved by the GobEncode, MarshalBinary, + * MarshalJSON, and MarshalText methods store the Time.Location's offset, but not + * the location name. They therefore lose information about Daylight Saving Time. + * + * In addition to the required “wall clock” reading, a Time may contain an optional + * reading of the current process's monotonic clock, to provide additional precision + * for comparison or subtraction. + * See the “Monotonic Clocks” section in the package documentation for details. + * + * Note that the Go == operator compares not just the time instant but also the + * Location and the monotonic clock reading. Therefore, Time values should not + * be used as map or database keys without first guaranteeing that the + * identical Location has been set for all values, which can be achieved + * through use of the UTC or Local method, and that the monotonic clock reading + * has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) + * to t == u, since t.Equal uses the most accurate comparison available and + * correctly handles the case when only one of its arguments has a monotonic + * clock reading. */ - interface Conn { + interface Time { } - interface Conn { + interface Time { /** - * PingContext verifies the connection to the database is still alive. + * After reports whether the time instant t is after u. */ - pingContext(ctx: context.Context): void + after(u: Time): boolean } - interface Conn { + interface Time { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * Before reports whether the time instant t is before u. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + before(u: Time): boolean } - interface Conn { + interface Time { /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) - } - interface Conn { + * Equal reports whether t and u represent the same time instant. + * Two times can be equal even if they are in different locations. + * For example, 6:00 +0200 and 4:00 UTC are Equal. + * See the documentation on the Time type for the pitfalls of using == with + * Time values; most code should use Equal instead. + */ + equal(u: Time): boolean + } + interface Time { /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * IsZero reports whether t represents the zero time instant, + * January 1, year 1, 00:00:00 UTC. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + isZero(): boolean } - interface Conn { + interface Time { /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * Date returns the year, month, and day in which t occurs. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + date(): [number, Month, number] } - interface Conn { + interface Time { /** - * Raw executes f exposing the underlying driver connection for the - * duration of f. The driverConn must not be used outside of f. - * - * Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable - * until Conn.Close is called. + * Year returns the year in which t occurs. */ - raw(f: (driverConn: any) => void): void + year(): number } - interface Conn { + interface Time { /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. Tx.Commit will return an error if the context provided to - * BeginTx is canceled. - * - * The provided TxOptions is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. + * Month returns the month of the year specified by t. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) + month(): Month } - interface Conn { + interface Time { /** - * Close returns the connection to the connection pool. - * All operations after a Close will return with ErrConnDone. - * Close is safe to call concurrently with other operations and will - * block until all other operations finish. It may be useful to first - * cancel any used context and then call close directly after. + * Day returns the day of the month specified by t. */ - close(): void + day(): number } - /** - * ColumnType contains the name and type of a column. - */ - interface ColumnType { + interface Time { + /** + * Weekday returns the day of the week specified by t. + */ + weekday(): Weekday } - interface ColumnType { + interface Time { /** - * Name returns the name or alias of the column. + * ISOWeek returns the ISO 8601 year and week number in which t occurs. + * Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to + * week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 + * of year n+1. */ - name(): string + isoWeek(): number } - interface ColumnType { + interface Time { /** - * Length returns the column type length for variable length column types such - * as text and binary field types. If the type length is unbounded the value will - * be math.MaxInt64 (any database limits will still apply). - * If the column type is not variable length, such as an int, or if not supported - * by the driver ok is false. + * Clock returns the hour, minute, and second within the day specified by t. */ - length(): [number, boolean] + clock(): number } - interface ColumnType { + interface Time { /** - * DecimalSize returns the scale and precision of a decimal type. - * If not applicable or if not supported ok is false. + * Hour returns the hour within the day specified by t, in the range [0, 23]. */ - decimalSize(): [number, boolean] + hour(): number } - interface ColumnType { + interface Time { /** - * 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. + * Minute returns the minute offset within the hour specified by t, in the range [0, 59]. */ - scanType(): reflect.Type + minute(): number } - interface ColumnType { + interface Time { /** - * Nullable reports whether the column may be null. - * If a driver does not support this property ok will be false. + * Second returns the second offset within the minute specified by t, in the range [0, 59]. */ - nullable(): boolean + second(): number } - interface ColumnType { + interface Time { /** - * 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". + * Nanosecond returns the nanosecond offset within the second specified by t, + * in the range [0, 999999999]. */ - databaseTypeName(): string + nanosecond(): number } - /** - * Row is the result of calling QueryRow to select a single row. - */ - interface Row { + interface Time { + /** + * YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, + * and [1,366] in leap years. + */ + yearDay(): number } - interface Row { + interface Time { /** - * 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. + * Add returns the time t+d. */ - scan(...dest: any[]): void + add(d: Duration): Time } - interface Row { + interface Time { /** - * 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. + * Sub returns the duration t-u. If the result exceeds the maximum (or minimum) + * value that can be stored in a Duration, the maximum (or minimum) duration + * will be returned. + * To compute t-d for a duration d, use t.Add(-d). */ - err(): void + sub(u: Time): Duration } -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * A URL represents a parsed URL (technically, a URI reference). - * - * The general form represented is: - * - * ``` - * [scheme:][//[userinfo@]host][/]path[?query][#fragment] - * ``` - * - * URLs that do not start with a slash after the scheme are interpreted as: - * - * ``` - * scheme:opaque[?query][#fragment] - * ``` - * - * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. - * A consequence is that it is impossible to tell which slashes in the Path were - * slashes in the raw URL and which were %2f. This distinction is rarely important, - * but when it is, the code should use RawPath, an optional field which only gets - * set if the default encoding is different from Path. - * - * URL's String method uses the EscapedPath method to obtain the path. See the - * EscapedPath method for more details. - */ - interface URL { - scheme: string - opaque: string // encoded opaque data - user?: Userinfo // username and password information - host: string // host or host:port - path: string // path (relative paths may omit leading slash) - rawPath: string // encoded path hint (see EscapedPath method) - forceQuery: boolean // append a query ('?') even if RawQuery is empty - rawQuery: string // encoded query values, without '?' - fragment: string // fragment for references, without '#' - rawFragment: string // encoded fragment hint (see EscapedFragment method) + interface Time { + /** + * AddDate returns the time corresponding to adding the + * given number of years, months, and days to t. + * For example, AddDate(-1, 2, 3) applied to January 1, 2011 + * returns March 4, 2010. + * + * AddDate normalizes its result in the same way that Date does, + * so, for example, adding one month to October 31 yields + * December 1, the normalized form for November 31. + */ + addDate(years: number, months: number, days: number): Time } - interface URL { + interface Time { /** - * EscapedPath returns the escaped form of u.Path. - * In general there are multiple possible escaped forms of any path. - * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. - * Otherwise EscapedPath ignores u.RawPath and computes an escaped - * form on its own. - * The String and RequestURI methods use EscapedPath to construct - * their results. - * In general, code should call EscapedPath instead of - * reading u.RawPath directly. + * UTC returns t with the location set to UTC. */ - escapedPath(): string + utc(): Time } - interface URL { + interface Time { /** - * EscapedFragment returns the escaped form of u.Fragment. - * In general there are multiple possible escaped forms of any fragment. - * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. - * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped - * form on its own. - * The String method uses EscapedFragment to construct its result. - * In general, code should call EscapedFragment instead of - * reading u.RawFragment directly. + * Local returns t with the location set to local time. */ - escapedFragment(): string + local(): Time } - interface URL { + interface Time { /** - * String reassembles the URL into a valid URL string. - * The general form of the result is one of: - * - * ``` - * scheme:opaque?query#fragment - * scheme://userinfo@host/path?query#fragment - * ``` + * In returns a copy of t representing the same time instant, but + * with the copy's location information set to loc for display + * purposes. * - * If u.Opaque is non-empty, String uses the first form; - * otherwise it uses the second form. - * Any non-ASCII characters in host are escaped. - * To obtain the path, String uses u.EscapedPath(). - * - * In the second form, the following rules apply: - * ``` - * - if u.Scheme is empty, scheme: is omitted. - * - if u.User is nil, userinfo@ is omitted. - * - if u.Host is empty, host/ is omitted. - * - if u.Scheme and u.Host are empty and u.User is nil, - * the entire scheme://userinfo@host/ is omitted. - * - if u.Host is non-empty and u.Path begins with a /, - * the form host/path does not add its own /. - * - if u.RawQuery is empty, ?query is omitted. - * - if u.Fragment is empty, #fragment is omitted. - * ``` + * In panics if loc is nil. */ - string(): string + in(loc: Location): Time } - interface URL { + interface Time { /** - * Redacted is like String but replaces any password with "xxxxx". - * Only the password in u.URL is redacted. + * Location returns the time zone information associated with t. */ - redacted(): string + location(): (Location | undefined) } - /** - * Values maps a string key to a list of values. - * It is typically used for query parameters and form values. - * Unlike in the http.Header map, the keys in a Values map - * are case-sensitive. - */ - interface Values extends _TygojaDict{} - interface Values { + interface Time { /** - * Get gets the first value associated with the given key. - * If there are no values associated with the key, Get returns - * the empty string. To access multiple values, use the map - * directly. + * Zone computes the time zone in effect at time t, returning the abbreviated + * name of the zone (such as "CET") and its offset in seconds east of UTC. */ - get(key: string): string + zone(): [string, number] } - interface Values { + interface Time { /** - * Set sets the key to value. It replaces any existing - * values. + * Unix returns t as a Unix time, the number of seconds elapsed + * since January 1, 1970 UTC. The result does not depend on the + * location associated with t. + * Unix-like operating systems often record time as a 32-bit + * count of seconds, but since the method here returns a 64-bit + * value it is valid for billions of years into the past or future. */ - set(key: string): void + unix(): number } - interface Values { + interface Time { /** - * Add adds the value to key. It appends to any existing - * values associated with key. + * UnixMilli returns t as a Unix time, the number of milliseconds elapsed since + * January 1, 1970 UTC. The result is undefined if the Unix time in + * milliseconds cannot be represented by an int64 (a date more than 292 million + * years before or after 1970). The result does not depend on the + * location associated with t. */ - add(key: string): void + unixMilli(): number } - interface Values { + interface Time { /** - * Del deletes the values associated with key. + * UnixMicro returns t as a Unix time, the number of microseconds elapsed since + * January 1, 1970 UTC. The result is undefined if the Unix time in + * microseconds cannot be represented by an int64 (a date before year -290307 or + * after year 294246). The result does not depend on the location associated + * with t. */ - del(key: string): void + unixMicro(): number } - interface Values { + interface Time { /** - * Has checks whether a given key is set. + * UnixNano returns t as a Unix time, the number of nanoseconds elapsed + * since January 1, 1970 UTC. The result is undefined if the Unix time + * in nanoseconds cannot be represented by an int64 (a date before the year + * 1678 or after 2262). Note that this means the result of calling UnixNano + * on the zero Time is undefined. The result does not depend on the + * location associated with t. */ - has(key: string): boolean + unixNano(): number } - interface Values { + interface Time { /** - * Encode encodes the values into ``URL encoded'' form - * ("bar=baz&foo=quux") sorted by key. + * MarshalBinary implements the encoding.BinaryMarshaler interface. */ - encode(): string + marshalBinary(): string } - interface URL { + interface Time { /** - * IsAbs reports whether the URL is absolute. - * Absolute means that it has a non-empty scheme. + * UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. */ - isAbs(): boolean + unmarshalBinary(data: string): void } - interface URL { + interface Time { /** - * Parse parses a URL in the context of the receiver. The provided URL - * may be relative or absolute. Parse returns nil, err on parse - * failure, otherwise its return value is the same as ResolveReference. + * GobEncode implements the gob.GobEncoder interface. */ - parse(ref: string): (URL | undefined) + gobEncode(): string } - interface URL { + interface Time { /** - * ResolveReference resolves a URI reference to an absolute URI from - * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference - * may be relative or absolute. ResolveReference always returns a new - * URL instance, even if the returned URL is identical to either the - * base or reference. If ref is an absolute URL, then ResolveReference - * ignores base and returns a copy of ref. + * GobDecode implements the gob.GobDecoder interface. */ - resolveReference(ref: URL): (URL | undefined) + gobDecode(data: string): void } - interface URL { + interface Time { /** - * Query parses RawQuery and returns the corresponding values. - * It silently discards malformed value pairs. - * To check errors use ParseQuery. + * MarshalJSON implements the json.Marshaler interface. + * The time is a quoted string in RFC 3339 format, with sub-second precision added if present. */ - query(): Values + marshalJSON(): string } - interface URL { + interface Time { /** - * RequestURI returns the encoded path?query or opaque?query - * string that would be used in an HTTP request for u. + * UnmarshalJSON implements the json.Unmarshaler interface. + * The time is expected to be a quoted string in RFC 3339 format. */ - requestURI(): string + unmarshalJSON(data: string): void } - interface URL { + interface Time { /** - * Hostname returns u.Host, stripping any valid port number if present. - * - * If the result is enclosed in square brackets, as literal IPv6 addresses are, - * the square brackets are removed from the result. + * MarshalText implements the encoding.TextMarshaler interface. + * The time is formatted in RFC 3339 format, with sub-second precision added if present. */ - hostname(): string + marshalText(): string } - interface URL { + interface Time { /** - * Port returns the port part of u.Host, without the leading colon. - * - * If u.Host doesn't contain a valid numeric port, Port returns an empty string. + * UnmarshalText implements the encoding.TextUnmarshaler interface. + * The time is expected to be in RFC 3339 format. */ - port(): string + unmarshalText(data: string): void } - interface URL { - marshalBinary(): string + interface Time { + /** + * IsDST reports whether the time in the configured location is in Daylight Savings Time. + */ + isDST(): boolean } - interface URL { - unmarshalBinary(text: string): void + interface Time { + /** + * Truncate returns the result of rounding t down to a multiple of d (since the zero time). + * If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. + * + * Truncate operates on the time as an absolute duration since the + * zero time; it does not operate on the presentation form of the + * time. Thus, Truncate(Hour) may return a time with a non-zero + * minute, depending on the time's Location. + */ + truncate(d: Duration): Time + } + interface Time { + /** + * Round returns the result of rounding t to the nearest multiple of d (since the zero time). + * The rounding behavior for halfway values is to round up. + * If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. + * + * Round operates on the time as an absolute duration since the + * zero time; it does not operate on the presentation form of the + * time. Thus, Round(Hour) may return a time with a non-zero + * minute, depending on the time's Location. + */ + round(d: Duration): Time } } -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + */ +namespace fs { + /** + * A File provides access to a single file. + * The File interface is the minimum implementation required of the file. + * Directory files should also implement ReadDirFile. + * A file may implement io.ReaderAt or io.Seeker as optimizations. + */ + interface File { + stat(): FileInfo + read(_arg0: string): number + close(): void } } /** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force cgo resolver - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. + * Package log implements a simple logging package. It defines a type, Logger, + * with methods for formatting output. It also has a predefined 'standard' + * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and + * Panic[f|ln], which are easier to use than creating a Logger manually. + * That logger writes to standard error and prints the date and time + * of each logged message. + * Every log message is output on a separate line: if the message being + * printed does not end in a newline, the logger will add one. + * The Fatal functions call os.Exit(1) after writing the log message. + * The Panic functions call panic after writing the log message. */ -namespace net { +namespace log { /** - * Conn is a generic stream-oriented network connection. - * - * Multiple goroutines may invoke methods on a Conn simultaneously. + * A Logger represents an active logging object that generates lines of + * output to an io.Writer. Each logging operation makes a single call to + * the Writer's Write method. A Logger can be used simultaneously from + * multiple goroutines; it guarantees to serialize access to the Writer. */ - interface Conn { - /** - * Read reads data from the connection. - * Read can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetReadDeadline. - */ - read(b: string): number - /** - * Write writes data to the connection. - * Write can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetWriteDeadline. - */ - write(b: string): number - /** - * Close closes the connection. - * Any blocked Read or Write operations will be unblocked and return errors. - */ - close(): void - /** - * LocalAddr returns the local network address, if known. - */ - localAddr(): Addr - /** - * RemoteAddr returns the remote network address, if known. - */ - remoteAddr(): Addr - /** - * SetDeadline sets the read and write deadlines associated - * with the connection. It is equivalent to calling both - * SetReadDeadline and SetWriteDeadline. - * - * A deadline is an absolute time after which I/O operations - * fail instead of blocking. The deadline applies to all future - * and pending I/O, not just the immediately following call to - * Read or Write. After a deadline has been exceeded, the - * connection can be refreshed by setting a deadline in the future. - * - * If the deadline is exceeded a call to Read or Write or to other - * I/O methods will return an error that wraps os.ErrDeadlineExceeded. - * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). - * The error's Timeout method will return true, but note that there - * are other possible errors for which the Timeout method will - * return true even if the deadline has not been exceeded. - * - * An idle timeout can be implemented by repeatedly extending - * the deadline after successful Read or Write calls. - * - * A zero value for t means I/O operations will not time out. - */ - setDeadline(t: time.Time): void - /** - * SetReadDeadline sets the deadline for future Read calls - * and any currently-blocked Read call. - * A zero value for t means Read will not time out. - */ - setReadDeadline(t: time.Time): void + interface Logger { + } + interface Logger { /** - * SetWriteDeadline sets the deadline for future Write calls - * and any currently-blocked Write call. - * Even if write times out, it may return n > 0, indicating that - * some of the data was successfully written. - * A zero value for t means Write will not time out. + * SetOutput sets the output destination for the logger. */ - setWriteDeadline(t: time.Time): void + setOutput(w: io.Writer): void } - /** - * A Listener is a generic network listener for stream-oriented protocols. - * - * Multiple goroutines may invoke methods on a Listener simultaneously. - */ - interface Listener { + interface Logger { /** - * Accept waits for and returns the next connection to the listener. + * Output writes the output for a logging event. The string s contains + * the text to print after the prefix specified by the flags of the + * Logger. A newline is appended if the last character of s is not + * already a newline. Calldepth is used to recover the PC and is + * provided for generality, although at the moment on all pre-defined + * paths it will be 2. */ - accept(): Conn + output(calldepth: number, s: string): void + } + interface Logger { /** - * Close closes the listener. - * Any blocked Accept operations will be unblocked and return errors. + * Printf calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Printf. */ - close(): void + printf(format: string, ...v: any[]): void + } + interface Logger { /** - * Addr returns the listener's network address. + * Print calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Print. */ - addr(): Addr + print(...v: any[]): void } -} - -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * ConnectionState records basic TLS details about the connection. - */ - interface ConnectionState { + interface Logger { /** - * Version is the TLS version used by the connection (e.g. VersionTLS12). + * Println calls l.Output to print to the logger. + * Arguments are handled in the manner of fmt.Println. */ - version: number + println(...v: any[]): void + } + interface Logger { /** - * HandshakeComplete is true if the handshake has concluded. + * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). */ - handshakeComplete: boolean + fatal(...v: any[]): void + } + interface Logger { /** - * DidResume is true if this connection was successfully resumed from a - * previous session with a session ticket or similar mechanism. + * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). */ - didResume: boolean + fatalf(format: string, ...v: any[]): void + } + interface Logger { /** - * CipherSuite is the cipher suite negotiated for the connection (e.g. - * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). + * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). */ - cipherSuite: number + fatalln(...v: any[]): void + } + interface Logger { /** - * NegotiatedProtocol is the application protocol negotiated with ALPN. + * Panic is equivalent to l.Print() followed by a call to panic(). */ - negotiatedProtocol: string + panic(...v: any[]): void + } + interface Logger { /** - * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. - * - * Deprecated: this value is always true. + * Panicf is equivalent to l.Printf() followed by a call to panic(). */ - negotiatedProtocolIsMutual: boolean + panicf(format: string, ...v: any[]): void + } + interface Logger { /** - * ServerName is the value of the Server Name Indication extension sent by - * the client. It's available both on the server and on the client side. + * Panicln is equivalent to l.Println() followed by a call to panic(). */ - serverName: string + panicln(...v: any[]): void + } + interface Logger { /** - * PeerCertificates are the parsed certificates sent by the peer, in the - * order in which they were sent. The first element is the leaf certificate - * that the connection is verified against. - * - * On the client side, it can't be empty. On the server side, it can be - * empty if Config.ClientAuth is not RequireAnyClientCert or - * RequireAndVerifyClientCert. + * Flags returns the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. */ - peerCertificates: Array<(x509.Certificate | undefined)> + flags(): number + } + interface Logger { /** - * VerifiedChains is a list of one or more chains where the first element is - * PeerCertificates[0] and the last element is from Config.RootCAs (on the - * client side) or Config.ClientCAs (on the server side). - * - * On the client side, it's set if Config.InsecureSkipVerify is false. On - * the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven - * (and the peer provided a certificate) or RequireAndVerifyClientCert. + * SetFlags sets the output flags for the logger. + * The flag bits are Ldate, Ltime, and so on. */ - verifiedChains: Array> + setFlags(flag: number): void + } + interface Logger { /** - * SignedCertificateTimestamps is a list of SCTs provided by the peer - * through the TLS handshake for the leaf certificate, if any. + * Prefix returns the output prefix for the logger. */ - signedCertificateTimestamps: Array + prefix(): string + } + interface Logger { /** - * OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) - * response provided by the peer for the leaf certificate, if any. + * SetPrefix sets the output prefix for the logger. */ - ocspResponse: string + setPrefix(prefix: string): void + } + interface Logger { /** - * TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, - * Section 3). This value will be nil for TLS 1.3 connections and for all - * resumed connections. - * - * Deprecated: there are conditions in which this value might not be unique - * to a connection. See the Security Considerations sections of RFC 5705 and - * RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings. + * Writer returns the output destination for the logger. */ - tlsUnique: string - } - interface ConnectionState { - /** - * ExportKeyingMaterial returns length bytes of exported key material in a new - * slice as defined in RFC 5705. If context is nil, it is not used as part of - * the seed. If the connection was set to allow renegotiation via - * Config.Renegotiation, this function will return an error. - */ - exportKeyingMaterial(label: string, context: string, length: number): string - } - /** - * A Config structure is used to configure a TLS client or server. - * After one has been passed to a TLS function it must not be - * modified. A Config may be reused; the tls package will also not - * modify it. - */ - interface Config { - /** - * Rand provides the source of entropy for nonces and RSA blinding. - * If Rand is nil, TLS uses the cryptographic random reader in package - * crypto/rand. - * The Reader must be safe for use by multiple goroutines. - */ - rand: io.Reader - /** - * Time returns the current time as the number of seconds since the epoch. - * If Time is nil, TLS uses time.Now. - */ - time: () => time.Time - /** - * Certificates contains one or more certificate chains to present to the - * other side of the connection. The first certificate compatible with the - * peer's requirements is selected automatically. - * - * Server configurations must set one of Certificates, GetCertificate or - * GetConfigForClient. Clients doing client-authentication may set either - * Certificates or GetClientCertificate. - * - * Note: if there are multiple Certificates, and they don't have the - * optional field Leaf set, certificate selection will incur a significant - * per-handshake performance cost. - */ - certificates: Array - /** - * NameToCertificate maps from a certificate name to an element of - * Certificates. Note that a certificate name can be of the form - * '*.example.com' and so doesn't have to be a domain name as such. - * - * Deprecated: NameToCertificate only allows associating a single - * certificate with a given name. Leave this field nil to let the library - * select the first compatible chain from Certificates. - */ - nameToCertificate: _TygojaDict - /** - * GetCertificate returns a Certificate based on the given - * ClientHelloInfo. It will only be called if the client supplies SNI - * information or if Certificates is empty. - * - * If GetCertificate is nil or returns nil, then the certificate is - * retrieved from NameToCertificate. If NameToCertificate is nil, the - * best element of Certificates will be used. - */ - getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) - /** - * GetClientCertificate, if not nil, is called when a server requests a - * certificate from a client. If set, the contents of Certificates will - * be ignored. - * - * If GetClientCertificate returns an error, the handshake will be - * aborted and that error will be returned. Otherwise - * GetClientCertificate must return a non-nil Certificate. If - * Certificate.Certificate is empty then no certificate will be sent to - * the server. If this is unacceptable to the server then it may abort - * the handshake. - * - * GetClientCertificate may be called multiple times for the same - * connection if renegotiation occurs or if TLS 1.3 is in use. - */ - getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) - /** - * GetConfigForClient, if not nil, is called after a ClientHello is - * received from a client. It may return a non-nil Config in order to - * change the Config that will be used to handle this connection. If - * the returned Config is nil, the original Config will be used. The - * Config returned by this callback may not be subsequently modified. - * - * If GetConfigForClient is nil, the Config passed to Server() will be - * used for all connections. - * - * If SessionTicketKey was explicitly set on the returned Config, or if - * SetSessionTicketKeys was called on the returned Config, those keys will - * be used. Otherwise, the original Config keys will be used (and possibly - * rotated if they are automatically managed). - */ - getConfigForClient: (_arg0: ClientHelloInfo) => (Config | undefined) - /** - * VerifyPeerCertificate, if not nil, is called after normal - * certificate verification by either a TLS client or server. It - * receives the raw ASN.1 certificates provided by the peer and also - * any verified chains that normal processing found. If it returns a - * non-nil error, the handshake is aborted and that error results. - * - * If normal verification fails then the handshake will abort before - * considering this callback. If normal verification is disabled by - * setting InsecureSkipVerify, or (for a server) when ClientAuth is - * RequestClientCert or RequireAnyClientCert, then this callback will - * be considered but the verifiedChains argument will always be nil. - */ - verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void - /** - * VerifyConnection, if not nil, is called after normal certificate - * verification and after VerifyPeerCertificate by either a TLS client - * or server. If it returns a non-nil error, the handshake is aborted - * and that error results. - * - * If normal verification fails then the handshake will abort before - * considering this callback. This callback will run for all connections - * regardless of InsecureSkipVerify or ClientAuth settings. - */ - verifyConnection: (_arg0: ConnectionState) => void - /** - * RootCAs defines the set of root certificate authorities - * that clients use when verifying server certificates. - * If RootCAs is nil, TLS uses the host's root CA set. - */ - rootCAs?: x509.CertPool - /** - * NextProtos is a list of supported application level protocols, in - * order of preference. If both peers support ALPN, the selected - * protocol will be one from this list, and the connection will fail - * if there is no mutually supported protocol. If NextProtos is empty - * or the peer doesn't support ALPN, the connection will succeed and - * ConnectionState.NegotiatedProtocol will be empty. - */ - nextProtos: Array - /** - * ServerName is used to verify the hostname on the returned - * certificates unless InsecureSkipVerify is given. It is also included - * in the client's handshake to support virtual hosting unless it is - * an IP address. - */ - serverName: string - /** - * ClientAuth determines the server's policy for - * TLS Client Authentication. The default is NoClientCert. - */ - clientAuth: ClientAuthType - /** - * ClientCAs defines the set of root certificate authorities - * that servers use if required to verify a client certificate - * by the policy in ClientAuth. - */ - clientCAs?: x509.CertPool - /** - * InsecureSkipVerify controls whether a client verifies the server's - * certificate chain and host name. If InsecureSkipVerify is true, crypto/tls - * accepts any certificate presented by the server and any host name in that - * certificate. In this mode, TLS is susceptible to machine-in-the-middle - * attacks unless custom verification is used. This should be used only for - * testing or in combination with VerifyConnection or VerifyPeerCertificate. - */ - insecureSkipVerify: boolean - /** - * CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of - * the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. - * - * If CipherSuites is nil, a safe default list is used. The default cipher - * suites might change over time. - */ - cipherSuites: Array - /** - * PreferServerCipherSuites is a legacy field and has no effect. - * - * It used to control whether the server would follow the client's or the - * server's preference. Servers now select the best mutually supported - * cipher suite based on logic that takes into account inferred client - * hardware, server hardware, and security. - * - * Deprecated: PreferServerCipherSuites is ignored. - */ - preferServerCipherSuites: boolean - /** - * SessionTicketsDisabled may be set to true to disable session ticket and - * PSK (resumption) support. Note that on clients, session ticket support is - * also disabled if ClientSessionCache is nil. - */ - sessionTicketsDisabled: boolean - /** - * SessionTicketKey is used by TLS servers to provide session resumption. - * See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled - * with random data before the first server handshake. - * - * Deprecated: if this field is left at zero, session ticket keys will be - * automatically rotated every day and dropped after seven days. For - * customizing the rotation schedule or synchronizing servers that are - * terminating connections for the same host, use SetSessionTicketKeys. - */ - sessionTicketKey: string - /** - * ClientSessionCache is a cache of ClientSessionState entries for TLS - * session resumption. It is only used by clients. - */ - clientSessionCache: ClientSessionCache - /** - * MinVersion contains the minimum TLS version that is acceptable. - * - * By default, TLS 1.2 is currently used as the minimum when acting as a - * client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum - * supported by this package, both as a client and as a server. - * - * The client-side default can temporarily be reverted to TLS 1.0 by - * including the value "x509sha1=1" in the GODEBUG environment variable. - * Note that this option will be removed in Go 1.19 (but it will still be - * possible to set this field to VersionTLS10 explicitly). - */ - minVersion: number - /** - * MaxVersion contains the maximum TLS version that is acceptable. - * - * By default, the maximum version supported by this package is used, - * which is currently TLS 1.3. - */ - maxVersion: number - /** - * CurvePreferences contains the elliptic curves that will be used in - * an ECDHE handshake, in preference order. If empty, the default will - * be used. The client will use the first preference as the type for - * its key share in TLS 1.3. This may change in the future. - */ - curvePreferences: Array - /** - * DynamicRecordSizingDisabled disables adaptive sizing of TLS records. - * When true, the largest possible TLS record size is always used. When - * false, the size of TLS records may be adjusted in an attempt to - * improve latency. - */ - dynamicRecordSizingDisabled: boolean - /** - * Renegotiation controls what types of renegotiation are supported. - * The default, none, is correct for the vast majority of applications. - */ - renegotiation: RenegotiationSupport - /** - * KeyLogWriter optionally specifies a destination for TLS master secrets - * in NSS key log format that can be used to allow external programs - * such as Wireshark to decrypt TLS connections. - * See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. - * Use of KeyLogWriter compromises security and should only be - * used for debugging. - */ - keyLogWriter: io.Writer - } - interface Config { - /** - * Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is - * being used concurrently by a TLS client or server. - */ - clone(): (Config | undefined) - } - interface Config { - /** - * SetSessionTicketKeys updates the session ticket keys for a server. - * - * The first key will be used when creating new tickets, while all keys can be - * used for decrypting tickets. It is safe to call this function while the - * server is running in order to rotate the session ticket keys. The function - * will panic if keys is empty. - * - * Calling this function will turn off automatic session ticket key rotation. - * - * If multiple servers are terminating connections for the same host they should - * all have the same session ticket keys. If the session ticket keys leaks, - * previously recorded and future TLS connections using those keys might be - * compromised. - */ - setSessionTicketKeys(keys: Array): void - } - interface Config { - /** - * BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate - * from the CommonName and SubjectAlternateName fields of each of the leaf - * certificates. - * - * Deprecated: NameToCertificate only allows associating a single certificate - * with a given name. Leave that field nil to let the library select the first - * compatible chain from Certificates. - */ - buildNameToCertificate(): void + writer(): io.Writer } } /** - * Package log implements a simple logging package. It defines a type, Logger, - * with methods for formatting output. It also has a predefined 'standard' - * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and - * Panic[f|ln], which are easier to use than creating a Logger manually. - * That logger writes to standard error and prints the date and time - * of each logged message. - * Every log message is output on a separate line: if the message being - * printed does not end in a newline, the logger will add one. - * The Fatal functions call os.Exit(1) after writing the log message. - * The Panic functions call panic after writing the log message. + * Package context defines the Context type, which carries deadlines, + * cancellation signals, and other request-scoped values across API boundaries + * and between processes. + * + * Incoming requests to a server should create a Context, and outgoing + * calls to servers should accept a Context. The chain of function + * calls between them must propagate the Context, optionally replacing + * it with a derived Context created using WithCancel, WithDeadline, + * WithTimeout, or WithValue. When a Context is canceled, all + * Contexts derived from it are also canceled. + * + * The WithCancel, WithDeadline, and WithTimeout functions take a + * Context (the parent) and return a derived Context (the child) and a + * CancelFunc. Calling the CancelFunc cancels the child and its + * children, removes the parent's reference to the child, and stops + * any associated timers. Failing to call the CancelFunc leaks the + * child and its children until the parent is canceled or the timer + * fires. The go vet tool checks that CancelFuncs are used on all + * control-flow paths. + * + * Programs that use Contexts should follow these rules to keep interfaces + * consistent across packages and enable static analysis tools to check context + * propagation: + * + * Do not store Contexts inside a struct type; instead, pass a Context + * explicitly to each function that needs it. The Context should be the first + * parameter, typically named ctx: + * + * ``` + * func DoSomething(ctx context.Context, arg Arg) error { + * // ... use ctx ... + * } + * ``` + * + * Do not pass a nil Context, even if a function permits it. Pass context.TODO + * if you are unsure about which Context to use. + * + * Use context Values only for request-scoped data that transits processes and + * APIs, not for passing optional parameters to functions. + * + * The same Context may be passed to functions running in different goroutines; + * Contexts are safe for simultaneous use by multiple goroutines. + * + * See https://blog.golang.org/context for example code for a server that uses + * Contexts. */ -namespace log { - /** - * A Logger represents an active logging object that generates lines of - * output to an io.Writer. Each logging operation makes a single call to - * the Writer's Write method. A Logger can be used simultaneously from - * multiple goroutines; it guarantees to serialize access to the Writer. - */ - interface Logger { - } - interface Logger { - /** - * SetOutput sets the output destination for the logger. - */ - setOutput(w: io.Writer): void - } - interface Logger { - /** - * Output writes the output for a logging event. The string s contains - * the text to print after the prefix specified by the flags of the - * Logger. A newline is appended if the last character of s is not - * already a newline. Calldepth is used to recover the PC and is - * provided for generality, although at the moment on all pre-defined - * paths it will be 2. - */ - output(calldepth: number, s: string): void - } - interface Logger { - /** - * Printf calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Printf. - */ - printf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Print calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Print. - */ - print(...v: any[]): void - } - interface Logger { - /** - * Println calls l.Output to print to the logger. - * Arguments are handled in the manner of fmt.Println. - */ - println(...v: any[]): void - } - interface Logger { - /** - * Fatal is equivalent to l.Print() followed by a call to os.Exit(1). - */ - fatal(...v: any[]): void - } - interface Logger { - /** - * Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). - */ - fatalf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). - */ - fatalln(...v: any[]): void - } - interface Logger { - /** - * Panic is equivalent to l.Print() followed by a call to panic(). - */ - panic(...v: any[]): void - } - interface Logger { - /** - * Panicf is equivalent to l.Printf() followed by a call to panic(). - */ - panicf(format: string, ...v: any[]): void - } - interface Logger { - /** - * Panicln is equivalent to l.Println() followed by a call to panic(). - */ - panicln(...v: any[]): void - } - interface Logger { - /** - * Flags returns the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. - */ - flags(): number - } - interface Logger { - /** - * SetFlags sets the output flags for the logger. - * The flag bits are Ldate, Ltime, and so on. - */ - setFlags(flag: number): void - } - interface Logger { - /** - * Prefix returns the output prefix for the logger. - */ - prefix(): string - } - interface Logger { - /** - * SetPrefix sets the output prefix for the logger. - */ - setPrefix(prefix: string): void - } - interface Logger { +namespace context { +} + +/** + * Package driver defines interfaces to be implemented by database + * drivers as used by package sql. + * + * Most code should use package sql. + * + * The driver interface has evolved over time. Drivers should implement + * Connector and DriverContext interfaces. + * The Connector.Connect and Driver.Open methods should never return ErrBadConn. + * ErrBadConn should only be returned from Validator, SessionResetter, or + * a query method if the connection is already in an invalid (e.g. closed) state. + * + * All Conn implementations should implement the following interfaces: + * Pinger, SessionResetter, and Validator. + * + * If named parameters or context are supported, the driver's Conn should implement: + * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * + * To support custom data types, implement NamedValueChecker. NamedValueChecker + * also allows queries to accept per-query options as a parameter by returning + * ErrRemoveArgument from CheckNamedValue. + * + * If multiple result sets are supported, Rows should implement RowsNextResultSet. + * If the driver knows how to describe the types present in the returned result + * it should implement the following interfaces: RowsColumnTypeScanType, + * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, + * and RowsColumnTypePrecisionScale. A given row value may also return a Rows + * type, which may represent a database cursor value. + * + * Before a connection is returned to the connection pool after use, IsValid is + * called if implemented. Before a connection is reused for another query, + * ResetSession is called if implemented. If a connection is never returned to the + * connection pool but immediately reused, then ResetSession is called prior to + * reuse but IsValid is not called. + */ +namespace driver { + /** + * Value is a value that drivers must be able to handle. + * It is either nil, a type handled by a database driver's NamedValueChecker + * interface, or an instance of one of these types: + * + * ``` + * int64 + * float64 + * bool + * []byte + * string + * time.Time + * ``` + * + * If the driver supports cursors, a returned Value may also implement the Rows interface + * in this package. This is used, for example, when a user selects a cursor + * such as "select cursor(select * from my_table) from dual". If the Rows + * from the select is closed, the cursor Rows will also be closed. + */ + interface Value extends _TygojaAny{} + /** + * Driver is the interface that must be implemented by a database + * driver. + * + * Database drivers may implement DriverContext for access + * to contexts and to parse the name only once for a pool of connections, + * instead of once per connection. + */ + interface Driver { /** - * Writer returns the output destination for the logger. + * Open returns a new connection to the database. + * The name is a string in a driver-specific format. + * + * Open may return a cached connection (one previously + * closed), but doing so is unnecessary; the sql package + * maintains a pool of idle connections for efficient re-use. + * + * The returned connection is only used by one goroutine at a + * time. */ - writer(): io.Writer + open(name: string): Conn } } /** - * Package textproto implements generic support for text-based request/response - * protocols in the style of HTTP, NNTP, and SMTP. + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. * - * The package provides: + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the Dial, Listen, and Accept functions and the associated + * Conn and Listener interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. * - * Error, which represents a numeric error response from - * a server. + * The Dial function connects to a server: * - * Pipeline, to manage pipelined requests and responses - * in a client. + * ``` + * conn, err := net.Dial("tcp", "golang.org:80") + * if err != nil { + * // handle error + * } + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') + * // ... + * ``` * - * Reader, to read numeric response code lines, - * key: value headers, lines wrapped with leading spaces - * on continuation lines, and whole text blocks ending - * with a dot on a line by itself. + * The Listen function creates servers: * - * Writer, to write dot-encoded text blocks. + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` * - * Conn, a convenient packaging of Reader, Writer, and Pipeline for use - * with a single network connection. + * Name Resolution + * + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. + * + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. + * + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: + * + * ``` + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force cgo resolver + * ``` + * + * The decision can also be forced while building the Go source tree + * by setting the netgo or netcgo build tag. + * + * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver + * to print debugging information about its decisions. + * To force a particular resolver while also printing debugging information, + * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. + * + * On Plan 9, the resolver always accesses /net/cs and /net/dns. + * + * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. */ -namespace textproto { +namespace net { /** - * A MIMEHeader represents a MIME-style header mapping - * keys to sets of values. + * Conn is a generic stream-oriented network connection. + * + * Multiple goroutines may invoke methods on a Conn simultaneously. */ - interface MIMEHeader extends _TygojaDict{} - interface MIMEHeader { + interface Conn { /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. + * Read reads data from the connection. + * Read can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetReadDeadline. */ - add(key: string): void - } - interface MIMEHeader { + read(b: string): number /** - * Set sets the header entries associated with key to - * the single element value. It replaces any existing - * values associated with key. + * Write writes data to the connection. + * Write can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetWriteDeadline. */ - set(key: string): void - } - interface MIMEHeader { + write(b: string): number /** - * Get gets the first value associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is used - * to canonicalize the provided key. - * If there are no values associated with the key, Get returns "". - * To use non-canonical keys, access the map directly. + * Close closes the connection. + * Any blocked Read or Write operations will be unblocked and return errors. */ - get(key: string): string - } - interface MIMEHeader { + close(): void /** - * Values returns all values associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. To use non-canonical - * keys, access the map directly. - * The returned slice is not a copy. + * LocalAddr returns the local network address, if known. */ - values(key: string): Array - } - interface MIMEHeader { + localAddr(): Addr /** - * Del deletes the values associated with key. + * RemoteAddr returns the remote network address, if known. */ - del(key: string): void - } -} - -/** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - */ -namespace multipart { - interface Reader { + remoteAddr(): Addr /** - * ReadForm parses an entire multipart message whose parts have - * a Content-Disposition of "form-data". - * It stores up to maxMemory bytes + 10MB (reserved for non-file parts) - * in memory. File parts which can't be stored in memory will be stored on - * disk in temporary files. - * It returns ErrMessageTooLarge if all non-file parts can't be stored in - * memory. + * SetDeadline sets the read and write deadlines associated + * with the connection. It is equivalent to calling both + * SetReadDeadline and SetWriteDeadline. + * + * A deadline is an absolute time after which I/O operations + * fail instead of blocking. The deadline applies to all future + * and pending I/O, not just the immediately following call to + * Read or Write. After a deadline has been exceeded, the + * connection can be refreshed by setting a deadline in the future. + * + * If the deadline is exceeded a call to Read or Write or to other + * I/O methods will return an error that wraps os.ErrDeadlineExceeded. + * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). + * The error's Timeout method will return true, but note that there + * are other possible errors for which the Timeout method will + * return true even if the deadline has not been exceeded. + * + * An idle timeout can be implemented by repeatedly extending + * the deadline after successful Read or Write calls. + * + * A zero value for t means I/O operations will not time out. */ - readForm(maxMemory: number): (Form | undefined) - } - /** - * Form is a parsed multipart form. - * Its File parts are stored either in memory or on disk, - * and are accessible via the *FileHeader's Open method. - * Its Value parts are stored as strings. - * Both are keyed by field name. - */ - interface Form { - value: _TygojaDict - file: _TygojaDict - } - interface Form { + setDeadline(t: time.Time): void /** - * RemoveAll removes any temporary files associated with a Form. + * SetReadDeadline sets the deadline for future Read calls + * and any currently-blocked Read call. + * A zero value for t means Read will not time out. + */ + setReadDeadline(t: time.Time): void + /** + * SetWriteDeadline sets the deadline for future Write calls + * and any currently-blocked Write call. + * Even if write times out, it may return n > 0, indicating that + * some of the data was successfully written. + * A zero value for t means Write will not time out. */ - removeAll(): void + setWriteDeadline(t: time.Time): void } /** - * File is an interface to access the file part of a multipart message. - * Its contents may be either stored in memory or on disk. - * If stored on disk, the File's underlying concrete type will be an *os.File. + * A Listener is a generic network listener for stream-oriented protocols. + * + * Multiple goroutines may invoke methods on a Listener simultaneously. */ - interface File { + interface Listener { + /** + * Accept waits for and returns the next connection to the listener. + */ + accept(): Conn + /** + * Close closes the listener. + * Any blocked Accept operations will be unblocked and return errors. + */ + close(): void + /** + * Addr returns the listener's network address. + */ + addr(): Addr } +} + +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { /** - * Reader is an iterator over parts in a MIME multipart body. - * Reader's underlying parser consumes its input as needed. Seeking - * isn't supported. + * A URL represents a parsed URL (technically, a URI reference). + * + * The general form represented is: + * + * ``` + * [scheme:][//[userinfo@]host][/]path[?query][#fragment] + * ``` + * + * URLs that do not start with a slash after the scheme are interpreted as: + * + * ``` + * scheme:opaque[?query][#fragment] + * ``` + * + * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. + * A consequence is that it is impossible to tell which slashes in the Path were + * slashes in the raw URL and which were %2f. This distinction is rarely important, + * but when it is, the code should use RawPath, an optional field which only gets + * set if the default encoding is different from Path. + * + * URL's String method uses the EscapedPath method to obtain the path. See the + * EscapedPath method for more details. */ - interface Reader { + interface URL { + scheme: string + opaque: string // encoded opaque data + user?: Userinfo // username and password information + host: string // host or host:port + path: string // path (relative paths may omit leading slash) + rawPath: string // encoded path hint (see EscapedPath method) + forceQuery: boolean // append a query ('?') even if RawQuery is empty + rawQuery: string // encoded query values, without '?' + fragment: string // fragment for references, without '#' + rawFragment: string // encoded fragment hint (see EscapedFragment method) } - interface Reader { + interface URL { /** - * NextPart returns the next part in the multipart or an error. - * When there are no more parts, the error io.EOF is returned. - * - * As a special case, if the "Content-Transfer-Encoding" header - * has a value of "quoted-printable", that header is instead - * hidden and the body is transparently decoded during Read calls. + * EscapedPath returns the escaped form of u.Path. + * In general there are multiple possible escaped forms of any path. + * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. + * Otherwise EscapedPath ignores u.RawPath and computes an escaped + * form on its own. + * The String and RequestURI methods use EscapedPath to construct + * their results. + * In general, code should call EscapedPath instead of + * reading u.RawPath directly. */ - nextPart(): (Part | undefined) + escapedPath(): string } - interface Reader { + interface URL { /** - * NextRawPart returns the next part in the multipart or an error. - * When there are no more parts, the error io.EOF is returned. + * EscapedFragment returns the escaped form of u.Fragment. + * In general there are multiple possible escaped forms of any fragment. + * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. + * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped + * form on its own. + * The String method uses EscapedFragment to construct its result. + * In general, code should call EscapedFragment instead of + * reading u.RawFragment directly. + */ + escapedFragment(): string + } + interface URL { + /** + * String reassembles the URL into a valid URL string. + * The general form of the result is one of: * - * Unlike NextPart, it does not have special handling for - * "Content-Transfer-Encoding: quoted-printable". + * ``` + * scheme:opaque?query#fragment + * scheme://userinfo@host/path?query#fragment + * ``` + * + * If u.Opaque is non-empty, String uses the first form; + * otherwise it uses the second form. + * Any non-ASCII characters in host are escaped. + * To obtain the path, String uses u.EscapedPath(). + * + * In the second form, the following rules apply: + * ``` + * - if u.Scheme is empty, scheme: is omitted. + * - if u.User is nil, userinfo@ is omitted. + * - if u.Host is empty, host/ is omitted. + * - if u.Scheme and u.Host are empty and u.User is nil, + * the entire scheme://userinfo@host/ is omitted. + * - if u.Host is non-empty and u.Path begins with a /, + * the form host/path does not add its own /. + * - if u.RawQuery is empty, ?query is omitted. + * - if u.Fragment is empty, #fragment is omitted. + * ``` */ - nextRawPart(): (Part | undefined) + string(): string + } + interface URL { + /** + * Redacted is like String but replaces any password with "xxxxx". + * Only the password in u.URL is redacted. + */ + redacted(): string } -} - -/** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The client must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG environment variables are - * currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * The GODEBUG variables are not covered by Go's API compatibility - * promise. Please report any issues before disabling HTTP/2 - * support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { /** - * A Client is an HTTP client. Its zero value (DefaultClient) is a - * usable client that uses DefaultTransport. - * - * The Client's Transport typically has internal state (cached TCP - * connections), so Clients should be reused instead of created as - * needed. Clients are safe for concurrent use by multiple goroutines. - * - * A Client is higher-level than a RoundTripper (such as Transport) - * and additionally handles HTTP details such as cookies and - * redirects. - * - * When following redirects, the Client will forward all headers set on the - * initial Request except: - * - * • when forwarding sensitive headers like "Authorization", - * "WWW-Authenticate", and "Cookie" to untrusted targets. - * These headers will be ignored when following a redirect to a domain - * that is not a subdomain match or exact match of the initial domain. - * For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" - * will forward the sensitive headers, but a redirect to "bar.com" will not. - * - * • when forwarding the "Cookie" header with a non-nil cookie Jar. - * Since each redirect may mutate the state of the cookie jar, - * a redirect may possibly alter a cookie set in the initial request. - * When forwarding the "Cookie" header, any mutated cookies will be omitted, - * with the expectation that the Jar will insert those mutated cookies - * with the updated values (assuming the origin matches). - * If Jar is nil, the initial cookies are forwarded without change. + * Values maps a string key to a list of values. + * It is typically used for query parameters and form values. + * Unlike in the http.Header map, the keys in a Values map + * are case-sensitive. */ - interface Client { + interface Values extends _TygojaDict{} + interface Values { /** - * Transport specifies the mechanism by which individual - * HTTP requests are made. - * If nil, DefaultTransport is used. + * Get gets the first value associated with the given key. + * If there are no values associated with the key, Get returns + * the empty string. To access multiple values, use the map + * directly. */ - transport: RoundTripper + get(key: string): string + } + interface Values { /** - * CheckRedirect specifies the policy for handling redirects. - * If CheckRedirect is not nil, the client calls it before - * following an HTTP redirect. The arguments req and via are - * the upcoming request and the requests made already, oldest - * first. If CheckRedirect returns an error, the Client's Get - * method returns both the previous Response (with its Body - * closed) and CheckRedirect's error (wrapped in a url.Error) - * instead of issuing the Request req. - * As a special case, if CheckRedirect returns ErrUseLastResponse, - * then the most recent response is returned with its body - * unclosed, along with a nil error. - * - * If CheckRedirect is nil, the Client uses its default policy, - * which is to stop after 10 consecutive requests. + * Set sets the key to value. It replaces any existing + * values. */ - checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void + set(key: string): void + } + interface Values { /** - * Jar specifies the cookie jar. - * - * The Jar is used to insert relevant cookies into every - * outbound Request and is updated with the cookie values - * of every inbound Response. The Jar is consulted for every - * redirect that the Client follows. - * - * If Jar is nil, cookies are only sent if they are explicitly - * set on the Request. + * Add adds the value to key. It appends to any existing + * values associated with key. */ - jar: CookieJar + add(key: string): void + } + interface Values { /** - * Timeout specifies a time limit for requests made by this - * Client. The timeout includes connection time, any - * redirects, and reading the response body. The timer remains - * running after Get, Head, Post, or Do return and will - * interrupt reading of the Response.Body. - * - * A Timeout of zero means no timeout. - * - * The Client cancels requests to the underlying Transport - * as if the Request's Context ended. - * - * For compatibility, the Client will also use the deprecated - * CancelRequest method on Transport if found. New - * RoundTripper implementations should use the Request's Context - * for cancellation instead of implementing CancelRequest. + * Del deletes the values associated with key. */ - timeout: time.Duration + del(key: string): void } - interface Client { + interface Values { /** - * Get issues a GET to the specified URL. If the response is one of the - * following redirect codes, Get follows the redirect after calling the - * Client's CheckRedirect function: - * - * ``` - * 301 (Moved Permanently) - * 302 (Found) - * 303 (See Other) - * 307 (Temporary Redirect) - * 308 (Permanent Redirect) - * ``` - * - * An error is returned if the Client's CheckRedirect function fails - * or if there was an HTTP protocol error. A non-2xx response doesn't - * cause an error. Any returned error will be of type *url.Error. The - * url.Error value's Timeout method will report true if the request - * timed out. - * - * When err is nil, resp always contains a non-nil resp.Body. - * Caller should close resp.Body when done reading from it. - * - * To make a request with custom headers, use NewRequest and Client.Do. - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. + * Has checks whether a given key is set. */ - get(url: string): (Response | undefined) + has(key: string): boolean } - interface Client { + interface Values { /** - * Do sends an HTTP request and returns an HTTP response, following - * policy (such as redirects, cookies, auth) as configured on the - * client. - * - * An error is returned if caused by client policy (such as - * CheckRedirect), or failure to speak HTTP (such as a network - * connectivity problem). A non-2xx status code doesn't cause an - * error. - * - * If the returned error is nil, the Response will contain a non-nil - * Body which the user is expected to close. If the Body is not both - * read to EOF and closed, the Client's underlying RoundTripper - * (typically Transport) may not be able to re-use a persistent TCP - * connection to the server for a subsequent "keep-alive" request. - * - * The request Body, if non-nil, will be closed by the underlying - * Transport, even on errors. - * - * On error, any Response can be ignored. A non-nil Response with a - * non-nil error only occurs when CheckRedirect fails, and even then - * the returned Response.Body is already closed. - * - * Generally Get, Post, or PostForm will be used instead of Do. + * Encode encodes the values into ``URL encoded'' form + * ("bar=baz&foo=quux") sorted by key. + */ + encode(): string + } + interface URL { + /** + * IsAbs reports whether the URL is absolute. + * Absolute means that it has a non-empty scheme. + */ + isAbs(): boolean + } + interface URL { + /** + * Parse parses a URL in the context of the receiver. The provided URL + * may be relative or absolute. Parse returns nil, err on parse + * failure, otherwise its return value is the same as ResolveReference. + */ + parse(ref: string): (URL | undefined) + } + interface URL { + /** + * ResolveReference resolves a URI reference to an absolute URI from + * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference + * may be relative or absolute. ResolveReference always returns a new + * URL instance, even if the returned URL is identical to either the + * base or reference. If ref is an absolute URL, then ResolveReference + * ignores base and returns a copy of ref. + */ + resolveReference(ref: URL): (URL | undefined) + } + interface URL { + /** + * Query parses RawQuery and returns the corresponding values. + * It silently discards malformed value pairs. + * To check errors use ParseQuery. + */ + query(): Values + } + interface URL { + /** + * RequestURI returns the encoded path?query or opaque?query + * string that would be used in an HTTP request for u. + */ + requestURI(): string + } + interface URL { + /** + * Hostname returns u.Host, stripping any valid port number if present. * - * If the server replies with a redirect, the Client first uses the - * CheckRedirect function to determine whether the redirect should be - * followed. If permitted, a 301, 302, or 303 redirect causes - * subsequent requests to use HTTP method GET - * (or HEAD if the original request was HEAD), with no body. - * A 307 or 308 redirect preserves the original HTTP method and body, - * provided that the Request.GetBody function is defined. - * The NewRequest function automatically sets GetBody for common - * standard library body types. + * If the result is enclosed in square brackets, as literal IPv6 addresses are, + * the square brackets are removed from the result. + */ + hostname(): string + } + interface URL { + /** + * Port returns the port part of u.Host, without the leading colon. * - * Any returned error will be of type *url.Error. The url.Error - * value's Timeout method will report true if the request timed out. + * If u.Host doesn't contain a valid numeric port, Port returns an empty string. + */ + port(): string + } + interface URL { + marshalBinary(): string + } + interface URL { + unmarshalBinary(text: string): void + } +} + +/** + * Package tls partially implements TLS 1.2, as specified in RFC 5246, + * and TLS 1.3, as specified in RFC 8446. + */ +namespace tls { + /** + * ConnectionState records basic TLS details about the connection. + */ + interface ConnectionState { + /** + * Version is the TLS version used by the connection (e.g. VersionTLS12). + */ + version: number + /** + * HandshakeComplete is true if the handshake has concluded. + */ + handshakeComplete: boolean + /** + * DidResume is true if this connection was successfully resumed from a + * previous session with a session ticket or similar mechanism. */ - do(req: Request): (Response | undefined) - } - interface Client { + didResume: boolean /** - * Post issues a POST to the specified URL. - * - * Caller should close resp.Body when done reading from it. + * CipherSuite is the cipher suite negotiated for the connection (e.g. + * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). + */ + cipherSuite: number + /** + * NegotiatedProtocol is the application protocol negotiated with ALPN. + */ + negotiatedProtocol: string + /** + * NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. * - * If the provided body is an io.Closer, it is closed after the - * request. + * Deprecated: this value is always true. + */ + negotiatedProtocolIsMutual: boolean + /** + * ServerName is the value of the Server Name Indication extension sent by + * the client. It's available both on the server and on the client side. + */ + serverName: string + /** + * PeerCertificates are the parsed certificates sent by the peer, in the + * order in which they were sent. The first element is the leaf certificate + * that the connection is verified against. * - * To set custom headers, use NewRequest and Client.Do. + * On the client side, it can't be empty. On the server side, it can be + * empty if Config.ClientAuth is not RequireAnyClientCert or + * RequireAndVerifyClientCert. + */ + peerCertificates: Array<(x509.Certificate | undefined)> + /** + * VerifiedChains is a list of one or more chains where the first element is + * PeerCertificates[0] and the last element is from Config.RootCAs (on the + * client side) or Config.ClientCAs (on the server side). * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. + * On the client side, it's set if Config.InsecureSkipVerify is false. On + * the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven + * (and the peer provided a certificate) or RequireAndVerifyClientCert. + */ + verifiedChains: Array> + /** + * SignedCertificateTimestamps is a list of SCTs provided by the peer + * through the TLS handshake for the leaf certificate, if any. + */ + signedCertificateTimestamps: Array + /** + * OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) + * response provided by the peer for the leaf certificate, if any. + */ + ocspResponse: string + /** + * TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, + * Section 3). This value will be nil for TLS 1.3 connections and for all + * resumed connections. * - * See the Client.Do method documentation for details on how redirects - * are handled. + * Deprecated: there are conditions in which this value might not be unique + * to a connection. See the Security Considerations sections of RFC 5705 and + * RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings. */ - post(url: string, body: io.Reader): (Response | undefined) + tlsUnique: string } - interface Client { + interface ConnectionState { /** - * PostForm issues a POST to the specified URL, - * with data's keys and values URL-encoded as the request body. - * - * The Content-Type header is set to application/x-www-form-urlencoded. - * To set other headers, use NewRequest and Client.Do. - * - * When err is nil, resp always contains a non-nil resp.Body. - * Caller should close resp.Body when done reading from it. - * - * See the Client.Do method documentation for details on how redirects - * are handled. - * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. + * ExportKeyingMaterial returns length bytes of exported key material in a new + * slice as defined in RFC 5705. If context is nil, it is not used as part of + * the seed. If the connection was set to allow renegotiation via + * Config.Renegotiation, this function will return an error. */ - postForm(url: string, data: url.Values): (Response | undefined) + exportKeyingMaterial(label: string, context: string, length: number): string } - interface Client { + /** + * A Config structure is used to configure a TLS client or server. + * After one has been passed to a TLS function it must not be + * modified. A Config may be reused; the tls package will also not + * modify it. + */ + interface Config { /** - * Head issues a HEAD to the specified URL. If the response is one of the - * following redirect codes, Head follows the redirect after calling the - * Client's CheckRedirect function: + * Rand provides the source of entropy for nonces and RSA blinding. + * If Rand is nil, TLS uses the cryptographic random reader in package + * crypto/rand. + * The Reader must be safe for use by multiple goroutines. + */ + rand: io.Reader + /** + * Time returns the current time as the number of seconds since the epoch. + * If Time is nil, TLS uses time.Now. + */ + time: () => time.Time + /** + * Certificates contains one or more certificate chains to present to the + * other side of the connection. The first certificate compatible with the + * peer's requirements is selected automatically. * - * ``` - * 301 (Moved Permanently) - * 302 (Found) - * 303 (See Other) - * 307 (Temporary Redirect) - * 308 (Permanent Redirect) - * ``` + * Server configurations must set one of Certificates, GetCertificate or + * GetConfigForClient. Clients doing client-authentication may set either + * Certificates or GetClientCertificate. * - * To make a request with a specified context.Context, use NewRequestWithContext - * and Client.Do. + * Note: if there are multiple Certificates, and they don't have the + * optional field Leaf set, certificate selection will incur a significant + * per-handshake performance cost. */ - head(url: string): (Response | undefined) - } - interface Client { + certificates: Array /** - * CloseIdleConnections closes any connections on its Transport which - * were previously connected from previous requests but are now - * sitting idle in a "keep-alive" state. It does not interrupt any - * connections currently in use. + * NameToCertificate maps from a certificate name to an element of + * Certificates. Note that a certificate name can be of the form + * '*.example.com' and so doesn't have to be a domain name as such. * - * If the Client's Transport does not have a CloseIdleConnections method - * then this method does nothing. + * Deprecated: NameToCertificate only allows associating a single + * certificate with a given name. Leave this field nil to let the library + * select the first compatible chain from Certificates. */ - closeIdleConnections(): void - } - /** - * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an - * HTTP response or the Cookie header of an HTTP request. - * - * See https://tools.ietf.org/html/rfc6265 for details. - */ - interface Cookie { - name: string - value: string - path: string // optional - domain: string // optional - expires: time.Time // optional - rawExpires: string // for reading cookies only + nameToCertificate: _TygojaDict /** - * MaxAge=0 means no 'Max-Age' attribute specified. - * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' - * MaxAge>0 means Max-Age attribute present and given in seconds + * GetCertificate returns a Certificate based on the given + * ClientHelloInfo. It will only be called if the client supplies SNI + * information or if Certificates is empty. + * + * If GetCertificate is nil or returns nil, then the certificate is + * retrieved from NameToCertificate. If NameToCertificate is nil, the + * best element of Certificates will be used. */ - maxAge: number - secure: boolean - httpOnly: boolean - sameSite: SameSite - raw: string - unparsed: Array // Raw text of unparsed attribute-value pairs - } - interface Cookie { + getCertificate: (_arg0: ClientHelloInfo) => (Certificate | undefined) /** - * String returns the serialization of the cookie for use in a Cookie - * header (if only Name and Value are set) or a Set-Cookie response - * header (if other fields are set). - * If c is nil or c.Name is invalid, the empty string is returned. + * GetClientCertificate, if not nil, is called when a server requests a + * certificate from a client. If set, the contents of Certificates will + * be ignored. + * + * If GetClientCertificate returns an error, the handshake will be + * aborted and that error will be returned. Otherwise + * GetClientCertificate must return a non-nil Certificate. If + * Certificate.Certificate is empty then no certificate will be sent to + * the server. If this is unacceptable to the server then it may abort + * the handshake. + * + * GetClientCertificate may be called multiple times for the same + * connection if renegotiation occurs or if TLS 1.3 is in use. */ - string(): string - } - interface Cookie { + getClientCertificate: (_arg0: CertificateRequestInfo) => (Certificate | undefined) /** - * Valid reports whether the cookie is valid. + * GetConfigForClient, if not nil, is called after a ClientHello is + * received from a client. It may return a non-nil Config in order to + * change the Config that will be used to handle this connection. If + * the returned Config is nil, the original Config will be used. The + * Config returned by this callback may not be subsequently modified. + * + * If GetConfigForClient is nil, the Config passed to Server() will be + * used for all connections. + * + * If SessionTicketKey was explicitly set on the returned Config, or if + * SetSessionTicketKeys was called on the returned Config, those keys will + * be used. Otherwise, the original Config keys will be used (and possibly + * rotated if they are automatically managed). */ - valid(): void - } - // @ts-ignore - import mathrand = rand - /** - * A Header represents the key-value pairs in an HTTP header. - * - * The keys should be in canonical form, as returned by - * CanonicalHeaderKey. - */ - interface Header extends _TygojaDict{} - interface Header { + getConfigForClient: (_arg0: ClientHelloInfo) => (Config | undefined) /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. - * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. + * VerifyPeerCertificate, if not nil, is called after normal + * certificate verification by either a TLS client or server. It + * receives the raw ASN.1 certificates provided by the peer and also + * any verified chains that normal processing found. If it returns a + * non-nil error, the handshake is aborted and that error results. + * + * If normal verification fails then the handshake will abort before + * considering this callback. If normal verification is disabled by + * setting InsecureSkipVerify, or (for a server) when ClientAuth is + * RequestClientCert or RequireAnyClientCert, then this callback will + * be considered but the verifiedChains argument will always be nil. */ - add(key: string): void - } - interface Header { + verifyPeerCertificate: (rawCerts: Array, verifiedChains: Array>) => void /** - * Set sets the header entries associated with key to the - * single element value. It replaces any existing values - * associated with key. The key is case insensitive; it is - * canonicalized by textproto.CanonicalMIMEHeaderKey. - * To use non-canonical keys, assign to the map directly. + * VerifyConnection, if not nil, is called after normal certificate + * verification and after VerifyPeerCertificate by either a TLS client + * or server. If it returns a non-nil error, the handshake is aborted + * and that error results. + * + * If normal verification fails then the handshake will abort before + * considering this callback. This callback will run for all connections + * regardless of InsecureSkipVerify or ClientAuth settings. */ - set(key: string): void - } - interface Header { + verifyConnection: (_arg0: ConnectionState) => void /** - * Get gets the first value associated with the given key. If - * there are no values associated with the key, Get returns "". - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. To use non-canonical keys, - * access the map directly. + * RootCAs defines the set of root certificate authorities + * that clients use when verifying server certificates. + * If RootCAs is nil, TLS uses the host's root CA set. */ - get(key: string): string - } - interface Header { + rootCAs?: x509.CertPool /** - * Values returns all values associated with the given key. - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is - * used to canonicalize the provided key. To use non-canonical - * keys, access the map directly. - * The returned slice is not a copy. + * NextProtos is a list of supported application level protocols, in + * order of preference. If both peers support ALPN, the selected + * protocol will be one from this list, and the connection will fail + * if there is no mutually supported protocol. If NextProtos is empty + * or the peer doesn't support ALPN, the connection will succeed and + * ConnectionState.NegotiatedProtocol will be empty. */ - values(key: string): Array - } - interface Header { + nextProtos: Array /** - * Del deletes the values associated with key. - * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. + * ServerName is used to verify the hostname on the returned + * certificates unless InsecureSkipVerify is given. It is also included + * in the client's handshake to support virtual hosting unless it is + * an IP address. */ - del(key: string): void - } - interface Header { + serverName: string /** - * Write writes a header in wire format. + * ClientAuth determines the server's policy for + * TLS Client Authentication. The default is NoClientCert. */ - write(w: io.Writer): void - } - interface Header { + clientAuth: ClientAuthType /** - * Clone returns a copy of h or nil if h is nil. + * ClientCAs defines the set of root certificate authorities + * that servers use if required to verify a client certificate + * by the policy in ClientAuth. */ - clone(): Header - } - interface Header { + clientCAs?: x509.CertPool /** - * WriteSubset writes a header in wire format. - * If exclude is not nil, keys where exclude[key] == true are not written. - * Keys are not canonicalized before checking the exclude map. + * InsecureSkipVerify controls whether a client verifies the server's + * certificate chain and host name. If InsecureSkipVerify is true, crypto/tls + * accepts any certificate presented by the server and any host name in that + * certificate. In this mode, TLS is susceptible to machine-in-the-middle + * attacks unless custom verification is used. This should be used only for + * testing or in combination with VerifyConnection or VerifyPeerCertificate. */ - writeSubset(w: io.Writer, exclude: _TygojaDict): void - } - // @ts-ignore - import urlpkg = url - /** - * Response represents the response from an HTTP request. - * - * The Client and Transport return Responses from servers once - * the response headers have been received. The response body - * is streamed on demand as the Body field is read. - */ - interface Response { - status: string // e.g. "200 OK" - statusCode: number // e.g. 200 - proto: string // e.g. "HTTP/1.0" - protoMajor: number // e.g. 1 - protoMinor: number // e.g. 0 + insecureSkipVerify: boolean /** - * Header maps header keys to values. If the response had multiple - * headers with the same key, they may be concatenated, with comma - * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers - * be semantically equivalent to a comma-delimited sequence.) When - * Header values are duplicated by other fields in this struct (e.g., - * ContentLength, TransferEncoding, Trailer), the field values are - * authoritative. + * CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of + * the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. * - * Keys in the map are canonicalized (see CanonicalHeaderKey). + * If CipherSuites is nil, a safe default list is used. The default cipher + * suites might change over time. */ - header: Header + cipherSuites: Array /** - * Body represents the response body. - * - * The response body is streamed on demand as the Body field - * is read. If the network connection fails or the server - * terminates the response, Body.Read calls return an error. - * - * The http Client and Transport guarantee that Body is always - * non-nil, even on responses without a body or responses with - * a zero-length body. It is the caller's responsibility to - * close Body. The default HTTP client's Transport may not - * reuse HTTP/1.x "keep-alive" TCP connections if the Body is - * not read to completion and closed. + * PreferServerCipherSuites is a legacy field and has no effect. * - * The Body is automatically dechunked if the server replied - * with a "chunked" Transfer-Encoding. + * It used to control whether the server would follow the client's or the + * server's preference. Servers now select the best mutually supported + * cipher suite based on logic that takes into account inferred client + * hardware, server hardware, and security. * - * As of Go 1.12, the Body will also implement io.Writer - * on a successful "101 Switching Protocols" response, - * as used by WebSockets and HTTP/2's "h2c" mode. - */ - body: io.ReadCloser - /** - * ContentLength records the length of the associated content. The - * value -1 indicates that the length is unknown. Unless Request.Method - * is "HEAD", values >= 0 indicate that the given number of bytes may - * be read from Body. + * Deprecated: PreferServerCipherSuites is ignored. */ - contentLength: number + preferServerCipherSuites: boolean /** - * Contains transfer encodings from outer-most to inner-most. Value is - * nil, means that "identity" encoding is used. + * SessionTicketsDisabled may be set to true to disable session ticket and + * PSK (resumption) support. Note that on clients, session ticket support is + * also disabled if ClientSessionCache is nil. */ - transferEncoding: Array + sessionTicketsDisabled: boolean /** - * Close records whether the header directed that the connection be - * closed after reading Body. The value is advice for clients: neither - * ReadResponse nor Response.Write ever closes a connection. + * SessionTicketKey is used by TLS servers to provide session resumption. + * See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled + * with random data before the first server handshake. + * + * Deprecated: if this field is left at zero, session ticket keys will be + * automatically rotated every day and dropped after seven days. For + * customizing the rotation schedule or synchronizing servers that are + * terminating connections for the same host, use SetSessionTicketKeys. */ - close: boolean + sessionTicketKey: string /** - * Uncompressed reports whether the response was sent compressed but - * was decompressed by the http package. When true, reading from - * Body yields the uncompressed content instead of the compressed - * content actually set from the server, ContentLength is set to -1, - * and the "Content-Length" and "Content-Encoding" fields are deleted - * from the responseHeader. To get the original response from - * the server, set Transport.DisableCompression to true. + * ClientSessionCache is a cache of ClientSessionState entries for TLS + * session resumption. It is only used by clients. */ - uncompressed: boolean + clientSessionCache: ClientSessionCache /** - * Trailer maps trailer keys to values in the same - * format as Header. + * MinVersion contains the minimum TLS version that is acceptable. * - * The Trailer initially contains only nil values, one for - * each key specified in the server's "Trailer" header - * value. Those values are not added to Header. + * By default, TLS 1.2 is currently used as the minimum when acting as a + * client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum + * supported by this package, both as a client and as a server. * - * Trailer must not be accessed concurrently with Read calls - * on the Body. + * The client-side default can temporarily be reverted to TLS 1.0 by + * including the value "x509sha1=1" in the GODEBUG environment variable. + * Note that this option will be removed in Go 1.19 (but it will still be + * possible to set this field to VersionTLS10 explicitly). + */ + minVersion: number + /** + * MaxVersion contains the maximum TLS version that is acceptable. * - * After Body.Read has returned io.EOF, Trailer will contain - * any trailer values sent by the server. + * By default, the maximum version supported by this package is used, + * which is currently TLS 1.3. */ - trailer: Header + maxVersion: number /** - * Request is the request that was sent to obtain this Response. - * Request's Body is nil (having already been consumed). - * This is only populated for Client requests. + * CurvePreferences contains the elliptic curves that will be used in + * an ECDHE handshake, in preference order. If empty, the default will + * be used. The client will use the first preference as the type for + * its key share in TLS 1.3. This may change in the future. */ - request?: Request + curvePreferences: Array /** - * TLS contains information about the TLS connection on which the - * response was received. It is nil for unencrypted responses. - * The pointer is shared between responses and should not be - * modified. + * DynamicRecordSizingDisabled disables adaptive sizing of TLS records. + * When true, the largest possible TLS record size is always used. When + * false, the size of TLS records may be adjusted in an attempt to + * improve latency. */ - tls?: tls.ConnectionState - } - interface Response { + dynamicRecordSizingDisabled: boolean /** - * Cookies parses and returns the cookies set in the Set-Cookie headers. + * Renegotiation controls what types of renegotiation are supported. + * The default, none, is correct for the vast majority of applications. */ - cookies(): Array<(Cookie | undefined)> + renegotiation: RenegotiationSupport + /** + * KeyLogWriter optionally specifies a destination for TLS master secrets + * in NSS key log format that can be used to allow external programs + * such as Wireshark to decrypt TLS connections. + * See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. + * Use of KeyLogWriter compromises security and should only be + * used for debugging. + */ + keyLogWriter: io.Writer } - interface Response { + interface Config { /** - * Location returns the URL of the response's "Location" header, - * if present. Relative redirects are resolved relative to - * the Response's Request. ErrNoLocation is returned if no - * Location header is present. + * Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is + * being used concurrently by a TLS client or server. */ - location(): (url.URL | undefined) + clone(): (Config | undefined) } - interface Response { + interface Config { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the response is at least major.minor. + * SetSessionTicketKeys updates the session ticket keys for a server. + * + * The first key will be used when creating new tickets, while all keys can be + * used for decrypting tickets. It is safe to call this function while the + * server is running in order to rotate the session ticket keys. The function + * will panic if keys is empty. + * + * Calling this function will turn off automatic session ticket key rotation. + * + * If multiple servers are terminating connections for the same host they should + * all have the same session ticket keys. If the session ticket keys leaks, + * previously recorded and future TLS connections using those keys might be + * compromised. */ - protoAtLeast(major: number): boolean + setSessionTicketKeys(keys: Array): void } - interface Response { + interface Config { /** - * Write writes r to w in the HTTP/1.x server response format, - * including the status line, headers, body, and optional trailer. - * - * This method consults the following fields of the response r: - * - * StatusCode - * ProtoMajor - * ProtoMinor - * Request.Method - * TransferEncoding - * Trailer - * Body - * ContentLength - * Header, values for non-canonical keys will have unpredictable behavior + * BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate + * from the CommonName and SubjectAlternateName fields of each of the leaf + * certificates. * - * The Response Body is closed after it is sent. + * Deprecated: NameToCertificate only allows associating a single certificate + * with a given name. Leave that field nil to let the library select the first + * compatible chain from Certificates. */ - write(w: io.Writer): void - } - /** - * A Handler responds to an HTTP request. - * - * ServeHTTP should write reply headers and data to the ResponseWriter - * and then return. Returning signals that the request is finished; it - * is not valid to use the ResponseWriter or read from the - * Request.Body after or concurrently with the completion of the - * ServeHTTP call. - * - * Depending on the HTTP client software, HTTP protocol version, and - * any intermediaries between the client and the Go server, it may not - * be possible to read from the Request.Body after writing to the - * ResponseWriter. Cautious handlers should read the Request.Body - * first, and then reply. - * - * Except for reading the body, handlers should not modify the - * provided Request. - * - * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes - * that the effect of the panic was isolated to the active request. - * It recovers the panic, logs a stack trace to the server error log, - * and either closes the network connection or sends an HTTP/2 - * RST_STREAM, depending on the HTTP protocol. To abort a handler so - * the client sees an interrupted response but the server doesn't log - * an error, panic with the value ErrAbortHandler. - */ - interface Handler { - serveHTTP(_arg0: ResponseWriter, _arg1: Request): void - } - /** - * A ConnState represents the state of a client connection to a server. - * It's used by the optional Server.ConnState hook. - */ - interface ConnState extends Number{} - interface ConnState { - string(): string + buildNameToCertificate(): void } } /** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) + * Package textproto implements generic support for text-based request/response + * protocols in the style of HTTP, NNTP, and SMTP. * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } + * The package provides: * - * func main() { - * // Echo instance - * e := echo.New() + * Error, which represents a numeric error response from + * a server. * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) + * Pipeline, to manage pipelined requests and responses + * in a client. * - * // Routes - * e.GET("/", hello) + * Reader, to read numeric response code lines, + * key: value headers, lines wrapped with leading spaces + * on continuation lines, and whole text blocks ending + * with a dot on a line by itself. * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` + * Writer, to write dot-encoded text blocks. * - * Learn more at https://echo.labstack.com + * Conn, a convenient packaging of Reader, Writer, and Pipeline for use + * with a single network connection. */ -namespace echo { - /** - * Binder is the interface that wraps the Bind method. - */ - interface Binder { - bind(c: Context, i: { - }): void - } +namespace textproto { /** - * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and - * be able to be routed by Router. + * A MIMEHeader represents a MIME-style header mapping + * keys to sets of values. */ - interface ServableContext { + interface MIMEHeader extends _TygojaDict{} + interface MIMEHeader { /** - * Reset resets the context after request completes. It must be called along - * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. - * See `Echo#ServeHTTP()` + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. */ - reset(r: http.Request, w: http.ResponseWriter): void - } - // @ts-ignore - import stdContext = context - /** - * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. - */ - interface JSONSerializer { - serialize(c: Context, i: { - }, indent: string): void - deserialize(c: Context, i: { - }): void - } - /** - * HTTPErrorHandler is a centralized HTTP error handler. - */ - interface HTTPErrorHandler {(c: Context, err: Error): void } - /** - * Validator is the interface that wraps the Validate function. - */ - interface Validator { - validate(i: { - }): void - } - /** - * Renderer is the interface that wraps the Render function. - */ - interface Renderer { - render(_arg0: io.Writer, _arg1: string, _arg2: { - }, _arg3: Context): void - } - /** - * Group is a set of sub-routes for a specified route. It can be used for inner - * routes that share a common middleware or functionality that should be separate - * from the parent echo instance while still inheriting from it. - */ - interface Group { + add(key: string): void } - interface Group { + interface MIMEHeader { /** - * Use implements `Echo#Use()` for sub-routes within the Group. - * Group middlewares are not executed on request when there is no matching route found. + * Set sets the header entries associated with key to + * the single element value. It replaces any existing + * values associated with key. */ - use(...middleware: MiddlewareFunc[]): void + set(key: string): void } - interface Group { + interface MIMEHeader { /** - * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. + * Get gets the first value associated with the given key. + * It is case insensitive; CanonicalMIMEHeaderKey is used + * to canonicalize the provided key. + * If there are no values associated with the key, Get returns "". + * To use non-canonical keys, access the map directly. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + get(key: string): string } - interface Group { + interface MIMEHeader { /** - * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. + * Values returns all values associated with the given key. + * It is case insensitive; CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical + * keys, access the map directly. + * The returned slice is not a copy. */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + values(key: string): Array } - interface Group { + interface MIMEHeader { /** - * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. + * Del deletes the values associated with key. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + del(key: string): void } - interface Group { +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + */ +namespace multipart { + interface Reader { /** - * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. + * ReadForm parses an entire multipart message whose parts have + * a Content-Disposition of "form-data". + * It stores up to maxMemory bytes + 10MB (reserved for non-file parts) + * in memory. File parts which can't be stored in memory will be stored on + * disk in temporary files. + * It returns ErrMessageTooLarge if all non-file parts can't be stored in + * memory. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + readForm(maxMemory: number): (Form | undefined) } - interface Group { - /** - * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. - */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + /** + * Form is a parsed multipart form. + * Its File parts are stored either in memory or on disk, + * and are accessible via the *FileHeader's Open method. + * Its Value parts are stored as strings. + * Both are keyed by field name. + */ + interface Form { + value: _TygojaDict + file: _TygojaDict } - interface Group { + interface Form { /** - * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. + * RemoveAll removes any temporary files associated with a Form. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + removeAll(): void } - interface Group { - /** - * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. - */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + /** + * File is an interface to access the file part of a multipart message. + * Its contents may be either stored in memory or on disk. + * If stored on disk, the File's underlying concrete type will be an *os.File. + */ + interface File { } - interface Group { + /** + * Reader is an iterator over parts in a MIME multipart body. + * Reader's underlying parser consumes its input as needed. Seeking + * isn't supported. + */ + interface Reader { + } + interface Reader { /** - * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. + * NextPart returns the next part in the multipart or an error. + * When there are no more parts, the error io.EOF is returned. + * + * As a special case, if the "Content-Transfer-Encoding" header + * has a value of "quoted-printable", that header is instead + * hidden and the body is transparently decoded during Read calls. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + nextPart(): (Part | undefined) } - interface Group { + interface Reader { /** - * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. + * NextRawPart returns the next part in the multipart or an error. + * When there are no more parts, the error io.EOF is returned. + * + * Unlike NextPart, it does not have special handling for + * "Content-Transfer-Encoding: quoted-printable". */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + nextRawPart(): (Part | undefined) } - interface Group { +} + +/** + * Package http provides HTTP client and server implementations. + * + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: + * + * ``` + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) + * ``` + * + * The client must close the response body when finished with it: + * + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: + * + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... + * ``` + * + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use DefaultServeMux. + * Handle and HandleFunc add handlers to DefaultServeMux: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting Transport.TLSNextProto (for clients) or + * Server.TLSNextProto (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG environment variables are + * currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * The GODEBUG variables are not covered by Go's API compatibility + * promise. Please report any issues before disabling HTTP/2 + * support: https://golang.org/s/http2bug + * + * The http package's Transport and Server both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { + /** + * A Client is an HTTP client. Its zero value (DefaultClient) is a + * usable client that uses DefaultTransport. + * + * The Client's Transport typically has internal state (cached TCP + * connections), so Clients should be reused instead of created as + * needed. Clients are safe for concurrent use by multiple goroutines. + * + * A Client is higher-level than a RoundTripper (such as Transport) + * and additionally handles HTTP details such as cookies and + * redirects. + * + * When following redirects, the Client will forward all headers set on the + * initial Request except: + * + * • when forwarding sensitive headers like "Authorization", + * "WWW-Authenticate", and "Cookie" to untrusted targets. + * These headers will be ignored when following a redirect to a domain + * that is not a subdomain match or exact match of the initial domain. + * For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + * will forward the sensitive headers, but a redirect to "bar.com" will not. + * + * • when forwarding the "Cookie" header with a non-nil cookie Jar. + * Since each redirect may mutate the state of the cookie jar, + * a redirect may possibly alter a cookie set in the initial request. + * When forwarding the "Cookie" header, any mutated cookies will be omitted, + * with the expectation that the Jar will insert those mutated cookies + * with the updated values (assuming the origin matches). + * If Jar is nil, the initial cookies are forwarded without change. + */ + interface Client { /** - * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. + * Transport specifies the mechanism by which individual + * HTTP requests are made. + * If nil, DefaultTransport is used. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Group { + transport: RoundTripper /** - * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. + * CheckRedirect specifies the policy for handling redirects. + * If CheckRedirect is not nil, the client calls it before + * following an HTTP redirect. The arguments req and via are + * the upcoming request and the requests made already, oldest + * first. If CheckRedirect returns an error, the Client's Get + * method returns both the previous Response (with its Body + * closed) and CheckRedirect's error (wrapped in a url.Error) + * instead of issuing the Request req. + * As a special case, if CheckRedirect returns ErrUseLastResponse, + * then the most recent response is returned with its body + * unclosed, along with a nil error. + * + * If CheckRedirect is nil, the Client uses its default policy, + * which is to stop after 10 consecutive requests. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Group { + checkRedirect: (req: Request, via: Array<(Request | undefined)>) => void /** - * Group creates a new sub-group with prefix and optional sub-group-level middleware. - * Important! Group middlewares are only executed in case there was exact route match and not - * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add - * a catch-all route `/*` for the group which handler returns always 404 + * Jar specifies the cookie jar. + * + * The Jar is used to insert relevant cookies into every + * outbound Request and is updated with the cookie values + * of every inbound Response. The Jar is consulted for every + * redirect that the Client follows. + * + * If Jar is nil, cookies are only sent if they are explicitly + * set on the Request. */ - group(prefix: string, ...middleware: MiddlewareFunc[]): (Group | undefined) - } - interface Group { + jar: CookieJar /** - * Static implements `Echo#Static()` for sub-routes within the Group. + * Timeout specifies a time limit for requests made by this + * Client. The timeout includes connection time, any + * redirects, and reading the response body. The timer remains + * running after Get, Head, Post, or Do return and will + * interrupt reading of the Response.Body. + * + * A Timeout of zero means no timeout. + * + * The Client cancels requests to the underlying Transport + * as if the Request's Context ended. + * + * For compatibility, the Client will also use the deprecated + * CancelRequest method on Transport if found. New + * RoundTripper implementations should use the Request's Context + * for cancellation instead of implementing CancelRequest. */ - static(pathPrefix: string): RouteInfo + timeout: time.Duration } - interface Group { + interface Client { /** - * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. + * Get issues a GET to the specified URL. If the response is one of the + * following redirect codes, Get follows the redirect after calling the + * Client's CheckRedirect function: + * + * ``` + * 301 (Moved Permanently) + * 302 (Found) + * 303 (See Other) + * 307 (Temporary Redirect) + * 308 (Permanent Redirect) + * ``` * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. - */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo - } - interface Group { - /** - * FileFS implements `Echo#FileFS()` for sub-routes within the Group. + * An error is returned if the Client's CheckRedirect function fails + * or if there was an HTTP protocol error. A non-2xx response doesn't + * cause an error. Any returned error will be of type *url.Error. The + * url.Error value's Timeout method will report true if the request + * timed out. + * + * When err is nil, resp always contains a non-nil resp.Body. + * Caller should close resp.Body when done reading from it. + * + * To make a request with custom headers, use NewRequest and Client.Do. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo + get(url: string): (Response | undefined) } - interface Group { + interface Client { /** - * File implements `Echo#File()` for sub-routes within the Group. Panics on error. + * Do sends an HTTP request and returns an HTTP response, following + * policy (such as redirects, cookies, auth) as configured on the + * client. + * + * An error is returned if caused by client policy (such as + * CheckRedirect), or failure to speak HTTP (such as a network + * connectivity problem). A non-2xx status code doesn't cause an + * error. + * + * If the returned error is nil, the Response will contain a non-nil + * Body which the user is expected to close. If the Body is not both + * read to EOF and closed, the Client's underlying RoundTripper + * (typically Transport) may not be able to re-use a persistent TCP + * connection to the server for a subsequent "keep-alive" request. + * + * The request Body, if non-nil, will be closed by the underlying + * Transport, even on errors. + * + * On error, any Response can be ignored. A non-nil Response with a + * non-nil error only occurs when CheckRedirect fails, and even then + * the returned Response.Body is already closed. + * + * Generally Get, Post, or PostForm will be used instead of Do. + * + * If the server replies with a redirect, the Client first uses the + * CheckRedirect function to determine whether the redirect should be + * followed. If permitted, a 301, 302, or 303 redirect causes + * subsequent requests to use HTTP method GET + * (or HEAD if the original request was HEAD), with no body. + * A 307 or 308 redirect preserves the original HTTP method and body, + * provided that the Request.GetBody function is defined. + * The NewRequest function automatically sets GetBody for common + * standard library body types. + * + * Any returned error will be of type *url.Error. The url.Error + * value's Timeout method will report true if the request timed out. */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo + do(req: Request): (Response | undefined) } - interface Group { + interface Client { /** - * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. + * Post issues a POST to the specified URL. * - * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` + * Caller should close resp.Body when done reading from it. + * + * If the provided body is an io.Closer, it is closed after the + * request. + * + * To set custom headers, use NewRequest and Client.Do. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. + * + * See the Client.Do method documentation for details on how redirects + * are handled. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + post(url: string, body: io.Reader): (Response | undefined) } - interface Group { + interface Client { /** - * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. + * PostForm issues a POST to the specified URL, + * with data's keys and values URL-encoded as the request body. + * + * The Content-Type header is set to application/x-www-form-urlencoded. + * To set other headers, use NewRequest and Client.Do. + * + * When err is nil, resp always contains a non-nil resp.Body. + * Caller should close resp.Body when done reading from it. + * + * See the Client.Do method documentation for details on how redirects + * are handled. + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo + postForm(url: string, data: url.Values): (Response | undefined) } - interface Group { + interface Client { /** - * AddRoute registers a new Routable with Router + * Head issues a HEAD to the specified URL. If the response is one of the + * following redirect codes, Head follows the redirect after calling the + * Client's CheckRedirect function: + * + * ``` + * 301 (Moved Permanently) + * 302 (Found) + * 303 (See Other) + * 307 (Temporary Redirect) + * 308 (Permanent Redirect) + * ``` + * + * To make a request with a specified context.Context, use NewRequestWithContext + * and Client.Do. */ - addRoute(route: Routable): RouteInfo + head(url: string): (Response | undefined) } - /** - * IPExtractor is a function to extract IP addr from http.Request. - * Set appropriate one to Echo#IPExtractor. - * See https://echo.labstack.com/guide/ip-address for more details. - */ - interface IPExtractor {(_arg0: http.Request): string } - /** - * Logger defines the logging interface that Echo uses internally in few places. - * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. - */ - interface Logger { - /** - * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. - * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, - * and underlying FileSystem errors. - * `logger` middleware will use this method to write its JSON payload. - */ - write(p: string): number + interface Client { /** - * Error logs the error + * CloseIdleConnections closes any connections on its Transport which + * were previously connected from previous requests but are now + * sitting idle in a "keep-alive" state. It does not interrupt any + * connections currently in use. + * + * If the Client's Transport does not have a CloseIdleConnections method + * then this method does nothing. */ - error(err: Error): void + closeIdleConnections(): void } /** - * Response wraps an http.ResponseWriter and implements its interface to be used - * by an HTTP handler to construct an HTTP response. - * See: https://golang.org/pkg/net/http/#ResponseWriter + * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an + * HTTP response or the Cookie header of an HTTP request. + * + * See https://tools.ietf.org/html/rfc6265 for details. */ - interface Response { - writer: http.ResponseWriter - status: number - size: number - committed: boolean - } - interface Response { - /** - * Header returns the header map for the writer that will be sent by - * WriteHeader. Changing the header after a call to WriteHeader (or Write) has - * no effect unless the modified headers were declared as trailers by setting - * the "Trailer" header before the call to WriteHeader (see example) - * To suppress implicit response headers, set their value to nil. - * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers - */ - header(): http.Header - } - interface Response { + interface Cookie { + name: string + value: string + path: string // optional + domain: string // optional + expires: time.Time // optional + rawExpires: string // for reading cookies only /** - * Before registers a function which is called just before the response is written. + * MaxAge=0 means no 'Max-Age' attribute specified. + * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' + * MaxAge>0 means Max-Age attribute present and given in seconds */ - before(fn: () => void): void + maxAge: number + secure: boolean + httpOnly: boolean + sameSite: SameSite + raw: string + unparsed: Array // Raw text of unparsed attribute-value pairs } - interface Response { + interface Cookie { /** - * After registers a function which is called just after the response is written. - * If the `Content-Length` is unknown, none of the after function is executed. + * String returns the serialization of the cookie for use in a Cookie + * header (if only Name and Value are set) or a Set-Cookie response + * header (if other fields are set). + * If c is nil or c.Name is invalid, the empty string is returned. */ - after(fn: () => void): void + string(): string } - interface Response { + interface Cookie { /** - * WriteHeader sends an HTTP response header with status code. If WriteHeader is - * not called explicitly, the first call to Write will trigger an implicit - * WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly - * used to send error codes. + * Valid reports whether the cookie is valid. */ - writeHeader(code: number): void + valid(): void } - interface Response { + // @ts-ignore + import mathrand = rand + /** + * A Header represents the key-value pairs in an HTTP header. + * + * The keys should be in canonical form, as returned by + * CanonicalHeaderKey. + */ + interface Header extends _TygojaDict{} + interface Header { /** - * Write writes the data to the connection as part of an HTTP reply. + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. + * The key is case insensitive; it is canonicalized by + * CanonicalHeaderKey. */ - write(b: string): number + add(key: string): void } - interface Response { + interface Header { /** - * Flush implements the http.Flusher interface to allow an HTTP handler to flush - * buffered data to the client. - * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) + * Set sets the header entries associated with key to the + * single element value. It replaces any existing values + * associated with key. The key is case insensitive; it is + * canonicalized by textproto.CanonicalMIMEHeaderKey. + * To use non-canonical keys, assign to the map directly. */ - flush(): void + set(key: string): void } - interface Response { + interface Header { /** - * Hijack implements the http.Hijacker interface to allow an HTTP handler to - * take over the connection. - * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) + * Get gets the first value associated with the given key. If + * there are no values associated with the key, Get returns "". + * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical keys, + * access the map directly. */ - hijack(): [net.Conn, (bufio.ReadWriter | undefined)] + get(key: string): string } - interface Routes { + interface Header { /** - * Reverse reverses route to URL string by replacing path parameters with given params values. + * Values returns all values associated with the given key. + * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * used to canonicalize the provided key. To use non-canonical + * keys, access the map directly. + * The returned slice is not a copy. */ - reverse(name: string, ...params: { - }[]): string + values(key: string): Array } - interface Routes { + interface Header { /** - * FindByMethodPath searched for matching route info by method and path + * Del deletes the values associated with key. + * The key is case insensitive; it is canonicalized by + * CanonicalHeaderKey. */ - findByMethodPath(method: string, path: string): RouteInfo + del(key: string): void } - interface Routes { + interface Header { /** - * FilterByMethod searched for matching route info by method + * Write writes a header in wire format. */ - filterByMethod(method: string): Routes + write(w: io.Writer): void } - interface Routes { + interface Header { /** - * FilterByPath searched for matching route info by path + * Clone returns a copy of h or nil if h is nil. */ - filterByPath(path: string): Routes + clone(): Header } - interface Routes { + interface Header { /** - * FilterByName searched for matching route info by name + * WriteSubset writes a header in wire format. + * If exclude is not nil, keys where exclude[key] == true are not written. + * Keys are not canonicalized before checking the exclude map. */ - filterByName(name: string): Routes + writeSubset(w: io.Writer, exclude: _TygojaDict): void } + // @ts-ignore + import urlpkg = url /** - * Router is interface for routing request contexts to registered routes. + * Response represents the response from an HTTP request. * - * Contract between Echo/Context instance and the router: - * * all routes must be added through methods on echo.Echo instance. - * ``` - * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). - * ``` - * * Router must populate Context during Router.Route call with: - * ``` - * * RoutableContext.SetPath - * * RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) - * * RoutableContext.SetRouteInfo - * And optionally can set additional information to Context with RoutableContext.Set - * ``` + * The Client and Transport return Responses from servers once + * the response headers have been received. The response body + * is streamed on demand as the Body field is read. */ - interface Router { + interface Response { + status: string // e.g. "200 OK" + statusCode: number // e.g. 200 + proto: string // e.g. "HTTP/1.0" + protoMajor: number // e.g. 1 + protoMinor: number // e.g. 0 /** - * Add registers Routable with the Router and returns registered RouteInfo + * Header maps header keys to values. If the response had multiple + * headers with the same key, they may be concatenated, with comma + * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers + * be semantically equivalent to a comma-delimited sequence.) When + * Header values are duplicated by other fields in this struct (e.g., + * ContentLength, TransferEncoding, Trailer), the field values are + * authoritative. + * + * Keys in the map are canonicalized (see CanonicalHeaderKey). */ - add(routable: Routable): RouteInfo + header: Header /** - * Remove removes route from the Router + * Body represents the response body. + * + * The response body is streamed on demand as the Body field + * is read. If the network connection fails or the server + * terminates the response, Body.Read calls return an error. + * + * The http Client and Transport guarantee that Body is always + * non-nil, even on responses without a body or responses with + * a zero-length body. It is the caller's responsibility to + * close Body. The default HTTP client's Transport may not + * reuse HTTP/1.x "keep-alive" TCP connections if the Body is + * not read to completion and closed. + * + * The Body is automatically dechunked if the server replied + * with a "chunked" Transfer-Encoding. + * + * As of Go 1.12, the Body will also implement io.Writer + * on a successful "101 Switching Protocols" response, + * as used by WebSockets and HTTP/2's "h2c" mode. */ - remove(method: string, path: string): void + body: io.ReadCloser /** - * Routes returns information about all registered routes + * ContentLength records the length of the associated content. The + * value -1 indicates that the length is unknown. Unless Request.Method + * is "HEAD", values >= 0 indicate that the given number of bytes may + * be read from Body. */ - routes(): Routes + contentLength: number /** - * Route searches Router for matching route and applies it to the given context. In case when no matching method - * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 - * handler function. + * Contains transfer encodings from outer-most to inner-most. Value is + * nil, means that "identity" encoding is used. */ - route(c: RoutableContext): HandlerFunc - } - /** - * Routable is interface for registering Route with Router. During route registration process the Router will - * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional - * information about registered route can be stored in Routes (i.e. privileges used with route etc.) - */ - interface Routable { + transferEncoding: Array /** - * ToRouteInfo converts Routable to RouteInfo - * - * This method is meant to be used by Router after it parses url for path parameters, to store information about - * route just added. + * Close records whether the header directed that the connection be + * closed after reading Body. The value is advice for clients: neither + * ReadResponse nor Response.Write ever closes a connection. */ - toRouteInfo(params: Array): RouteInfo + close: boolean /** - * ToRoute converts Routable to Route which Router uses to register the method handler for path. - * - * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to - * add Route to Router. + * Uncompressed reports whether the response was sent compressed but + * was decompressed by the http package. When true, reading from + * Body yields the uncompressed content instead of the compressed + * content actually set from the server, ContentLength is set to -1, + * and the "Content-Length" and "Content-Encoding" fields are deleted + * from the responseHeader. To get the original response from + * the server, set Transport.DisableCompression to true. */ - toRoute(): Route + uncompressed: boolean /** - * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. + * Trailer maps trailer keys to values in the same + * format as Header. * - * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group - * middlewares included in actually registered Route. - */ - forGroup(pathPrefix: string, middlewares: Array): Routable - } - /** - * Routes is collection of RouteInfo instances with various helper methods. - */ - interface Routes extends Array{} - /** - * RouteInfo describes registered route base fields. - * Method+Path pair uniquely identifies the Route. Name can have duplicates. - */ - interface RouteInfo { - method(): string - path(): string - name(): string - params(): Array - reverse(...params: { - }[]): string - } - /** - * PathParams is collections of PathParam instances with various helper methods - */ - interface PathParams extends Array{} - interface PathParams { - /** - * Get returns path parameter value for given name or default value. + * The Trailer initially contains only nil values, one for + * each key specified in the server's "Trailer" header + * value. Those values are not added to Header. + * + * Trailer must not be accessed concurrently with Read calls + * on the Body. + * + * After Body.Read has returned io.EOF, Trailer will contain + * any trailer values sent by the server. */ - get(name: string, defaultValue: string): string - } -} - -/** - * 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 { + trailer: Header /** - * Time returns the internal [time.Time] instance. + * Request is the request that was sent to obtain this Response. + * Request's Body is nil (having already been consumed). + * This is only populated for Client requests. */ - time(): time.Time - } - interface DateTime { + request?: Request /** - * IsZero checks whether the current DateTime instance has zero time value. + * TLS contains information about the TLS connection on which the + * response was received. It is nil for unencrypted responses. + * The pointer is shared between responses and should not be + * modified. */ - isZero(): boolean + tls?: tls.ConnectionState } - interface DateTime { + interface Response { /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. + * Cookies parses and returns the cookies set in the Set-Cookie headers. */ - string(): string + cookies(): Array<(Cookie | undefined)> } - interface DateTime { + interface Response { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Location returns the URL of the response's "Location" header, + * if present. Relative redirects are resolved relative to + * the Response's Request. ErrNoLocation is returned if no + * Location header is present. */ - marshalJSON(): string + location(): (url.URL | undefined) } - interface DateTime { + interface Response { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * ProtoAtLeast reports whether the HTTP protocol used + * in the response is at least major.minor. */ - unmarshalJSON(b: string): void + protoAtLeast(major: number): boolean } - interface DateTime { + interface Response { /** - * Value implements the [driver.Valuer] interface. + * Write writes r to w in the HTTP/1.x server response format, + * including the status line, headers, body, and optional trailer. + * + * This method consults the following fields of the response r: + * + * StatusCode + * ProtoMajor + * ProtoMinor + * Request.Method + * TransferEncoding + * Trailer + * Body + * ContentLength + * Header, values for non-canonical keys will have unpredictable behavior + * + * The Response Body is closed after it is sent. */ - value(): driver.Value + write(w: io.Writer): void } - interface DateTime { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. - */ - scan(value: any): void + /** + * A Handler responds to an HTTP request. + * + * ServeHTTP should write reply headers and data to the ResponseWriter + * and then return. Returning signals that the request is finished; it + * is not valid to use the ResponseWriter or read from the + * Request.Body after or concurrently with the completion of the + * ServeHTTP call. + * + * Depending on the HTTP client software, HTTP protocol version, and + * any intermediaries between the client and the Go server, it may not + * be possible to read from the Request.Body after writing to the + * ResponseWriter. Cautious handlers should read the Request.Body + * first, and then reply. + * + * Except for reading the body, handlers should not modify the + * provided Request. + * + * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes + * that the effect of the panic was isolated to the active request. + * It recovers the panic, logs a stack trace to the server error log, + * and either closes the network connection or sends an HTTP/2 + * RST_STREAM, depending on the HTTP protocol. To abort a handler so + * the client sees an interrupted response but the server doesn't log + * an error, panic with the value ErrAbortHandler. + */ + interface Handler { + serveHTTP(_arg0: ResponseWriter, _arg1: Request): void + } + /** + * A ConnState represents the state of a client connection to a server. + * It's used by the optional Server.ConnState hook. + */ + interface ConnState extends Number{} + interface ConnState { + string(): string } } @@ -14074,92 +13353,290 @@ namespace store { } } +namespace mailer { + /** + * Mailer defines a base mail client interface. + */ + interface Mailer { + /** + * Send sends an email with the provided Message. + */ + send(message: Message): void + } +} + /** - * Package oauth2 provides support for making - * OAuth2 authorized and authenticated HTTP requests, - * as specified in RFC 6749. - * It can additionally grant authorization with Bearer JWT. + * 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 oauth2 { +namespace sql { /** - * An AuthCodeOption is passed to Config.AuthCodeURL. + * IsolationLevel is the transaction isolation level used in TxOptions. */ - interface AuthCodeOption { + interface IsolationLevel extends Number{} + interface IsolationLevel { + /** + * String returns the name of the transaction isolation level. + */ + string(): string } /** - * Token represents the credentials used to authorize - * the requests to access protected resources on the OAuth 2.0 - * provider's backend. + * 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. * - * Most users of this package should not access fields of Token - * directly. They're exported mostly for use by related packages - * implementing derivative OAuth2 flows. + * 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 Token { + interface Conn { + } + interface Conn { /** - * AccessToken is the token that authorizes and authenticates - * the requests. + * PingContext verifies the connection to the database is still alive. */ - accessToken: string + 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 | undefined) + } + 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 | undefined) + } + 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 | undefined) + } + 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 | undefined) + } + 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(): reflect.Type + } + interface ColumnType { + /** + * Nullable reports whether the column may be null. + * If a driver does not support this property ok will be false. + */ + nullable(): boolean + } + interface ColumnType { + /** + * DatabaseTypeName returns the database system name of the column type. If an empty + * string is returned, then the driver type name is not supported. + * Consult your driver documentation for a list of driver data types. Length specifiers + * are not included. + * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", + * "INT", and "BIGINT". + */ + databaseTypeName(): string + } + /** + * Row is the result of calling QueryRow to select a single row. + */ + interface Row { + } + interface Row { /** - * TokenType is the type of token. - * The Type method returns either this or "Bearer", the default. + * 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. */ - tokenType: string + scan(...dest: any[]): void + } + interface Row { /** - * RefreshToken is a token that's used by the application - * (as opposed to the user) to refresh the access token - * if it expires. + * 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. */ - refreshToken: string + err(): void + } +} + +/** + * 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 { /** - * Expiry is the optional expiration time of the access token. - * - * If zero, TokenSource implementations will reuse the same - * token forever and RefreshToken or equivalent - * mechanisms for that TokenSource will not be used. + * Time returns the internal [time.Time] instance. */ - expiry: time.Time + time(): time.Time } - interface Token { + interface DateTime { /** - * Type returns t.TokenType if non-empty, else "Bearer". + * IsZero checks whether the current DateTime instance has zero time value. */ - type(): string + isZero(): boolean } - interface Token { + interface DateTime { /** - * SetAuthHeader sets the Authorization header to r using the access - * token in t. + * String serializes the current DateTime instance into a formatted + * UTC date string. * - * This method is unnecessary when using Transport or an HTTP Client - * returned by this package. + * The zero value is serialized to an empty string. */ - setAuthHeader(r: http.Request): void + string(): string } - interface Token { + interface DateTime { /** - * WithExtra returns a new Token that's a clone of t, but using the - * provided raw extra map. This is only intended for use by packages - * implementing derivative OAuth2 flows. + * MarshalJSON implements the [json.Marshaler] interface. */ - withExtra(extra: { - }): (Token | undefined) + marshalJSON(): string } - interface Token { + interface DateTime { /** - * Extra returns an extra field. - * Extra fields are key-value pairs returned by the server as a - * part of the token retrieval response. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - extra(key: string): { + unmarshalJSON(b: string): void } + interface DateTime { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value } - interface Token { + interface DateTime { /** - * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. */ - valid(): boolean + scan(value: any): void } } @@ -14339,222 +13816,92 @@ namespace models { */ refreshUpdated(): void } - interface BaseModel { - /** - * PostScan implements the [dbx.PostScanner] interface. - * - * It is executed right after the model was populated with the db row values. - */ - postScan(): void - } - // @ts-ignore - import validation = ozzo_validation - /** - * CollectionBaseOptions defines the "base" Collection.Options fields. - */ - interface CollectionBaseOptions { - } - interface CollectionBaseOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - /** - * CollectionAuthOptions defines the "auth" Collection.Options fields. - */ - interface CollectionAuthOptions { - manageRule?: string - allowOAuth2Auth: boolean - allowUsernameAuth: boolean - allowEmailAuth: boolean - requireEmail: boolean - exceptEmailDomains: Array - onlyEmailDomains: Array - minPasswordLength: number - } - interface CollectionAuthOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - /** - * CollectionViewOptions defines the "view" Collection.Options fields. - */ - interface CollectionViewOptions { - query: string - } - interface CollectionViewOptions { - /** - * Validate implements [validation.Validatable] interface. - */ - validate(): void - } - type _subMHkHQ = BaseModel - interface Param extends _subMHkHQ { - key: string - value: types.JsonRaw - } - interface Param { - tableName(): string - } - type _subMGMLI = BaseModel - interface Request extends _subMGMLI { - url: string - method: string - status: number - auth: string - userIp: string - remoteIp: string - referer: string - userAgent: string - meta: types.JsonMap - } - interface Request { - tableName(): string - } - interface TableInfoRow { - /** - * the `db:"pk"` tag has special semantic so we cannot rename - * the original field without specifying a custom mapper - */ - pk: number - index: number - name: string - type: string - notNull: boolean - defaultValue: types.JsonRaw - } -} - -namespace subscriptions { - /** - * Broker defines a struct for managing subscriptions clients. - */ - interface Broker { - } - interface Broker { - /** - * Clients returns a shallow copy of all registered clients indexed - * with their connection id. - */ - clients(): _TygojaDict - } - interface Broker { - /** - * ClientById finds a registered client by its id. - * - * Returns non-nil error when client with clientId is not registered. - */ - clientById(clientId: string): Client - } - interface Broker { - /** - * Register adds a new client to the broker instance. - */ - register(client: Client): void - } - interface Broker { - /** - * Unregister removes a single client by its id. - * - * If client with clientId doesn't exist, this method does nothing. - */ - unregister(clientId: string): void - } -} - -namespace mailer { - /** - * Mailer defines a base mail client interface. - */ - interface Mailer { - /** - * Send sends an email with the provided Message. - */ - send(message: Message): 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 { + interface BaseModel { /** - * RemoveAll removes all registered handlers. + * PostScan implements the [dbx.PostScanner] interface. + * + * It is executed right after the model was populated with the db row values. */ - removeAll(): void + postScan(): void } - interface Hook { + // @ts-ignore + import validation = ozzo_validation + /** + * CollectionBaseOptions defines the "base" Collection.Options fields. + */ + interface CollectionBaseOptions { + } + interface CollectionBaseOptions { /** - * 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 + * Validate implements [validation.Validatable] interface. */ - trigger(data: T, ...oneOffHandlers: Handler[]): void + validate(): 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). + * CollectionAuthOptions defines the "auth" Collection.Options fields. */ - type _subdssyw = mainHook - interface TaggedHook extends _subdssyw { + interface CollectionAuthOptions { + manageRule?: string + allowOAuth2Auth: boolean + allowUsernameAuth: boolean + allowEmailAuth: boolean + requireEmail: boolean + exceptEmailDomains: Array + onlyEmailDomains: Array + minPasswordLength: number } - interface TaggedHook { + interface CollectionAuthOptions { /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. + * Validate implements [validation.Validatable] interface. */ - canTriggerOn(tags: Array): boolean + validate(): void } - interface TaggedHook { + /** + * CollectionViewOptions defines the "view" Collection.Options fields. + */ + interface CollectionViewOptions { + query: string + } + interface CollectionViewOptions { /** - * 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. + * Validate implements [validation.Validatable] interface. */ - preAdd(fn: Handler): string + validate(): void } - interface TaggedHook { + type _subapxEF = BaseModel + interface Param extends _subapxEF { + key: string + value: types.JsonRaw + } + interface Param { + tableName(): string + } + type _subhRGTt = BaseModel + interface Request extends _subhRGTt { + url: string + method: string + status: number + auth: string + userIp: string + remoteIp: string + referer: string + userAgent: string + meta: types.JsonMap + } + interface Request { + tableName(): string + } + interface TableInfoRow { /** - * 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. + * the `db:"pk"` tag has special semantic so we cannot rename + * the original field without specifying a custom mapper */ - add(fn: Handler): string + pk: number + index: number + name: string + type: string + notNull: boolean + defaultValue: types.JsonRaw } } @@ -16072,1658 +15419,1513 @@ namespace pflag { } interface FlagSet { /** - * Uint8 defines a uint8 flag with specified name, default value, and usage string. - * The return value is the address of a uint8 variable that stores the value of the flag. - */ - uint8(name: string, value: number, usage: string): (number | undefined) - } - interface FlagSet { - /** - * Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. - */ - uint8P(name: string, value: number, usage: string): (number | undefined) - } - interface FlagSet { - /** - * GetUintSlice returns the []uint value of a flag with the given name. - */ - getUintSlice(name: string): Array - } - interface FlagSet { - /** - * UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. - * The argument p points to a []uint variable in which to store the value of the flag. - */ - uintSliceVar(p: Array, name: string, value: Array, usage: string): void - } - interface FlagSet { - /** - * UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. - */ - uintSliceVarP(p: Array, name: string, value: Array, usage: string): void - } - interface FlagSet { - /** - * UintSlice defines a []uint flag with specified name, default value, and usage string. - * The return value is the address of a []uint variable that stores the value of the flag. - */ - uintSlice(name: string, value: Array, usage: string): (Array | undefined) - } - interface FlagSet { - /** - * UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. - */ - uintSliceP(name: string, value: Array, usage: string): (Array | undefined) - } -} - -/** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. - */ -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag - /** - * FParseErrWhitelist configures Flag parse errors to be ignored - */ - interface FParseErrWhitelist extends flag.ParseErrorsWhitelist{} - /** - * Group Structure to manage groups for commands - */ - interface Group { - id: string - title: string - } - /** - * 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 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 - } - 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. + * Uint8 defines a uint8 flag with specified name, default value, and usage string. + * The return value is the address of a uint8 variable that stores the value of the flag. */ - s3: S3Config + uint8(name: string, value: number, usage: string): (number | undefined) } - interface BackupsConfig { + interface FlagSet { /** - * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. + * Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. */ - validate(): void - } - interface MetaConfig { - appName: string - appUrl: string - hideControls: boolean - senderName: string - senderAddress: string - verificationTemplate: EmailTemplate - resetPasswordTemplate: EmailTemplate - confirmEmailChangeTemplate: EmailTemplate + uint8P(name: string, value: number, usage: string): (number | undefined) } - interface MetaConfig { + interface FlagSet { /** - * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. + * GetUintSlice returns the []uint value of a flag with the given name. */ - validate(): void - } - interface LogsConfig { - maxDays: number + getUintSlice(name: string): Array } - interface LogsConfig { + interface FlagSet { /** - * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. + * UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. + * The argument p points to a []uint variable in which to store the value of the flag. */ - validate(): void - } - interface AuthProviderConfig { - enabled: boolean - clientId: string - clientSecret: string - authUrl: string - tokenUrl: string - userApiUrl: string + uintSliceVar(p: Array, name: string, value: Array, usage: string): void } - interface AuthProviderConfig { + interface FlagSet { /** - * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. + * UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. */ - validate(): void + uintSliceVarP(p: Array, name: string, value: Array, usage: string): void } - interface AuthProviderConfig { + interface FlagSet { /** - * SetupProvider loads the current AuthProviderConfig into the specified provider. + * UintSlice defines a []uint flag with specified name, default value, and usage string. + * The return value is the address of a []uint variable that stores the value of the flag. */ - setupProvider(provider: auth.Provider): void - } - /** - * Deprecated: Will be removed in v0.9+ - */ - interface EmailAuthConfig { - enabled: boolean - exceptDomains: Array - onlyDomains: Array - minPasswordLength: number + uintSlice(name: string, value: Array, usage: string): (Array | undefined) } - interface EmailAuthConfig { + interface FlagSet { /** - * Deprecated: Will be removed in v0.9+ + * UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. */ - validate(): void + uintSliceP(name: string, value: Array, usage: string): (Array | undefined) } } -/** - * Package daos handles common PocketBase DB model manipulations. - * - * Think of daos as DB repository and service layer in one. - */ -namespace daos { - /** - * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. - */ - interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } - // @ts-ignore - import validation = ozzo_validation - interface RequestsStatsItem { - total: number - date: types.DateTime +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void } } /** - * Package core is the backbone of PocketBase. + * Package echo implements high performance, minimalist Go web framework. * - * It defines the main PocketBase App interface and its base implementation. + * 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 core { - interface BootstrapEvent { - app: App - } - interface TerminateEvent { - app: App - } - interface ServeEvent { - app: App - router?: echo.Echo - server?: http.Server - certManager?: autocert.Manager - } - interface ApiErrorEvent { - httpContext: echo.Context - error: Error - } - type _subILctd = BaseModelEvent - interface ModelEvent extends _subILctd { - dao?: daos.Dao - } - type _subrzCXG = BaseCollectionEvent - interface MailerRecordEvent extends _subrzCXG { - mailClient: mailer.Mailer - message?: mailer.Message - record?: models.Record - meta: _TygojaDict +namespace echo { + /** + * Binder is the interface that wraps the Bind method. + */ + interface Binder { + bind(c: Context, i: { + }): void } - interface MailerAdminEvent { - mailClient: mailer.Mailer - message?: mailer.Message - admin?: models.Admin - meta: _TygojaDict + /** + * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and + * be able to be routed by Router. + */ + interface ServableContext { + /** + * Reset resets the context after request completes. It must be called along + * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. + * See `Echo#ServeHTTP()` + */ + reset(r: http.Request, w: http.ResponseWriter): void } - interface RealtimeConnectEvent { - httpContext: echo.Context - client: subscriptions.Client + // @ts-ignore + import stdContext = context + /** + * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. + */ + interface JSONSerializer { + serialize(c: Context, i: { + }, indent: string): void + deserialize(c: Context, i: { + }): void } - interface RealtimeDisconnectEvent { - httpContext: echo.Context - client: subscriptions.Client + /** + * HTTPErrorHandler is a centralized HTTP error handler. + */ + interface HTTPErrorHandler {(c: Context, err: Error): void } + /** + * Validator is the interface that wraps the Validate function. + */ + interface Validator { + validate(i: { + }): void } - interface RealtimeMessageEvent { - httpContext: echo.Context - client: subscriptions.Client - message?: subscriptions.Message + /** + * Renderer is the interface that wraps the Render function. + */ + interface Renderer { + render(_arg0: io.Writer, _arg1: string, _arg2: { + }, _arg3: Context): void } - interface RealtimeSubscribeEvent { - httpContext: echo.Context - client: subscriptions.Client - subscriptions: Array + /** + * Group is a set of sub-routes for a specified route. It can be used for inner + * routes that share a common middleware or functionality that should be separate + * from the parent echo instance while still inheriting from it. + */ + interface Group { } - interface SettingsListEvent { - httpContext: echo.Context - redactedSettings?: settings.Settings + interface Group { + /** + * Use implements `Echo#Use()` for sub-routes within the Group. + * Group middlewares are not executed on request when there is no matching route found. + */ + use(...middleware: MiddlewareFunc[]): void } - interface SettingsUpdateEvent { - httpContext: echo.Context - oldSettings?: settings.Settings - newSettings?: settings.Settings + interface Group { + /** + * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. + */ + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subzyoHt = BaseCollectionEvent - interface RecordsListEvent extends _subzyoHt { - httpContext: echo.Context - records: Array<(models.Record | undefined)> - result?: search.Result + interface Group { + /** + * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. + */ + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subiZWjg = BaseCollectionEvent - interface RecordViewEvent extends _subiZWjg { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. + */ + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subXRlLT = BaseCollectionEvent - interface RecordCreateEvent extends _subXRlLT { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict + interface Group { + /** + * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. + */ + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subkDpOa = BaseCollectionEvent - interface RecordUpdateEvent extends _subkDpOa { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict + interface Group { + /** + * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. + */ + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subUAqlt = BaseCollectionEvent - interface RecordDeleteEvent extends _subUAqlt { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. + */ + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subIPVTm = BaseCollectionEvent - interface RecordAuthEvent extends _subIPVTm { - httpContext: echo.Context - record?: models.Record - token: string - meta: any + interface Group { + /** + * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. + */ + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subMRbKp = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subMRbKp { - httpContext: echo.Context - record?: models.Record - identity: string - password: string + interface Group { + /** + * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. + */ + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subbEbir = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subbEbir { - httpContext: echo.Context - providerName: string - providerClient: auth.Provider - record?: models.Record - oAuth2User?: auth.AuthUser - isNewRecord: boolean + interface Group { + /** + * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. + */ + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subcrxER = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subcrxER { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. + */ + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - type _subfoFRl = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subfoFRl { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. + */ + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - type _subkRWOI = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subkRWOI { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * Group creates a new sub-group with prefix and optional sub-group-level middleware. + * Important! Group middlewares are only executed in case there was exact route match and not + * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add + * a catch-all route `/*` for the group which handler returns always 404 + */ + group(prefix: string, ...middleware: MiddlewareFunc[]): (Group | undefined) } - type _subXwTSq = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subXwTSq { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * Static implements `Echo#Static()` for sub-routes within the Group. + */ + static(pathPrefix: string): RouteInfo } - type _subisziS = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subisziS { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. + * + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. + */ + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - type _subQazEt = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subQazEt { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * FileFS implements `Echo#FileFS()` for sub-routes within the Group. + */ + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - type _subDDoxK = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subDDoxK { - httpContext: echo.Context - record?: models.Record + interface Group { + /** + * File implements `Echo#File()` for sub-routes within the Group. Panics on error. + */ + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - type _subScNif = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subScNif { - httpContext: echo.Context - record?: models.Record - externalAuths: Array<(models.ExternalAuth | undefined)> + interface Group { + /** + * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. + * + * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` + */ + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - type _subVOahu = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subVOahu { - httpContext: echo.Context - record?: models.Record - externalAuth?: models.ExternalAuth + interface Group { + /** + * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. + */ + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - interface AdminsListEvent { - httpContext: echo.Context - admins: Array<(models.Admin | undefined)> - result?: search.Result + interface Group { + /** + * AddRoute registers a new Routable with Router + */ + addRoute(route: Routable): RouteInfo } - interface AdminViewEvent { - httpContext: echo.Context - admin?: models.Admin + /** + * IPExtractor is a function to extract IP addr from http.Request. + * Set appropriate one to Echo#IPExtractor. + * See https://echo.labstack.com/guide/ip-address for more details. + */ + interface IPExtractor {(_arg0: http.Request): string } + /** + * Logger defines the logging interface that Echo uses internally in few places. + * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. + */ + interface Logger { + /** + * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. + * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, + * and underlying FileSystem errors. + * `logger` middleware will use this method to write its JSON payload. + */ + write(p: string): number + /** + * Error logs the error + */ + error(err: Error): void } - interface AdminCreateEvent { - httpContext: echo.Context - admin?: models.Admin + /** + * Response wraps an http.ResponseWriter and implements its interface to be used + * by an HTTP handler to construct an HTTP response. + * See: https://golang.org/pkg/net/http/#ResponseWriter + */ + interface Response { + writer: http.ResponseWriter + status: number + size: number + committed: boolean } - interface AdminUpdateEvent { - httpContext: echo.Context - admin?: models.Admin + interface Response { + /** + * Header returns the header map for the writer that will be sent by + * WriteHeader. Changing the header after a call to WriteHeader (or Write) has + * no effect unless the modified headers were declared as trailers by setting + * the "Trailer" header before the call to WriteHeader (see example) + * To suppress implicit response headers, set their value to nil. + * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers + */ + header(): http.Header } - interface AdminDeleteEvent { - httpContext: echo.Context - admin?: models.Admin + interface Response { + /** + * Before registers a function which is called just before the response is written. + */ + before(fn: () => void): void } - interface AdminAuthEvent { - httpContext: echo.Context - admin?: models.Admin - token: string + interface Response { + /** + * After registers a function which is called just after the response is written. + * If the `Content-Length` is unknown, none of the after function is executed. + */ + after(fn: () => void): void } - interface AdminAuthWithPasswordEvent { - httpContext: echo.Context - admin?: models.Admin - identity: string - password: string + interface Response { + /** + * WriteHeader sends an HTTP response header with status code. If WriteHeader is + * not called explicitly, the first call to Write will trigger an implicit + * WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly + * used to send error codes. + */ + writeHeader(code: number): void } - interface AdminAuthRefreshEvent { - httpContext: echo.Context - admin?: models.Admin + interface Response { + /** + * Write writes the data to the connection as part of an HTTP reply. + */ + write(b: string): number } - interface AdminRequestPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin + interface Response { + /** + * Flush implements the http.Flusher interface to allow an HTTP handler to flush + * buffered data to the client. + * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) + */ + flush(): void } - interface AdminConfirmPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin + interface Response { + /** + * Hijack implements the http.Hijacker interface to allow an HTTP handler to + * take over the connection. + * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) + */ + hijack(): [net.Conn, (bufio.ReadWriter | undefined)] } - interface CollectionsListEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> - result?: search.Result + interface Routes { + /** + * Reverse reverses route to URL string by replacing path parameters with given params values. + */ + reverse(name: string, ...params: { + }[]): string } - type _subNyqzI = BaseCollectionEvent - interface CollectionViewEvent extends _subNyqzI { - httpContext: echo.Context + interface Routes { + /** + * FindByMethodPath searched for matching route info by method and path + */ + findByMethodPath(method: string, path: string): RouteInfo } - type _subidTiB = BaseCollectionEvent - interface CollectionCreateEvent extends _subidTiB { - httpContext: echo.Context + interface Routes { + /** + * FilterByMethod searched for matching route info by method + */ + filterByMethod(method: string): Routes } - type _subeiEOO = BaseCollectionEvent - interface CollectionUpdateEvent extends _subeiEOO { - httpContext: echo.Context + interface Routes { + /** + * FilterByPath searched for matching route info by path + */ + filterByPath(path: string): Routes } - type _subsMJwt = BaseCollectionEvent - interface CollectionDeleteEvent extends _subsMJwt { - httpContext: echo.Context + interface Routes { + /** + * FilterByName searched for matching route info by name + */ + filterByName(name: string): Routes } - interface CollectionsImportEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> + /** + * Router is interface for routing request contexts to registered routes. + * + * Contract between Echo/Context instance and the router: + * * all routes must be added through methods on echo.Echo instance. + * ``` + * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). + * ``` + * * Router must populate Context during Router.Route call with: + * ``` + * * RoutableContext.SetPath + * * RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) + * * RoutableContext.SetRouteInfo + * And optionally can set additional information to Context with RoutableContext.Set + * ``` + */ + interface Router { + /** + * Add registers Routable with the Router and returns registered RouteInfo + */ + add(routable: Routable): RouteInfo + /** + * Remove removes route from the Router + */ + remove(method: string, path: string): void + /** + * Routes returns information about all registered routes + */ + routes(): Routes + /** + * Route searches Router for matching route and applies it to the given context. In case when no matching method + * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 + * handler function. + */ + route(c: RoutableContext): HandlerFunc } - type _subokvZP = BaseModelEvent - interface FileTokenEvent extends _subokvZP { - httpContext: echo.Context - token: string + /** + * Routable is interface for registering Route with Router. During route registration process the Router will + * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional + * information about registered route can be stored in Routes (i.e. privileges used with route etc.) + */ + interface Routable { + /** + * ToRouteInfo converts Routable to RouteInfo + * + * This method is meant to be used by Router after it parses url for path parameters, to store information about + * route just added. + */ + toRouteInfo(params: Array): RouteInfo + /** + * ToRoute converts Routable to Route which Router uses to register the method handler for path. + * + * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to + * add Route to Router. + */ + toRoute(): Route + /** + * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. + * + * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group + * middlewares included in actually registered Route. + */ + forGroup(pathPrefix: string, middlewares: Array): Routable } - type _subxjpio = BaseCollectionEvent - interface FileDownloadEvent extends _subxjpio { - httpContext: echo.Context - record?: models.Record - fileField?: schema.SchemaField - servedPath: string - servedName: string + /** + * Routes is collection of RouteInfo instances with various helper methods. + */ + interface Routes extends Array{} + /** + * RouteInfo describes registered route base fields. + * Method+Path pair uniquely identifies the Route. Name can have duplicates. + */ + interface RouteInfo { + method(): string + path(): string + name(): string + params(): Array + reverse(...params: { + }[]): string + } + /** + * PathParams is collections of PathParam instances with various helper methods + */ + interface PathParams extends Array{} + interface PathParams { + /** + * Get returns path parameter value for given name or default value. + */ + get(name: string, defaultValue: string): string } } /** - * Package time provides functionality for measuring and displaying time. - * - * The calendrical calculations always assume a Gregorian calendar, with - * no leap seconds. - * - * Monotonic Clocks - * - * Operating systems provide both a “wall clock,” which is subject to - * changes for clock synchronization, and a “monotonic clock,” which is - * not. The general rule is that the wall clock is for telling time and - * the monotonic clock is for measuring time. Rather than split the API, - * in this package the Time returned by time.Now contains both a wall - * clock reading and a monotonic clock reading; later time-telling - * operations use the wall clock reading, but later time-measuring - * operations, specifically comparisons and subtractions, use the - * monotonic clock reading. - * - * For example, this code always computes a positive elapsed time of - * approximately 20 milliseconds, even if the wall clock is changed during - * the operation being timed: - * - * ``` - * start := time.Now() - * ... operation that takes 20 milliseconds ... - * t := time.Now() - * elapsed := t.Sub(start) - * ``` - * - * Other idioms, such as time.Since(start), time.Until(deadline), and - * time.Now().Before(deadline), are similarly robust against wall clock - * resets. - * - * The rest of this section gives the precise details of how operations - * use monotonic clocks, but understanding those details is not required - * to use this package. - * - * The Time returned by time.Now contains a monotonic clock reading. - * If Time t has a monotonic clock reading, t.Add adds the same duration to - * both the wall clock and monotonic clock readings to compute the result. - * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time - * computations, they always strip any monotonic clock reading from their results. - * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation - * of the wall time, they also strip any monotonic clock reading from their results. - * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). - * - * If Times t and u both contain monotonic clock readings, the operations - * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out - * using the monotonic clock readings alone, ignoring the wall clock - * readings. If either t or u contains no monotonic clock reading, these - * operations fall back to using the wall clock readings. - * - * On some systems the monotonic clock will stop if the computer goes to sleep. - * On such a system, t.Sub(u) may not accurately reflect the actual - * time that passed between t and u. - * - * Because the monotonic clock reading has no meaning outside - * the current process, the serialized forms generated by t.GobEncode, - * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic - * clock reading, and t.Format provides no format for it. Similarly, the - * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, - * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. - * t.UnmarshalJSON, and t.UnmarshalText always create times with - * no monotonic clock reading. - * - * Note that the Go == operator compares not just the time instant but - * also the Location and the monotonic clock reading. See the - * documentation for the Time type for a discussion of equality - * testing for Time values. - * - * For debugging, the result of t.String does include the monotonic - * clock reading if present. If t != u because of different monotonic clock readings, - * that difference will be visible when printing t.String() and u.String(). + * Package oauth2 provides support for making + * OAuth2 authorized and authenticated HTTP requests, + * as specified in RFC 6749. + * It can additionally grant authorization with Bearer JWT. */ -namespace time { +namespace oauth2 { /** - * A Month specifies a month of the year (January = 1, ...). + * An AuthCodeOption is passed to Config.AuthCodeURL. */ - interface Month extends Number{} - interface Month { + interface AuthCodeOption { + } + /** + * Token represents the credentials used to authorize + * the requests to access protected resources on the OAuth 2.0 + * provider's backend. + * + * Most users of this package should not access fields of Token + * directly. They're exported mostly for use by related packages + * implementing derivative OAuth2 flows. + */ + interface Token { + /** + * AccessToken is the token that authorizes and authenticates + * the requests. + */ + accessToken: string + /** + * TokenType is the type of token. + * The Type method returns either this or "Bearer", the default. + */ + tokenType: string + /** + * RefreshToken is a token that's used by the application + * (as opposed to the user) to refresh the access token + * if it expires. + */ + refreshToken: string + /** + * Expiry is the optional expiration time of the access token. + * + * If zero, TokenSource implementations will reuse the same + * token forever and RefreshToken or equivalent + * mechanisms for that TokenSource will not be used. + */ + expiry: time.Time + } + interface Token { + /** + * Type returns t.TokenType if non-empty, else "Bearer". + */ + type(): string + } + interface Token { + /** + * SetAuthHeader sets the Authorization header to r using the access + * token in t. + * + * This method is unnecessary when using Transport or an HTTP Client + * returned by this package. + */ + setAuthHeader(r: http.Request): void + } + interface Token { /** - * String returns the English name of the month ("January", "February", ...). + * WithExtra returns a new Token that's a clone of t, but using the + * provided raw extra map. This is only intended for use by packages + * implementing derivative OAuth2 flows. */ - string(): string + withExtra(extra: { + }): (Token | undefined) } - /** - * A Weekday specifies a day of the week (Sunday = 0, ...). - */ - interface Weekday extends Number{} - interface Weekday { + interface Token { /** - * String returns the English name of the day ("Sunday", "Monday", ...). + * Extra returns an extra field. + * Extra fields are key-value pairs returned by the server as a + * part of the token retrieval response. */ - string(): string + extra(key: string): { } - /** - * A Location maps time instants to the zone in use at that time. - * Typically, the Location represents the collection of time offsets - * in use in a geographical area. For many Locations the time offset varies - * depending on whether daylight savings time is in use at the time instant. - */ - interface Location { } - interface Location { + interface Token { /** - * String returns a descriptive name for the time zone information, - * corresponding to the name argument to LoadLocation or FixedZone. + * Valid reports whether t is non-nil, has an AccessToken, and is not expired. */ - string(): string + valid(): boolean } } -/** - * Package reflect implements run-time reflection, allowing a program to - * manipulate objects with arbitrary types. The typical use is to take a value - * with static type interface{} and extract its dynamic type information by - * calling TypeOf, which returns a Type. - * - * A call to ValueOf returns a Value representing the run-time data. - * Zero takes a Type and returns a Value representing a zero value - * for that type. - * - * See "The Laws of Reflection" for an introduction to reflection in Go: - * https://golang.org/doc/articles/laws_of_reflection.html - */ -namespace reflect { +namespace subscriptions { /** - * Type is the representation of a Go type. - * - * Not all methods apply to all kinds of types. Restrictions, - * if any, are noted in the documentation for each method. - * Use the Kind method to find out the kind of type before - * calling kind-specific methods. Calling a method - * inappropriate to the kind of type causes a run-time panic. - * - * Type values are comparable, such as with the == operator, - * so they can be used as map keys. - * Two Type values are equal if they represent identical types. + * Broker defines a struct for managing subscriptions clients. */ - interface Type { - /** - * Align returns the alignment in bytes of a value of - * this type when allocated in memory. - */ - align(): number + interface Broker { + } + interface Broker { /** - * FieldAlign returns the alignment in bytes of a value of - * this type when used as a field in a struct. + * Clients returns a shallow copy of all registered clients indexed + * with their connection id. */ - fieldAlign(): number + clients(): _TygojaDict + } + interface Broker { /** - * Method returns the i'th method in the type's method set. - * It panics if i is not in the range [0, NumMethod()). - * - * For a non-interface type T or *T, the returned Method's Type and Func - * fields describe a function whose first argument is the receiver, - * and only exported methods are accessible. - * - * For an interface type, the returned Method's Type field gives the - * method signature, without a receiver, and the Func field is nil. + * ClientById finds a registered client by its id. * - * Methods are sorted in lexicographic order. + * Returns non-nil error when client with clientId is not registered. */ - method(_arg0: number): Method + clientById(clientId: string): Client + } + interface Broker { /** - * MethodByName returns the method with that name in the type's - * method set and a boolean indicating if the method was found. - * - * For a non-interface type T or *T, the returned Method's Type and Func - * fields describe a function whose first argument is the receiver. - * - * For an interface type, the returned Method's Type field gives the - * method signature, without a receiver, and the Func field is nil. + * Register adds a new client to the broker instance. */ - methodByName(_arg0: string): [Method, boolean] + register(client: Client): void + } + interface Broker { /** - * NumMethod returns the number of methods accessible using Method. + * Unregister removes a single client by its id. * - * Note that NumMethod counts unexported methods only for interface types. - */ - numMethod(): number - /** - * Name returns the type's name within its package for a defined type. - * For other (non-defined) types it returns the empty string. - */ - name(): string - /** - * PkgPath returns a defined type's package path, that is, the import path - * that uniquely identifies the package, such as "encoding/base64". - * If the type was predeclared (string, error) or not defined (*T, struct{}, - * []int, or A where A is an alias for a non-defined type), the package path - * will be the empty string. - */ - pkgPath(): string - /** - * Size returns the number of bytes needed to store - * a value of the given type; it is analogous to unsafe.Sizeof. + * If client with clientId doesn't exist, this method does nothing. */ - size(): number + unregister(clientId: string): void + } +} + +namespace hook { + /** + * Hook defines a concurrent safe structure for handling event hooks + * (aka. callbacks propagation). + */ + interface Hook { + } + interface Hook { /** - * String returns a string representation of the type. - * The string representation may use shortened package names - * (e.g., base64 instead of "encoding/base64") and is not - * guaranteed to be unique among types. To test for type identity, - * compare the Types directly. + * 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). */ - string(): string + preAdd(fn: Handler): string + } + interface Hook { /** - * Kind returns the specific kind of this type. + * 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). */ - kind(): Kind + add(fn: Handler): string + } + interface Hook { /** - * Implements reports whether the type implements the interface type u. + * Remove removes a single hook handler by its id. */ - implements(u: Type): boolean + remove(id: string): void + } + interface Hook { /** - * AssignableTo reports whether a value of the type is assignable to type u. + * RemoveAll removes all registered handlers. */ - assignableTo(u: Type): boolean + removeAll(): void + } + interface Hook { /** - * ConvertibleTo reports whether a value of the type is convertible to type u. - * Even if ConvertibleTo returns true, the conversion may still panic. - * For example, a slice of type []T is convertible to *[N]T, - * but the conversion will panic if its length is less than N. + * 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 */ - convertibleTo(u: Type): boolean + 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 _subqBHMT = mainHook + interface TaggedHook extends _subqBHMT { + } + interface TaggedHook { /** - * Comparable reports whether values of this type are comparable. - * Even if Comparable returns true, the comparison may still panic. - * For example, values of interface type are comparable, - * but the comparison will panic if their dynamic type is not comparable. + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. */ - comparable(): boolean + canTriggerOn(tags: Array): boolean + } + interface TaggedHook { /** - * Bits returns the size of the type in bits. - * It panics if the type's Kind is not one of the - * sized or unsized Int, Uint, Float, or Complex kinds. + * 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. */ - bits(): number + preAdd(fn: Handler): string + } + interface TaggedHook { /** - * ChanDir returns a channel type's direction. - * It panics if the type's Kind is not Chan. + * 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. */ - chanDir(): ChanDir + add(fn: Handler): string + } +} + +namespace settings { + // @ts-ignore + import validation = ozzo_validation + interface TokenConfig { + secret: string + duration: number + } + interface TokenConfig { /** - * IsVariadic reports whether a function type's final input parameter - * is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's - * implicit actual type []T. - * - * For concreteness, if t represents func(x int, y ... float64), then - * - * ``` - * t.NumIn() == 2 - * t.In(0) is the reflect.Type for "int" - * t.In(1) is the reflect.Type for "[]float64" - * t.IsVariadic() == true - * ``` - * - * IsVariadic panics if the type's Kind is not Func. + * Validate makes TokenConfig validatable by implementing [validation.Validatable] interface. */ - isVariadic(): boolean + validate(): void + } + interface SmtpConfig { + enabled: boolean + host: string + port: number + username: string + password: string /** - * Elem returns a type's element type. - * It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice. + * SMTP AUTH - PLAIN (default) or LOGIN */ - elem(): Type + authMethod: string /** - * Field returns a struct type's i'th field. - * It panics if the type's Kind is not Struct. - * It panics if i is not in the range [0, NumField()). + * 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. */ - field(i: number): StructField + tls: boolean + } + interface SmtpConfig { /** - * FieldByIndex returns the nested field corresponding - * to the index sequence. It is equivalent to calling Field - * successively for each index i. - * It panics if the type's Kind is not Struct. + * Validate makes SmtpConfig validatable by implementing [validation.Validatable] interface. */ - fieldByIndex(index: Array): StructField + validate(): void + } + interface S3Config { + enabled: boolean + bucket: string + region: string + endpoint: string + accessKey: string + secret: string + forcePathStyle: boolean + } + interface S3Config { /** - * FieldByName returns the struct field with the given name - * and a boolean indicating if the field was found. + * Validate makes S3Config validatable by implementing [validation.Validatable] interface. */ - fieldByName(name: string): [StructField, boolean] + validate(): void + } + interface BackupsConfig { /** - * FieldByNameFunc returns the struct field with a name - * that satisfies the match function and a boolean indicating if - * the field was found. + * Cron is a cron expression to schedule auto backups, eg. "* * * * *". * - * FieldByNameFunc considers the fields in the struct itself - * and then the fields in any embedded structs, in breadth first order, - * stopping at the shallowest nesting depth containing one or more - * fields satisfying the match function. If multiple fields at that depth - * satisfy the match function, they cancel each other - * and FieldByNameFunc returns no match. - * This behavior mirrors Go's handling of name lookup in - * structs containing embedded fields. + * Leave it empty to disable the auto backups functionality. */ - fieldByNameFunc(match: (_arg0: string) => boolean): [StructField, boolean] + cron: string /** - * In returns the type of a function type's i'th input parameter. - * It panics if the type's Kind is not Func. - * It panics if i is not in the range [0, NumIn()). + * 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. */ - in(i: number): Type + cronMaxKeep: number /** - * Key returns a map type's key type. - * It panics if the type's Kind is not Map. + * S3 is an optional S3 storage config specifying where to store the app backups. */ - key(): Type + s3: S3Config + } + interface BackupsConfig { /** - * Len returns an array type's length. - * It panics if the type's Kind is not Array. + * Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface. */ - len(): number + validate(): void + } + interface MetaConfig { + appName: string + appUrl: string + hideControls: boolean + senderName: string + senderAddress: string + verificationTemplate: EmailTemplate + resetPasswordTemplate: EmailTemplate + confirmEmailChangeTemplate: EmailTemplate + } + interface MetaConfig { /** - * NumField returns a struct type's field count. - * It panics if the type's Kind is not Struct. + * Validate makes MetaConfig validatable by implementing [validation.Validatable] interface. */ - numField(): number + validate(): void + } + interface LogsConfig { + maxDays: number + } + interface LogsConfig { /** - * NumIn returns a function type's input parameter count. - * It panics if the type's Kind is not Func. + * Validate makes LogsConfig validatable by implementing [validation.Validatable] interface. */ - numIn(): number + validate(): void + } + interface AuthProviderConfig { + enabled: boolean + clientId: string + clientSecret: string + authUrl: string + tokenUrl: string + userApiUrl: string + } + interface AuthProviderConfig { /** - * NumOut returns a function type's output parameter count. - * It panics if the type's Kind is not Func. + * Validate makes `ProviderConfig` validatable by implementing [validation.Validatable] interface. */ - numOut(): number + validate(): void + } + interface AuthProviderConfig { /** - * Out returns the type of a function type's i'th output parameter. - * It panics if the type's Kind is not Func. - * It panics if i is not in the range [0, NumOut()). + * SetupProvider loads the current AuthProviderConfig into the specified provider. */ - out(i: number): Type + setupProvider(provider: auth.Provider): void } -} - -/** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { /** - * ReadWriter stores pointers to a Reader and a Writer. - * It implements io.ReadWriter. + * Deprecated: Will be removed in v0.9+ */ - type _subzILxs = Reader&Writer - interface ReadWriter extends _subzILxs { + interface EmailAuthConfig { + enabled: boolean + exceptDomains: Array + onlyDomains: Array + minPasswordLength: number + } + interface EmailAuthConfig { + /** + * Deprecated: Will be removed in v0.9+ + */ + validate(): void } } /** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. + * Package daos handles common PocketBase DB model manipulations. + * + * Think of daos as DB repository and service layer in one. */ -namespace fs { +namespace daos { /** - * A FileInfo describes a file and is returned by Stat. + * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. */ - interface FileInfo { - name(): string // base name of the file - size(): number // length in bytes for regular files; system-dependent for others - mode(): FileMode // file mode bits - modTime(): time.Time // modification time - isDir(): boolean // abbreviation for Mode().IsDir() - sys(): any // underlying data source (can return nil) + interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } + // @ts-ignore + import validation = ozzo_validation + interface RequestsStatsItem { + total: number + date: types.DateTime } } /** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force cgo resolver - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. + * 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 net { +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag /** - * An IP is a single IP address, a slice of bytes. - * Functions in this package accept either 4-byte (IPv4) - * or 16-byte (IPv6) slices as input. - * - * Note that in this documentation, referring to an - * IP address as an IPv4 address or an IPv6 address - * is a semantic property of the address, not just the - * length of the byte slice: a 16-byte slice can still - * be an IPv4 address. + * FParseErrWhitelist configures Flag parse errors to be ignored */ - interface IP extends String{} + interface FParseErrWhitelist extends flag.ParseErrorsWhitelist{} /** - * An IPMask is a bitmask that can be used to manipulate - * IP addresses for IP addressing and routing. - * - * See type IPNet and func ParseCIDR for details. + * Group Structure to manage groups for commands */ - interface IPMask extends String{} + interface Group { + id: string + title: string + } /** - * An IPNet represents an IP network. + * ShellCompDirective is a bit map representing the different behaviors the shell + * can be instructed to have once completions have been provided. */ - interface IPNet { - ip: IP // network number - mask: IPMask // network mask - } - interface IP { + interface ShellCompDirective extends Number{} + /** + * CompletionOptions are the options to control shell completion + */ + interface CompletionOptions { /** - * IsUnspecified reports whether ip is an unspecified address, either - * the IPv4 address "0.0.0.0" or the IPv6 address "::". + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command */ - isUnspecified(): boolean - } - interface IP { + disableDefaultCmd: boolean /** - * IsLoopback reports whether ip is a loopback address. + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions */ - isLoopback(): boolean - } - interface IP { + disableNoDescFlag: boolean /** - * IsPrivate reports whether ip is a private address, according to - * RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). + * DisableDescriptions turns off all completion descriptions for shells + * that support them */ - isPrivate(): boolean - } - interface IP { + disableDescriptions: boolean /** - * IsMulticast reports whether ip is a multicast address. + * HiddenDefaultCmd makes the default 'completion' command hidden */ - isMulticast(): boolean + hiddenDefaultCmd: boolean } - interface IP { - /** - * IsInterfaceLocalMulticast reports whether ip is - * an interface-local multicast address. - */ - isInterfaceLocalMulticast(): boolean +} + +/** + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + interface BootstrapEvent { + app: App } - interface IP { - /** - * IsLinkLocalMulticast reports whether ip is a link-local - * multicast address. - */ - isLinkLocalMulticast(): boolean + interface TerminateEvent { + app: App } - interface IP { - /** - * IsLinkLocalUnicast reports whether ip is a link-local - * unicast address. - */ - isLinkLocalUnicast(): boolean + interface ServeEvent { + app: App + router?: echo.Echo + server?: http.Server + certManager?: autocert.Manager } - interface IP { - /** - * IsGlobalUnicast reports whether ip is a global unicast - * address. - * - * The identification of global unicast addresses uses address type - * identification as defined in RFC 1122, RFC 4632 and RFC 4291 with - * the exception of IPv4 directed broadcast addresses. - * It returns true even if ip is in IPv4 private address space or - * local IPv6 unicast address space. - */ - isGlobalUnicast(): boolean + interface ApiErrorEvent { + httpContext: echo.Context + error: Error } - interface IP { - /** - * To4 converts the IPv4 address ip to a 4-byte representation. - * If ip is not an IPv4 address, To4 returns nil. - */ - to4(): IP + type _subPNoTK = BaseModelEvent + interface ModelEvent extends _subPNoTK { + dao?: daos.Dao } - interface IP { - /** - * To16 converts the IP address ip to a 16-byte representation. - * If ip is not an IP address (it is the wrong length), To16 returns nil. - */ - to16(): IP + type _subRGvDm = BaseCollectionEvent + interface MailerRecordEvent extends _subRGvDm { + mailClient: mailer.Mailer + message?: mailer.Message + record?: models.Record + meta: _TygojaDict } - interface IP { - /** - * DefaultMask returns the default IP mask for the IP address ip. - * Only IPv4 addresses have default masks; DefaultMask returns - * nil if ip is not a valid IPv4 address. - */ - defaultMask(): IPMask + interface MailerAdminEvent { + mailClient: mailer.Mailer + message?: mailer.Message + admin?: models.Admin + meta: _TygojaDict } - interface IP { - /** - * Mask returns the result of masking the IP address ip with mask. - */ - mask(mask: IPMask): IP + interface RealtimeConnectEvent { + httpContext: echo.Context + client: subscriptions.Client } - interface IP { - /** - * String returns the string form of the IP address ip. - * It returns one of 4 forms: - * ``` - * - "", if ip has length 0 - * - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address - * - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address - * - the hexadecimal form of ip, without punctuation, if no other cases apply - * ``` - */ - string(): string + interface RealtimeDisconnectEvent { + httpContext: echo.Context + client: subscriptions.Client } - interface IP { - /** - * MarshalText implements the encoding.TextMarshaler interface. - * The encoding is the same as returned by String, with one exception: - * When len(ip) is zero, it returns an empty slice. - */ - marshalText(): string + interface RealtimeMessageEvent { + httpContext: echo.Context + client: subscriptions.Client + message?: subscriptions.Message } - interface IP { - /** - * UnmarshalText implements the encoding.TextUnmarshaler interface. - * The IP address is expected in a form accepted by ParseIP. - */ - unmarshalText(text: string): void + interface RealtimeSubscribeEvent { + httpContext: echo.Context + client: subscriptions.Client + subscriptions: Array + } + interface SettingsListEvent { + httpContext: echo.Context + redactedSettings?: settings.Settings + } + interface SettingsUpdateEvent { + httpContext: echo.Context + oldSettings?: settings.Settings + newSettings?: settings.Settings + } + type _subOyveX = BaseCollectionEvent + interface RecordsListEvent extends _subOyveX { + httpContext: echo.Context + records: Array<(models.Record | undefined)> + result?: search.Result + } + type _subThnyx = BaseCollectionEvent + interface RecordViewEvent extends _subThnyx { + httpContext: echo.Context + record?: models.Record + } + type _subIVFnF = BaseCollectionEvent + interface RecordCreateEvent extends _subIVFnF { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subeBnsZ = BaseCollectionEvent + interface RecordUpdateEvent extends _subeBnsZ { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subzUNCU = BaseCollectionEvent + interface RecordDeleteEvent extends _subzUNCU { + httpContext: echo.Context + record?: models.Record + } + type _subDvuYX = BaseCollectionEvent + interface RecordAuthEvent extends _subDvuYX { + httpContext: echo.Context + record?: models.Record + token: string + meta: any + } + type _subbSqpX = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subbSqpX { + httpContext: echo.Context + record?: models.Record + identity: string + password: string + } + type _subYHXOK = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subYHXOK { + httpContext: echo.Context + providerName: string + providerClient: auth.Provider + record?: models.Record + oAuth2User?: auth.AuthUser + isNewRecord: boolean + } + type _subImoXE = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subImoXE { + httpContext: echo.Context + record?: models.Record + } + type _subuBXjy = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subuBXjy { + httpContext: echo.Context + record?: models.Record + } + type _subAXNeX = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _subAXNeX { + httpContext: echo.Context + record?: models.Record + } + type _subWEOwy = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subWEOwy { + httpContext: echo.Context + record?: models.Record + } + type _subLIYKs = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subLIYKs { + httpContext: echo.Context + record?: models.Record + } + type _subdGjWf = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subdGjWf { + httpContext: echo.Context + record?: models.Record + } + type _subonrbf = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subonrbf { + httpContext: echo.Context + record?: models.Record + } + type _subkHQSt = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subkHQSt { + httpContext: echo.Context + record?: models.Record + externalAuths: Array<(models.ExternalAuth | undefined)> + } + type _subcRdzl = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subcRdzl { + httpContext: echo.Context + record?: models.Record + externalAuth?: models.ExternalAuth } - interface IP { - /** - * Equal reports whether ip and x are the same IP address. - * An IPv4 address and that same address in IPv6 form are - * considered to be equal. - */ - equal(x: IP): boolean + interface AdminsListEvent { + httpContext: echo.Context + admins: Array<(models.Admin | undefined)> + result?: search.Result } - interface IPMask { - /** - * Size returns the number of leading ones and total bits in the mask. - * If the mask is not in the canonical form--ones followed by zeros--then - * Size returns 0, 0. - */ - size(): number + interface AdminViewEvent { + httpContext: echo.Context + admin?: models.Admin } - interface IPMask { - /** - * String returns the hexadecimal form of m, with no punctuation. - */ - string(): string + interface AdminCreateEvent { + httpContext: echo.Context + admin?: models.Admin } - interface IPNet { - /** - * Contains reports whether the network includes ip. - */ - contains(ip: IP): boolean + interface AdminUpdateEvent { + httpContext: echo.Context + admin?: models.Admin } - interface IPNet { - /** - * Network returns the address's network name, "ip+net". - */ - network(): string + interface AdminDeleteEvent { + httpContext: echo.Context + admin?: models.Admin } - interface IPNet { - /** - * String returns the CIDR notation of n like "192.0.2.0/24" - * or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. - * If the mask is not in the canonical form, it returns the - * string which consists of an IP address, followed by a slash - * character and a mask expressed as hexadecimal form with no - * punctuation like "198.51.100.0/c000ff00". - */ - string(): string + interface AdminAuthEvent { + httpContext: echo.Context + admin?: models.Admin + token: string } - /** - * Addr represents a network end point address. - * - * The two methods Network and String conventionally return strings - * that can be passed as the arguments to Dial, but the exact form - * and meaning of the strings is up to the implementation. - */ - interface Addr { - network(): string // name of the network (for example, "tcp", "udp") - string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") + interface AdminAuthWithPasswordEvent { + httpContext: echo.Context + admin?: models.Admin + identity: string + password: string } -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * The Userinfo type is an immutable encapsulation of username and - * password details for a URL. An existing Userinfo value is guaranteed - * to have a username set (potentially empty, as allowed by RFC 2396), - * and optionally a password. - */ - interface Userinfo { + interface AdminAuthRefreshEvent { + httpContext: echo.Context + admin?: models.Admin } - interface Userinfo { - /** - * Username returns the username. - */ - username(): string + interface AdminRequestPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin } - interface Userinfo { - /** - * Password returns the password in case it is set, and whether it is set. - */ - password(): [string, boolean] + interface AdminConfirmPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin } - interface Userinfo { - /** - * String returns the encoded userinfo information in the standard form - * of "username[:password]". - */ - string(): string + interface CollectionsListEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> + result?: search.Result } -} - -/** - * Copyright 2021 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -/** - * Package x509 parses X.509-encoded keys and certificates. - */ -namespace x509 { - /** - * CertPool is a set of certificates. - */ - interface CertPool { + type _subYCSPM = BaseCollectionEvent + interface CollectionViewEvent extends _subYCSPM { + httpContext: echo.Context } - interface CertPool { - /** - * AddCert adds a certificate to a pool. - */ - addCert(cert: Certificate): void + type _subzRBEP = BaseCollectionEvent + interface CollectionCreateEvent extends _subzRBEP { + httpContext: echo.Context } - interface CertPool { - /** - * AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. - * It appends any certificates found to s and reports whether any certificates - * were successfully parsed. - * - * On many Linux systems, /etc/ssl/cert.pem will contain the system wide set - * of root CAs in a format suitable for this function. - */ - appendCertsFromPEM(pemCerts: string): boolean + type _subxqUkw = BaseCollectionEvent + interface CollectionUpdateEvent extends _subxqUkw { + httpContext: echo.Context } - interface CertPool { - /** - * Subjects returns a list of the DER-encoded subjects of - * all of the certificates in the pool. - * - * Deprecated: if s was returned by SystemCertPool, Subjects - * will not include the system roots. - */ - subjects(): Array + type _subHRvxH = BaseCollectionEvent + interface CollectionDeleteEvent extends _subHRvxH { + httpContext: echo.Context } - // @ts-ignore - import cryptobyte_asn1 = asn1 - interface Certificate { - /** - * Verify attempts to verify c by building one or more chains from c to a - * certificate in opts.Roots, using certificates in opts.Intermediates if - * needed. If successful, it returns one or more chains where the first - * element of the chain is c and the last element is from opts.Roots. - * - * If opts.Roots is nil, the platform verifier might be used, and - * verification details might differ from what is described below. If system - * roots are unavailable the returned error will be of type SystemRootsError. - * - * Name constraints in the intermediates will be applied to all names claimed - * in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim - * example.com if an intermediate doesn't permit it, even if example.com is not - * the name being validated. Note that DirectoryName constraints are not - * supported. - * - * Name constraint validation follows the rules from RFC 5280, with the - * addition that DNS name constraints may use the leading period format - * defined for emails and URIs. When a constraint has a leading period - * it indicates that at least one additional label must be prepended to - * the constrained name to be considered valid. - * - * Extended Key Usage values are enforced nested down a chain, so an intermediate - * or root that enumerates EKUs prevents a leaf from asserting an EKU not in that - * list. (While this is not specified, it is common practice in order to limit - * the types of certificates a CA can issue.) - * - * Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, - * and will not be used to build chains. - * - * WARNING: this function doesn't do any revocation checking. - */ - verify(opts: VerifyOptions): Array> + interface CollectionsImportEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> } - interface Certificate { - /** - * VerifyHostname returns nil if c is a valid certificate for the named host. - * Otherwise it returns an error describing the mismatch. - * - * IP addresses can be optionally enclosed in square brackets and are checked - * against the IPAddresses field. Other names are checked case insensitively - * against the DNSNames field. If the names are valid hostnames, the certificate - * fields can have a wildcard as the left-most label. - * - * Note that the legacy Common Name field is ignored. - */ - verifyHostname(h: string): void + type _submLVfd = BaseModelEvent + interface FileTokenEvent extends _submLVfd { + httpContext: echo.Context + token: string } - /** - * A Certificate represents an X.509 certificate. - */ - interface Certificate { - raw: string // Complete ASN.1 DER content (certificate, signature algorithm and signature). - rawTBSCertificate: string // Certificate part of raw ASN.1 DER content. - rawSubjectPublicKeyInfo: string // DER encoded SubjectPublicKeyInfo. - rawSubject: string // DER encoded Subject - rawIssuer: string // DER encoded Issuer - signature: string - signatureAlgorithm: SignatureAlgorithm - publicKeyAlgorithm: PublicKeyAlgorithm - publicKey: any - version: number - serialNumber?: big.Int - issuer: pkix.Name - subject: pkix.Name - notBefore: time.Time // Validity bounds. - keyUsage: KeyUsage + type _subunTgk = BaseCollectionEvent + interface FileDownloadEvent extends _subunTgk { + httpContext: echo.Context + record?: models.Record + fileField?: schema.SchemaField + servedPath: string + servedName: string + } +} + +/** + * Package reflect implements run-time reflection, allowing a program to + * manipulate objects with arbitrary types. The typical use is to take a value + * with static type interface{} and extract its dynamic type information by + * calling TypeOf, which returns a Type. + * + * A call to ValueOf returns a Value representing the run-time data. + * Zero takes a Type and returns a Value representing a zero value + * for that type. + * + * See "The Laws of Reflection" for an introduction to reflection in Go: + * https://golang.org/doc/articles/laws_of_reflection.html + */ +namespace reflect { + /** + * Type is the representation of a Go type. + * + * Not all methods apply to all kinds of types. Restrictions, + * if any, are noted in the documentation for each method. + * Use the Kind method to find out the kind of type before + * calling kind-specific methods. Calling a method + * inappropriate to the kind of type causes a run-time panic. + * + * Type values are comparable, such as with the == operator, + * so they can be used as map keys. + * Two Type values are equal if they represent identical types. + */ + interface Type { /** - * Extensions contains raw X.509 extensions. When parsing certificates, - * this can be used to extract non-critical extensions that are not - * parsed by this package. When marshaling certificates, the Extensions - * field is ignored, see ExtraExtensions. + * Align returns the alignment in bytes of a value of + * this type when allocated in memory. */ - extensions: Array + align(): number /** - * ExtraExtensions contains extensions to be copied, raw, into any - * marshaled certificates. Values override any extensions that would - * otherwise be produced based on the other fields. The ExtraExtensions - * field is not populated when parsing certificates, see Extensions. + * FieldAlign returns the alignment in bytes of a value of + * this type when used as a field in a struct. */ - extraExtensions: Array + fieldAlign(): number /** - * UnhandledCriticalExtensions contains a list of extension IDs that - * were not (fully) processed when parsing. Verify will fail if this - * slice is non-empty, unless verification is delegated to an OS - * library which understands all the critical extensions. + * Method returns the i'th method in the type's method set. + * It panics if i is not in the range [0, NumMethod()). * - * Users can access these extensions using Extensions and can remove - * elements from this slice if they believe that they have been - * handled. - */ - unhandledCriticalExtensions: Array - extKeyUsage: Array // Sequence of extended key usages. - unknownExtKeyUsage: Array // Encountered extended key usages unknown to this package. - /** - * BasicConstraintsValid indicates whether IsCA, MaxPathLen, - * and MaxPathLenZero are valid. + * For a non-interface type T or *T, the returned Method's Type and Func + * fields describe a function whose first argument is the receiver, + * and only exported methods are accessible. + * + * For an interface type, the returned Method's Type field gives the + * method signature, without a receiver, and the Func field is nil. + * + * Methods are sorted in lexicographic order. */ - basicConstraintsValid: boolean - isCA: boolean + method(_arg0: number): Method /** - * MaxPathLen and MaxPathLenZero indicate the presence and - * value of the BasicConstraints' "pathLenConstraint". + * MethodByName returns the method with that name in the type's + * method set and a boolean indicating if the method was found. * - * When parsing a certificate, a positive non-zero MaxPathLen - * means that the field was specified, -1 means it was unset, - * and MaxPathLenZero being true mean that the field was - * explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false - * should be treated equivalent to -1 (unset). + * For a non-interface type T or *T, the returned Method's Type and Func + * fields describe a function whose first argument is the receiver. * - * When generating a certificate, an unset pathLenConstraint - * can be requested with either MaxPathLen == -1 or using the - * zero value for both MaxPathLen and MaxPathLenZero. + * For an interface type, the returned Method's Type field gives the + * method signature, without a receiver, and the Func field is nil. */ - maxPathLen: number + methodByName(_arg0: string): [Method, boolean] /** - * MaxPathLenZero indicates that BasicConstraintsValid==true - * and MaxPathLen==0 should be interpreted as an actual - * maximum path length of zero. Otherwise, that combination is - * interpreted as MaxPathLen not being set. + * NumMethod returns the number of methods accessible using Method. + * + * Note that NumMethod counts unexported methods only for interface types. */ - maxPathLenZero: boolean - subjectKeyId: string - authorityKeyId: string + numMethod(): number /** - * RFC 5280, 4.2.2.1 (Authority Information Access) + * Name returns the type's name within its package for a defined type. + * For other (non-defined) types it returns the empty string. */ - ocspServer: Array - issuingCertificateURL: Array + name(): string /** - * Subject Alternate Name values. (Note that these values may not be valid - * if invalid values were contained within a parsed certificate. For - * example, an element of DNSNames may not be a valid DNS domain name.) + * PkgPath returns a defined type's package path, that is, the import path + * that uniquely identifies the package, such as "encoding/base64". + * If the type was predeclared (string, error) or not defined (*T, struct{}, + * []int, or A where A is an alias for a non-defined type), the package path + * will be the empty string. */ - dnsNames: Array - emailAddresses: Array - ipAddresses: Array - urIs: Array<(url.URL | undefined)> + pkgPath(): string /** - * Name constraints + * Size returns the number of bytes needed to store + * a value of the given type; it is analogous to unsafe.Sizeof. */ - permittedDNSDomainsCritical: boolean // if true then the name constraints are marked critical. - permittedDNSDomains: Array - excludedDNSDomains: Array - permittedIPRanges: Array<(net.IPNet | undefined)> - excludedIPRanges: Array<(net.IPNet | undefined)> - permittedEmailAddresses: Array - excludedEmailAddresses: Array - permittedURIDomains: Array - excludedURIDomains: Array + size(): number /** - * CRL Distribution Points + * String returns a string representation of the type. + * The string representation may use shortened package names + * (e.g., base64 instead of "encoding/base64") and is not + * guaranteed to be unique among types. To test for type identity, + * compare the Types directly. */ - crlDistributionPoints: Array - policyIdentifiers: Array - } - interface Certificate { - equal(other: Certificate): boolean - } - interface Certificate { + string(): string /** - * CheckSignatureFrom verifies that the signature on c is a valid signature - * from parent. SHA1WithRSA and ECDSAWithSHA1 signatures are not supported. + * Kind returns the specific kind of this type. */ - checkSignatureFrom(parent: Certificate): void - } - interface Certificate { + kind(): Kind /** - * CheckSignature verifies that signature is a valid signature over signed from - * c's public key. + * Implements reports whether the type implements the interface type u. */ - checkSignature(algo: SignatureAlgorithm, signed: string): void - } - interface Certificate { + implements(u: Type): boolean /** - * CheckCRLSignature checks that the signature in crl is from c. + * AssignableTo reports whether a value of the type is assignable to type u. */ - checkCRLSignature(crl: pkix.CertificateList): void - } - interface Certificate { + assignableTo(u: Type): boolean /** - * CreateCRL returns a DER encoded CRL, signed by this Certificate, that - * contains the given list of revoked certificates. - * - * Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. - * To generate a standards compliant CRL, use CreateRevocationList instead. + * ConvertibleTo reports whether a value of the type is convertible to type u. + * Even if ConvertibleTo returns true, the conversion may still panic. + * For example, a slice of type []T is convertible to *[N]T, + * but the conversion will panic if its length is less than N. */ - createCRL(rand: io.Reader, priv: any, revokedCerts: Array, now: time.Time): string - } -} - -/** - * Package tls partially implements TLS 1.2, as specified in RFC 5246, - * and TLS 1.3, as specified in RFC 8446. - */ -namespace tls { - /** - * CurveID is the type of a TLS identifier for an elliptic curve. See - * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. - * - * In TLS 1.3, this type is called NamedGroup, but at this time this library - * only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7. - */ - interface CurveID extends Number{} - /** - * ClientAuthType declares the policy the server will follow for - * TLS Client Authentication. - */ - interface ClientAuthType extends Number{} - /** - * ClientSessionCache is a cache of ClientSessionState objects that can be used - * by a client to resume a TLS session with a given server. ClientSessionCache - * implementations should expect to be called concurrently from different - * goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not - * SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which - * are supported via this interface. - */ - interface ClientSessionCache { + convertibleTo(u: Type): boolean /** - * Get searches for a ClientSessionState associated with the given key. - * On return, ok is true if one was found. + * Comparable reports whether values of this type are comparable. + * Even if Comparable returns true, the comparison may still panic. + * For example, values of interface type are comparable, + * but the comparison will panic if their dynamic type is not comparable. */ - get(sessionKey: string): [(ClientSessionState | undefined), boolean] + comparable(): boolean /** - * Put adds the ClientSessionState to the cache with the given key. It might - * get called multiple times in a connection if a TLS 1.3 server provides - * more than one session ticket. If called with a nil *ClientSessionState, - * it should remove the cache entry. + * Bits returns the size of the type in bits. + * It panics if the type's Kind is not one of the + * sized or unsized Int, Uint, Float, or Complex kinds. */ - put(sessionKey: string, cs: ClientSessionState): void - } - /** - * ClientHelloInfo contains information from a ClientHello message in order to - * guide application logic in the GetCertificate and GetConfigForClient callbacks. - */ - interface ClientHelloInfo { + bits(): number /** - * CipherSuites lists the CipherSuites supported by the client (e.g. - * TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). + * ChanDir returns a channel type's direction. + * It panics if the type's Kind is not Chan. */ - cipherSuites: Array + chanDir(): ChanDir /** - * ServerName indicates the name of the server requested by the client - * in order to support virtual hosting. ServerName is only set if the - * client is using SNI (see RFC 4366, Section 3.1). + * IsVariadic reports whether a function type's final input parameter + * is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's + * implicit actual type []T. + * + * For concreteness, if t represents func(x int, y ... float64), then + * + * ``` + * t.NumIn() == 2 + * t.In(0) is the reflect.Type for "int" + * t.In(1) is the reflect.Type for "[]float64" + * t.IsVariadic() == true + * ``` + * + * IsVariadic panics if the type's Kind is not Func. */ - serverName: string + isVariadic(): boolean /** - * SupportedCurves lists the elliptic curves supported by the client. - * SupportedCurves is set only if the Supported Elliptic Curves - * Extension is being used (see RFC 4492, Section 5.1.1). + * Elem returns a type's element type. + * It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice. */ - supportedCurves: Array + elem(): Type /** - * SupportedPoints lists the point formats supported by the client. - * SupportedPoints is set only if the Supported Point Formats Extension - * is being used (see RFC 4492, Section 5.1.2). + * Field returns a struct type's i'th field. + * It panics if the type's Kind is not Struct. + * It panics if i is not in the range [0, NumField()). + */ + field(i: number): StructField + /** + * FieldByIndex returns the nested field corresponding + * to the index sequence. It is equivalent to calling Field + * successively for each index i. + * It panics if the type's Kind is not Struct. */ - supportedPoints: Array + fieldByIndex(index: Array): StructField /** - * SignatureSchemes lists the signature and hash schemes that the client - * is willing to verify. SignatureSchemes is set only if the Signature - * Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). + * FieldByName returns the struct field with the given name + * and a boolean indicating if the field was found. */ - signatureSchemes: Array + fieldByName(name: string): [StructField, boolean] /** - * SupportedProtos lists the application protocols supported by the client. - * SupportedProtos is set only if the Application-Layer Protocol - * Negotiation Extension is being used (see RFC 7301, Section 3.1). + * FieldByNameFunc returns the struct field with a name + * that satisfies the match function and a boolean indicating if + * the field was found. * - * Servers can select a protocol by setting Config.NextProtos in a - * GetConfigForClient return value. + * FieldByNameFunc considers the fields in the struct itself + * and then the fields in any embedded structs, in breadth first order, + * stopping at the shallowest nesting depth containing one or more + * fields satisfying the match function. If multiple fields at that depth + * satisfy the match function, they cancel each other + * and FieldByNameFunc returns no match. + * This behavior mirrors Go's handling of name lookup in + * structs containing embedded fields. */ - supportedProtos: Array + fieldByNameFunc(match: (_arg0: string) => boolean): [StructField, boolean] /** - * SupportedVersions lists the TLS versions supported by the client. - * For TLS versions less than 1.3, this is extrapolated from the max - * version advertised by the client, so values other than the greatest - * might be rejected if used. + * In returns the type of a function type's i'th input parameter. + * It panics if the type's Kind is not Func. + * It panics if i is not in the range [0, NumIn()). */ - supportedVersions: Array + in(i: number): Type /** - * Conn is the underlying net.Conn for the connection. Do not read - * from, or write to, this connection; that will cause the TLS - * connection to fail. + * Key returns a map type's key type. + * It panics if the type's Kind is not Map. */ - conn: net.Conn - } - interface ClientHelloInfo { + key(): Type /** - * Context returns the context of the handshake that is in progress. - * This context is a child of the context passed to HandshakeContext, - * if any, and is canceled when the handshake concludes. + * Len returns an array type's length. + * It panics if the type's Kind is not Array. */ - context(): context.Context - } - /** - * CertificateRequestInfo contains information from a server's - * CertificateRequest message, which is used to demand a certificate and proof - * of control from a client. - */ - interface CertificateRequestInfo { + len(): number /** - * AcceptableCAs contains zero or more, DER-encoded, X.501 - * Distinguished Names. These are the names of root or intermediate CAs - * that the server wishes the returned certificate to be signed by. An - * empty slice indicates that the server has no preference. + * NumField returns a struct type's field count. + * It panics if the type's Kind is not Struct. */ - acceptableCAs: Array + numField(): number /** - * SignatureSchemes lists the signature schemes that the server is - * willing to verify. + * NumIn returns a function type's input parameter count. + * It panics if the type's Kind is not Func. */ - signatureSchemes: Array + numIn(): number /** - * Version is the TLS version that was negotiated for this connection. + * NumOut returns a function type's output parameter count. + * It panics if the type's Kind is not Func. */ - version: number - } - interface CertificateRequestInfo { + numOut(): number /** - * Context returns the context of the handshake that is in progress. - * This context is a child of the context passed to HandshakeContext, - * if any, and is canceled when the handshake concludes. + * Out returns the type of a function type's i'th output parameter. + * It panics if the type's Kind is not Func. + * It panics if i is not in the range [0, NumOut()). */ - context(): context.Context + out(i: number): Type } +} + +/** + * Package time provides functionality for measuring and displaying time. + * + * The calendrical calculations always assume a Gregorian calendar, with + * no leap seconds. + * + * Monotonic Clocks + * + * Operating systems provide both a “wall clock,” which is subject to + * changes for clock synchronization, and a “monotonic clock,” which is + * not. The general rule is that the wall clock is for telling time and + * the monotonic clock is for measuring time. Rather than split the API, + * in this package the Time returned by time.Now contains both a wall + * clock reading and a monotonic clock reading; later time-telling + * operations use the wall clock reading, but later time-measuring + * operations, specifically comparisons and subtractions, use the + * monotonic clock reading. + * + * For example, this code always computes a positive elapsed time of + * approximately 20 milliseconds, even if the wall clock is changed during + * the operation being timed: + * + * ``` + * start := time.Now() + * ... operation that takes 20 milliseconds ... + * t := time.Now() + * elapsed := t.Sub(start) + * ``` + * + * Other idioms, such as time.Since(start), time.Until(deadline), and + * time.Now().Before(deadline), are similarly robust against wall clock + * resets. + * + * The rest of this section gives the precise details of how operations + * use monotonic clocks, but understanding those details is not required + * to use this package. + * + * The Time returned by time.Now contains a monotonic clock reading. + * If Time t has a monotonic clock reading, t.Add adds the same duration to + * both the wall clock and monotonic clock readings to compute the result. + * Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time + * computations, they always strip any monotonic clock reading from their results. + * Because t.In, t.Local, and t.UTC are used for their effect on the interpretation + * of the wall time, they also strip any monotonic clock reading from their results. + * The canonical way to strip a monotonic clock reading is to use t = t.Round(0). + * + * If Times t and u both contain monotonic clock readings, the operations + * t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out + * using the monotonic clock readings alone, ignoring the wall clock + * readings. If either t or u contains no monotonic clock reading, these + * operations fall back to using the wall clock readings. + * + * On some systems the monotonic clock will stop if the computer goes to sleep. + * On such a system, t.Sub(u) may not accurately reflect the actual + * time that passed between t and u. + * + * Because the monotonic clock reading has no meaning outside + * the current process, the serialized forms generated by t.GobEncode, + * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic + * clock reading, and t.Format provides no format for it. Similarly, the + * constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, + * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. + * t.UnmarshalJSON, and t.UnmarshalText always create times with + * no monotonic clock reading. + * + * Note that the Go == operator compares not just the time instant but + * also the Location and the monotonic clock reading. See the + * documentation for the Time type for a discussion of equality + * testing for Time values. + * + * For debugging, the result of t.String does include the monotonic + * clock reading if present. If t != u because of different monotonic clock readings, + * that difference will be visible when printing t.String() and u.String(). + */ +namespace time { /** - * RenegotiationSupport enumerates the different levels of support for TLS - * renegotiation. TLS renegotiation is the act of performing subsequent - * handshakes on a connection after the first. This significantly complicates - * the state machine and has been the source of numerous, subtle security - * issues. Initiating a renegotiation is not supported, but support for - * accepting renegotiation requests may be enabled. - * - * Even when enabled, the server may not change its identity between handshakes - * (i.e. the leaf certificate must be the same). Additionally, concurrent - * handshake and application data flow is not permitted so renegotiation can - * only be used with protocols that synchronise with the renegotiation, such as - * HTTPS. - * - * Renegotiation is not defined in TLS 1.3. + * A Month specifies a month of the year (January = 1, ...). */ - interface RenegotiationSupport extends Number{} - interface ClientHelloInfo { - /** - * SupportsCertificate returns nil if the provided certificate is supported by - * the client that sent the ClientHello. Otherwise, it returns an error - * describing the reason for the incompatibility. - * - * If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate - * callback, this method will take into account the associated Config. Note that - * if GetConfigForClient returns a different Config, the change can't be - * accounted for by this method. - * - * This function will call x509.ParseCertificate unless c.Leaf is set, which can - * incur a significant performance cost. - */ - supportsCertificate(c: Certificate): void - } - interface CertificateRequestInfo { + interface Month extends Number{} + interface Month { /** - * SupportsCertificate returns nil if the provided certificate is supported by - * the server that sent the CertificateRequest. Otherwise, it returns an error - * describing the reason for the incompatibility. + * String returns the English name of the month ("January", "February", ...). */ - supportsCertificate(c: Certificate): void + string(): string } /** - * A Certificate is a chain of one or more certificates, leaf first. + * A Weekday specifies a day of the week (Sunday = 0, ...). */ - interface Certificate { - certificate: Array - /** - * PrivateKey contains the private key corresponding to the public key in - * Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey. - * For a server up to TLS 1.2, it can also implement crypto.Decrypter with - * an RSA PublicKey. - */ - privateKey: crypto.PrivateKey - /** - * SupportedSignatureAlgorithms is an optional list restricting what - * signature algorithms the PrivateKey can be used for. - */ - supportedSignatureAlgorithms: Array - /** - * OCSPStaple contains an optional OCSP response which will be served - * to clients that request it. - */ - ocspStaple: string - /** - * SignedCertificateTimestamps contains an optional list of Signed - * Certificate Timestamps which will be served to clients that request it. - */ - signedCertificateTimestamps: Array + interface Weekday extends Number{} + interface Weekday { /** - * Leaf is the parsed form of the leaf certificate, which may be initialized - * using x509.ParseCertificate to reduce per-handshake processing. If nil, - * the leaf certificate will be parsed as needed. + * String returns the English name of the day ("Sunday", "Monday", ...). */ - leaf?: x509.Certificate - } - interface CurveID { string(): string } - interface ClientAuthType { + /** + * A Location maps time instants to the zone in use at that time. + * Typically, the Location represents the collection of time offsets + * in use in a geographical area. For many Locations the time offset varies + * depending on whether daylight savings time is in use at the time instant. + */ + interface Location { + } + interface Location { + /** + * String returns a descriptive name for the time zone information, + * corresponding to the name argument to LoadLocation or FixedZone. + */ string(): string } } -namespace store { -} - -namespace hook { - /** - * Handler defines a hook handler function. - */ - interface Handler {(e: T): void } +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + */ +namespace fs { /** - * wrapped local Hook embedded struct to limit the public API surface. + * A FileInfo describes a file and is returned by Stat. */ - type _subpzjnf = Hook - interface mainHook extends _subpzjnf { + interface FileInfo { + name(): string // base name of the file + size(): number // length in bytes for regular files; system-dependent for others + mode(): FileMode // file mode bits + modTime(): time.Time // modification time + isDir(): boolean // abbreviation for Mode().IsDir() + sys(): any // underlying data source (can return nil) } } @@ -18063,6 +17265,21 @@ namespace flag { } } +/** + * Package log implements a simple logging package. It defines a type, Logger, + * with methods for formatting output. It also has a predefined 'standard' + * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and + * Panic[f|ln], which are easier to use than creating a Logger manually. + * That logger writes to standard error and prints the date and time + * of each logged message. + * Every log message is output on a separate line: if the message being + * printed does not end in a newline, the logger will add one. + * The Fatal functions call os.Exit(1) after writing the log message. + * The Panic functions call panic after writing the log message. + */ +namespace log { +} + /** * Package driver defines interfaces to be implemented by database * drivers as used by package sql. @@ -18133,1074 +17350,1639 @@ namespace driver { } } -namespace subscriptions { +/** + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { /** - * Message defines a client's channel data. + * ReadWriter stores pointers to a Reader and a Writer. + * It implements io.ReadWriter. */ - interface Message { - name: string - data: string + type _subpsAZZ = Reader&Writer + interface ReadWriter extends _subpsAZZ { } +} + +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. + * + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the Dial, Listen, and Accept functions and the associated + * Conn and Listener interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. + * + * The Dial function connects to a server: + * + * ``` + * conn, err := net.Dial("tcp", "golang.org:80") + * if err != nil { + * // handle error + * } + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') + * // ... + * ``` + * + * The Listen function creates servers: + * + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` + * + * Name Resolution + * + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. + * + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. + * + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: + * + * ``` + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force cgo resolver + * ``` + * + * The decision can also be forced while building the Go source tree + * by setting the netgo or netcgo build tag. + * + * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver + * to print debugging information about its decisions. + * To force a particular resolver while also printing debugging information, + * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. + * + * On Plan 9, the resolver always accesses /net/cs and /net/dns. + * + * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. + */ +namespace net { /** - * Client is an interface for a generic subscription client. + * An IP is a single IP address, a slice of bytes. + * Functions in this package accept either 4-byte (IPv4) + * or 16-byte (IPv6) slices as input. + * + * Note that in this documentation, referring to an + * IP address as an IPv4 address or an IPv6 address + * is a semantic property of the address, not just the + * length of the byte slice: a 16-byte slice can still + * be an IPv4 address. */ - interface Client { + interface IP extends String{} + /** + * An IPMask is a bitmask that can be used to manipulate + * IP addresses for IP addressing and routing. + * + * See type IPNet and func ParseCIDR for details. + */ + interface IPMask extends String{} + /** + * An IPNet represents an IP network. + */ + interface IPNet { + ip: IP // network number + mask: IPMask // network mask + } + interface IP { /** - * Id Returns the unique id of the client. + * IsUnspecified reports whether ip is an unspecified address, either + * the IPv4 address "0.0.0.0" or the IPv6 address "::". */ - id(): string + isUnspecified(): boolean + } + interface IP { /** - * Channel returns the client's communication channel. + * IsLoopback reports whether ip is a loopback address. */ - channel(): undefined + isLoopback(): boolean + } + interface IP { /** - * Subscriptions returns all subscriptions to which the client has subscribed to. + * IsPrivate reports whether ip is a private address, according to + * RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). */ - subscriptions(): _TygojaDict + isPrivate(): boolean + } + interface IP { /** - * Subscribe subscribes the client to the provided subscriptions list. + * IsMulticast reports whether ip is a multicast address. */ - subscribe(...subs: string[]): void + isMulticast(): boolean + } + interface IP { /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. + * IsInterfaceLocalMulticast reports whether ip is + * an interface-local multicast address. */ - unsubscribe(...subs: string[]): void + isInterfaceLocalMulticast(): boolean + } + interface IP { /** - * HasSubscription checks if the client is subscribed to `sub`. + * IsLinkLocalMulticast reports whether ip is a link-local + * multicast address. */ - hasSubscription(sub: string): boolean + isLinkLocalMulticast(): boolean + } + interface IP { /** - * Set stores any value to the client's context. + * IsLinkLocalUnicast reports whether ip is a link-local + * unicast address. */ - set(key: string, value: any): void + isLinkLocalUnicast(): boolean + } + interface IP { /** - * Unset removes a single value from the client's context. + * IsGlobalUnicast reports whether ip is a global unicast + * address. + * + * The identification of global unicast addresses uses address type + * identification as defined in RFC 1122, RFC 4632 and RFC 4291 with + * the exception of IPv4 directed broadcast addresses. + * It returns true even if ip is in IPv4 private address space or + * local IPv6 unicast address space. */ - unset(key: string): void + isGlobalUnicast(): boolean + } + interface IP { /** - * Get retrieves the key value from the client's context. + * To4 converts the IPv4 address ip to a 4-byte representation. + * If ip is not an IPv4 address, To4 returns nil. + */ + to4(): IP + } + interface IP { + /** + * To16 converts the IP address ip to a 16-byte representation. + * If ip is not an IP address (it is the wrong length), To16 returns nil. + */ + to16(): IP + } + interface IP { + /** + * DefaultMask returns the default IP mask for the IP address ip. + * Only IPv4 addresses have default masks; DefaultMask returns + * nil if ip is not a valid IPv4 address. + */ + defaultMask(): IPMask + } + interface IP { + /** + * Mask returns the result of masking the IP address ip with mask. + */ + mask(mask: IPMask): IP + } + interface IP { + /** + * String returns the string form of the IP address ip. + * It returns one of 4 forms: + * ``` + * - "", if ip has length 0 + * - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address + * - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address + * - the hexadecimal form of ip, without punctuation, if no other cases apply + * ``` */ - get(key: string): any + string(): string + } + interface IP { /** - * 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. + * MarshalText implements the encoding.TextMarshaler interface. + * The encoding is the same as returned by String, with one exception: + * When len(ip) is zero, it returns an empty slice. */ - discard(): void + marshalText(): string + } + interface IP { /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. + * UnmarshalText implements the encoding.TextUnmarshaler interface. + * The IP address is expected in a form accepted by ParseIP. */ - isDiscarded(): boolean + unmarshalText(text: string): void + } + interface IP { /** - * Send sends the specified message to the client's channel (if not discarded). + * Equal reports whether ip and x are the same IP address. + * An IPv4 address and that same address in IPv6 form are + * considered to be equal. */ - send(m: Message): void + equal(x: IP): boolean } -} - -/** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - */ -namespace multipart { - /** - * A Part represents a single part in a multipart body. - */ - interface Part { + interface IPMask { /** - * The headers of the body, if any, with the keys canonicalized - * in the same fashion that the Go http.Request headers are. - * For example, "foo-bar" changes case to "Foo-Bar" + * Size returns the number of leading ones and total bits in the mask. + * If the mask is not in the canonical form--ones followed by zeros--then + * Size returns 0, 0. */ - header: textproto.MIMEHeader + size(): number } - interface Part { + interface IPMask { /** - * FormName returns the name parameter if p has a Content-Disposition - * of type "form-data". Otherwise it returns the empty string. + * String returns the hexadecimal form of m, with no punctuation. */ - formName(): string + string(): string } - interface Part { + interface IPNet { /** - * FileName returns the filename parameter of the Part's Content-Disposition - * header. If not empty, the filename is passed through filepath.Base (which is - * platform dependent) before being returned. + * Contains reports whether the network includes ip. */ - fileName(): string + contains(ip: IP): boolean } - interface Part { + interface IPNet { /** - * Read reads the body of a part, after its headers and before the - * next part (if any) begins. + * Network returns the address's network name, "ip+net". */ - read(d: string): number - } - interface Part { - close(): void + network(): string } -} - -/** - * Package log implements a simple logging package. It defines a type, Logger, - * with methods for formatting output. It also has a predefined 'standard' - * Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and - * Panic[f|ln], which are easier to use than creating a Logger manually. - * That logger writes to standard error and prints the date and time - * of each logged message. - * Every log message is output on a separate line: if the message being - * printed does not end in a newline, the logger will add one. - * The Fatal functions call os.Exit(1) after writing the log message. - * The Panic functions call panic after writing the log message. - */ -namespace log { -} - -/** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The client must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG environment variables are - * currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * The GODEBUG variables are not covered by Go's API compatibility - * promise. Please report any issues before disabling HTTP/2 - * support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { - /** - * RoundTripper is an interface representing the ability to execute a - * single HTTP transaction, obtaining the Response for a given Request. - * - * A RoundTripper must be safe for concurrent use by multiple - * goroutines. - */ - interface RoundTripper { + interface IPNet { /** - * RoundTrip executes a single HTTP transaction, returning - * a Response for the provided Request. - * - * RoundTrip should not attempt to interpret the response. In - * particular, RoundTrip must return err == nil if it obtained - * a response, regardless of the response's HTTP status code. - * A non-nil err should be reserved for failure to obtain a - * response. Similarly, RoundTrip should not attempt to - * handle higher-level protocol details such as redirects, - * authentication, or cookies. - * - * RoundTrip should not modify the request, except for - * consuming and closing the Request's Body. RoundTrip may - * read fields of the request in a separate goroutine. Callers - * should not mutate or reuse the request until the Response's - * Body has been closed. - * - * RoundTrip must always close the body, including on errors, - * but depending on the implementation may do so in a separate - * goroutine even after RoundTrip returns. This means that - * callers wanting to reuse the body for subsequent requests - * must arrange to wait for the Close call before doing so. - * - * The Request's URL and Header fields must be initialized. + * String returns the CIDR notation of n like "192.0.2.0/24" + * or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. + * If the mask is not in the canonical form, it returns the + * string which consists of an IP address, followed by a slash + * character and a mask expressed as hexadecimal form with no + * punctuation like "198.51.100.0/c000ff00". */ - roundTrip(_arg0: Request): (Response | undefined) + string(): string } /** - * SameSite allows a server to define a cookie attribute making it impossible for - * the browser to send this cookie along with cross-site requests. The main - * goal is to mitigate the risk of cross-origin information leakage, and provide - * some protection against cross-site request forgery attacks. + * Addr represents a network end point address. * - * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. + * The two methods Network and String conventionally return strings + * that can be passed as the arguments to Dial, but the exact form + * and meaning of the strings is up to the implementation. */ - interface SameSite extends Number{} - // @ts-ignore - import mathrand = rand + interface Addr { + network(): string // name of the network (for example, "tcp", "udp") + string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") + } +} + +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { /** - * A CookieJar manages storage and use of cookies in HTTP requests. - * - * Implementations of CookieJar must be safe for concurrent use by multiple - * goroutines. - * - * The net/http/cookiejar package provides a CookieJar implementation. + * The Userinfo type is an immutable encapsulation of username and + * password details for a URL. An existing Userinfo value is guaranteed + * to have a username set (potentially empty, as allowed by RFC 2396), + * and optionally a password. */ - interface CookieJar { + interface Userinfo { + } + interface Userinfo { /** - * SetCookies handles the receipt of the cookies in a reply for the - * given URL. It may or may not choose to save the cookies, depending - * on the jar's policy and implementation. + * Username returns the username. */ - setCookies(u: url.URL, cookies: Array<(Cookie | undefined)>): void + username(): string + } + interface Userinfo { /** - * Cookies returns the cookies to send in a request for the given URL. - * It is up to the implementation to honor the standard cookie use - * restrictions such as in RFC 6265. + * Password returns the password in case it is set, and whether it is set. */ - cookies(u: url.URL): Array<(Cookie | undefined)> + password(): [string, boolean] } - // @ts-ignore - import urlpkg = url -} - -namespace mailer { - /** - * Message defines a generic email message struct. - */ - interface Message { - from: mail.Address - to: Array - bcc: Array - cc: Array - subject: string - html: string - text: string - headers: _TygojaDict - attachments: _TygojaDict + interface Userinfo { + /** + * String returns the encoded userinfo information in the standard form + * of "username[:password]". + */ + string(): string } } /** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. + * Copyright 2021 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. */ -namespace types { +/** + * Package x509 parses X.509-encoded keys and certificates. + */ +namespace x509 { /** - * JsonRaw defines a json value type that is safe for db read/write. + * CertPool is a set of certificates. */ - interface JsonRaw extends String{} - interface JsonRaw { + interface CertPool { + } + interface CertPool { + /** + * AddCert adds a certificate to a pool. + */ + addCert(cert: Certificate): void + } + interface CertPool { + /** + * AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. + * It appends any certificates found to s and reports whether any certificates + * were successfully parsed. + * + * On many Linux systems, /etc/ssl/cert.pem will contain the system wide set + * of root CAs in a format suitable for this function. + */ + appendCertsFromPEM(pemCerts: string): boolean + } + interface CertPool { + /** + * Subjects returns a list of the DER-encoded subjects of + * all of the certificates in the pool. + * + * Deprecated: if s was returned by SystemCertPool, Subjects + * will not include the system roots. + */ + subjects(): Array + } + // @ts-ignore + import cryptobyte_asn1 = asn1 + interface Certificate { + /** + * Verify attempts to verify c by building one or more chains from c to a + * certificate in opts.Roots, using certificates in opts.Intermediates if + * needed. If successful, it returns one or more chains where the first + * element of the chain is c and the last element is from opts.Roots. + * + * If opts.Roots is nil, the platform verifier might be used, and + * verification details might differ from what is described below. If system + * roots are unavailable the returned error will be of type SystemRootsError. + * + * Name constraints in the intermediates will be applied to all names claimed + * in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim + * example.com if an intermediate doesn't permit it, even if example.com is not + * the name being validated. Note that DirectoryName constraints are not + * supported. + * + * Name constraint validation follows the rules from RFC 5280, with the + * addition that DNS name constraints may use the leading period format + * defined for emails and URIs. When a constraint has a leading period + * it indicates that at least one additional label must be prepended to + * the constrained name to be considered valid. + * + * Extended Key Usage values are enforced nested down a chain, so an intermediate + * or root that enumerates EKUs prevents a leaf from asserting an EKU not in that + * list. (While this is not specified, it is common practice in order to limit + * the types of certificates a CA can issue.) + * + * Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, + * and will not be used to build chains. + * + * WARNING: this function doesn't do any revocation checking. + */ + verify(opts: VerifyOptions): Array> + } + interface Certificate { + /** + * VerifyHostname returns nil if c is a valid certificate for the named host. + * Otherwise it returns an error describing the mismatch. + * + * IP addresses can be optionally enclosed in square brackets and are checked + * against the IPAddresses field. Other names are checked case insensitively + * against the DNSNames field. If the names are valid hostnames, the certificate + * fields can have a wildcard as the left-most label. + * + * Note that the legacy Common Name field is ignored. + */ + verifyHostname(h: string): void + } + /** + * A Certificate represents an X.509 certificate. + */ + interface Certificate { + raw: string // Complete ASN.1 DER content (certificate, signature algorithm and signature). + rawTBSCertificate: string // Certificate part of raw ASN.1 DER content. + rawSubjectPublicKeyInfo: string // DER encoded SubjectPublicKeyInfo. + rawSubject: string // DER encoded Subject + rawIssuer: string // DER encoded Issuer + signature: string + signatureAlgorithm: SignatureAlgorithm + publicKeyAlgorithm: PublicKeyAlgorithm + publicKey: any + version: number + serialNumber?: big.Int + issuer: pkix.Name + subject: pkix.Name + notBefore: time.Time // Validity bounds. + keyUsage: KeyUsage + /** + * Extensions contains raw X.509 extensions. When parsing certificates, + * this can be used to extract non-critical extensions that are not + * parsed by this package. When marshaling certificates, the Extensions + * field is ignored, see ExtraExtensions. + */ + extensions: Array + /** + * ExtraExtensions contains extensions to be copied, raw, into any + * marshaled certificates. Values override any extensions that would + * otherwise be produced based on the other fields. The ExtraExtensions + * field is not populated when parsing certificates, see Extensions. + */ + extraExtensions: Array + /** + * UnhandledCriticalExtensions contains a list of extension IDs that + * were not (fully) processed when parsing. Verify will fail if this + * slice is non-empty, unless verification is delegated to an OS + * library which understands all the critical extensions. + * + * Users can access these extensions using Extensions and can remove + * elements from this slice if they believe that they have been + * handled. + */ + unhandledCriticalExtensions: Array + extKeyUsage: Array // Sequence of extended key usages. + unknownExtKeyUsage: Array // Encountered extended key usages unknown to this package. + /** + * BasicConstraintsValid indicates whether IsCA, MaxPathLen, + * and MaxPathLenZero are valid. + */ + basicConstraintsValid: boolean + isCA: boolean + /** + * MaxPathLen and MaxPathLenZero indicate the presence and + * value of the BasicConstraints' "pathLenConstraint". + * + * When parsing a certificate, a positive non-zero MaxPathLen + * means that the field was specified, -1 means it was unset, + * and MaxPathLenZero being true mean that the field was + * explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false + * should be treated equivalent to -1 (unset). + * + * When generating a certificate, an unset pathLenConstraint + * can be requested with either MaxPathLen == -1 or using the + * zero value for both MaxPathLen and MaxPathLenZero. + */ + maxPathLen: number + /** + * MaxPathLenZero indicates that BasicConstraintsValid==true + * and MaxPathLen==0 should be interpreted as an actual + * maximum path length of zero. Otherwise, that combination is + * interpreted as MaxPathLen not being set. + */ + maxPathLenZero: boolean + subjectKeyId: string + authorityKeyId: string + /** + * RFC 5280, 4.2.2.1 (Authority Information Access) + */ + ocspServer: Array + issuingCertificateURL: Array + /** + * Subject Alternate Name values. (Note that these values may not be valid + * if invalid values were contained within a parsed certificate. For + * example, an element of DNSNames may not be a valid DNS domain name.) + */ + dnsNames: Array + emailAddresses: Array + ipAddresses: Array + urIs: Array<(url.URL | undefined)> /** - * String returns the current JsonRaw instance as a json encoded string. + * Name constraints */ - string(): string + permittedDNSDomainsCritical: boolean // if true then the name constraints are marked critical. + permittedDNSDomains: Array + excludedDNSDomains: Array + permittedIPRanges: Array<(net.IPNet | undefined)> + excludedIPRanges: Array<(net.IPNet | undefined)> + permittedEmailAddresses: Array + excludedEmailAddresses: Array + permittedURIDomains: Array + excludedURIDomains: Array + /** + * CRL Distribution Points + */ + crlDistributionPoints: Array + policyIdentifiers: Array } - interface JsonRaw { + interface Certificate { + equal(other: Certificate): boolean + } + interface Certificate { /** - * MarshalJSON implements the [json.Marshaler] interface. + * CheckSignatureFrom verifies that the signature on c is a valid signature + * from parent. SHA1WithRSA and ECDSAWithSHA1 signatures are not supported. */ - marshalJSON(): string + checkSignatureFrom(parent: Certificate): void } - interface JsonRaw { + interface Certificate { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * CheckSignature verifies that signature is a valid signature over signed from + * c's public key. */ - unmarshalJSON(b: string): void + checkSignature(algo: SignatureAlgorithm, signed: string): void } - interface JsonRaw { + interface Certificate { /** - * Value implements the [driver.Valuer] interface. + * CheckCRLSignature checks that the signature in crl is from c. */ - value(): driver.Value + checkCRLSignature(crl: pkix.CertificateList): void } - interface JsonRaw { + interface Certificate { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. + * CreateCRL returns a DER encoded CRL, signed by this Certificate, that + * contains the given list of revoked certificates. + * + * Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. + * To generate a standards compliant CRL, use CreateRevocationList instead. */ - scan(value: { - }): void + createCRL(rand: io.Reader, priv: any, revokedCerts: Array, now: time.Time): string } } /** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com + * Package tls partially implements TLS 1.2, as specified in RFC 5246, + * and TLS 1.3, as specified in RFC 8446. */ -namespace echo { - // @ts-ignore - import stdContext = context +namespace tls { /** - * 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. + * CurveID is the type of a TLS identifier for an elliptic curve. See + * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. + * + * In TLS 1.3, this type is called NamedGroup, but at this time this library + * only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7. */ - interface Route { - method: string - path: string - handler: HandlerFunc - middlewares: Array - name: string - } - interface Route { - /** - * ToRouteInfo converts Route to RouteInfo - */ - toRouteInfo(params: Array): RouteInfo - } - interface Route { + interface CurveID extends Number{} + /** + * ClientAuthType declares the policy the server will follow for + * TLS Client Authentication. + */ + interface ClientAuthType extends Number{} + /** + * ClientSessionCache is a cache of ClientSessionState objects that can be used + * by a client to resume a TLS session with a given server. ClientSessionCache + * implementations should expect to be called concurrently from different + * goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not + * SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which + * are supported via this interface. + */ + interface ClientSessionCache { /** - * ToRoute returns Route which Router uses to register the method handler for path. + * Get searches for a ClientSessionState associated with the given key. + * On return, ok is true if one was found. */ - toRoute(): Route - } - interface Route { + get(sessionKey: string): [(ClientSessionState | undefined), boolean] /** - * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. + * Put adds the ClientSessionState to the cache with the given key. It might + * get called multiple times in a connection if a TLS 1.3 server provides + * more than one session ticket. If called with a nil *ClientSessionState, + * it should remove the cache entry. */ - forGroup(pathPrefix: string, middlewares: Array): Routable + put(sessionKey: string, cs: ClientSessionState): void } /** - * RoutableContext is additional interface that structures implementing Context must implement. Methods inside this - * interface are meant for request routing purposes and should not be used in middlewares. + * ClientHelloInfo contains information from a ClientHello message in order to + * guide application logic in the GetCertificate and GetConfigForClient callbacks. */ - interface RoutableContext { + interface ClientHelloInfo { /** - * Request returns `*http.Request`. + * CipherSuites lists the CipherSuites supported by the client (e.g. + * TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). */ - request(): (http.Request | undefined) + cipherSuites: Array /** - * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. + * ServerName indicates the name of the server requested by the client + * in order to support virtual hosting. ServerName is only set if the + * client is using SNI (see RFC 4366, Section 3.1). */ - rawPathParams(): (PathParams | undefined) + serverName: string /** - * 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. + * SupportedCurves lists the elliptic curves supported by the client. + * SupportedCurves is set only if the Supported Elliptic Curves + * Extension is being used (see RFC 4492, Section 5.1.1). */ - setRawPathParams(params: PathParams): void + supportedCurves: Array /** - * SetPath sets the registered path for the handler. + * SupportedPoints lists the point formats supported by the client. + * SupportedPoints is set only if the Supported Point Formats Extension + * is being used (see RFC 4492, Section 5.1.2). */ - setPath(p: string): void + supportedPoints: Array /** - * SetRouteInfo sets the route info of this request to the context. + * SignatureSchemes lists the signature and hash schemes that the client + * is willing to verify. SignatureSchemes is set only if the Signature + * Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). */ - setRouteInfo(ri: RouteInfo): void + signatureSchemes: Array /** - * 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. + * SupportedProtos lists the application protocols supported by the client. + * SupportedProtos is set only if the Application-Layer Protocol + * Negotiation Extension is being used (see RFC 7301, Section 3.1). + * + * Servers can select a protocol by setting Config.NextProtos in a + * GetConfigForClient return value. */ - set(key: string, val: { - }): void + supportedProtos: Array + /** + * SupportedVersions lists the TLS versions supported by the client. + * For TLS versions less than 1.3, this is extrapolated from the max + * version advertised by the client, so values other than the greatest + * might be rejected if used. + */ + supportedVersions: Array + /** + * Conn is the underlying net.Conn for the connection. Do not read + * from, or write to, this connection; that will cause the TLS + * connection to fail. + */ + conn: net.Conn } - /** - * PathParam is tuple pf path parameter name and its value in request path - */ - interface PathParam { - name: string - value: string + interface ClientHelloInfo { + /** + * Context returns the context of the handshake that is in progress. + * This context is a child of the context passed to HandshakeContext, + * if any, and is canceled when the handshake concludes. + */ + context(): context.Context } -} - -namespace search { /** - * Result defines the returned search result structure. + * CertificateRequestInfo contains information from a server's + * CertificateRequest message, which is used to demand a certificate and proof + * of control from a client. */ - 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 { + interface CertificateRequestInfo { + /** + * AcceptableCAs contains zero or more, DER-encoded, X.501 + * Distinguished Names. These are the names of root or intermediate CAs + * that the server wishes the returned certificate to be signed by. An + * empty slice indicates that the server has no preference. + */ + acceptableCAs: Array + /** + * SignatureSchemes lists the signature schemes that the server is + * willing to verify. + */ + signatureSchemes: Array /** - * Validate makes EmailTemplate validatable by implementing [validation.Validatable] interface. + * Version is the TLS version that was negotiated for this connection. */ - validate(): void + version: number } - interface EmailTemplate { + interface CertificateRequestInfo { /** - * Resolve replaces the placeholder parameters in the current email - * template and returns its components as ready-to-use strings. + * Context returns the context of the handshake that is in progress. + * This context is a child of the context passed to HandshakeContext, + * if any, and is canceled when the handshake concludes. */ - resolve(appName: string, appUrl: string): string + context(): context.Context } -} - -/** - * Package autocert provides automatic access to certificates from Let's Encrypt - * and any other ACME-based CA. - * - * This package is a work in progress and makes no API stability promises. - */ -namespace autocert { - // @ts-ignore - import mathrand = rand /** - * Manager is a stateful certificate manager built on top of acme.Client. - * It obtains and refreshes certificates automatically using "tls-alpn-01" - * or "http-01" challenge types, as well as providing them to a TLS server - * via tls.Config. + * RenegotiationSupport enumerates the different levels of support for TLS + * renegotiation. TLS renegotiation is the act of performing subsequent + * handshakes on a connection after the first. This significantly complicates + * the state machine and has been the source of numerous, subtle security + * issues. Initiating a renegotiation is not supported, but support for + * accepting renegotiation requests may be enabled. * - * You must specify a cache implementation, such as DirCache, - * to reuse obtained certificates across program restarts. - * Otherwise your server is very likely to exceed the certificate - * issuer's request rate limits. + * Even when enabled, the server may not change its identity between handshakes + * (i.e. the leaf certificate must be the same). Additionally, concurrent + * handshake and application data flow is not permitted so renegotiation can + * only be used with protocols that synchronise with the renegotiation, such as + * HTTPS. + * + * Renegotiation is not defined in TLS 1.3. */ - interface Manager { - /** - * Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). - * The registration may require the caller to agree to the CA's TOS. - * If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report - * whether the caller agrees to the terms. - * - * To always accept the terms, the callers can use AcceptTOS. - */ - prompt: (tosURL: string) => boolean - /** - * Cache optionally stores and retrieves previously-obtained certificates - * and other state. If nil, certs will only be cached for the lifetime of - * the Manager. Multiple Managers can share the same Cache. - * - * Using a persistent Cache, such as DirCache, is strongly recommended. - */ - cache: Cache + interface RenegotiationSupport extends Number{} + interface ClientHelloInfo { /** - * HostPolicy controls which domains the Manager will attempt - * to retrieve new certificates for. It does not affect cached certs. + * SupportsCertificate returns nil if the provided certificate is supported by + * the client that sent the ClientHello. Otherwise, it returns an error + * describing the reason for the incompatibility. * - * If non-nil, HostPolicy is called before requesting a new cert. - * If nil, all hosts are currently allowed. This is not recommended, - * as it opens a potential attack where clients connect to a server - * by IP address and pretend to be asking for an incorrect host name. - * Manager will attempt to obtain a certificate for that host, incorrectly, - * eventually reaching the CA's rate limit for certificate requests - * and making it impossible to obtain actual certificates. + * If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate + * callback, this method will take into account the associated Config. Note that + * if GetConfigForClient returns a different Config, the change can't be + * accounted for by this method. * - * See GetCertificate for more details. + * This function will call x509.ParseCertificate unless c.Leaf is set, which can + * incur a significant performance cost. */ - hostPolicy: HostPolicy + supportsCertificate(c: Certificate): void + } + interface CertificateRequestInfo { /** - * RenewBefore optionally specifies how early certificates should - * be renewed before they expire. - * - * If zero, they're renewed 30 days before expiration. + * SupportsCertificate returns nil if the provided certificate is supported by + * the server that sent the CertificateRequest. Otherwise, it returns an error + * describing the reason for the incompatibility. */ - renewBefore: time.Duration + supportsCertificate(c: Certificate): void + } + /** + * A Certificate is a chain of one or more certificates, leaf first. + */ + interface Certificate { + certificate: Array /** - * Client is used to perform low-level operations, such as account registration - * and requesting new certificates. - * - * If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory - * as the directory endpoint. - * If the Client.Key is nil, a new ECDSA P-256 key is generated and, - * if Cache is not nil, stored in cache. - * - * Mutating the field after the first call of GetCertificate method will have no effect. + * PrivateKey contains the private key corresponding to the public key in + * Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey. + * For a server up to TLS 1.2, it can also implement crypto.Decrypter with + * an RSA PublicKey. */ - client?: acme.Client + privateKey: crypto.PrivateKey /** - * Email optionally specifies a contact email address. - * This is used by CAs, such as Let's Encrypt, to notify about problems - * with issued certificates. - * - * If the Client's account key is already registered, Email is not used. + * SupportedSignatureAlgorithms is an optional list restricting what + * signature algorithms the PrivateKey can be used for. */ - email: string + supportedSignatureAlgorithms: Array /** - * ForceRSA used to make the Manager generate RSA certificates. It is now ignored. - * - * Deprecated: the Manager will request the correct type of certificate based - * on what each client supports. + * OCSPStaple contains an optional OCSP response which will be served + * to clients that request it. */ - forceRSA: boolean + ocspStaple: string /** - * ExtraExtensions are used when generating a new CSR (Certificate Request), - * thus allowing customization of the resulting certificate. - * For instance, TLS Feature Extension (RFC 7633) can be used - * to prevent an OCSP downgrade attack. - * - * The field value is passed to crypto/x509.CreateCertificateRequest - * in the template's ExtraExtensions field as is. + * SignedCertificateTimestamps contains an optional list of Signed + * Certificate Timestamps which will be served to clients that request it. */ - extraExtensions: Array + signedCertificateTimestamps: Array /** - * ExternalAccountBinding optionally represents an arbitrary binding to an - * account of the CA to which the ACME server is tied. - * See RFC 8555, Section 7.3.4 for more details. + * Leaf is the parsed form of the leaf certificate, which may be initialized + * using x509.ParseCertificate to reduce per-handshake processing. If nil, + * the leaf certificate will be parsed as needed. */ - externalAccountBinding?: acme.ExternalAccountBinding + leaf?: x509.Certificate } - interface Manager { + interface CurveID { + string(): string + } + interface ClientAuthType { + string(): string + } +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + */ +namespace multipart { + /** + * A Part represents a single part in a multipart body. + */ + interface Part { /** - * TLSConfig creates a new TLS config suitable for net/http.Server servers, - * supporting HTTP/2 and the tls-alpn-01 ACME challenge type. + * The headers of the body, if any, with the keys canonicalized + * in the same fashion that the Go http.Request headers are. + * For example, "foo-bar" changes case to "Foo-Bar" */ - tlsConfig(): (tls.Config | undefined) + header: textproto.MIMEHeader } - interface Manager { + interface Part { /** - * GetCertificate implements the tls.Config.GetCertificate hook. - * It provides a TLS certificate for hello.ServerName host, including answering - * tls-alpn-01 challenges. - * All other fields of hello are ignored. - * - * If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting - * a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. - * The error is propagated back to the caller of GetCertificate and is user-visible. - * This does not affect cached certs. See HostPolicy field description for more details. - * - * If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will - * also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. + * FormName returns the name parameter if p has a Content-Disposition + * of type "form-data". Otherwise it returns the empty string. */ - getCertificate(hello: tls.ClientHelloInfo): (tls.Certificate | undefined) + formName(): string } - interface Manager { + interface Part { /** - * HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. - * It returns an http.Handler that responds to the challenges and must be - * running on port 80. If it receives a request that is not an ACME challenge, - * it delegates the request to the optional fallback handler. - * - * If fallback is nil, the returned handler redirects all GET and HEAD requests - * to the default TLS port 443 with 302 Found status code, preserving the original - * request path and query. It responds with 400 Bad Request to all other HTTP methods. - * The fallback is not protected by the optional HostPolicy. - * - * Because the fallback handler is run with unencrypted port 80 requests, - * the fallback should not serve TLS-only requests. - * - * If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" - * challenge for domain verification. + * FileName returns the filename parameter of the Part's Content-Disposition + * header. If not empty, the filename is passed through filepath.Base (which is + * platform dependent) before being returned. */ - httpHandler(fallback: http.Handler): http.Handler + fileName(): string } - interface Manager { + interface Part { /** - * Listener listens on the standard TLS port (443) on all interfaces - * and returns a net.Listener returning *tls.Conn connections. - * - * The returned listener uses a *tls.Config that enables HTTP/2, and - * should only be used with servers that support HTTP/2. - * - * The returned Listener also enables TCP keep-alives on the accepted - * connections. The returned *tls.Conn are returned before their TLS - * handshake has completed. - * - * Unlike NewListener, it is the caller's responsibility to initialize - * the Manager m's Prompt, Cache, HostPolicy, and other desired options. + * Read reads the body of a part, after its headers and before the + * next part (if any) begins. */ - listener(): net.Listener + read(d: string): number + } + interface Part { + close(): void } } /** - * Package pflag is a drop-in replacement for Go's flag package, implementing - * POSIX/GNU-style --flags. - * - * pflag is compatible with the GNU extensions to the POSIX recommendations - * for command-line options. See - * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - * - * Usage: + * Package http provides HTTP client and server implementations. * - * pflag is a drop-in replacement of Go's native flag package. If you import - * pflag under the name "flag" then all code should continue to function - * with no changes. + * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: * * ``` - * import flag "github.com/spf13/pflag" + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) * ``` * - * There is one exception to this: if you directly instantiate the Flag struct - * there is one more field "Shorthand" that you will need to set. - * Most code never instantiates this struct directly, and instead uses - * functions such as String(), BoolVar(), and Var(), and is therefore - * unaffected. - * - * Define flags using flag.String(), Bool(), Int(), etc. + * The client must close the response body when finished with it: * - * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - * ``` - * var ip = flag.Int("flagname", 1234, "help message for flagname") - * ``` - * If you like, you can bind the flag to a variable using the Var() functions. * ``` - * var flagvar int - * func init() { - * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... * ``` - * Or you can create custom flags that satisfy the Value interface (with - * pointer receivers) and couple them to flag parsing by + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a Client: + * * ``` - * flag.Var(&flagVal, "name", "help message for flagname") + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... * ``` - * For such flags, the default value is just the initial value of the variable. * - * After all flags are defined, call + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a Transport: + * * ``` - * flag.Parse() + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") * ``` - * to parse the command line into the defined flags. * - * Flags may then be used directly. If you're using the flags themselves, - * they are all pointers; if you bind to variables, they're values. + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use DefaultServeMux. + * Handle and HandleFunc add handlers to DefaultServeMux: + * * ``` - * fmt.Println("ip has value ", *ip) - * fmt.Println("flagvar has value ", flagvar) + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) * ``` * - * After parsing, the arguments after the flag are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. + * More control over the server's behavior is available by creating a + * custom Server: * - * The pflag package also defines some new functions that are not in flag, - * that give one-letter shorthands for flags. You can use these by appending - * 'P' to the name of any function that defines a flag. * ``` - * var ip = flag.IntP("flagname", "f", 1234, "help message") - * var flagvar bool - * func init() { - * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, * } - * flag.VarP(&flagval, "varname", "v", "help message") + * log.Fatal(s.ListenAndServe()) * ``` - * Shorthand letters can be used with single dashes on the command line. - * Boolean shorthand flags can be combined with other shorthand flags. * - * Command line flag syntax: + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting Transport.TLSNextProto (for clients) or + * Server.TLSNextProto (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG environment variables are + * currently supported: + * * ``` - * --flag // boolean flags only - * --flag=x + * 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 * ``` * - * Unlike the flag package, a single dash before an option means something - * different than a double dash. Single dashes signify a series of shorthand - * letters for flags. All but the last shorthand letter must be boolean flags. - * ``` - * // boolean flags - * -f - * -abc - * // non-boolean flags - * -n 1234 - * -Ifile - * // mixed - * -abcs "hello" - * -abcn1234 + * The GODEBUG variables are not covered by Go's API compatibility + * promise. Please report any issues before disabling HTTP/2 + * support: https://golang.org/s/http2bug + * + * The http package's Transport and Server both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { + /** + * RoundTripper is an interface representing the ability to execute a + * single HTTP transaction, obtaining the Response for a given Request. + * + * A RoundTripper must be safe for concurrent use by multiple + * goroutines. + */ + interface RoundTripper { + /** + * RoundTrip executes a single HTTP transaction, returning + * a Response for the provided Request. + * + * RoundTrip should not attempt to interpret the response. In + * particular, RoundTrip must return err == nil if it obtained + * a response, regardless of the response's HTTP status code. + * A non-nil err should be reserved for failure to obtain a + * response. Similarly, RoundTrip should not attempt to + * handle higher-level protocol details such as redirects, + * authentication, or cookies. + * + * RoundTrip should not modify the request, except for + * consuming and closing the Request's Body. RoundTrip may + * read fields of the request in a separate goroutine. Callers + * should not mutate or reuse the request until the Response's + * Body has been closed. + * + * RoundTrip must always close the body, including on errors, + * but depending on the implementation may do so in a separate + * goroutine even after RoundTrip returns. This means that + * callers wanting to reuse the body for subsequent requests + * must arrange to wait for the Close call before doing so. + * + * The Request's URL and Header fields must be initialized. + */ + roundTrip(_arg0: Request): (Response | undefined) + } + /** + * SameSite allows a server to define a cookie attribute making it impossible for + * the browser to send this cookie along with cross-site requests. The main + * goal is to mitigate the risk of cross-origin information leakage, and provide + * some protection against cross-site request forgery attacks. + * + * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. + */ + interface SameSite extends Number{} + // @ts-ignore + import mathrand = rand + /** + * A CookieJar manages storage and use of cookies in HTTP requests. + * + * Implementations of CookieJar must be safe for concurrent use by multiple + * goroutines. + * + * The net/http/cookiejar package provides a CookieJar implementation. + */ + interface CookieJar { + /** + * SetCookies handles the receipt of the cookies in a reply for the + * given URL. It may or may not choose to save the cookies, depending + * on the jar's policy and implementation. + */ + setCookies(u: url.URL, cookies: Array<(Cookie | undefined)>): void + /** + * Cookies returns the cookies to send in a request for the given URL. + * It is up to the implementation to honor the standard cookie use + * restrictions such as in RFC 6265. + */ + cookies(u: url.URL): Array<(Cookie | undefined)> + } + // @ts-ignore + import urlpkg = url +} + +namespace store { +} + +namespace mailer { + /** + * Message defines a generic email message struct. + */ + interface Message { + from: mail.Address + to: Array + bcc: Array + cc: Array + subject: string + html: string + text: string + headers: _TygojaDict + attachments: _TygojaDict + } +} + +/** + * Package echo implements high performance, minimalist Go web framework. + * + * 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!") + * } * - * Flag parsing stops after the terminator "--". Unlike the flag package, - * flags can be interspersed with arguments anywhere on the command line - * before this terminator. + * func main() { + * // Echo instance + * e := echo.New() * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags (in their long form) accept 1, 0, t, f, true, false, - * TRUE, FALSE, True, False. - * Duration flags accept any input valid for time.ParseDuration. + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) * - * The default set of command-line flags is controlled by - * top-level functions. The FlagSet type allows one to define - * independent sets of flags, such as to implement subcommands - * in a command-line interface. The methods of FlagSet are - * analogous to the top-level functions for the command-line - * flag set. + * // 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 pflag { +namespace echo { // @ts-ignore - import goflag = flag + import stdContext = context /** - * ErrorHandling defines how to handle flag parsing errors. + * 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 ErrorHandling extends Number{} + interface Route { + method: string + path: string + handler: HandlerFunc + middlewares: Array + name: string + } + interface Route { + /** + * ToRouteInfo converts Route to RouteInfo + */ + toRouteInfo(params: Array): RouteInfo + } + interface Route { + /** + * ToRoute returns Route which Router uses to register the method handler for path. + */ + toRoute(): Route + } + interface Route { + /** + * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. + */ + forGroup(pathPrefix: string, middlewares: Array): Routable + } /** - * ParseErrorsWhitelist defines the parsing errors that can be ignored + * 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 ParseErrorsWhitelist { + interface RoutableContext { /** - * UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags + * Request returns `*http.Request`. */ - unknownFlags: boolean + request(): (http.Request | undefined) + /** + * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. + */ + rawPathParams(): (PathParams | undefined) + /** + * SetRawPathParams replaces any existing param values with new values for this context lifetime (request). + * Do not set any other value than what you got from RawPathParams as allocation of PathParams is handled by Context. + */ + setRawPathParams(params: PathParams): void + /** + * SetPath sets the registered path for the handler. + */ + setPath(p: string): void + /** + * SetRouteInfo sets the route info of this request to the context. + */ + setRouteInfo(ri: RouteInfo): void + /** + * Set saves data in the context. Allows router to store arbitrary (that only router has access to) data in context + * for later use in middlewares/handler. + */ + set(key: string, val: { + }): void } /** - * Value is the interface to the dynamic value stored in a flag. - * (The default value is represented as a string.) + * PathParam is tuple pf path parameter name and its value in request path */ - interface Value { - string(): string - set(_arg0: string): void - type(): string + interface PathParam { + name: string + value: string } } /** - * Package core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. + * Package types implements some commonly used db serializable types + * like datetime, json, etc. */ -namespace core { - interface BaseModelEvent { - model: models.Model +namespace types { + /** + * JsonRaw defines a json value type that is safe for db read/write. + */ + interface JsonRaw extends String{} + interface JsonRaw { + /** + * String returns the current JsonRaw instance as a json encoded string. + */ + string(): string } - interface BaseModelEvent { - tags(): Array + interface JsonRaw { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string } - interface BaseCollectionEvent { - collection?: models.Collection + interface JsonRaw { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string): void } - interface BaseCollectionEvent { - tags(): Array + interface JsonRaw { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): driver.Value + } + interface JsonRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. + */ + scan(value: { + }): void } } -/** - * Package reflect implements run-time reflection, allowing a program to - * manipulate objects with arbitrary types. The typical use is to take a value - * with static type interface{} and extract its dynamic type information by - * calling TypeOf, which returns a Type. - * - * A call to ValueOf returns a Value representing the run-time data. - * Zero takes a Type and returns a Value representing a zero value - * for that type. - * - * See "The Laws of Reflection" for an introduction to reflection in Go: - * https://golang.org/doc/articles/laws_of_reflection.html - */ -namespace reflect { +namespace search { /** - * A Kind represents the specific kind of type that a Type represents. - * The zero Kind is not a valid kind. + * Result defines the returned search result structure. */ - interface Kind extends Number{} + 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 { /** - * ChanDir represents a channel type's direction. + * Handler defines a hook handler function. */ - interface ChanDir extends Number{} + interface Handler {(e: T): void } /** - * Method represents a single method. + * wrapped local Hook embedded struct to limit the public API surface. */ - interface Method { + type _suberRcY = Hook + interface mainHook extends _suberRcY { + } +} + +namespace subscriptions { + /** + * Message defines a client's channel data. + */ + interface Message { + name: string + data: string + } + /** + * Client is an interface for a generic subscription client. + */ + interface Client { /** - * Name is the method name. + * Id Returns the unique id of the client. */ - name: string + id(): string /** - * PkgPath is the package path that qualifies a lower case (unexported) - * method name. It is empty for upper case (exported) method names. - * The combination of PkgPath and Name uniquely identifies a method - * in a method set. - * See https://golang.org/ref/spec#Uniqueness_of_identifiers + * Channel returns the client's communication channel. + */ + channel(): undefined + /** + * Subscriptions returns all subscriptions to which the client has subscribed to. + */ + subscriptions(): _TygojaDict + /** + * Subscribe subscribes the client to the provided subscriptions list. + */ + subscribe(...subs: string[]): void + /** + * Unsubscribe unsubscribes the client from the provided subscriptions list. + */ + unsubscribe(...subs: string[]): void + /** + * HasSubscription checks if the client is subscribed to `sub`. + */ + hasSubscription(sub: string): boolean + /** + * Set stores any value to the client's context. */ - pkgPath: string - type: Type // method type - func: Value // func with receiver as first argument - index: number // index for Type.Method - } - interface Method { + set(key: string, value: any): void /** - * IsExported reports whether the method is exported. + * Unset removes a single value from the client's context. */ - isExported(): boolean - } - interface Kind { + unset(key: string): void /** - * String returns the name of k. + * Get retrieves the key value from the client's context. */ - string(): string - } - interface ChanDir { - string(): string - } - /** - * A StructField describes a single field in a struct. - */ - interface StructField { + get(key: string): any /** - * Name is the field name. + * 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. */ - name: string + discard(): void /** - * PkgPath is the package path that qualifies a lower case (unexported) - * field name. It is empty for upper case (exported) field names. - * See https://golang.org/ref/spec#Uniqueness_of_identifiers + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. */ - pkgPath: string - type: Type // field type - tag: StructTag // field tag string - offset: number // offset within struct, in bytes - index: Array // index sequence for Type.FieldByIndex - anonymous: boolean // is an embedded field - } - interface StructField { + isDiscarded(): boolean /** - * IsExported reports whether the field is exported. + * Send sends the specified message to the client's channel (if not discarded). */ - isExported(): boolean + send(m: Message): void } } /** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. + * Package autocert provides automatic access to certificates from Let's Encrypt + * and any other ACME-based CA. + * + * This package is a work in progress and makes no API stability promises. */ -namespace fs { +namespace autocert { + // @ts-ignore + import mathrand = rand /** - * A FileMode represents a file's mode and permission bits. - * The bits have the same definition on all systems, so that - * information about files can be moved from one system - * to another portably. Not all bits apply to all systems. - * The only required bit is ModeDir for directories. + * Manager is a stateful certificate manager built on top of acme.Client. + * It obtains and refreshes certificates automatically using "tls-alpn-01" + * or "http-01" challenge types, as well as providing them to a TLS server + * via tls.Config. + * + * You must specify a cache implementation, such as DirCache, + * to reuse obtained certificates across program restarts. + * Otherwise your server is very likely to exceed the certificate + * issuer's request rate limits. */ - interface FileMode extends Number{} - interface FileMode { - string(): string + interface Manager { + /** + * Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). + * The registration may require the caller to agree to the CA's TOS. + * If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report + * whether the caller agrees to the terms. + * + * To always accept the terms, the callers can use AcceptTOS. + */ + prompt: (tosURL: string) => boolean + /** + * Cache optionally stores and retrieves previously-obtained certificates + * and other state. If nil, certs will only be cached for the lifetime of + * the Manager. Multiple Managers can share the same Cache. + * + * Using a persistent Cache, such as DirCache, is strongly recommended. + */ + cache: Cache + /** + * HostPolicy controls which domains the Manager will attempt + * to retrieve new certificates for. It does not affect cached certs. + * + * If non-nil, HostPolicy is called before requesting a new cert. + * If nil, all hosts are currently allowed. This is not recommended, + * as it opens a potential attack where clients connect to a server + * by IP address and pretend to be asking for an incorrect host name. + * Manager will attempt to obtain a certificate for that host, incorrectly, + * eventually reaching the CA's rate limit for certificate requests + * and making it impossible to obtain actual certificates. + * + * See GetCertificate for more details. + */ + hostPolicy: HostPolicy + /** + * RenewBefore optionally specifies how early certificates should + * be renewed before they expire. + * + * If zero, they're renewed 30 days before expiration. + */ + renewBefore: time.Duration + /** + * Client is used to perform low-level operations, such as account registration + * and requesting new certificates. + * + * If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory + * as the directory endpoint. + * If the Client.Key is nil, a new ECDSA P-256 key is generated and, + * if Cache is not nil, stored in cache. + * + * Mutating the field after the first call of GetCertificate method will have no effect. + */ + client?: acme.Client + /** + * Email optionally specifies a contact email address. + * This is used by CAs, such as Let's Encrypt, to notify about problems + * with issued certificates. + * + * If the Client's account key is already registered, Email is not used. + */ + email: string + /** + * ForceRSA used to make the Manager generate RSA certificates. It is now ignored. + * + * Deprecated: the Manager will request the correct type of certificate based + * on what each client supports. + */ + forceRSA: boolean + /** + * ExtraExtensions are used when generating a new CSR (Certificate Request), + * thus allowing customization of the resulting certificate. + * For instance, TLS Feature Extension (RFC 7633) can be used + * to prevent an OCSP downgrade attack. + * + * The field value is passed to crypto/x509.CreateCertificateRequest + * in the template's ExtraExtensions field as is. + */ + extraExtensions: Array + /** + * ExternalAccountBinding optionally represents an arbitrary binding to an + * account of the CA to which the ACME server is tied. + * See RFC 8555, Section 7.3.4 for more details. + */ + externalAccountBinding?: acme.ExternalAccountBinding } - interface FileMode { + interface Manager { /** - * IsDir reports whether m describes a directory. - * That is, it tests for the ModeDir bit being set in m. + * TLSConfig creates a new TLS config suitable for net/http.Server servers, + * supporting HTTP/2 and the tls-alpn-01 ACME challenge type. */ - isDir(): boolean + tlsConfig(): (tls.Config | undefined) } - interface FileMode { + interface Manager { /** - * IsRegular reports whether m describes a regular file. - * That is, it tests that no mode type bits are set. + * GetCertificate implements the tls.Config.GetCertificate hook. + * It provides a TLS certificate for hello.ServerName host, including answering + * tls-alpn-01 challenges. + * All other fields of hello are ignored. + * + * If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting + * a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. + * The error is propagated back to the caller of GetCertificate and is user-visible. + * This does not affect cached certs. See HostPolicy field description for more details. + * + * If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will + * also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. */ - isRegular(): boolean + getCertificate(hello: tls.ClientHelloInfo): (tls.Certificate | undefined) } - interface FileMode { + interface Manager { /** - * Perm returns the Unix permission bits in m (m & ModePerm). + * HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. + * It returns an http.Handler that responds to the challenges and must be + * running on port 80. If it receives a request that is not an ACME challenge, + * it delegates the request to the optional fallback handler. + * + * If fallback is nil, the returned handler redirects all GET and HEAD requests + * to the default TLS port 443 with 302 Found status code, preserving the original + * request path and query. It responds with 400 Bad Request to all other HTTP methods. + * The fallback is not protected by the optional HostPolicy. + * + * Because the fallback handler is run with unencrypted port 80 requests, + * the fallback should not serve TLS-only requests. + * + * If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" + * challenge for domain verification. */ - perm(): FileMode + httpHandler(fallback: http.Handler): http.Handler } - interface FileMode { + interface Manager { /** - * Type returns type bits in m (m & ModeType). + * Listener listens on the standard TLS port (443) on all interfaces + * and returns a net.Listener returning *tls.Conn connections. + * + * The returned listener uses a *tls.Config that enables HTTP/2, and + * should only be used with servers that support HTTP/2. + * + * The returned Listener also enables TCP keep-alives on the accepted + * connections. The returned *tls.Conn are returned before their TLS + * handshake has completed. + * + * Unlike NewListener, it is the caller's responsibility to initialize + * the Manager m's Prompt, Cache, HostPolicy, and other desired options. */ - type(): FileMode + listener(): net.Listener } } /** - * Package driver defines interfaces to be implemented by database - * drivers as used by package sql. + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. + */ +namespace core { + interface BaseModelEvent { + model: models.Model + } + interface BaseModelEvent { + tags(): Array + } + interface BaseCollectionEvent { + collection?: models.Collection + } + interface BaseCollectionEvent { + tags(): Array + } +} + +/** + * Package pflag is a drop-in replacement for Go's flag package, implementing + * POSIX/GNU-style --flags. + * + * pflag is compatible with the GNU extensions to the POSIX recommendations + * for command-line options. See + * http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + * + * Usage: * - * Most code should use package sql. + * pflag is a drop-in replacement of Go's native flag package. If you import + * pflag under the name "flag" then all code should continue to function + * with no changes. * - * The driver interface has evolved over time. Drivers should implement - * Connector and DriverContext interfaces. - * The Connector.Connect and Driver.Open methods should never return ErrBadConn. - * ErrBadConn should only be returned from Validator, SessionResetter, or - * a query method if the connection is already in an invalid (e.g. closed) state. + * ``` + * import flag "github.com/spf13/pflag" + * ``` * - * All Conn implementations should implement the following interfaces: - * Pinger, SessionResetter, and Validator. + * There is one exception to this: if you directly instantiate the Flag struct + * there is one more field "Shorthand" that you will need to set. + * Most code never instantiates this struct directly, and instead uses + * functions such as String(), BoolVar(), and Var(), and is therefore + * unaffected. * - * If named parameters or context are supported, the driver's Conn should implement: - * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * Define flags using flag.String(), Bool(), Int(), etc. * - * To support custom data types, implement NamedValueChecker. NamedValueChecker - * also allows queries to accept per-query options as a parameter by returning - * ErrRemoveArgument from CheckNamedValue. + * This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + * ``` + * var ip = flag.Int("flagname", 1234, "help message for flagname") + * ``` + * If you like, you can bind the flag to a variable using the Var() functions. + * ``` + * var flagvar int + * func init() { + * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + * } + * ``` + * Or you can create custom flags that satisfy the Value interface (with + * pointer receivers) and couple them to flag parsing by + * ``` + * flag.Var(&flagVal, "name", "help message for flagname") + * ``` + * For such flags, the default value is just the initial value of the variable. * - * If multiple result sets are supported, Rows should implement RowsNextResultSet. - * If the driver knows how to describe the types present in the returned result - * it should implement the following interfaces: RowsColumnTypeScanType, - * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, - * and RowsColumnTypePrecisionScale. A given row value may also return a Rows - * type, which may represent a database cursor value. + * After all flags are defined, call + * ``` + * flag.Parse() + * ``` + * to parse the command line into the defined flags. * - * Before a connection is returned to the connection pool after use, IsValid is - * called if implemented. Before a connection is reused for another query, - * ResetSession is called if implemented. If a connection is never returned to the - * connection pool but immediately reused, then ResetSession is called prior to - * reuse but IsValid is not called. + * Flags may then be used directly. If you're using the flags themselves, + * they are all pointers; if you bind to variables, they're values. + * ``` + * fmt.Println("ip has value ", *ip) + * fmt.Println("flagvar has value ", flagvar) + * ``` + * + * After parsing, the arguments after the flag are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * The pflag package also defines some new functions that are not in flag, + * that give one-letter shorthands for flags. You can use these by appending + * 'P' to the name of any function that defines a flag. + * ``` + * var ip = flag.IntP("flagname", "f", 1234, "help message") + * var flagvar bool + * func init() { + * flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + * } + * flag.VarP(&flagval, "varname", "v", "help message") + * ``` + * Shorthand letters can be used with single dashes on the command line. + * Boolean shorthand flags can be combined with other shorthand flags. + * + * Command line flag syntax: + * ``` + * --flag // boolean flags only + * --flag=x + * ``` + * + * Unlike the flag package, a single dash before an option means something + * different than a double dash. Single dashes signify a series of shorthand + * letters for flags. All but the last shorthand letter must be boolean flags. + * ``` + * // boolean flags + * -f + * -abc + * // non-boolean flags + * -n 1234 + * -Ifile + * // mixed + * -abcs "hello" + * -abcn1234 + * ``` + * + * Flag parsing stops after the terminator "--". Unlike the flag package, + * flags can be interspersed with arguments anywhere on the command line + * before this terminator. + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags (in their long form) accept 1, 0, t, f, true, false, + * TRUE, FALSE, True, False. + * Duration flags accept any input valid for time.ParseDuration. + * + * The default set of command-line flags is controlled by + * top-level functions. The FlagSet type allows one to define + * independent sets of flags, such as to implement subcommands + * in a command-line interface. The methods of FlagSet are + * analogous to the top-level functions for the command-line + * flag set. */ -namespace driver { +namespace pflag { + // @ts-ignore + import goflag = flag /** - * Stmt is a prepared statement. It is bound to a Conn and not - * used by multiple goroutines concurrently. + * ErrorHandling defines how to handle flag parsing errors. */ - interface Stmt { - /** - * Close closes the statement. - * - * As of Go 1.1, a Stmt will not be closed if it's in use - * by any queries. - * - * Drivers must ensure all network calls made by Close - * do not block indefinitely (e.g. apply a timeout). - */ - close(): void - /** - * NumInput returns the number of placeholder parameters. - * - * If NumInput returns >= 0, the sql package will sanity check - * argument counts from callers and return errors to the caller - * before the statement's Exec or Query methods are called. - * - * NumInput may also return -1, if the driver doesn't know - * its number of placeholders. In that case, the sql package - * will not sanity check Exec or Query argument counts. - */ - numInput(): number - /** - * Exec executes a query that doesn't return rows, such - * as an INSERT or UPDATE. - * - * Deprecated: Drivers should implement StmtExecContext instead (or additionally). - */ - exec(args: Array): Result + interface ErrorHandling extends Number{} + /** + * ParseErrorsWhitelist defines the parsing errors that can be ignored + */ + interface ParseErrorsWhitelist { /** - * Query executes a query that may return rows, such as a - * SELECT. - * - * Deprecated: Drivers should implement StmtQueryContext instead (or additionally). + * UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags */ - query(args: Array): Rows + unknownFlags: boolean } /** - * Tx is a transaction. + * Value is the interface to the dynamic value stored in a flag. + * (The default value is represented as a string.) */ - interface Tx { - commit(): void - rollback(): void + interface Value { + string(): string + set(_arg0: string): void + type(): string } } @@ -19467,61 +19249,134 @@ namespace bufio { } /** - * Package mail implements parsing of mail messages. + * Package reflect implements run-time reflection, allowing a program to + * manipulate objects with arbitrary types. The typical use is to take a value + * with static type interface{} and extract its dynamic type information by + * calling TypeOf, which returns a Type. * - * For the most part, this package follows the syntax as specified by RFC 5322 and - * extended by RFC 6532. - * Notable divergences: - * ``` - * * Obsolete address formats are not parsed, including addresses with - * embedded route information. - * * The full range of spacing (the CFWS syntax element) is not supported, - * such as breaking addresses across lines. - * * No unicode normalization is performed. - * * The special characters ()[]:;@\, are allowed to appear unquoted in names. - * ``` + * A call to ValueOf returns a Value representing the run-time data. + * Zero takes a Type and returns a Value representing a zero value + * for that type. + * + * See "The Laws of Reflection" for an introduction to reflection in Go: + * https://golang.org/doc/articles/laws_of_reflection.html */ -namespace mail { +namespace reflect { /** - * Address represents a single mail address. - * An address such as "Barry Gibbs " is represented - * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. + * A Kind represents the specific kind of type that a Type represents. + * The zero Kind is not a valid kind. */ - interface Address { - name: string // Proper name; may be empty. - address: string // user@domain + interface Kind extends Number{} + /** + * ChanDir represents a channel type's direction. + */ + interface ChanDir extends Number{} + /** + * Method represents a single method. + */ + interface Method { + /** + * Name is the method name. + */ + name: string + /** + * PkgPath is the package path that qualifies a lower case (unexported) + * method name. It is empty for upper case (exported) method names. + * The combination of PkgPath and Name uniquely identifies a method + * in a method set. + * See https://golang.org/ref/spec#Uniqueness_of_identifiers + */ + pkgPath: string + type: Type // method type + func: Value // func with receiver as first argument + index: number // index for Type.Method + } + interface Method { + /** + * IsExported reports whether the method is exported. + */ + isExported(): boolean + } + interface Kind { + /** + * String returns the name of k. + */ + string(): string + } + interface ChanDir { + string(): string + } + /** + * A StructField describes a single field in a struct. + */ + interface StructField { + /** + * Name is the field name. + */ + name: string + /** + * PkgPath is the package path that qualifies a lower case (unexported) + * field name. It is empty for upper case (exported) field names. + * See https://golang.org/ref/spec#Uniqueness_of_identifiers + */ + pkgPath: string + type: Type // field type + tag: StructTag // field tag string + offset: number // offset within struct, in bytes + index: Array // index sequence for Type.FieldByIndex + anonymous: boolean // is an embedded field } - interface Address { + interface StructField { /** - * String formats the address as a valid RFC 5322 address. - * If the address's name contains non-ASCII characters - * the name will be rendered according to RFC 2047. + * IsExported reports whether the field is exported. */ - string(): string + isExported(): boolean } } /** - * Package crypto collects common cryptographic constants. + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. */ -namespace crypto { +namespace fs { /** - * PrivateKey represents a private key using an unspecified algorithm. - * - * Although this type is an empty interface for backwards compatibility reasons, - * all private key types in the standard library implement the following interface - * - * ``` - * interface{ - * Public() crypto.PublicKey - * Equal(x crypto.PrivateKey) bool - * } - * ``` - * - * as well as purpose-specific interfaces such as Signer and Decrypter, which - * can be used for increased type safety within applications. + * A FileMode represents a file's mode and permission bits. + * The bits have the same definition on all systems, so that + * information about files can be moved from one system + * to another portably. Not all bits apply to all systems. + * The only required bit is ModeDir for directories. */ - interface PrivateKey extends _TygojaAny{} + interface FileMode extends Number{} + interface FileMode { + string(): string + } + interface FileMode { + /** + * IsDir reports whether m describes a directory. + * That is, it tests for the ModeDir bit being set in m. + */ + isDir(): boolean + } + interface FileMode { + /** + * IsRegular reports whether m describes a regular file. + * That is, it tests that no mode type bits are set. + */ + isRegular(): boolean + } + interface FileMode { + /** + * Perm returns the Unix permission bits in m (m & ModePerm). + */ + perm(): FileMode + } + interface FileMode { + /** + * Type returns type bits in m (m & ModeType). + */ + type(): FileMode + } } /** @@ -20158,6 +20013,29 @@ namespace big { } } +/** + * Package crypto collects common cryptographic constants. + */ +namespace crypto { + /** + * PrivateKey represents a private key using an unspecified algorithm. + * + * Although this type is an empty interface for backwards compatibility reasons, + * all private key types in the standard library implement the following interface + * + * ``` + * interface{ + * Public() crypto.PublicKey + * Equal(x crypto.PrivateKey) bool + * } + * ``` + * + * as well as purpose-specific interfaces such as Signer and Decrypter, which + * can be used for increased type safety within applications. + */ + interface PrivateKey extends _TygojaAny{} +} + /** * Package asn1 implements parsing of DER-encoded ASN.1 data structures, * as defined in ITU-T Rec X.690. @@ -20350,25 +20228,241 @@ namespace x509 { interface ExtKeyUsage extends Number{} } +namespace subscriptions { +} + +/** + * Package mail implements parsing of mail messages. + * + * For the most part, this package follows the syntax as specified by RFC 5322 and + * extended by RFC 6532. + * Notable divergences: + * ``` + * * Obsolete address formats are not parsed, including addresses with + * embedded route information. + * * The full range of spacing (the CFWS syntax element) is not supported, + * such as breaking addresses across lines. + * * No unicode normalization is performed. + * * The special characters ()[]:;@\, are allowed to appear unquoted in names. + * ``` + */ +namespace mail { + /** + * Address represents a single mail address. + * An address such as "Barry Gibbs " is represented + * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. + */ + interface Address { + name: string // Proper name; may be empty. + address: string // user@domain + } + interface Address { + /** + * String formats the address as a valid RFC 5322 address. + * If the address's name contains non-ASCII characters + * the name will be rendered according to RFC 2047. + */ + string(): string + } +} + /** * Package tls partially implements TLS 1.2, as specified in RFC 5246, * and TLS 1.3, as specified in RFC 8446. */ -namespace tls { +namespace tls { + /** + * ClientSessionState contains the state needed by clients to resume TLS + * sessions. + */ + interface ClientSessionState { + } + /** + * SignatureScheme identifies a signature algorithm supported by TLS. See + * RFC 8446, Section 4.2.3. + */ + interface SignatureScheme extends Number{} + interface SignatureScheme { + string(): string + } +} + +/** + * Package driver defines interfaces to be implemented by database + * drivers as used by package sql. + * + * Most code should use package sql. + * + * The driver interface has evolved over time. Drivers should implement + * Connector and DriverContext interfaces. + * The Connector.Connect and Driver.Open methods should never return ErrBadConn. + * ErrBadConn should only be returned from Validator, SessionResetter, or + * a query method if the connection is already in an invalid (e.g. closed) state. + * + * All Conn implementations should implement the following interfaces: + * Pinger, SessionResetter, and Validator. + * + * If named parameters or context are supported, the driver's Conn should implement: + * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * + * To support custom data types, implement NamedValueChecker. NamedValueChecker + * also allows queries to accept per-query options as a parameter by returning + * ErrRemoveArgument from CheckNamedValue. + * + * If multiple result sets are supported, Rows should implement RowsNextResultSet. + * If the driver knows how to describe the types present in the returned result + * it should implement the following interfaces: RowsColumnTypeScanType, + * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, + * and RowsColumnTypePrecisionScale. A given row value may also return a Rows + * type, which may represent a database cursor value. + * + * Before a connection is returned to the connection pool after use, IsValid is + * called if implemented. Before a connection is reused for another query, + * ResetSession is called if implemented. If a connection is never returned to the + * connection pool but immediately reused, then ResetSession is called prior to + * reuse but IsValid is not called. + */ +namespace driver { + /** + * Stmt is a prepared statement. It is bound to a Conn and not + * used by multiple goroutines concurrently. + */ + interface Stmt { + /** + * Close closes the statement. + * + * As of Go 1.1, a Stmt will not be closed if it's in use + * by any queries. + * + * Drivers must ensure all network calls made by Close + * do not block indefinitely (e.g. apply a timeout). + */ + close(): void + /** + * NumInput returns the number of placeholder parameters. + * + * If NumInput returns >= 0, the sql package will sanity check + * argument counts from callers and return errors to the caller + * before the statement's Exec or Query methods are called. + * + * NumInput may also return -1, if the driver doesn't know + * its number of placeholders. In that case, the sql package + * will not sanity check Exec or Query argument counts. + */ + numInput(): number + /** + * Exec executes a query that doesn't return rows, such + * as an INSERT or UPDATE. + * + * Deprecated: Drivers should implement StmtExecContext instead (or additionally). + */ + exec(args: Array): Result + /** + * Query executes a query that may return rows, such as a + * SELECT. + * + * Deprecated: Drivers should implement StmtQueryContext instead (or additionally). + */ + query(args: Array): Rows + } + /** + * Tx is a transaction. + */ + interface Tx { + commit(): void + rollback(): void + } +} + +namespace search { +} + +/** + * ``` + * Package flag implements command-line flag parsing. + * + * Usage + * + * Define flags using flag.String(), Bool(), Int(), etc. + * + * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: + * import "flag" + * var nFlag = flag.Int("n", 1234, "help message for flag n") + * If you like, you can bind the flag to a variable using the Var() functions. + * var flagvar int + * func init() { + * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + * } + * Or you can create custom flags that satisfy the Value interface (with + * pointer receivers) and couple them to flag parsing by + * flag.Var(&flagVal, "name", "help message for flagname") + * For such flags, the default value is just the initial value of the variable. + * + * After all flags are defined, call + * flag.Parse() + * to parse the command line into the defined flags. + * + * Flags may then be used directly. If you're using the flags themselves, + * they are all pointers; if you bind to variables, they're values. + * fmt.Println("ip has value ", *ip) + * fmt.Println("flagvar has value ", flagvar) + * + * After parsing, the arguments following the flags are available as the + * slice flag.Args() or individually as flag.Arg(i). + * The arguments are indexed from 0 through flag.NArg()-1. + * + * Command line flag syntax + * + * The following forms are permitted: + * + * -flag + * -flag=x + * -flag x // non-boolean flags only + * One or two minus signs may be used; they are equivalent. + * The last form is not permitted for boolean flags because the + * meaning of the command + * cmd -x * + * where * is a Unix shell wildcard, will change if there is a file + * called 0, false, etc. You must use the -flag=false form to turn + * off a boolean flag. + * + * Flag parsing stops just before the first non-flag argument + * ("-" is a non-flag argument) or after the terminator "--". + * + * Integer flags accept 1234, 0664, 0x1234 and may be negative. + * Boolean flags may be: + * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False + * Duration flags accept any input valid for time.ParseDuration. + * + * The default set of command-line flags is controlled by + * top-level functions. The FlagSet type allows one to define + * independent sets of flags, such as to implement subcommands + * in a command-line interface. The methods of FlagSet are + * analogous to the top-level functions for the command-line + * flag set. + * ``` + */ +namespace flag { /** - * ClientSessionState contains the state needed by clients to resume TLS - * sessions. + * Value is the interface to the dynamic value stored in a flag. + * (The default value is represented as a string.) + * + * If a Value has an IsBoolFlag() bool method returning true, + * the command-line parser makes -name equivalent to -name=true + * rather than using the next command-line argument. + * + * Set is called once, in command line order, for each flag present. + * The flag package may call the String method with a zero-valued receiver, + * such as a nil pointer. */ - interface ClientSessionState { + interface Value { + string(): string + set(_arg0: string): void } /** - * SignatureScheme identifies a signature algorithm supported by TLS. See - * RFC 8446, Section 4.2.3. + * ErrorHandling defines how FlagSet.Parse behaves if the parse fails. */ - interface SignatureScheme extends Number{} - interface SignatureScheme { - string(): string - } + interface ErrorHandling extends Number{} } /** @@ -20796,100 +20890,6 @@ namespace acme { } } -/** - * ``` - * Package flag implements command-line flag parsing. - * - * Usage - * - * Define flags using flag.String(), Bool(), Int(), etc. - * - * This declares an integer flag, -n, stored in the pointer nFlag, with type *int: - * import "flag" - * var nFlag = flag.Int("n", 1234, "help message for flag n") - * If you like, you can bind the flag to a variable using the Var() functions. - * var flagvar int - * func init() { - * flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - * } - * Or you can create custom flags that satisfy the Value interface (with - * pointer receivers) and couple them to flag parsing by - * flag.Var(&flagVal, "name", "help message for flagname") - * For such flags, the default value is just the initial value of the variable. - * - * After all flags are defined, call - * flag.Parse() - * to parse the command line into the defined flags. - * - * Flags may then be used directly. If you're using the flags themselves, - * they are all pointers; if you bind to variables, they're values. - * fmt.Println("ip has value ", *ip) - * fmt.Println("flagvar has value ", flagvar) - * - * After parsing, the arguments following the flags are available as the - * slice flag.Args() or individually as flag.Arg(i). - * The arguments are indexed from 0 through flag.NArg()-1. - * - * Command line flag syntax - * - * The following forms are permitted: - * - * -flag - * -flag=x - * -flag x // non-boolean flags only - * One or two minus signs may be used; they are equivalent. - * The last form is not permitted for boolean flags because the - * meaning of the command - * cmd -x * - * where * is a Unix shell wildcard, will change if there is a file - * called 0, false, etc. You must use the -flag=false form to turn - * off a boolean flag. - * - * Flag parsing stops just before the first non-flag argument - * ("-" is a non-flag argument) or after the terminator "--". - * - * Integer flags accept 1234, 0664, 0x1234 and may be negative. - * Boolean flags may be: - * 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False - * Duration flags accept any input valid for time.ParseDuration. - * - * The default set of command-line flags is controlled by - * top-level functions. The FlagSet type allows one to define - * independent sets of flags, such as to implement subcommands - * in a command-line interface. The methods of FlagSet are - * analogous to the top-level functions for the command-line - * flag set. - * ``` - */ -namespace flag { - /** - * Value is the interface to the dynamic value stored in a flag. - * (The default value is represented as a string.) - * - * If a Value has an IsBoolFlag() bool method returning true, - * the command-line parser makes -name equivalent to -name=true - * rather than using the next command-line argument. - * - * Set is called once, in command line order, for each flag present. - * The flag package may call the String method with a zero-valued receiver, - * such as a nil pointer. - */ - interface Value { - string(): string - set(_arg0: string): void - } - /** - * ErrorHandling defines how FlagSet.Parse behaves if the parse fails. - */ - interface ErrorHandling extends Number{} -} - -namespace search { -} - -namespace subscriptions { -} - /** * Package autocert provides automatic access to certificates from Let's Encrypt * and any other ACME-based CA. @@ -21002,8 +21002,8 @@ namespace reflect { * Using == on two Values does not compare the underlying values * they represent. */ - type _subffNTw = flag - interface Value extends _subffNTw { + type _suboLiBu = flag + interface Value extends _suboLiBu { } interface Value { /** @@ -21977,50 +21977,132 @@ namespace fmt { flag(c: number): boolean } /** - * ScanState represents the scanner state passed to custom scanners. - * Scanners may do rune-at-a-time scanning or ask the ScanState - * to discover the next space-delimited token. + * ScanState represents the scanner state passed to custom scanners. + * Scanners may do rune-at-a-time scanning or ask the ScanState + * to discover the next space-delimited token. + */ + interface ScanState { + /** + * ReadRune reads the next rune (Unicode code point) from the input. + * If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will + * return EOF after returning the first '\n' or when reading beyond + * the specified width. + */ + readRune(): [string, number] + /** + * UnreadRune causes the next call to ReadRune to return the same rune. + */ + unreadRune(): void + /** + * SkipSpace skips space in the input. Newlines are treated appropriately + * for the operation being performed; see the package documentation + * for more information. + */ + skipSpace(): void + /** + * Token skips space in the input if skipSpace is true, then returns the + * run of Unicode code points c satisfying f(c). If f is nil, + * !unicode.IsSpace(c) is used; that is, the token will hold non-space + * characters. Newlines are treated appropriately for the operation being + * performed; see the package documentation for more information. + * The returned slice points to shared data that may be overwritten + * by the next call to Token, a call to a Scan function using the ScanState + * as input, or when the calling Scan method returns. + */ + token(skipSpace: boolean, f: (_arg0: string) => boolean): string + /** + * Width returns the value of the width option and whether it has been set. + * The unit is Unicode code points. + */ + width(): [number, boolean] + /** + * Because ReadRune is implemented by the interface, Read should never be + * called by the scanning routines and a valid implementation of + * ScanState may choose always to return an error from Read. + */ + read(buf: string): number + } +} + +/** + * Package driver defines interfaces to be implemented by database + * drivers as used by package sql. + * + * Most code should use package sql. + * + * The driver interface has evolved over time. Drivers should implement + * Connector and DriverContext interfaces. + * The Connector.Connect and Driver.Open methods should never return ErrBadConn. + * ErrBadConn should only be returned from Validator, SessionResetter, or + * a query method if the connection is already in an invalid (e.g. closed) state. + * + * All Conn implementations should implement the following interfaces: + * Pinger, SessionResetter, and Validator. + * + * If named parameters or context are supported, the driver's Conn should implement: + * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. + * + * To support custom data types, implement NamedValueChecker. NamedValueChecker + * also allows queries to accept per-query options as a parameter by returning + * ErrRemoveArgument from CheckNamedValue. + * + * If multiple result sets are supported, Rows should implement RowsNextResultSet. + * If the driver knows how to describe the types present in the returned result + * it should implement the following interfaces: RowsColumnTypeScanType, + * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, + * and RowsColumnTypePrecisionScale. A given row value may also return a Rows + * type, which may represent a database cursor value. + * + * Before a connection is returned to the connection pool after use, IsValid is + * called if implemented. Before a connection is reused for another query, + * ResetSession is called if implemented. If a connection is never returned to the + * connection pool but immediately reused, then ResetSession is called prior to + * reuse but IsValid is not called. + */ +namespace driver { + /** + * Result is the result of a query execution. */ - interface ScanState { - /** - * ReadRune reads the next rune (Unicode code point) from the input. - * If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will - * return EOF after returning the first '\n' or when reading beyond - * the specified width. - */ - readRune(): [string, number] + interface Result { /** - * UnreadRune causes the next call to ReadRune to return the same rune. + * LastInsertId returns the database's auto-generated ID + * after, for example, an INSERT into a table with primary + * key. */ - unreadRune(): void + lastInsertId(): number /** - * SkipSpace skips space in the input. Newlines are treated appropriately - * for the operation being performed; see the package documentation - * for more information. + * RowsAffected returns the number of rows affected by the + * query. */ - skipSpace(): void + rowsAffected(): number + } + /** + * Rows is an iterator over an executed query's results. + */ + interface Rows { /** - * Token skips space in the input if skipSpace is true, then returns the - * run of Unicode code points c satisfying f(c). If f is nil, - * !unicode.IsSpace(c) is used; that is, the token will hold non-space - * characters. Newlines are treated appropriately for the operation being - * performed; see the package documentation for more information. - * The returned slice points to shared data that may be overwritten - * by the next call to Token, a call to a Scan function using the ScanState - * as input, or when the calling Scan method returns. + * Columns returns the names of the columns. The number of + * columns of the result is inferred from the length of the + * slice. If a particular column name isn't known, an empty + * string should be returned for that entry. */ - token(skipSpace: boolean, f: (_arg0: string) => boolean): string + columns(): Array /** - * Width returns the value of the width option and whether it has been set. - * The unit is Unicode code points. + * Close closes the rows iterator. */ - width(): [number, boolean] + close(): void /** - * Because ReadRune is implemented by the interface, Read should never be - * called by the scanning routines and a valid implementation of - * ScanState may choose always to return an error from Read. + * Next is called to populate the next row of data into + * the provided slice. The provided slice will be the same + * size as the Columns() are wide. + * + * Next should return io.EOF when there are no more rows. + * + * The dest should not be written to outside of Next. Care + * should be taken when closing Rows not to modify + * a buffer held in dest. */ - read(buf: string): number + next(dest: Array): void } } @@ -22283,39 +22365,6 @@ namespace big { interface Word extends Number{} } -/** - * Package crypto collects common cryptographic constants. - */ -namespace crypto { - /** - * Signer is an interface for an opaque private key that can be used for - * signing operations. For example, an RSA key kept in a hardware module. - */ - interface Signer { - /** - * Public returns the public key corresponding to the opaque, - * private key. - */ - public(): PublicKey - /** - * Sign signs digest with the private key, possibly using entropy from - * rand. For an RSA key, the resulting signature should be either a - * PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA - * key, it should be a DER-serialised, ASN.1 signature structure. - * - * Hash implements the SignerOpts interface and, in most cases, one can - * simply pass in the hash function used as opts. Sign may also attempt - * to type assert opts to other types in order to obtain algorithm - * specific values. See the documentation in each package for details. - * - * Note that when a signature of a hash of a larger message is needed, - * the caller is responsible for hashing the larger message and passing - * the hash (as digest) and the hash function (as opts) to Sign. - */ - sign(rand: io.Reader, digest: string, opts: SignerOpts): string - } -} - /** * Package asn1 implements parsing of DER-encoded ASN.1 data structures, * as defined in ITU-T Rec X.690. @@ -22394,6 +22443,39 @@ namespace pkix { } } +/** + * Package crypto collects common cryptographic constants. + */ +namespace crypto { + /** + * Signer is an interface for an opaque private key that can be used for + * signing operations. For example, an RSA key kept in a hardware module. + */ + interface Signer { + /** + * Public returns the public key corresponding to the opaque, + * private key. + */ + public(): PublicKey + /** + * Sign signs digest with the private key, possibly using entropy from + * rand. For an RSA key, the resulting signature should be either a + * PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA + * key, it should be a DER-serialised, ASN.1 signature structure. + * + * Hash implements the SignerOpts interface and, in most cases, one can + * simply pass in the hash function used as opts. Sign may also attempt + * to type assert opts to other types in order to obtain algorithm + * specific values. See the documentation in each package for details. + * + * Note that when a signature of a hash of a larger message is needed, + * the caller is responsible for hashing the larger message and passing + * the hash (as digest) and the hash function (as opts) to Sign. + */ + sign(rand: io.Reader, digest: string, opts: SignerOpts): string + } +} + /** * Package acme provides an implementation of the * Automatic Certificate Management Environment (ACME) spec, @@ -22723,84 +22805,34 @@ namespace acme { } /** - * Package driver defines interfaces to be implemented by database - * drivers as used by package sql. - * - * Most code should use package sql. - * - * The driver interface has evolved over time. Drivers should implement - * Connector and DriverContext interfaces. - * The Connector.Connect and Driver.Open methods should never return ErrBadConn. - * ErrBadConn should only be returned from Validator, SessionResetter, or - * a query method if the connection is already in an invalid (e.g. closed) state. - * - * All Conn implementations should implement the following interfaces: - * Pinger, SessionResetter, and Validator. - * - * If named parameters or context are supported, the driver's Conn should implement: - * ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx. - * - * To support custom data types, implement NamedValueChecker. NamedValueChecker - * also allows queries to accept per-query options as a parameter by returning - * ErrRemoveArgument from CheckNamedValue. - * - * If multiple result sets are supported, Rows should implement RowsNextResultSet. - * If the driver knows how to describe the types present in the returned result - * it should implement the following interfaces: RowsColumnTypeScanType, - * RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, - * and RowsColumnTypePrecisionScale. A given row value may also return a Rows - * type, which may represent a database cursor value. - * - * Before a connection is returned to the connection pool after use, IsValid is - * called if implemented. Before a connection is reused for another query, - * ResetSession is called if implemented. If a connection is never returned to the - * connection pool but immediately reused, then ResetSession is called prior to - * reuse but IsValid is not called. + * Package crypto collects common cryptographic constants. */ -namespace driver { +namespace crypto { /** - * Result is the result of a query execution. + * PublicKey represents a public key using an unspecified algorithm. + * + * Although this type is an empty interface for backwards compatibility reasons, + * all public key types in the standard library implement the following interface + * + * ``` + * interface{ + * Equal(x crypto.PublicKey) bool + * } + * ``` + * + * which can be used for increased type safety within applications. */ - interface Result { - /** - * LastInsertId returns the database's auto-generated ID - * after, for example, an INSERT into a table with primary - * key. - */ - lastInsertId(): number - /** - * RowsAffected returns the number of rows affected by the - * query. - */ - rowsAffected(): number - } + interface PublicKey extends _TygojaAny{} /** - * Rows is an iterator over an executed query's results. + * SignerOpts contains options for signing with a Signer. */ - interface Rows { - /** - * Columns returns the names of the columns. The number of - * columns of the result is inferred from the length of the - * slice. If a particular column name isn't known, an empty - * string should be returned for that entry. - */ - columns(): Array - /** - * Close closes the rows iterator. - */ - close(): void + interface SignerOpts { /** - * Next is called to populate the next row of data into - * the provided slice. The provided slice will be the same - * size as the Columns() are wide. - * - * Next should return io.EOF when there are no more rows. - * - * The dest should not be written to outside of Next. Care - * should be taken when closing Rows not to modify - * a buffer held in dest. + * HashFunc returns an identifier for the hash function used to produce + * the message passed to Signer.Sign, or else zero to indicate that no + * hashing was done. */ - next(dest: Array): void + hashFunc(): Hash } } @@ -22856,38 +22888,6 @@ namespace reflect { } } -/** - * Package crypto collects common cryptographic constants. - */ -namespace crypto { - /** - * PublicKey represents a public key using an unspecified algorithm. - * - * Although this type is an empty interface for backwards compatibility reasons, - * all public key types in the standard library implement the following interface - * - * ``` - * interface{ - * Equal(x crypto.PublicKey) bool - * } - * ``` - * - * which can be used for increased type safety within applications. - */ - interface PublicKey extends _TygojaAny{} - /** - * SignerOpts contains options for signing with a Signer. - */ - interface SignerOpts { - /** - * HashFunc returns an identifier for the hash function used to produce - * the message passed to Signer.Sign, or else zero to indicate that no - * hashing was done. - */ - hashFunc(): Hash - } -} - /** * Package asn1 implements parsing of DER-encoded ASN.1 data structures, * as defined in ITU-T Rec X.690.