From 0b7741f1f7b34c125cf0c688ec20c2097b5be3d7 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Thu, 24 Oct 2024 08:37:22 +0300 Subject: [PATCH] added additional godoc and updated the OAuth2 form to use the same created record pointer --- apis/batch.go | 16 +- apis/file.go | 1 + apis/record_auth_with_oauth2.go | 25 +- apis/record_crud.go | 18 +- apis/record_helpers_test.go | 1 + core/app.go | 134 +- core/base.go | 4 +- core/collection_model.go | 5 +- core/event_request_batch.go | 2 + core/events.go | 1 + core/field_autodate.go | 24 +- core/field_bool.go | 24 +- core/field_date.go | 24 +- core/field_editor.go | 24 +- core/field_email.go | 24 +- core/field_file.go | 24 +- core/field_json.go | 24 +- core/field_number.go | 24 +- core/field_password.go | 22 +- core/field_relation.go | 24 +- core/field_select.go | 24 +- core/field_text.go | 24 +- core/field_url.go | 24 +- core/record_query.go | 2 +- .../jsvm/internal/types/generated/types.d.ts | 7184 +++++++++-------- plugins/jsvm/internal/types/types.go | 26 +- pocketbase.go | 14 +- tools/router/event.go | 27 +- 28 files changed, 4020 insertions(+), 3750 deletions(-) diff --git a/apis/batch.go b/apis/batch.go index bd1727f1..349705ad 100644 --- a/apis/batch.go +++ b/apis/batch.go @@ -29,14 +29,14 @@ func bindBatchApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) { type HandleFunc func(e *core.RequestEvent) error -type BatchActionHandlerFunc func(app core.App, ir *core.InternalRequest, params map[string]string, next func() error) HandleFunc +type BatchActionHandlerFunc func(app core.App, ir *core.InternalRequest, params map[string]string, next func(data any) error) HandleFunc // ValidBatchActions defines a map with the supported batch InternalRequest actions. // // Note: when adding new routes make sure that their middlewares are inlined! var ValidBatchActions = map[*regexp.Regexp]BatchActionHandlerFunc{ // "upsert" handler - regexp.MustCompile(`^PUT /api/collections/(?P[^\/\?]+)/records(?P\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func() error) HandleFunc { + regexp.MustCompile(`^PUT /api/collections/(?P[^\/\?]+)/records(?P\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func(any) error) HandleFunc { var id string if len(ir.Body) > 0 && ir.Body["id"] != "" { id = cast.ToString(ir.Body["id"]) @@ -59,13 +59,13 @@ var ValidBatchActions = map[*regexp.Regexp]BatchActionHandlerFunc{ ir.URL = "/api/collections/" + params["collection"] + "/records" + params["query"] return recordCreate(next) }, - regexp.MustCompile(`^POST /api/collections/(?P[^\/\?]+)/records(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func() error) HandleFunc { + regexp.MustCompile(`^POST /api/collections/(?P[^\/\?]+)/records(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func(any) error) HandleFunc { return recordCreate(next) }, - regexp.MustCompile(`^PATCH /api/collections/(?P[^\/\?]+)/records/(?P[^\/\?]+)(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func() error) HandleFunc { + regexp.MustCompile(`^PATCH /api/collections/(?P[^\/\?]+)/records/(?P[^\/\?]+)(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func(any) error) HandleFunc { return recordUpdate(next) }, - regexp.MustCompile(`^DELETE /api/collections/(?P[^\/\?]+)/records/(?P[^\/\?]+)(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func() error) HandleFunc { + regexp.MustCompile(`^DELETE /api/collections/(?P[^\/\?]+)/records/(?P[^\/\?]+)(\?.*)?$`): func(app core.App, ir *core.InternalRequest, params map[string]string, next func(any) error) HandleFunc { return recordDelete(next) }, } @@ -246,7 +246,7 @@ func (p *batchProcessor) process(activeApp core.App, batch []*core.InternalReque p.baseEvent, batch[0], p.infoContext, - func() error { + func(_ any) error { if len(batch) == 1 { return nil } @@ -277,7 +277,7 @@ func processInternalRequest( baseEvent *core.RequestEvent, ir *core.InternalRequest, infoContext string, - optNext func() error, + optNext func(data any) error, ) (*BatchRequestResult, error) { handle, params, ok := prepareInternalAction(activeApp, ir, optNext) if !ok { @@ -475,7 +475,7 @@ func extractPrefixedFiles(request *http.Request, prefixes ...string) (map[string return result, nil } -func prepareInternalAction(activeApp core.App, ir *core.InternalRequest, optNext func() error) (HandleFunc, map[string]string, bool) { +func prepareInternalAction(activeApp core.App, ir *core.InternalRequest, optNext func(data any) error) (HandleFunc, map[string]string, bool) { full := strings.ToUpper(ir.Method) + " " + ir.URL for re, actionFactory := range ValidBatchActions { diff --git a/apis/file.go b/apis/file.go index aaa87976..1cd04c48 100644 --- a/apis/file.go +++ b/apis/file.go @@ -60,6 +60,7 @@ func (api *fileApi) fileToken(e *core.RequestEvent) error { event := new(core.FileTokenRequestEvent) event.RequestEvent = e event.Token = token + event.Record = e.Auth return e.App.OnFileTokenRequest().Trigger(event, func(e *core.FileTokenRequestEvent) error { return e.JSON(http.StatusOK, map[string]string{ diff --git a/apis/record_auth_with_oauth2.go b/apis/record_auth_with_oauth2.go index 022818e2..ab78d55a 100644 --- a/apis/record_auth_with_oauth2.go +++ b/apis/record_auth_with_oauth2.go @@ -2,7 +2,6 @@ package apis import ( "context" - "encoding/json" "errors" "fmt" "log/slog" @@ -335,27 +334,19 @@ func sendOAuth2RecordCreateRequest(txApp core.App, e *core.RecordAuthWithOAuth2R Body: payload, } - response, err := processInternalRequest(txApp, e.RequestEvent, ir, core.RequestInfoContextOAuth2, nil) + var createdRecord *core.Record + response, err := processInternalRequest(txApp, e.RequestEvent, ir, core.RequestInfoContextOAuth2, func(data any) error { + createdRecord, _ = data.(*core.Record) + + return nil + }) if err != nil { return nil, err } - if response.Status != http.StatusOK { + if response.Status != http.StatusOK || createdRecord == nil { return nil, errors.New("failed to create OAuth2 auth record") } - recordResponse := struct { - Id string `json:"id"` - }{} - - raw, err := json.Marshal(response.Body) - if err != nil { - return nil, err - } - - if err = json.Unmarshal(raw, &recordResponse); err != nil { - return nil, err - } - - return txApp.FindRecordById(e.Collection, recordResponse.Id) + return createdRecord, nil } diff --git a/apis/record_crud.go b/apis/record_crud.go index badd3a52..c0f4f88f 100644 --- a/apis/record_crud.go +++ b/apis/record_crud.go @@ -147,7 +147,7 @@ func recordView(e *core.RequestEvent) error { }) } -func recordCreate(optFinalizer func() error) func(e *core.RequestEvent) error { +func recordCreate(optFinalizer func(data any) error) func(e *core.RequestEvent) error { return func(e *core.RequestEvent) error { collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection")) if err != nil || collection == nil { @@ -278,7 +278,7 @@ func recordCreate(optFinalizer func() error) func(e *core.RequestEvent) error { if optFinalizer != nil { isOptFinalizerCalled = true - err = optFinalizer() + err = optFinalizer(e.Record) if err != nil { return firstApiError(err, e.InternalServerError("", err)) } @@ -292,7 +292,7 @@ func recordCreate(optFinalizer func() error) func(e *core.RequestEvent) error { // e.g. in case the regular hook chain was stopped and the finalizer cannot be executed as part of the last e.Next() task if !isOptFinalizerCalled && optFinalizer != nil { - if err := optFinalizer(); err != nil { + if err := optFinalizer(event.Record); err != nil { return firstApiError(err, e.InternalServerError("", err)) } } @@ -301,7 +301,7 @@ func recordCreate(optFinalizer func() error) func(e *core.RequestEvent) error { } } -func recordUpdate(optFinalizer func() error) func(e *core.RequestEvent) error { +func recordUpdate(optFinalizer func(data any) error) func(e *core.RequestEvent) error { return func(e *core.RequestEvent) error { collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection")) if err != nil || collection == nil { @@ -404,7 +404,7 @@ func recordUpdate(optFinalizer func() error) func(e *core.RequestEvent) error { if optFinalizer != nil { isOptFinalizerCalled = true - err = optFinalizer() + err = optFinalizer(e.Record) if err != nil { return firstApiError(err, e.InternalServerError("", fmt.Errorf("update optFinalizer error: %w", err))) } @@ -418,7 +418,7 @@ func recordUpdate(optFinalizer func() error) func(e *core.RequestEvent) error { // e.g. in case the regular hook chain was stopped and the finalizer cannot be executed as part of the last e.Next() task if !isOptFinalizerCalled && optFinalizer != nil { - if err := optFinalizer(); err != nil { + if err := optFinalizer(event.Record); err != nil { return firstApiError(err, e.InternalServerError("", fmt.Errorf("update optFinalizer error: %w", err))) } } @@ -427,7 +427,7 @@ func recordUpdate(optFinalizer func() error) func(e *core.RequestEvent) error { } } -func recordDelete(optFinalizer func() error) func(e *core.RequestEvent) error { +func recordDelete(optFinalizer func(data any) error) func(e *core.RequestEvent) error { return func(e *core.RequestEvent) error { collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection")) if err != nil || collection == nil { @@ -494,7 +494,7 @@ func recordDelete(optFinalizer func() error) func(e *core.RequestEvent) error { if optFinalizer != nil { isOptFinalizerCalled = true - err = optFinalizer() + err = optFinalizer(e.Record) if err != nil { return firstApiError(err, e.InternalServerError("", fmt.Errorf("delete optFinalizer error: %w", err))) } @@ -508,7 +508,7 @@ func recordDelete(optFinalizer func() error) func(e *core.RequestEvent) error { // e.g. in case the regular hook chain was stopped and the finalizer cannot be executed as part of the last e.Next() task if !isOptFinalizerCalled && optFinalizer != nil { - if err := optFinalizer(); err != nil { + if err := optFinalizer(event.Record); err != nil { return firstApiError(err, e.InternalServerError("", fmt.Errorf("delete optFinalizer error: %w", err))) } } diff --git a/apis/record_helpers_test.go b/apis/record_helpers_test.go index 475b15e2..15616bda 100644 --- a/apis/record_helpers_test.go +++ b/apis/record_helpers_test.go @@ -152,6 +152,7 @@ func TestEnrichRecords(t *testing.T) { `"test@example.com"`, `"expand":{"rel_many"`, `"id":"bgs820n361vj1qd"`, + `"id":"4q1xlclmfloku33"`, `"id":"oap640cot4yru2s"`, }, notExpected: []string{ diff --git a/core/app.go b/core/app.go index 2278b40d..6275e3f5 100644 --- a/core/app.go +++ b/core/app.go @@ -596,7 +596,7 @@ type App interface { // 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.AuthRecord is a superuser. + // Rule and db checks are ignored in case requestInfo.Auth is a superuser. // // The returned error indicate that something unexpected happened during // the check (eg. invalid rule or db query error). @@ -633,17 +633,19 @@ type App interface { // App event hooks // --------------------------------------------------------------- - // OnBootstrap hook is triggered on initializing the main application + // OnBootstrap hook is triggered when initializing the main application // resources (db, app settings, etc). OnBootstrap() *hook.Hook[*BootstrapEvent] - // OnServe hook is triggered on when the app web server is started - // (after starting the tcp listener but before initializing the blocking serve task), + // OnServe hook is triggered when the app web server is started + // (after starting the TCP listener but before initializing the blocking serve task), // allowing you to adjust its options and attach new routes or middlewares. OnServe() *hook.Hook[*ServeEvent] // OnTerminate hook is triggered when the app is in the process // of being terminated (ex. on SIGTERM signal). + // + // Note that the app could be terminated abruptly without awaiting the hook completion. OnTerminate() *hook.Hook[*TerminateEvent] // OnBackupCreate hook is triggered on each [App.CreateBackup] call. @@ -661,6 +663,9 @@ type App interface { // OnModelValidate is triggered every time when a model is being validated // (e.g. triggered by App.Validate() or App.Save()). // + // For convenience, if you want to listen to only the Record models + // events without doing manual type assertion, you can attach to the OnRecord* proxy hooks. + // // If the optional "tags" list (Collection id/name, Model table name, etc.) is specified, // then all event handlers registered via the created hook will be // triggered and called only if their event data origin matches the tags. @@ -680,7 +685,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is persisted in the database since its wrapping transaction may // not have been committed yet. - // If you wan to listen to only the actual persisted events, you can + // If you want to listen to only the actual persisted events, you can // bind to [OnModelAfterCreateSuccess] or [OnModelAfterCreateError] hooks. // // For convenience, if you want to listen to only the Record models @@ -703,7 +708,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is persisted in the database since its wrapping transaction may have been // committed yet. - // If you wan to listen to only the actual persisted events, + // If you want to listen to only the actual persisted events, // you can bind to [OnModelAfterCreateSuccess] or [OnModelAfterCreateError] hooks. // // For convenience, if you want to listen to only the Record models @@ -718,7 +723,7 @@ type App interface { // Model DB create persistence. // // Note that when a Model is persisted as part of a transaction, - // this hook is triggered AFTER the transaction has been committed. + // this hook is delayed and executed only AFTER the transaction has been committed. // This hook is NOT triggered in case the transaction rollbacks // (aka. when the model wasn't persisted). // @@ -732,10 +737,11 @@ type App interface { // OnModelAfterCreateError is triggered after each failed // Model DB create persistence. - // Note that when a Model is persisted as part of a transaction, - // this hook is triggered in one of the following cases: - // - immediately after App.Save() failure - // - on transaction rollback + // + // Note that the execution of this hook is either immediate or delayed + // depending on the error: + // - "immediate" on App.Save() failure + // - "delayed" on transaction rollback // // For convenience, if you want to listen to only the Record models // events without doing manual type assertion, you can attach to the OnRecord* proxy hooks. @@ -759,7 +765,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is persisted in the database since its wrapping transaction may // not have been committed yet. - // If you wan to listen to only the actual persisted events, you can + // If you want to listen to only the actual persisted events, you can // bind to [OnModelAfterUpdateSuccess] or [OnModelAfterUpdateError] hooks. // // For convenience, if you want to listen to only the Record models @@ -782,7 +788,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is persisted in the database since its wrapping transaction may have been // committed yet. - // If you wan to listen to only the actual persisted events, + // If you want to listen to only the actual persisted events, // you can bind to [OnModelAfterUpdateSuccess] or [OnModelAfterUpdateError] hooks. // // For convenience, if you want to listen to only the Record models @@ -797,7 +803,7 @@ type App interface { // Model DB update persistence. // // Note that when a Model is persisted as part of a transaction, - // this hook is triggered AFTER the transaction has been committed. + // this hook is delayed and executed only AFTER the transaction has been committed. // This hook is NOT triggered in case the transaction rollbacks // (aka. when the model changes weren't persisted). // @@ -812,10 +818,10 @@ type App interface { // OnModelAfterUpdateError is triggered after each failed // Model DB update persistence. // - // Note that when a Model is persisted as part of a transaction, - // this hook is triggered in one of the following cases: - // - immediately after App.Save() failure - // - on transaction rollback + // Note that the execution of this hook is either immediate or delayed + // depending on the error: + // - "immediate" on App.Save() failure + // - "delayed" on transaction rollback // // For convenience, if you want to listen to only the Record models // events without doing manual type assertion, you can attach to the OnRecord* proxy hooks. @@ -833,7 +839,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is deleted from the database since its wrapping transaction may // not have been committed yet. - // If you wan to listen to only the actual persisted deleted events, you can + // If you want to listen to only the actual persisted deleted events, you can // bind to [OnModelAfterDeleteSuccess] or [OnModelAfterDeleteError] hooks. // // For convenience, if you want to listen to only the Record models @@ -856,7 +862,7 @@ type App interface { // Note that successful execution doesn't guarantee that the model // is deleted from the database since its wrapping transaction may // not have been committed yet. - // If you wan to listen to only the actual persisted deleted events, you can + // If you want to listen to only the actual persisted deleted events, you can // bind to [OnModelAfterDeleteSuccess] or [OnModelAfterDeleteError] hooks. // // For convenience, if you want to listen to only the Record models @@ -871,7 +877,7 @@ type App interface { // Model DB delete persistence. // // Note that when a Model is deleted as part of a transaction, - // this hook is triggered AFTER the transaction has been committed. + // this hook is delayed and executed only AFTER the transaction has been committed. // This hook is NOT triggered in case the transaction rollbacks // (aka. when the model delete wasn't persisted). // @@ -886,10 +892,10 @@ type App interface { // OnModelAfterDeleteError is triggered after each failed // Model DB delete persistence. // - // Note that when a Model is deleted as part of a transaction, - // this hook is triggered in one of the following cases: - // - immediately after App.Delete() failure - // - on transaction rollback + // Note that the execution of this hook is either immediate or delayed + // depending on the error: + // - "immediate" on App.Delete() failure + // - "delayed" on transaction rollback // // For convenience, if you want to listen to only the Record models // events without doing manual type assertion, you can attach to the OnRecord* proxy hooks. @@ -904,10 +910,9 @@ type App interface { // --------------------------------------------------------------- // OnRecordEnrich is triggered every time when a record is enriched - // (during realtime message seriazation, as part of the builtin Record - // responses, or when [apis.EnrichRecord] is invoked). + // (as part of the builtin Record responses, during realtime message seriazation, or when [apis.EnrichRecord] is invoked). // - // It could be used for example to redact/hide or add computed temp + // It could be used for example to redact/hide or add computed temporary // Record model props only for the specific request info. For example: // // app.OnRecordEnrich("posts").BindFunc(func(e core.*RecordEnrichEvent) { @@ -928,7 +933,7 @@ type App interface { // triggered and called only if their event data origin matches the tags. OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent] - // OnRecordValidate is a proxy Record model hook for [OnModelValidate]. + // OnRecordValidate is a Record proxy model hook of [OnModelValidate]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -937,28 +942,28 @@ type App interface { // --------------------------------------------------------------- - // OnRecordCreate is a proxy Record model hook for [OnModelCreate]. + // OnRecordCreate is a Record proxy model hook of [OnModelCreate]. // // 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. OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordCreateExecute is a proxy Record model hook for [OnModelCreateExecute]. + // OnRecordCreateExecute is a Record proxy model hook of [OnModelCreateExecute]. // // 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. OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterCreateSuccess is a proxy Record model hook for [OnModelAfterCreateSuccess]. + // OnRecordAfterCreateSuccess is a Record proxy model hook of [OnModelAfterCreateSuccess]. // // 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. OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterCreateError is a proxy Record model hook for [OnModelAfterCreateError]. + // OnRecordAfterCreateError is a Record proxy model hook of [OnModelAfterCreateError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -967,28 +972,28 @@ type App interface { // --------------------------------------------------------------- - // OnRecordUpdate is a proxy Record model hook for [OnModelUpdate]. + // OnRecordUpdate is a Record proxy model hook of [OnModelUpdate]. // // 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. OnRecordUpdate(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordUpdateExecute is a proxy Record model hook for [OnModelUpdateExecute]. + // OnRecordUpdateExecute is a Record proxy model hook of [OnModelUpdateExecute]. // // 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. OnRecordUpdateExecute(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterUpdateSuccess is a proxy Record model hook for [OnModelAfterUpdateSuccess]. + // OnRecordAfterUpdateSuccess is a Record proxy model hook of [OnModelAfterUpdateSuccess]. // // 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. OnRecordAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterUpdateError is a proxy Record model hook for [OnModelAfterUpdateError]. + // OnRecordAfterUpdateError is a Record proxy model hook of [OnModelAfterUpdateError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -997,28 +1002,28 @@ type App interface { // --------------------------------------------------------------- - // OnRecordDelete is a proxy Record model hook for [OnModelDelete]. + // OnRecordDelete is a Record proxy model hook of [OnModelDelete]. // // 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. OnRecordDelete(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordDeleteExecute is a proxy Record model hook for [OnModelDeleteExecute]. + // OnRecordDeleteExecute is a Record proxy model hook of [OnModelDeleteExecute]. // // 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. OnRecordDeleteExecute(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterDeleteSuccess is a proxy Record model hook for [OnModelAfterDeleteSuccess]. + // OnRecordAfterDeleteSuccess is a Record proxy model hook of [OnModelAfterDeleteSuccess]. // // 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. OnRecordAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*RecordEvent] - // OnRecordAfterDeleteError is a proxy Record model hook for [OnModelAfterDeleteError]. + // OnRecordAfterDeleteError is a Record proxy model hook of [OnModelAfterDeleteError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1029,7 +1034,7 @@ type App interface { // Collection models event hooks // --------------------------------------------------------------- - // OnCollectionValidate is a proxy Collection model hook for [OnModelValidate]. + // OnCollectionValidate is a Collection proxy model hook of [OnModelValidate]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1038,28 +1043,28 @@ type App interface { // --------------------------------------------------------------- - // OnCollectionCreate is a proxy Collection model hook for [OnModelCreate]. + // OnCollectionCreate is a Collection proxy model hook of [OnModelCreate]. // // 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. OnCollectionCreate(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionCreateExecute is a proxy Collection model hook for [OnModelCreateExecute]. + // OnCollectionCreateExecute is a Collection proxy model hook of [OnModelCreateExecute]. // // 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. OnCollectionCreateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterCreateSuccess is a proxy Collection model hook for [OnModelAfterCreateSuccess]. + // OnCollectionAfterCreateSuccess is a Collection proxy model hook of [OnModelAfterCreateSuccess]. // // 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. OnCollectionAfterCreateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterCreateError is a proxy Collection model hook for [OnModelAfterCreateError]. + // OnCollectionAfterCreateError is a Collection proxy model hook of [OnModelAfterCreateError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1068,28 +1073,28 @@ type App interface { // --------------------------------------------------------------- - // OnCollectionUpdate is a proxy Collection model hook for [OnModelUpdate]. + // OnCollectionUpdate is a Collection proxy model hook of [OnModelUpdate]. // // 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. OnCollectionUpdate(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionUpdateExecute is a proxy Collection model hook for [OnModelUpdateExecute]. + // OnCollectionUpdateExecute is a Collection proxy model hook of [OnModelUpdateExecute]. // // 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. OnCollectionUpdateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterUpdateSuccess is a proxy Collection model hook for [OnModelAfterUpdateSuccess]. + // OnCollectionAfterUpdateSuccess is a Collection proxy model hook of [OnModelAfterUpdateSuccess]. // // 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. OnCollectionAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterUpdateError is a proxy Collection model hook for [OnModelAfterUpdateError]. + // OnCollectionAfterUpdateError is a Collection proxy model hook of [OnModelAfterUpdateError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1098,28 +1103,28 @@ type App interface { // --------------------------------------------------------------- - // OnCollectionDelete is a proxy Collection model hook for [OnModelDelete]. + // OnCollectionDelete is a Collection proxy model hook of [OnModelDelete]. // // 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. OnCollectionDelete(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionDeleteExecute is a proxy Collection model hook for [OnModelDeleteExecute]. + // OnCollectionDeleteExecute is a Collection proxy model hook of [OnModelDeleteExecute]. // // 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. OnCollectionDeleteExecute(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterDeleteSuccess is a proxy Collection model hook for [OnModelAfterDeleteSuccess]. + // OnCollectionAfterDeleteSuccess is a Collection proxy model hook of [OnModelAfterDeleteSuccess]. // // 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. OnCollectionAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent] - // OnCollectionAfterDeleteError is a proxy Collection model hook for [OnModelAfterDeleteError]. + // OnCollectionAfterDeleteError is a Collection proxy model hook of [OnModelAfterDeleteError]. // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1131,7 +1136,7 @@ type App interface { // --------------------------------------------------------------- // OnMailerSend hook is triggered every time when a new email is - // being send using the App.NewMailClient() instance. + // being send using the [App.NewMailClient()] instance. // // It allows intercepting the email message or to use a custom mailer client. OnMailerSend() *hook.Hook[*MailerEvent] @@ -1187,7 +1192,7 @@ type App interface { // OnRealtimeConnectRequest hook is triggered when establishing the SSE client connection. // - // Any execution after [e.Next()] of a hook handler happens after the client disconnects. + // Any execution after e.Next() of a hook handler happens after the client disconnects. OnRealtimeConnectRequest() *hook.Hook[*RealtimeConnectRequestEvent] // OnRealtimeMessageSend hook is triggered when sending an SSE message to a client. @@ -1216,7 +1221,7 @@ type App interface { // OnSettingsReload hook is triggered every time when the App.Settings() // is being replaced with a new state. // - // Calling App.Settings() after e.Next() should return the new state. + // Calling App.Settings() after e.Next() returns the new state. OnSettingsReload() *hook.Hook[*SettingsReloadEvent] // --------------------------------------------------------------- @@ -1229,8 +1234,12 @@ type App interface { // returning it to the client. OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*FileDownloadRequestEvent] - // OnFileBeforeTokenRequest hook is triggered on each file token API request. - OnFileTokenRequest() *hook.Hook[*FileTokenRequestEvent] + // OnFileBeforeTokenRequest hook is triggered on each auth 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. + OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent] // --------------------------------------------------------------- // Record Auth API event hooks @@ -1250,9 +1259,8 @@ type App interface { // OnRecordAuthWithPasswordRequest hook is triggered on each // Record auth with password API request. // - // RecordAuthWithPasswordRequestEvent.Record could be nil if no - // matching identity is found, allowing you to manually locate a different - // Record model (by reassigning [RecordAuthWithPasswordRequestEvent.Record]). + // [RecordAuthWithPasswordRequestEvent.Record] could be nil if no matching identity is found, allowing + // you to manually locate a different Record model (by reassigning [RecordAuthWithPasswordRequestEvent.Record]). // // If the optional "tags" list (Collection ids or names) is specified, // then all event handlers registered via the created hook will be @@ -1262,7 +1270,7 @@ type App interface { // OnRecordAuthWithOAuth2Request hook is triggered on each Record // OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking). // - // If the [RecordAuthWithOAuth2RequestEvent.Record] is not set, then the OAuth2 + // If [RecordAuthWithOAuth2RequestEvent.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 diff --git a/core/base.go b/core/base.go index 22869f83..781d64b8 100644 --- a/core/base.go +++ b/core/base.go @@ -981,8 +981,8 @@ func (app *BaseApp) OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*File return hook.NewTaggedHook(app.onFileDownloadRequest, tags...) } -func (app *BaseApp) OnFileTokenRequest() *hook.Hook[*FileTokenRequestEvent] { - return app.onFileTokenRequest +func (app *BaseApp) OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent] { + return hook.NewTaggedHook(app.onFileTokenRequest, tags...) } // ------------------------------------------------------------------- diff --git a/core/collection_model.go b/core/collection_model.go index c0cd57c0..e952ccf4 100644 --- a/core/collection_model.go +++ b/core/collection_model.go @@ -325,9 +325,12 @@ type baseCollection struct { Type string `db:"type" json:"type" form:"type"` Fields FieldsList `db:"fields" json:"fields" form:"fields"` Indexes types.JSONArray[string] `db:"indexes" json:"indexes" form:"indexes"` - System bool `db:"system" json:"system" form:"system"` Created types.DateTime `db:"created" json:"created"` Updated types.DateTime `db:"updated" json:"updated"` + + // System prevents the collection rename, deletion and rules change. + // It is used primarily for internal purposes for collections like "_superusers", "_externalAuths", etc. + System bool `db:"system" json:"system" form:"system"` } // Collection defines the table, fields and various options related to a set of records. diff --git a/core/event_request_batch.go b/core/event_request_batch.go index 1f24e075..240c880f 100644 --- a/core/event_request_batch.go +++ b/core/event_request_batch.go @@ -4,9 +4,11 @@ import ( "net/http" validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/pocketbase/pocketbase/tools/hook" ) type BatchRequestEvent struct { + hook.Event *RequestEvent Batch []*InternalRequest diff --git a/core/events.go b/core/events.go index 12af18fc..bd90f19a 100644 --- a/core/events.go +++ b/core/events.go @@ -323,6 +323,7 @@ func syncModelErrorEventWithCollectionErrorEvent(me *ModelErrorEvent, ce *Collec type FileTokenRequestEvent struct { hook.Event *RequestEvent + baseRecordEventData Token string } diff --git a/core/field_autodate.go b/core/field_autodate.go index 9b54211a..ad5fc066 100644 --- a/core/field_autodate.go +++ b/core/field_autodate.go @@ -25,13 +25,27 @@ var ( // AutodateField defines an "autodate" type field, aka. // field which datetime value could be auto set on record create/update. // +// This field is usually used for defining timestamp fields like "created" and "updated". +// // Requires either both or at least one of the OnCreate or OnUpdate options to be set. type AutodateField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_bool.go b/core/field_bool.go index cd4e3786..7be98c2a 100644 --- a/core/field_bool.go +++ b/core/field_bool.go @@ -19,12 +19,26 @@ const FieldTypeBool = "bool" var _ Field = (*BoolField)(nil) // BoolField defines "bool" type field to store a single true/false value. +// +// The respective zero record field value is false. type BoolField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_date.go b/core/field_date.go index 5bb67cf3..67ee1ebf 100644 --- a/core/field_date.go +++ b/core/field_date.go @@ -19,12 +19,26 @@ const FieldTypeDate = "date" var _ Field = (*DateField)(nil) // DateField defines "date" type field to store a single [types.DateTime] value. +// +// The respective zero record field value is the zero [types.DateTime]. type DateField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_editor.go b/core/field_editor.go index be75677f..5d3738fc 100644 --- a/core/field_editor.go +++ b/core/field_editor.go @@ -25,12 +25,26 @@ var ( ) // EditorField defines "editor" type field to store HTML formatted text. +// +// The respective zero record field value is empty string. type EditorField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_email.go b/core/field_email.go index f189aee5..23cd250c 100644 --- a/core/field_email.go +++ b/core/field_email.go @@ -22,12 +22,26 @@ const FieldTypeEmail = "email" var _ Field = (*EmailField)(nil) // EmailField defines "email" type field for storing single email string address. +// +// The respective zero record field value is empty string. type EmailField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_file.go b/core/field_file.go index 55cc6cb8..d047012c 100644 --- a/core/field_file.go +++ b/core/field_file.go @@ -53,6 +53,8 @@ var ( // // If MaxSelect is > 1, then the field value is expected to be a slice of record ids. // +// The respective zero record field value is either empty string (single) or empty string slice (multiple). +// // --- // // The following additional setter keys are available: @@ -72,11 +74,23 @@ var ( // // []string{"old2.txt",} // record.Set("documents-", "old1.txt") type FileField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_json.go b/core/field_json.go index 45adc473..27f047c8 100644 --- a/core/field_json.go +++ b/core/field_json.go @@ -29,12 +29,26 @@ var ( ) // JSONField defines "json" type field for storing any serialized JSON value. +// +// The respective zero record field value is the zero [types.JSONRaw]. type JSONField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_number.go b/core/field_number.go index 138c97dd..d11e1750 100644 --- a/core/field_number.go +++ b/core/field_number.go @@ -25,6 +25,8 @@ var ( // NumberField defines "number" type field for storing numeric (float64) value. // +// The respective zero record field value is 0. +// // The following additional setter keys are available: // // - "fieldName+" - appends to the existing record value. For example: @@ -32,11 +34,23 @@ var ( // - "fieldName-" - subtracts from the existing record value. For example: // record.Set("total-", 5) type NumberField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_password.go b/core/field_password.go index 147e279c..794846f7 100644 --- a/core/field_password.go +++ b/core/field_password.go @@ -47,11 +47,23 @@ var ( // - "fieldName:hash" - returns the bcrypt hash string of the record field value (if any). For example: // record.GetString("password:hash") type PasswordField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_relation.go b/core/field_relation.go index e41a440b..3c903000 100644 --- a/core/field_relation.go +++ b/core/field_relation.go @@ -35,6 +35,8 @@ var ( // // If MaxSelect is > 1, then the field value is expected to be a slice of record ids. // +// The respective zero record field value is either empty string (single) or empty string slice (multiple). +// // --- // // The following additional setter keys are available: @@ -51,11 +53,23 @@ var ( // // record.Set("categories-", "old1") // []string{"old2"} type RelationField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_select.go b/core/field_select.go index 18344095..07744088 100644 --- a/core/field_select.go +++ b/core/field_select.go @@ -35,6 +35,8 @@ var ( // // If MaxSelect is > 1, then the field value is expected to be a subset of Values slice. // +// The respective zero record field value is either empty string (single) or empty string slice (multiple). +// // --- // // The following additional setter keys are available: @@ -51,11 +53,23 @@ var ( // // record.Set("roles-", "old1") // []string{"old2"} type SelectField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_text.go b/core/field_text.go index c5aeb80c..cbcfc52f 100644 --- a/core/field_text.go +++ b/core/field_text.go @@ -29,6 +29,8 @@ var ( // TextField defines "text" type field for storing any string value. // +// The respective zero record field value is empty string. +// // The following additional setter keys are available: // // - "fieldName:autogenerate" - autogenerate field value if AutogeneratePattern is set. For example: @@ -36,11 +38,23 @@ var ( // record.Set("slug:autogenerate", "") // [random value] // record.Set("slug:autogenerate", "abc-") // abc-[random value] type TextField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/field_url.go b/core/field_url.go index 7066f78e..d925f3b4 100644 --- a/core/field_url.go +++ b/core/field_url.go @@ -22,12 +22,26 @@ const FieldTypeURL = "url" var _ Field = (*URLField)(nil) // URLField defines "url" type field for storing URL string value. +// +// The respective zero record field value is empty string. type URLField struct { - Id string `form:"id" json:"id"` - Name string `form:"name" json:"name"` - System bool `form:"system" json:"system"` - Hidden bool `form:"hidden" json:"hidden"` - Presentable bool `form:"presentable" json:"presentable"` + // Name (required) is the unique name of the field. + Name string `form:"name" json:"name"` + + // Id is the unique stable field identifier. + // + // It is automatically generated from the name when adding to a collection FieldsList. + Id string `form:"id" json:"id"` + + // System prevents the renaming and removal of the field. + System bool `form:"system" json:"system"` + + // Hidden hides the field from the API response. + Hidden bool `form:"hidden" json:"hidden"` + + // Presentable hints the Dashboard UI to use the underlying + // field record value in the relation preview label. + Presentable bool `form:"presentable" json:"presentable"` // --- diff --git a/core/record_query.go b/core/record_query.go index fac7313d..9f640df3 100644 --- a/core/record_query.go +++ b/core/record_query.go @@ -553,7 +553,7 @@ func (app *BaseApp) FindAuthRecordByEmail(collectionModelOrIdentifier any, email // 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.AuthRecord is a superuser. +// Rule and db checks are ignored in case requestInfo.Auth is a superuser. // // The returned error indicate that something unexpected happened during // the check (eg. invalid rule or db query error). diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index b1a7ea47..23e47187 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1,4 +1,4 @@ -// 1729249348 +// 1729362410 // GENERATED CODE - DO NOT MODIFY BY HAND // ------------------------------------------------------------------- @@ -420,7 +420,7 @@ declare class Field implements core.Field { interface NumberField extends core.NumberField{} // merge /** - * NumberField class defines a single "number" collection field. + * {@inheritDoc core.NumberField} * * @group PocketBase */ @@ -430,7 +430,7 @@ declare class NumberField implements core.NumberField { interface BoolField extends core.BoolField{} // merge /** - * BoolField class defines a single "bool" collection field. + * {@inheritDoc core.BoolField} * * @group PocketBase */ @@ -440,7 +440,7 @@ declare class BoolField implements core.BoolField { interface TextField extends core.TextField{} // merge /** - * TextField class defines a single "text" collection field. + * {@inheritDoc core.TextField} * * @group PocketBase */ @@ -450,7 +450,7 @@ declare class TextField implements core.TextField { interface URLField extends core.URLField{} // merge /** - * URLField class defines a single "url" collection field. + * {@inheritDoc core.URLField} * * @group PocketBase */ @@ -460,7 +460,7 @@ declare class URLField implements core.URLField { interface EmailField extends core.EmailField{} // merge /** - * EmailField class defines a single "email" collection field. + * {@inheritDoc core.EmailField} * * @group PocketBase */ @@ -470,7 +470,7 @@ declare class EmailField implements core.EmailField { interface EditorField extends core.EditorField{} // merge /** - * EditorField class defines a single "editor" collection field. + * {@inheritDoc core.EditorField} * * @group PocketBase */ @@ -480,7 +480,7 @@ declare class EditorField implements core.EditorField { interface PasswordField extends core.PasswordField{} // merge /** - * PasswordField class defines a single "password" collection field. + * {@inheritDoc core.PasswordField} * * @group PocketBase */ @@ -490,7 +490,7 @@ declare class PasswordField implements core.PasswordField { interface DateField extends core.DateField{} // merge /** - * DateField class defines a single "date" collection field. + * {@inheritDoc core.DateField} * * @group PocketBase */ @@ -500,7 +500,7 @@ declare class DateField implements core.DateField { interface AutodateField extends core.AutodateField{} // merge /** - * AutodateField class defines a single "autodate" collection field. + * {@inheritDoc core.AutodateField} * * @group PocketBase */ @@ -510,7 +510,7 @@ declare class AutodateField implements core.AutodateField { interface JSONField extends core.JSONField{} // merge /** - * JSONField class defines a single "json" collection field. + * {@inheritDoc core.JSONField} * * @group PocketBase */ @@ -520,7 +520,7 @@ declare class JSONField implements core.JSONField { interface RelationField extends core.RelationField{} // merge /** - * RelationField class defines a single "relation" collection field. + * {@inheritDoc core.RelationField} * * @group PocketBase */ @@ -530,7 +530,7 @@ declare class RelationField implements core.RelationField { interface SelectField extends core.SelectField{} // merge /** - * SelectField class defines a single "select" collection field. + * {@inheritDoc core.SelectField} * * @group PocketBase */ @@ -540,7 +540,7 @@ declare class SelectField implements core.SelectField { interface FileField extends core.FileField{} // merge /** - * FileField class defines a single "file" collection field. + * {@inheritDoc core.FileField} * * @group PocketBase */ @@ -1789,8 +1789,8 @@ namespace os { * than ReadFrom. This is used to permit ReadFrom to call io.Copy * without leading to a recursive call to ReadFrom. */ - type _subEhlJU = noReadFrom&File - interface fileWithoutReadFrom extends _subEhlJU { + type _subAuruC = noReadFrom&File + interface fileWithoutReadFrom extends _subAuruC { } interface File { /** @@ -1834,8 +1834,8 @@ namespace os { * than WriteTo. This is used to permit WriteTo to call io.Copy * without leading to a recursive call to WriteTo. */ - type _subpVAuO = noWriteTo&File - interface fileWithoutWriteTo extends _subpVAuO { + type _subJMiwj = noWriteTo&File + interface fileWithoutWriteTo extends _subJMiwj { } interface File { /** @@ -2479,8 +2479,8 @@ namespace os { * * The methods of File are safe for concurrent use. */ - type _subKFllw = file - interface File extends _subKFllw { + type _subGgjTD = file + interface File extends _subGgjTD { } /** * A FileInfo describes a file and is returned by [Stat] and [Lstat]. @@ -2872,24 +2872,6 @@ namespace filepath { } } -/** - * Package validation provides configurable and extensible rules for validating data of various types. - */ -namespace ozzo_validation { - /** - * Error interface represents an validation error - */ - interface Error { - [key:string]: any; - error(): string - code(): string - message(): string - setMessage(_arg0: string): Error - params(): _TygojaDict - setParams(_arg0: _TygojaDict): Error - } -} - /** * Package exec runs external commands. It wraps os.StartProcess to make it * easier to remap stdin and stdout, connect I/O with pipes, and do other @@ -3016,511 +2998,6 @@ namespace exec { } } -namespace security { - interface s256Challenge { - /** - * S256Challenge creates base64 encoded sha256 challenge string derived from code. - * The padding of the result base64 string is stripped per [RFC 7636]. - * - * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 - */ - (code: string): string - } - interface md5 { - /** - * MD5 creates md5 hash from the provided plain text. - */ - (text: string): string - } - interface sha256 { - /** - * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. - */ - (text: string): string - } - interface sha512 { - /** - * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. - */ - (text: string): string - } - interface hs256 { - /** - * HS256 creates a HMAC hash with sha256 digest algorithm. - */ - (text: string, secret: string): string - } - interface hs512 { - /** - * HS512 creates a HMAC hash with sha512 digest algorithm. - */ - (text: string, secret: string): string - } - interface equal { - /** - * Equal compares two hash strings for equality without leaking timing information. - */ - (hash1: string, hash2: string): boolean - } - // @ts-ignore - import crand = rand - interface encrypt { - /** - * Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key). - * - * This method uses AES-256-GCM block cypher mode. - */ - (data: string|Array, key: string): string - } - interface decrypt { - /** - * Decrypt decrypts encrypted text with key (must be valid 32 chars AES key). - * - * This method uses AES-256-GCM block cypher mode. - */ - (cipherText: string, key: string): string|Array - } - interface parseUnverifiedJWT { - /** - * ParseUnverifiedJWT parses JWT and returns its claims - * but DOES NOT verify the signature. - * - * It verifies only the exp, iat and nbf claims. - */ - (token: string): jwt.MapClaims - } - interface parseJWT { - /** - * ParseJWT verifies and parses JWT and returns its claims. - */ - (token: string, verificationKey: string): jwt.MapClaims - } - interface newJWT { - /** - * NewJWT generates and returns new HS256 signed JWT. - */ - (payload: jwt.MapClaims, signingKey: string, duration: time.Duration): string - } - // @ts-ignore - import cryptoRand = rand - // @ts-ignore - import mathRand = rand - interface randomString { - /** - * RandomString generates a cryptographically random string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - */ - (length: number): string - } - interface randomStringWithAlphabet { - /** - * RandomStringWithAlphabet generates a cryptographically random string - * with the specified length and characters set. - * - * It panics if for some reason rand.Int returns a non-nil error. - */ - (length: number, alphabet: string): string - } - interface pseudorandomString { - /** - * PseudorandomString generates a pseudorandom string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - * - * For a cryptographically random string (but a little bit slower) use RandomString instead. - */ - (length: number): string - } - interface pseudorandomStringWithAlphabet { - /** - * PseudorandomStringWithAlphabet generates a pseudorandom string - * with the specified length and characters set. - * - * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. - */ - (length: number, alphabet: string): string - } - interface randomStringByRegex { - /** - * RandomStringByRegex generates a random string matching the regex pattern. - * If optFlags is not set, fallbacks to [syntax.Perl]. - * - * NB! While the source of the randomness comes from [crypto/rand] this method - * is not recommended to be used on its own in critical secure contexts because - * the generated length could vary too much on the used pattern and may not be - * as secure as simply calling [security.RandomString]. - * If you still insist on using it for such purposes, consider at least - * a large enough minimum length for the generated string, e.g. `[a-z0-9]{30}`. - * - * This function is inspired by github.com/pipe01/revregexp, github.com/lucasjones/reggen and other similar packages. - */ - (pattern: string, ...optFlags: syntax.Flags[]): string - } -} - -namespace filesystem { - /** - * FileReader defines an interface for a file resource reader. - */ - interface FileReader { - [key:string]: any; - open(): io.ReadSeekCloser - } - /** - * File defines a single file [io.ReadSeekCloser] resource. - * - * The file could be from a local path, multipart/form-data header, etc. - */ - interface File { - reader: FileReader - name: string - originalName: string - size: number - } - interface File { - /** - * AsMap implements [core.mapExtractor] and returns a value suitable - * to be used in an API rule expression. - */ - asMap(): _TygojaDict - } - interface newFileFromPath { - /** - * NewFileFromPath creates a new File instance from the provided local file path. - */ - (path: string): (File) - } - interface newFileFromBytes { - /** - * NewFileFromBytes creates a new File instance from the provided byte slice. - */ - (b: string|Array, name: string): (File) - } - interface newFileFromMultipart { - /** - * NewFileFromMultipart creates a new File from the provided multipart header. - */ - (mh: multipart.FileHeader): (File) - } - interface newFileFromURL { - /** - * NewFileFromURL creates a new File from the provided url by - * downloading the resource and load it as BytesReader. - * - * Example - * - * ``` - * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - * defer cancel() - * - * file, err := filesystem.NewFileFromURL(ctx, "https://example.com/image.png") - * ``` - */ - (ctx: context.Context, url: string): (File) - } - /** - * MultipartReader defines a FileReader from [multipart.FileHeader]. - */ - interface MultipartReader { - header?: multipart.FileHeader - } - interface MultipartReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - /** - * PathReader defines a FileReader from a local file path. - */ - interface PathReader { - path: string - } - interface PathReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - /** - * BytesReader defines a FileReader from bytes content. - */ - interface BytesReader { - bytes: string|Array - } - interface BytesReader { - /** - * Open implements the [filesystem.FileReader] interface. - */ - open(): io.ReadSeekCloser - } - type _subCxJPz = bytes.Reader - interface bytesReadSeekCloser extends _subCxJPz { - } - interface bytesReadSeekCloser { - /** - * Close implements the [io.ReadSeekCloser] interface. - */ - close(): void - } - interface System { - } - interface newS3 { - /** - * NewS3 initializes an S3 filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. - */ - (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) - } - interface newLocal { - /** - * NewLocal initializes a new local filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. - */ - (dirPath: string): (System) - } - interface System { - /** - * SetContext assigns the specified context to the current filesystem. - */ - setContext(ctx: context.Context): void - } - interface System { - /** - * Close releases any resources used for the related filesystem. - */ - close(): void - } - interface System { - /** - * Exists checks if file with fileKey path exists or not. - * - * If the file doesn't exist returns false and ErrNotFound. - */ - exists(fileKey: string): boolean - } - interface System { - /** - * Attributes returns the attributes for the file with fileKey path. - * - * If the file doesn't exist it returns ErrNotFound. - */ - attributes(fileKey: string): (blob.Attributes) - } - interface System { - /** - * GetFile returns a file content reader for the given fileKey. - * - * NB! Make sure to call Close() on the file after you are done working with it. - * - * If the file doesn't exist returns ErrNotFound. - */ - getFile(fileKey: string): (blob.Reader) - } - interface System { - /** - * Copy copies the file stored at srcKey to dstKey. - * - * If srcKey file doesn't exist, it returns ErrNotFound. - * - * If dstKey file already exists, it is overwritten. - */ - copy(srcKey: string, dstKey: string): void - } - interface System { - /** - * List returns a flat list with info for all files under the specified prefix. - */ - list(prefix: string): Array<(blob.ListObject | undefined)> - } - interface System { - /** - * Upload writes content into the fileKey location. - */ - upload(content: string|Array, fileKey: string): void - } - interface System { - /** - * UploadFile uploads the provided 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. - * - * If the file doesn't exist returns ErrNotFound. - */ - delete(fileKey: string): void - } - interface System { - /** - * DeletePrefix deletes everything starting with the specified prefix. - * - * The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_"). - */ - deletePrefix(prefix: string): Array - } - interface System { - /** - * Checks if the provided dir prefix doesn't have any files. - * - * A trailing slash will be appended to a non-empty dir string argument - * to ensure that the checked prefix is a "directory". - * - * Returns "false" in case the has at least one file, otherwise - "true". - */ - isEmptyDir(dir: string): boolean - } - 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"). - * - * Internally this method uses [http.ServeContent] so Range requests, - * If-Match, If-Unmodified-Since, etc. headers are handled transparently. - */ - 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, thumbSize: string): void - } - // @ts-ignore - import v4 = signer - // @ts-ignore - import smithyhttp = http - interface ignoredHeadersKey { - } -} - -/** - * Package template is a thin wrapper around the standard html/template - * and text/template packages that implements a convenient registry to - * load and cache templates on the fly concurrently. - * - * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. - * - * Example: - * - * ``` - * registry := template.NewRegistry() - * - * html1, err := registry.LoadFiles( - * // the files set wil be parsed only once and then cached - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "John"}) - * - * html2, err := registry.LoadFiles( - * // reuse the already parsed and cached files set - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "Jane"}) - * ``` - */ -namespace template { - interface newRegistry { - /** - * NewRegistry creates and initializes a new templates registry with - * some defaults (eg. global "raw" template function for unescaped HTML). - * - * Use the Registry.Load* methods to load templates into the registry. - */ - (): (Registry) - } - /** - * Registry defines a templates registry that is safe to be used by multiple goroutines. - * - * Use the Registry.Load* methods to load templates into the registry. - */ - interface Registry { - } - interface Registry { - /** - * AddFuncs registers new global template functions. - * - * The key of each map entry is the function name that will be used in the templates. - * If a function with the map entry name already exists it will be replaced with the new one. - * - * The value of each map entry is a function that must have either a - * single return value, or two return values of which the second has type error. - * - * Example: - * - * ``` - * r.AddFuncs(map[string]any{ - * "toUpper": func(str string) string { - * return strings.ToUppser(str) - * }, - * ... - * }) - * ``` - */ - addFuncs(funcs: _TygojaDict): (Registry) - } - interface Registry { - /** - * LoadFiles caches (if not already) the specified filenames set as a - * single template and returns a ready to use Renderer instance. - * - * There must be at least 1 filename specified. - */ - loadFiles(...filenames: string[]): (Renderer) - } - interface Registry { - /** - * LoadString caches (if not already) the specified inline string as a - * single template and returns a ready to use Renderer instance. - */ - loadString(text: string): (Renderer) - } - interface Registry { - /** - * LoadFS caches (if not already) the specified fs and globPatterns - * pair as single template and returns a ready to use Renderer instance. - * - * There must be at least 1 file matching the provided globPattern(s) - * (note that most file names serves as glob patterns matching themselves). - */ - loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) - } - /** - * Renderer defines a single parsed template. - */ - interface Renderer { - } - interface Renderer { - /** - * Render executes the template with the specified data as the dot object - * and returns the result as plain string. - */ - render(data: any): string - } -} - /** * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. */ @@ -3857,14 +3334,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subLgFNn = BaseBuilder - interface MssqlBuilder extends _subLgFNn { + type _subrIOYV = BaseBuilder + interface MssqlBuilder extends _subrIOYV { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subhtmFu = BaseQueryBuilder - interface MssqlQueryBuilder extends _subhtmFu { + type _subwWXeR = BaseQueryBuilder + interface MssqlQueryBuilder extends _subwWXeR { } interface newMssqlBuilder { /** @@ -3935,8 +3412,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subpluAG = BaseBuilder - interface MysqlBuilder extends _subpluAG { + type _subhrUel = BaseBuilder + interface MysqlBuilder extends _subhrUel { } interface newMysqlBuilder { /** @@ -4011,14 +3488,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subHxGWr = BaseBuilder - interface OciBuilder extends _subHxGWr { + type _subSqcPu = BaseBuilder + interface OciBuilder extends _subSqcPu { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subzeKAp = BaseQueryBuilder - interface OciQueryBuilder extends _subzeKAp { + type _subulEQF = BaseQueryBuilder + interface OciQueryBuilder extends _subulEQF { } interface newOciBuilder { /** @@ -4081,8 +3558,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subosDkh = BaseBuilder - interface PgsqlBuilder extends _subosDkh { + type _subuLUhu = BaseBuilder + interface PgsqlBuilder extends _subuLUhu { } interface newPgsqlBuilder { /** @@ -4149,8 +3626,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subWlPOj = BaseBuilder - interface SqliteBuilder extends _subWlPOj { + type _subdexIY = BaseBuilder + interface SqliteBuilder extends _subdexIY { } interface newSqliteBuilder { /** @@ -4249,8 +3726,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subWurQo = BaseBuilder - interface StandardBuilder extends _subWurQo { + type _subTTuxV = BaseBuilder + interface StandardBuilder extends _subTTuxV { } interface newStandardBuilder { /** @@ -4316,8 +3793,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 _subwnElh = Builder - interface DB extends _subwnElh { + type _subehEnN = Builder + interface DB extends _subehEnN { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -5121,8 +4598,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 _subJWanl = sql.Rows - interface Rows extends _subJWanl { + type _subieyZZ = sql.Rows + interface Rows extends _subieyZZ { } interface Rows { /** @@ -5480,8 +4957,8 @@ namespace dbx { }): string } interface structInfo { } - type _subYmMMK = structInfo - interface structValue extends _subYmMMK { + type _subYcgqa = structInfo + interface structValue extends _subYcgqa { } interface fieldInfo { } @@ -5520,8 +4997,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subgQtJs = Builder - interface Tx extends _subgQtJs { + type _subDiMnt = Builder + interface Tx extends _subDiMnt { } interface Tx { /** @@ -5537,6 +5014,424 @@ namespace dbx { } } +/** + * Package validation provides configurable and extensible rules for validating data of various types. + */ +namespace ozzo_validation { + /** + * Error interface represents an validation error + */ + interface Error { + [key:string]: any; + error(): string + code(): string + message(): string + setMessage(_arg0: string): Error + params(): _TygojaDict + setParams(_arg0: _TygojaDict): Error + } +} + +namespace security { + interface s256Challenge { + /** + * S256Challenge creates base64 encoded sha256 challenge string derived from code. + * The padding of the result base64 string is stripped per [RFC 7636]. + * + * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 + */ + (code: string): string + } + interface md5 { + /** + * MD5 creates md5 hash from the provided plain text. + */ + (text: string): string + } + interface sha256 { + /** + * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. + */ + (text: string): string + } + interface sha512 { + /** + * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. + */ + (text: string): string + } + interface hs256 { + /** + * HS256 creates a HMAC hash with sha256 digest algorithm. + */ + (text: string, secret: string): string + } + interface hs512 { + /** + * HS512 creates a HMAC hash with sha512 digest algorithm. + */ + (text: string, secret: string): string + } + interface equal { + /** + * Equal compares two hash strings for equality without leaking timing information. + */ + (hash1: string, hash2: string): boolean + } + // @ts-ignore + import crand = rand + interface encrypt { + /** + * Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key). + * + * This method uses AES-256-GCM block cypher mode. + */ + (data: string|Array, key: string): string + } + interface decrypt { + /** + * Decrypt decrypts encrypted text with key (must be valid 32 chars AES key). + * + * This method uses AES-256-GCM block cypher mode. + */ + (cipherText: string, key: string): string|Array + } + interface parseUnverifiedJWT { + /** + * ParseUnverifiedJWT parses JWT and returns its claims + * but DOES NOT verify the signature. + * + * It verifies only the exp, iat and nbf claims. + */ + (token: string): jwt.MapClaims + } + interface parseJWT { + /** + * ParseJWT verifies and parses JWT and returns its claims. + */ + (token: string, verificationKey: string): jwt.MapClaims + } + interface newJWT { + /** + * NewJWT generates and returns new HS256 signed JWT. + */ + (payload: jwt.MapClaims, signingKey: string, duration: time.Duration): string + } + // @ts-ignore + import cryptoRand = rand + // @ts-ignore + import mathRand = rand + interface randomString { + /** + * RandomString generates a cryptographically random string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + */ + (length: number): string + } + interface randomStringWithAlphabet { + /** + * RandomStringWithAlphabet generates a cryptographically random string + * with the specified length and characters set. + * + * It panics if for some reason rand.Int returns a non-nil error. + */ + (length: number, alphabet: string): string + } + interface pseudorandomString { + /** + * PseudorandomString generates a pseudorandom string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * + * For a cryptographically random string (but a little bit slower) use RandomString instead. + */ + (length: number): string + } + interface pseudorandomStringWithAlphabet { + /** + * PseudorandomStringWithAlphabet generates a pseudorandom string + * with the specified length and characters set. + * + * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. + */ + (length: number, alphabet: string): string + } + interface randomStringByRegex { + /** + * RandomStringByRegex generates a random string matching the regex pattern. + * If optFlags is not set, fallbacks to [syntax.Perl]. + * + * NB! While the source of the randomness comes from [crypto/rand] this method + * is not recommended to be used on its own in critical secure contexts because + * the generated length could vary too much on the used pattern and may not be + * as secure as simply calling [security.RandomString]. + * If you still insist on using it for such purposes, consider at least + * a large enough minimum length for the generated string, e.g. `[a-z0-9]{30}`. + * + * This function is inspired by github.com/pipe01/revregexp, github.com/lucasjones/reggen and other similar packages. + */ + (pattern: string, ...optFlags: syntax.Flags[]): string + } +} + +namespace filesystem { + /** + * FileReader defines an interface for a file resource reader. + */ + interface FileReader { + [key:string]: any; + open(): io.ReadSeekCloser + } + /** + * File defines a single file [io.ReadSeekCloser] resource. + * + * The file could be from a local path, multipart/form-data header, etc. + */ + interface File { + reader: FileReader + name: string + originalName: string + size: number + } + interface File { + /** + * AsMap implements [core.mapExtractor] and returns a value suitable + * to be used in an API rule expression. + */ + asMap(): _TygojaDict + } + interface newFileFromPath { + /** + * NewFileFromPath creates a new File instance from the provided local file path. + */ + (path: string): (File) + } + interface newFileFromBytes { + /** + * NewFileFromBytes creates a new File instance from the provided byte slice. + */ + (b: string|Array, name: string): (File) + } + interface newFileFromMultipart { + /** + * NewFileFromMultipart creates a new File from the provided multipart header. + */ + (mh: multipart.FileHeader): (File) + } + interface newFileFromURL { + /** + * NewFileFromURL creates a new File from the provided url by + * downloading the resource and load it as BytesReader. + * + * Example + * + * ``` + * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + * defer cancel() + * + * file, err := filesystem.NewFileFromURL(ctx, "https://example.com/image.png") + * ``` + */ + (ctx: context.Context, url: string): (File) + } + /** + * MultipartReader defines a FileReader from [multipart.FileHeader]. + */ + interface MultipartReader { + header?: multipart.FileHeader + } + interface MultipartReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * PathReader defines a FileReader from a local file path. + */ + interface PathReader { + path: string + } + interface PathReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * BytesReader defines a FileReader from bytes content. + */ + interface BytesReader { + bytes: string|Array + } + interface BytesReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + type _subnHQZD = bytes.Reader + interface bytesReadSeekCloser extends _subnHQZD { + } + interface bytesReadSeekCloser { + /** + * Close implements the [io.ReadSeekCloser] interface. + */ + close(): void + } + interface System { + } + interface newS3 { + /** + * NewS3 initializes an S3 filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) + } + interface newLocal { + /** + * NewLocal initializes a new local filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (dirPath: string): (System) + } + interface System { + /** + * SetContext assigns the specified context to the current filesystem. + */ + setContext(ctx: context.Context): void + } + interface System { + /** + * Close releases any resources used for the related filesystem. + */ + close(): void + } + interface System { + /** + * Exists checks if file with fileKey path exists or not. + * + * If the file doesn't exist returns false and ErrNotFound. + */ + exists(fileKey: string): boolean + } + interface System { + /** + * Attributes returns the attributes for the file with fileKey path. + * + * If the file doesn't exist it returns ErrNotFound. + */ + attributes(fileKey: string): (blob.Attributes) + } + interface System { + /** + * GetFile returns a file content reader for the given fileKey. + * + * NB! Make sure to call Close() on the file after you are done working with it. + * + * If the file doesn't exist returns ErrNotFound. + */ + getFile(fileKey: string): (blob.Reader) + } + interface System { + /** + * Copy copies the file stored at srcKey to dstKey. + * + * If srcKey file doesn't exist, it returns ErrNotFound. + * + * If dstKey file already exists, it is overwritten. + */ + copy(srcKey: string, dstKey: string): void + } + interface System { + /** + * List returns a flat list with info for all files under the specified prefix. + */ + list(prefix: string): Array<(blob.ListObject | undefined)> + } + interface System { + /** + * Upload writes content into the fileKey location. + */ + upload(content: string|Array, fileKey: string): void + } + interface System { + /** + * UploadFile uploads the provided 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. + * + * If the file doesn't exist returns ErrNotFound. + */ + delete(fileKey: string): void + } + interface System { + /** + * DeletePrefix deletes everything starting with the specified prefix. + * + * The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_"). + */ + deletePrefix(prefix: string): Array + } + interface System { + /** + * Checks if the provided dir prefix doesn't have any files. + * + * A trailing slash will be appended to a non-empty dir string argument + * to ensure that the checked prefix is a "directory". + * + * Returns "false" in case the has at least one file, otherwise - "true". + */ + isEmptyDir(dir: string): boolean + } + 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"). + * + * Internally this method uses [http.ServeContent] so Range requests, + * If-Match, If-Unmodified-Since, etc. headers are handled transparently. + */ + 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, thumbSize: string): void + } + // @ts-ignore + import v4 = signer + // @ts-ignore + import smithyhttp = http + interface ignoredHeadersKey { + } +} + /** * Package core is the backbone of PocketBase. * @@ -7116,8 +7011,8 @@ namespace core { /** * AuthOrigin defines a Record proxy for working with the authOrigins collection. */ - type _subkRwkw = Record - interface AuthOrigin extends _subkRwkw { + type _subEUydm = Record + interface AuthOrigin extends _subEUydm { } interface newAuthOrigin { /** @@ -7809,8 +7704,8 @@ namespace core { /** * @todo experiment eventually replacing the rules *string with a struct? */ - type _subcRXwk = BaseModel - interface baseCollection extends _subcRXwk { + type _subXMuqe = BaseModel + interface baseCollection extends _subXMuqe { listRule?: string viewRule?: string createRule?: string @@ -7826,15 +7721,19 @@ namespace core { type: string fields: FieldsList indexes: types.JSONArray - system: boolean created: types.DateTime updated: types.DateTime + /** + * System prevents the collection rename, deletion and rules change. + * It is used primarily for internal purposes for collections like "_superusers", "_externalAuths", etc. + */ + system: boolean } /** * Collection defines the table, fields and various options related to a set of records. */ - type _subMWFDa = baseCollection&collectionAuthOptions&collectionViewOptions - interface Collection extends _subMWFDa { + type _subxnBpC = baseCollection&collectionAuthOptions&collectionViewOptions + interface Collection extends _subxnBpC { } interface newCollection { /** @@ -8615,8 +8514,8 @@ namespace core { /** * RequestEvent defines the PocketBase router handler event. */ - type _subLQJJQ = router.Event - interface RequestEvent extends _subLQJJQ { + type _subEofIu = router.Event + interface RequestEvent extends _subEofIu { app: App auth?: Record } @@ -8676,8 +8575,8 @@ namespace core { */ clone(): (RequestInfo) } - type _subikfrr = RequestEvent - interface BatchRequestEvent extends _subikfrr { + type _subcRGQN = RequestEvent + interface BatchRequestEvent extends _subcRGQN { batch: Array<(InternalRequest | undefined)> } interface InternalRequest { @@ -8714,54 +8613,54 @@ namespace core { interface baseCollectionEventData { tags(): Array } - type _subqRTuA = hook.Event - interface BootstrapEvent extends _subqRTuA { + type _subsueMz = hook.Event + interface BootstrapEvent extends _subsueMz { app: App } - type _subTzLHa = hook.Event - interface TerminateEvent extends _subTzLHa { + type _subbopwH = hook.Event + interface TerminateEvent extends _subbopwH { app: App isRestart: boolean } - type _subedMai = hook.Event - interface BackupEvent extends _subedMai { + type _subICcVi = hook.Event + interface BackupEvent extends _subICcVi { app: App context: context.Context name: string // the name of the backup to create/restore. exclude: Array // list of dir entries to exclude from the backup create/restore. } - type _subSNIMf = hook.Event - interface ServeEvent extends _subSNIMf { + type _subpHCuZ = hook.Event + interface ServeEvent extends _subpHCuZ { app: App router?: router.Router server?: http.Server certManager?: any } - type _subSJyBV = hook.Event&RequestEvent - interface SettingsListRequestEvent extends _subSJyBV { + type _subNDoNJ = hook.Event&RequestEvent + interface SettingsListRequestEvent extends _subNDoNJ { settings?: Settings } - type _subKlvdM = hook.Event&RequestEvent - interface SettingsUpdateRequestEvent extends _subKlvdM { + type _subTeqgd = hook.Event&RequestEvent + interface SettingsUpdateRequestEvent extends _subTeqgd { oldSettings?: Settings newSettings?: Settings } - type _subFAkLp = hook.Event - interface SettingsReloadEvent extends _subFAkLp { + type _subKetXG = hook.Event + interface SettingsReloadEvent extends _subKetXG { app: App } - type _subqsVri = hook.Event - interface MailerEvent extends _subqsVri { + type _subieeyS = hook.Event + interface MailerEvent extends _subieeyS { app: App mailer: mailer.Mailer message?: mailer.Message } - type _subxTcqA = MailerEvent&baseRecordEventData - interface MailerRecordEvent extends _subxTcqA { + type _subBNoLz = MailerEvent&baseRecordEventData + interface MailerRecordEvent extends _subBNoLz { meta: _TygojaDict } - type _subntiAo = hook.Event&baseModelEventData - interface ModelEvent extends _subntiAo { + type _subpacrt = hook.Event&baseModelEventData + interface ModelEvent extends _subpacrt { app: App context: context.Context /** @@ -8773,12 +8672,12 @@ namespace core { */ type: string } - type _subEaDjm = ModelEvent - interface ModelErrorEvent extends _subEaDjm { + type _subIvjVb = ModelEvent + interface ModelErrorEvent extends _subIvjVb { error: Error } - type _subPSrfJ = hook.Event&baseRecordEventData - interface RecordEvent extends _subPSrfJ { + type _subBbcWw = hook.Event&baseRecordEventData + interface RecordEvent extends _subBbcWw { app: App context: context.Context /** @@ -8790,12 +8689,12 @@ namespace core { */ type: string } - type _subWxJKI = RecordEvent - interface RecordErrorEvent extends _subWxJKI { + type _subwnKwb = RecordEvent + interface RecordErrorEvent extends _subwnKwb { error: Error } - type _subRDjMr = hook.Event&baseCollectionEventData - interface CollectionEvent extends _subRDjMr { + type _subzlOCE = hook.Event&baseCollectionEventData + interface CollectionEvent extends _subzlOCE { app: App context: context.Context /** @@ -8807,95 +8706,95 @@ namespace core { */ type: string } - type _subQofrR = CollectionEvent - interface CollectionErrorEvent extends _subQofrR { + type _subAehdb = CollectionEvent + interface CollectionErrorEvent extends _subAehdb { error: Error } - type _subJQdCE = hook.Event&RequestEvent - interface FileTokenRequestEvent extends _subJQdCE { + type _subYiTif = hook.Event&RequestEvent + interface FileTokenRequestEvent extends _subYiTif { token: string } - type _subBOkRo = hook.Event&RequestEvent&baseCollectionEventData - interface FileDownloadRequestEvent extends _subBOkRo { + type _subgtOYH = hook.Event&RequestEvent&baseCollectionEventData + interface FileDownloadRequestEvent extends _subgtOYH { record?: Record fileField?: FileField servedPath: string servedName: string } - type _subZoZyR = hook.Event&RequestEvent - interface CollectionsListRequestEvent extends _subZoZyR { + type _subCUVSf = hook.Event&RequestEvent + interface CollectionsListRequestEvent extends _subCUVSf { collections: Array<(Collection | undefined)> result?: search.Result } - type _subPsbHQ = hook.Event&RequestEvent - interface CollectionsImportRequestEvent extends _subPsbHQ { + type _subXoStg = hook.Event&RequestEvent + interface CollectionsImportRequestEvent extends _subXoStg { collectionsData: Array<_TygojaDict> deleteMissing: boolean } - type _subdSBBj = hook.Event&RequestEvent&baseCollectionEventData - interface CollectionRequestEvent extends _subdSBBj { + type _subNXmch = hook.Event&RequestEvent&baseCollectionEventData + interface CollectionRequestEvent extends _subNXmch { } - type _subNdTiq = hook.Event&RequestEvent - interface RealtimeConnectRequestEvent extends _subNdTiq { + type _subTAxds = hook.Event&RequestEvent + interface RealtimeConnectRequestEvent extends _subTAxds { client: subscriptions.Client /** * note: modifying it after the connect has no effect */ idleTimeout: time.Duration } - type _suboisTK = hook.Event&RequestEvent - interface RealtimeMessageEvent extends _suboisTK { + type _submgfcU = hook.Event&RequestEvent + interface RealtimeMessageEvent extends _submgfcU { client: subscriptions.Client message?: subscriptions.Message } - type _subZMzGM = hook.Event&RequestEvent - interface RealtimeSubscribeRequestEvent extends _subZMzGM { + type _subjxRiy = hook.Event&RequestEvent + interface RealtimeSubscribeRequestEvent extends _subjxRiy { client: subscriptions.Client subscriptions: Array } - type _subIxqwq = hook.Event&RequestEvent&baseCollectionEventData - interface RecordsListRequestEvent extends _subIxqwq { + type _subcWxDQ = hook.Event&RequestEvent&baseCollectionEventData + interface RecordsListRequestEvent extends _subcWxDQ { /** * @todo consider removing and maybe add as generic to the search.Result? */ records: Array<(Record | undefined)> result?: search.Result } - type _subNVFBF = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestEvent extends _subNVFBF { + type _subQWgAs = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestEvent extends _subQWgAs { record?: Record } - type _sublbfgG = hook.Event&baseRecordEventData - interface RecordEnrichEvent extends _sublbfgG { + type _subOojxF = hook.Event&baseRecordEventData + interface RecordEnrichEvent extends _subOojxF { app: App requestInfo?: RequestInfo } - type _subJTfWO = hook.Event&RequestEvent&baseCollectionEventData - interface RecordCreateOTPRequestEvent extends _subJTfWO { + type _subrgVIX = hook.Event&RequestEvent&baseCollectionEventData + interface RecordCreateOTPRequestEvent extends _subrgVIX { record?: Record password: string } - type _subsRrfj = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithOTPRequestEvent extends _subsRrfj { + type _subphfoV = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithOTPRequestEvent extends _subphfoV { record?: Record otp?: OTP } - type _subBdjMj = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthRequestEvent extends _subBdjMj { + type _subgZRzM = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthRequestEvent extends _subgZRzM { record?: Record token: string meta: any authMethod: string } - type _subSSqtd = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithPasswordRequestEvent extends _subSSqtd { + type _subRIWZy = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithPasswordRequestEvent extends _subRIWZy { record?: Record identity: string identityField: string password: string } - type _subFrXxz = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithOAuth2RequestEvent extends _subFrXxz { + type _subiwxDL = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithOAuth2RequestEvent extends _subiwxDL { providerName: string providerClient: auth.Provider record?: Record @@ -8903,41 +8802,41 @@ namespace core { createData: _TygojaDict isNewRecord: boolean } - type _subHLzLo = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthRefreshRequestEvent extends _subHLzLo { + type _subaUGkp = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthRefreshRequestEvent extends _subaUGkp { record?: Record } - type _subUUvKJ = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestPasswordResetRequestEvent extends _subUUvKJ { + type _subxBwSd = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestPasswordResetRequestEvent extends _subxBwSd { record?: Record } - type _subceOMv = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmPasswordResetRequestEvent extends _subceOMv { + type _subGhHrK = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmPasswordResetRequestEvent extends _subGhHrK { record?: Record } - type _subITuvo = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestVerificationRequestEvent extends _subITuvo { + type _subnYNmB = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestVerificationRequestEvent extends _subnYNmB { record?: Record } - type _subxFGer = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmVerificationRequestEvent extends _subxFGer { + type _subcKDkB = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmVerificationRequestEvent extends _subcKDkB { record?: Record } - type _subqeEwP = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestEmailChangeRequestEvent extends _subqeEwP { + type _subILFVC = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestEmailChangeRequestEvent extends _subILFVC { record?: Record newEmail: string } - type _subTodjE = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmEmailChangeRequestEvent extends _subTodjE { + type _subkWmEZ = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmEmailChangeRequestEvent extends _subkWmEZ { record?: Record newEmail: string } /** * ExternalAuth defines a Record proxy for working with the externalAuths collection. */ - type _subcdgwX = Record - interface ExternalAuth extends _subcdgwX { + type _subQnMWK = Record + interface ExternalAuth extends _subQnMWK { } interface newExternalAuth { /** @@ -9220,13 +9119,33 @@ namespace core { * AutodateField defines an "autodate" type field, aka. * field which datetime value could be auto set on record create/update. * + * This field is usually used for defining timestamp fields like "created" and "updated". + * * Requires either both or at least one of the OnCreate or OnUpdate options to be set. */ interface AutodateField { - id: string + /** + * Name (required) is the unique name of the field. + */ name: string + /** + * Id is the unique stable field identifier. + * + * It is automatically generated from the name when adding to a collection FieldsList. + */ + id: string + /** + * System prevents the renaming and removal of the field. + */ system: boolean + /** + * Hidden hides the field from the API response. + */ hidden: boolean + /** + * Presentable hints the Dashboard UI to use the underlying + * field record value in the relation preview label. + */ presentable: boolean /** * OnCreate auto sets the current datetime as field value on record create. @@ -9329,12 +9248,32 @@ namespace core { } /** * BoolField defines "bool" type field to store a single true/false value. + * + * The respective zero record field value is false. */ interface BoolField { - id: string + /** + * Name (required) is the unique name of the field. + */ name: string + /** + * Id is the unique stable field identifier. + * + * It is automatically generated from the name when adding to a collection FieldsList. + */ + id: string + /** + * System prevents the renaming and removal of the field. + */ system: boolean + /** + * Hidden hides the field from the API response. + */ hidden: boolean + /** + * Presentable hints the Dashboard UI to use the underlying + * field record value in the relation preview label. + */ presentable: boolean /** * Required will require the field value to be always "true". @@ -10059,10 +9998,28 @@ namespace core { * ``` */ interface NumberField { - id: string + /** + * Name (required) is the unique name of the field. + */ name: string + /** + * Id is the unique stable field identifier. + * + * It is automatically generated from the name when adding to a collection FieldsList. + */ + id: string + /** + * System prevents the renaming and removal of the field. + */ system: boolean + /** + * Hidden hides the field from the API response. + */ hidden: boolean + /** + * Presentable hints the Dashboard UI to use the underlying + * field record value in the relation preview label. + */ presentable: boolean /** * Min specifies the min allowed field value. @@ -10995,8 +10952,8 @@ namespace core { interface onlyFieldType { type: string } - type _subEWNIZ = Field - interface fieldWithType extends _subEWNIZ { + type _subaVuKr = Field + interface fieldWithType extends _subaVuKr { type: string } interface fieldWithType { @@ -11028,8 +10985,8 @@ namespace core { */ scan(value: any): void } - type _subQkFvf = BaseModel - interface Log extends _subQkFvf { + type _subhBpjk = BaseModel + interface Log extends _subhBpjk { created: types.DateTime data: types.JSONMap message: string @@ -11075,8 +11032,8 @@ namespace core { /** * MFA defines a Record proxy for working with the mfas collection. */ - type _subxhrNq = Record - interface MFA extends _subxhrNq { + type _subFIFSN = Record + interface MFA extends _subFIFSN { } interface newMFA { /** @@ -11298,8 +11255,8 @@ namespace core { /** * OTP defines a Record proxy for working with the otps collection. */ - type _subVManP = Record - interface OTP extends _subVManP { + type _subFZFgO = Record + interface OTP extends _subFZFgO { } interface newOTP { /** @@ -11495,8 +11452,8 @@ namespace core { } interface runner { } - type _subQEFpq = BaseModel - interface Record extends _subQEFpq { + type _subxyTLZ = BaseModel + interface Record extends _subxyTLZ { } interface newRecord { /** @@ -11945,8 +11902,8 @@ namespace core { * BaseRecordProxy implements the [RecordProxy] interface and it is intended * to be used as embed to custom user provided Record proxy structs. */ - type _subngxOp = Record - interface BaseRecordProxy extends _subngxOp { + type _subXgCvw = Record + interface BaseRecordProxy extends _subXgCvw { } interface BaseRecordProxy { /** @@ -12192,8 +12149,8 @@ namespace core { /** * Settings defines the PocketBase app settings. */ - type _subgJusu = settings - interface Settings extends _subgJusu { + type _subVwDlz = settings + interface Settings extends _subVwDlz { } interface Settings { /** @@ -12482,8 +12439,8 @@ namespace core { */ durationTime(): time.Duration } - type _subMdjGL = BaseModel - interface Param extends _subMdjGL { + type _subRzpPn = BaseModel + interface Param extends _subRzpPn { created: types.DateTime updated: types.DateTime value: types.JSONRaw @@ -12580,6 +12537,111 @@ namespace mails { } } +/** + * Package template is a thin wrapper around the standard html/template + * and text/template packages that implements a convenient registry to + * load and cache templates on the fly concurrently. + * + * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. + * + * Example: + * + * ``` + * registry := template.NewRegistry() + * + * html1, err := registry.LoadFiles( + * // the files set wil be parsed only once and then cached + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "John"}) + * + * html2, err := registry.LoadFiles( + * // reuse the already parsed and cached files set + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "Jane"}) + * ``` + */ +namespace template { + interface newRegistry { + /** + * NewRegistry creates and initializes a new templates registry with + * some defaults (eg. global "raw" template function for unescaped HTML). + * + * Use the Registry.Load* methods to load templates into the registry. + */ + (): (Registry) + } + /** + * Registry defines a templates registry that is safe to be used by multiple goroutines. + * + * Use the Registry.Load* methods to load templates into the registry. + */ + interface Registry { + } + interface Registry { + /** + * AddFuncs registers new global template functions. + * + * The key of each map entry is the function name that will be used in the templates. + * If a function with the map entry name already exists it will be replaced with the new one. + * + * The value of each map entry is a function that must have either a + * single return value, or two return values of which the second has type error. + * + * Example: + * + * ``` + * r.AddFuncs(map[string]any{ + * "toUpper": func(str string) string { + * return strings.ToUppser(str) + * }, + * ... + * }) + * ``` + */ + addFuncs(funcs: _TygojaDict): (Registry) + } + interface Registry { + /** + * LoadFiles caches (if not already) the specified filenames set as a + * single template and returns a ready to use Renderer instance. + * + * There must be at least 1 filename specified. + */ + loadFiles(...filenames: string[]): (Renderer) + } + interface Registry { + /** + * LoadString caches (if not already) the specified inline string as a + * single template and returns a ready to use Renderer instance. + */ + loadString(text: string): (Renderer) + } + interface Registry { + /** + * LoadFS caches (if not already) the specified fs and globPatterns + * pair as single template and returns a ready to use Renderer instance. + * + * There must be at least 1 file matching the provided globPattern(s) + * (note that most file names serves as glob patterns matching themselves). + */ + loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) + } + /** + * Renderer defines a single parsed template. + */ + interface Renderer { + } + interface Renderer { + /** + * Render executes the template with the specified data as the dot object + * and returns the result as plain string. + */ + render(data: any): string + } +} + namespace forms { // @ts-ignore import validation = ozzo_validation @@ -12991,8 +13053,8 @@ namespace apis { */ (limitBytes: number): (hook.Handler) } - type _subTrmRH = io.ReadCloser - interface limitedReader extends _subTrmRH { + type _subGDKSW = io.ReadCloser + interface limitedReader extends _subGDKSW { } interface limitedReader { read(b: string|Array): number @@ -13143,8 +13205,8 @@ namespace apis { */ (config: GzipConfig): (hook.Handler) } - type _subRYHiL = http.ResponseWriter&io.Writer - interface gzipResponseWriter extends _subRYHiL { + type _subzcXoK = http.ResponseWriter&io.Writer + interface gzipResponseWriter extends _subzcXoK { } interface gzipResponseWriter { writeHeader(code: number): void @@ -13167,11 +13229,11 @@ namespace apis { interface gzipResponseWriter { unwrap(): http.ResponseWriter } - type _subBjoHg = sync.RWMutex - interface rateLimiter extends _subBjoHg { + type _subMkQWw = sync.RWMutex + interface rateLimiter extends _subMkQWw { } - type _subThKvD = sync.Mutex - interface fixedWindow extends _subThKvD { + type _subagZdY = sync.Mutex + interface fixedWindow extends _subagZdY { } interface realtimeSubscribeForm { clientId: string @@ -13417,8 +13479,8 @@ namespace pocketbase { * It implements [CoreApp] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _subfLWjs = CoreApp - interface PocketBase extends _subfLWjs { + type _subTaISZ = CoreApp + interface PocketBase extends _subTaISZ { /** * RootCmd is the main console command */ @@ -13650,169 +13712,6 @@ namespace sync { } } -/** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * Reader is the interface that wraps the basic Read method. - * - * Read reads up to len(p) bytes into p. It returns the number of bytes - * read (0 <= n <= len(p)) and any error encountered. Even if Read - * returns n < len(p), it may use all of p as scratch space during the call. - * If some data is available but not len(p) bytes, Read conventionally - * returns what is available instead of waiting for more. - * - * When Read encounters an error or end-of-file condition after - * successfully reading n > 0 bytes, it returns the number of - * bytes read. It may return the (non-nil) error from the same call - * or return the error (and n == 0) from a subsequent call. - * An instance of this general case is that a Reader returning - * a non-zero number of bytes at the end of the input stream may - * return either err == EOF or err == nil. The next Read should - * return 0, EOF. - * - * Callers should always process the n > 0 bytes returned before - * considering the error err. Doing so correctly handles I/O errors - * that happen after reading some bytes and also both of the - * allowed EOF behaviors. - * - * If len(p) == 0, Read should always return n == 0. It may return a - * non-nil error if some error condition is known, such as EOF. - * - * Implementations of Read are discouraged from returning a - * zero byte count with a nil error, except when len(p) == 0. - * Callers should treat a return of 0 and nil as indicating that - * nothing happened; in particular it does not indicate EOF. - * - * Implementations must not retain p. - */ - interface Reader { - [key:string]: any; - read(p: string|Array): number - } - /** - * Writer is the interface that wraps the basic Write method. - * - * Write writes len(p) bytes from p to the underlying data stream. - * It returns the number of bytes written from p (0 <= n <= len(p)) - * and any error encountered that caused the write to stop early. - * Write must return a non-nil error if it returns n < len(p). - * Write must not modify the slice data, even temporarily. - * - * Implementations must not retain p. - */ - interface Writer { - [key:string]: any; - write(p: string|Array): number - } - /** - * ReadCloser is the interface that groups the basic Read and Close methods. - */ - interface ReadCloser { - [key:string]: any; - } - /** - * ReadSeekCloser is the interface that groups the basic Read, Seek and Close - * methods. - */ - interface ReadSeekCloser { - [key:string]: any; - } -} - -/** - * 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 [Reader.ReadAt]. - * The result is unaffected by any method calls except [Reader.Reset]. - */ - size(): number - } - interface Reader { - /** - * Read implements the [io.Reader] interface. - */ - read(b: string|Array): number - } - interface Reader { - /** - * ReadAt implements the [io.ReaderAt] interface. - */ - readAt(b: string|Array, off: number): number - } - interface Reader { - /** - * ReadByte implements the [io.ByteReader] interface. - */ - readByte(): number - } - interface Reader { - /** - * UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the [io.RuneReader] interface. - */ - readRune(): [number, number] - } - interface Reader { - /** - * UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. - */ - unreadRune(): void - } - interface Reader { - /** - * Seek implements the [io.Seeker] interface. - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * WriteTo implements the [io.WriterTo] interface. - */ - writeTo(w: io.Writer): number - } - interface Reader { - /** - * Reset resets the [Reader] to be reading from b. - */ - reset(b: string|Array): void - } -} - /** * Package syscall contains an interface to the low-level operating system * primitives. The details vary depending on the underlying system, and @@ -14709,6 +14608,84 @@ namespace context { } } +/** + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. + */ +namespace io { + /** + * Reader is the interface that wraps the basic Read method. + * + * Read reads up to len(p) bytes into p. It returns the number of bytes + * read (0 <= n <= len(p)) and any error encountered. Even if Read + * returns n < len(p), it may use all of p as scratch space during the call. + * If some data is available but not len(p) bytes, Read conventionally + * returns what is available instead of waiting for more. + * + * When Read encounters an error or end-of-file condition after + * successfully reading n > 0 bytes, it returns the number of + * bytes read. It may return the (non-nil) error from the same call + * or return the error (and n == 0) from a subsequent call. + * An instance of this general case is that a Reader returning + * a non-zero number of bytes at the end of the input stream may + * return either err == EOF or err == nil. The next Read should + * return 0, EOF. + * + * Callers should always process the n > 0 bytes returned before + * considering the error err. Doing so correctly handles I/O errors + * that happen after reading some bytes and also both of the + * allowed EOF behaviors. + * + * If len(p) == 0, Read should always return n == 0. It may return a + * non-nil error if some error condition is known, such as EOF. + * + * Implementations of Read are discouraged from returning a + * zero byte count with a nil error, except when len(p) == 0. + * Callers should treat a return of 0 and nil as indicating that + * nothing happened; in particular it does not indicate EOF. + * + * Implementations must not retain p. + */ + interface Reader { + [key:string]: any; + read(p: string|Array): number + } + /** + * Writer is the interface that wraps the basic Write method. + * + * Write writes len(p) bytes from p to the underlying data stream. + * It returns the number of bytes written from p (0 <= n <= len(p)) + * and any error encountered that caused the write to stop early. + * Write must return a non-nil error if it returns n < len(p). + * Write must not modify the slice data, even temporarily. + * + * Implementations must not retain p. + */ + interface Writer { + [key:string]: any; + write(p: string|Array): number + } + /** + * ReadCloser is the interface that groups the basic Read and Close methods. + */ + interface ReadCloser { + [key:string]: any; + } + /** + * ReadSeekCloser is the interface that groups the basic Read, Seek and Close + * methods. + */ + interface ReadSeekCloser { + [key:string]: any; + } +} + /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -14910,945 +14887,193 @@ namespace fs { } /** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. + * Package cron implements a crontab-like service to execute and schedule + * repeative tasks/jobs. * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. + * Example: * - * 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. + * ``` + * c := cron.New() + * c.MustAdd("dailyReport", "0 0 * * *", func() { ... }) + * c.Start() + * ``` */ -namespace sql { +namespace cron { /** - * TxOptions holds the transaction options to be used in [DB.BeginTx]. + * Cron is a crontab-like struct for tasks/jobs scheduling. */ - interface TxOptions { + interface Cron { + } + interface Cron { /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * SetInterval changes the current cron tick interval + * (it usually should be >= 1 minute). */ - isolation: IsolationLevel - readOnly: boolean + setInterval(d: time.Duration): void } - /** - * NullString represents a string that may be null. - * NullString implements the [Scanner] interface so - * it can be used as a scan destination: - * - * ``` - * var s NullString - * err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) - * ... - * if s.Valid { - * // use s.String - * } else { - * // NULL value - * } - * ``` - */ - interface NullString { - string: string - valid: boolean // Valid is true if String is not NULL - } - interface NullString { + interface Cron { /** - * Scan implements the [Scanner] interface. + * SetTimezone changes the current cron tick timezone. */ - scan(value: any): void + setTimezone(l: time.Location): void } - interface NullString { + interface Cron { /** - * Value implements the [driver.Valuer] interface. + * MustAdd is similar to Add() but panic on failure. */ - value(): any + mustAdd(jobId: string, cronExpr: string, run: () => void): void } - /** - * 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 [Tx.Commit] or - * [Tx.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 [DB.SetMaxIdleConns]. - */ - interface DB { - } - interface DB { + interface Cron { /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * Add registers a single cron job. + * + * If there is already a job with the provided id, then the old job + * will be replaced with the new one. + * + * cronExpr is a regular cron expression, eg. "0 *\/3 * * *" (aka. at minute 0 past every 3rd hour). + * Check cron.NewSchedule() for the supported tokens. */ - pingContext(ctx: context.Context): void + add(jobId: string, cronExpr: string, run: () => void): void } - interface DB { + interface Cron { /** - * 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 - * [DB.PingContext]. + * Remove removes a single cron job by its id. */ - ping(): void + remove(jobId: string): void } - interface DB { + interface Cron { /** - * 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. + * RemoveAll removes all registered cron jobs. */ - close(): void + removeAll(): void } - interface DB { + interface Cron { /** - * 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. + * Total returns the current total number of registered cron jobs. */ - setMaxIdleConns(n: number): void + total(): number } - interface DB { + interface Cron { /** - * SetMaxOpenConns sets the maximum number of open connections to the database. + * Stop stops the current cron ticker (if not already). * - * 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). + * You can resume the ticker by calling Start(). */ - setMaxOpenConns(n: number): void + stop(): void } - interface DB { + interface Cron { /** - * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. + * Start starts the cron ticker. * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's age. + * Calling Start() on already started cron will restart the ticker. */ - setConnMaxLifetime(d: time.Duration): void + start(): void } - interface DB { + interface Cron { /** - * 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. + * HasStarted checks whether the current Cron ticker has been started. */ - setConnMaxIdleTime(d: time.Duration): void - } - interface DB { - /** - * Stats returns database statistics. - */ - stats(): DBStats - } - interface DB { - /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's [*Stmt.Close] method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface DB { - /** - * Prepare creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's [*Stmt.Close] method - * when the statement is no longer needed. - * - * Prepare uses [context.Background] internally; to specify the context, use - * [DB.PrepareContext]. - */ - prepare(query: string): (Stmt) - } - interface DB { - /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface DB { - /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - * - * Exec uses [context.Background] internally; to specify the context, use - * [DB.ExecContext]. - */ - exec(query: string, ...args: any[]): Result - } - interface DB { - /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface DB { - /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - * - * Query uses [context.Background] internally; to specify the context, use - * [DB.QueryContext]. - */ - query(query: string, ...args: any[]): (Rows) - } - interface DB { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, [*Row.Scan] scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface DB { - /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, [*Row.Scan] scans the first selected row and discards - * the rest. - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [DB.QueryRowContext]. - */ - queryRow(query: string, ...args: any[]): (Row) - } - interface DB { - /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. [Tx.Commit] will return an error if the context provided to - * BeginTx is canceled. - * - * The provided [TxOptions] is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. - */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) - } - interface DB { - /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. - * - * Begin uses [context.Background] internally; to specify the context, use - * [DB.BeginTx]. - */ - begin(): (Tx) - } - interface DB { - /** - * Driver returns the database's underlying driver. - */ - driver(): any - } - interface DB { - /** - * Conn returns a single connection by either opening a new connection - * or returning an existing connection from the connection pool. Conn will - * block until either a connection is returned or ctx is canceled. - * Queries run on the same Conn will be run in the same database session. - * - * Every Conn must be returned to the database pool after use by - * calling [Conn.Close]. - */ - conn(ctx: context.Context): (Conn) - } - /** - * Tx is an in-progress database transaction. - * - * A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. - * - * After a call to [Tx.Commit] or [Tx.Rollback], all operations on the - * transaction fail with [ErrTxDone]. - * - * The statements prepared for a transaction by calling - * the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed - * by the call to [Tx.Commit] or [Tx.Rollback]. - */ - interface Tx { - } - interface Tx { - /** - * Commit commits the transaction. - */ - commit(): void - } - interface Tx { - /** - * Rollback aborts the transaction. - */ - rollback(): void - } - interface Tx { - /** - * PrepareContext creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see [Tx.Stmt]. - * - * The provided context will be used for the preparation of the context, not - * for the execution of the returned statement. The returned statement - * will run in the transaction context. - */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface Tx { - /** - * Prepare creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see [Tx.Stmt]. - * - * Prepare uses [context.Background] internally; to specify the context, use - * [Tx.PrepareContext]. - */ - prepare(query: string): (Stmt) - } - interface Tx { - /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) - * ``` - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) - } - interface Tx { - /** - * Stmt returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) - * ``` - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * Stmt uses [context.Background] internally; to specify the context, use - * [Tx.StmtContext]. - */ - stmt(stmt: Stmt): (Stmt) - } - interface Tx { - /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. - */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Tx { - /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. - * - * Exec uses [context.Background] internally; to specify the context, use - * [Tx.ExecContext]. - */ - exec(query: string, ...args: any[]): Result - } - interface Tx { - /** - * QueryContext executes a query that returns rows, typically a SELECT. - */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface Tx { - /** - * Query executes a query that returns rows, typically a SELECT. - * - * Query uses [context.Background] internally; to specify the context, use - * [Tx.QueryContext]. - */ - query(query: string, ...args: any[]): (Rows) - } - interface Tx { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - 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.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [Tx.QueryRowContext]. - */ - queryRow(query: string, ...args: any[]): (Row) - } - /** - * Stmt is a prepared statement. - * A Stmt is safe for concurrent use by multiple goroutines. - * - * If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single - * underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will - * become unusable and all operations will return an error. - * If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the - * [DB]. When the Stmt needs to execute on a new underlying connection, it will - * prepare itself on the new connection automatically. - */ - interface Stmt { - } - interface Stmt { - /** - * ExecContext executes a prepared statement with the given arguments and - * returns a [Result] summarizing the effect of the statement. - */ - execContext(ctx: context.Context, ...args: any[]): Result - } - interface Stmt { - /** - * Exec executes a prepared statement with the given arguments and - * returns a [Result] summarizing the effect of the statement. - * - * Exec uses [context.Background] internally; to specify the context, use - * [Stmt.ExecContext]. - */ - exec(...args: any[]): Result - } - interface Stmt { - /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a [*Rows]. - */ - queryContext(ctx: context.Context, ...args: any[]): (Rows) - } - interface Stmt { - /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. - * - * Query uses [context.Background] internally; to specify the context, use - * [Stmt.QueryContext]. - */ - query(...args: any[]): (Rows) - } - interface Stmt { - /** - * QueryRowContext executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned [*Row], which is always non-nil. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row) - } - interface Stmt { - /** - * QueryRow executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned [*Row], which is always non-nil. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. - * - * Example usage: - * - * ``` - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) - * ``` - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [Stmt.QueryRowContext]. - */ - queryRow(...args: any[]): (Row) - } - interface Stmt { - /** - * Close closes the statement. - */ - close(): void - } - /** - * Rows is the result of a query. Its cursor starts before the first row - * of the result set. Use [Rows.Next] to advance from row to row. - */ - interface Rows { - } - interface Rows { - /** - * Next prepares the next result row for reading with the [Rows.Scan] method. It - * returns true on success, or false if there is no next result row or an error - * happened while preparing it. [Rows.Err] should be consulted to distinguish between - * the two cases. - * - * Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. - */ - next(): boolean - } - interface Rows { - /** - * NextResultSet prepares the next result set for reading. It reports whether - * there is further result sets, or false if there is no further result set - * or if there is an error advancing to it. The [Rows.Err] method should be consulted - * to distinguish between the two cases. - * - * After calling NextResultSet, the [Rows.Next] method should always be called before - * scanning. If there are further result sets they may not have rows in the result - * set. - */ - nextResultSet(): boolean - } - interface Rows { - /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit [Rows.Close]. - */ - err(): void - } - interface Rows { - /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. - */ - columns(): Array - } - interface Rows { - /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. - */ - columnTypes(): Array<(ColumnType | undefined)> - } - interface Rows { - /** - * Scan copies the columns in the current row into the values pointed - * at by dest. The number of values in dest must be the same as the - * number of columns in [Rows]. - * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: - * - * ``` - * *string - * *[]byte - * *int, *int8, *int16, *int32, *int64 - * *uint, *uint8, *uint16, *uint32, *uint64 - * *bool - * *float32, *float64 - * *interface{} - * *RawBytes - * *Rows (cursor value) - * any type implementing Scanner (see Scanner docs) - * ``` - * - * In the most simple case, if the type of the value from the source - * column is an integer, bool or string type T and dest is of type *T, - * Scan simply assigns the value through the pointer. - * - * Scan also converts between string and numeric types, as long as no - * information would be lost. While Scan stringifies all numbers - * scanned from numeric database columns into *string, scans into - * numeric types are checked for overflow. For example, a float64 with - * value 300 or a string with value "300" can scan into a uint16, but - * not into a uint8, though float64(255) or "255" can scan into a - * uint8. One exception is that scans of some float64 numbers to - * strings may lose information when stringifying. In general, scan - * floating point columns into *float64. - * - * If a dest argument has type *[]byte, Scan saves in that argument a - * copy of the corresponding data. The copy is owned by the caller and - * can be modified and held indefinitely. The copy can be avoided by - * using an argument of type [*RawBytes] instead; see the documentation - * for [RawBytes] for restrictions on its use. - * - * If an argument has type *interface{}, Scan copies the value - * provided by the underlying driver without conversion. When scanning - * from a source value of type []byte to *interface{}, a copy of the - * slice is made and the caller owns the result. - * - * Source values of type [time.Time] may be scanned into values of type - * *time.Time, *interface{}, *string, or *[]byte. When converting to - * the latter two, [time.RFC3339Nano] is used. - * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or [*RawBytes]. - * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by [strconv.ParseBool]. - * - * Scan can also convert a cursor returned from a query, such as - * "select cursor(select * from my_table) from dual", into a - * [*Rows] value that can itself be scanned from. The parent - * select query will close any cursor [*Rows] if the parent [*Rows] is closed. - * - * If any of the first arguments implementing [Scanner] returns an error, - * that error will be wrapped in the returned error. - */ - scan(...dest: any[]): void - } - interface Rows { - /** - * Close closes the [Rows], preventing further enumeration. If [Rows.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 [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err]. - */ - close(): void - } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - [key:string]: any; - /** - * LastInsertId returns the integer generated by the database - * in response to a command. Typically this will be from an - * "auto increment" column when inserting a new row. Not all - * databases support this feature, and the syntax of such - * statements varies. - */ - lastInsertId(): number - /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. - */ - rowsAffected(): number + hasStarted(): boolean } } /** - * Package syntax parses regular expressions into parse trees and compiles - * parse trees into programs. Most clients of regular expressions will use the - * facilities of package [regexp] (such as [regexp.Compile] and [regexp.Match]) instead of this package. - * - * # Syntax - * - * The regular expression syntax understood by this package when parsing with the [Perl] flag is as follows. - * Parts of the syntax can be disabled by passing alternate flags to [Parse]. - * - * Single characters: - * - * ``` - * . any character, possibly including newline (flag s=true) - * [xyz] character class - * [^xyz] negated character class - * \d Perl character class - * \D negated Perl character class - * [[:alpha:]] ASCII character class - * [[:^alpha:]] negated ASCII character class - * \pN Unicode character class (one-letter name) - * \p{Greek} Unicode character class - * \PN negated Unicode character class (one-letter name) - * \P{Greek} negated Unicode character class - * ``` - * - * Composites: - * - * ``` - * xy x followed by y - * x|y x or y (prefer x) - * ``` - * - * Repetitions: - * - * ``` - * x* zero or more x, prefer more - * x+ one or more x, prefer more - * x? zero or one x, prefer one - * x{n,m} n or n+1 or ... or m x, prefer more - * x{n,} n or more x, prefer more - * x{n} exactly n x - * x*? zero or more x, prefer fewer - * x+? one or more x, prefer fewer - * x?? zero or one x, prefer zero - * x{n,m}? n or n+1 or ... or m x, prefer fewer - * x{n,}? n or more x, prefer fewer - * x{n}? exactly n x - * ``` - * - * Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} - * reject forms that create a minimum or maximum repetition count above 1000. - * Unlimited repetitions are not subject to this restriction. - * - * Grouping: - * - * ``` - * (re) numbered capturing group (submatch) - * (?Pre) named & numbered capturing group (submatch) - * (?re) named & numbered capturing group (submatch) - * (?:re) non-capturing group - * (?flags) set flags within current group; non-capturing - * (?flags:re) set flags during re; non-capturing - * - * Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are: - * - * i case-insensitive (default false) - * m multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false) - * s let . match \n (default false) - * U ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false) - * ``` - * - * Empty strings: - * - * ``` - * ^ at beginning of text or line (flag m=true) - * $ at end of text (like \z not \Z) or line (flag m=true) - * \A at beginning of text - * \b at ASCII word boundary (\w on one side and \W, \A, or \z on the other) - * \B not at ASCII word boundary - * \z at end of text - * ``` - * - * Escape sequences: - * - * ``` - * \a bell (== \007) - * \f form feed (== \014) - * \t horizontal tab (== \011) - * \n newline (== \012) - * \r carriage return (== \015) - * \v vertical tab character (== \013) - * \* literal *, for any punctuation character * - * \123 octal character code (up to three digits) - * \x7F hex character code (exactly two digits) - * \x{10FFFF} hex character code - * \Q...\E literal text ... even if ... has punctuation - * ``` - * - * Character class elements: - * - * ``` - * x single character - * A-Z character range (inclusive) - * \d Perl character class - * [:foo:] ASCII character class foo - * \p{Foo} Unicode character class Foo - * \pF Unicode character class F (one-letter name) - * ``` - * - * Named character classes as character class elements: - * - * ``` - * [\d] digits (== \d) - * [^\d] not digits (== \D) - * [\D] not digits (== \D) - * [^\D] not not digits (== \d) - * [[:name:]] named ASCII class inside character class (== [:name:]) - * [^[:name:]] named ASCII class inside negated character class (== [:^name:]) - * [\p{Name}] named Unicode property inside character class (== \p{Name}) - * [^\p{Name}] named Unicode property inside negated character class (== \P{Name}) - * ``` - * - * Perl character classes (all ASCII-only): - * - * ``` - * \d digits (== [0-9]) - * \D not digits (== [^0-9]) - * \s whitespace (== [\t\n\f\r ]) - * \S not whitespace (== [^\t\n\f\r ]) - * \w word characters (== [0-9A-Za-z_]) - * \W not word characters (== [^0-9A-Za-z_]) - * ``` - * - * ASCII character classes: - * - * ``` - * [[:alnum:]] alphanumeric (== [0-9A-Za-z]) - * [[:alpha:]] alphabetic (== [A-Za-z]) - * [[:ascii:]] ASCII (== [\x00-\x7F]) - * [[:blank:]] blank (== [\t ]) - * [[:cntrl:]] control (== [\x00-\x1F\x7F]) - * [[:digit:]] digits (== [0-9]) - * [[:graph:]] graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]) - * [[:lower:]] lower case (== [a-z]) - * [[:print:]] printable (== [ -~] == [ [:graph:]]) - * [[:punct:]] punctuation (== [!-/:-@[-`{-~]) - * [[:space:]] whitespace (== [\t\n\v\f\r ]) - * [[:upper:]] upper case (== [A-Z]) - * [[:word:]] word characters (== [0-9A-Za-z_]) - * [[:xdigit:]] hex digit (== [0-9A-Fa-f]) - * ``` - * - * Unicode character classes are those in [unicode.Categories] and [unicode.Scripts]. + * Package bytes implements functions for the manipulation of byte slices. + * It is analogous to the facilities of the [strings] package. */ -namespace syntax { +namespace bytes { /** - * Flags control the behavior of the parser and record information about regexp context. + * 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 Flags extends Number{} + 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 [Reader.ReadAt]. + * The result is unaffected by any method calls except [Reader.Reset]. + */ + size(): number + } + interface Reader { + /** + * Read implements the [io.Reader] interface. + */ + read(b: string|Array): number + } + interface Reader { + /** + * ReadAt implements the [io.ReaderAt] interface. + */ + readAt(b: string|Array, off: number): number + } + interface Reader { + /** + * ReadByte implements the [io.ByteReader] interface. + */ + readByte(): number + } + interface Reader { + /** + * UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. + */ + unreadByte(): void + } + interface Reader { + /** + * ReadRune implements the [io.RuneReader] interface. + */ + readRune(): [number, number] + } + interface Reader { + /** + * UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. + */ + unreadRune(): void + } + interface Reader { + /** + * Seek implements the [io.Seeker] interface. + */ + seek(offset: number, whence: number): number + } + interface Reader { + /** + * WriteTo implements the [io.WriterTo] interface. + */ + writeTo(w: io.Writer): number + } + interface Reader { + /** + * Reset resets the [Reader] to be reading from b. + */ + reset(b: string|Array): void + } } -namespace store { +/** + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { /** - * Store defines a concurrent safe in memory key-value data store. + * ReadWriter stores pointers to a [Reader] and a [Writer]. + * It implements [io.ReadWriter]. */ - interface Store { - } - interface Store { - /** - * Reset clears the store and replaces the store data with a - * shallow copy of the provided newData. - */ - reset(newData: _TygojaDict): void - } - interface Store { - /** - * Length returns the current number of elements in the store. - */ - length(): number - } - interface Store { - /** - * RemoveAll removes all the existing store entries. - */ - removeAll(): void - } - interface Store { - /** - * Remove removes a single entry from the store. - * - * Remove does nothing if key doesn't exist in the store. - */ - remove(key: string): void - } - interface Store { - /** - * Has checks if element with the specified key exist or not. - */ - has(key: string): boolean - } - interface Store { - /** - * Get returns a single element value from the store. - * - * If key is not set, the zero T value is returned. - */ - get(key: string): T - } - interface Store { - /** - * GetOk is similar to Get but returns also a boolean indicating whether the key exists or not. - */ - getOk(key: string): [T, boolean] - } - interface Store { - /** - * GetAll returns a shallow copy of the current store data. - */ - getAll(): _TygojaDict - } - interface Store { - /** - * Values returns a slice with all of the current store values. - */ - values(): Array - } - interface Store { - /** - * Set sets (or overwrite if already exist) a new value for key. - */ - set(key: string, value: T): void - } - interface Store { - /** - * GetOrSet retrieves a single existing value for the provided key - * or stores a new one if it doesn't exist. - */ - getOrSet(key: string, setFunc: () => T): T - } - interface Store { - /** - * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. - * - * This method is similar to Set() but **it will skip adding new elements** - * to the store if the store length has reached the specified limit. - * false is returned if maxAllowedElements limit is reached. - */ - setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean - } - interface Store { - /** - * UnmarshalJSON implements [json.Unmarshaler] and imports the - * provided JSON data into the store. - * - * The store entries that match with the ones from the data will be overwritten with the new value. - */ - unmarshalJSON(data: string|Array): void - } - interface Store { - /** - * MarshalJSON implements [json.Marshaler] and export the current - * store data into valid JSON. - */ - marshalJSON(): string|Array + type _subLJGXi = Reader&Writer + interface ReadWriter extends _subLJGXi { } } @@ -16020,195 +15245,165 @@ namespace net { } /** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * Package syntax parses regular expressions into parse trees and compiles + * parse trees into programs. Most clients of regular expressions will use the + * facilities of package [regexp] (such as [regexp.Compile] and [regexp.Match]) instead of this package. * - * See README.md for more info. + * # Syntax + * + * The regular expression syntax understood by this package when parsing with the [Perl] flag is as follows. + * Parts of the syntax can be disabled by passing alternate flags to [Parse]. + * + * Single characters: + * + * ``` + * . any character, possibly including newline (flag s=true) + * [xyz] character class + * [^xyz] negated character class + * \d Perl character class + * \D negated Perl character class + * [[:alpha:]] ASCII character class + * [[:^alpha:]] negated ASCII character class + * \pN Unicode character class (one-letter name) + * \p{Greek} Unicode character class + * \PN negated Unicode character class (one-letter name) + * \P{Greek} negated Unicode character class + * ``` + * + * Composites: + * + * ``` + * xy x followed by y + * x|y x or y (prefer x) + * ``` + * + * Repetitions: + * + * ``` + * x* zero or more x, prefer more + * x+ one or more x, prefer more + * x? zero or one x, prefer one + * x{n,m} n or n+1 or ... or m x, prefer more + * x{n,} n or more x, prefer more + * x{n} exactly n x + * x*? zero or more x, prefer fewer + * x+? one or more x, prefer fewer + * x?? zero or one x, prefer zero + * x{n,m}? n or n+1 or ... or m x, prefer fewer + * x{n,}? n or more x, prefer fewer + * x{n}? exactly n x + * ``` + * + * Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} + * reject forms that create a minimum or maximum repetition count above 1000. + * Unlimited repetitions are not subject to this restriction. + * + * Grouping: + * + * ``` + * (re) numbered capturing group (submatch) + * (?Pre) named & numbered capturing group (submatch) + * (?re) named & numbered capturing group (submatch) + * (?:re) non-capturing group + * (?flags) set flags within current group; non-capturing + * (?flags:re) set flags during re; non-capturing + * + * Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are: + * + * i case-insensitive (default false) + * m multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false) + * s let . match \n (default false) + * U ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false) + * ``` + * + * Empty strings: + * + * ``` + * ^ at beginning of text or line (flag m=true) + * $ at end of text (like \z not \Z) or line (flag m=true) + * \A at beginning of text + * \b at ASCII word boundary (\w on one side and \W, \A, or \z on the other) + * \B not at ASCII word boundary + * \z at end of text + * ``` + * + * Escape sequences: + * + * ``` + * \a bell (== \007) + * \f form feed (== \014) + * \t horizontal tab (== \011) + * \n newline (== \012) + * \r carriage return (== \015) + * \v vertical tab character (== \013) + * \* literal *, for any punctuation character * + * \123 octal character code (up to three digits) + * \x7F hex character code (exactly two digits) + * \x{10FFFF} hex character code + * \Q...\E literal text ... even if ... has punctuation + * ``` + * + * Character class elements: + * + * ``` + * x single character + * A-Z character range (inclusive) + * \d Perl character class + * [:foo:] ASCII character class foo + * \p{Foo} Unicode character class Foo + * \pF Unicode character class F (one-letter name) + * ``` + * + * Named character classes as character class elements: + * + * ``` + * [\d] digits (== \d) + * [^\d] not digits (== \D) + * [\D] not digits (== \D) + * [^\D] not not digits (== \d) + * [[:name:]] named ASCII class inside character class (== [:name:]) + * [^[:name:]] named ASCII class inside negated character class (== [:^name:]) + * [\p{Name}] named Unicode property inside character class (== \p{Name}) + * [^\p{Name}] named Unicode property inside negated character class (== \P{Name}) + * ``` + * + * Perl character classes (all ASCII-only): + * + * ``` + * \d digits (== [0-9]) + * \D not digits (== [^0-9]) + * \s whitespace (== [\t\n\f\r ]) + * \S not whitespace (== [^\t\n\f\r ]) + * \w word characters (== [0-9A-Za-z_]) + * \W not word characters (== [^0-9A-Za-z_]) + * ``` + * + * ASCII character classes: + * + * ``` + * [[:alnum:]] alphanumeric (== [0-9A-Za-z]) + * [[:alpha:]] alphabetic (== [A-Za-z]) + * [[:ascii:]] ASCII (== [\x00-\x7F]) + * [[:blank:]] blank (== [\t ]) + * [[:cntrl:]] control (== [\x00-\x1F\x7F]) + * [[:digit:]] digits (== [0-9]) + * [[:graph:]] graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]) + * [[:lower:]] lower case (== [a-z]) + * [[:print:]] printable (== [ -~] == [ [:graph:]]) + * [[:punct:]] punctuation (== [!-/:-@[-`{-~]) + * [[:space:]] whitespace (== [\t\n\v\f\r ]) + * [[:upper:]] upper case (== [A-Z]) + * [[:word:]] word characters (== [0-9A-Za-z_]) + * [[:xdigit:]] hex digit (== [0-9A-Fa-f]) + * ``` + * + * Unicode character classes are those in [unicode.Categories] and [unicode.Scripts]. */ -namespace jwt { +namespace syntax { /** - * 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 + * Flags control the behavior of the parser and record information about regexp context. */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { - /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyAudience(cmp: string, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. - */ - verifyExpiresAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. - */ - verifyIssuedAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. - */ - verifyNotBefore(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyIssuer(cmp: string, req: boolean): boolean - } - interface MapClaims { - /** - * Valid validates time based claims "exp, iat, nbf". - * There is no accounting for clock skew. - * As well, if any of the above claims are not in the token, it will still - * be considered a valid claim. - */ - valid(): void - } -} - -namespace 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 { - /** - * ChunkedClients splits the current clients into a chunked slice. - */ - chunkedClients(chunkSize: number): Array> - } - 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 - } - /** - * Message defines a client's channel data. - */ - interface Message { - name: string - data: string|Array - } - /** - * Client is an interface for a generic subscription client. - */ - interface Client { - [key:string]: any; - /** - * Id Returns the unique id of the client. - */ - id(): string - /** - * Channel returns the client's communication channel. - */ - channel(): undefined - /** - * Subscriptions returns a shallow copy of the client subscriptions matching the prefixes. - * If no prefix is specified, returns all subscriptions. - */ - subscriptions(...prefixes: string[]): _TygojaDict - /** - * Subscribe subscribes the client to the provided subscriptions list. - * - * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. - * - * Example: - * - * ``` - * Subscribe( - * "subscriptionA", - * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, - * ) - * ``` - */ - subscribe(...subs: string[]): void - /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. - */ - unsubscribe(...subs: string[]): void - /** - * HasSubscription checks if the client is subscribed to `sub`. - */ - hasSubscription(sub: string): boolean - /** - * Set stores any value to the client's context. - */ - set(key: string, value: any): void - /** - * Unset removes a single value from the client's context. - */ - unset(key: string): void - /** - * Get retrieves the key value from the client's context. - */ - get(key: string): any - /** - * Discard marks the client as "discarded", meaning that it - * shouldn't be used anymore for sending new messages. - * - * It is safe to call Discard() multiple times. - */ - discard(): void - /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. - */ - isDiscarded(): boolean - /** - * Send sends the specified message to the client's channel (if not discarded). - */ - send(m: Message): void - } -} - -/** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { - /** - * ReadWriter stores pointers to a [Reader] and a [Writer]. - * It implements [io.ReadWriter]. - */ - type _subkORum = Reader&Writer - interface ReadWriter extends _subkORum { - } + interface Flags extends Number{} } /** @@ -17279,6 +16474,1116 @@ namespace cobra { } } +/** + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. + * + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. + * + * Drivers that do not support context cancellation will not return until + * after the query is completed. + * + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. + */ +namespace sql { + /** + * TxOptions holds the transaction options to be used in [DB.BeginTx]. + */ + interface TxOptions { + /** + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. + */ + isolation: IsolationLevel + readOnly: boolean + } + /** + * NullString represents a string that may be null. + * NullString implements the [Scanner] interface so + * it can be used as a scan destination: + * + * ``` + * var s NullString + * err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) + * ... + * if s.Valid { + * // use s.String + * } else { + * // NULL value + * } + * ``` + */ + interface NullString { + string: string + valid: boolean // Valid is true if String is not NULL + } + interface NullString { + /** + * Scan implements the [Scanner] interface. + */ + scan(value: any): void + } + interface NullString { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + /** + * 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 [Tx.Commit] or + * [Tx.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 [DB.SetMaxIdleConns]. + */ + interface DB { + } + interface DB { + /** + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. + */ + pingContext(ctx: context.Context): void + } + interface DB { + /** + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. + * + * Ping uses [context.Background] internally; to specify the context, use + * [DB.PingContext]. + */ + ping(): void + } + interface DB { + /** + * Close closes the database and prevents new queries from starting. + * Close then waits for all queries that have started processing on the server + * to finish. + * + * It is rare to Close a [DB], as the [DB] handle is meant to be + * long-lived and shared between many goroutines. + */ + close(): void + } + interface DB { + /** + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. + * + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * + * If n <= 0, no idle connections are retained. + * + * The default max idle connections is currently 2. This may change in + * a future release. + */ + setMaxIdleConns(n: number): void + } + interface DB { + /** + * SetMaxOpenConns sets the maximum number of open connections to the database. + * + * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than + * MaxIdleConns, then MaxIdleConns will be reduced to match the new + * MaxOpenConns limit. + * + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). + */ + setMaxOpenConns(n: number): void + } + interface DB { + /** + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. + * + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's age. + */ + setConnMaxLifetime(d: time.Duration): void + } + interface DB { + /** + * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. + * + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's idle time. + */ + setConnMaxIdleTime(d: time.Duration): void + } + interface DB { + /** + * Stats returns database statistics. + */ + stats(): DBStats + } + interface DB { + /** + * PrepareContext creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + */ + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface DB { + /** + * Prepare creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. + * + * Prepare uses [context.Background] internally; to specify the context, use + * [DB.PrepareContext]. + */ + prepare(query: string): (Stmt) + } + interface DB { + /** + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + */ + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface DB { + /** + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. + * + * Exec uses [context.Background] internally; to specify the context, use + * [DB.ExecContext]. + */ + exec(query: string, ...args: any[]): Result + } + interface DB { + /** + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. + */ + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface DB { + /** + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. + * + * Query uses [context.Background] internally; to specify the context, use + * [DB.QueryContext]. + */ + query(query: string, ...args: any[]): (Rows) + } + interface DB { + /** + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface DB { + /** + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [DB.QueryRowContext]. + */ + queryRow(query: string, ...args: any[]): (Row) + } + interface DB { + /** + * BeginTx starts a transaction. + * + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. [Tx.Commit] will return an error if the context provided to + * BeginTx is canceled. + * + * The provided [TxOptions] is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. + */ + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface DB { + /** + * Begin starts a transaction. The default isolation level is dependent on + * the driver. + * + * Begin uses [context.Background] internally; to specify the context, use + * [DB.BeginTx]. + */ + begin(): (Tx) + } + interface DB { + /** + * Driver returns the database's underlying driver. + */ + driver(): any + } + interface DB { + /** + * Conn returns a single connection by either opening a new connection + * or returning an existing connection from the connection pool. Conn will + * block until either a connection is returned or ctx is canceled. + * Queries run on the same Conn will be run in the same database session. + * + * Every Conn must be returned to the database pool after use by + * calling [Conn.Close]. + */ + conn(ctx: context.Context): (Conn) + } + /** + * Tx is an in-progress database transaction. + * + * A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. + * + * After a call to [Tx.Commit] or [Tx.Rollback], all operations on the + * transaction fail with [ErrTxDone]. + * + * The statements prepared for a transaction by calling + * the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed + * by the call to [Tx.Commit] or [Tx.Rollback]. + */ + interface Tx { + } + interface Tx { + /** + * Commit commits the transaction. + */ + commit(): void + } + interface Tx { + /** + * Rollback aborts the transaction. + */ + rollback(): void + } + interface Tx { + /** + * PrepareContext creates a prepared statement for use within a transaction. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. + * + * The provided context will be used for the preparation of the context, not + * for the execution of the returned statement. The returned statement + * will run in the transaction context. + */ + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface Tx { + /** + * Prepare creates a prepared statement for use within a transaction. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. + * + * Prepare uses [context.Background] internally; to specify the context, use + * [Tx.PrepareContext]. + */ + prepare(query: string): (Stmt) + } + interface Tx { + /** + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. + * + * Example: + * + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) + * ``` + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + */ + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) + } + interface Tx { + /** + * Stmt returns a transaction-specific prepared statement from + * an existing statement. + * + * Example: + * + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) + * ``` + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * Stmt uses [context.Background] internally; to specify the context, use + * [Tx.StmtContext]. + */ + stmt(stmt: Stmt): (Stmt) + } + interface Tx { + /** + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. + */ + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Tx { + /** + * Exec executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. + * + * Exec uses [context.Background] internally; to specify the context, use + * [Tx.ExecContext]. + */ + exec(query: string, ...args: any[]): Result + } + interface Tx { + /** + * QueryContext executes a query that returns rows, typically a SELECT. + */ + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface Tx { + /** + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses [context.Background] internally; to specify the context, use + * [Tx.QueryContext]. + */ + query(query: string, ...args: any[]): (Rows) + } + interface Tx { + /** + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + 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.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [Tx.QueryRowContext]. + */ + queryRow(query: string, ...args: any[]): (Row) + } + /** + * Stmt is a prepared statement. + * A Stmt is safe for concurrent use by multiple goroutines. + * + * If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single + * underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will + * become unusable and all operations will return an error. + * If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the + * [DB]. When the Stmt needs to execute on a new underlying connection, it will + * prepare itself on the new connection automatically. + */ + interface Stmt { + } + interface Stmt { + /** + * ExecContext executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. + */ + execContext(ctx: context.Context, ...args: any[]): Result + } + interface Stmt { + /** + * Exec executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. + * + * Exec uses [context.Background] internally; to specify the context, use + * [Stmt.ExecContext]. + */ + exec(...args: any[]): Result + } + interface Stmt { + /** + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a [*Rows]. + */ + queryContext(ctx: context.Context, ...args: any[]): (Rows) + } + interface Stmt { + /** + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. + * + * Query uses [context.Background] internally; to specify the context, use + * [Stmt.QueryContext]. + */ + query(...args: any[]): (Rows) + } + interface Stmt { + /** + * QueryRowContext executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + */ + queryRowContext(ctx: context.Context, ...args: any[]): (Row) + } + interface Stmt { + /** + * QueryRow executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + * + * Example usage: + * + * ``` + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * ``` + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [Stmt.QueryRowContext]. + */ + queryRow(...args: any[]): (Row) + } + interface Stmt { + /** + * Close closes the statement. + */ + close(): void + } + /** + * Rows is the result of a query. Its cursor starts before the first row + * of the result set. Use [Rows.Next] to advance from row to row. + */ + interface Rows { + } + interface Rows { + /** + * Next prepares the next result row for reading with the [Rows.Scan] method. It + * returns true on success, or false if there is no next result row or an error + * happened while preparing it. [Rows.Err] should be consulted to distinguish between + * the two cases. + * + * Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. + */ + next(): boolean + } + interface Rows { + /** + * NextResultSet prepares the next result set for reading. It reports whether + * there is further result sets, or false if there is no further result set + * or if there is an error advancing to it. The [Rows.Err] method should be consulted + * to distinguish between the two cases. + * + * After calling NextResultSet, the [Rows.Next] method should always be called before + * scanning. If there are further result sets they may not have rows in the result + * set. + */ + nextResultSet(): boolean + } + interface Rows { + /** + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit [Rows.Close]. + */ + err(): void + } + interface Rows { + /** + * Columns returns the column names. + * Columns returns an error if the rows are closed. + */ + columns(): Array + } + interface Rows { + /** + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. + */ + columnTypes(): Array<(ColumnType | undefined)> + } + interface Rows { + /** + * Scan copies the columns in the current row into the values pointed + * at by dest. The number of values in dest must be the same as the + * number of columns in [Rows]. + * + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: + * + * ``` + * *string + * *[]byte + * *int, *int8, *int16, *int32, *int64 + * *uint, *uint8, *uint16, *uint32, *uint64 + * *bool + * *float32, *float64 + * *interface{} + * *RawBytes + * *Rows (cursor value) + * any type implementing Scanner (see Scanner docs) + * ``` + * + * In the most simple case, if the type of the value from the source + * column is an integer, bool or string type T and dest is of type *T, + * Scan simply assigns the value through the pointer. + * + * Scan also converts between string and numeric types, as long as no + * information would be lost. While Scan stringifies all numbers + * scanned from numeric database columns into *string, scans into + * numeric types are checked for overflow. For example, a float64 with + * value 300 or a string with value "300" can scan into a uint16, but + * not into a uint8, though float64(255) or "255" can scan into a + * uint8. One exception is that scans of some float64 numbers to + * strings may lose information when stringifying. In general, scan + * floating point columns into *float64. + * + * If a dest argument has type *[]byte, Scan saves in that argument a + * copy of the corresponding data. The copy is owned by the caller and + * can be modified and held indefinitely. The copy can be avoided by + * using an argument of type [*RawBytes] instead; see the documentation + * for [RawBytes] for restrictions on its use. + * + * If an argument has type *interface{}, Scan copies the value + * provided by the underlying driver without conversion. When scanning + * from a source value of type []byte to *interface{}, a copy of the + * slice is made and the caller owns the result. + * + * Source values of type [time.Time] may be scanned into values of type + * *time.Time, *interface{}, *string, or *[]byte. When converting to + * the latter two, [time.RFC3339Nano] is used. + * + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or [*RawBytes]. + * + * For scanning into *bool, the source may be true, false, 1, 0, or + * string inputs parseable by [strconv.ParseBool]. + * + * Scan can also convert a cursor returned from a query, such as + * "select cursor(select * from my_table) from dual", into a + * [*Rows] value that can itself be scanned from. The parent + * select query will close any cursor [*Rows] if the parent [*Rows] is closed. + * + * If any of the first arguments implementing [Scanner] returns an error, + * that error will be wrapped in the returned error. + */ + scan(...dest: any[]): void + } + interface Rows { + /** + * Close closes the [Rows], preventing further enumeration. If [Rows.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 [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err]. + */ + close(): void + } + /** + * A Result summarizes an executed SQL command. + */ + interface Result { + [key:string]: any; + /** + * LastInsertId returns the integer generated by the database + * in response to a command. Typically this will be from an + * "auto increment" column when inserting a new row. Not all + * databases support this feature, and the syntax of such + * statements varies. + */ + lastInsertId(): number + /** + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. + */ + rowsAffected(): number + } +} + +namespace store { + /** + * Store defines a concurrent safe in memory key-value data store. + */ + interface Store { + } + interface Store { + /** + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. + */ + reset(newData: _TygojaDict): void + } + interface Store { + /** + * Length returns the current number of elements in the store. + */ + length(): number + } + interface Store { + /** + * RemoveAll removes all the existing store entries. + */ + removeAll(): void + } + interface Store { + /** + * Remove removes a single entry from the store. + * + * Remove does nothing if key doesn't exist in the store. + */ + remove(key: string): void + } + interface Store { + /** + * Has checks if element with the specified key exist or not. + */ + has(key: string): boolean + } + interface Store { + /** + * Get returns a single element value from the store. + * + * If key is not set, the zero T value is returned. + */ + get(key: string): T + } + interface Store { + /** + * GetOk is similar to Get but returns also a boolean indicating whether the key exists or not. + */ + getOk(key: string): [T, boolean] + } + interface Store { + /** + * GetAll returns a shallow copy of the current store data. + */ + getAll(): _TygojaDict + } + interface Store { + /** + * Values returns a slice with all of the current store values. + */ + values(): Array + } + interface Store { + /** + * Set sets (or overwrite if already exist) a new value for key. + */ + set(key: string, value: T): void + } + interface Store { + /** + * GetOrSet retrieves a single existing value for the provided key + * or stores a new one if it doesn't exist. + */ + getOrSet(key: string, setFunc: () => T): T + } + interface Store { + /** + * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. + * + * This method is similar to Set() but **it will skip adding new elements** + * to the store if the store length has reached the specified limit. + * false is returned if maxAllowedElements limit is reached. + */ + setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean + } + interface Store { + /** + * UnmarshalJSON implements [json.Unmarshaler] and imports the + * provided JSON data into the store. + * + * The store entries that match with the ones from the data will be overwritten with the new value. + */ + unmarshalJSON(data: string|Array): void + } + interface Store { + /** + * MarshalJSON implements [json.Marshaler] and export the current + * store data into valid JSON. + */ + marshalJSON(): string|Array + } +} + +/** + * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * + * See README.md for more info. + */ +namespace jwt { + /** + * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. + * This is the default claims type if you don't supply one + */ + interface MapClaims extends _TygojaDict{} + interface MapClaims { + /** + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset + */ + verifyAudience(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. + */ + verifyExpiresAt(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. + */ + verifyIssuedAt(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. + */ + verifyNotBefore(cmp: number, req: boolean): boolean + } + interface MapClaims { + /** + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset + */ + verifyIssuer(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * Valid validates time based claims "exp, iat, nbf". + * There is no accounting for clock skew. + * As well, if any of the above claims are not in the token, it will still + * be considered a valid claim. + */ + valid(): void + } +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { + /** + * DateTime represents a [time.Time] instance in UTC that is wrapped + * and serialized using the app default date layout. + */ + interface DateTime { + } + interface DateTime { + /** + * Time returns the internal [time.Time] instance. + */ + time(): time.Time + } + interface DateTime { + /** + * Add returns a new DateTime based on the current DateTime + the specified duration. + */ + add(duration: time.Duration): DateTime + } + interface DateTime { + /** + * Sub returns a [time.Duration] by subtracting the specified DateTime from the current one. + * + * If the result exceeds the maximum (or minimum) value that can be stored in a [time.Duration], + * the maximum (or minimum) duration will be returned. + */ + sub(u: DateTime): time.Duration + } + interface DateTime { + /** + * AddDate returns a new DateTime based on the current one + duration. + * + * It follows the same rules as [time.AddDate]. + */ + addDate(years: number, months: number, days: number): DateTime + } + interface DateTime { + /** + * After reports whether the current DateTime instance is after u. + */ + after(u: DateTime): boolean + } + interface DateTime { + /** + * Before reports whether the current DateTime instance is before u. + */ + before(u: DateTime): boolean + } + interface DateTime { + /** + * Compare compares the current DateTime instance with u. + * If the current instance is before u, it returns -1. + * If the current instance is after u, it returns +1. + * If they're the same, it returns 0. + */ + compare(u: DateTime): number + } + interface DateTime { + /** + * Equal reports whether the current DateTime and u represent the same time instant. + * Two DateTime can be equal even if they are in different locations. + * For example, 6:00 +0200 and 4:00 UTC are Equal. + */ + equal(u: DateTime): boolean + } + interface DateTime { + /** + * Unix returns the current DateTime as a Unix time, aka. + * the number of seconds elapsed since January 1, 1970 UTC. + */ + unix(): number + } + interface DateTime { + /** + * IsZero checks whether the current DateTime instance has zero time value. + */ + isZero(): boolean + } + interface DateTime { + /** + * String serializes the current DateTime instance into a formatted + * UTC date string. + * + * The zero value is serialized to an empty string. + */ + string(): string + } + interface DateTime { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface DateTime { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string|Array): void + } + interface DateTime { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface DateTime { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. + */ + scan(value: any): void + } + /** + * 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|Array + } + interface JSONArray { + /** + * String returns the string representation of the current json array. + */ + string(): string + } + interface JSONArray { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JSONArray { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONArray[T] instance. + */ + scan(value: any): void + } + /** + * JSONMap defines a map that is safe for json and db read/write. + */ + interface JSONMap extends _TygojaDict{} + interface JSONMap { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface JSONMap { + /** + * String returns the string representation of the current json map. + */ + string(): string + } + interface JSONMap { + /** + * Get retrieves a single value from the current JSONMap[T]. + * + * 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): T + } + interface JSONMap { + /** + * Set sets a single value in the current JSONMap[T]. + * + * 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: T): void + } + interface JSONMap { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JSONMap { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONMap[T] instance. + */ + scan(value: any): void + } + /** + * JSONRaw defines a json value type that is safe for db read/write. + */ + interface JSONRaw extends Array{} + interface JSONRaw { + /** + * String returns the current JSONRaw instance as a json encoded string. + */ + string(): string + } + interface JSONRaw { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string|Array + } + interface JSONRaw { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string|Array): void + } + interface JSONRaw { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JSONRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONRaw instance. + */ + scan(value: any): void + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + items: any + page: number + perPage: number + totalItems: number + totalPages: number + } + /** + * ResolverResult defines a single FieldResolver.Resolve() successfully parsed result. + */ + interface ResolverResult { + /** + * Identifier is the plain SQL identifier/column that will be used + * in the final db expression as left or right operand. + */ + identifier: string + /** + * NoCoalesce instructs to not use COALESCE or NULL fallbacks + * when building the identifier expression. + */ + noCoalesce: boolean + /** + * Params is a map with db placeholder->value pairs that will be added + * to the query when building both resolved operands/sides in a single expression. + */ + params: dbx.Params + /** + * MultiMatchSubQuery is an optional sub query expression that will be added + * in addition to the combined ResolverResult expression during build. + */ + multiMatchSubQuery: dbx.Expression + /** + * AfterBuild is an optional function that will be called after building + * and combining the result of both resolved operands/sides in a single expression. + */ + afterBuild: (expr: dbx.Expression) => dbx.Expression + } +} + /** * Package multipart implements MIME multipart parsing, as defined in RFC * 2046. @@ -18537,6 +18842,322 @@ namespace blob { } } +namespace hook { + /** + * Event implements [Resolver] and it is intended to be used as a base + * Hook event that you can embed in your custom typed event structs. + * + * Example: + * + * ``` + * type CustomEvent struct { + * hook.Event + * + * SomeField int + * } + * ``` + */ + interface Event { + } + interface Event { + /** + * Next calls the next hook handler. + */ + next(): void + } + /** + * Handler defines a single Hook handler. + * Multiple handlers can share the same id. + * If Id is not explicitly set it will be autogenerated by Hook.Add and Hook.AddHandler. + */ + interface Handler { + /** + * Func defines the handler function to execute. + * + * Note that users need to call e.Next() in order to proceed with + * the execution of the hook chain. + */ + func: (_arg0: T) => void + /** + * Id is the unique identifier of the handler. + * + * It could be used later to remove the handler from a hook via [Hook.Remove]. + * + * If missing, an autogenerated value will be assigned when adding + * the handler to a hook. + */ + id: string + /** + * Priority allows changing the default exec priority of the handler within a hook. + * + * If 0, the handler will be executed in the same order it was registered. + */ + priority: number + } + /** + * Hook defines a generic concurrent safe structure for managing event hooks. + * + * When using custom event it must embed the base [hook.Event]. + * + * Example: + * + * ``` + * type CustomEvent struct { + * hook.Event + * SomeField int + * } + * + * h := Hook[*CustomEvent]{} + * + * h.BindFunc(func(e *CustomEvent) error { + * println(e.SomeField) + * + * return e.Next() + * }) + * + * h.Trigger(&CustomEvent{ SomeField: 123 }) + * ``` + */ + interface Hook { + } + interface Hook { + /** + * Bind registers the provided handler to the current hooks queue. + * + * If handler.Id is empty it is updated with autogenerated value. + * + * If a handler from the current hook list has Id matching handler.Id + * then the old handler is replaced with the new one. + */ + bind(handler: Handler): string + } + interface Hook { + /** + * BindFunc is similar to Bind but registers a new handler from just the provided function. + * + * The registered handler is added with a default 0 priority and the id will be autogenerated. + * + * If you want to register a handler with custom priority or id use the [Hook.Bind] method. + */ + bindFunc(fn: (e: T) => void): string + } + interface Hook { + /** + * Unbind removes a single hook handler by its id. + */ + unbind(id: string): void + } + interface Hook { + /** + * UnbindAll removes all registered handlers. + */ + unbindAll(): void + } + interface Hook { + /** + * Length returns to total number of registered hook handlers. + */ + length(): number + } + interface Hook { + /** + * Trigger executes all registered hook handlers one by one + * with the specified event as an argument. + * + * Optionally, this method allows also to register additional one off + * handler funcs that will be temporary appended to the handlers queue. + * + * NB! Each hook handler must call event.Next() in order the hook chain to proceed. + */ + trigger(event: T, ...oneOffHandlerFuncs: ((_arg0: T) => void)[]): 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 _subYJxyl = mainHook + interface TaggedHook extends _subYJxyl { + } + interface TaggedHook { + /** + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. + * + * It returns always true if the hook doens't have any tags. + */ + canTriggerOn(tagsToCheck: Array): boolean + } + interface TaggedHook { + /** + * Bind registers the provided handler to the current hooks queue. + * + * It is similar to [Hook.Bind] with the difference that the handler + * function is invoked only if the event data tags satisfy h.CanTriggerOn. + */ + bind(handler: Handler): string + } + interface TaggedHook { + /** + * BindFunc registers a new handler with the specified function. + * + * It is similar to [Hook.Bind] with the difference that the handler + * function is invoked only if the event data tags satisfy h.CanTriggerOn. + */ + bindFunc(fn: (e: T) => void): string + } +} + +namespace auth { + /** + * Provider defines a common interface for an OAuth2 client. + */ + interface Provider { + [key:string]: any; + /** + * Context 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 + /** + * PKCE indicates whether the provider can use the PKCE flow. + */ + pkce(): boolean + /** + * SetPKCE toggles the state whether the provider can use the PKCE flow or not. + */ + setPKCE(enable: boolean): void + /** + * DisplayName usually returns provider name as it is officially written + * and it could be used directly in the UI. + */ + displayName(): string + /** + * SetDisplayName sets the provider's display name. + */ + setDisplayName(displayName: string): void + /** + * Scopes returns the provider access permissions that will be requested. + */ + scopes(): Array + /** + * SetScopes sets the provider access permissions that will be requested later. + */ + setScopes(scopes: Array): void + /** + * ClientId returns the provider client's app ID. + */ + clientId(): string + /** + * SetClientId sets the provider client's ID. + */ + setClientId(clientId: string): void + /** + * ClientSecret returns the provider client's app secret. + */ + clientSecret(): string + /** + * SetClientSecret sets the provider client's app secret. + */ + setClientSecret(secret: string): void + /** + * RedirectURL returns the end address to redirect the user + * going through the OAuth flow. + */ + redirectURL(): string + /** + * SetRedirectURL sets the provider's RedirectURL. + */ + setRedirectURL(url: string): void + /** + * AuthURL returns the provider's authorization service url. + */ + authURL(): string + /** + * SetAuthURL sets the provider's AuthURL. + */ + setAuthURL(url: string): void + /** + * TokenURL returns the provider's token exchange service url. + */ + tokenURL(): string + /** + * SetTokenURL sets the provider's TokenURL. + */ + setTokenURL(url: string): void + /** + * UserInfoURL returns the provider's user info api url. + */ + userInfoURL(): string + /** + * SetUserInfoURL sets the provider's UserInfoURL. + */ + setUserInfoURL(url: string): void + /** + * Extra returns a shallow copy of any custom config data + * that the provider may be need. + */ + extra(): _TygojaDict + /** + * SetExtra updates the provider's custom config data. + */ + setExtra(data: _TygojaDict): void + /** + * Client returns an http client using the provided token. + */ + client(token: oauth2.Token): (any) + /** + * 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) + /** + * FetchRawUserInfo requests and marshalizes into `result` the + * the OAuth user api response. + */ + fetchRawUserInfo(token: oauth2.Token): string|Array + /** + * FetchAuthUser is similar to FetchRawUserInfo, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. + */ + fetchAuthUser(token: oauth2.Token): (AuthUser) + } + /** + * AuthUser defines a standardized OAuth2 user data structure. + */ + interface AuthUser { + expiry: types.DateTime + rawUser: _TygojaDict + id: string + name: string + username: string + email: string + avatarURL: string + accessToken: string + refreshToken: string + /** + * @todo + * deprecated: use AvatarURL instead + * AvatarUrl will be removed after dropping v0.22 support + */ + avatarUrl: string + } + interface AuthUser { + /** + * MarshalJSON implements the [json.Marshaler] interface. + * + * @todo remove after dropping v0.22 support + */ + marshalJSON(): string|Array + } +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -19027,386 +19648,6 @@ namespace slog { } } -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * DateTime represents a [time.Time] instance in UTC that is wrapped - * and serialized using the app default date layout. - */ - interface DateTime { - } - interface DateTime { - /** - * Time returns the internal [time.Time] instance. - */ - time(): time.Time - } - interface DateTime { - /** - * Add returns a new DateTime based on the current DateTime + the specified duration. - */ - add(duration: time.Duration): DateTime - } - interface DateTime { - /** - * Sub returns a [time.Duration] by subtracting the specified DateTime from the current one. - * - * If the result exceeds the maximum (or minimum) value that can be stored in a [time.Duration], - * the maximum (or minimum) duration will be returned. - */ - sub(u: DateTime): time.Duration - } - interface DateTime { - /** - * AddDate returns a new DateTime based on the current one + duration. - * - * It follows the same rules as [time.AddDate]. - */ - addDate(years: number, months: number, days: number): DateTime - } - interface DateTime { - /** - * After reports whether the current DateTime instance is after u. - */ - after(u: DateTime): boolean - } - interface DateTime { - /** - * Before reports whether the current DateTime instance is before u. - */ - before(u: DateTime): boolean - } - interface DateTime { - /** - * Compare compares the current DateTime instance with u. - * If the current instance is before u, it returns -1. - * If the current instance is after u, it returns +1. - * If they're the same, it returns 0. - */ - compare(u: DateTime): number - } - interface DateTime { - /** - * Equal reports whether the current DateTime and u represent the same time instant. - * Two DateTime can be equal even if they are in different locations. - * For example, 6:00 +0200 and 4:00 UTC are Equal. - */ - equal(u: DateTime): boolean - } - interface DateTime { - /** - * Unix returns the current DateTime as a Unix time, aka. - * the number of seconds elapsed since January 1, 1970 UTC. - */ - unix(): number - } - interface DateTime { - /** - * IsZero checks whether the current DateTime instance has zero time value. - */ - isZero(): boolean - } - interface DateTime { - /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. - */ - string(): string - } - interface DateTime { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface DateTime { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string|Array): void - } - interface DateTime { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface DateTime { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. - */ - scan(value: any): void - } - /** - * 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|Array - } - interface JSONArray { - /** - * String returns the string representation of the current json array. - */ - string(): string - } - interface JSONArray { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface JSONArray { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONArray[T] instance. - */ - scan(value: any): void - } - /** - * JSONMap defines a map that is safe for json and db read/write. - */ - interface JSONMap extends _TygojaDict{} - interface JSONMap { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface JSONMap { - /** - * String returns the string representation of the current json map. - */ - string(): string - } - interface JSONMap { - /** - * Get retrieves a single value from the current JSONMap[T]. - * - * 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): T - } - interface JSONMap { - /** - * Set sets a single value in the current JSONMap[T]. - * - * 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: T): void - } - interface JSONMap { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface JSONMap { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONMap[T] instance. - */ - scan(value: any): void - } - /** - * JSONRaw defines a json value type that is safe for db read/write. - */ - interface JSONRaw extends Array{} - interface JSONRaw { - /** - * String returns the current JSONRaw instance as a json encoded string. - */ - string(): string - } - interface JSONRaw { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface JSONRaw { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string|Array): void - } - interface JSONRaw { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface JSONRaw { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONRaw instance. - */ - scan(value: any): void - } -} - -namespace auth { - /** - * Provider defines a common interface for an OAuth2 client. - */ - interface Provider { - [key:string]: any; - /** - * Context 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 - /** - * PKCE indicates whether the provider can use the PKCE flow. - */ - pkce(): boolean - /** - * SetPKCE toggles the state whether the provider can use the PKCE flow or not. - */ - setPKCE(enable: boolean): void - /** - * DisplayName usually returns provider name as it is officially written - * and it could be used directly in the UI. - */ - displayName(): string - /** - * SetDisplayName sets the provider's display name. - */ - setDisplayName(displayName: string): void - /** - * Scopes returns the provider access permissions that will be requested. - */ - scopes(): Array - /** - * SetScopes sets the provider access permissions that will be requested later. - */ - setScopes(scopes: Array): void - /** - * ClientId returns the provider client's app ID. - */ - clientId(): string - /** - * SetClientId sets the provider client's ID. - */ - setClientId(clientId: string): void - /** - * ClientSecret returns the provider client's app secret. - */ - clientSecret(): string - /** - * SetClientSecret sets the provider client's app secret. - */ - setClientSecret(secret: string): void - /** - * RedirectURL returns the end address to redirect the user - * going through the OAuth flow. - */ - redirectURL(): string - /** - * SetRedirectURL sets the provider's RedirectURL. - */ - setRedirectURL(url: string): void - /** - * AuthURL returns the provider's authorization service url. - */ - authURL(): string - /** - * SetAuthURL sets the provider's AuthURL. - */ - setAuthURL(url: string): void - /** - * TokenURL returns the provider's token exchange service url. - */ - tokenURL(): string - /** - * SetTokenURL sets the provider's TokenURL. - */ - setTokenURL(url: string): void - /** - * UserInfoURL returns the provider's user info api url. - */ - userInfoURL(): string - /** - * SetUserInfoURL sets the provider's UserInfoURL. - */ - setUserInfoURL(url: string): void - /** - * Extra returns a shallow copy of any custom config data - * that the provider may be need. - */ - extra(): _TygojaDict - /** - * SetExtra updates the provider's custom config data. - */ - setExtra(data: _TygojaDict): void - /** - * Client returns an http client using the provided token. - */ - client(token: oauth2.Token): (any) - /** - * 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) - /** - * FetchRawUserInfo requests and marshalizes into `result` the - * the OAuth user api response. - */ - fetchRawUserInfo(token: oauth2.Token): string|Array - /** - * FetchAuthUser is similar to FetchRawUserInfo, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. - */ - fetchAuthUser(token: oauth2.Token): (AuthUser) - } - /** - * AuthUser defines a standardized OAuth2 user data structure. - */ - interface AuthUser { - expiry: types.DateTime - rawUser: _TygojaDict - id: string - name: string - username: string - email: string - avatarURL: string - accessToken: string - refreshToken: string - /** - * @todo - * deprecated: use AvatarURL instead - * AvatarUrl will be removed after dropping v0.22 support - */ - avatarUrl: string - } - interface AuthUser { - /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * @todo remove after dropping v0.22 support - */ - marshalJSON(): string|Array - } -} - /** * Package exec runs external commands. It wraps os.StartProcess to make it * easier to remap stdin and stdout, connect I/O with pipes, and do other @@ -19781,214 +20022,6 @@ namespace exec { } } -namespace hook { - /** - * Event implements [Resolver] and it is intended to be used as a base - * Hook event that you can embed in your custom typed event structs. - * - * Example: - * - * ``` - * type CustomEvent struct { - * hook.Event - * - * SomeField int - * } - * ``` - */ - interface Event { - } - interface Event { - /** - * Next calls the next hook handler. - */ - next(): void - } - /** - * Handler defines a single Hook handler. - * Multiple handlers can share the same id. - * If Id is not explicitly set it will be autogenerated by Hook.Add and Hook.AddHandler. - */ - interface Handler { - /** - * Func defines the handler function to execute. - * - * Note that users need to call e.Next() in order to proceed with - * the execution of the hook chain. - */ - func: (_arg0: T) => void - /** - * Id is the unique identifier of the handler. - * - * It could be used later to remove the handler from a hook via [Hook.Remove]. - * - * If missing, an autogenerated value will be assigned when adding - * the handler to a hook. - */ - id: string - /** - * Priority allows changing the default exec priority of the handler within a hook. - * - * If 0, the handler will be executed in the same order it was registered. - */ - priority: number - } - /** - * Hook defines a generic concurrent safe structure for managing event hooks. - * - * When using custom event it must embed the base [hook.Event]. - * - * Example: - * - * ``` - * type CustomEvent struct { - * hook.Event - * SomeField int - * } - * - * h := Hook[*CustomEvent]{} - * - * h.BindFunc(func(e *CustomEvent) error { - * println(e.SomeField) - * - * return e.Next() - * }) - * - * h.Trigger(&CustomEvent{ SomeField: 123 }) - * ``` - */ - interface Hook { - } - interface Hook { - /** - * Bind registers the provided handler to the current hooks queue. - * - * If handler.Id is empty it is updated with autogenerated value. - * - * If a handler from the current hook list has Id matching handler.Id - * then the old handler is replaced with the new one. - */ - bind(handler: Handler): string - } - interface Hook { - /** - * BindFunc is similar to Bind but registers a new handler from just the provided function. - * - * The registered handler is added with a default 0 priority and the id will be autogenerated. - * - * If you want to register a handler with custom priority or id use the [Hook.Bind] method. - */ - bindFunc(fn: (e: T) => void): string - } - interface Hook { - /** - * Unbind removes a single hook handler by its id. - */ - unbind(id: string): void - } - interface Hook { - /** - * UnbindAll removes all registered handlers. - */ - unbindAll(): void - } - interface Hook { - /** - * Length returns to total number of registered hook handlers. - */ - length(): number - } - interface Hook { - /** - * Trigger executes all registered hook handlers one by one - * with the specified event as an argument. - * - * Optionally, this method allows also to register additional one off - * handler funcs that will be temporary appended to the handlers queue. - * - * NB! Each hook handler must call event.Next() in order the hook chain to proceed. - */ - trigger(event: T, ...oneOffHandlerFuncs: ((_arg0: T) => void)[]): 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 _subUbkxw = mainHook - interface TaggedHook extends _subUbkxw { - } - interface TaggedHook { - /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. - * - * It returns always true if the hook doens't have any tags. - */ - canTriggerOn(tagsToCheck: Array): boolean - } - interface TaggedHook { - /** - * Bind registers the provided handler to the current hooks queue. - * - * It is similar to [Hook.Bind] with the difference that the handler - * function is invoked only if the event data tags satisfy h.CanTriggerOn. - */ - bind(handler: Handler): string - } - interface TaggedHook { - /** - * BindFunc registers a new handler with the specified function. - * - * It is similar to [Hook.Bind] with the difference that the handler - * function is invoked only if the event data tags satisfy h.CanTriggerOn. - */ - bindFunc(fn: (e: T) => void): string - } -} - -namespace search { - /** - * Result defines the returned search result structure. - */ - interface Result { - items: any - page: number - perPage: number - totalItems: number - totalPages: number - } - /** - * ResolverResult defines a single FieldResolver.Resolve() successfully parsed result. - */ - interface ResolverResult { - /** - * Identifier is the plain SQL identifier/column that will be used - * in the final db expression as left or right operand. - */ - identifier: string - /** - * NoCoalesce instructs to not use COALESCE or NULL fallbacks - * when building the identifier expression. - */ - noCoalesce: boolean - /** - * Params is a map with db placeholder->value pairs that will be added - * to the query when building both resolved operands/sides in a single expression. - */ - params: dbx.Params - /** - * MultiMatchSubQuery is an optional sub query expression that will be added - * in addition to the combined ResolverResult expression during build. - */ - multiMatchSubQuery: dbx.Expression - /** - * AfterBuild is an optional function that will be called after building - * and combining the result of both resolved operands/sides in a single expression. - */ - afterBuild: (expr: dbx.Expression) => dbx.Expression - } -} - namespace router { // @ts-ignore import validation = ozzo_validation @@ -20024,8 +20057,8 @@ namespace router { * * NB! It is expected that the Response and Request fields are always set. */ - type _subvPQQR = hook.Event - interface Event extends _subvPQQR { + type _subQvGcE = hook.Event + interface Event extends _subQvGcE { response: http.ResponseWriter request?: http.Request } @@ -20237,8 +20270,8 @@ namespace router { * http.ListenAndServe("localhost:8090", mux) * ``` */ - type _subXubLR = RouterGroup - interface Router extends _subXubLR { + type _subhamft = RouterGroup + interface Router extends _subhamft { } interface Router { /** @@ -20248,97 +20281,6 @@ namespace router { } } -/** - * Package cron implements a crontab-like service to execute and schedule - * repeative tasks/jobs. - * - * Example: - * - * ``` - * c := cron.New() - * c.MustAdd("dailyReport", "0 0 * * *", func() { ... }) - * c.Start() - * ``` - */ -namespace cron { - /** - * Cron is a crontab-like struct for tasks/jobs scheduling. - */ - interface Cron { - } - interface Cron { - /** - * SetInterval changes the current cron tick interval - * (it usually should be >= 1 minute). - */ - setInterval(d: time.Duration): void - } - interface Cron { - /** - * SetTimezone changes the current cron tick timezone. - */ - setTimezone(l: time.Location): void - } - interface Cron { - /** - * MustAdd is similar to Add() but panic on failure. - */ - mustAdd(jobId: string, cronExpr: string, run: () => void): void - } - interface Cron { - /** - * Add registers a single cron job. - * - * If there is already a job with the provided id, then the old job - * will be replaced with the new one. - * - * cronExpr is a regular cron expression, eg. "0 *\/3 * * *" (aka. at minute 0 past every 3rd hour). - * Check cron.NewSchedule() for the supported tokens. - */ - add(jobId: string, cronExpr: string, run: () => void): void - } - interface Cron { - /** - * Remove removes a single cron job by its id. - */ - remove(jobId: string): void - } - interface Cron { - /** - * RemoveAll removes all registered cron jobs. - */ - removeAll(): void - } - interface Cron { - /** - * Total returns the current total number of registered cron jobs. - */ - total(): number - } - interface Cron { - /** - * Stop stops the current cron ticker (if not already). - * - * You can resume the ticker by calling Start(). - */ - stop(): void - } - interface Cron { - /** - * Start starts the cron ticker. - * - * Calling Start() on already started cron will restart the ticker. - */ - start(): void - } - interface Cron { - /** - * HasStarted checks whether the current Cron ticker has been started. - */ - hasStarted(): boolean - } -} - namespace mailer { /** * Message defines a generic email message struct. @@ -20366,6 +20308,126 @@ namespace mailer { } } +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 { + /** + * ChunkedClients splits the current clients into a chunked slice. + */ + chunkedClients(chunkSize: number): Array> + } + 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 + } + /** + * Message defines a client's channel data. + */ + interface Message { + name: string + data: string|Array + } + /** + * Client is an interface for a generic subscription client. + */ + interface Client { + [key:string]: any; + /** + * Id Returns the unique id of the client. + */ + id(): string + /** + * Channel returns the client's communication channel. + */ + channel(): undefined + /** + * Subscriptions returns a shallow copy of the client subscriptions matching the prefixes. + * If no prefix is specified, returns all subscriptions. + */ + subscriptions(...prefixes: string[]): _TygojaDict + /** + * Subscribe subscribes the client to the provided subscriptions list. + * + * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. + * + * Example: + * + * ``` + * Subscribe( + * "subscriptionA", + * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, + * ) + * ``` + */ + subscribe(...subs: string[]): void + /** + * Unsubscribe unsubscribes the client from the provided subscriptions list. + */ + unsubscribe(...subs: string[]): void + /** + * HasSubscription checks if the client is subscribed to `sub`. + */ + hasSubscription(sub: string): boolean + /** + * Set stores any value to the client's context. + */ + set(key: string, value: any): void + /** + * Unset removes a single value from the client's context. + */ + unset(key: string): void + /** + * Get retrieves the key value from the client's context. + */ + get(key: string): any + /** + * Discard marks the client as "discarded", meaning that it + * shouldn't be used anymore for sending new messages. + * + * It is safe to call Discard() multiple times. + */ + discard(): void + /** + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. + */ + isDiscarded(): boolean + /** + * Send sends the specified message to the client's channel (if not discarded). + */ + send(m: Message): void + } +} + /** * Package sync provides basic synchronization primitives such as mutual * exclusion locks. Other than the [Once] and [WaitGroup] types, most are intended @@ -20404,808 +20466,6 @@ namespace io { } } -/** - * Package syscall contains an interface to the low-level operating system - * primitives. The details vary depending on the underlying system, and - * by default, godoc will display the syscall documentation for the current - * system. If you want godoc to display syscall documentation for another - * system, set $GOOS and $GOARCH to the desired system. For example, if - * you want to view documentation for freebsd/arm on linux/amd64, set $GOOS - * to freebsd and $GOARCH to arm. - * The primary use of syscall is inside other packages that provide a more - * portable interface to the system, such as "os", "time" and "net". Use - * those packages rather than this one if you can. - * For details of the functions and data types in this package consult - * the manuals for the appropriate operating system. - * These calls return err == nil to indicate success; otherwise - * err is an operating system error describing the failure. - * On most systems, that error has type [Errno]. - * - * NOTE: Most of the functions, types, and constants defined in - * this package are also available in the [golang.org/x/sys] package. - * That package has more system call support than this one, - * and most new code should prefer that package where possible. - * See https://golang.org/s/go1.4-syscall for more information. - */ -namespace syscall { - /** - * SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. - * See user_namespaces(7). - * - * Note that User Namespaces are not available on a number of popular Linux - * versions (due to security issues), or are available but subject to AppArmor - * restrictions like in Ubuntu 24.04. - */ - interface SysProcIDMap { - containerID: number // Container ID. - hostID: number // Host ID. - size: number // Size. - } - // @ts-ignore - import errorspkg = errors - /** - * Credential holds user and group identities to be assumed - * by a child process started by [StartProcess]. - */ - interface Credential { - uid: number // User ID. - gid: number // Group ID. - groups: Array // Supplementary group IDs. - noSetGroups: boolean // If true, don't set supplementary groups - } - // @ts-ignore - import runtimesyscall = syscall - /** - * A Signal is a number describing a process signal. - * It implements the [os.Signal] interface. - */ - interface Signal extends Number{} - interface Signal { - signal(): void - } - interface Signal { - 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), t.Compare(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. The same applies to other functions and - * methods that subtract times, such as [Since], [Until], [Before], [After], - * [Add], [Sub], [Equal] and [Compare]. In some cases, you may need to strip - * the monotonic clock to get accurate results. - * - * Because the monotonic clock reading has no meaning outside - * the current process, the serialized forms generated by t.GobEncode, - * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic - * clock reading, and t.Format provides no format for it. Similarly, the - * constructors [time.Date], [time.Parse], [time.ParseInLocation], and [time.Unix], - * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. - * t.UnmarshalJSON, and t.UnmarshalText always create times with - * no monotonic clock reading. - * - * The monotonic clock reading exists only in [Time] values. It is not - * a part of [Duration] values or the Unix times returned by t.Unix and - * friends. - * - * Note that the Go == operator compares not just the time instant but - * also the [Location] and the monotonic clock reading. See the - * documentation for the Time type for a discussion of equality - * testing for Time values. - * - * For debugging, the result of t.String does include the monotonic - * clock reading if present. If t != u because of different monotonic clock readings, - * that difference will be visible when printing t.String() and u.String(). - * - * # Timer Resolution - * - * [Timer] resolution varies depending on the Go runtime, the operating system - * and the underlying hardware. - * On Unix, the resolution is ~1ms. - * On Windows version 1803 and newer, the resolution is ~0.5ms. - * On older Windows versions, the default resolution is ~16ms, but - * a higher resolution may be requested using [golang.org/x/sys/windows.TimeBeginPeriod]. - */ -namespace time { - /** - * A Month specifies a month of the year (January = 1, ...). - */ - interface Month extends Number{} - interface Month { - /** - * String returns the English name of the month ("January", "February", ...). - */ - string(): string - } - /** - * A Weekday specifies a day of the week (Sunday = 0, ...). - */ - interface Weekday extends Number{} - interface Weekday { - /** - * String returns the English name of the day ("Sunday", "Monday", ...). - */ - string(): string - } - /** - * A Location maps time instants to the zone in use at that time. - * Typically, the Location represents the collection of time offsets - * in use in a geographical area. For many Locations the time offset varies - * depending on whether daylight savings time is in use at the time instant. - * - * Location is used to provide a time zone in a printed Time value and for - * calculations involving intervals that may cross daylight savings time - * boundaries. - */ - interface Location { - } - interface Location { - /** - * String returns a descriptive name for the time zone information, - * corresponding to the name argument to [LoadLocation] or [FixedZone]. - */ - string(): string - } -} - -/** - * Package context defines the Context type, which carries deadlines, - * cancellation signals, and other request-scoped values across API boundaries - * and between processes. - * - * Incoming requests to a server should create a [Context], and outgoing - * calls to servers should accept a Context. The chain of function - * calls between them must propagate the Context, optionally replacing - * it with a derived Context created using [WithCancel], [WithDeadline], - * [WithTimeout], or [WithValue]. When a Context is canceled, all - * Contexts derived from it are also canceled. - * - * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a - * Context (the parent) and return a derived Context (the child) and a - * [CancelFunc]. Calling the CancelFunc cancels the child and its - * children, removes the parent's reference to the child, and stops - * any associated timers. Failing to call the CancelFunc leaks the - * child and its children until the parent is canceled or the timer - * fires. The go vet tool checks that CancelFuncs are used on all - * control-flow paths. - * - * The [WithCancelCause] function returns a [CancelCauseFunc], which - * takes an error and records it as the cancellation cause. Calling - * [Cause] on the canceled context or any of its children retrieves - * the cause. If no cause is specified, Cause(ctx) returns the same - * value as ctx.Err(). - * - * Programs that use Contexts should follow these rules to keep interfaces - * consistent across packages and enable static analysis tools to check context - * propagation: - * - * Do not store Contexts inside a struct type; instead, pass a Context - * explicitly to each function that needs it. The Context should be the first - * parameter, typically named ctx: - * - * ``` - * func DoSomething(ctx context.Context, arg Arg) error { - * // ... use ctx ... - * } - * ``` - * - * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] - * if you are unsure about which Context to use. - * - * Use context Values only for request-scoped data that transits processes and - * APIs, not for passing optional parameters to functions. - * - * The same Context may be passed to functions running in different goroutines; - * Contexts are safe for simultaneous use by multiple goroutines. - * - * See https://blog.golang.org/context for example code for a server that uses - * Contexts. - */ -namespace context { -} - -/** - * 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. - * - * See the [testing/fstest] package for support with testing - * implementations of file systems. - */ -namespace fs { -} - -/** - * Package slog provides structured logging, - * in which log records include a message, - * a severity level, and various other attributes - * expressed as key-value pairs. - * - * It defines a type, [Logger], - * which provides several methods (such as [Logger.Info] and [Logger.Error]) - * for reporting events of interest. - * - * Each Logger is associated with a [Handler]. - * A Logger output method creates a [Record] from the method arguments - * and passes it to the Handler, which decides how to handle it. - * There is a default Logger accessible through top-level functions - * (such as [Info] and [Error]) that call the corresponding Logger methods. - * - * A log record consists of a time, a level, a message, and a set of key-value - * pairs, where the keys are strings and the values may be of any type. - * As an example, - * - * ``` - * slog.Info("hello", "count", 3) - * ``` - * - * creates a record containing the time of the call, - * a level of Info, the message "hello", and a single - * pair with key "count" and value 3. - * - * The [Info] top-level function calls the [Logger.Info] method on the default Logger. - * In addition to [Logger.Info], there are methods for Debug, Warn and Error levels. - * Besides these convenience methods for common levels, - * there is also a [Logger.Log] method which takes the level as an argument. - * Each of these methods has a corresponding top-level function that uses the - * default logger. - * - * The default handler formats the log record's message, time, level, and attributes - * as a string and passes it to the [log] package. - * - * ``` - * 2022/11/08 15:28:26 INFO hello count=3 - * ``` - * - * For more control over the output format, create a logger with a different handler. - * This statement uses [New] to create a new logger with a [TextHandler] - * that writes structured records in text form to standard error: - * - * ``` - * logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) - * ``` - * - * [TextHandler] output is a sequence of key=value pairs, easily and unambiguously - * parsed by machine. This statement: - * - * ``` - * logger.Info("hello", "count", 3) - * ``` - * - * produces this output: - * - * ``` - * time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3 - * ``` - * - * The package also provides [JSONHandler], whose output is line-delimited JSON: - * - * ``` - * logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - * logger.Info("hello", "count", 3) - * ``` - * - * produces this output: - * - * ``` - * {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3} - * ``` - * - * Both [TextHandler] and [JSONHandler] can be configured with [HandlerOptions]. - * There are options for setting the minimum level (see Levels, below), - * displaying the source file and line of the log call, and - * modifying attributes before they are logged. - * - * Setting a logger as the default with - * - * ``` - * slog.SetDefault(logger) - * ``` - * - * will cause the top-level functions like [Info] to use it. - * [SetDefault] also updates the default logger used by the [log] package, - * so that existing applications that use [log.Printf] and related functions - * will send log records to the logger's handler without needing to be rewritten. - * - * Some attributes are common to many log calls. - * For example, you may wish to include the URL or trace identifier of a server request - * with all log events arising from the request. - * Rather than repeat the attribute with every log call, you can use [Logger.With] - * to construct a new Logger containing the attributes: - * - * ``` - * logger2 := logger.With("url", r.URL) - * ``` - * - * The arguments to With are the same key-value pairs used in [Logger.Info]. - * The result is a new Logger with the same handler as the original, but additional - * attributes that will appear in the output of every call. - * - * # Levels - * - * A [Level] is an integer representing the importance or severity of a log event. - * The higher the level, the more severe the event. - * This package defines constants for the most common levels, - * but any int can be used as a level. - * - * In an application, you may wish to log messages only at a certain level or greater. - * One common configuration is to log messages at Info or higher levels, - * suppressing debug logging until it is needed. - * The built-in handlers can be configured with the minimum level to output by - * setting [HandlerOptions.Level]. - * The program's `main` function typically does this. - * The default value is LevelInfo. - * - * Setting the [HandlerOptions.Level] field to a [Level] value - * fixes the handler's minimum level throughout its lifetime. - * Setting it to a [LevelVar] allows the level to be varied dynamically. - * A LevelVar holds a Level and is safe to read or write from multiple - * goroutines. - * To vary the level dynamically for an entire program, first initialize - * a global LevelVar: - * - * ``` - * var programLevel = new(slog.LevelVar) // Info by default - * ``` - * - * Then use the LevelVar to construct a handler, and make it the default: - * - * ``` - * h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}) - * slog.SetDefault(slog.New(h)) - * ``` - * - * Now the program can change its logging level with a single statement: - * - * ``` - * programLevel.Set(slog.LevelDebug) - * ``` - * - * # Groups - * - * Attributes can be collected into groups. - * A group has a name that is used to qualify the names of its attributes. - * How this qualification is displayed depends on the handler. - * [TextHandler] separates the group and attribute names with a dot. - * [JSONHandler] treats each group as a separate JSON object, with the group name as the key. - * - * Use [Group] to create a Group attribute from a name and a list of key-value pairs: - * - * ``` - * slog.Group("request", - * "method", r.Method, - * "url", r.URL) - * ``` - * - * TextHandler would display this group as - * - * ``` - * request.method=GET request.url=http://example.com - * ``` - * - * JSONHandler would display it as - * - * ``` - * "request":{"method":"GET","url":"http://example.com"} - * ``` - * - * Use [Logger.WithGroup] to qualify all of a Logger's output - * with a group name. Calling WithGroup on a Logger results in a - * new Logger with the same Handler as the original, but with all - * its attributes qualified by the group name. - * - * This can help prevent duplicate attribute keys in large systems, - * where subsystems might use the same keys. - * Pass each subsystem a different Logger with its own group name so that - * potential duplicates are qualified: - * - * ``` - * logger := slog.Default().With("id", systemID) - * parserLogger := logger.WithGroup("parser") - * parseInput(input, parserLogger) - * ``` - * - * When parseInput logs with parserLogger, its keys will be qualified with "parser", - * so even if it uses the common key "id", the log line will have distinct keys. - * - * # Contexts - * - * Some handlers may wish to include information from the [context.Context] that is - * available at the call site. One example of such information - * is the identifier for the current span when tracing is enabled. - * - * The [Logger.Log] and [Logger.LogAttrs] methods take a context as a first - * argument, as do their corresponding top-level functions. - * - * Although the convenience methods on Logger (Info and so on) and the - * corresponding top-level functions do not take a context, the alternatives ending - * in "Context" do. For example, - * - * ``` - * slog.InfoContext(ctx, "message") - * ``` - * - * It is recommended to pass a context to an output method if one is available. - * - * # Attrs and Values - * - * An [Attr] is a key-value pair. The Logger output methods accept Attrs as well as - * alternating keys and values. The statement - * - * ``` - * slog.Info("hello", slog.Int("count", 3)) - * ``` - * - * behaves the same as - * - * ``` - * slog.Info("hello", "count", 3) - * ``` - * - * There are convenience constructors for [Attr] such as [Int], [String], and [Bool] - * for common types, as well as the function [Any] for constructing Attrs of any - * type. - * - * The value part of an Attr is a type called [Value]. - * Like an [any], a Value can hold any Go value, - * but it can represent typical values, including all numbers and strings, - * without an allocation. - * - * For the most efficient log output, use [Logger.LogAttrs]. - * It is similar to [Logger.Log] but accepts only Attrs, not alternating - * keys and values; this allows it, too, to avoid allocation. - * - * The call - * - * ``` - * logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3)) - * ``` - * - * is the most efficient way to achieve the same output as - * - * ``` - * slog.InfoContext(ctx, "hello", "count", 3) - * ``` - * - * # Customizing a type's logging behavior - * - * If a type implements the [LogValuer] interface, the [Value] returned from its LogValue - * method is used for logging. You can use this to control how values of the type - * appear in logs. For example, you can redact secret information like passwords, - * or gather a struct's fields in a Group. See the examples under [LogValuer] for - * details. - * - * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] - * method handles these cases carefully, avoiding infinite loops and unbounded recursion. - * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. - * - * # Wrapping output methods - * - * The logger functions use reflection over the call stack to find the file name - * and line number of the logging call within the application. This can produce - * incorrect source information for functions that wrap slog. For instance, if you - * define this function in file mylog.go: - * - * ``` - * func Infof(logger *slog.Logger, format string, args ...any) { - * logger.Info(fmt.Sprintf(format, args...)) - * } - * ``` - * - * and you call it like this in main.go: - * - * ``` - * Infof(slog.Default(), "hello, %s", "world") - * ``` - * - * then slog will report the source file as mylog.go, not main.go. - * - * A correct implementation of Infof will obtain the source location - * (pc) and pass it to NewRecord. - * The Infof function in the package-level example called "wrapping" - * demonstrates how to do this. - * - * # Working with Records - * - * Sometimes a Handler will need to modify a Record - * before passing it on to another Handler or backend. - * A Record contains a mixture of simple public fields (e.g. Time, Level, Message) - * and hidden fields that refer to state (such as attributes) indirectly. This - * means that modifying a simple copy of a Record (e.g. by calling - * [Record.Add] or [Record.AddAttrs] to add attributes) - * may have unexpected effects on the original. - * Before modifying a Record, use [Record.Clone] to - * create a copy that shares no state with the original, - * or create a new Record with [NewRecord] - * and build up its Attrs by traversing the old ones with [Record.Attrs]. - * - * # Performance considerations - * - * If profiling your application demonstrates that logging is taking significant time, - * the following suggestions may help. - * - * If many log lines have a common attribute, use [Logger.With] to create a Logger with - * that attribute. The built-in handlers will format that attribute only once, at the - * call to [Logger.With]. The [Handler] interface is designed to allow that optimization, - * and a well-written Handler should take advantage of it. - * - * The arguments to a log call are always evaluated, even if the log event is discarded. - * If possible, defer computation so that it happens only if the value is actually logged. - * For example, consider the call - * - * ``` - * slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily - * ``` - * - * The URL.String method will be called even if the logger discards Info-level events. - * Instead, pass the URL directly: - * - * ``` - * slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed - * ``` - * - * The built-in [TextHandler] will call its String method, but only - * if the log event is enabled. - * Avoiding the call to String also preserves the structure of the underlying value. - * For example [JSONHandler] emits the components of the parsed URL as a JSON object. - * If you want to avoid eagerly paying the cost of the String call - * without causing the handler to potentially inspect the structure of the value, - * wrap the value in a fmt.Stringer implementation that hides its Marshal methods. - * - * You can also use the [LogValuer] interface to avoid unnecessary work in disabled log - * calls. Say you need to log some expensive value: - * - * ``` - * slog.Debug("frobbing", "value", computeExpensiveValue(arg)) - * ``` - * - * Even if this line is disabled, computeExpensiveValue will be called. - * To avoid that, define a type implementing LogValuer: - * - * ``` - * type expensive struct { arg int } - * - * func (e expensive) LogValue() slog.Value { - * return slog.AnyValue(computeExpensiveValue(e.arg)) - * } - * ``` - * - * Then use a value of that type in log calls: - * - * ``` - * slog.Debug("frobbing", "value", expensive{arg}) - * ``` - * - * Now computeExpensiveValue will only be called when the line is enabled. - * - * The built-in handlers acquire a lock before calling [io.Writer.Write] - * to ensure that exactly one [Record] is written at a time in its entirety. - * Although each log record has a timestamp, - * the built-in handlers do not use that time to sort the written records. - * User-defined handlers are responsible for their own locking and sorting. - * - * # Writing a handler - * - * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. - */ -namespace slog { - /** - * An Attr is a key-value pair. - */ - interface Attr { - key: string - value: Value - } - interface Attr { - /** - * Equal reports whether a and b have equal keys and values. - */ - equal(b: Attr): boolean - } - interface Attr { - string(): string - } - /** - * A Handler handles log records produced by a Logger. - * - * A typical handler may print log records to standard error, - * or write them to a file or database, or perhaps augment them - * with additional attributes and pass them on to another handler. - * - * Any of the Handler's methods may be called concurrently with itself - * or with other methods. It is the responsibility of the Handler to - * manage this concurrency. - * - * Users of the slog package should not invoke Handler methods directly. - * They should use the methods of [Logger] instead. - */ - interface Handler { - [key:string]: any; - /** - * Enabled reports whether the handler handles records at the given level. - * The handler ignores records whose level is lower. - * It is called early, before any arguments are processed, - * to save effort if the log event should be discarded. - * If called from a Logger method, the first argument is the context - * passed to that method, or context.Background() if nil was passed - * or the method does not take a context. - * The context is passed so Enabled can use its values - * to make a decision. - */ - enabled(_arg0: context.Context, _arg1: Level): boolean - /** - * Handle handles the Record. - * It will only be called when Enabled returns true. - * The Context argument is as for Enabled. - * It is present solely to provide Handlers access to the context's values. - * Canceling the context should not affect record processing. - * (Among other things, log messages may be necessary to debug a - * cancellation-related problem.) - * - * Handle methods that produce output should observe the following rules: - * ``` - * - If r.Time is the zero time, ignore the time. - * - If r.PC is zero, ignore it. - * - Attr's values should be resolved. - * - If an Attr's key and value are both the zero value, ignore the Attr. - * This can be tested with attr.Equal(Attr{}). - * - If a group's key is empty, inline the group's Attrs. - * - If a group has no Attrs (even if it has a non-empty key), - * ignore it. - * ``` - */ - handle(_arg0: context.Context, _arg1: Record): void - /** - * WithAttrs returns a new Handler whose attributes consist of - * both the receiver's attributes and the arguments. - * The Handler owns the slice: it may retain, modify or discard it. - */ - withAttrs(attrs: Array): Handler - /** - * WithGroup returns a new Handler with the given group appended to - * the receiver's existing groups. - * The keys of all subsequent attributes, whether added by With or in a - * Record, should be qualified by the sequence of group names. - * - * How this qualification happens is up to the Handler, so long as - * this Handler's attribute keys differ from those of another Handler - * with a different sequence of group names. - * - * A Handler should treat WithGroup as starting a Group of Attrs that ends - * at the end of the log event. That is, - * - * ``` - * logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2)) - * ``` - * - * should behave like - * - * ``` - * logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) - * ``` - * - * If the name is empty, WithGroup returns the receiver. - */ - withGroup(name: string): Handler - } - /** - * A Level is the importance or severity of a log event. - * The higher the level, the more important or severe the event. - */ - interface Level extends Number{} - interface Level { - /** - * String returns a name for the level. - * If the level has a name, then that name - * in uppercase is returned. - * If the level is between named values, then - * an integer is appended to the uppercased name. - * Examples: - * - * ``` - * LevelWarn.String() => "WARN" - * (LevelInfo+2).String() => "INFO+2" - * ``` - */ - string(): string - } - interface Level { - /** - * MarshalJSON implements [encoding/json.Marshaler] - * by quoting the output of [Level.String]. - */ - marshalJSON(): string|Array - } - interface Level { - /** - * UnmarshalJSON implements [encoding/json.Unmarshaler] - * It accepts any string produced by [Level.MarshalJSON], - * ignoring case. - * It also accepts numeric offsets that would result in a different string on - * output. For example, "Error-8" would marshal as "INFO". - */ - unmarshalJSON(data: string|Array): void - } - interface Level { - /** - * MarshalText implements [encoding.TextMarshaler] - * by calling [Level.String]. - */ - marshalText(): string|Array - } - interface Level { - /** - * UnmarshalText implements [encoding.TextUnmarshaler]. - * It accepts any string produced by [Level.MarshalText], - * ignoring case. - * It also accepts numeric offsets that would result in a different string on - * output. For example, "Error-8" would marshal as "INFO". - */ - unmarshalText(data: string|Array): void - } - interface Level { - /** - * Level returns the receiver. - * It implements [Leveler]. - */ - level(): Level - } - // @ts-ignore - import loginternal = internal -} - /** * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer * object, creating another object (Reader or Writer) that also implements @@ -21471,6 +20731,269 @@ namespace bufio { } } +/** + * Package syscall contains an interface to the low-level operating system + * primitives. The details vary depending on the underlying system, and + * by default, godoc will display the syscall documentation for the current + * system. If you want godoc to display syscall documentation for another + * system, set $GOOS and $GOARCH to the desired system. For example, if + * you want to view documentation for freebsd/arm on linux/amd64, set $GOOS + * to freebsd and $GOARCH to arm. + * The primary use of syscall is inside other packages that provide a more + * portable interface to the system, such as "os", "time" and "net". Use + * those packages rather than this one if you can. + * For details of the functions and data types in this package consult + * the manuals for the appropriate operating system. + * These calls return err == nil to indicate success; otherwise + * err is an operating system error describing the failure. + * On most systems, that error has type [Errno]. + * + * NOTE: Most of the functions, types, and constants defined in + * this package are also available in the [golang.org/x/sys] package. + * That package has more system call support than this one, + * and most new code should prefer that package where possible. + * See https://golang.org/s/go1.4-syscall for more information. + */ +namespace syscall { + /** + * SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. + * See user_namespaces(7). + * + * Note that User Namespaces are not available on a number of popular Linux + * versions (due to security issues), or are available but subject to AppArmor + * restrictions like in Ubuntu 24.04. + */ + interface SysProcIDMap { + containerID: number // Container ID. + hostID: number // Host ID. + size: number // Size. + } + // @ts-ignore + import errorspkg = errors + /** + * Credential holds user and group identities to be assumed + * by a child process started by [StartProcess]. + */ + interface Credential { + uid: number // User ID. + gid: number // Group ID. + groups: Array // Supplementary group IDs. + noSetGroups: boolean // If true, don't set supplementary groups + } + // @ts-ignore + import runtimesyscall = syscall + /** + * A Signal is a number describing a process signal. + * It implements the [os.Signal] interface. + */ + interface Signal extends Number{} + interface Signal { + signal(): void + } + interface Signal { + 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), t.Compare(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. The same applies to other functions and + * methods that subtract times, such as [Since], [Until], [Before], [After], + * [Add], [Sub], [Equal] and [Compare]. In some cases, you may need to strip + * the monotonic clock to get accurate results. + * + * Because the monotonic clock reading has no meaning outside + * the current process, the serialized forms generated by t.GobEncode, + * t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic + * clock reading, and t.Format provides no format for it. Similarly, the + * constructors [time.Date], [time.Parse], [time.ParseInLocation], and [time.Unix], + * as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. + * t.UnmarshalJSON, and t.UnmarshalText always create times with + * no monotonic clock reading. + * + * The monotonic clock reading exists only in [Time] values. It is not + * a part of [Duration] values or the Unix times returned by t.Unix and + * friends. + * + * Note that the Go == operator compares not just the time instant but + * also the [Location] and the monotonic clock reading. See the + * documentation for the Time type for a discussion of equality + * testing for Time values. + * + * For debugging, the result of t.String does include the monotonic + * clock reading if present. If t != u because of different monotonic clock readings, + * that difference will be visible when printing t.String() and u.String(). + * + * # Timer Resolution + * + * [Timer] resolution varies depending on the Go runtime, the operating system + * and the underlying hardware. + * On Unix, the resolution is ~1ms. + * On Windows version 1803 and newer, the resolution is ~0.5ms. + * On older Windows versions, the default resolution is ~16ms, but + * a higher resolution may be requested using [golang.org/x/sys/windows.TimeBeginPeriod]. + */ +namespace time { + /** + * A Month specifies a month of the year (January = 1, ...). + */ + interface Month extends Number{} + interface Month { + /** + * String returns the English name of the month ("January", "February", ...). + */ + string(): string + } + /** + * A Weekday specifies a day of the week (Sunday = 0, ...). + */ + interface Weekday extends Number{} + interface Weekday { + /** + * String returns the English name of the day ("Sunday", "Monday", ...). + */ + string(): string + } + /** + * A Location maps time instants to the zone in use at that time. + * Typically, the Location represents the collection of time offsets + * in use in a geographical area. For many Locations the time offset varies + * depending on whether daylight savings time is in use at the time instant. + * + * Location is used to provide a time zone in a printed Time value and for + * calculations involving intervals that may cross daylight savings time + * boundaries. + */ + interface Location { + } + interface Location { + /** + * String returns a descriptive name for the time zone information, + * corresponding to the name argument to [LoadLocation] or [FixedZone]. + */ + string(): string + } +} + +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + * + * See the [testing/fstest] package for support with testing + * implementations of file systems. + */ +namespace fs { +} + +/** + * Package context defines the Context type, which carries deadlines, + * cancellation signals, and other request-scoped values across API boundaries + * and between processes. + * + * Incoming requests to a server should create a [Context], and outgoing + * calls to servers should accept a Context. The chain of function + * calls between them must propagate the Context, optionally replacing + * it with a derived Context created using [WithCancel], [WithDeadline], + * [WithTimeout], or [WithValue]. When a Context is canceled, all + * Contexts derived from it are also canceled. + * + * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a + * Context (the parent) and return a derived Context (the child) and a + * [CancelFunc]. Calling the CancelFunc cancels the child and its + * children, removes the parent's reference to the child, and stops + * any associated timers. Failing to call the CancelFunc leaks the + * child and its children until the parent is canceled or the timer + * fires. The go vet tool checks that CancelFuncs are used on all + * control-flow paths. + * + * The [WithCancelCause] function returns a [CancelCauseFunc], which + * takes an error and records it as the cancellation cause. Calling + * [Cause] on the canceled context or any of its children retrieves + * the cause. If no cause is specified, Cause(ctx) returns the same + * value as ctx.Err(). + * + * Programs that use Contexts should follow these rules to keep interfaces + * consistent across packages and enable static analysis tools to check context + * propagation: + * + * Do not store Contexts inside a struct type; instead, pass a Context + * explicitly to each function that needs it. The Context should be the first + * parameter, typically named ctx: + * + * ``` + * func DoSomething(ctx context.Context, arg Arg) error { + * // ... use ctx ... + * } + * ``` + * + * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] + * if you are unsure about which Context to use. + * + * Use context Values only for request-scoped data that transits processes and + * APIs, not for passing optional parameters to functions. + * + * The same Context may be passed to functions running in different goroutines; + * Contexts are safe for simultaneous use by multiple goroutines. + * + * See https://blog.golang.org/context for example code for a server that uses + * Contexts. + */ +namespace context { +} + /** * Package sql provides a generic interface around SQL (or SQL-like) * databases. @@ -22628,18 +22151,6 @@ namespace http { } } -namespace subscriptions { -} - -namespace hook { - /** - * wrapped local Hook embedded struct to limit the public API surface. - */ - type _subVlape = Hook - interface mainHook extends _subVlape { - } -} - /** * Package oauth2 provides support for making * OAuth2 authorized and authenticated HTTP requests, @@ -22743,6 +22254,15 @@ namespace oauth2 { } } +namespace hook { + /** + * wrapped local Hook embedded struct to limit the public API surface. + */ + type _subLYIwY = Hook + interface mainHook extends _subLYIwY { + } +} + namespace router { // @ts-ignore import validation = ozzo_validation @@ -22926,6 +22446,9 @@ namespace cobra { } } +namespace subscriptions { +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -23300,175 +22823,169 @@ namespace cobra { * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. */ namespace slog { - // @ts-ignore - import loginternal = internal /** - * A Record holds information about a log event. - * Copies of a Record share state. - * Do not modify a Record after handing out a copy to it. - * Call [NewRecord] to create a new Record. - * Use [Record.Clone] to create a copy with no shared state. + * An Attr is a key-value pair. */ - interface Record { + interface Attr { + key: string + value: Value + } + interface Attr { /** - * The time at which the output method (Log, Info, etc.) was called. + * Equal reports whether a and b have equal keys and values. */ - time: time.Time + equal(b: Attr): boolean + } + interface Attr { + string(): string + } + /** + * A Handler handles log records produced by a Logger. + * + * A typical handler may print log records to standard error, + * or write them to a file or database, or perhaps augment them + * with additional attributes and pass them on to another handler. + * + * Any of the Handler's methods may be called concurrently with itself + * or with other methods. It is the responsibility of the Handler to + * manage this concurrency. + * + * Users of the slog package should not invoke Handler methods directly. + * They should use the methods of [Logger] instead. + */ + interface Handler { + [key:string]: any; /** - * The log message. + * Enabled reports whether the handler handles records at the given level. + * The handler ignores records whose level is lower. + * It is called early, before any arguments are processed, + * to save effort if the log event should be discarded. + * If called from a Logger method, the first argument is the context + * passed to that method, or context.Background() if nil was passed + * or the method does not take a context. + * The context is passed so Enabled can use its values + * to make a decision. */ - message: string + enabled(_arg0: context.Context, _arg1: Level): boolean /** - * The level of the event. - */ - level: Level - /** - * The program counter at the time the record was constructed, as determined - * by runtime.Callers. If zero, no program counter is available. + * Handle handles the Record. + * It will only be called when Enabled returns true. + * The Context argument is as for Enabled. + * It is present solely to provide Handlers access to the context's values. + * Canceling the context should not affect record processing. + * (Among other things, log messages may be necessary to debug a + * cancellation-related problem.) * - * The only valid use for this value is as an argument to - * [runtime.CallersFrames]. In particular, it must not be passed to - * [runtime.FuncForPC]. + * Handle methods that produce output should observe the following rules: + * ``` + * - If r.Time is the zero time, ignore the time. + * - If r.PC is zero, ignore it. + * - Attr's values should be resolved. + * - If an Attr's key and value are both the zero value, ignore the Attr. + * This can be tested with attr.Equal(Attr{}). + * - If a group's key is empty, inline the group's Attrs. + * - If a group has no Attrs (even if it has a non-empty key), + * ignore it. + * ``` */ - pc: number - } - interface Record { + handle(_arg0: context.Context, _arg1: Record): void /** - * Clone returns a copy of the record with no shared state. - * The original record and the clone can both be modified - * without interfering with each other. + * WithAttrs returns a new Handler whose attributes consist of + * both the receiver's attributes and the arguments. + * The Handler owns the slice: it may retain, modify or discard it. */ - clone(): Record - } - interface Record { + withAttrs(attrs: Array): Handler /** - * NumAttrs returns the number of attributes in the [Record]. + * WithGroup returns a new Handler with the given group appended to + * the receiver's existing groups. + * The keys of all subsequent attributes, whether added by With or in a + * Record, should be qualified by the sequence of group names. + * + * How this qualification happens is up to the Handler, so long as + * this Handler's attribute keys differ from those of another Handler + * with a different sequence of group names. + * + * A Handler should treat WithGroup as starting a Group of Attrs that ends + * at the end of the log event. That is, + * + * ``` + * logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2)) + * ``` + * + * should behave like + * + * ``` + * logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) + * ``` + * + * If the name is empty, WithGroup returns the receiver. */ - numAttrs(): number - } - interface Record { - /** - * Attrs calls f on each Attr in the [Record]. - * Iteration stops if f returns false. - */ - attrs(f: (_arg0: Attr) => boolean): void - } - interface Record { - /** - * AddAttrs appends the given Attrs to the [Record]'s list of Attrs. - * It omits empty groups. - */ - addAttrs(...attrs: Attr[]): void - } - interface Record { - /** - * Add converts the args to Attrs as described in [Logger.Log], - * then appends the Attrs to the [Record]'s list of Attrs. - * It omits empty groups. - */ - add(...args: any[]): void + withGroup(name: string): Handler } /** - * A Value can represent any Go value, but unlike type any, - * it can represent most small values without an allocation. - * The zero Value corresponds to nil. + * A Level is the importance or severity of a log event. + * The higher the level, the more important or severe the event. */ - interface Value { - } - interface Value { + interface Level extends Number{} + interface Level { /** - * Kind returns v's Kind. - */ - kind(): Kind - } - interface Value { - /** - * Any returns v's value as an any. - */ - any(): any - } - interface Value { - /** - * String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike - * the methods Int64, Float64, and so on, which panic if v is of the - * wrong kind, String never panics. + * String returns a name for the level. + * If the level has a name, then that name + * in uppercase is returned. + * If the level is between named values, then + * an integer is appended to the uppercased name. + * Examples: + * + * ``` + * LevelWarn.String() => "WARN" + * (LevelInfo+2).String() => "INFO+2" + * ``` */ string(): string } - interface Value { + interface Level { /** - * Int64 returns v's value as an int64. It panics - * if v is not a signed integer. + * MarshalJSON implements [encoding/json.Marshaler] + * by quoting the output of [Level.String]. */ - int64(): number + marshalJSON(): string|Array } - interface Value { + interface Level { /** - * Uint64 returns v's value as a uint64. It panics - * if v is not an unsigned integer. + * UnmarshalJSON implements [encoding/json.Unmarshaler] + * It accepts any string produced by [Level.MarshalJSON], + * ignoring case. + * It also accepts numeric offsets that would result in a different string on + * output. For example, "Error-8" would marshal as "INFO". */ - uint64(): number + unmarshalJSON(data: string|Array): void } - interface Value { + interface Level { /** - * Bool returns v's value as a bool. It panics - * if v is not a bool. + * MarshalText implements [encoding.TextMarshaler] + * by calling [Level.String]. */ - bool(): boolean + marshalText(): string|Array } - interface Value { + interface Level { /** - * Duration returns v's value as a [time.Duration]. It panics - * if v is not a time.Duration. + * UnmarshalText implements [encoding.TextUnmarshaler]. + * It accepts any string produced by [Level.MarshalText], + * ignoring case. + * It also accepts numeric offsets that would result in a different string on + * output. For example, "Error-8" would marshal as "INFO". */ - duration(): time.Duration + unmarshalText(data: string|Array): void } - interface Value { + interface Level { /** - * Float64 returns v's value as a float64. It panics - * if v is not a float64. + * Level returns the receiver. + * It implements [Leveler]. */ - float64(): number - } - interface Value { - /** - * Time returns v's value as a [time.Time]. It panics - * if v is not a time.Time. - */ - time(): time.Time - } - interface Value { - /** - * LogValuer returns v's value as a LogValuer. It panics - * if v is not a LogValuer. - */ - logValuer(): LogValuer - } - interface Value { - /** - * Group returns v's value as a []Attr. - * It panics if v's [Kind] is not [KindGroup]. - */ - group(): Array - } - interface Value { - /** - * Equal reports whether v and w represent the same Go value. - */ - equal(w: Value): boolean - } - interface Value { - /** - * Resolve repeatedly calls LogValue on v while it implements [LogValuer], - * and returns the result. - * If v resolves to a group, the group's attributes' values are not recursively - * resolved. - * If the number of LogValue calls exceeds a threshold, a Value containing an - * error is returned. - * Resolve's return value is guaranteed not to be of Kind [KindLogValuer]. - */ - resolve(): Value + level(): Level } + // @ts-ignore + import loginternal = internal } /** @@ -24114,6 +23631,556 @@ namespace router { * * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. */ +namespace slog { + // @ts-ignore + import loginternal = internal + /** + * A Record holds information about a log event. + * Copies of a Record share state. + * Do not modify a Record after handing out a copy to it. + * Call [NewRecord] to create a new Record. + * Use [Record.Clone] to create a copy with no shared state. + */ + interface Record { + /** + * The time at which the output method (Log, Info, etc.) was called. + */ + time: time.Time + /** + * The log message. + */ + message: string + /** + * The level of the event. + */ + level: Level + /** + * The program counter at the time the record was constructed, as determined + * by runtime.Callers. If zero, no program counter is available. + * + * The only valid use for this value is as an argument to + * [runtime.CallersFrames]. In particular, it must not be passed to + * [runtime.FuncForPC]. + */ + pc: number + } + interface Record { + /** + * Clone returns a copy of the record with no shared state. + * The original record and the clone can both be modified + * without interfering with each other. + */ + clone(): Record + } + interface Record { + /** + * NumAttrs returns the number of attributes in the [Record]. + */ + numAttrs(): number + } + interface Record { + /** + * Attrs calls f on each Attr in the [Record]. + * Iteration stops if f returns false. + */ + attrs(f: (_arg0: Attr) => boolean): void + } + interface Record { + /** + * AddAttrs appends the given Attrs to the [Record]'s list of Attrs. + * It omits empty groups. + */ + addAttrs(...attrs: Attr[]): void + } + interface Record { + /** + * Add converts the args to Attrs as described in [Logger.Log], + * then appends the Attrs to the [Record]'s list of Attrs. + * It omits empty groups. + */ + add(...args: any[]): void + } + /** + * A Value can represent any Go value, but unlike type any, + * it can represent most small values without an allocation. + * The zero Value corresponds to nil. + */ + interface Value { + } + interface Value { + /** + * Kind returns v's Kind. + */ + kind(): Kind + } + interface Value { + /** + * Any returns v's value as an any. + */ + any(): any + } + interface Value { + /** + * String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike + * the methods Int64, Float64, and so on, which panic if v is of the + * wrong kind, String never panics. + */ + string(): string + } + interface Value { + /** + * Int64 returns v's value as an int64. It panics + * if v is not a signed integer. + */ + int64(): number + } + interface Value { + /** + * Uint64 returns v's value as a uint64. It panics + * if v is not an unsigned integer. + */ + uint64(): number + } + interface Value { + /** + * Bool returns v's value as a bool. It panics + * if v is not a bool. + */ + bool(): boolean + } + interface Value { + /** + * Duration returns v's value as a [time.Duration]. It panics + * if v is not a time.Duration. + */ + duration(): time.Duration + } + interface Value { + /** + * Float64 returns v's value as a float64. It panics + * if v is not a float64. + */ + float64(): number + } + interface Value { + /** + * Time returns v's value as a [time.Time]. It panics + * if v is not a time.Time. + */ + time(): time.Time + } + interface Value { + /** + * LogValuer returns v's value as a LogValuer. It panics + * if v is not a LogValuer. + */ + logValuer(): LogValuer + } + interface Value { + /** + * Group returns v's value as a []Attr. + * It panics if v's [Kind] is not [KindGroup]. + */ + group(): Array + } + interface Value { + /** + * Equal reports whether v and w represent the same Go value. + */ + equal(w: Value): boolean + } + interface Value { + /** + * Resolve repeatedly calls LogValue on v while it implements [LogValuer], + * and returns the result. + * If v resolves to a group, the group's attributes' values are not recursively + * resolved. + * If the number of LogValue calls exceeds a threshold, a Value containing an + * error is returned. + * Resolve's return value is guaranteed not to be of Kind [KindLogValuer]. + */ + resolve(): Value + } +} + +namespace router { + // @ts-ignore + import validation = ozzo_validation +} + +/** + * Package slog provides structured logging, + * in which log records include a message, + * a severity level, and various other attributes + * expressed as key-value pairs. + * + * It defines a type, [Logger], + * which provides several methods (such as [Logger.Info] and [Logger.Error]) + * for reporting events of interest. + * + * Each Logger is associated with a [Handler]. + * A Logger output method creates a [Record] from the method arguments + * and passes it to the Handler, which decides how to handle it. + * There is a default Logger accessible through top-level functions + * (such as [Info] and [Error]) that call the corresponding Logger methods. + * + * A log record consists of a time, a level, a message, and a set of key-value + * pairs, where the keys are strings and the values may be of any type. + * As an example, + * + * ``` + * slog.Info("hello", "count", 3) + * ``` + * + * creates a record containing the time of the call, + * a level of Info, the message "hello", and a single + * pair with key "count" and value 3. + * + * The [Info] top-level function calls the [Logger.Info] method on the default Logger. + * In addition to [Logger.Info], there are methods for Debug, Warn and Error levels. + * Besides these convenience methods for common levels, + * there is also a [Logger.Log] method which takes the level as an argument. + * Each of these methods has a corresponding top-level function that uses the + * default logger. + * + * The default handler formats the log record's message, time, level, and attributes + * as a string and passes it to the [log] package. + * + * ``` + * 2022/11/08 15:28:26 INFO hello count=3 + * ``` + * + * For more control over the output format, create a logger with a different handler. + * This statement uses [New] to create a new logger with a [TextHandler] + * that writes structured records in text form to standard error: + * + * ``` + * logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) + * ``` + * + * [TextHandler] output is a sequence of key=value pairs, easily and unambiguously + * parsed by machine. This statement: + * + * ``` + * logger.Info("hello", "count", 3) + * ``` + * + * produces this output: + * + * ``` + * time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3 + * ``` + * + * The package also provides [JSONHandler], whose output is line-delimited JSON: + * + * ``` + * logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + * logger.Info("hello", "count", 3) + * ``` + * + * produces this output: + * + * ``` + * {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3} + * ``` + * + * Both [TextHandler] and [JSONHandler] can be configured with [HandlerOptions]. + * There are options for setting the minimum level (see Levels, below), + * displaying the source file and line of the log call, and + * modifying attributes before they are logged. + * + * Setting a logger as the default with + * + * ``` + * slog.SetDefault(logger) + * ``` + * + * will cause the top-level functions like [Info] to use it. + * [SetDefault] also updates the default logger used by the [log] package, + * so that existing applications that use [log.Printf] and related functions + * will send log records to the logger's handler without needing to be rewritten. + * + * Some attributes are common to many log calls. + * For example, you may wish to include the URL or trace identifier of a server request + * with all log events arising from the request. + * Rather than repeat the attribute with every log call, you can use [Logger.With] + * to construct a new Logger containing the attributes: + * + * ``` + * logger2 := logger.With("url", r.URL) + * ``` + * + * The arguments to With are the same key-value pairs used in [Logger.Info]. + * The result is a new Logger with the same handler as the original, but additional + * attributes that will appear in the output of every call. + * + * # Levels + * + * A [Level] is an integer representing the importance or severity of a log event. + * The higher the level, the more severe the event. + * This package defines constants for the most common levels, + * but any int can be used as a level. + * + * In an application, you may wish to log messages only at a certain level or greater. + * One common configuration is to log messages at Info or higher levels, + * suppressing debug logging until it is needed. + * The built-in handlers can be configured with the minimum level to output by + * setting [HandlerOptions.Level]. + * The program's `main` function typically does this. + * The default value is LevelInfo. + * + * Setting the [HandlerOptions.Level] field to a [Level] value + * fixes the handler's minimum level throughout its lifetime. + * Setting it to a [LevelVar] allows the level to be varied dynamically. + * A LevelVar holds a Level and is safe to read or write from multiple + * goroutines. + * To vary the level dynamically for an entire program, first initialize + * a global LevelVar: + * + * ``` + * var programLevel = new(slog.LevelVar) // Info by default + * ``` + * + * Then use the LevelVar to construct a handler, and make it the default: + * + * ``` + * h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}) + * slog.SetDefault(slog.New(h)) + * ``` + * + * Now the program can change its logging level with a single statement: + * + * ``` + * programLevel.Set(slog.LevelDebug) + * ``` + * + * # Groups + * + * Attributes can be collected into groups. + * A group has a name that is used to qualify the names of its attributes. + * How this qualification is displayed depends on the handler. + * [TextHandler] separates the group and attribute names with a dot. + * [JSONHandler] treats each group as a separate JSON object, with the group name as the key. + * + * Use [Group] to create a Group attribute from a name and a list of key-value pairs: + * + * ``` + * slog.Group("request", + * "method", r.Method, + * "url", r.URL) + * ``` + * + * TextHandler would display this group as + * + * ``` + * request.method=GET request.url=http://example.com + * ``` + * + * JSONHandler would display it as + * + * ``` + * "request":{"method":"GET","url":"http://example.com"} + * ``` + * + * Use [Logger.WithGroup] to qualify all of a Logger's output + * with a group name. Calling WithGroup on a Logger results in a + * new Logger with the same Handler as the original, but with all + * its attributes qualified by the group name. + * + * This can help prevent duplicate attribute keys in large systems, + * where subsystems might use the same keys. + * Pass each subsystem a different Logger with its own group name so that + * potential duplicates are qualified: + * + * ``` + * logger := slog.Default().With("id", systemID) + * parserLogger := logger.WithGroup("parser") + * parseInput(input, parserLogger) + * ``` + * + * When parseInput logs with parserLogger, its keys will be qualified with "parser", + * so even if it uses the common key "id", the log line will have distinct keys. + * + * # Contexts + * + * Some handlers may wish to include information from the [context.Context] that is + * available at the call site. One example of such information + * is the identifier for the current span when tracing is enabled. + * + * The [Logger.Log] and [Logger.LogAttrs] methods take a context as a first + * argument, as do their corresponding top-level functions. + * + * Although the convenience methods on Logger (Info and so on) and the + * corresponding top-level functions do not take a context, the alternatives ending + * in "Context" do. For example, + * + * ``` + * slog.InfoContext(ctx, "message") + * ``` + * + * It is recommended to pass a context to an output method if one is available. + * + * # Attrs and Values + * + * An [Attr] is a key-value pair. The Logger output methods accept Attrs as well as + * alternating keys and values. The statement + * + * ``` + * slog.Info("hello", slog.Int("count", 3)) + * ``` + * + * behaves the same as + * + * ``` + * slog.Info("hello", "count", 3) + * ``` + * + * There are convenience constructors for [Attr] such as [Int], [String], and [Bool] + * for common types, as well as the function [Any] for constructing Attrs of any + * type. + * + * The value part of an Attr is a type called [Value]. + * Like an [any], a Value can hold any Go value, + * but it can represent typical values, including all numbers and strings, + * without an allocation. + * + * For the most efficient log output, use [Logger.LogAttrs]. + * It is similar to [Logger.Log] but accepts only Attrs, not alternating + * keys and values; this allows it, too, to avoid allocation. + * + * The call + * + * ``` + * logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3)) + * ``` + * + * is the most efficient way to achieve the same output as + * + * ``` + * slog.InfoContext(ctx, "hello", "count", 3) + * ``` + * + * # Customizing a type's logging behavior + * + * If a type implements the [LogValuer] interface, the [Value] returned from its LogValue + * method is used for logging. You can use this to control how values of the type + * appear in logs. For example, you can redact secret information like passwords, + * or gather a struct's fields in a Group. See the examples under [LogValuer] for + * details. + * + * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] + * method handles these cases carefully, avoiding infinite loops and unbounded recursion. + * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. + * + * # Wrapping output methods + * + * The logger functions use reflection over the call stack to find the file name + * and line number of the logging call within the application. This can produce + * incorrect source information for functions that wrap slog. For instance, if you + * define this function in file mylog.go: + * + * ``` + * func Infof(logger *slog.Logger, format string, args ...any) { + * logger.Info(fmt.Sprintf(format, args...)) + * } + * ``` + * + * and you call it like this in main.go: + * + * ``` + * Infof(slog.Default(), "hello, %s", "world") + * ``` + * + * then slog will report the source file as mylog.go, not main.go. + * + * A correct implementation of Infof will obtain the source location + * (pc) and pass it to NewRecord. + * The Infof function in the package-level example called "wrapping" + * demonstrates how to do this. + * + * # Working with Records + * + * Sometimes a Handler will need to modify a Record + * before passing it on to another Handler or backend. + * A Record contains a mixture of simple public fields (e.g. Time, Level, Message) + * and hidden fields that refer to state (such as attributes) indirectly. This + * means that modifying a simple copy of a Record (e.g. by calling + * [Record.Add] or [Record.AddAttrs] to add attributes) + * may have unexpected effects on the original. + * Before modifying a Record, use [Record.Clone] to + * create a copy that shares no state with the original, + * or create a new Record with [NewRecord] + * and build up its Attrs by traversing the old ones with [Record.Attrs]. + * + * # Performance considerations + * + * If profiling your application demonstrates that logging is taking significant time, + * the following suggestions may help. + * + * If many log lines have a common attribute, use [Logger.With] to create a Logger with + * that attribute. The built-in handlers will format that attribute only once, at the + * call to [Logger.With]. The [Handler] interface is designed to allow that optimization, + * and a well-written Handler should take advantage of it. + * + * The arguments to a log call are always evaluated, even if the log event is discarded. + * If possible, defer computation so that it happens only if the value is actually logged. + * For example, consider the call + * + * ``` + * slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily + * ``` + * + * The URL.String method will be called even if the logger discards Info-level events. + * Instead, pass the URL directly: + * + * ``` + * slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed + * ``` + * + * The built-in [TextHandler] will call its String method, but only + * if the log event is enabled. + * Avoiding the call to String also preserves the structure of the underlying value. + * For example [JSONHandler] emits the components of the parsed URL as a JSON object. + * If you want to avoid eagerly paying the cost of the String call + * without causing the handler to potentially inspect the structure of the value, + * wrap the value in a fmt.Stringer implementation that hides its Marshal methods. + * + * You can also use the [LogValuer] interface to avoid unnecessary work in disabled log + * calls. Say you need to log some expensive value: + * + * ``` + * slog.Debug("frobbing", "value", computeExpensiveValue(arg)) + * ``` + * + * Even if this line is disabled, computeExpensiveValue will be called. + * To avoid that, define a type implementing LogValuer: + * + * ``` + * type expensive struct { arg int } + * + * func (e expensive) LogValue() slog.Value { + * return slog.AnyValue(computeExpensiveValue(e.arg)) + * } + * ``` + * + * Then use a value of that type in log calls: + * + * ``` + * slog.Debug("frobbing", "value", expensive{arg}) + * ``` + * + * Now computeExpensiveValue will only be called when the line is enabled. + * + * The built-in handlers acquire a lock before calling [io.Writer.Write] + * to ensure that exactly one [Record] is written at a time in its entirety. + * Although each log record has a timestamp, + * the built-in handlers do not use that time to sort the written records. + * User-defined handlers are responsible for their own locking and sorting. + * + * # Writing a handler + * + * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. + */ namespace slog { // @ts-ignore import loginternal = internal @@ -24135,8 +24202,3 @@ namespace slog { logValue(): Value } } - -namespace router { - // @ts-ignore - import validation = ozzo_validation -} diff --git a/plugins/jsvm/internal/types/types.go b/plugins/jsvm/internal/types/types.go index 90039d34..a231ad16 100644 --- a/plugins/jsvm/internal/types/types.go +++ b/plugins/jsvm/internal/types/types.go @@ -436,7 +436,7 @@ declare class Field implements core.Field { interface NumberField extends core.NumberField{} // merge /** - * NumberField class defines a single "number" collection field. + * {@inheritDoc core.NumberField} * * @group PocketBase */ @@ -446,7 +446,7 @@ declare class NumberField implements core.NumberField { interface BoolField extends core.BoolField{} // merge /** - * BoolField class defines a single "bool" collection field. + * {@inheritDoc core.BoolField} * * @group PocketBase */ @@ -456,7 +456,7 @@ declare class BoolField implements core.BoolField { interface TextField extends core.TextField{} // merge /** - * TextField class defines a single "text" collection field. + * {@inheritDoc core.TextField} * * @group PocketBase */ @@ -466,7 +466,7 @@ declare class TextField implements core.TextField { interface URLField extends core.URLField{} // merge /** - * URLField class defines a single "url" collection field. + * {@inheritDoc core.URLField} * * @group PocketBase */ @@ -476,7 +476,7 @@ declare class URLField implements core.URLField { interface EmailField extends core.EmailField{} // merge /** - * EmailField class defines a single "email" collection field. + * {@inheritDoc core.EmailField} * * @group PocketBase */ @@ -486,7 +486,7 @@ declare class EmailField implements core.EmailField { interface EditorField extends core.EditorField{} // merge /** - * EditorField class defines a single "editor" collection field. + * {@inheritDoc core.EditorField} * * @group PocketBase */ @@ -496,7 +496,7 @@ declare class EditorField implements core.EditorField { interface PasswordField extends core.PasswordField{} // merge /** - * PasswordField class defines a single "password" collection field. + * {@inheritDoc core.PasswordField} * * @group PocketBase */ @@ -506,7 +506,7 @@ declare class PasswordField implements core.PasswordField { interface DateField extends core.DateField{} // merge /** - * DateField class defines a single "date" collection field. + * {@inheritDoc core.DateField} * * @group PocketBase */ @@ -516,7 +516,7 @@ declare class DateField implements core.DateField { interface AutodateField extends core.AutodateField{} // merge /** - * AutodateField class defines a single "autodate" collection field. + * {@inheritDoc core.AutodateField} * * @group PocketBase */ @@ -526,7 +526,7 @@ declare class AutodateField implements core.AutodateField { interface JSONField extends core.JSONField{} // merge /** - * JSONField class defines a single "json" collection field. + * {@inheritDoc core.JSONField} * * @group PocketBase */ @@ -536,7 +536,7 @@ declare class JSONField implements core.JSONField { interface RelationField extends core.RelationField{} // merge /** - * RelationField class defines a single "relation" collection field. + * {@inheritDoc core.RelationField} * * @group PocketBase */ @@ -546,7 +546,7 @@ declare class RelationField implements core.RelationField { interface SelectField extends core.SelectField{} // merge /** - * SelectField class defines a single "select" collection field. + * {@inheritDoc core.SelectField} * * @group PocketBase */ @@ -556,7 +556,7 @@ declare class SelectField implements core.SelectField { interface FileField extends core.FileField{} // merge /** - * FileField class defines a single "file" collection field. + * {@inheritDoc core.FileField} * * @group PocketBase */ diff --git a/pocketbase.go b/pocketbase.go index b62971fd..f1d497cf 100644 --- a/pocketbase.go +++ b/pocketbase.go @@ -60,13 +60,13 @@ type Config struct { } // New creates a new PocketBase instance with the default configuration. -// Use [NewWithConfig()] if you want to provide a custom configuration. +// Use [NewWithConfig] if you want to provide a custom configuration. // // Note that the application will not be initialized/bootstrapped yet, // aka. DB connections, migrations, app settings, etc. will not be accessible. -// Everything will be initialized when [Start()] is executed. -// If you want to initialize the application before calling [Start()], -// then you'll have to manually call [Bootstrap()]. +// Everything will be initialized when [PocketBase.Start()] is executed. +// If you want to initialize the application before calling [PocketBase.Start()], +// then you'll have to manually call [PocketBase.Bootstrap()]. func New() *PocketBase { _, isUsingGoRun := inspectRuntime() @@ -79,9 +79,9 @@ func New() *PocketBase { // // Note that the application will not be initialized/bootstrapped yet, // aka. DB connections, migrations, app settings, etc. will not be accessible. -// Everything will be initialized when [Start()] is executed. -// If you want to initialize the application before calling [Start()], -// then you'll have to manually call [Bootstrap()]. +// Everything will be initialized when [PocketBase.Start()] is executed. +// If you want to initialize the application before calling [PocketBase..Start()], +// then you'll have to manually call [PocketBase.Bootstrap()]. func NewWithConfig(config Config) *PocketBase { // initialize a default data directory based on the executable baseDir if config.DefaultDataDir == "" { diff --git a/tools/router/event.go b/tools/router/event.go index 7f8fc143..548ecc72 100644 --- a/tools/router/event.go +++ b/tools/router/event.go @@ -345,12 +345,33 @@ func (e *Event) InternalServerError(message string, errData any) *ApiError { const DefaultMaxMemory = 32 << 20 // 32mb -// Supports the following content-types: +// BindBody unmarshal the request body into the provided dst. // +// dst must be either a struct pointer or map[string]any. +// +// The rules how the body will be scanned depends on the request Content-Type. +// +// Currently the following Content-Types are supported: // - application/json -// - multipart/form-data -// - application/x-www-form-urlencoded // - text/xml, application/xml +// - multipart/form-data, application/x-www-form-urlencoded +// +// Respectively the following struct tags are supported (again, which one will be used depends on the Content-Type): +// - "json" (json body)- uses the builtin Go json package for unmarshaling. +// - "xml" (xml body) - uses the builtin Go xml package for unmarshaling. +// - "form" (form data) - utilizes the custom [router.UnmarshalRequestData] method. +// +// NB! When dst is a struct make sure that it doesn't have public fields +// that shouldn't be bindable and it is advisible such fields to be unexported +// or have a separate struct just for the binding. For example: +// +// data := struct{ +// somethingPrivate string +// +// Title string `json:"title" form:"title"` +// Total int `json:"total" form:"total"` +// } +// err := e.BindBody(&data) func (e *Event) BindBody(dst any) error { if e.Request.ContentLength == 0 { return nil