Socket
Socket
Sign inDemoInstall

pocketbase

Package Overview
Dependencies
Maintainers
1
Versions
84
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pocketbase - npm Package Compare versions

Comparing version 0.16.0 to 0.17.0-rc1

dist/pocketbase.es.d.ts

109

CHANGELOG.md

@@ -0,1 +1,110 @@

## 0.17.0-rc1
- To simplify file uploads, we now allow sending the `multipart/form-data` request body also as plain object if at least one of the object props has `File` or `Blob` value.
```js
// the standard way to create multipart/form-data body
const data = new FormData();
data.set("title", "lorem ipsum...")
data.set("document", new File(...))
// this is the same as above
// (it will be converted behind the scenes to FormData)
const data = {
"title": "lorem ipsum...",
"document": new File(...),
};
await pb.collection("example").create(data);
```
- Added new `pb.authStore.isAdmin` and `pb.authStore.isAuthRecord` helpers to check the type of the current auth state.
- The default `LocalAuthStore` now listen to the browser [storage event](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event),
so that we can sync automatically the `pb.authStore` state between multiple tabs.
- Added new helper `AsyncAuthStore` class that can be used to integrate with any 3rd party async storage implementation (_usually this is needed when working with React Native_):
```js
import AsyncStorage from "@react-native-async-storage/async-storage";
import PocketBase, { AsyncAuthStore } from "pocketbase";
const store = new AsyncAuthStore({
save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
initial: await AsyncStorage.getItem("pb_auth"),
});
const pb = new PocketBase("https://example.com", store)
```
- ⚠️ All API actions now return plain object (POJO) as response, aka. the custom class wrapping was removed and you no longer need to manually call `structuredClone(response)` when using with SSR frameworks.
This could be a breaking change if you use the below classes (_and respectively their helper methods like `$isNew`, `$load()`, etc._) since they were replaced with plain TS interfaces:
```ts
class BaseModel -> interface BaseModel
class Admin -> interface AdminModel
class Record -> interface RecordModel
class LogRequest -> interface LogRequestModel
class ExternalAuth -> interface ExternalAuthModel
class Collection -> interface CollectionModel
class SchemaField -> interface SchemaField
class ListResult -> interface ListResult
```
_Side-note:_ If you use somewhere in your code the `Record` and `Admin` classes to determine the type of your `pb.authStore.model`,
you can safely replace it with the new `pb.authStore.isAdmin` and `pb.authStore.isAuthRecord` getters.
- ⚠️ Added support for per-request `fetch` options, including also specifying completely custom `fetch` implementation.
In addition to the default [`fetch` options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options), the following configurable fields are supported:
```ts
interface SendOptions extends RequestInit {
// any other custom key will be merged with the query parameters
// for backward compatibility and to minimize the verbosity
[key: string]: any;
// optional custom fetch function to use for sending the request
fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
// custom headers to send with the requests
headers?: { [key: string]: string };
// the body of the request (serialized automatically for json requests)
body?: any;
// query params that will be appended to the request url
query?: { [key: string]: any };
// the request identifier that can be used to cancel pending requests
requestKey?: string|null;
// @deprecated use `requestKey:string` instead
$cancelKey?: string;
// @deprecated use `requestKey:null` instead
$autoCancel?: boolean;
}
```
For most users the above will not be a breaking change since there are available function overloads (_when possible_) to preserve the old behavior, but you can get a warning message in the console to update to the new format.
For example:
```js
// OLD (should still work but with a warning in the console)
await pb.collection("example").authRefresh({}, {
"expand": "someRelField",
})
// NEW
await pb.collection("example").authRefresh({
"expand": "someRelField",
// send some additional header
"headers": {
"X-Custom-Header": "123",
},
"cache": "no-store" // also usually used by frameworks like Next.js
})
```
- Internal refactoring (updated dev dependencies, refactored the tests to use Vitest instead of Mocha, etc.).
## 0.16.0

@@ -2,0 +111,0 @@

634

dist/pocketbase.cjs.d.ts

@@ -12,3 +12,10 @@ interface SerializeOptions {

}
declare abstract class BaseModel {
interface ListResult<T> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<T>;
}
interface BaseModel {
[key: string]: any;

@@ -18,71 +25,61 @@ id: string;

updated: string;
constructor(data?: {
}
interface AdminModel extends BaseModel {
avatar: number;
email: string;
}
interface SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
});
/**
* Alias of this.$load(data).
*/
load(data: {
};
}
interface CollectionModel extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule?: string;
viewRule?: string;
createRule?: string;
updateRule?: string;
deleteRule?: string;
options: {
[key: string]: any;
}): void;
/**
* Loads `data` into the current model.
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Returns whether the current loaded data represent a stored db record.
*/
get $isNew(): boolean;
/**
* Alias of this.clone().
*/
clone(): BaseModel;
/**
* Creates a deep clone of the current model.
*/
$clone(): BaseModel;
/**
* Alias of this.$export().
*/
export(): {
[key: string]: any;
};
/**
* Exports all model properties as a new plain object.
*/
$export(): {
}
interface ExternalAuthModel extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
}
interface LogRequestModel extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
}
declare class Record extends BaseModel {
interface RecordModel extends BaseModel {
[key: string]: any;
collectionId: string;
collectionName: string;
expand: {
[key: string]: Record | Array<Record>;
expand?: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Loads the provided expand items and recursively normalizes each
* item to a `Record|Array<Record>`.
*/
private _loadExpand;
}
declare class Admin extends BaseModel {
avatar: number;
email: string;
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
type OnStoreChangeFunc = (token: string, model: Record | Admin | null) => void;
type AuthModel = RecordModel | AdminModel | null;
type OnStoreChangeFunc = (token: string, model: AuthModel) => void;
/**

@@ -94,3 +91,3 @@ * Base AuthStore class that is intended to be extended by all other

protected baseToken: string;
protected baseModel: Record | Admin | null;
protected baseModel: AuthModel;
private _onChangeCallbacks;

@@ -104,3 +101,3 @@ /**

*/
get model(): Record | Admin | null;
get model(): AuthModel;
/**

@@ -111,5 +108,13 @@ * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).

/**
* Checks whether the current store state is for admin authentication.
*/
get isAdmin(): boolean;
/**
* Checks whether the current store state is for auth record authentication.
*/
get isAuthRecord(): boolean;
/**
* Saves the provided new token and model data in the auth store.
*/
save(token: string, model: Record | Admin | null): void;
save(token: string, model?: AuthModel): void;
/**

@@ -177,9 +182,34 @@ * Removes the stored token and model data form the auth store.

}
interface BaseQueryParams {
[key: string]: any;
fields?: string;
interface SendOptions extends RequestInit {
[key: string]: any; // for backward compatibility
// optional custom fetch function to use for sending the request
fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
// custom headers to send with the requests
headers?: {
[key: string]: string;
};
// the body of the request (serialized automatically for json requests)
body?: any;
// query params that will be appended to the request url
query?: {
[key: string]: any;
};
// @deprecated use `query` instead
//
// for backward-compatibility `params` values are merged with `query`,
// but this option may get removed in the final v1 release
params?: {
[key: string]: any;
};
// the request identifier that can be used to cancel pending requests
requestKey?: string | null;
// @deprecated use `requestKey:string` instead
$cancelKey?: string;
// @deprecated use `requestKey:null` instead
$autoCancel?: boolean;
$cancelKey?: string;
}
interface ListQueryParams extends BaseQueryParams {
interface CommonOptions extends SendOptions {
fields?: string;
}
interface ListOptions extends CommonOptions {
page?: number;

@@ -191,16 +221,16 @@ perPage?: number;

}
interface FullListQueryParams extends ListQueryParams {
interface FullListOptions extends ListOptions {
batch?: number;
}
interface RecordQueryParams extends BaseQueryParams {
interface RecordOptions extends CommonOptions {
expand?: string;
}
interface RecordListQueryParams extends ListQueryParams, RecordQueryParams {
interface RecordListOptions extends ListOptions, RecordOptions {
}
interface RecordFullListQueryParams extends FullListQueryParams, RecordQueryParams {
interface RecordFullListOptions extends FullListOptions, RecordOptions {
}
interface LogStatsQueryParams extends BaseQueryParams {
interface LogStatsOptions extends CommonOptions {
filter?: string;
}
interface FileQueryParams extends BaseQueryParams {
interface FileOptions extends CommonOptions {
thumb?: string;

@@ -216,3 +246,3 @@ download?: boolean;

*/
getAll(queryParams?: BaseQueryParams): Promise<{
getAll(options?: CommonOptions): Promise<{
[key: string]: any;

@@ -223,4 +253,6 @@ }>;

*/
update(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<{
update(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<{
[key: string]: any;
}>;

@@ -232,3 +264,3 @@ /**

*/
testS3(filesystem?: string, queryParams?: BaseQueryParams): Promise<boolean>;
testS3(filesystem?: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -242,65 +274,20 @@ * Sends a test email.

*/
testEmail(toEmail: string, emailTemplate: string, queryParams?: BaseQueryParams): Promise<boolean>;
testEmail(toEmail: string, emailTemplate: string, options?: CommonOptions): Promise<boolean>;
/**
* Generates a new Apple OAuth2 client secret.
*/
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<appleClientSecret>;
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, options?: CommonOptions): Promise<appleClientSecret>;
}
declare class ListResult<M = BaseModel> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<M>;
constructor(page: number, perPage: number, totalItems: number, totalPages: number, items: Array<M>);
}
// @todo since there is no longer need of SubCrudService consider merging with CrudService in v0.9+
declare abstract class BaseCrudService<M extends BaseModel> extends BaseService {
declare abstract class CrudService<M> extends BaseService {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Response data decoder.
*/
abstract decode(data: {
decode<T = M>(data: {
[key: string]: any;
}): M;
}): T;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(basePath: string, batchSize?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
/**
* Returns paginated items list.
*/
protected _getList<T = M>(basePath: string, page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
/**
* Returns single item by its id.
*/
protected _getOne<T = M>(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Returns the first found item by a list filter.
*
* Internally it calls `_getList(basePath, 1, 1, { filter, skipTotal })`
* and returns its first item.
*
* For consistency with `_getOne`, this method will throw a 404
* ClientResponseError if no item was found.
*/
protected _getFirstListItem<T = M>(basePath: string, filter: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Creates a new item.
*/
protected _create<T = M>(basePath: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Updates an existing item by its id.
*/
protected _update<T = M>(basePath: string, id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Deletes an existing item by its id.
*/
protected _delete(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare abstract class CrudService<M extends BaseModel> extends BaseCrudService<M> {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Returns a promise with all list items batch fetched at once

@@ -311,7 +298,7 @@ * (by default 500 items per request; to change it set the `batch` query param).

*/
getFullList<T = M>(queryParams?: FullListQueryParams): Promise<Array<T>>;
getFullList<T = M>(options?: FullListOptions): Promise<Array<T>>;
/**
* Legacy version of getFullList with explicitly specified batch size.
*/
getFullList<T = M>(batch?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
getFullList<T = M>(batch?: number, options?: ListOptions): Promise<Array<T>>;
/**

@@ -322,3 +309,3 @@ * Returns paginated items list.

*/
getList<T = M>(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
getList<T = M>(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<T>>;
/**

@@ -335,3 +322,3 @@ * Returns the first found item by the specified filter.

*/
getFirstListItem<T = M>(filter: string, queryParams?: BaseQueryParams): Promise<T>;
getFirstListItem<T = M>(filter: string, options?: CommonOptions): Promise<T>;
/**

@@ -342,3 +329,3 @@ * Returns single item by its id.

*/
getOne<T = M>(id: string, queryParams?: BaseQueryParams): Promise<T>;
getOne<T = M>(id: string, options?: CommonOptions): Promise<T>;
/**

@@ -349,3 +336,5 @@ * Creates a new item.

*/
create<T = M>(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
create<T = M>(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -356,7 +345,13 @@ * Updates an existing item by its id.

*/
update<T = M>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = M>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**
* Deletes an existing item by its id.
*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(batchSize?: number, options?: ListOptions): Promise<Array<T>>;
}

@@ -366,14 +361,8 @@ interface AdminAuthResponse {

token: string;
admin: Admin;
admin: AdminModel;
}
declare class AdminService extends CrudService<Admin> {
declare class AdminService extends CrudService<AdminModel> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Admin;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -389,3 +378,5 @@ // ---------------------------------------------------------------

*/
update<T = Admin>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = AdminModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -397,3 +388,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -412,4 +403,9 @@ // Auth handlers

*/
authWithPassword(email: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authWithPassword(email: string, password: string, options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authWithPassword(email, password, options?).
*/
authWithPassword(email: string, password: string, body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Refreshes the current admin authenticated instance and

@@ -420,23 +416,26 @@ * returns a new token and admin data.

*/
authRefresh(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authRefresh(options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh(body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Sends admin password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms admin password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare class ExternalAuth extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @inheritdoc
* @deprecated
* Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).
*/
$load(data: {
[key: string]: any;
}): void;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
}

@@ -512,5 +511,11 @@ type UnsubscribeFunc = () => Promise<void>;

}
interface RecordAuthResponse<T = Record> {
interface RecordAuthResponse<T = RecordModel> {
// The signed PocketBase auth record.
record: T;
// The PocketBase record auth token.
//
// If you are looking for the OAuth2 access and refresh tokens
// they are available under the `meta.accessToken` and `meta.refreshToken` props.
token: string;
// Auth meta data usually filled when OAuth2 is used.
meta?: {

@@ -533,3 +538,3 @@ [key: string]: any;

}
interface RecordSubscription<T = Record> {
interface RecordSubscription<T = RecordModel> {
action: string; // eg. create, update, delete

@@ -539,3 +544,3 @@ record: T;

type OAuth2UrlCallback = (url: string) => void | Promise<void>;
interface OAuth2AuthConfig {
interface OAuth2AuthConfig extends SendOptions {
// the name of the OAuth2 provider (eg. "google")

@@ -552,9 +557,5 @@ provider: string;

// optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)
query?: RecordQueryParams;
// optional body params to send with the PocketBase auth request
body?: {
[key: string]: any;
};
query?: RecordOptions;
}
declare class RecordService extends CrudService<Record> {
declare class RecordService extends CrudService<RecordModel> {
readonly collectionIdOrName: string;

@@ -565,8 +566,2 @@ constructor(client: Client, collectionIdOrName: string);

*/
decode<T = Record>(data: {
[key: string]: any;
}): T;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -585,7 +580,7 @@ /**

*/
subscribeOne<T = Record>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribeOne<T = RecordModel>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**
* @deprecated This form of subscribe is deprecated. Please use `subscribe("*", callback)`.
*/
subscribe<T = Record>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -604,3 +599,3 @@ * Subscribe to realtime changes to the specified topic ("*" or record id).

*/
subscribe<T = Record>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -620,23 +615,25 @@ * Unsubscribe from all subscriptions of the specified topic

*/
getFullList<T = Record>(queryParams?: RecordFullListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(options?: RecordFullListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getFullList<T = Record>(batch?: number, queryParams?: RecordListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(batch?: number, options?: RecordListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getList<T = Record>(page?: number, perPage?: number, queryParams?: RecordListQueryParams): Promise<ListResult<T>>;
getList<T = RecordModel>(page?: number, perPage?: number, options?: RecordListOptions): Promise<ListResult<T>>;
/**
* @inheritdoc
*/
getFirstListItem<T = Record>(filter: string, queryParams?: RecordListQueryParams): Promise<T>;
getFirstListItem<T = RecordModel>(filter: string, options?: RecordListOptions): Promise<T>;
/**
* @inheritdoc
*/
getOne<T = Record>(id: string, queryParams?: RecordQueryParams): Promise<T>;
getOne<T = RecordModel>(id: string, options?: RecordOptions): Promise<T>;
/**
* @inheritdoc
*/
create<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
create<T = RecordModel>(bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -648,3 +645,5 @@ * @inheritdoc

*/
update<T = Record>(id: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
update<T = RecordModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -656,3 +655,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -664,7 +663,7 @@ // Auth handlers

*/
protected authResponse<T = Record>(responseData: any): RecordAuthResponse<T>;
protected authResponse<T = RecordModel>(responseData: any): RecordAuthResponse<T>;
/**
* Returns all available collection auth methods.
*/
listAuthMethods(queryParams?: BaseQueryParams): Promise<AuthMethodsList>;
listAuthMethods(options?: CommonOptions): Promise<AuthMethodsList>;
/**

@@ -678,4 +677,9 @@ * Authenticate a single auth collection record via its username/email and password.

*/
authWithPassword<T = Record>(usernameOrEmail: string, password: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithPassword(usernameOrEmail, password, options?).
*/
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Authenticate a single auth collection record with OAuth2 code.

@@ -691,4 +695,13 @@ *

*/
authWithOAuth2Code<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {}, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).
*/
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* @deprecated This form of authWithOAuth2 is deprecated.

@@ -699,7 +712,7 @@ *

*/
authWithOAuth2<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
authWithOAuth2<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, bodyParams?: {
[key: string]: any;
}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
}, queryParams?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**

@@ -736,3 +749,3 @@ * Authenticate a single auth collection record with OAuth2

*/
authWithOAuth2<T = Record>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
authWithOAuth2<T = RecordModel>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
/**

@@ -744,35 +757,70 @@ * Refreshes the current authenticated record instance and

*/
authRefresh<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authRefresh<T = RecordModel>(options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh<T = RecordModel>(body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Sends auth record password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends auth record verification email request.
*/
requestVerification(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestVerification(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestVerification(email, options?).
*/
requestVerification(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record email verification request.
*/
confirmVerification(verificationToken: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmVerification(verificationToken: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmVerification(verificationToken, options?).
*/
confirmVerification(verificationToken: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends an email change request to the authenticated record model.
*/
requestEmailChange(newEmail: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestEmailChange(newEmail: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestEmailChange(newEmail, options?).
*/
requestEmailChange(newEmail: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record's new email address.
*/
confirmEmailChange(emailChangeToken: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmEmailChange(emailChangeToken: string, password: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmEmailChange(emailChangeToken, password, options?).
*/
confirmEmailChange(emailChangeToken: string, password: string, body?: any, query?: any): Promise<boolean>;
/**
* Lists all linked external auth providers for the specified auth record.
*/
listExternalAuths(recordId: string, queryParams?: BaseQueryParams): Promise<Array<ExternalAuth>>;
listExternalAuths(recordId: string, options?: CommonOptions): Promise<Array<ExternalAuthModel>>;
/**
* Unlink a single external auth provider from the specified auth record.
*/
unlinkExternalAuth(recordId: string, provider: string, queryParams?: BaseQueryParams): Promise<boolean>;
unlinkExternalAuth(recordId: string, provider: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -786,70 +834,6 @@ // very rudimentary url query params replacement because at the moment

}
declare class SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
};
constructor(data?: {
[key: string]: any;
});
}
declare class Collection extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule: null | string;
viewRule: null | string;
createRule: null | string;
updateRule: null | string;
deleteRule: null | string;
options: {
[key: string]: any;
};
declare class CollectionService extends CrudService<CollectionModel> {
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* @deprecated Please use $isBase instead.
*/
get isBase(): boolean;
/**
* Checks if the current model is "base" collection.
*/
get $isBase(): boolean;
/**
* @deprecated Please use $isAuth instead.
*/
get isAuth(): boolean;
/**
* Checks if the current model is "auth" collection.
*/
get $isAuth(): boolean;
/**
* @deprecated Please use $isView instead.
*/
get isView(): boolean;
/**
* Checks if the current model is "view" collection.
*/
get $isView(): boolean;
}
declare class CollectionService extends CrudService<Collection> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Collection;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -863,23 +847,4 @@ /**

*/
import(collections: Array<Collection>, deleteMissing?: boolean, queryParams?: BaseQueryParams): Promise<true>;
import(collections: Array<CollectionModel>, deleteMissing?: boolean, options?: CommonOptions): Promise<true>;
}
declare class LogRequest extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
interface HourlyStats {

@@ -893,11 +858,11 @@ total: number;

*/
getRequestsList(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<LogRequest>>;
getRequestsList(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<LogRequestModel>>;
/**
* Returns a single logged request by its id.
*/
getRequest(id: string, queryParams?: BaseQueryParams): Promise<LogRequest>;
getRequest(id: string, options?: CommonOptions): Promise<LogRequestModel>;
/**
* Returns request logs statistics.
*/
getRequestsStats(queryParams?: LogStatsQueryParams): Promise<Array<HourlyStats>>;
getRequestsStats(options?: LogStatsOptions): Promise<Array<HourlyStats>>;
}

@@ -915,3 +880,3 @@ interface HealthCheckResponse {

*/
check(queryParams?: BaseQueryParams): Promise<HealthCheckResponse>;
check(options?: CommonOptions): Promise<HealthCheckResponse>;
}

@@ -922,7 +887,9 @@ declare class FileService extends BaseService {

*/
getUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
getUrl(record: Pick<{
[key: string]: any;
}, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileOptions): string;
/**
* Requests a new private file access token for the current auth model (admin or record).
*/
getToken(queryParams?: BaseQueryParams): Promise<string>;
getToken(options?: CommonOptions): Promise<string>;
}

@@ -938,15 +905,15 @@ interface BackupFileInfo {

*/
getFullList(queryParams?: BaseQueryParams): Promise<Array<BackupFileInfo>>;
getFullList(options?: CommonOptions): Promise<Array<BackupFileInfo>>;
/**
* Initializes a new backup.
*/
create(basename: string, queryParams?: BaseQueryParams): Promise<boolean>;
create(basename: string, options?: CommonOptions): Promise<boolean>;
/**
* Deletes a single backup file.
*/
delete(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(key: string, options?: CommonOptions): Promise<boolean>;
/**
* Initializes an app data restore from an existing backup.
*/
restore(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
restore(key: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -960,9 +927,2 @@ * Builds a download url for a single existing backup using an

}
interface SendOptions extends RequestInit {
headers?: {
[key: string]: string;
};
body?: any;
params?: BaseQueryParams;
}
interface BeforeSendResult {

@@ -1096,3 +1056,3 @@ [key: string]: any;

*/
cancelRequest(cancelKey: string): Client;
cancelRequest(requestKey: string): Client;
/**

@@ -1106,2 +1066,18 @@ * Cancels all pending requests.

/**
* Legacy alias of `pb.files.getUrl()`.
*/
/**
* Legacy alias of `pb.files.getUrl()`.
*/
getFileUrl(record: Pick<{
[key: string]: any;
}, 'id' | 'collectionId' | 'collectionName'>, filename: string, queryParams?: FileOptions): string;
/**
* Builds a full client url by safely concatenating the provided path.
*/
/**
* Builds a full client url by safely concatenating the provided path.
*/
buildUrl(path: string): string;
/**
* Sends an api http request.

@@ -1112,18 +1088,44 @@ */

*/
send<T = any>(path: string, reqOptions: SendOptions): Promise<T>;
send<T = any>(path: string, options: SendOptions): Promise<T>;
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
getFileUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
private initSendOptions;
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
buildUrl(path: string): string;
private convertToFormDataIfNeeded;
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
private hasBlobField;
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
private getHeader;
/**
* Loosely checks if the specified body is a FormData instance.

@@ -1143,2 +1145,2 @@ */

}
export { SendOptions, BeforeSendResult, Client as default };
export { BeforeSendResult, Client as default };

@@ -1,2 +0,2 @@

"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}var __assign=function(){return __assign=Object.assign||function __assign(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}function __generator(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function verb(a){return function(c){return function step(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}var e,t=function(e){function ClientResponseError(t){var n,i,o,r,s=this;return(s=e.call(this,"ClientResponseError")||this).url="",s.status=0,s.response={},s.isAbort=!1,s.originalError=null,Object.setPrototypeOf(s,ClientResponseError.prototype),null!==t&&"object"==typeof t&&(s.url="string"==typeof t.url?t.url:"",s.status="number"==typeof t.status?t.status:0,s.isAbort=!!t.isAbort,s.originalError=t.originalError,null!==t.response&&"object"==typeof t.response?s.response=t.response:null!==t.data&&"object"==typeof t.data?s.response=t.data:s.response={}),s.originalError||t instanceof ClientResponseError||(s.originalError=t),"undefined"!=typeof DOMException&&t instanceof DOMException&&(s.isAbort=!0),s.name="ClientResponseError "+s.status,s.message=null===(n=s.response)||void 0===n?void 0:n.message,s.message||(s.isAbort?s.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(r=null===(o=null===(i=s.originalError)||void 0===i?void 0:i.cause)||void 0===o?void 0:o.message)||void 0===r?void 0:r.includes("ECONNREFUSED ::1"))?s.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":s.message="Something went wrong while processing your request."),s}return __extends(ClientResponseError,e),Object.defineProperty(ClientResponseError.prototype,"data",{get:function(){return this.response},enumerable:!1,configurable:!0}),ClientResponseError.prototype.toJSON=function(){return __assign({},this)},ClientResponseError}(Error),n=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(e,t,i){var o=Object.assign({},i||{}),r=o.encode||defaultEncode;if(!n.test(e))throw new TypeError("argument name is invalid");var s=r(t);if(s&&!n.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(null!=o.maxAge){var c=o.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(o.domain){if(!n.test(o.domain))throw new TypeError("option domain is invalid");a+="; Domain="+o.domain}if(o.path){if(!n.test(o.path))throw new TypeError("option path is invalid");a+="; Path="+o.path}if(o.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(o.expires)||isNaN(o.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.priority)switch("string"==typeof o.priority?o.priority.toLowerCase():o.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}function getTokenPayload(t){if(t)try{var n=decodeURIComponent(e(t.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)||{}}catch(e){}return{}}e="function"==typeof atob?atob:function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,o=0,r=0,s="";i=t.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};var i=function(){function BaseModel(e){void 0===e&&(e={}),this.$load(e||{})}return BaseModel.prototype.load=function(e){return this.$load(e)},BaseModel.prototype.$load=function(e){for(var t=0,n=Object.entries(e);t<n.length;t++){var i=n[t],o=i[0],r=i[1];this[o]=r}this.id=void 0!==e.id?e.id:"",this.created=void 0!==e.created?e.created:"",this.updated=void 0!==e.updated?e.updated:""},Object.defineProperty(BaseModel.prototype,"$isNew",{get:function(){return!this.id},enumerable:!1,configurable:!0}),BaseModel.prototype.clone=function(){return this.$clone()},BaseModel.prototype.$clone=function(){var e="function"==typeof structuredClone?structuredClone(this):JSON.parse(JSON.stringify(this));return new this.constructor(e)},BaseModel.prototype.export=function(){return this.$export()},BaseModel.prototype.$export=function(){return"function"==typeof structuredClone?structuredClone(this):Object.assign({},this)},BaseModel}(),o=function(e){function Record(){return null!==e&&e.apply(this,arguments)||this}return __extends(Record,e),Record.prototype.$load=function(t){e.prototype.$load.call(this,t),this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.collectionName="string"==typeof t.collectionName?t.collectionName:"",this._loadExpand(t.expand)},Record.prototype._loadExpand=function(e){for(var t in e=e||{},this.expand={},e)Array.isArray(e[t])?this.expand[t]=e[t].map((function(e){return new Record(e||{})})):this.expand[t]=new Record(e[t]||{})},Record}(i),r=function(e){function Admin(){return null!==e&&e.apply(this,arguments)||this}return __extends(Admin,e),Admin.prototype.$load=function(t){e.prototype.$load.call(this,t),this.avatar="number"==typeof t.avatar?t.avatar:0,this.email="string"==typeof t.email?t.email:""},Admin}(i),s="pb_auth",a=function(e){function LocalAuthStore(t){void 0===t&&(t="pocketbase_auth");var n=e.call(this)||this;return n.storageFallback={},n.storageKey=t,n}return __extends(LocalAuthStore,e),Object.defineProperty(LocalAuthStore.prototype,"token",{get:function(){return(this._storageGet(this.storageKey)||{}).token||""},enumerable:!1,configurable:!0}),Object.defineProperty(LocalAuthStore.prototype,"model",{get:function(){var e,t=this._storageGet(this.storageKey)||{};return null===t||"object"!=typeof t||null===t.model||"object"!=typeof t.model?null:void 0===(null===(e=t.model)||void 0===e?void 0:e.collectionId)?new r(t.model):new o(t.model)},enumerable:!1,configurable:!0}),LocalAuthStore.prototype.save=function(t,n){this._storageSet(this.storageKey,{token:t,model:n}),e.prototype.save.call(this,t,n)},LocalAuthStore.prototype.clear=function(){this._storageRemove(this.storageKey),e.prototype.clear.call(this)},LocalAuthStore.prototype._storageGet=function(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]},LocalAuthStore.prototype._storageSet=function(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var n=t;"string"!=typeof t&&(n=JSON.stringify(t)),window.localStorage.setItem(e,n)}else this.storageFallback[e]=t},LocalAuthStore.prototype._storageRemove=function(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]},LocalAuthStore}(function(){function BaseAuthStore(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}return Object.defineProperty(BaseAuthStore.prototype,"token",{get:function(){return this.baseToken},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"model",{get:function(){return this.baseModel},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"isValid",{get:function(){return!function isTokenExpired(e,t){void 0===t&&(t=0);var n=getTokenPayload(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}(this.token)},enumerable:!1,configurable:!0}),BaseAuthStore.prototype.save=function(e,t){this.baseToken=e||"",this.baseModel=null!==t&&"object"==typeof t?void 0!==t.collectionId?new o(t):new r(t):null,this.triggerChange()},BaseAuthStore.prototype.clear=function(){this.baseToken="",this.baseModel=null,this.triggerChange()},BaseAuthStore.prototype.loadFromCookie=function(e,t){void 0===t&&(t=s);var n=function cookieParse(e,t){var n={};if("string"!=typeof e)return n;for(var i=Object.assign({},t||{}).decode||defaultDecode,o=0;o<e.length;){var r=e.indexOf("=",o);if(-1===r)break;var s=e.indexOf(";",o);if(-1===s)s=e.length;else if(s<r){o=e.lastIndexOf(";",r-1)+1;continue}var a=e.slice(o,r).trim();if(void 0===n[a]){var c=e.slice(r+1,s).trim();34===c.charCodeAt(0)&&(c=c.slice(1,-1));try{n[a]=i(c)}catch(e){n[a]=c}}o=s+1}return n}(e||"")[t]||"",i={};try{(null===typeof(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))&&(i={})}catch(e){}this.save(i.token||"",i.model||null)},BaseAuthStore.prototype.exportToCookie=function(e,t){var n,i,r;void 0===t&&(t=s);var a={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},c=getTokenPayload(this.token);(null==c?void 0:c.exp)?a.expires=new Date(1e3*c.exp):a.expires=new Date("1970-01-01"),e=Object.assign({},a,e);var u={token:this.token,model:(null===(n=this.model)||void 0===n?void 0:n.export())||null},l=cookieSerialize(t,JSON.stringify(u),e),d="undefined"!=typeof Blob?new Blob([l]).size:l.length;return u.model&&d>4096&&(u.model={id:null===(i=null==u?void 0:u.model)||void 0===i?void 0:i.id,email:null===(r=null==u?void 0:u.model)||void 0===r?void 0:r.email},this.model instanceof o&&(u.model.username=this.model.username,u.model.verified=this.model.verified,u.model.collectionId=this.model.collectionId),l=cookieSerialize(t,JSON.stringify(u),e)),l},BaseAuthStore.prototype.onChange=function(e,t){var n=this;return void 0===t&&(t=!1),this._onChangeCallbacks.push(e),t&&e(this.token,this.model),function(){for(var t=n._onChangeCallbacks.length-1;t>=0;t--)if(n._onChangeCallbacks[t]==e)return delete n._onChangeCallbacks[t],void n._onChangeCallbacks.splice(t,1)}},BaseAuthStore.prototype.triggerChange=function(){for(var e=0,t=this._onChangeCallbacks;e<t.length;e++){var n=t[e];n&&n(this.token,this.model)}},BaseAuthStore}()),c=function c(e){this.client=e},u=function(e){function SettingsService(){return null!==e&&e.apply(this,arguments)||this}return __extends(SettingsService,e),SettingsService.prototype.getAll=function(e){return void 0===e&&(e={}),this.client.send("/api/settings",{method:"GET",params:e}).then((function(e){return e||{}}))},SettingsService.prototype.update=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send("/api/settings",{method:"PATCH",params:t,body:e}).then((function(e){return e||{}}))},SettingsService.prototype.testS3=function(e,t){void 0===e&&(e="storage"),void 0===t&&(t={});var n={filesystem:e};return this.client.send("/api/settings/test/s3",{method:"POST",params:t,body:n}).then((function(){return!0}))},SettingsService.prototype.testEmail=function(e,t,n){void 0===n&&(n={});var i={email:e,template:t};return this.client.send("/api/settings/test/email",{method:"POST",params:n,body:i}).then((function(){return!0}))},SettingsService.prototype.generateAppleClientSecret=function(e,t,n,i,o,r,s){return void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({clientId:e,teamId:t,keyId:n,privateKey:i,duration:o},r),this.client.send("/api/settings/apple/generate-client-secret",{method:"POST",params:s,body:r})},SettingsService}(c),l=function l(e,t,n,i,o){this.page=e>0?e:1,this.perPage=t>=0?t:0,this.totalItems=n>=0?n:0,this.totalPages=i>=0?i:0,this.items=o||[]},d=function(e){function CrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CrudService,e),CrudService.prototype.getFullList=function(e,t){if("number"==typeof e)return this._getFullList(this.baseCrudPath,e,t);var n=Object.assign({},e,t),i=500;return n.batch&&(i=n.batch,delete n.batch),this._getFullList(this.baseCrudPath,i,n)},CrudService.prototype.getList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),this._getList(this.baseCrudPath,e,t,n)},CrudService.prototype.getFirstListItem=function(e,t){return void 0===t&&(t={}),this._getFirstListItem(this.baseCrudPath,e,t)},CrudService.prototype.getOne=function(e,t){return void 0===t&&(t={}),this._getOne(this.baseCrudPath,e,t)},CrudService.prototype.create=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this._create(this.baseCrudPath,e,t)},CrudService.prototype.update=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),this._update(this.baseCrudPath,e,t,n)},CrudService.prototype.delete=function(e,t){return void 0===t&&(t={}),this._delete(this.baseCrudPath,e,t)},CrudService}(function(e){function BaseCrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BaseCrudService,e),BaseCrudService.prototype._getFullList=function(e,t,n){var i=this;void 0===t&&(t=500),void 0===n&&(n={}),n=Object.assign({skipTotal:1},n);var o=[],request=function(r){return __awaiter(i,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this._getList(e,r,t||500,n).then((function(e){var t=e.items;return o=o.concat(t),t.length==e.perPage?request(r+1):o}))]}))}))};return request(1)},BaseCrudService.prototype._getList=function(e,t,n,i){var o=this;return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),i=Object.assign({page:t,perPage:n},i),this.client.send(e,{method:"GET",params:i}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=e.items||[];for(var n=0,i=e.items;n<i.length;n++){var r=i[n];t.push(o.decode(r))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},BaseCrudService.prototype._getOne=function(e,t,n){var i=this;return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"GET",params:n}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._getFirstListItem=function(e,n,i){return void 0===i&&(i={}),i=Object.assign({filter:n,skipTotal:1,$cancelKey:"one_by_filter_"+e+"_"+n},i),this._getList(e,1,1,i).then((function(e){var n;if(!(null===(n=null==e?void 0:e.items)||void 0===n?void 0:n.length))throw new t({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))},BaseCrudService.prototype._create=function(e,t,n){var i=this;return void 0===t&&(t={}),void 0===n&&(n={}),this.client.send(e,{method:"POST",params:n,body:t}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._update=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"PATCH",params:i,body:n}).then((function(e){return o.decode(e)}))},BaseCrudService.prototype._delete=function(e,t,n){return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},BaseCrudService}(c)),h=function(e){function AdminService(){return null!==e&&e.apply(this,arguments)||this}return __extends(AdminService,e),AdminService.prototype.decode=function(e){return new r(e)},Object.defineProperty(AdminService.prototype,"baseCrudPath",{get:function(){return"/api/admins"},enumerable:!1,configurable:!0}),AdminService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n;return o.client.authStore.model&&void 0===(null===(t=o.client.authStore.model)||void 0===t?void 0:t.collectionId)&&(null===(n=o.client.authStore.model)||void 0===n?void 0:n.id)===(null==e?void 0:e.id)&&o.client.authStore.save(o.client.authStore.token,e),e}))},AdminService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o;return e&&i.client.authStore.model&&void 0===(null===(n=i.client.authStore.model)||void 0===n?void 0:n.collectionId)&&(null===(o=i.client.authStore.model)||void 0===o?void 0:o.id)===t&&i.client.authStore.clear(),e}))},AdminService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})},AdminService.prototype.authWithPassword=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCrudPath+"/auth-with-password",{method:"POST",params:i,body:n}).then(this.authResponse.bind(this))},AdminService.prototype.authRefresh=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/auth-refresh",{method:"POST",params:t,body:e}).then(this.authResponse.bind(this))},AdminService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCrudPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},AdminService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCrudPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},AdminService}(d),p=function(e){function ExternalAuth(){return null!==e&&e.apply(this,arguments)||this}return __extends(ExternalAuth,e),ExternalAuth.prototype.$load=function(t){e.prototype.$load.call(this,t),this.recordId="string"==typeof t.recordId?t.recordId:"",this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.provider="string"==typeof t.provider?t.provider:"",this.providerId="string"==typeof t.providerId?t.providerId:""},ExternalAuth}(i),v=function(e){function RecordService(t,n){var i=e.call(this,t)||this;return i.collectionIdOrName=n,i}return __extends(RecordService,e),RecordService.prototype.decode=function(e){return new o(e)},Object.defineProperty(RecordService.prototype,"baseCrudPath",{get:function(){return this.baseCollectionPath+"/records"},enumerable:!1,configurable:!0}),Object.defineProperty(RecordService.prototype,"baseCollectionPath",{get:function(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)},enumerable:!1,configurable:!0}),RecordService.prototype.subscribeOne=function(e,t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)]}))}))},RecordService.prototype.subscribe=function(e,t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(i){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName,e)];if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");return n=this.collectionIdOrName,"*"!==e&&(n+="/"+e),[2,this.client.realtime.subscribe(n,t)]}))}))},RecordService.prototype.unsubscribe=function(e){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return"*"===e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName)]:e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e)]:[2,this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)]}))}))},RecordService.prototype.getFullList=function(t,n){if("number"==typeof t)return e.prototype.getFullList.call(this,t,n);var i=Object.assign({},t,n);return e.prototype.getFullList.call(this,i)},RecordService.prototype.getList=function(t,n,i){return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),e.prototype.getList.call(this,t,n,i)},RecordService.prototype.getFirstListItem=function(t,n){return void 0===n&&(n={}),e.prototype.getFirstListItem.call(this,t,n)},RecordService.prototype.getOne=function(t,n){return void 0===n&&(n={}),e.prototype.getOne.call(this,t,n)},RecordService.prototype.create=function(t,n){return void 0===t&&(t={}),void 0===n&&(n={}),e.prototype.create.call(this,t,n)},RecordService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n,i;return(null===(t=o.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(n=o.client.authStore.model)||void 0===n?void 0:n.collectionId)!==o.collectionIdOrName&&(null===(i=o.client.authStore.model)||void 0===i?void 0:i.collectionName)!==o.collectionIdOrName||o.client.authStore.save(o.client.authStore.token,e),e}))},RecordService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o,r;return!e||(null===(n=i.client.authStore.model)||void 0===n?void 0:n.id)!==t||(null===(o=i.client.authStore.model)||void 0===o?void 0:o.collectionId)!==i.collectionIdOrName&&(null===(r=i.client.authStore.model)||void 0===r?void 0:r.collectionName)!==i.collectionIdOrName||i.client.authStore.clear(),e}))},RecordService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})},RecordService.prototype.listAuthMethods=function(e){return void 0===e&&(e={}),this.client.send(this.baseCollectionPath+"/auth-methods",{method:"GET",params:e}).then((function(e){return Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})}))},RecordService.prototype.authWithPassword=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCollectionPath+"/auth-with-password",{method:"POST",params:i,body:n}).then((function(e){return o.authResponse(e)}))},RecordService.prototype.authWithOAuth2Code=function(e,t,n,i,o,r,s){var a=this;return void 0===o&&(o={}),void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({provider:e,code:t,codeVerifier:n,redirectUrl:i,createData:o},r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",{method:"POST",params:s,body:r}).then((function(e){return a.authResponse(e)}))},RecordService.prototype.authWithOAuth2=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s=this;return __generator(this,(function(a){switch(a.label){case 0:return e.length>1||"string"==typeof(null==e?void 0:e[0])?(console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),[2,this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{})]):(n=(null==e?void 0:e[0])||{},[4,this.listAuthMethods()]);case 1:if(i=a.sent(),!(o=i.authProviders.find((function(e){return e.name===n.provider}))))throw new t(new Error('Missing or invalid provider "'.concat(n.provider,'".')));return r=this.client.buildUrl("/api/oauth2-redirect"),[2,new Promise((function(e,i){return __awaiter(s,void 0,void 0,(function(){var s,a,c,u,l,d=this;return __generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this.client.realtime.subscribe("@oauth2",(function(a){return __awaiter(d,void 0,void 0,(function(){var c,u,l;return __generator(this,(function(d){switch(d.label){case 0:c=this.client.realtime.clientId,d.label=1;case 1:if(d.trys.push([1,3,,4]),s(),!a.state||c!==a.state)throw new Error("State parameters don't match.");return[4,this.authWithOAuth2Code(o.name,a.code,o.codeVerifier,r,n.createData,n.body,n.query)];case 2:return u=d.sent(),e(u),[3,4];case 3:return l=d.sent(),i(new t(l)),[3,4];case 4:return[2]}}))}))}))];case 1:return s=h.sent(),a={state:this.client.realtime.clientId},(null===(l=n.scopes)||void 0===l?void 0:l.length)&&(a.scope=n.scopes.join(" ")),c=this._replaceQueryParams(o.authUrl+r,a),[4,n.urlCallback?n.urlCallback(c):this._defaultUrlCallback(c)];case 2:return h.sent(),[3,4];case 3:return u=h.sent(),i(new t(u)),[3,4];case 4:return[2]}}))}))}))]}}))}))},RecordService.prototype.authRefresh=function(e,t){var n=this;return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCollectionPath+"/auth-refresh",{method:"POST",params:t,body:e}).then((function(e){return n.authResponse(e)}))},RecordService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCollectionPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},RecordService.prototype.requestVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({token:e},t),this.client.send(this.baseCollectionPath+"/confirm-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.requestEmailChange=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({newEmail:e},t),this.client.send(this.baseCollectionPath+"/request-email-change",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmEmailChange=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({token:e,password:t},n),this.client.send(this.baseCollectionPath+"/confirm-email-change",{method:"POST",params:i,body:n}).then((function(){return!0}))},RecordService.prototype.listExternalAuths=function(e,t){return void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",{method:"GET",params:t}).then((function(e){var t=[];if(Array.isArray(e))for(var n=0,i=e;n<i.length;n++){var o=i[n];t.push(new p(o))}return t}))},RecordService.prototype.unlinkExternalAuth=function(e,t,n){return void 0===n&&(n={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},RecordService.prototype._replaceQueryParams=function(e,t){void 0===t&&(t={});var n=e,i="";e.indexOf("?")>=0&&(n=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));for(var o={},r=0,s=i.split("&");r<s.length;r++){var a=s[r];if(""!=a){var c=a.split("=");o[decodeURIComponent(c[0].replace(/\+/g," "))]=decodeURIComponent((c[1]||"").replace(/\+/g," "))}}for(var u in t)t.hasOwnProperty(u)&&(null==t[u]?delete o[u]:o[u]=t[u]);for(var u in i="",o)o.hasOwnProperty(u)&&(""!=i&&(i+="&"),i+=encodeURIComponent(u.replace(/%20/g,"+"))+"="+encodeURIComponent(o[u].replace(/%20/g,"+")));return""!=i?n+"?"+i:n},RecordService.prototype._defaultUrlCallback=function(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new t(new Error("Not in a browser context - please pass a custom urlCallback function."));var n=1024,i=768,o=window.innerWidth,r=window.innerHeight,s=o/2-(n=n>o?o:n)/2,a=r/2-(i=i>r?r:i)/2;window.open(e,"oauth2-popup","width="+n+",height="+i+",top="+a+",left="+s+",resizable,menubar=no")},RecordService}(d),f=function f(e){void 0===e&&(e={}),this.id=void 0!==e.id?e.id:"",this.name=void 0!==e.name?e.name:"",this.type=void 0!==e.type?e.type:"text",this.system=!!e.system,this.required=!!e.required,this.options="object"==typeof e.options&&null!==e.options?e.options:{}},m=function(e){function Collection(){return null!==e&&e.apply(this,arguments)||this}return __extends(Collection,e),Collection.prototype.$load=function(t){e.prototype.$load.call(this,t),this.system=!!t.system,this.name="string"==typeof t.name?t.name:"",this.type="string"==typeof t.type?t.type:"base",this.options=void 0!==t.options&&null!==t.options?t.options:{},this.indexes=Array.isArray(t.indexes)?t.indexes:[],this.listRule="string"==typeof t.listRule?t.listRule:null,this.viewRule="string"==typeof t.viewRule?t.viewRule:null,this.createRule="string"==typeof t.createRule?t.createRule:null,this.updateRule="string"==typeof t.updateRule?t.updateRule:null,this.deleteRule="string"==typeof t.deleteRule?t.deleteRule:null,t.schema=Array.isArray(t.schema)?t.schema:[],this.schema=[];for(var n=0,i=t.schema;n<i.length;n++){var o=i[n];this.schema.push(new f(o))}},Object.defineProperty(Collection.prototype,"isBase",{get:function(){return this.$isBase},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isBase",{get:function(){return"base"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isAuth",{get:function(){return this.$isAuth},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isAuth",{get:function(){return"auth"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isView",{get:function(){return this.$isView},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isView",{get:function(){return"view"===this.type},enumerable:!1,configurable:!0}),Collection}(i),b=function(e){function CollectionService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CollectionService,e),CollectionService.prototype.decode=function(e){return new m(e)},Object.defineProperty(CollectionService.prototype,"baseCrudPath",{get:function(){return"/api/collections"},enumerable:!1,configurable:!0}),CollectionService.prototype.import=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this.client.send(this.baseCrudPath+"/import",{method:"PUT",params:n,body:{collections:e,deleteMissing:t}}).then((function(){return!0}))]}))}))},CollectionService}(d),y=function(e){function LogRequest(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogRequest,e),LogRequest.prototype.$load=function(t){e.prototype.$load.call(this,t),t.remoteIp=t.remoteIp||t.ip,this.url="string"==typeof t.url?t.url:"",this.method="string"==typeof t.method?t.method:"GET",this.status="number"==typeof t.status?t.status:200,this.auth="string"==typeof t.auth?t.auth:"guest",this.remoteIp="string"==typeof t.remoteIp?t.remoteIp:"",this.userIp="string"==typeof t.userIp?t.userIp:"",this.referer="string"==typeof t.referer?t.referer:"",this.userAgent="string"==typeof t.userAgent?t.userAgent:"",this.meta="object"==typeof t.meta&&null!==t.meta?t.meta:{}},LogRequest}(i),g=function(e){function LogService(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogService,e),LogService.prototype.getRequestsList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),n=Object.assign({page:e,perPage:t},n),this.client.send("/api/logs/requests",{method:"GET",params:n}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=(null==e?void 0:e.items)||[];for(var n=0,i=e.items;n<i.length;n++){var o=i[n];t.push(new y(o))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},LogService.prototype.getRequest=function(e,t){return void 0===t&&(t={}),this.client.send("/api/logs/requests/"+encodeURIComponent(e),{method:"GET",params:t}).then((function(e){return new y(e)}))},LogService.prototype.getRequestsStats=function(e){return void 0===e&&(e={}),this.client.send("/api/logs/requests/stats",{method:"GET",params:e}).then((function(e){return e}))},LogService}(c),S=function(e){function RealtimeService(){var t=null!==e&&e.apply(this,arguments)||this;return t.clientId="",t.eventSource=null,t.subscriptions={},t.lastSentTopics=[],t.maxConnectTimeout=15e3,t.reconnectAttempts=0,t.maxReconnectAttempts=1/0,t.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],t.pendingConnects=[],t}return __extends(RealtimeService,e),Object.defineProperty(RealtimeService.prototype,"isConnected",{get:function(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length},enumerable:!1,configurable:!0}),RealtimeService.prototype.subscribe=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o=this;return __generator(this,(function(r){switch(r.label){case 0:if(!e)throw new Error("topic must be set.");return i=function(e){var n,i=e;try{n=JSON.parse(null==i?void 0:i.data)}catch(e){}t(n||{})},this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(i),this.isConnected?[3,2]:[4,this.connect()];case 1:return r.sent(),[3,5];case 2:return 1!==this.subscriptions[e].length?[3,4]:[4,this.submitSubscriptions()];case 3:return r.sent(),[3,5];case 4:null===(n=this.eventSource)||void 0===n||n.addEventListener(e,i),r.label=5;case 5:return[2,function(){return __awaiter(o,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this.unsubscribeByTopicAndListener(e,i)]}))}))}]}}))}))},RealtimeService.prototype.unsubscribe=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!this.hasSubscriptionListeners(e))return[2];if(e){for(n=0,i=this.subscriptions[e];n<i.length;n++)o=i[n],null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,o);delete this.subscriptions[e]}else this.subscriptions={};return this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3]);case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByPrefix=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s;return __generator(this,(function(a){switch(a.label){case 0:for(i in n=!1,this.subscriptions)if(i.startsWith(e)){for(n=!0,o=0,r=this.subscriptions[i];o<r.length;o++)s=r[o],null===(t=this.eventSource)||void 0===t||t.removeEventListener(i,s);delete this.subscriptions[i]}return n?this.hasSubscriptionListeners()?[4,this.submitSubscriptions()]:[3,2]:[2];case 1:return a.sent(),[3,3];case 2:this.disconnect(),a.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByTopicAndListener=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return[2];for(i=!1,o=this.subscriptions[e].length-1;o>=0;o--)this.subscriptions[e][o]===t&&(i=!0,delete this.subscriptions[e][o],this.subscriptions[e].splice(o,1),null===(n=this.eventSource)||void 0===n||n.removeEventListener(e,t));return i?(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3])):[2];case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.hasSubscriptionListeners=function(e){var t,n;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(var i in this.subscriptions)if(null===(n=this.subscriptions[i])||void 0===n?void 0:n.length)return!0;return!1},RealtimeService.prototype.submitSubscriptions=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(e){return this.clientId?(this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),[2,this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},params:{$cancelKey:this.getSubscriptionsCancelKey()}}).catch((function(e){if(!(null==e?void 0:e.isAbort))throw e}))]):[2]}))}))},RealtimeService.prototype.getSubscriptionsCancelKey=function(){return"realtime_"+this.clientId},RealtimeService.prototype.getNonEmptySubscriptionTopics=function(){var e=[];for(var t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e},RealtimeService.prototype.addAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.removeAllSubscriptionListeners(),this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.addEventListener(e,i)}},RealtimeService.prototype.removeAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.removeEventListener(e,i)}},RealtimeService.prototype.connect=function(){return __awaiter(this,void 0,void 0,(function(){var e=this;return __generator(this,(function(t){return this.reconnectAttempts>0?[2]:[2,new Promise((function(t,n){e.pendingConnects.push({resolve:t,reject:n}),e.pendingConnects.length>1||e.initConnect()}))]}))}))},RealtimeService.prototype.initConnect=function(){var e=this;this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((function(){e.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=function(t){e.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(function(t){var n=t;e.clientId=null==n?void 0:n.lastEventId,e.submitSubscriptions().then((function(){return __awaiter(e,void 0,void 0,(function(){var e;return __generator(this,(function(t){switch(t.label){case 0:e=3,t.label=1;case 1:return this.hasUnsentSubscriptions()&&e>0?(e--,[4,this.submitSubscriptions()]):[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))}))})).then((function(){for(var t=0,n=e.pendingConnects;t<n.length;t++){n[t].resolve()}e.pendingConnects=[],e.reconnectAttempts=0,clearTimeout(e.reconnectTimeoutId),clearTimeout(e.connectTimeoutId)})).catch((function(t){e.clientId="",e.connectErrorHandler(t)}))}))},RealtimeService.prototype.hasUnsentSubscriptions=function(){var e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(var t=0,n=e;t<n.length;t++){var i=n[t];if(!this.lastSentTopics.includes(i))return!0}return!1},RealtimeService.prototype.connectErrorHandler=function(e){var n=this;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(var i=0,o=this.pendingConnects;i<o.length;i++){o[i].reject(new t(e))}return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);var r=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((function(){n.initConnect()}),r)},RealtimeService.prototype.disconnect=function(e){var t;if(void 0===e&&(e=!1),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(var n=0,i=this.pendingConnects;n<i.length;n++){i[n].resolve()}this.pendingConnects=[]}},RealtimeService}(c),w=function(e){function HealthService(){return null!==e&&e.apply(this,arguments)||this}return __extends(HealthService,e),HealthService.prototype.check=function(e){return void 0===e&&(e={}),this.client.send("/api/health",{method:"GET",params:e})},HealthService}(c),C=function(e){function FileService(){return null!==e&&e.apply(this,arguments)||this}return __extends(FileService,e),FileService.prototype.getUrl=function(e,t,n){void 0===n&&(n={});var i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));var o=this.client.buildUrl(i.join("/"));if(Object.keys(n).length){!1===n.download&&delete n.download;var r=new URLSearchParams(n);o+=(o.includes("?")?"&":"?")+r}return o},FileService.prototype.getToken=function(e){return void 0===e&&(e={}),this.client.send("/api/files/token",{method:"POST",params:e}).then((function(e){return(null==e?void 0:e.token)||""}))},FileService}(c),_=function(e){function BackupService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BackupService,e),BackupService.prototype.getFullList=function(e){return void 0===e&&(e={}),this.client.send("/api/backups",{method:"GET",params:e})},BackupService.prototype.create=function(e,t){void 0===t&&(t={});var n={name:e};return this.client.send("/api/backups",{method:"POST",params:t,body:n}).then((function(){return!0}))},BackupService.prototype.delete=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e)),{method:"DELETE",params:t}).then((function(){return!0}))},BackupService.prototype.restore=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e),"/restore"),{method:"POST",params:t}).then((function(){return!0}))},BackupService.prototype.getDownloadUrl=function(e,t){return this.client.buildUrl("/api/backups/".concat(encodeURIComponent(t),"?token=").concat(encodeURIComponent(e)))},BackupService}(c),R=function(){function Client(e,t,n){void 0===e&&(e="/"),void 0===n&&(n="en-US"),this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=n,this.authStore=t||new a,this.admins=new h(this),this.collections=new b(this),this.files=new C(this),this.logs=new g(this),this.settings=new u(this),this.realtime=new S(this),this.health=new w(this),this.backups=new _(this)}return Client.prototype.collection=function(e){return this.recordServices[e]||(this.recordServices[e]=new v(this,e)),this.recordServices[e]},Client.prototype.autoCancellation=function(e){return this.enableAutoCancellation=!!e,this},Client.prototype.cancelRequest=function(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this},Client.prototype.cancelAllRequests=function(){for(var e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this},Client.prototype.send=function(e,n){var i,o,r,s,a,c,u,l;return __awaiter(this,void 0,void 0,(function(){var d,h,p,v,f,m,b,y,g,S=this;return __generator(this,(function(w){switch(w.label){case 0:return d=Object.assign({method:"GET"},n),this.isFormData(d.body)||(d.body&&"string"!=typeof d.body&&(d.body=JSON.stringify(d.body)),void 0===(null===(i=null==d?void 0:d.headers)||void 0===i?void 0:i["Content-Type"])&&(d.headers=Object.assign({},d.headers,{"Content-Type":"application/json"}))),void 0===(null===(o=null==d?void 0:d.headers)||void 0===o?void 0:o["Accept-Language"])&&(d.headers=Object.assign({},d.headers,{"Accept-Language":this.lang})),(null===(r=this.authStore)||void 0===r?void 0:r.token)&&void 0===(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s.Authorization)&&(d.headers=Object.assign({},d.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&!1!==(null===(a=d.params)||void 0===a?void 0:a.$autoCancel)&&(h=(null===(c=d.params)||void 0===c?void 0:c.$cancelKey)||(d.method||"GET")+e,this.cancelRequest(h),p=new AbortController,this.cancelControllers[h]=p,d.signal=p.signal),null===(u=d.params)||void 0===u||delete u.$autoCancel,null===(l=d.params)||void 0===l||delete l.$cancelKey,v=this.buildUrl(e),void 0!==d.params&&((f=this.serializeQueryParams(d.params))&&(v+=(v.includes("?")?"&":"?")+f),delete d.params),this.beforeSend?(y=(b=Object).assign,g=[{}],[4,this.beforeSend(v,d)]):[3,2];case 1:void 0!==(m=y.apply(b,g.concat([w.sent()]))).url||void 0!==m.options?(v=m.url||v,d=m.options||d):Object.keys(m).length&&(d=m,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.")),w.label=2;case 2:return[2,fetch(v,d).then((function(e){return __awaiter(S,void 0,void 0,(function(){var n;return __generator(this,(function(i){switch(i.label){case 0:n={},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.json()];case 2:return n=i.sent(),[3,4];case 3:return i.sent(),[3,4];case 4:return this.afterSend?[4,this.afterSend(e,n)]:[3,6];case 5:n=i.sent(),i.label=6;case 6:if(e.status>=400)throw new t({url:e.url,status:e.status,data:n});return[2,n]}}))}))})).catch((function(e){throw new t(e)}))]}}))}))},Client.prototype.getFileUrl=function(e,t,n){return void 0===n&&(n={}),this.files.getUrl(e,t,n)},Client.prototype.buildUrl=function(e){var t,n=this.baseUrl;return"undefined"==typeof window||!window.location||n.startsWith("https://")||n.startsWith("http://")||(n=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(n+=window.location.pathname||"/",n+=n.endsWith("/")?"":"/"),n+=this.baseUrl),e&&(n+=n.endsWith("/")?"":"/",n+=e.startsWith("/")?e.substring(1):e),n},Client.prototype.isFormData=function(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)},Client.prototype.serializeQueryParams=function(e){var t=[];for(var n in e)if(null!==e[n]){var i=e[n],o=encodeURIComponent(n);if(Array.isArray(i))for(var r=0,s=i;r<s.length;r++){var a=s[r];t.push(o+"="+encodeURIComponent(a))}else i instanceof Date?t.push(o+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(o+"="+encodeURIComponent(JSON.stringify(i))):t.push(o+"="+encodeURIComponent(i))}return t.join("&")},Client}();module.exports=R;
"use strict";function __awaiter(e,t,i,s){return new(i||(i=Promise))((function(n,o){function fulfilled(e){try{step(s.next(e))}catch(e){o(e)}}function rejected(e){try{step(s.throw(e))}catch(e){o(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class ClientResponseError extends Error{constructor(e){var t,i,s,n;super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=null===(t=this.response)||void 0===t?void 0:t.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(n=null===(s=null===(i=this.originalError)||void 0===i?void 0:i.cause)||void 0===s?void 0:s.message)||void 0===n?void 0:n.includes("ECONNREFUSED ::1"))?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return Object.assign({},this)}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,i,s){const n=Object.assign({},s||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(i);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}let t;function getTokenPayload(e){if(e)try{const i=decodeURIComponent(t(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(i)||{}}catch(e){}return{}}t="function"==typeof atob?atob:e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,s,n=0,o=0,r="";s=t.charAt(o++);~s&&(i=n%4?64*i+s:s,n++%4)?r+=String.fromCharCode(255&i>>(-2*n&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return r};const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!function isTokenExpired(e,t=0){let i=getTokenPayload(e);return!(Object.keys(i).length>0&&(!i.exp||i.exp-t>Date.now()/1e3))}(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const i={};if("string"!=typeof e)return i;const s=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n<e.length;){const t=e.indexOf("=",n);if(-1===t)break;let o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<t){n=e.lastIndexOf(";",t-1)+1;continue}const r=e.slice(n,t).trim();if(void 0===i[r]){let n=e.slice(t+1,o).trim();34===n.charCodeAt(0)&&(n=n.slice(1,-1));try{i[r]=s(n)}catch(e){i[r]=n}}n=o+1}return i}(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){var s,n;const o={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=getTokenPayload(this.token);(null==r?void 0:r.exp)?o.expires=new Date(1e3*r.exp):o.expires=new Date("1970-01-01"),e=Object.assign({},o,e);const a={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let l=cookieSerialize(t,JSON.stringify(a),e);const c="undefined"!=typeof Blob?new Blob([l]).size:l.length;if(a.model&&c>4096){a.model={id:null===(s=null==a?void 0:a.model)||void 0===s?void 0:s.id,email:null===(n=null==a?void 0:a.model)||void 0===n?void 0:n.email};const i=["collectionId","username","verified"];for(const e in this.model)i.includes(e)&&(a.model[e]=this.model[e]);l=cookieSerialize(t,JSON.stringify(a),e)}return l}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){let i=t;"string"!=typeof t&&(i=JSON.stringify(t)),window.localStorage.setItem(e,i)}else this.storageFallback[e]=t}_storageRemove(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}testEmail(e,t,i){return i=Object.assign({method:"POST",body:{email:e,template:t}},i),this.client.send("/api/settings/test/email",i).then((()=>!0))}generateAppleClientSecret(e,t,i,s,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:i,privateKey:s,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let i=500;return(t=Object.assign({},e,t)).batch&&(i=t.batch,delete t.batch),this._getFullList(i,t)}getList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send(this.baseCrudPath,i).then((e=>{var t;return e.items=(null===(t=e.items)||void 0===t?void 0:t.map((e=>this.decode(e))))||[],e}))}getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{var t;if(!(null===(t=null==e?void 0:e.items)||void 0===t?void 0:t.length))throw new ClientResponseError({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}getOne(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}update(e,t,i){return i=Object.assign({method:"PATCH",body:t},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),i).then((e=>this.decode(e)))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let i=[],request=s=>__awaiter(this,void 0,void 0,(function*(){return this.getList(s,e||500,t).then((e=>{const t=e.items;return i=i.concat(t),t.length==e.perPage?request(s+1):i}))}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,i,s){const n=void 0!==s;return n||void 0!==i?n?(console.warn(e),t.body=Object.assign({},t.body,i),t.query=Object.assign({},t.query,s),t):t=Object.assign(t,i):t}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)===e.id&&void 0===(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)&&this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s;return t&&(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)===e&&void 0===(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)&&this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(email, pass, options?).",n,i,s),this.client.send(this.baseCrudPath+"/auth-with-password",n).then(this.authResponse.bind(this))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",i).then(this.authResponse.bind(this))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCrudPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}subscribeOne(e,t){return __awaiter(this,void 0,void 0,(function*(){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),this.client.realtime.subscribe(this.collectionIdOrName,e);if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");let i=this.collectionIdOrName;return"*"!==e&&(i+="/"+e),this.client.realtime.subscribe(i,t)}))}unsubscribe(e){return __awaiter(this,void 0,void 0,(function*(){return"*"===e?this.client.realtime.unsubscribe(this.collectionIdOrName):e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}))}getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const i=Object.assign({},e,t);return super.getFullList(i)}getList(e=1,t=30,i){return super.getList(e,t,i)}getFirstListItem(e,t){return super.getFirstListItem(e,t)}getOne(e,t){return super.getOne(e,t)}create(e,t){return super.create(e,t)}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i,s;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)!==this.collectionIdOrName&&(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionName)!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s,n;return!t||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)!==e||(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)!==this.collectionIdOrName&&(null===(n=this.client.authStore.model)||void 0===n?void 0:n.collectionName)!==this.collectionIdOrName||this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})}listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})))}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}authWithOAuth2Code(e,t,i,s,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:i,redirectUrl:s,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is depreacted. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){return __awaiter(this,void 0,void 0,(function*(){if(e.length>1||"string"==typeof(null==e?void 0:e[0]))return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{});const t=(null==e?void 0:e[0])||{},i=(yield this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!i)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const s=this.client.buildUrl("/api/oauth2-redirect");return new Promise(((e,n)=>__awaiter(this,void 0,void 0,(function*(){var o;try{const r=yield this.client.realtime.subscribe("@oauth2",(o=>__awaiter(this,void 0,void 0,(function*(){const a=this.client.realtime.clientId;try{if(r(),!o.state||a!==o.state)throw new Error("State parameters don't match.");const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const l=yield this.authWithOAuth2Code(i.name,o.code,i.codeVerifier,s,t.createData,n);e(l)}catch(e){n(new ClientResponseError(e))}})))),a={state:this.client.realtime.clientId};(null===(o=t.scopes)||void 0===o?void 0:o.length)&&(a.scope=t.scopes.join(" "));const l=this._replaceQueryParams(i.authUrl+s,a);yield t.urlCallback?t.urlCallback(l):this._defaultUrlCallback(l)}catch(e){n(new ClientResponseError(e))}}))))}))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",i).then((e=>this.authResponse(e)))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}requestVerification(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is depreacted. Consider replacing it with requestVerification(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-verification",s).then((()=>!0))}confirmVerification(e,t,i){let s={method:"POST",body:{token:e}};return s=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is depreacted. Consider replacing it with confirmVerification(token, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/confirm-verification",s).then((()=>!0))}requestEmailChange(e,t,i){let s={method:"POST",body:{newEmail:e}};return s=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is depreacted. Consider replacing it with requestEmailChange(newEmail, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-email-change",s).then((()=>!0))}confirmEmailChange(e,t,i,s){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is depreacted. Consider replacing it with confirmEmailChange(token, password, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>!0))}listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}unlinkExternalAuth(e,t,i){return i=Object.assign({method:"DELETE"},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),i).then((()=>!0))}_replaceQueryParams(e,t={}){let i=e,s="";e.indexOf("?")>=0&&(i=e.substring(0,e.indexOf("?")),s=e.substring(e.indexOf("?")+1));const n={},o=s.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);s="";for(let e in n)n.hasOwnProperty(e)&&(""!=s&&(s+="&"),s+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=s?i+"?"+s:i}_defaultUrlCallback(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,i=768,s=window.innerWidth,n=window.innerHeight;t=t>s?s:t,i=i>n?n:i;let o=s/2-t/2,r=n/2-i/2;window.open(e,"oauth2-popup","width="+t+",height="+i+",top="+r+",left="+o+",resizable,menubar=no")}}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}import(e,t=!1,i){return __awaiter(this,void 0,void 0,(function*(){return i=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},i),this.client.send(this.baseCrudPath+"/import",i).then((()=>!0))}))}}class LogService extends BaseService{getRequestsList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send("/api/logs/requests",i)}getRequest(e,t){return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/requests/"+encodeURIComponent(e),t)}getRequestsStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/requests/stats",e)}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentTopics=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}subscribe(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!e)throw new Error("topic must be set.");const listener=function(e){const i=e;let s;try{s=JSON.parse(null==i?void 0:i.data)}catch(e){}t(s||{})};return this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(listener),this.isConnected?1===this.subscriptions[e].length?yield this.submitSubscriptions():null===(i=this.eventSource)||void 0===i||i.addEventListener(e,listener):yield this.connect(),()=>__awaiter(this,void 0,void 0,(function*(){return this.unsubscribeByTopicAndListener(e,listener)}))}))}unsubscribe(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this.hasSubscriptionListeners(e)){if(e){for(let i of this.subscriptions[e])null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,i);delete this.subscriptions[e]}else this.subscriptions={};this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect()}}))}unsubscribeByPrefix(e){var t;return __awaiter(this,void 0,void 0,(function*(){let i=!1;for(let s in this.subscriptions)if(s.startsWith(e)){i=!0;for(let e of this.subscriptions[s])null===(t=this.eventSource)||void 0===t||t.removeEventListener(s,e);delete this.subscriptions[s]}i&&(this.hasSubscriptionListeners()?yield this.submitSubscriptions():this.disconnect())}))}unsubscribeByTopicAndListener(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return;let s=!1;for(let n=this.subscriptions[e].length-1;n>=0;n--)this.subscriptions[e][n]===t&&(s=!0,delete this.subscriptions[e][n],this.subscriptions[e].splice(n,1),null===(i=this.eventSource)||void 0===i||i.removeEventListener(e,t));s&&(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect())}))}hasSubscriptionListeners(e){var t,i;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(let e in this.subscriptions)if(null===(i=this.subscriptions[e])||void 0===i?void 0:i.length)return!0;return!1}submitSubscriptions(){return __awaiter(this,void 0,void 0,(function*(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},query:{requestKey:this.getSubscriptionsCancelKey()}}).catch((e=>{if(!(null==e?void 0:e.isAbort))throw e}))}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getNonEmptySubscriptionTopics(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}connect(){return __awaiter(this,void 0,void 0,(function*(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=null==t?void 0:t.lastEventId,this.submitSubscriptions().then((()=>__awaiter(this,void 0,void 0,(function*(){let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,yield this.submitSubscriptions()})))).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(const t of e)if(!this.lastSentTopics.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){var t;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class HealthService extends BaseService{check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,i={}){const s=[];s.push("api"),s.push("files"),s.push(encodeURIComponent(e.collectionId||e.collectionName)),s.push(encodeURIComponent(e.id)),s.push(encodeURIComponent(t));let n=this.client.buildUrl(s.join("/"));if(Object.keys(i).length){!1===i.download&&delete i.download;const e=new URLSearchParams(i);n+=(n.includes("?")?"&":"?")+e}return n}getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>(null==e?void 0:e.token)||""))}}class BackupService extends BaseService{getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}const s=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];module.exports=class Client{constructor(e="/",t,i="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=i,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}getFileUrl(e,t,i={}){return this.files.getUrl(e,t,i)}buildUrl(e){var t;let i=this.baseUrl;return"undefined"==typeof window||!window.location||i.startsWith("https://")||i.startsWith("http://")||(i=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(i+=window.location.pathname||"/",i+=i.endsWith("/")?"":"/"),i+=this.baseUrl),e&&(i+=i.endsWith("/")?"":"/",i+=e.startsWith("/")?e.substring(1):e),i}send(e,t){return __awaiter(this,void 0,void 0,(function*(){t=this.initSendOptions(e,t);let i=this.buildUrl(e);if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(i+=(i.includes("?")?"&":"?")+e),delete t.query}if(this.beforeSend){const e=Object.assign({},yield this.beforeSend(i,t));void 0!==e.url||void 0!==e.options?(i=e.url||i,t=e.options||t):Object.keys(e).length&&(t=e,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(i,t).then((e=>__awaiter(this,void 0,void 0,(function*(){let t={};try{t=yield e.json()}catch(e){}if(this.afterSend&&(t=yield this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})))).catch((e=>{throw new ClientResponseError(e)}))}))}initSendOptions(e,t){(t=Object.assign({method:"GET"},t)).query=t.query||{},t.body=this.convertToFormDataIfNeeded(t.body);for(let e in t)s.includes(e)||(t.query[e]=t[e],delete t[e]);if(t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const i=t.requestKey||(t.method||"GET")+e;this.cancelRequest(i);const s=new AbortController;this.cancelControllers[i]=s,t.signal=s.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(let i in e)t.append(i,e[i]);return t}hasBlobField(e){for(let t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];for(let e of i)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let i in e)if(i.toLowerCase()==t)return e[i];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const i in e){if(null===e[i])continue;const s=e[i],n=encodeURIComponent(i);if(Array.isArray(s))for(const e of s)t.push(n+"="+encodeURIComponent(e));else s instanceof Date?t.push(n+"="+encodeURIComponent(s.toISOString())):null!==typeof s&&"object"==typeof s?t.push(n+"="+encodeURIComponent(JSON.stringify(s))):t.push(n+"="+encodeURIComponent(s))}return t.join("&")}};
//# sourceMappingURL=pocketbase.cjs.js.map

@@ -1,2 +0,2 @@

var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}var __assign=function(){return __assign=Object.assign||function __assign(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}function __generator(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function verb(a){return function(c){return function step(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}var e,t=function(e){function ClientResponseError(t){var n,i,o,r,s=this;return(s=e.call(this,"ClientResponseError")||this).url="",s.status=0,s.response={},s.isAbort=!1,s.originalError=null,Object.setPrototypeOf(s,ClientResponseError.prototype),null!==t&&"object"==typeof t&&(s.url="string"==typeof t.url?t.url:"",s.status="number"==typeof t.status?t.status:0,s.isAbort=!!t.isAbort,s.originalError=t.originalError,null!==t.response&&"object"==typeof t.response?s.response=t.response:null!==t.data&&"object"==typeof t.data?s.response=t.data:s.response={}),s.originalError||t instanceof ClientResponseError||(s.originalError=t),"undefined"!=typeof DOMException&&t instanceof DOMException&&(s.isAbort=!0),s.name="ClientResponseError "+s.status,s.message=null===(n=s.response)||void 0===n?void 0:n.message,s.message||(s.isAbort?s.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(r=null===(o=null===(i=s.originalError)||void 0===i?void 0:i.cause)||void 0===o?void 0:o.message)||void 0===r?void 0:r.includes("ECONNREFUSED ::1"))?s.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":s.message="Something went wrong while processing your request."),s}return __extends(ClientResponseError,e),Object.defineProperty(ClientResponseError.prototype,"data",{get:function(){return this.response},enumerable:!1,configurable:!0}),ClientResponseError.prototype.toJSON=function(){return __assign({},this)},ClientResponseError}(Error),n=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(e,t,i){var o=Object.assign({},i||{}),r=o.encode||defaultEncode;if(!n.test(e))throw new TypeError("argument name is invalid");var s=r(t);if(s&&!n.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(null!=o.maxAge){var c=o.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(o.domain){if(!n.test(o.domain))throw new TypeError("option domain is invalid");a+="; Domain="+o.domain}if(o.path){if(!n.test(o.path))throw new TypeError("option path is invalid");a+="; Path="+o.path}if(o.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(o.expires)||isNaN(o.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.priority)switch("string"==typeof o.priority?o.priority.toLowerCase():o.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}function getTokenPayload(t){if(t)try{var n=decodeURIComponent(e(t.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)||{}}catch(e){}return{}}function isTokenExpired(e,t){void 0===t&&(t=0);var n=getTokenPayload(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}e="function"==typeof atob?atob:function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,o=0,r=0,s="";i=t.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};var i=function(){function BaseModel(e){void 0===e&&(e={}),this.$load(e||{})}return BaseModel.prototype.load=function(e){return this.$load(e)},BaseModel.prototype.$load=function(e){for(var t=0,n=Object.entries(e);t<n.length;t++){var i=n[t],o=i[0],r=i[1];this[o]=r}this.id=void 0!==e.id?e.id:"",this.created=void 0!==e.created?e.created:"",this.updated=void 0!==e.updated?e.updated:""},Object.defineProperty(BaseModel.prototype,"$isNew",{get:function(){return!this.id},enumerable:!1,configurable:!0}),BaseModel.prototype.clone=function(){return this.$clone()},BaseModel.prototype.$clone=function(){var e="function"==typeof structuredClone?structuredClone(this):JSON.parse(JSON.stringify(this));return new this.constructor(e)},BaseModel.prototype.export=function(){return this.$export()},BaseModel.prototype.$export=function(){return"function"==typeof structuredClone?structuredClone(this):Object.assign({},this)},BaseModel}(),o=function(e){function Record(){return null!==e&&e.apply(this,arguments)||this}return __extends(Record,e),Record.prototype.$load=function(t){e.prototype.$load.call(this,t),this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.collectionName="string"==typeof t.collectionName?t.collectionName:"",this._loadExpand(t.expand)},Record.prototype._loadExpand=function(e){for(var t in e=e||{},this.expand={},e)Array.isArray(e[t])?this.expand[t]=e[t].map((function(e){return new Record(e||{})})):this.expand[t]=new Record(e[t]||{})},Record}(i),r=function(e){function Admin(){return null!==e&&e.apply(this,arguments)||this}return __extends(Admin,e),Admin.prototype.$load=function(t){e.prototype.$load.call(this,t),this.avatar="number"==typeof t.avatar?t.avatar:0,this.email="string"==typeof t.email?t.email:""},Admin}(i),s="pb_auth",a=function(){function BaseAuthStore(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}return Object.defineProperty(BaseAuthStore.prototype,"token",{get:function(){return this.baseToken},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"model",{get:function(){return this.baseModel},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"isValid",{get:function(){return!isTokenExpired(this.token)},enumerable:!1,configurable:!0}),BaseAuthStore.prototype.save=function(e,t){this.baseToken=e||"",this.baseModel=null!==t&&"object"==typeof t?void 0!==t.collectionId?new o(t):new r(t):null,this.triggerChange()},BaseAuthStore.prototype.clear=function(){this.baseToken="",this.baseModel=null,this.triggerChange()},BaseAuthStore.prototype.loadFromCookie=function(e,t){void 0===t&&(t=s);var n=function cookieParse(e,t){var n={};if("string"!=typeof e)return n;for(var i=Object.assign({},t||{}).decode||defaultDecode,o=0;o<e.length;){var r=e.indexOf("=",o);if(-1===r)break;var s=e.indexOf(";",o);if(-1===s)s=e.length;else if(s<r){o=e.lastIndexOf(";",r-1)+1;continue}var a=e.slice(o,r).trim();if(void 0===n[a]){var c=e.slice(r+1,s).trim();34===c.charCodeAt(0)&&(c=c.slice(1,-1));try{n[a]=i(c)}catch(e){n[a]=c}}o=s+1}return n}(e||"")[t]||"",i={};try{(null===typeof(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))&&(i={})}catch(e){}this.save(i.token||"",i.model||null)},BaseAuthStore.prototype.exportToCookie=function(e,t){var n,i,r;void 0===t&&(t=s);var a={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},c=getTokenPayload(this.token);(null==c?void 0:c.exp)?a.expires=new Date(1e3*c.exp):a.expires=new Date("1970-01-01"),e=Object.assign({},a,e);var u={token:this.token,model:(null===(n=this.model)||void 0===n?void 0:n.export())||null},l=cookieSerialize(t,JSON.stringify(u),e),d="undefined"!=typeof Blob?new Blob([l]).size:l.length;return u.model&&d>4096&&(u.model={id:null===(i=null==u?void 0:u.model)||void 0===i?void 0:i.id,email:null===(r=null==u?void 0:u.model)||void 0===r?void 0:r.email},this.model instanceof o&&(u.model.username=this.model.username,u.model.verified=this.model.verified,u.model.collectionId=this.model.collectionId),l=cookieSerialize(t,JSON.stringify(u),e)),l},BaseAuthStore.prototype.onChange=function(e,t){var n=this;return void 0===t&&(t=!1),this._onChangeCallbacks.push(e),t&&e(this.token,this.model),function(){for(var t=n._onChangeCallbacks.length-1;t>=0;t--)if(n._onChangeCallbacks[t]==e)return delete n._onChangeCallbacks[t],void n._onChangeCallbacks.splice(t,1)}},BaseAuthStore.prototype.triggerChange=function(){for(var e=0,t=this._onChangeCallbacks;e<t.length;e++){var n=t[e];n&&n(this.token,this.model)}},BaseAuthStore}(),c=function(e){function LocalAuthStore(t){void 0===t&&(t="pocketbase_auth");var n=e.call(this)||this;return n.storageFallback={},n.storageKey=t,n}return __extends(LocalAuthStore,e),Object.defineProperty(LocalAuthStore.prototype,"token",{get:function(){return(this._storageGet(this.storageKey)||{}).token||""},enumerable:!1,configurable:!0}),Object.defineProperty(LocalAuthStore.prototype,"model",{get:function(){var e,t=this._storageGet(this.storageKey)||{};return null===t||"object"!=typeof t||null===t.model||"object"!=typeof t.model?null:void 0===(null===(e=t.model)||void 0===e?void 0:e.collectionId)?new r(t.model):new o(t.model)},enumerable:!1,configurable:!0}),LocalAuthStore.prototype.save=function(t,n){this._storageSet(this.storageKey,{token:t,model:n}),e.prototype.save.call(this,t,n)},LocalAuthStore.prototype.clear=function(){this._storageRemove(this.storageKey),e.prototype.clear.call(this)},LocalAuthStore.prototype._storageGet=function(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]},LocalAuthStore.prototype._storageSet=function(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var n=t;"string"!=typeof t&&(n=JSON.stringify(t)),window.localStorage.setItem(e,n)}else this.storageFallback[e]=t},LocalAuthStore.prototype._storageRemove=function(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]},LocalAuthStore}(a),u=function u(e){this.client=e},l=function(e){function SettingsService(){return null!==e&&e.apply(this,arguments)||this}return __extends(SettingsService,e),SettingsService.prototype.getAll=function(e){return void 0===e&&(e={}),this.client.send("/api/settings",{method:"GET",params:e}).then((function(e){return e||{}}))},SettingsService.prototype.update=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send("/api/settings",{method:"PATCH",params:t,body:e}).then((function(e){return e||{}}))},SettingsService.prototype.testS3=function(e,t){void 0===e&&(e="storage"),void 0===t&&(t={});var n={filesystem:e};return this.client.send("/api/settings/test/s3",{method:"POST",params:t,body:n}).then((function(){return!0}))},SettingsService.prototype.testEmail=function(e,t,n){void 0===n&&(n={});var i={email:e,template:t};return this.client.send("/api/settings/test/email",{method:"POST",params:n,body:i}).then((function(){return!0}))},SettingsService.prototype.generateAppleClientSecret=function(e,t,n,i,o,r,s){return void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({clientId:e,teamId:t,keyId:n,privateKey:i,duration:o},r),this.client.send("/api/settings/apple/generate-client-secret",{method:"POST",params:s,body:r})},SettingsService}(u),d=function d(e,t,n,i,o){this.page=e>0?e:1,this.perPage=t>=0?t:0,this.totalItems=n>=0?n:0,this.totalPages=i>=0?i:0,this.items=o||[]},h=function(e){function CrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CrudService,e),CrudService.prototype.getFullList=function(e,t){if("number"==typeof e)return this._getFullList(this.baseCrudPath,e,t);var n=Object.assign({},e,t),i=500;return n.batch&&(i=n.batch,delete n.batch),this._getFullList(this.baseCrudPath,i,n)},CrudService.prototype.getList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),this._getList(this.baseCrudPath,e,t,n)},CrudService.prototype.getFirstListItem=function(e,t){return void 0===t&&(t={}),this._getFirstListItem(this.baseCrudPath,e,t)},CrudService.prototype.getOne=function(e,t){return void 0===t&&(t={}),this._getOne(this.baseCrudPath,e,t)},CrudService.prototype.create=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this._create(this.baseCrudPath,e,t)},CrudService.prototype.update=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),this._update(this.baseCrudPath,e,t,n)},CrudService.prototype.delete=function(e,t){return void 0===t&&(t={}),this._delete(this.baseCrudPath,e,t)},CrudService}(function(e){function BaseCrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BaseCrudService,e),BaseCrudService.prototype._getFullList=function(e,t,n){var i=this;void 0===t&&(t=500),void 0===n&&(n={}),n=Object.assign({skipTotal:1},n);var o=[],request=function(r){return __awaiter(i,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this._getList(e,r,t||500,n).then((function(e){var t=e.items;return o=o.concat(t),t.length==e.perPage?request(r+1):o}))]}))}))};return request(1)},BaseCrudService.prototype._getList=function(e,t,n,i){var o=this;return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),i=Object.assign({page:t,perPage:n},i),this.client.send(e,{method:"GET",params:i}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=e.items||[];for(var n=0,i=e.items;n<i.length;n++){var r=i[n];t.push(o.decode(r))}}return new d((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},BaseCrudService.prototype._getOne=function(e,t,n){var i=this;return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"GET",params:n}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._getFirstListItem=function(e,n,i){return void 0===i&&(i={}),i=Object.assign({filter:n,skipTotal:1,$cancelKey:"one_by_filter_"+e+"_"+n},i),this._getList(e,1,1,i).then((function(e){var n;if(!(null===(n=null==e?void 0:e.items)||void 0===n?void 0:n.length))throw new t({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))},BaseCrudService.prototype._create=function(e,t,n){var i=this;return void 0===t&&(t={}),void 0===n&&(n={}),this.client.send(e,{method:"POST",params:n,body:t}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._update=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"PATCH",params:i,body:n}).then((function(e){return o.decode(e)}))},BaseCrudService.prototype._delete=function(e,t,n){return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},BaseCrudService}(u)),p=function(e){function AdminService(){return null!==e&&e.apply(this,arguments)||this}return __extends(AdminService,e),AdminService.prototype.decode=function(e){return new r(e)},Object.defineProperty(AdminService.prototype,"baseCrudPath",{get:function(){return"/api/admins"},enumerable:!1,configurable:!0}),AdminService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n;return o.client.authStore.model&&void 0===(null===(t=o.client.authStore.model)||void 0===t?void 0:t.collectionId)&&(null===(n=o.client.authStore.model)||void 0===n?void 0:n.id)===(null==e?void 0:e.id)&&o.client.authStore.save(o.client.authStore.token,e),e}))},AdminService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o;return e&&i.client.authStore.model&&void 0===(null===(n=i.client.authStore.model)||void 0===n?void 0:n.collectionId)&&(null===(o=i.client.authStore.model)||void 0===o?void 0:o.id)===t&&i.client.authStore.clear(),e}))},AdminService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})},AdminService.prototype.authWithPassword=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCrudPath+"/auth-with-password",{method:"POST",params:i,body:n}).then(this.authResponse.bind(this))},AdminService.prototype.authRefresh=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/auth-refresh",{method:"POST",params:t,body:e}).then(this.authResponse.bind(this))},AdminService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCrudPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},AdminService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCrudPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},AdminService}(h),v=function(e){function ExternalAuth(){return null!==e&&e.apply(this,arguments)||this}return __extends(ExternalAuth,e),ExternalAuth.prototype.$load=function(t){e.prototype.$load.call(this,t),this.recordId="string"==typeof t.recordId?t.recordId:"",this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.provider="string"==typeof t.provider?t.provider:"",this.providerId="string"==typeof t.providerId?t.providerId:""},ExternalAuth}(i),f=function(e){function RecordService(t,n){var i=e.call(this,t)||this;return i.collectionIdOrName=n,i}return __extends(RecordService,e),RecordService.prototype.decode=function(e){return new o(e)},Object.defineProperty(RecordService.prototype,"baseCrudPath",{get:function(){return this.baseCollectionPath+"/records"},enumerable:!1,configurable:!0}),Object.defineProperty(RecordService.prototype,"baseCollectionPath",{get:function(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)},enumerable:!1,configurable:!0}),RecordService.prototype.subscribeOne=function(e,t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)]}))}))},RecordService.prototype.subscribe=function(e,t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(i){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName,e)];if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");return n=this.collectionIdOrName,"*"!==e&&(n+="/"+e),[2,this.client.realtime.subscribe(n,t)]}))}))},RecordService.prototype.unsubscribe=function(e){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return"*"===e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName)]:e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e)]:[2,this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)]}))}))},RecordService.prototype.getFullList=function(t,n){if("number"==typeof t)return e.prototype.getFullList.call(this,t,n);var i=Object.assign({},t,n);return e.prototype.getFullList.call(this,i)},RecordService.prototype.getList=function(t,n,i){return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),e.prototype.getList.call(this,t,n,i)},RecordService.prototype.getFirstListItem=function(t,n){return void 0===n&&(n={}),e.prototype.getFirstListItem.call(this,t,n)},RecordService.prototype.getOne=function(t,n){return void 0===n&&(n={}),e.prototype.getOne.call(this,t,n)},RecordService.prototype.create=function(t,n){return void 0===t&&(t={}),void 0===n&&(n={}),e.prototype.create.call(this,t,n)},RecordService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n,i;return(null===(t=o.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(n=o.client.authStore.model)||void 0===n?void 0:n.collectionId)!==o.collectionIdOrName&&(null===(i=o.client.authStore.model)||void 0===i?void 0:i.collectionName)!==o.collectionIdOrName||o.client.authStore.save(o.client.authStore.token,e),e}))},RecordService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o,r;return!e||(null===(n=i.client.authStore.model)||void 0===n?void 0:n.id)!==t||(null===(o=i.client.authStore.model)||void 0===o?void 0:o.collectionId)!==i.collectionIdOrName&&(null===(r=i.client.authStore.model)||void 0===r?void 0:r.collectionName)!==i.collectionIdOrName||i.client.authStore.clear(),e}))},RecordService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})},RecordService.prototype.listAuthMethods=function(e){return void 0===e&&(e={}),this.client.send(this.baseCollectionPath+"/auth-methods",{method:"GET",params:e}).then((function(e){return Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})}))},RecordService.prototype.authWithPassword=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCollectionPath+"/auth-with-password",{method:"POST",params:i,body:n}).then((function(e){return o.authResponse(e)}))},RecordService.prototype.authWithOAuth2Code=function(e,t,n,i,o,r,s){var a=this;return void 0===o&&(o={}),void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({provider:e,code:t,codeVerifier:n,redirectUrl:i,createData:o},r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",{method:"POST",params:s,body:r}).then((function(e){return a.authResponse(e)}))},RecordService.prototype.authWithOAuth2=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s=this;return __generator(this,(function(a){switch(a.label){case 0:return e.length>1||"string"==typeof(null==e?void 0:e[0])?(console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),[2,this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{})]):(n=(null==e?void 0:e[0])||{},[4,this.listAuthMethods()]);case 1:if(i=a.sent(),!(o=i.authProviders.find((function(e){return e.name===n.provider}))))throw new t(new Error('Missing or invalid provider "'.concat(n.provider,'".')));return r=this.client.buildUrl("/api/oauth2-redirect"),[2,new Promise((function(e,i){return __awaiter(s,void 0,void 0,(function(){var s,a,c,u,l,d=this;return __generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this.client.realtime.subscribe("@oauth2",(function(a){return __awaiter(d,void 0,void 0,(function(){var c,u,l;return __generator(this,(function(d){switch(d.label){case 0:c=this.client.realtime.clientId,d.label=1;case 1:if(d.trys.push([1,3,,4]),s(),!a.state||c!==a.state)throw new Error("State parameters don't match.");return[4,this.authWithOAuth2Code(o.name,a.code,o.codeVerifier,r,n.createData,n.body,n.query)];case 2:return u=d.sent(),e(u),[3,4];case 3:return l=d.sent(),i(new t(l)),[3,4];case 4:return[2]}}))}))}))];case 1:return s=h.sent(),a={state:this.client.realtime.clientId},(null===(l=n.scopes)||void 0===l?void 0:l.length)&&(a.scope=n.scopes.join(" ")),c=this._replaceQueryParams(o.authUrl+r,a),[4,n.urlCallback?n.urlCallback(c):this._defaultUrlCallback(c)];case 2:return h.sent(),[3,4];case 3:return u=h.sent(),i(new t(u)),[3,4];case 4:return[2]}}))}))}))]}}))}))},RecordService.prototype.authRefresh=function(e,t){var n=this;return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCollectionPath+"/auth-refresh",{method:"POST",params:t,body:e}).then((function(e){return n.authResponse(e)}))},RecordService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCollectionPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},RecordService.prototype.requestVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({token:e},t),this.client.send(this.baseCollectionPath+"/confirm-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.requestEmailChange=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({newEmail:e},t),this.client.send(this.baseCollectionPath+"/request-email-change",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmEmailChange=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({token:e,password:t},n),this.client.send(this.baseCollectionPath+"/confirm-email-change",{method:"POST",params:i,body:n}).then((function(){return!0}))},RecordService.prototype.listExternalAuths=function(e,t){return void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",{method:"GET",params:t}).then((function(e){var t=[];if(Array.isArray(e))for(var n=0,i=e;n<i.length;n++){var o=i[n];t.push(new v(o))}return t}))},RecordService.prototype.unlinkExternalAuth=function(e,t,n){return void 0===n&&(n={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},RecordService.prototype._replaceQueryParams=function(e,t){void 0===t&&(t={});var n=e,i="";e.indexOf("?")>=0&&(n=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));for(var o={},r=0,s=i.split("&");r<s.length;r++){var a=s[r];if(""!=a){var c=a.split("=");o[decodeURIComponent(c[0].replace(/\+/g," "))]=decodeURIComponent((c[1]||"").replace(/\+/g," "))}}for(var u in t)t.hasOwnProperty(u)&&(null==t[u]?delete o[u]:o[u]=t[u]);for(var u in i="",o)o.hasOwnProperty(u)&&(""!=i&&(i+="&"),i+=encodeURIComponent(u.replace(/%20/g,"+"))+"="+encodeURIComponent(o[u].replace(/%20/g,"+")));return""!=i?n+"?"+i:n},RecordService.prototype._defaultUrlCallback=function(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new t(new Error("Not in a browser context - please pass a custom urlCallback function."));var n=1024,i=768,o=window.innerWidth,r=window.innerHeight,s=o/2-(n=n>o?o:n)/2,a=r/2-(i=i>r?r:i)/2;window.open(e,"oauth2-popup","width="+n+",height="+i+",top="+a+",left="+s+",resizable,menubar=no")},RecordService}(h),m=function m(e){void 0===e&&(e={}),this.id=void 0!==e.id?e.id:"",this.name=void 0!==e.name?e.name:"",this.type=void 0!==e.type?e.type:"text",this.system=!!e.system,this.required=!!e.required,this.options="object"==typeof e.options&&null!==e.options?e.options:{}},b=function(e){function Collection(){return null!==e&&e.apply(this,arguments)||this}return __extends(Collection,e),Collection.prototype.$load=function(t){e.prototype.$load.call(this,t),this.system=!!t.system,this.name="string"==typeof t.name?t.name:"",this.type="string"==typeof t.type?t.type:"base",this.options=void 0!==t.options&&null!==t.options?t.options:{},this.indexes=Array.isArray(t.indexes)?t.indexes:[],this.listRule="string"==typeof t.listRule?t.listRule:null,this.viewRule="string"==typeof t.viewRule?t.viewRule:null,this.createRule="string"==typeof t.createRule?t.createRule:null,this.updateRule="string"==typeof t.updateRule?t.updateRule:null,this.deleteRule="string"==typeof t.deleteRule?t.deleteRule:null,t.schema=Array.isArray(t.schema)?t.schema:[],this.schema=[];for(var n=0,i=t.schema;n<i.length;n++){var o=i[n];this.schema.push(new m(o))}},Object.defineProperty(Collection.prototype,"isBase",{get:function(){return this.$isBase},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isBase",{get:function(){return"base"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isAuth",{get:function(){return this.$isAuth},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isAuth",{get:function(){return"auth"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isView",{get:function(){return this.$isView},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isView",{get:function(){return"view"===this.type},enumerable:!1,configurable:!0}),Collection}(i),y=function(e){function CollectionService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CollectionService,e),CollectionService.prototype.decode=function(e){return new b(e)},Object.defineProperty(CollectionService.prototype,"baseCrudPath",{get:function(){return"/api/collections"},enumerable:!1,configurable:!0}),CollectionService.prototype.import=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this.client.send(this.baseCrudPath+"/import",{method:"PUT",params:n,body:{collections:e,deleteMissing:t}}).then((function(){return!0}))]}))}))},CollectionService}(h),g=function(e){function LogRequest(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogRequest,e),LogRequest.prototype.$load=function(t){e.prototype.$load.call(this,t),t.remoteIp=t.remoteIp||t.ip,this.url="string"==typeof t.url?t.url:"",this.method="string"==typeof t.method?t.method:"GET",this.status="number"==typeof t.status?t.status:200,this.auth="string"==typeof t.auth?t.auth:"guest",this.remoteIp="string"==typeof t.remoteIp?t.remoteIp:"",this.userIp="string"==typeof t.userIp?t.userIp:"",this.referer="string"==typeof t.referer?t.referer:"",this.userAgent="string"==typeof t.userAgent?t.userAgent:"",this.meta="object"==typeof t.meta&&null!==t.meta?t.meta:{}},LogRequest}(i),S=function(e){function LogService(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogService,e),LogService.prototype.getRequestsList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),n=Object.assign({page:e,perPage:t},n),this.client.send("/api/logs/requests",{method:"GET",params:n}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=(null==e?void 0:e.items)||[];for(var n=0,i=e.items;n<i.length;n++){var o=i[n];t.push(new g(o))}}return new d((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},LogService.prototype.getRequest=function(e,t){return void 0===t&&(t={}),this.client.send("/api/logs/requests/"+encodeURIComponent(e),{method:"GET",params:t}).then((function(e){return new g(e)}))},LogService.prototype.getRequestsStats=function(e){return void 0===e&&(e={}),this.client.send("/api/logs/requests/stats",{method:"GET",params:e}).then((function(e){return e}))},LogService}(u),w=function(e){function RealtimeService(){var t=null!==e&&e.apply(this,arguments)||this;return t.clientId="",t.eventSource=null,t.subscriptions={},t.lastSentTopics=[],t.maxConnectTimeout=15e3,t.reconnectAttempts=0,t.maxReconnectAttempts=1/0,t.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],t.pendingConnects=[],t}return __extends(RealtimeService,e),Object.defineProperty(RealtimeService.prototype,"isConnected",{get:function(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length},enumerable:!1,configurable:!0}),RealtimeService.prototype.subscribe=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o=this;return __generator(this,(function(r){switch(r.label){case 0:if(!e)throw new Error("topic must be set.");return i=function(e){var n,i=e;try{n=JSON.parse(null==i?void 0:i.data)}catch(e){}t(n||{})},this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(i),this.isConnected?[3,2]:[4,this.connect()];case 1:return r.sent(),[3,5];case 2:return 1!==this.subscriptions[e].length?[3,4]:[4,this.submitSubscriptions()];case 3:return r.sent(),[3,5];case 4:null===(n=this.eventSource)||void 0===n||n.addEventListener(e,i),r.label=5;case 5:return[2,function(){return __awaiter(o,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this.unsubscribeByTopicAndListener(e,i)]}))}))}]}}))}))},RealtimeService.prototype.unsubscribe=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!this.hasSubscriptionListeners(e))return[2];if(e){for(n=0,i=this.subscriptions[e];n<i.length;n++)o=i[n],null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,o);delete this.subscriptions[e]}else this.subscriptions={};return this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3]);case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByPrefix=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s;return __generator(this,(function(a){switch(a.label){case 0:for(i in n=!1,this.subscriptions)if(i.startsWith(e)){for(n=!0,o=0,r=this.subscriptions[i];o<r.length;o++)s=r[o],null===(t=this.eventSource)||void 0===t||t.removeEventListener(i,s);delete this.subscriptions[i]}return n?this.hasSubscriptionListeners()?[4,this.submitSubscriptions()]:[3,2]:[2];case 1:return a.sent(),[3,3];case 2:this.disconnect(),a.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByTopicAndListener=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return[2];for(i=!1,o=this.subscriptions[e].length-1;o>=0;o--)this.subscriptions[e][o]===t&&(i=!0,delete this.subscriptions[e][o],this.subscriptions[e].splice(o,1),null===(n=this.eventSource)||void 0===n||n.removeEventListener(e,t));return i?(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3])):[2];case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.hasSubscriptionListeners=function(e){var t,n;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(var i in this.subscriptions)if(null===(n=this.subscriptions[i])||void 0===n?void 0:n.length)return!0;return!1},RealtimeService.prototype.submitSubscriptions=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(e){return this.clientId?(this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),[2,this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},params:{$cancelKey:this.getSubscriptionsCancelKey()}}).catch((function(e){if(!(null==e?void 0:e.isAbort))throw e}))]):[2]}))}))},RealtimeService.prototype.getSubscriptionsCancelKey=function(){return"realtime_"+this.clientId},RealtimeService.prototype.getNonEmptySubscriptionTopics=function(){var e=[];for(var t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e},RealtimeService.prototype.addAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.removeAllSubscriptionListeners(),this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.addEventListener(e,i)}},RealtimeService.prototype.removeAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.removeEventListener(e,i)}},RealtimeService.prototype.connect=function(){return __awaiter(this,void 0,void 0,(function(){var e=this;return __generator(this,(function(t){return this.reconnectAttempts>0?[2]:[2,new Promise((function(t,n){e.pendingConnects.push({resolve:t,reject:n}),e.pendingConnects.length>1||e.initConnect()}))]}))}))},RealtimeService.prototype.initConnect=function(){var e=this;this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((function(){e.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=function(t){e.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(function(t){var n=t;e.clientId=null==n?void 0:n.lastEventId,e.submitSubscriptions().then((function(){return __awaiter(e,void 0,void 0,(function(){var e;return __generator(this,(function(t){switch(t.label){case 0:e=3,t.label=1;case 1:return this.hasUnsentSubscriptions()&&e>0?(e--,[4,this.submitSubscriptions()]):[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))}))})).then((function(){for(var t=0,n=e.pendingConnects;t<n.length;t++){n[t].resolve()}e.pendingConnects=[],e.reconnectAttempts=0,clearTimeout(e.reconnectTimeoutId),clearTimeout(e.connectTimeoutId)})).catch((function(t){e.clientId="",e.connectErrorHandler(t)}))}))},RealtimeService.prototype.hasUnsentSubscriptions=function(){var e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(var t=0,n=e;t<n.length;t++){var i=n[t];if(!this.lastSentTopics.includes(i))return!0}return!1},RealtimeService.prototype.connectErrorHandler=function(e){var n=this;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(var i=0,o=this.pendingConnects;i<o.length;i++){o[i].reject(new t(e))}return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);var r=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((function(){n.initConnect()}),r)},RealtimeService.prototype.disconnect=function(e){var t;if(void 0===e&&(e=!1),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(var n=0,i=this.pendingConnects;n<i.length;n++){i[n].resolve()}this.pendingConnects=[]}},RealtimeService}(u),C=function(e){function HealthService(){return null!==e&&e.apply(this,arguments)||this}return __extends(HealthService,e),HealthService.prototype.check=function(e){return void 0===e&&(e={}),this.client.send("/api/health",{method:"GET",params:e})},HealthService}(u),_=function(e){function FileService(){return null!==e&&e.apply(this,arguments)||this}return __extends(FileService,e),FileService.prototype.getUrl=function(e,t,n){void 0===n&&(n={});var i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));var o=this.client.buildUrl(i.join("/"));if(Object.keys(n).length){!1===n.download&&delete n.download;var r=new URLSearchParams(n);o+=(o.includes("?")?"&":"?")+r}return o},FileService.prototype.getToken=function(e){return void 0===e&&(e={}),this.client.send("/api/files/token",{method:"POST",params:e}).then((function(e){return(null==e?void 0:e.token)||""}))},FileService}(u),R=function(e){function BackupService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BackupService,e),BackupService.prototype.getFullList=function(e){return void 0===e&&(e={}),this.client.send("/api/backups",{method:"GET",params:e})},BackupService.prototype.create=function(e,t){void 0===t&&(t={});var n={name:e};return this.client.send("/api/backups",{method:"POST",params:t,body:n}).then((function(){return!0}))},BackupService.prototype.delete=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e)),{method:"DELETE",params:t}).then((function(){return!0}))},BackupService.prototype.restore=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e),"/restore"),{method:"POST",params:t}).then((function(){return!0}))},BackupService.prototype.getDownloadUrl=function(e,t){return this.client.buildUrl("/api/backups/".concat(encodeURIComponent(t),"?token=").concat(encodeURIComponent(e)))},BackupService}(u),O=function(){function Client(e,t,n){void 0===e&&(e="/"),void 0===n&&(n="en-US"),this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=n,this.authStore=t||new c,this.admins=new p(this),this.collections=new y(this),this.files=new _(this),this.logs=new S(this),this.settings=new l(this),this.realtime=new w(this),this.health=new C(this),this.backups=new R(this)}return Client.prototype.collection=function(e){return this.recordServices[e]||(this.recordServices[e]=new f(this,e)),this.recordServices[e]},Client.prototype.autoCancellation=function(e){return this.enableAutoCancellation=!!e,this},Client.prototype.cancelRequest=function(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this},Client.prototype.cancelAllRequests=function(){for(var e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this},Client.prototype.send=function(e,n){var i,o,r,s,a,c,u,l;return __awaiter(this,void 0,void 0,(function(){var d,h,p,v,f,m,b,y,g,S=this;return __generator(this,(function(w){switch(w.label){case 0:return d=Object.assign({method:"GET"},n),this.isFormData(d.body)||(d.body&&"string"!=typeof d.body&&(d.body=JSON.stringify(d.body)),void 0===(null===(i=null==d?void 0:d.headers)||void 0===i?void 0:i["Content-Type"])&&(d.headers=Object.assign({},d.headers,{"Content-Type":"application/json"}))),void 0===(null===(o=null==d?void 0:d.headers)||void 0===o?void 0:o["Accept-Language"])&&(d.headers=Object.assign({},d.headers,{"Accept-Language":this.lang})),(null===(r=this.authStore)||void 0===r?void 0:r.token)&&void 0===(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s.Authorization)&&(d.headers=Object.assign({},d.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&!1!==(null===(a=d.params)||void 0===a?void 0:a.$autoCancel)&&(h=(null===(c=d.params)||void 0===c?void 0:c.$cancelKey)||(d.method||"GET")+e,this.cancelRequest(h),p=new AbortController,this.cancelControllers[h]=p,d.signal=p.signal),null===(u=d.params)||void 0===u||delete u.$autoCancel,null===(l=d.params)||void 0===l||delete l.$cancelKey,v=this.buildUrl(e),void 0!==d.params&&((f=this.serializeQueryParams(d.params))&&(v+=(v.includes("?")?"&":"?")+f),delete d.params),this.beforeSend?(y=(b=Object).assign,g=[{}],[4,this.beforeSend(v,d)]):[3,2];case 1:void 0!==(m=y.apply(b,g.concat([w.sent()]))).url||void 0!==m.options?(v=m.url||v,d=m.options||d):Object.keys(m).length&&(d=m,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.")),w.label=2;case 2:return[2,fetch(v,d).then((function(e){return __awaiter(S,void 0,void 0,(function(){var n;return __generator(this,(function(i){switch(i.label){case 0:n={},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.json()];case 2:return n=i.sent(),[3,4];case 3:return i.sent(),[3,4];case 4:return this.afterSend?[4,this.afterSend(e,n)]:[3,6];case 5:n=i.sent(),i.label=6;case 6:if(e.status>=400)throw new t({url:e.url,status:e.status,data:n});return[2,n]}}))}))})).catch((function(e){throw new t(e)}))]}}))}))},Client.prototype.getFileUrl=function(e,t,n){return void 0===n&&(n={}),this.files.getUrl(e,t,n)},Client.prototype.buildUrl=function(e){var t,n=this.baseUrl;return"undefined"==typeof window||!window.location||n.startsWith("https://")||n.startsWith("http://")||(n=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(n+=window.location.pathname||"/",n+=n.endsWith("/")?"":"/"),n+=this.baseUrl),e&&(n+=n.endsWith("/")?"":"/",n+=e.startsWith("/")?e.substring(1):e),n},Client.prototype.isFormData=function(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)},Client.prototype.serializeQueryParams=function(e){var t=[];for(var n in e)if(null!==e[n]){var i=e[n],o=encodeURIComponent(n);if(Array.isArray(i))for(var r=0,s=i;r<s.length;r++){var a=s[r];t.push(o+"="+encodeURIComponent(a))}else i instanceof Date?t.push(o+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(o+"="+encodeURIComponent(JSON.stringify(i))):t.push(o+"="+encodeURIComponent(i))}return t.join("&")},Client}();export{r as Admin,p as AdminService,a as BaseAuthStore,i as BaseModel,t as ClientResponseError,b as Collection,y as CollectionService,h as CrudService,v as ExternalAuth,d as ListResult,c as LocalAuthStore,g as LogRequest,S as LogService,w as RealtimeService,o as Record,f as RecordService,m as SchemaField,l as SettingsService,O as default,getTokenPayload,isTokenExpired};
function __awaiter(e,t,i,s){return new(i||(i=Promise))((function(n,o){function fulfilled(e){try{step(s.next(e))}catch(e){o(e)}}function rejected(e){try{step(s.throw(e))}catch(e){o(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class ClientResponseError extends Error{constructor(e){var t,i,s,n;super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=null===(t=this.response)||void 0===t?void 0:t.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(n=null===(s=null===(i=this.originalError)||void 0===i?void 0:i.cause)||void 0===s?void 0:s.message)||void 0===n?void 0:n.includes("ECONNREFUSED ::1"))?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return Object.assign({},this)}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(e,t){const i={};if("string"!=typeof e)return i;const s=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n<e.length;){const t=e.indexOf("=",n);if(-1===t)break;let o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<t){n=e.lastIndexOf(";",t-1)+1;continue}const r=e.slice(n,t).trim();if(void 0===i[r]){let n=e.slice(t+1,o).trim();34===n.charCodeAt(0)&&(n=n.slice(1,-1));try{i[r]=s(n)}catch(e){i[r]=n}}n=o+1}return i}function cookieSerialize(t,i,s){const n=Object.assign({},s||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(i);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}let t;function getTokenPayload(e){if(e)try{const i=decodeURIComponent(t(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(i)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let i=getTokenPayload(e);return!(Object.keys(i).length>0&&(!i.exp||i.exp-t>Date.now()/1e3))}t="function"==typeof atob?atob:e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,s,n=0,o=0,r="";s=t.charAt(o++);~s&&(i=n%4?64*i+s:s,n++%4)?r+=String.fromCharCode(255&i>>(-2*n&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return r};const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=cookieParse(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){var s,n;const o={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=getTokenPayload(this.token);(null==r?void 0:r.exp)?o.expires=new Date(1e3*r.exp):o.expires=new Date("1970-01-01"),e=Object.assign({},o,e);const a={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let l=cookieSerialize(t,JSON.stringify(a),e);const c="undefined"!=typeof Blob?new Blob([l]).size:l.length;if(a.model&&c>4096){a.model={id:null===(s=null==a?void 0:a.model)||void 0===s?void 0:s.id,email:null===(n=null==a?void 0:a.model)||void 0===n?void 0:n.email};const i=["collectionId","username","verified"];for(const e in this.model)i.includes(e)&&(a.model[e]=this.model[e]);l=cookieSerialize(t,JSON.stringify(a),e)}return l}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){let i=t;"string"!=typeof t&&(i=JSON.stringify(t)),window.localStorage.setItem(e,i)}else this.storageFallback[e]=t}_storageRemove(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}testEmail(e,t,i){return i=Object.assign({method:"POST",body:{email:e,template:t}},i),this.client.send("/api/settings/test/email",i).then((()=>!0))}generateAppleClientSecret(e,t,i,s,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:i,privateKey:s,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let i=500;return(t=Object.assign({},e,t)).batch&&(i=t.batch,delete t.batch),this._getFullList(i,t)}getList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send(this.baseCrudPath,i).then((e=>{var t;return e.items=(null===(t=e.items)||void 0===t?void 0:t.map((e=>this.decode(e))))||[],e}))}getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{var t;if(!(null===(t=null==e?void 0:e.items)||void 0===t?void 0:t.length))throw new ClientResponseError({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}getOne(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}update(e,t,i){return i=Object.assign({method:"PATCH",body:t},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),i).then((e=>this.decode(e)))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let i=[],request=s=>__awaiter(this,void 0,void 0,(function*(){return this.getList(s,e||500,t).then((e=>{const t=e.items;return i=i.concat(t),t.length==e.perPage?request(s+1):i}))}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,i,s){const n=void 0!==s;return n||void 0!==i?n?(console.warn(e),t.body=Object.assign({},t.body,i),t.query=Object.assign({},t.query,s),t):t=Object.assign(t,i):t}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)===e.id&&void 0===(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)&&this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s;return t&&(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)===e&&void 0===(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)&&this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(email, pass, options?).",n,i,s),this.client.send(this.baseCrudPath+"/auth-with-password",n).then(this.authResponse.bind(this))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",i).then(this.authResponse.bind(this))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCrudPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}subscribeOne(e,t){return __awaiter(this,void 0,void 0,(function*(){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),this.client.realtime.subscribe(this.collectionIdOrName,e);if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");let i=this.collectionIdOrName;return"*"!==e&&(i+="/"+e),this.client.realtime.subscribe(i,t)}))}unsubscribe(e){return __awaiter(this,void 0,void 0,(function*(){return"*"===e?this.client.realtime.unsubscribe(this.collectionIdOrName):e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}))}getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const i=Object.assign({},e,t);return super.getFullList(i)}getList(e=1,t=30,i){return super.getList(e,t,i)}getFirstListItem(e,t){return super.getFirstListItem(e,t)}getOne(e,t){return super.getOne(e,t)}create(e,t){return super.create(e,t)}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i,s;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)!==this.collectionIdOrName&&(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionName)!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s,n;return!t||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)!==e||(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)!==this.collectionIdOrName&&(null===(n=this.client.authStore.model)||void 0===n?void 0:n.collectionName)!==this.collectionIdOrName||this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})}listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})))}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}authWithOAuth2Code(e,t,i,s,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:i,redirectUrl:s,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is depreacted. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){return __awaiter(this,void 0,void 0,(function*(){if(e.length>1||"string"==typeof(null==e?void 0:e[0]))return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{});const t=(null==e?void 0:e[0])||{},i=(yield this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!i)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const s=this.client.buildUrl("/api/oauth2-redirect");return new Promise(((e,n)=>__awaiter(this,void 0,void 0,(function*(){var o;try{const r=yield this.client.realtime.subscribe("@oauth2",(o=>__awaiter(this,void 0,void 0,(function*(){const a=this.client.realtime.clientId;try{if(r(),!o.state||a!==o.state)throw new Error("State parameters don't match.");const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const l=yield this.authWithOAuth2Code(i.name,o.code,i.codeVerifier,s,t.createData,n);e(l)}catch(e){n(new ClientResponseError(e))}})))),a={state:this.client.realtime.clientId};(null===(o=t.scopes)||void 0===o?void 0:o.length)&&(a.scope=t.scopes.join(" "));const l=this._replaceQueryParams(i.authUrl+s,a);yield t.urlCallback?t.urlCallback(l):this._defaultUrlCallback(l)}catch(e){n(new ClientResponseError(e))}}))))}))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",i).then((e=>this.authResponse(e)))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}requestVerification(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is depreacted. Consider replacing it with requestVerification(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-verification",s).then((()=>!0))}confirmVerification(e,t,i){let s={method:"POST",body:{token:e}};return s=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is depreacted. Consider replacing it with confirmVerification(token, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/confirm-verification",s).then((()=>!0))}requestEmailChange(e,t,i){let s={method:"POST",body:{newEmail:e}};return s=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is depreacted. Consider replacing it with requestEmailChange(newEmail, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-email-change",s).then((()=>!0))}confirmEmailChange(e,t,i,s){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is depreacted. Consider replacing it with confirmEmailChange(token, password, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>!0))}listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}unlinkExternalAuth(e,t,i){return i=Object.assign({method:"DELETE"},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),i).then((()=>!0))}_replaceQueryParams(e,t={}){let i=e,s="";e.indexOf("?")>=0&&(i=e.substring(0,e.indexOf("?")),s=e.substring(e.indexOf("?")+1));const n={},o=s.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);s="";for(let e in n)n.hasOwnProperty(e)&&(""!=s&&(s+="&"),s+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=s?i+"?"+s:i}_defaultUrlCallback(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,i=768,s=window.innerWidth,n=window.innerHeight;t=t>s?s:t,i=i>n?n:i;let o=s/2-t/2,r=n/2-i/2;window.open(e,"oauth2-popup","width="+t+",height="+i+",top="+r+",left="+o+",resizable,menubar=no")}}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}import(e,t=!1,i){return __awaiter(this,void 0,void 0,(function*(){return i=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},i),this.client.send(this.baseCrudPath+"/import",i).then((()=>!0))}))}}class LogService extends BaseService{getRequestsList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send("/api/logs/requests",i)}getRequest(e,t){return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/requests/"+encodeURIComponent(e),t)}getRequestsStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/requests/stats",e)}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentTopics=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}subscribe(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!e)throw new Error("topic must be set.");const listener=function(e){const i=e;let s;try{s=JSON.parse(null==i?void 0:i.data)}catch(e){}t(s||{})};return this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(listener),this.isConnected?1===this.subscriptions[e].length?yield this.submitSubscriptions():null===(i=this.eventSource)||void 0===i||i.addEventListener(e,listener):yield this.connect(),()=>__awaiter(this,void 0,void 0,(function*(){return this.unsubscribeByTopicAndListener(e,listener)}))}))}unsubscribe(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this.hasSubscriptionListeners(e)){if(e){for(let i of this.subscriptions[e])null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,i);delete this.subscriptions[e]}else this.subscriptions={};this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect()}}))}unsubscribeByPrefix(e){var t;return __awaiter(this,void 0,void 0,(function*(){let i=!1;for(let s in this.subscriptions)if(s.startsWith(e)){i=!0;for(let e of this.subscriptions[s])null===(t=this.eventSource)||void 0===t||t.removeEventListener(s,e);delete this.subscriptions[s]}i&&(this.hasSubscriptionListeners()?yield this.submitSubscriptions():this.disconnect())}))}unsubscribeByTopicAndListener(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return;let s=!1;for(let n=this.subscriptions[e].length-1;n>=0;n--)this.subscriptions[e][n]===t&&(s=!0,delete this.subscriptions[e][n],this.subscriptions[e].splice(n,1),null===(i=this.eventSource)||void 0===i||i.removeEventListener(e,t));s&&(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect())}))}hasSubscriptionListeners(e){var t,i;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(let e in this.subscriptions)if(null===(i=this.subscriptions[e])||void 0===i?void 0:i.length)return!0;return!1}submitSubscriptions(){return __awaiter(this,void 0,void 0,(function*(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},query:{requestKey:this.getSubscriptionsCancelKey()}}).catch((e=>{if(!(null==e?void 0:e.isAbort))throw e}))}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getNonEmptySubscriptionTopics(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}connect(){return __awaiter(this,void 0,void 0,(function*(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=null==t?void 0:t.lastEventId,this.submitSubscriptions().then((()=>__awaiter(this,void 0,void 0,(function*(){let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,yield this.submitSubscriptions()})))).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(const t of e)if(!this.lastSentTopics.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){var t;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class HealthService extends BaseService{check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,i={}){const s=[];s.push("api"),s.push("files"),s.push(encodeURIComponent(e.collectionId||e.collectionName)),s.push(encodeURIComponent(e.id)),s.push(encodeURIComponent(t));let n=this.client.buildUrl(s.join("/"));if(Object.keys(i).length){!1===i.download&&delete i.download;const e=new URLSearchParams(i);n+=(n.includes("?")?"&":"?")+e}return n}getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>(null==e?void 0:e.token)||""))}}class BackupService extends BaseService{getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}const s=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];class Client{constructor(e="/",t,i="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=i,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}getFileUrl(e,t,i={}){return this.files.getUrl(e,t,i)}buildUrl(e){var t;let i=this.baseUrl;return"undefined"==typeof window||!window.location||i.startsWith("https://")||i.startsWith("http://")||(i=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(i+=window.location.pathname||"/",i+=i.endsWith("/")?"":"/"),i+=this.baseUrl),e&&(i+=i.endsWith("/")?"":"/",i+=e.startsWith("/")?e.substring(1):e),i}send(e,t){return __awaiter(this,void 0,void 0,(function*(){t=this.initSendOptions(e,t);let i=this.buildUrl(e);if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(i+=(i.includes("?")?"&":"?")+e),delete t.query}if(this.beforeSend){const e=Object.assign({},yield this.beforeSend(i,t));void 0!==e.url||void 0!==e.options?(i=e.url||i,t=e.options||t):Object.keys(e).length&&(t=e,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(i,t).then((e=>__awaiter(this,void 0,void 0,(function*(){let t={};try{t=yield e.json()}catch(e){}if(this.afterSend&&(t=yield this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})))).catch((e=>{throw new ClientResponseError(e)}))}))}initSendOptions(e,t){(t=Object.assign({method:"GET"},t)).query=t.query||{},t.body=this.convertToFormDataIfNeeded(t.body);for(let e in t)s.includes(e)||(t.query[e]=t[e],delete t[e]);if(t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const i=t.requestKey||(t.method||"GET")+e;this.cancelRequest(i);const s=new AbortController;this.cancelControllers[i]=s,t.signal=s.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(let i in e)t.append(i,e[i]);return t}hasBlobField(e){for(let t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];for(let e of i)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let i in e)if(i.toLowerCase()==t)return e[i];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const i in e){if(null===e[i])continue;const s=e[i],n=encodeURIComponent(i);if(Array.isArray(s))for(const e of s)t.push(n+"="+encodeURIComponent(e));else s instanceof Date?t.push(n+"="+encodeURIComponent(s.toISOString())):null!==typeof s&&"object"==typeof s?t.push(n+"="+encodeURIComponent(JSON.stringify(s))):t.push(n+"="+encodeURIComponent(s))}return t.join("&")}}class AsyncAuthStore extends BaseAuthStore{constructor(e){super(),this.queue=[],this.saveFunc=e.save,this.clearFunc=e.clear,this._loadInitial(e.initial)}save(e,t){super.save(e,t);let i="";try{i=JSON.stringify({token:e,model:t})}catch(e){console.warn("AsyncAuthStore: failed to stringify the new state")}this._enqueue((()=>this.saveFunc(i)))}clear(){super.clear(),this.clearFunc?this._enqueue((()=>this.clearFunc())):this._enqueue((()=>this.saveFunc("")))}_loadInitial(e){if(e)try{const t=JSON.parse(e)||{};this.save(t.token||"",t.model||null)}catch(e){}}_enqueue(e){this.queue.push(e),1==this.queue.length&&this._dequeue()}_dequeue(){this.queue.length&&this.queue[0]().finally((()=>{this.queue.shift(),this.queue.length&&this._dequeue()}))}}export{AdminService,AsyncAuthStore,BaseAuthStore,ClientResponseError,CollectionService,CrudService,LocalAuthStore,LogService,RealtimeService,RecordService,cookieParse,cookieSerialize,Client as default,getTokenPayload,isTokenExpired};
//# sourceMappingURL=pocketbase.es.js.map

@@ -12,3 +12,10 @@ interface SerializeOptions {

}
declare abstract class BaseModel {
interface ListResult<T> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<T>;
}
interface BaseModel {
[key: string]: any;

@@ -18,71 +25,61 @@ id: string;

updated: string;
constructor(data?: {
}
interface AdminModel extends BaseModel {
avatar: number;
email: string;
}
interface SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
});
/**
* Alias of this.$load(data).
*/
load(data: {
};
}
interface CollectionModel extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule?: string;
viewRule?: string;
createRule?: string;
updateRule?: string;
deleteRule?: string;
options: {
[key: string]: any;
}): void;
/**
* Loads `data` into the current model.
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Returns whether the current loaded data represent a stored db record.
*/
get $isNew(): boolean;
/**
* Alias of this.clone().
*/
clone(): BaseModel;
/**
* Creates a deep clone of the current model.
*/
$clone(): BaseModel;
/**
* Alias of this.$export().
*/
export(): {
[key: string]: any;
};
/**
* Exports all model properties as a new plain object.
*/
$export(): {
}
interface ExternalAuthModel extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
}
interface LogRequestModel extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
}
declare class Record extends BaseModel {
interface RecordModel extends BaseModel {
[key: string]: any;
collectionId: string;
collectionName: string;
expand: {
[key: string]: Record | Array<Record>;
expand?: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Loads the provided expand items and recursively normalizes each
* item to a `Record|Array<Record>`.
*/
private _loadExpand;
}
declare class Admin extends BaseModel {
avatar: number;
email: string;
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
type OnStoreChangeFunc = (token: string, model: Record | Admin | null) => void;
type AuthModel = RecordModel | AdminModel | null;
type OnStoreChangeFunc = (token: string, model: AuthModel) => void;
/**

@@ -94,3 +91,3 @@ * Base AuthStore class that is intended to be extended by all other

protected baseToken: string;
protected baseModel: Record | Admin | null;
protected baseModel: AuthModel;
private _onChangeCallbacks;

@@ -104,3 +101,3 @@ /**

*/
get model(): Record | Admin | null;
get model(): AuthModel;
/**

@@ -111,5 +108,13 @@ * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).

/**
* Checks whether the current store state is for admin authentication.
*/
get isAdmin(): boolean;
/**
* Checks whether the current store state is for auth record authentication.
*/
get isAuthRecord(): boolean;
/**
* Saves the provided new token and model data in the auth store.
*/
save(token: string, model: Record | Admin | null): void;
save(token: string, model?: AuthModel): void;
/**

@@ -177,9 +182,34 @@ * Removes the stored token and model data form the auth store.

}
interface BaseQueryParams {
[key: string]: any;
fields?: string;
interface SendOptions extends RequestInit {
[key: string]: any; // for backward compatibility
// optional custom fetch function to use for sending the request
fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
// custom headers to send with the requests
headers?: {
[key: string]: string;
};
// the body of the request (serialized automatically for json requests)
body?: any;
// query params that will be appended to the request url
query?: {
[key: string]: any;
};
// @deprecated use `query` instead
//
// for backward-compatibility `params` values are merged with `query`,
// but this option may get removed in the final v1 release
params?: {
[key: string]: any;
};
// the request identifier that can be used to cancel pending requests
requestKey?: string | null;
// @deprecated use `requestKey:string` instead
$cancelKey?: string;
// @deprecated use `requestKey:null` instead
$autoCancel?: boolean;
$cancelKey?: string;
}
interface ListQueryParams extends BaseQueryParams {
interface CommonOptions extends SendOptions {
fields?: string;
}
interface ListOptions extends CommonOptions {
page?: number;

@@ -191,16 +221,16 @@ perPage?: number;

}
interface FullListQueryParams extends ListQueryParams {
interface FullListOptions extends ListOptions {
batch?: number;
}
interface RecordQueryParams extends BaseQueryParams {
interface RecordOptions extends CommonOptions {
expand?: string;
}
interface RecordListQueryParams extends ListQueryParams, RecordQueryParams {
interface RecordListOptions extends ListOptions, RecordOptions {
}
interface RecordFullListQueryParams extends FullListQueryParams, RecordQueryParams {
interface RecordFullListOptions extends FullListOptions, RecordOptions {
}
interface LogStatsQueryParams extends BaseQueryParams {
interface LogStatsOptions extends CommonOptions {
filter?: string;
}
interface FileQueryParams extends BaseQueryParams {
interface FileOptions extends CommonOptions {
thumb?: string;

@@ -216,3 +246,3 @@ download?: boolean;

*/
getAll(queryParams?: BaseQueryParams): Promise<{
getAll(options?: CommonOptions): Promise<{
[key: string]: any;

@@ -223,4 +253,6 @@ }>;

*/
update(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<{
update(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<{
[key: string]: any;
}>;

@@ -232,3 +264,3 @@ /**

*/
testS3(filesystem?: string, queryParams?: BaseQueryParams): Promise<boolean>;
testS3(filesystem?: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -242,65 +274,20 @@ * Sends a test email.

*/
testEmail(toEmail: string, emailTemplate: string, queryParams?: BaseQueryParams): Promise<boolean>;
testEmail(toEmail: string, emailTemplate: string, options?: CommonOptions): Promise<boolean>;
/**
* Generates a new Apple OAuth2 client secret.
*/
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<appleClientSecret>;
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, options?: CommonOptions): Promise<appleClientSecret>;
}
declare class ListResult<M = BaseModel> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<M>;
constructor(page: number, perPage: number, totalItems: number, totalPages: number, items: Array<M>);
}
// @todo since there is no longer need of SubCrudService consider merging with CrudService in v0.9+
declare abstract class BaseCrudService<M extends BaseModel> extends BaseService {
declare abstract class CrudService<M> extends BaseService {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Response data decoder.
*/
abstract decode(data: {
decode<T = M>(data: {
[key: string]: any;
}): M;
}): T;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(basePath: string, batchSize?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
/**
* Returns paginated items list.
*/
protected _getList<T = M>(basePath: string, page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
/**
* Returns single item by its id.
*/
protected _getOne<T = M>(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Returns the first found item by a list filter.
*
* Internally it calls `_getList(basePath, 1, 1, { filter, skipTotal })`
* and returns its first item.
*
* For consistency with `_getOne`, this method will throw a 404
* ClientResponseError if no item was found.
*/
protected _getFirstListItem<T = M>(basePath: string, filter: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Creates a new item.
*/
protected _create<T = M>(basePath: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Updates an existing item by its id.
*/
protected _update<T = M>(basePath: string, id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Deletes an existing item by its id.
*/
protected _delete(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare abstract class CrudService<M extends BaseModel> extends BaseCrudService<M> {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Returns a promise with all list items batch fetched at once

@@ -311,7 +298,7 @@ * (by default 500 items per request; to change it set the `batch` query param).

*/
getFullList<T = M>(queryParams?: FullListQueryParams): Promise<Array<T>>;
getFullList<T = M>(options?: FullListOptions): Promise<Array<T>>;
/**
* Legacy version of getFullList with explicitly specified batch size.
*/
getFullList<T = M>(batch?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
getFullList<T = M>(batch?: number, options?: ListOptions): Promise<Array<T>>;
/**

@@ -322,3 +309,3 @@ * Returns paginated items list.

*/
getList<T = M>(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
getList<T = M>(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<T>>;
/**

@@ -335,3 +322,3 @@ * Returns the first found item by the specified filter.

*/
getFirstListItem<T = M>(filter: string, queryParams?: BaseQueryParams): Promise<T>;
getFirstListItem<T = M>(filter: string, options?: CommonOptions): Promise<T>;
/**

@@ -342,3 +329,3 @@ * Returns single item by its id.

*/
getOne<T = M>(id: string, queryParams?: BaseQueryParams): Promise<T>;
getOne<T = M>(id: string, options?: CommonOptions): Promise<T>;
/**

@@ -349,3 +336,5 @@ * Creates a new item.

*/
create<T = M>(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
create<T = M>(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -356,7 +345,13 @@ * Updates an existing item by its id.

*/
update<T = M>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = M>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**
* Deletes an existing item by its id.
*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(batchSize?: number, options?: ListOptions): Promise<Array<T>>;
}

@@ -366,14 +361,8 @@ interface AdminAuthResponse {

token: string;
admin: Admin;
admin: AdminModel;
}
declare class AdminService extends CrudService<Admin> {
declare class AdminService extends CrudService<AdminModel> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Admin;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -389,3 +378,5 @@ // ---------------------------------------------------------------

*/
update<T = Admin>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = AdminModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -397,3 +388,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -412,4 +403,9 @@ // Auth handlers

*/
authWithPassword(email: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authWithPassword(email: string, password: string, options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authWithPassword(email, password, options?).
*/
authWithPassword(email: string, password: string, body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Refreshes the current admin authenticated instance and

@@ -420,23 +416,26 @@ * returns a new token and admin data.

*/
authRefresh(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authRefresh(options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh(body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Sends admin password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms admin password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare class ExternalAuth extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @inheritdoc
* @deprecated
* Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).
*/
$load(data: {
[key: string]: any;
}): void;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
}

@@ -512,5 +511,11 @@ type UnsubscribeFunc = () => Promise<void>;

}
interface RecordAuthResponse<T = Record> {
interface RecordAuthResponse<T = RecordModel> {
// The signed PocketBase auth record.
record: T;
// The PocketBase record auth token.
//
// If you are looking for the OAuth2 access and refresh tokens
// they are available under the `meta.accessToken` and `meta.refreshToken` props.
token: string;
// Auth meta data usually filled when OAuth2 is used.
meta?: {

@@ -533,3 +538,3 @@ [key: string]: any;

}
interface RecordSubscription<T = Record> {
interface RecordSubscription<T = RecordModel> {
action: string; // eg. create, update, delete

@@ -539,3 +544,3 @@ record: T;

type OAuth2UrlCallback = (url: string) => void | Promise<void>;
interface OAuth2AuthConfig {
interface OAuth2AuthConfig extends SendOptions {
// the name of the OAuth2 provider (eg. "google")

@@ -552,9 +557,5 @@ provider: string;

// optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)
query?: RecordQueryParams;
// optional body params to send with the PocketBase auth request
body?: {
[key: string]: any;
};
query?: RecordOptions;
}
declare class RecordService extends CrudService<Record> {
declare class RecordService extends CrudService<RecordModel> {
readonly collectionIdOrName: string;

@@ -565,8 +566,2 @@ constructor(client: Client, collectionIdOrName: string);

*/
decode<T = Record>(data: {
[key: string]: any;
}): T;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -585,7 +580,7 @@ /**

*/
subscribeOne<T = Record>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribeOne<T = RecordModel>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**
* @deprecated This form of subscribe is deprecated. Please use `subscribe("*", callback)`.
*/
subscribe<T = Record>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -604,3 +599,3 @@ * Subscribe to realtime changes to the specified topic ("*" or record id).

*/
subscribe<T = Record>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -620,23 +615,25 @@ * Unsubscribe from all subscriptions of the specified topic

*/
getFullList<T = Record>(queryParams?: RecordFullListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(options?: RecordFullListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getFullList<T = Record>(batch?: number, queryParams?: RecordListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(batch?: number, options?: RecordListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getList<T = Record>(page?: number, perPage?: number, queryParams?: RecordListQueryParams): Promise<ListResult<T>>;
getList<T = RecordModel>(page?: number, perPage?: number, options?: RecordListOptions): Promise<ListResult<T>>;
/**
* @inheritdoc
*/
getFirstListItem<T = Record>(filter: string, queryParams?: RecordListQueryParams): Promise<T>;
getFirstListItem<T = RecordModel>(filter: string, options?: RecordListOptions): Promise<T>;
/**
* @inheritdoc
*/
getOne<T = Record>(id: string, queryParams?: RecordQueryParams): Promise<T>;
getOne<T = RecordModel>(id: string, options?: RecordOptions): Promise<T>;
/**
* @inheritdoc
*/
create<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
create<T = RecordModel>(bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -648,3 +645,5 @@ * @inheritdoc

*/
update<T = Record>(id: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
update<T = RecordModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -656,3 +655,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -664,7 +663,7 @@ // Auth handlers

*/
protected authResponse<T = Record>(responseData: any): RecordAuthResponse<T>;
protected authResponse<T = RecordModel>(responseData: any): RecordAuthResponse<T>;
/**
* Returns all available collection auth methods.
*/
listAuthMethods(queryParams?: BaseQueryParams): Promise<AuthMethodsList>;
listAuthMethods(options?: CommonOptions): Promise<AuthMethodsList>;
/**

@@ -678,4 +677,9 @@ * Authenticate a single auth collection record via its username/email and password.

*/
authWithPassword<T = Record>(usernameOrEmail: string, password: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithPassword(usernameOrEmail, password, options?).
*/
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Authenticate a single auth collection record with OAuth2 code.

@@ -691,4 +695,13 @@ *

*/
authWithOAuth2Code<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {}, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).
*/
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* @deprecated This form of authWithOAuth2 is deprecated.

@@ -699,7 +712,7 @@ *

*/
authWithOAuth2<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
authWithOAuth2<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, bodyParams?: {
[key: string]: any;
}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
}, queryParams?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**

@@ -736,3 +749,3 @@ * Authenticate a single auth collection record with OAuth2

*/
authWithOAuth2<T = Record>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
authWithOAuth2<T = RecordModel>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
/**

@@ -744,35 +757,70 @@ * Refreshes the current authenticated record instance and

*/
authRefresh<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authRefresh<T = RecordModel>(options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh<T = RecordModel>(body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Sends auth record password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends auth record verification email request.
*/
requestVerification(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestVerification(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestVerification(email, options?).
*/
requestVerification(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record email verification request.
*/
confirmVerification(verificationToken: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmVerification(verificationToken: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmVerification(verificationToken, options?).
*/
confirmVerification(verificationToken: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends an email change request to the authenticated record model.
*/
requestEmailChange(newEmail: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestEmailChange(newEmail: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestEmailChange(newEmail, options?).
*/
requestEmailChange(newEmail: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record's new email address.
*/
confirmEmailChange(emailChangeToken: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmEmailChange(emailChangeToken: string, password: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmEmailChange(emailChangeToken, password, options?).
*/
confirmEmailChange(emailChangeToken: string, password: string, body?: any, query?: any): Promise<boolean>;
/**
* Lists all linked external auth providers for the specified auth record.
*/
listExternalAuths(recordId: string, queryParams?: BaseQueryParams): Promise<Array<ExternalAuth>>;
listExternalAuths(recordId: string, options?: CommonOptions): Promise<Array<ExternalAuthModel>>;
/**
* Unlink a single external auth provider from the specified auth record.
*/
unlinkExternalAuth(recordId: string, provider: string, queryParams?: BaseQueryParams): Promise<boolean>;
unlinkExternalAuth(recordId: string, provider: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -786,70 +834,6 @@ // very rudimentary url query params replacement because at the moment

}
declare class SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
};
constructor(data?: {
[key: string]: any;
});
}
declare class Collection extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule: null | string;
viewRule: null | string;
createRule: null | string;
updateRule: null | string;
deleteRule: null | string;
options: {
[key: string]: any;
};
declare class CollectionService extends CrudService<CollectionModel> {
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* @deprecated Please use $isBase instead.
*/
get isBase(): boolean;
/**
* Checks if the current model is "base" collection.
*/
get $isBase(): boolean;
/**
* @deprecated Please use $isAuth instead.
*/
get isAuth(): boolean;
/**
* Checks if the current model is "auth" collection.
*/
get $isAuth(): boolean;
/**
* @deprecated Please use $isView instead.
*/
get isView(): boolean;
/**
* Checks if the current model is "view" collection.
*/
get $isView(): boolean;
}
declare class CollectionService extends CrudService<Collection> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Collection;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -863,23 +847,4 @@ /**

*/
import(collections: Array<Collection>, deleteMissing?: boolean, queryParams?: BaseQueryParams): Promise<true>;
import(collections: Array<CollectionModel>, deleteMissing?: boolean, options?: CommonOptions): Promise<true>;
}
declare class LogRequest extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
interface HourlyStats {

@@ -893,11 +858,11 @@ total: number;

*/
getRequestsList(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<LogRequest>>;
getRequestsList(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<LogRequestModel>>;
/**
* Returns a single logged request by its id.
*/
getRequest(id: string, queryParams?: BaseQueryParams): Promise<LogRequest>;
getRequest(id: string, options?: CommonOptions): Promise<LogRequestModel>;
/**
* Returns request logs statistics.
*/
getRequestsStats(queryParams?: LogStatsQueryParams): Promise<Array<HourlyStats>>;
getRequestsStats(options?: LogStatsOptions): Promise<Array<HourlyStats>>;
}

@@ -915,3 +880,3 @@ interface HealthCheckResponse {

*/
check(queryParams?: BaseQueryParams): Promise<HealthCheckResponse>;
check(options?: CommonOptions): Promise<HealthCheckResponse>;
}

@@ -922,7 +887,9 @@ declare class FileService extends BaseService {

*/
getUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
getUrl(record: Pick<{
[key: string]: any;
}, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileOptions): string;
/**
* Requests a new private file access token for the current auth model (admin or record).
*/
getToken(queryParams?: BaseQueryParams): Promise<string>;
getToken(options?: CommonOptions): Promise<string>;
}

@@ -938,15 +905,15 @@ interface BackupFileInfo {

*/
getFullList(queryParams?: BaseQueryParams): Promise<Array<BackupFileInfo>>;
getFullList(options?: CommonOptions): Promise<Array<BackupFileInfo>>;
/**
* Initializes a new backup.
*/
create(basename: string, queryParams?: BaseQueryParams): Promise<boolean>;
create(basename: string, options?: CommonOptions): Promise<boolean>;
/**
* Deletes a single backup file.
*/
delete(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(key: string, options?: CommonOptions): Promise<boolean>;
/**
* Initializes an app data restore from an existing backup.
*/
restore(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
restore(key: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -960,9 +927,2 @@ * Builds a download url for a single existing backup using an

}
interface SendOptions extends RequestInit {
headers?: {
[key: string]: string;
};
body?: any;
params?: BaseQueryParams;
}
interface BeforeSendResult {

@@ -1096,3 +1056,3 @@ [key: string]: any;

*/
cancelRequest(cancelKey: string): Client;
cancelRequest(requestKey: string): Client;
/**

@@ -1106,2 +1066,18 @@ * Cancels all pending requests.

/**
* Legacy alias of `pb.files.getUrl()`.
*/
/**
* Legacy alias of `pb.files.getUrl()`.
*/
getFileUrl(record: Pick<{
[key: string]: any;
}, 'id' | 'collectionId' | 'collectionName'>, filename: string, queryParams?: FileOptions): string;
/**
* Builds a full client url by safely concatenating the provided path.
*/
/**
* Builds a full client url by safely concatenating the provided path.
*/
buildUrl(path: string): string;
/**
* Sends an api http request.

@@ -1112,18 +1088,44 @@ */

*/
send<T = any>(path: string, reqOptions: SendOptions): Promise<T>;
send<T = any>(path: string, options: SendOptions): Promise<T>;
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
getFileUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
private initSendOptions;
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
buildUrl(path: string): string;
private convertToFormDataIfNeeded;
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
private hasBlobField;
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
private getHeader;
/**
* Loosely checks if the specified body is a FormData instance.

@@ -1143,2 +1145,2 @@ */

}
export { SendOptions, BeforeSendResult, Client as default };
export { BeforeSendResult, Client as default };

@@ -1,2 +0,2 @@

var PocketBase=function(){"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}var __assign=function(){return __assign=Object.assign||function __assign(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}function __generator(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function verb(a){return function(c){return function step(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}var e,t=function(e){function ClientResponseError(t){var n,i,o,r,s=this;return(s=e.call(this,"ClientResponseError")||this).url="",s.status=0,s.response={},s.isAbort=!1,s.originalError=null,Object.setPrototypeOf(s,ClientResponseError.prototype),null!==t&&"object"==typeof t&&(s.url="string"==typeof t.url?t.url:"",s.status="number"==typeof t.status?t.status:0,s.isAbort=!!t.isAbort,s.originalError=t.originalError,null!==t.response&&"object"==typeof t.response?s.response=t.response:null!==t.data&&"object"==typeof t.data?s.response=t.data:s.response={}),s.originalError||t instanceof ClientResponseError||(s.originalError=t),"undefined"!=typeof DOMException&&t instanceof DOMException&&(s.isAbort=!0),s.name="ClientResponseError "+s.status,s.message=null===(n=s.response)||void 0===n?void 0:n.message,s.message||(s.isAbort?s.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(r=null===(o=null===(i=s.originalError)||void 0===i?void 0:i.cause)||void 0===o?void 0:o.message)||void 0===r?void 0:r.includes("ECONNREFUSED ::1"))?s.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":s.message="Something went wrong while processing your request."),s}return __extends(ClientResponseError,e),Object.defineProperty(ClientResponseError.prototype,"data",{get:function(){return this.response},enumerable:!1,configurable:!0}),ClientResponseError.prototype.toJSON=function(){return __assign({},this)},ClientResponseError}(Error),n=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(e,t,i){var o=Object.assign({},i||{}),r=o.encode||defaultEncode;if(!n.test(e))throw new TypeError("argument name is invalid");var s=r(t);if(s&&!n.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(null!=o.maxAge){var c=o.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(o.domain){if(!n.test(o.domain))throw new TypeError("option domain is invalid");a+="; Domain="+o.domain}if(o.path){if(!n.test(o.path))throw new TypeError("option path is invalid");a+="; Path="+o.path}if(o.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(o.expires)||isNaN(o.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.priority)switch("string"==typeof o.priority?o.priority.toLowerCase():o.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}function getTokenPayload(t){if(t)try{var n=decodeURIComponent(e(t.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)||{}}catch(e){}return{}}e="function"==typeof atob?atob:function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,o=0,r=0,s="";i=t.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};var i=function(){function BaseModel(e){void 0===e&&(e={}),this.$load(e||{})}return BaseModel.prototype.load=function(e){return this.$load(e)},BaseModel.prototype.$load=function(e){for(var t=0,n=Object.entries(e);t<n.length;t++){var i=n[t],o=i[0],r=i[1];this[o]=r}this.id=void 0!==e.id?e.id:"",this.created=void 0!==e.created?e.created:"",this.updated=void 0!==e.updated?e.updated:""},Object.defineProperty(BaseModel.prototype,"$isNew",{get:function(){return!this.id},enumerable:!1,configurable:!0}),BaseModel.prototype.clone=function(){return this.$clone()},BaseModel.prototype.$clone=function(){var e="function"==typeof structuredClone?structuredClone(this):JSON.parse(JSON.stringify(this));return new this.constructor(e)},BaseModel.prototype.export=function(){return this.$export()},BaseModel.prototype.$export=function(){return"function"==typeof structuredClone?structuredClone(this):Object.assign({},this)},BaseModel}(),o=function(e){function Record(){return null!==e&&e.apply(this,arguments)||this}return __extends(Record,e),Record.prototype.$load=function(t){e.prototype.$load.call(this,t),this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.collectionName="string"==typeof t.collectionName?t.collectionName:"",this._loadExpand(t.expand)},Record.prototype._loadExpand=function(e){for(var t in e=e||{},this.expand={},e)Array.isArray(e[t])?this.expand[t]=e[t].map((function(e){return new Record(e||{})})):this.expand[t]=new Record(e[t]||{})},Record}(i),r=function(e){function Admin(){return null!==e&&e.apply(this,arguments)||this}return __extends(Admin,e),Admin.prototype.$load=function(t){e.prototype.$load.call(this,t),this.avatar="number"==typeof t.avatar?t.avatar:0,this.email="string"==typeof t.email?t.email:""},Admin}(i),s="pb_auth",a=function(e){function LocalAuthStore(t){void 0===t&&(t="pocketbase_auth");var n=e.call(this)||this;return n.storageFallback={},n.storageKey=t,n}return __extends(LocalAuthStore,e),Object.defineProperty(LocalAuthStore.prototype,"token",{get:function(){return(this._storageGet(this.storageKey)||{}).token||""},enumerable:!1,configurable:!0}),Object.defineProperty(LocalAuthStore.prototype,"model",{get:function(){var e,t=this._storageGet(this.storageKey)||{};return null===t||"object"!=typeof t||null===t.model||"object"!=typeof t.model?null:void 0===(null===(e=t.model)||void 0===e?void 0:e.collectionId)?new r(t.model):new o(t.model)},enumerable:!1,configurable:!0}),LocalAuthStore.prototype.save=function(t,n){this._storageSet(this.storageKey,{token:t,model:n}),e.prototype.save.call(this,t,n)},LocalAuthStore.prototype.clear=function(){this._storageRemove(this.storageKey),e.prototype.clear.call(this)},LocalAuthStore.prototype._storageGet=function(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]},LocalAuthStore.prototype._storageSet=function(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var n=t;"string"!=typeof t&&(n=JSON.stringify(t)),window.localStorage.setItem(e,n)}else this.storageFallback[e]=t},LocalAuthStore.prototype._storageRemove=function(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]},LocalAuthStore}(function(){function BaseAuthStore(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}return Object.defineProperty(BaseAuthStore.prototype,"token",{get:function(){return this.baseToken},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"model",{get:function(){return this.baseModel},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"isValid",{get:function(){return!function isTokenExpired(e,t){void 0===t&&(t=0);var n=getTokenPayload(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}(this.token)},enumerable:!1,configurable:!0}),BaseAuthStore.prototype.save=function(e,t){this.baseToken=e||"",this.baseModel=null!==t&&"object"==typeof t?void 0!==t.collectionId?new o(t):new r(t):null,this.triggerChange()},BaseAuthStore.prototype.clear=function(){this.baseToken="",this.baseModel=null,this.triggerChange()},BaseAuthStore.prototype.loadFromCookie=function(e,t){void 0===t&&(t=s);var n=function cookieParse(e,t){var n={};if("string"!=typeof e)return n;for(var i=Object.assign({},t||{}).decode||defaultDecode,o=0;o<e.length;){var r=e.indexOf("=",o);if(-1===r)break;var s=e.indexOf(";",o);if(-1===s)s=e.length;else if(s<r){o=e.lastIndexOf(";",r-1)+1;continue}var a=e.slice(o,r).trim();if(void 0===n[a]){var c=e.slice(r+1,s).trim();34===c.charCodeAt(0)&&(c=c.slice(1,-1));try{n[a]=i(c)}catch(e){n[a]=c}}o=s+1}return n}(e||"")[t]||"",i={};try{(null===typeof(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))&&(i={})}catch(e){}this.save(i.token||"",i.model||null)},BaseAuthStore.prototype.exportToCookie=function(e,t){var n,i,r;void 0===t&&(t=s);var a={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},c=getTokenPayload(this.token);(null==c?void 0:c.exp)?a.expires=new Date(1e3*c.exp):a.expires=new Date("1970-01-01"),e=Object.assign({},a,e);var u={token:this.token,model:(null===(n=this.model)||void 0===n?void 0:n.export())||null},l=cookieSerialize(t,JSON.stringify(u),e),d="undefined"!=typeof Blob?new Blob([l]).size:l.length;return u.model&&d>4096&&(u.model={id:null===(i=null==u?void 0:u.model)||void 0===i?void 0:i.id,email:null===(r=null==u?void 0:u.model)||void 0===r?void 0:r.email},this.model instanceof o&&(u.model.username=this.model.username,u.model.verified=this.model.verified,u.model.collectionId=this.model.collectionId),l=cookieSerialize(t,JSON.stringify(u),e)),l},BaseAuthStore.prototype.onChange=function(e,t){var n=this;return void 0===t&&(t=!1),this._onChangeCallbacks.push(e),t&&e(this.token,this.model),function(){for(var t=n._onChangeCallbacks.length-1;t>=0;t--)if(n._onChangeCallbacks[t]==e)return delete n._onChangeCallbacks[t],void n._onChangeCallbacks.splice(t,1)}},BaseAuthStore.prototype.triggerChange=function(){for(var e=0,t=this._onChangeCallbacks;e<t.length;e++){var n=t[e];n&&n(this.token,this.model)}},BaseAuthStore}()),c=function c(e){this.client=e},u=function(e){function SettingsService(){return null!==e&&e.apply(this,arguments)||this}return __extends(SettingsService,e),SettingsService.prototype.getAll=function(e){return void 0===e&&(e={}),this.client.send("/api/settings",{method:"GET",params:e}).then((function(e){return e||{}}))},SettingsService.prototype.update=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send("/api/settings",{method:"PATCH",params:t,body:e}).then((function(e){return e||{}}))},SettingsService.prototype.testS3=function(e,t){void 0===e&&(e="storage"),void 0===t&&(t={});var n={filesystem:e};return this.client.send("/api/settings/test/s3",{method:"POST",params:t,body:n}).then((function(){return!0}))},SettingsService.prototype.testEmail=function(e,t,n){void 0===n&&(n={});var i={email:e,template:t};return this.client.send("/api/settings/test/email",{method:"POST",params:n,body:i}).then((function(){return!0}))},SettingsService.prototype.generateAppleClientSecret=function(e,t,n,i,o,r,s){return void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({clientId:e,teamId:t,keyId:n,privateKey:i,duration:o},r),this.client.send("/api/settings/apple/generate-client-secret",{method:"POST",params:s,body:r})},SettingsService}(c),l=function l(e,t,n,i,o){this.page=e>0?e:1,this.perPage=t>=0?t:0,this.totalItems=n>=0?n:0,this.totalPages=i>=0?i:0,this.items=o||[]},d=function(e){function BaseCrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BaseCrudService,e),BaseCrudService.prototype._getFullList=function(e,t,n){var i=this;void 0===t&&(t=500),void 0===n&&(n={}),n=Object.assign({skipTotal:1},n);var o=[],request=function(r){return __awaiter(i,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this._getList(e,r,t||500,n).then((function(e){var t=e.items;return o=o.concat(t),t.length==e.perPage?request(r+1):o}))]}))}))};return request(1)},BaseCrudService.prototype._getList=function(e,t,n,i){var o=this;return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),i=Object.assign({page:t,perPage:n},i),this.client.send(e,{method:"GET",params:i}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=e.items||[];for(var n=0,i=e.items;n<i.length;n++){var r=i[n];t.push(o.decode(r))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},BaseCrudService.prototype._getOne=function(e,t,n){var i=this;return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"GET",params:n}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._getFirstListItem=function(e,n,i){return void 0===i&&(i={}),i=Object.assign({filter:n,skipTotal:1,$cancelKey:"one_by_filter_"+e+"_"+n},i),this._getList(e,1,1,i).then((function(e){var n;if(!(null===(n=null==e?void 0:e.items)||void 0===n?void 0:n.length))throw new t({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))},BaseCrudService.prototype._create=function(e,t,n){var i=this;return void 0===t&&(t={}),void 0===n&&(n={}),this.client.send(e,{method:"POST",params:n,body:t}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._update=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"PATCH",params:i,body:n}).then((function(e){return o.decode(e)}))},BaseCrudService.prototype._delete=function(e,t,n){return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},BaseCrudService}(c),h=function(e){function CrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CrudService,e),CrudService.prototype.getFullList=function(e,t){if("number"==typeof e)return this._getFullList(this.baseCrudPath,e,t);var n=Object.assign({},e,t),i=500;return n.batch&&(i=n.batch,delete n.batch),this._getFullList(this.baseCrudPath,i,n)},CrudService.prototype.getList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),this._getList(this.baseCrudPath,e,t,n)},CrudService.prototype.getFirstListItem=function(e,t){return void 0===t&&(t={}),this._getFirstListItem(this.baseCrudPath,e,t)},CrudService.prototype.getOne=function(e,t){return void 0===t&&(t={}),this._getOne(this.baseCrudPath,e,t)},CrudService.prototype.create=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this._create(this.baseCrudPath,e,t)},CrudService.prototype.update=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),this._update(this.baseCrudPath,e,t,n)},CrudService.prototype.delete=function(e,t){return void 0===t&&(t={}),this._delete(this.baseCrudPath,e,t)},CrudService}(d),p=function(e){function AdminService(){return null!==e&&e.apply(this,arguments)||this}return __extends(AdminService,e),AdminService.prototype.decode=function(e){return new r(e)},Object.defineProperty(AdminService.prototype,"baseCrudPath",{get:function(){return"/api/admins"},enumerable:!1,configurable:!0}),AdminService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n;return o.client.authStore.model&&void 0===(null===(t=o.client.authStore.model)||void 0===t?void 0:t.collectionId)&&(null===(n=o.client.authStore.model)||void 0===n?void 0:n.id)===(null==e?void 0:e.id)&&o.client.authStore.save(o.client.authStore.token,e),e}))},AdminService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o;return e&&i.client.authStore.model&&void 0===(null===(n=i.client.authStore.model)||void 0===n?void 0:n.collectionId)&&(null===(o=i.client.authStore.model)||void 0===o?void 0:o.id)===t&&i.client.authStore.clear(),e}))},AdminService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})},AdminService.prototype.authWithPassword=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCrudPath+"/auth-with-password",{method:"POST",params:i,body:n}).then(this.authResponse.bind(this))},AdminService.prototype.authRefresh=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/auth-refresh",{method:"POST",params:t,body:e}).then(this.authResponse.bind(this))},AdminService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCrudPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},AdminService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCrudPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},AdminService}(h),v=function(e){function ExternalAuth(){return null!==e&&e.apply(this,arguments)||this}return __extends(ExternalAuth,e),ExternalAuth.prototype.$load=function(t){e.prototype.$load.call(this,t),this.recordId="string"==typeof t.recordId?t.recordId:"",this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.provider="string"==typeof t.provider?t.provider:"",this.providerId="string"==typeof t.providerId?t.providerId:""},ExternalAuth}(i),f=function(e){function RecordService(t,n){var i=e.call(this,t)||this;return i.collectionIdOrName=n,i}return __extends(RecordService,e),RecordService.prototype.decode=function(e){return new o(e)},Object.defineProperty(RecordService.prototype,"baseCrudPath",{get:function(){return this.baseCollectionPath+"/records"},enumerable:!1,configurable:!0}),Object.defineProperty(RecordService.prototype,"baseCollectionPath",{get:function(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)},enumerable:!1,configurable:!0}),RecordService.prototype.subscribeOne=function(e,t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)]}))}))},RecordService.prototype.subscribe=function(e,t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(i){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName,e)];if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");return n=this.collectionIdOrName,"*"!==e&&(n+="/"+e),[2,this.client.realtime.subscribe(n,t)]}))}))},RecordService.prototype.unsubscribe=function(e){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return"*"===e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName)]:e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e)]:[2,this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)]}))}))},RecordService.prototype.getFullList=function(t,n){if("number"==typeof t)return e.prototype.getFullList.call(this,t,n);var i=Object.assign({},t,n);return e.prototype.getFullList.call(this,i)},RecordService.prototype.getList=function(t,n,i){return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),e.prototype.getList.call(this,t,n,i)},RecordService.prototype.getFirstListItem=function(t,n){return void 0===n&&(n={}),e.prototype.getFirstListItem.call(this,t,n)},RecordService.prototype.getOne=function(t,n){return void 0===n&&(n={}),e.prototype.getOne.call(this,t,n)},RecordService.prototype.create=function(t,n){return void 0===t&&(t={}),void 0===n&&(n={}),e.prototype.create.call(this,t,n)},RecordService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n,i;return(null===(t=o.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(n=o.client.authStore.model)||void 0===n?void 0:n.collectionId)!==o.collectionIdOrName&&(null===(i=o.client.authStore.model)||void 0===i?void 0:i.collectionName)!==o.collectionIdOrName||o.client.authStore.save(o.client.authStore.token,e),e}))},RecordService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o,r;return!e||(null===(n=i.client.authStore.model)||void 0===n?void 0:n.id)!==t||(null===(o=i.client.authStore.model)||void 0===o?void 0:o.collectionId)!==i.collectionIdOrName&&(null===(r=i.client.authStore.model)||void 0===r?void 0:r.collectionName)!==i.collectionIdOrName||i.client.authStore.clear(),e}))},RecordService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})},RecordService.prototype.listAuthMethods=function(e){return void 0===e&&(e={}),this.client.send(this.baseCollectionPath+"/auth-methods",{method:"GET",params:e}).then((function(e){return Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})}))},RecordService.prototype.authWithPassword=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCollectionPath+"/auth-with-password",{method:"POST",params:i,body:n}).then((function(e){return o.authResponse(e)}))},RecordService.prototype.authWithOAuth2Code=function(e,t,n,i,o,r,s){var a=this;return void 0===o&&(o={}),void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({provider:e,code:t,codeVerifier:n,redirectUrl:i,createData:o},r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",{method:"POST",params:s,body:r}).then((function(e){return a.authResponse(e)}))},RecordService.prototype.authWithOAuth2=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s=this;return __generator(this,(function(a){switch(a.label){case 0:return e.length>1||"string"==typeof(null==e?void 0:e[0])?(console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),[2,this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{})]):(n=(null==e?void 0:e[0])||{},[4,this.listAuthMethods()]);case 1:if(i=a.sent(),!(o=i.authProviders.find((function(e){return e.name===n.provider}))))throw new t(new Error('Missing or invalid provider "'.concat(n.provider,'".')));return r=this.client.buildUrl("/api/oauth2-redirect"),[2,new Promise((function(e,i){return __awaiter(s,void 0,void 0,(function(){var s,a,c,u,l,d=this;return __generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this.client.realtime.subscribe("@oauth2",(function(a){return __awaiter(d,void 0,void 0,(function(){var c,u,l;return __generator(this,(function(d){switch(d.label){case 0:c=this.client.realtime.clientId,d.label=1;case 1:if(d.trys.push([1,3,,4]),s(),!a.state||c!==a.state)throw new Error("State parameters don't match.");return[4,this.authWithOAuth2Code(o.name,a.code,o.codeVerifier,r,n.createData,n.body,n.query)];case 2:return u=d.sent(),e(u),[3,4];case 3:return l=d.sent(),i(new t(l)),[3,4];case 4:return[2]}}))}))}))];case 1:return s=h.sent(),a={state:this.client.realtime.clientId},(null===(l=n.scopes)||void 0===l?void 0:l.length)&&(a.scope=n.scopes.join(" ")),c=this._replaceQueryParams(o.authUrl+r,a),[4,n.urlCallback?n.urlCallback(c):this._defaultUrlCallback(c)];case 2:return h.sent(),[3,4];case 3:return u=h.sent(),i(new t(u)),[3,4];case 4:return[2]}}))}))}))]}}))}))},RecordService.prototype.authRefresh=function(e,t){var n=this;return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCollectionPath+"/auth-refresh",{method:"POST",params:t,body:e}).then((function(e){return n.authResponse(e)}))},RecordService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCollectionPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},RecordService.prototype.requestVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({token:e},t),this.client.send(this.baseCollectionPath+"/confirm-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.requestEmailChange=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({newEmail:e},t),this.client.send(this.baseCollectionPath+"/request-email-change",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmEmailChange=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({token:e,password:t},n),this.client.send(this.baseCollectionPath+"/confirm-email-change",{method:"POST",params:i,body:n}).then((function(){return!0}))},RecordService.prototype.listExternalAuths=function(e,t){return void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",{method:"GET",params:t}).then((function(e){var t=[];if(Array.isArray(e))for(var n=0,i=e;n<i.length;n++){var o=i[n];t.push(new v(o))}return t}))},RecordService.prototype.unlinkExternalAuth=function(e,t,n){return void 0===n&&(n={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},RecordService.prototype._replaceQueryParams=function(e,t){void 0===t&&(t={});var n=e,i="";e.indexOf("?")>=0&&(n=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));for(var o={},r=0,s=i.split("&");r<s.length;r++){var a=s[r];if(""!=a){var c=a.split("=");o[decodeURIComponent(c[0].replace(/\+/g," "))]=decodeURIComponent((c[1]||"").replace(/\+/g," "))}}for(var u in t)t.hasOwnProperty(u)&&(null==t[u]?delete o[u]:o[u]=t[u]);for(var u in i="",o)o.hasOwnProperty(u)&&(""!=i&&(i+="&"),i+=encodeURIComponent(u.replace(/%20/g,"+"))+"="+encodeURIComponent(o[u].replace(/%20/g,"+")));return""!=i?n+"?"+i:n},RecordService.prototype._defaultUrlCallback=function(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new t(new Error("Not in a browser context - please pass a custom urlCallback function."));var n=1024,i=768,o=window.innerWidth,r=window.innerHeight,s=o/2-(n=n>o?o:n)/2,a=r/2-(i=i>r?r:i)/2;window.open(e,"oauth2-popup","width="+n+",height="+i+",top="+a+",left="+s+",resizable,menubar=no")},RecordService}(h),m=function m(e){void 0===e&&(e={}),this.id=void 0!==e.id?e.id:"",this.name=void 0!==e.name?e.name:"",this.type=void 0!==e.type?e.type:"text",this.system=!!e.system,this.required=!!e.required,this.options="object"==typeof e.options&&null!==e.options?e.options:{}},b=function(e){function Collection(){return null!==e&&e.apply(this,arguments)||this}return __extends(Collection,e),Collection.prototype.$load=function(t){e.prototype.$load.call(this,t),this.system=!!t.system,this.name="string"==typeof t.name?t.name:"",this.type="string"==typeof t.type?t.type:"base",this.options=void 0!==t.options&&null!==t.options?t.options:{},this.indexes=Array.isArray(t.indexes)?t.indexes:[],this.listRule="string"==typeof t.listRule?t.listRule:null,this.viewRule="string"==typeof t.viewRule?t.viewRule:null,this.createRule="string"==typeof t.createRule?t.createRule:null,this.updateRule="string"==typeof t.updateRule?t.updateRule:null,this.deleteRule="string"==typeof t.deleteRule?t.deleteRule:null,t.schema=Array.isArray(t.schema)?t.schema:[],this.schema=[];for(var n=0,i=t.schema;n<i.length;n++){var o=i[n];this.schema.push(new m(o))}},Object.defineProperty(Collection.prototype,"isBase",{get:function(){return this.$isBase},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isBase",{get:function(){return"base"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isAuth",{get:function(){return this.$isAuth},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isAuth",{get:function(){return"auth"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isView",{get:function(){return this.$isView},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isView",{get:function(){return"view"===this.type},enumerable:!1,configurable:!0}),Collection}(i),y=function(e){function CollectionService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CollectionService,e),CollectionService.prototype.decode=function(e){return new b(e)},Object.defineProperty(CollectionService.prototype,"baseCrudPath",{get:function(){return"/api/collections"},enumerable:!1,configurable:!0}),CollectionService.prototype.import=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this.client.send(this.baseCrudPath+"/import",{method:"PUT",params:n,body:{collections:e,deleteMissing:t}}).then((function(){return!0}))]}))}))},CollectionService}(h),g=function(e){function LogRequest(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogRequest,e),LogRequest.prototype.$load=function(t){e.prototype.$load.call(this,t),t.remoteIp=t.remoteIp||t.ip,this.url="string"==typeof t.url?t.url:"",this.method="string"==typeof t.method?t.method:"GET",this.status="number"==typeof t.status?t.status:200,this.auth="string"==typeof t.auth?t.auth:"guest",this.remoteIp="string"==typeof t.remoteIp?t.remoteIp:"",this.userIp="string"==typeof t.userIp?t.userIp:"",this.referer="string"==typeof t.referer?t.referer:"",this.userAgent="string"==typeof t.userAgent?t.userAgent:"",this.meta="object"==typeof t.meta&&null!==t.meta?t.meta:{}},LogRequest}(i),S=function(e){function LogService(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogService,e),LogService.prototype.getRequestsList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),n=Object.assign({page:e,perPage:t},n),this.client.send("/api/logs/requests",{method:"GET",params:n}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=(null==e?void 0:e.items)||[];for(var n=0,i=e.items;n<i.length;n++){var o=i[n];t.push(new g(o))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},LogService.prototype.getRequest=function(e,t){return void 0===t&&(t={}),this.client.send("/api/logs/requests/"+encodeURIComponent(e),{method:"GET",params:t}).then((function(e){return new g(e)}))},LogService.prototype.getRequestsStats=function(e){return void 0===e&&(e={}),this.client.send("/api/logs/requests/stats",{method:"GET",params:e}).then((function(e){return e}))},LogService}(c),w=function(e){function RealtimeService(){var t=null!==e&&e.apply(this,arguments)||this;return t.clientId="",t.eventSource=null,t.subscriptions={},t.lastSentTopics=[],t.maxConnectTimeout=15e3,t.reconnectAttempts=0,t.maxReconnectAttempts=1/0,t.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],t.pendingConnects=[],t}return __extends(RealtimeService,e),Object.defineProperty(RealtimeService.prototype,"isConnected",{get:function(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length},enumerable:!1,configurable:!0}),RealtimeService.prototype.subscribe=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o=this;return __generator(this,(function(r){switch(r.label){case 0:if(!e)throw new Error("topic must be set.");return i=function(e){var n,i=e;try{n=JSON.parse(null==i?void 0:i.data)}catch(e){}t(n||{})},this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(i),this.isConnected?[3,2]:[4,this.connect()];case 1:return r.sent(),[3,5];case 2:return 1!==this.subscriptions[e].length?[3,4]:[4,this.submitSubscriptions()];case 3:return r.sent(),[3,5];case 4:null===(n=this.eventSource)||void 0===n||n.addEventListener(e,i),r.label=5;case 5:return[2,function(){return __awaiter(o,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this.unsubscribeByTopicAndListener(e,i)]}))}))}]}}))}))},RealtimeService.prototype.unsubscribe=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!this.hasSubscriptionListeners(e))return[2];if(e){for(n=0,i=this.subscriptions[e];n<i.length;n++)o=i[n],null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,o);delete this.subscriptions[e]}else this.subscriptions={};return this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3]);case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByPrefix=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s;return __generator(this,(function(a){switch(a.label){case 0:for(i in n=!1,this.subscriptions)if(i.startsWith(e)){for(n=!0,o=0,r=this.subscriptions[i];o<r.length;o++)s=r[o],null===(t=this.eventSource)||void 0===t||t.removeEventListener(i,s);delete this.subscriptions[i]}return n?this.hasSubscriptionListeners()?[4,this.submitSubscriptions()]:[3,2]:[2];case 1:return a.sent(),[3,3];case 2:this.disconnect(),a.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByTopicAndListener=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return[2];for(i=!1,o=this.subscriptions[e].length-1;o>=0;o--)this.subscriptions[e][o]===t&&(i=!0,delete this.subscriptions[e][o],this.subscriptions[e].splice(o,1),null===(n=this.eventSource)||void 0===n||n.removeEventListener(e,t));return i?(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3])):[2];case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.hasSubscriptionListeners=function(e){var t,n;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(var i in this.subscriptions)if(null===(n=this.subscriptions[i])||void 0===n?void 0:n.length)return!0;return!1},RealtimeService.prototype.submitSubscriptions=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(e){return this.clientId?(this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),[2,this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},params:{$cancelKey:this.getSubscriptionsCancelKey()}}).catch((function(e){if(!(null==e?void 0:e.isAbort))throw e}))]):[2]}))}))},RealtimeService.prototype.getSubscriptionsCancelKey=function(){return"realtime_"+this.clientId},RealtimeService.prototype.getNonEmptySubscriptionTopics=function(){var e=[];for(var t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e},RealtimeService.prototype.addAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.removeAllSubscriptionListeners(),this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.addEventListener(e,i)}},RealtimeService.prototype.removeAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.removeEventListener(e,i)}},RealtimeService.prototype.connect=function(){return __awaiter(this,void 0,void 0,(function(){var e=this;return __generator(this,(function(t){return this.reconnectAttempts>0?[2]:[2,new Promise((function(t,n){e.pendingConnects.push({resolve:t,reject:n}),e.pendingConnects.length>1||e.initConnect()}))]}))}))},RealtimeService.prototype.initConnect=function(){var e=this;this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((function(){e.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=function(t){e.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(function(t){var n=t;e.clientId=null==n?void 0:n.lastEventId,e.submitSubscriptions().then((function(){return __awaiter(e,void 0,void 0,(function(){var e;return __generator(this,(function(t){switch(t.label){case 0:e=3,t.label=1;case 1:return this.hasUnsentSubscriptions()&&e>0?(e--,[4,this.submitSubscriptions()]):[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))}))})).then((function(){for(var t=0,n=e.pendingConnects;t<n.length;t++){n[t].resolve()}e.pendingConnects=[],e.reconnectAttempts=0,clearTimeout(e.reconnectTimeoutId),clearTimeout(e.connectTimeoutId)})).catch((function(t){e.clientId="",e.connectErrorHandler(t)}))}))},RealtimeService.prototype.hasUnsentSubscriptions=function(){var e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(var t=0,n=e;t<n.length;t++){var i=n[t];if(!this.lastSentTopics.includes(i))return!0}return!1},RealtimeService.prototype.connectErrorHandler=function(e){var n=this;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(var i=0,o=this.pendingConnects;i<o.length;i++){o[i].reject(new t(e))}return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);var r=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((function(){n.initConnect()}),r)},RealtimeService.prototype.disconnect=function(e){var t;if(void 0===e&&(e=!1),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(var n=0,i=this.pendingConnects;n<i.length;n++){i[n].resolve()}this.pendingConnects=[]}},RealtimeService}(c),C=function(e){function HealthService(){return null!==e&&e.apply(this,arguments)||this}return __extends(HealthService,e),HealthService.prototype.check=function(e){return void 0===e&&(e={}),this.client.send("/api/health",{method:"GET",params:e})},HealthService}(c),_=function(e){function FileService(){return null!==e&&e.apply(this,arguments)||this}return __extends(FileService,e),FileService.prototype.getUrl=function(e,t,n){void 0===n&&(n={});var i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));var o=this.client.buildUrl(i.join("/"));if(Object.keys(n).length){!1===n.download&&delete n.download;var r=new URLSearchParams(n);o+=(o.includes("?")?"&":"?")+r}return o},FileService.prototype.getToken=function(e){return void 0===e&&(e={}),this.client.send("/api/files/token",{method:"POST",params:e}).then((function(e){return(null==e?void 0:e.token)||""}))},FileService}(c),R=function(e){function BackupService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BackupService,e),BackupService.prototype.getFullList=function(e){return void 0===e&&(e={}),this.client.send("/api/backups",{method:"GET",params:e})},BackupService.prototype.create=function(e,t){void 0===t&&(t={});var n={name:e};return this.client.send("/api/backups",{method:"POST",params:t,body:n}).then((function(){return!0}))},BackupService.prototype.delete=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e)),{method:"DELETE",params:t}).then((function(){return!0}))},BackupService.prototype.restore=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e),"/restore"),{method:"POST",params:t}).then((function(){return!0}))},BackupService.prototype.getDownloadUrl=function(e,t){return this.client.buildUrl("/api/backups/".concat(encodeURIComponent(t),"?token=").concat(encodeURIComponent(e)))},BackupService}(c);return function(){function Client(e,t,n){void 0===e&&(e="/"),void 0===n&&(n="en-US"),this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=n,this.authStore=t||new a,this.admins=new p(this),this.collections=new y(this),this.files=new _(this),this.logs=new S(this),this.settings=new u(this),this.realtime=new w(this),this.health=new C(this),this.backups=new R(this)}return Client.prototype.collection=function(e){return this.recordServices[e]||(this.recordServices[e]=new f(this,e)),this.recordServices[e]},Client.prototype.autoCancellation=function(e){return this.enableAutoCancellation=!!e,this},Client.prototype.cancelRequest=function(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this},Client.prototype.cancelAllRequests=function(){for(var e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this},Client.prototype.send=function(e,n){var i,o,r,s,a,c,u,l;return __awaiter(this,void 0,void 0,(function(){var d,h,p,v,f,m,b,y,g,S=this;return __generator(this,(function(w){switch(w.label){case 0:return d=Object.assign({method:"GET"},n),this.isFormData(d.body)||(d.body&&"string"!=typeof d.body&&(d.body=JSON.stringify(d.body)),void 0===(null===(i=null==d?void 0:d.headers)||void 0===i?void 0:i["Content-Type"])&&(d.headers=Object.assign({},d.headers,{"Content-Type":"application/json"}))),void 0===(null===(o=null==d?void 0:d.headers)||void 0===o?void 0:o["Accept-Language"])&&(d.headers=Object.assign({},d.headers,{"Accept-Language":this.lang})),(null===(r=this.authStore)||void 0===r?void 0:r.token)&&void 0===(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s.Authorization)&&(d.headers=Object.assign({},d.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&!1!==(null===(a=d.params)||void 0===a?void 0:a.$autoCancel)&&(h=(null===(c=d.params)||void 0===c?void 0:c.$cancelKey)||(d.method||"GET")+e,this.cancelRequest(h),p=new AbortController,this.cancelControllers[h]=p,d.signal=p.signal),null===(u=d.params)||void 0===u||delete u.$autoCancel,null===(l=d.params)||void 0===l||delete l.$cancelKey,v=this.buildUrl(e),void 0!==d.params&&((f=this.serializeQueryParams(d.params))&&(v+=(v.includes("?")?"&":"?")+f),delete d.params),this.beforeSend?(y=(b=Object).assign,g=[{}],[4,this.beforeSend(v,d)]):[3,2];case 1:void 0!==(m=y.apply(b,g.concat([w.sent()]))).url||void 0!==m.options?(v=m.url||v,d=m.options||d):Object.keys(m).length&&(d=m,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.")),w.label=2;case 2:return[2,fetch(v,d).then((function(e){return __awaiter(S,void 0,void 0,(function(){var n;return __generator(this,(function(i){switch(i.label){case 0:n={},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.json()];case 2:return n=i.sent(),[3,4];case 3:return i.sent(),[3,4];case 4:return this.afterSend?[4,this.afterSend(e,n)]:[3,6];case 5:n=i.sent(),i.label=6;case 6:if(e.status>=400)throw new t({url:e.url,status:e.status,data:n});return[2,n]}}))}))})).catch((function(e){throw new t(e)}))]}}))}))},Client.prototype.getFileUrl=function(e,t,n){return void 0===n&&(n={}),this.files.getUrl(e,t,n)},Client.prototype.buildUrl=function(e){var t,n=this.baseUrl;return"undefined"==typeof window||!window.location||n.startsWith("https://")||n.startsWith("http://")||(n=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(n+=window.location.pathname||"/",n+=n.endsWith("/")?"":"/"),n+=this.baseUrl),e&&(n+=n.endsWith("/")?"":"/",n+=e.startsWith("/")?e.substring(1):e),n},Client.prototype.isFormData=function(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)},Client.prototype.serializeQueryParams=function(e){var t=[];for(var n in e)if(null!==e[n]){var i=e[n],o=encodeURIComponent(n);if(Array.isArray(i))for(var r=0,s=i;r<s.length;r++){var a=s[r];t.push(o+"="+encodeURIComponent(a))}else i instanceof Date?t.push(o+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(o+"="+encodeURIComponent(JSON.stringify(i))):t.push(o+"="+encodeURIComponent(i))}return t.join("&")},Client}()}();
var PocketBase=function(){"use strict";function __awaiter(e,t,i,s){return new(i||(i=Promise))((function(n,o){function fulfilled(e){try{step(s.next(e))}catch(e){o(e)}}function rejected(e){try{step(s.throw(e))}catch(e){o(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class ClientResponseError extends Error{constructor(e){var t,i,s,n;super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=null===(t=this.response)||void 0===t?void 0:t.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(n=null===(s=null===(i=this.originalError)||void 0===i?void 0:i.cause)||void 0===s?void 0:s.message)||void 0===n?void 0:n.includes("ECONNREFUSED ::1"))?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return Object.assign({},this)}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,i,s){const n=Object.assign({},s||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(i);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}let t;function getTokenPayload(e){if(e)try{const i=decodeURIComponent(t(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(i)||{}}catch(e){}return{}}t="function"==typeof atob?atob:e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,s,n=0,o=0,r="";s=t.charAt(o++);~s&&(i=n%4?64*i+s:s,n++%4)?r+=String.fromCharCode(255&i>>(-2*n&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return r};const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!function isTokenExpired(e,t=0){let i=getTokenPayload(e);return!(Object.keys(i).length>0&&(!i.exp||i.exp-t>Date.now()/1e3))}(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const i={};if("string"!=typeof e)return i;const s=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n<e.length;){const t=e.indexOf("=",n);if(-1===t)break;let o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<t){n=e.lastIndexOf(";",t-1)+1;continue}const r=e.slice(n,t).trim();if(void 0===i[r]){let n=e.slice(t+1,o).trim();34===n.charCodeAt(0)&&(n=n.slice(1,-1));try{i[r]=s(n)}catch(e){i[r]=n}}n=o+1}return i}(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){var s,n;const o={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=getTokenPayload(this.token);(null==r?void 0:r.exp)?o.expires=new Date(1e3*r.exp):o.expires=new Date("1970-01-01"),e=Object.assign({},o,e);const a={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let l=cookieSerialize(t,JSON.stringify(a),e);const c="undefined"!=typeof Blob?new Blob([l]).size:l.length;if(a.model&&c>4096){a.model={id:null===(s=null==a?void 0:a.model)||void 0===s?void 0:s.id,email:null===(n=null==a?void 0:a.model)||void 0===n?void 0:n.email};const i=["collectionId","username","verified"];for(const e in this.model)i.includes(e)&&(a.model[e]=this.model[e]);l=cookieSerialize(t,JSON.stringify(a),e)}return l}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){let i=t;"string"!=typeof t&&(i=JSON.stringify(t)),window.localStorage.setItem(e,i)}else this.storageFallback[e]=t}_storageRemove(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}testEmail(e,t,i){return i=Object.assign({method:"POST",body:{email:e,template:t}},i),this.client.send("/api/settings/test/email",i).then((()=>!0))}generateAppleClientSecret(e,t,i,s,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:i,privateKey:s,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let i=500;return(t=Object.assign({},e,t)).batch&&(i=t.batch,delete t.batch),this._getFullList(i,t)}getList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send(this.baseCrudPath,i).then((e=>{var t;return e.items=(null===(t=e.items)||void 0===t?void 0:t.map((e=>this.decode(e))))||[],e}))}getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{var t;if(!(null===(t=null==e?void 0:e.items)||void 0===t?void 0:t.length))throw new ClientResponseError({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}getOne(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}update(e,t,i){return i=Object.assign({method:"PATCH",body:t},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),i).then((e=>this.decode(e)))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let i=[],request=s=>__awaiter(this,void 0,void 0,(function*(){return this.getList(s,e||500,t).then((e=>{const t=e.items;return i=i.concat(t),t.length==e.perPage?request(s+1):i}))}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,i,s){const n=void 0!==s;return n||void 0!==i?n?(console.warn(e),t.body=Object.assign({},t.body,i),t.query=Object.assign({},t.query,s),t):t=Object.assign(t,i):t}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)===e.id&&void 0===(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)&&this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s;return t&&(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)===e&&void 0===(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)&&this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(email, pass, options?).",n,i,s),this.client.send(this.baseCrudPath+"/auth-with-password",n).then(this.authResponse.bind(this))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",i).then(this.authResponse.bind(this))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCrudPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}subscribeOne(e,t){return __awaiter(this,void 0,void 0,(function*(){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),this.client.realtime.subscribe(this.collectionIdOrName,e);if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");let i=this.collectionIdOrName;return"*"!==e&&(i+="/"+e),this.client.realtime.subscribe(i,t)}))}unsubscribe(e){return __awaiter(this,void 0,void 0,(function*(){return"*"===e?this.client.realtime.unsubscribe(this.collectionIdOrName):e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}))}getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const i=Object.assign({},e,t);return super.getFullList(i)}getList(e=1,t=30,i){return super.getList(e,t,i)}getFirstListItem(e,t){return super.getFirstListItem(e,t)}getOne(e,t){return super.getOne(e,t)}create(e,t){return super.create(e,t)}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i,s;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)!==this.collectionIdOrName&&(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionName)!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s,n;return!t||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)!==e||(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)!==this.collectionIdOrName&&(null===(n=this.client.authStore.model)||void 0===n?void 0:n.collectionName)!==this.collectionIdOrName||this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})}listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})))}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}authWithOAuth2Code(e,t,i,s,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:i,redirectUrl:s,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is depreacted. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){return __awaiter(this,void 0,void 0,(function*(){if(e.length>1||"string"==typeof(null==e?void 0:e[0]))return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{});const t=(null==e?void 0:e[0])||{},i=(yield this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!i)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const s=this.client.buildUrl("/api/oauth2-redirect");return new Promise(((e,n)=>__awaiter(this,void 0,void 0,(function*(){var o;try{const r=yield this.client.realtime.subscribe("@oauth2",(o=>__awaiter(this,void 0,void 0,(function*(){const a=this.client.realtime.clientId;try{if(r(),!o.state||a!==o.state)throw new Error("State parameters don't match.");const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const l=yield this.authWithOAuth2Code(i.name,o.code,i.codeVerifier,s,t.createData,n);e(l)}catch(e){n(new ClientResponseError(e))}})))),a={state:this.client.realtime.clientId};(null===(o=t.scopes)||void 0===o?void 0:o.length)&&(a.scope=t.scopes.join(" "));const l=this._replaceQueryParams(i.authUrl+s,a);yield t.urlCallback?t.urlCallback(l):this._defaultUrlCallback(l)}catch(e){n(new ClientResponseError(e))}}))))}))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",i).then((e=>this.authResponse(e)))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}requestVerification(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is depreacted. Consider replacing it with requestVerification(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-verification",s).then((()=>!0))}confirmVerification(e,t,i){let s={method:"POST",body:{token:e}};return s=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is depreacted. Consider replacing it with confirmVerification(token, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/confirm-verification",s).then((()=>!0))}requestEmailChange(e,t,i){let s={method:"POST",body:{newEmail:e}};return s=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is depreacted. Consider replacing it with requestEmailChange(newEmail, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-email-change",s).then((()=>!0))}confirmEmailChange(e,t,i,s){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is depreacted. Consider replacing it with confirmEmailChange(token, password, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>!0))}listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}unlinkExternalAuth(e,t,i){return i=Object.assign({method:"DELETE"},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),i).then((()=>!0))}_replaceQueryParams(e,t={}){let i=e,s="";e.indexOf("?")>=0&&(i=e.substring(0,e.indexOf("?")),s=e.substring(e.indexOf("?")+1));const n={},o=s.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);s="";for(let e in n)n.hasOwnProperty(e)&&(""!=s&&(s+="&"),s+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=s?i+"?"+s:i}_defaultUrlCallback(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,i=768,s=window.innerWidth,n=window.innerHeight;t=t>s?s:t,i=i>n?n:i;let o=s/2-t/2,r=n/2-i/2;window.open(e,"oauth2-popup","width="+t+",height="+i+",top="+r+",left="+o+",resizable,menubar=no")}}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}import(e,t=!1,i){return __awaiter(this,void 0,void 0,(function*(){return i=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},i),this.client.send(this.baseCrudPath+"/import",i).then((()=>!0))}))}}class LogService extends BaseService{getRequestsList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send("/api/logs/requests",i)}getRequest(e,t){return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/requests/"+encodeURIComponent(e),t)}getRequestsStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/requests/stats",e)}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentTopics=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}subscribe(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!e)throw new Error("topic must be set.");const listener=function(e){const i=e;let s;try{s=JSON.parse(null==i?void 0:i.data)}catch(e){}t(s||{})};return this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(listener),this.isConnected?1===this.subscriptions[e].length?yield this.submitSubscriptions():null===(i=this.eventSource)||void 0===i||i.addEventListener(e,listener):yield this.connect(),()=>__awaiter(this,void 0,void 0,(function*(){return this.unsubscribeByTopicAndListener(e,listener)}))}))}unsubscribe(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this.hasSubscriptionListeners(e)){if(e){for(let i of this.subscriptions[e])null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,i);delete this.subscriptions[e]}else this.subscriptions={};this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect()}}))}unsubscribeByPrefix(e){var t;return __awaiter(this,void 0,void 0,(function*(){let i=!1;for(let s in this.subscriptions)if(s.startsWith(e)){i=!0;for(let e of this.subscriptions[s])null===(t=this.eventSource)||void 0===t||t.removeEventListener(s,e);delete this.subscriptions[s]}i&&(this.hasSubscriptionListeners()?yield this.submitSubscriptions():this.disconnect())}))}unsubscribeByTopicAndListener(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return;let s=!1;for(let n=this.subscriptions[e].length-1;n>=0;n--)this.subscriptions[e][n]===t&&(s=!0,delete this.subscriptions[e][n],this.subscriptions[e].splice(n,1),null===(i=this.eventSource)||void 0===i||i.removeEventListener(e,t));s&&(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect())}))}hasSubscriptionListeners(e){var t,i;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(let e in this.subscriptions)if(null===(i=this.subscriptions[e])||void 0===i?void 0:i.length)return!0;return!1}submitSubscriptions(){return __awaiter(this,void 0,void 0,(function*(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},query:{requestKey:this.getSubscriptionsCancelKey()}}).catch((e=>{if(!(null==e?void 0:e.isAbort))throw e}))}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getNonEmptySubscriptionTopics(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}connect(){return __awaiter(this,void 0,void 0,(function*(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=null==t?void 0:t.lastEventId,this.submitSubscriptions().then((()=>__awaiter(this,void 0,void 0,(function*(){let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,yield this.submitSubscriptions()})))).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(const t of e)if(!this.lastSentTopics.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){var t;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class HealthService extends BaseService{check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,i={}){const s=[];s.push("api"),s.push("files"),s.push(encodeURIComponent(e.collectionId||e.collectionName)),s.push(encodeURIComponent(e.id)),s.push(encodeURIComponent(t));let n=this.client.buildUrl(s.join("/"));if(Object.keys(i).length){!1===i.download&&delete i.download;const e=new URLSearchParams(i);n+=(n.includes("?")?"&":"?")+e}return n}getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>(null==e?void 0:e.token)||""))}}class BackupService extends BaseService{getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}const s=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];return class Client{constructor(e="/",t,i="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=i,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}getFileUrl(e,t,i={}){return this.files.getUrl(e,t,i)}buildUrl(e){var t;let i=this.baseUrl;return"undefined"==typeof window||!window.location||i.startsWith("https://")||i.startsWith("http://")||(i=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(i+=window.location.pathname||"/",i+=i.endsWith("/")?"":"/"),i+=this.baseUrl),e&&(i+=i.endsWith("/")?"":"/",i+=e.startsWith("/")?e.substring(1):e),i}send(e,t){return __awaiter(this,void 0,void 0,(function*(){t=this.initSendOptions(e,t);let i=this.buildUrl(e);if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(i+=(i.includes("?")?"&":"?")+e),delete t.query}if(this.beforeSend){const e=Object.assign({},yield this.beforeSend(i,t));void 0!==e.url||void 0!==e.options?(i=e.url||i,t=e.options||t):Object.keys(e).length&&(t=e,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(i,t).then((e=>__awaiter(this,void 0,void 0,(function*(){let t={};try{t=yield e.json()}catch(e){}if(this.afterSend&&(t=yield this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})))).catch((e=>{throw new ClientResponseError(e)}))}))}initSendOptions(e,t){(t=Object.assign({method:"GET"},t)).query=t.query||{},t.body=this.convertToFormDataIfNeeded(t.body);for(let e in t)s.includes(e)||(t.query[e]=t[e],delete t[e]);if(t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const i=t.requestKey||(t.method||"GET")+e;this.cancelRequest(i);const s=new AbortController;this.cancelControllers[i]=s,t.signal=s.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(let i in e)t.append(i,e[i]);return t}hasBlobField(e){for(let t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];for(let e of i)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let i in e)if(i.toLowerCase()==t)return e[i];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const i in e){if(null===e[i])continue;const s=e[i],n=encodeURIComponent(i);if(Array.isArray(s))for(const e of s)t.push(n+"="+encodeURIComponent(e));else s instanceof Date?t.push(n+"="+encodeURIComponent(s.toISOString())):null!==typeof s&&"object"==typeof s?t.push(n+"="+encodeURIComponent(JSON.stringify(s))):t.push(n+"="+encodeURIComponent(s))}return t.join("&")}}}();
//# sourceMappingURL=pocketbase.iife.js.map

@@ -12,3 +12,10 @@ interface SerializeOptions {

}
declare abstract class BaseModel {
interface ListResult<T> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<T>;
}
interface BaseModel {
[key: string]: any;

@@ -18,71 +25,61 @@ id: string;

updated: string;
constructor(data?: {
}
interface AdminModel extends BaseModel {
avatar: number;
email: string;
}
interface SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
});
/**
* Alias of this.$load(data).
*/
load(data: {
};
}
interface CollectionModel extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule?: string;
viewRule?: string;
createRule?: string;
updateRule?: string;
deleteRule?: string;
options: {
[key: string]: any;
}): void;
/**
* Loads `data` into the current model.
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Returns whether the current loaded data represent a stored db record.
*/
get $isNew(): boolean;
/**
* Alias of this.clone().
*/
clone(): BaseModel;
/**
* Creates a deep clone of the current model.
*/
$clone(): BaseModel;
/**
* Alias of this.$export().
*/
export(): {
[key: string]: any;
};
/**
* Exports all model properties as a new plain object.
*/
$export(): {
}
interface ExternalAuthModel extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
}
interface LogRequestModel extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
}
declare class Record extends BaseModel {
interface RecordModel extends BaseModel {
[key: string]: any;
collectionId: string;
collectionName: string;
expand: {
[key: string]: Record | Array<Record>;
expand?: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* Loads the provided expand items and recursively normalizes each
* item to a `Record|Array<Record>`.
*/
private _loadExpand;
}
declare class Admin extends BaseModel {
avatar: number;
email: string;
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
type OnStoreChangeFunc = (token: string, model: Record | Admin | null) => void;
type AuthModel = RecordModel | AdminModel | null;
type OnStoreChangeFunc = (token: string, model: AuthModel) => void;
/**

@@ -94,3 +91,3 @@ * Base AuthStore class that is intended to be extended by all other

protected baseToken: string;
protected baseModel: Record | Admin | null;
protected baseModel: AuthModel;
private _onChangeCallbacks;

@@ -104,3 +101,3 @@ /**

*/
get model(): Record | Admin | null;
get model(): AuthModel;
/**

@@ -111,5 +108,13 @@ * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).

/**
* Checks whether the current store state is for admin authentication.
*/
get isAdmin(): boolean;
/**
* Checks whether the current store state is for auth record authentication.
*/
get isAuthRecord(): boolean;
/**
* Saves the provided new token and model data in the auth store.
*/
save(token: string, model: Record | Admin | null): void;
save(token: string, model?: AuthModel): void;
/**

@@ -177,9 +182,34 @@ * Removes the stored token and model data form the auth store.

}
interface BaseQueryParams {
[key: string]: any;
fields?: string;
interface SendOptions extends RequestInit {
[key: string]: any; // for backward compatibility
// optional custom fetch function to use for sending the request
fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
// custom headers to send with the requests
headers?: {
[key: string]: string;
};
// the body of the request (serialized automatically for json requests)
body?: any;
// query params that will be appended to the request url
query?: {
[key: string]: any;
};
// @deprecated use `query` instead
//
// for backward-compatibility `params` values are merged with `query`,
// but this option may get removed in the final v1 release
params?: {
[key: string]: any;
};
// the request identifier that can be used to cancel pending requests
requestKey?: string | null;
// @deprecated use `requestKey:string` instead
$cancelKey?: string;
// @deprecated use `requestKey:null` instead
$autoCancel?: boolean;
$cancelKey?: string;
}
interface ListQueryParams extends BaseQueryParams {
interface CommonOptions extends SendOptions {
fields?: string;
}
interface ListOptions extends CommonOptions {
page?: number;

@@ -191,16 +221,16 @@ perPage?: number;

}
interface FullListQueryParams extends ListQueryParams {
interface FullListOptions extends ListOptions {
batch?: number;
}
interface RecordQueryParams extends BaseQueryParams {
interface RecordOptions extends CommonOptions {
expand?: string;
}
interface RecordListQueryParams extends ListQueryParams, RecordQueryParams {
interface RecordListOptions extends ListOptions, RecordOptions {
}
interface RecordFullListQueryParams extends FullListQueryParams, RecordQueryParams {
interface RecordFullListOptions extends FullListOptions, RecordOptions {
}
interface LogStatsQueryParams extends BaseQueryParams {
interface LogStatsOptions extends CommonOptions {
filter?: string;
}
interface FileQueryParams extends BaseQueryParams {
interface FileOptions extends CommonOptions {
thumb?: string;

@@ -216,3 +246,3 @@ download?: boolean;

*/
getAll(queryParams?: BaseQueryParams): Promise<{
getAll(options?: CommonOptions): Promise<{
[key: string]: any;

@@ -223,4 +253,6 @@ }>;

*/
update(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<{
update(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<{
[key: string]: any;
}>;

@@ -232,3 +264,3 @@ /**

*/
testS3(filesystem?: string, queryParams?: BaseQueryParams): Promise<boolean>;
testS3(filesystem?: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -242,65 +274,20 @@ * Sends a test email.

*/
testEmail(toEmail: string, emailTemplate: string, queryParams?: BaseQueryParams): Promise<boolean>;
testEmail(toEmail: string, emailTemplate: string, options?: CommonOptions): Promise<boolean>;
/**
* Generates a new Apple OAuth2 client secret.
*/
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<appleClientSecret>;
generateAppleClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string, duration: number, options?: CommonOptions): Promise<appleClientSecret>;
}
declare class ListResult<M = BaseModel> {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: Array<M>;
constructor(page: number, perPage: number, totalItems: number, totalPages: number, items: Array<M>);
}
// @todo since there is no longer need of SubCrudService consider merging with CrudService in v0.9+
declare abstract class BaseCrudService<M extends BaseModel> extends BaseService {
declare abstract class CrudService<M> extends BaseService {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Response data decoder.
*/
abstract decode(data: {
decode<T = M>(data: {
[key: string]: any;
}): M;
}): T;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(basePath: string, batchSize?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
/**
* Returns paginated items list.
*/
protected _getList<T = M>(basePath: string, page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
/**
* Returns single item by its id.
*/
protected _getOne<T = M>(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Returns the first found item by a list filter.
*
* Internally it calls `_getList(basePath, 1, 1, { filter, skipTotal })`
* and returns its first item.
*
* For consistency with `_getOne`, this method will throw a 404
* ClientResponseError if no item was found.
*/
protected _getFirstListItem<T = M>(basePath: string, filter: string, queryParams?: BaseQueryParams): Promise<T>;
/**
* Creates a new item.
*/
protected _create<T = M>(basePath: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Updates an existing item by its id.
*/
protected _update<T = M>(basePath: string, id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
/**
* Deletes an existing item by its id.
*/
protected _delete(basePath: string, id: string, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare abstract class CrudService<M extends BaseModel> extends BaseCrudService<M> {
/**
* Base path for the crud actions (without trailing slash, eg. '/admins').
*/
abstract get baseCrudPath(): string;
/**
* Returns a promise with all list items batch fetched at once

@@ -311,7 +298,7 @@ * (by default 500 items per request; to change it set the `batch` query param).

*/
getFullList<T = M>(queryParams?: FullListQueryParams): Promise<Array<T>>;
getFullList<T = M>(options?: FullListOptions): Promise<Array<T>>;
/**
* Legacy version of getFullList with explicitly specified batch size.
*/
getFullList<T = M>(batch?: number, queryParams?: ListQueryParams): Promise<Array<T>>;
getFullList<T = M>(batch?: number, options?: ListOptions): Promise<Array<T>>;
/**

@@ -322,3 +309,3 @@ * Returns paginated items list.

*/
getList<T = M>(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<T>>;
getList<T = M>(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<T>>;
/**

@@ -335,3 +322,3 @@ * Returns the first found item by the specified filter.

*/
getFirstListItem<T = M>(filter: string, queryParams?: BaseQueryParams): Promise<T>;
getFirstListItem<T = M>(filter: string, options?: CommonOptions): Promise<T>;
/**

@@ -342,3 +329,3 @@ * Returns single item by its id.

*/
getOne<T = M>(id: string, queryParams?: BaseQueryParams): Promise<T>;
getOne<T = M>(id: string, options?: CommonOptions): Promise<T>;
/**

@@ -349,3 +336,5 @@ * Creates a new item.

*/
create<T = M>(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
create<T = M>(bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -356,7 +345,13 @@ * Updates an existing item by its id.

*/
update<T = M>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = M>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**
* Deletes an existing item by its id.
*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
/**
* Returns a promise with all list items batch fetched at once.
*/
protected _getFullList<T = M>(batchSize?: number, options?: ListOptions): Promise<Array<T>>;
}

@@ -366,14 +361,8 @@ interface AdminAuthResponse {

token: string;
admin: Admin;
admin: AdminModel;
}
declare class AdminService extends CrudService<Admin> {
declare class AdminService extends CrudService<AdminModel> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Admin;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -389,3 +378,5 @@ // ---------------------------------------------------------------

*/
update<T = Admin>(id: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<T>;
update<T = AdminModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: CommonOptions): Promise<T>;
/**

@@ -397,3 +388,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -412,4 +403,9 @@ // Auth handlers

*/
authWithPassword(email: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authWithPassword(email: string, password: string, options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authWithPassword(email, password, options?).
*/
authWithPassword(email: string, password: string, body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Refreshes the current admin authenticated instance and

@@ -420,23 +416,26 @@ * returns a new token and admin data.

*/
authRefresh(bodyParams?: {}, queryParams?: BaseQueryParams): Promise<AdminAuthResponse>;
authRefresh(options?: CommonOptions): Promise<AdminAuthResponse>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh(body?: any, query?: any): Promise<AdminAuthResponse>;
/**
* Sends admin password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms admin password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
}
declare class ExternalAuth extends BaseModel {
recordId: string;
collectionId: string;
provider: string;
providerId: string;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @inheritdoc
* @deprecated
* Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).
*/
$load(data: {
[key: string]: any;
}): void;
confirmPasswordReset(resetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
}

@@ -512,5 +511,11 @@ type UnsubscribeFunc = () => Promise<void>;

}
interface RecordAuthResponse<T = Record> {
interface RecordAuthResponse<T = RecordModel> {
// The signed PocketBase auth record.
record: T;
// The PocketBase record auth token.
//
// If you are looking for the OAuth2 access and refresh tokens
// they are available under the `meta.accessToken` and `meta.refreshToken` props.
token: string;
// Auth meta data usually filled when OAuth2 is used.
meta?: {

@@ -533,3 +538,3 @@ [key: string]: any;

}
interface RecordSubscription<T = Record> {
interface RecordSubscription<T = RecordModel> {
action: string; // eg. create, update, delete

@@ -539,3 +544,3 @@ record: T;

type OAuth2UrlCallback = (url: string) => void | Promise<void>;
interface OAuth2AuthConfig {
interface OAuth2AuthConfig extends SendOptions {
// the name of the OAuth2 provider (eg. "google")

@@ -552,9 +557,5 @@ provider: string;

// optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)
query?: RecordQueryParams;
// optional body params to send with the PocketBase auth request
body?: {
[key: string]: any;
};
query?: RecordOptions;
}
declare class RecordService extends CrudService<Record> {
declare class RecordService extends CrudService<RecordModel> {
readonly collectionIdOrName: string;

@@ -565,8 +566,2 @@ constructor(client: Client, collectionIdOrName: string);

*/
decode<T = Record>(data: {
[key: string]: any;
}): T;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -585,7 +580,7 @@ /**

*/
subscribeOne<T = Record>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribeOne<T = RecordModel>(recordId: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**
* @deprecated This form of subscribe is deprecated. Please use `subscribe("*", callback)`.
*/
subscribe<T = Record>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -604,3 +599,3 @@ * Subscribe to realtime changes to the specified topic ("*" or record id).

*/
subscribe<T = Record>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
subscribe<T = RecordModel>(topic: string, callback: (data: RecordSubscription<T>) => void): Promise<UnsubscribeFunc>;
/**

@@ -620,23 +615,25 @@ * Unsubscribe from all subscriptions of the specified topic

*/
getFullList<T = Record>(queryParams?: RecordFullListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(options?: RecordFullListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getFullList<T = Record>(batch?: number, queryParams?: RecordListQueryParams): Promise<Array<T>>;
getFullList<T = RecordModel>(batch?: number, options?: RecordListOptions): Promise<Array<T>>;
/**
* @inheritdoc
*/
getList<T = Record>(page?: number, perPage?: number, queryParams?: RecordListQueryParams): Promise<ListResult<T>>;
getList<T = RecordModel>(page?: number, perPage?: number, options?: RecordListOptions): Promise<ListResult<T>>;
/**
* @inheritdoc
*/
getFirstListItem<T = Record>(filter: string, queryParams?: RecordListQueryParams): Promise<T>;
getFirstListItem<T = RecordModel>(filter: string, options?: RecordListOptions): Promise<T>;
/**
* @inheritdoc
*/
getOne<T = Record>(id: string, queryParams?: RecordQueryParams): Promise<T>;
getOne<T = RecordModel>(id: string, options?: RecordOptions): Promise<T>;
/**
* @inheritdoc
*/
create<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
create<T = RecordModel>(bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -648,3 +645,5 @@ * @inheritdoc

*/
update<T = Record>(id: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<T>;
update<T = RecordModel>(id: string, bodyParams?: {
[key: string]: any;
} | FormData, options?: RecordOptions): Promise<T>;
/**

@@ -656,3 +655,3 @@ * @inheritdoc

*/
delete(id: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(id: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -664,7 +663,7 @@ // Auth handlers

*/
protected authResponse<T = Record>(responseData: any): RecordAuthResponse<T>;
protected authResponse<T = RecordModel>(responseData: any): RecordAuthResponse<T>;
/**
* Returns all available collection auth methods.
*/
listAuthMethods(queryParams?: BaseQueryParams): Promise<AuthMethodsList>;
listAuthMethods(options?: CommonOptions): Promise<AuthMethodsList>;
/**

@@ -678,4 +677,9 @@ * Authenticate a single auth collection record via its username/email and password.

*/
authWithPassword<T = Record>(usernameOrEmail: string, password: string, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithPassword(usernameOrEmail, password, options?).
*/
authWithPassword<T = RecordModel>(usernameOrEmail: string, password: string, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Authenticate a single auth collection record with OAuth2 code.

@@ -691,4 +695,13 @@ *

*/
authWithOAuth2Code<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {}, bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).
*/
authWithOAuth2Code<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* @deprecated This form of authWithOAuth2 is deprecated.

@@ -699,7 +712,7 @@ *

*/
authWithOAuth2<T = Record>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
authWithOAuth2<T = RecordModel>(provider: string, code: string, codeVerifier: string, redirectUrl: string, createData?: {
[key: string]: any;
}, bodyParams?: {
[key: string]: any;
}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
}, queryParams?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**

@@ -736,3 +749,3 @@ * Authenticate a single auth collection record with OAuth2

*/
authWithOAuth2<T = Record>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
authWithOAuth2<T = RecordModel>(options: OAuth2AuthConfig): Promise<RecordAuthResponse<T>>;
/**

@@ -744,35 +757,70 @@ * Refreshes the current authenticated record instance and

*/
authRefresh<T = Record>(bodyParams?: {}, queryParams?: RecordQueryParams): Promise<RecordAuthResponse<T>>;
authRefresh<T = RecordModel>(options?: RecordOptions): Promise<RecordAuthResponse<T>>;
/**
* @deprecated
* Consider using authRefresh(options?).
*/
authRefresh<T = RecordModel>(body?: any, query?: any): Promise<RecordAuthResponse<T>>;
/**
* Sends auth record password reset request.
*/
requestPasswordReset(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestPasswordReset(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestPasswordReset(email, options?).
*/
requestPasswordReset(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record password reset request.
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).
*/
confirmPasswordReset(passwordResetToken: string, password: string, passwordConfirm: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends auth record verification email request.
*/
requestVerification(email: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestVerification(email: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestVerification(email, options?).
*/
requestVerification(email: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record email verification request.
*/
confirmVerification(verificationToken: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmVerification(verificationToken: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmVerification(verificationToken, options?).
*/
confirmVerification(verificationToken: string, body?: any, query?: any): Promise<boolean>;
/**
* Sends an email change request to the authenticated record model.
*/
requestEmailChange(newEmail: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
requestEmailChange(newEmail: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using requestEmailChange(newEmail, options?).
*/
requestEmailChange(newEmail: string, body?: any, query?: any): Promise<boolean>;
/**
* Confirms auth record's new email address.
*/
confirmEmailChange(emailChangeToken: string, password: string, bodyParams?: {}, queryParams?: BaseQueryParams): Promise<boolean>;
confirmEmailChange(emailChangeToken: string, password: string, options?: CommonOptions): Promise<boolean>;
/**
* @deprecated
* Consider using confirmEmailChange(emailChangeToken, password, options?).
*/
confirmEmailChange(emailChangeToken: string, password: string, body?: any, query?: any): Promise<boolean>;
/**
* Lists all linked external auth providers for the specified auth record.
*/
listExternalAuths(recordId: string, queryParams?: BaseQueryParams): Promise<Array<ExternalAuth>>;
listExternalAuths(recordId: string, options?: CommonOptions): Promise<Array<ExternalAuthModel>>;
/**
* Unlink a single external auth provider from the specified auth record.
*/
unlinkExternalAuth(recordId: string, provider: string, queryParams?: BaseQueryParams): Promise<boolean>;
unlinkExternalAuth(recordId: string, provider: string, options?: CommonOptions): Promise<boolean>;
// ---------------------------------------------------------------

@@ -786,70 +834,6 @@ // very rudimentary url query params replacement because at the moment

}
declare class SchemaField {
id: string;
name: string;
type: string;
system: boolean;
required: boolean;
options: {
[key: string]: any;
};
constructor(data?: {
[key: string]: any;
});
}
declare class Collection extends BaseModel {
name: string;
type: string;
schema: Array<SchemaField>;
indexes: Array<string>;
system: boolean;
listRule: null | string;
viewRule: null | string;
createRule: null | string;
updateRule: null | string;
deleteRule: null | string;
options: {
[key: string]: any;
};
declare class CollectionService extends CrudService<CollectionModel> {
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
/**
* @deprecated Please use $isBase instead.
*/
get isBase(): boolean;
/**
* Checks if the current model is "base" collection.
*/
get $isBase(): boolean;
/**
* @deprecated Please use $isAuth instead.
*/
get isAuth(): boolean;
/**
* Checks if the current model is "auth" collection.
*/
get $isAuth(): boolean;
/**
* @deprecated Please use $isView instead.
*/
get isView(): boolean;
/**
* Checks if the current model is "view" collection.
*/
get $isView(): boolean;
}
declare class CollectionService extends CrudService<Collection> {
/**
* @inheritdoc
*/
decode(data: {
[key: string]: any;
}): Collection;
/**
* @inheritdoc
*/
get baseCrudPath(): string;

@@ -863,23 +847,4 @@ /**

*/
import(collections: Array<Collection>, deleteMissing?: boolean, queryParams?: BaseQueryParams): Promise<true>;
import(collections: Array<CollectionModel>, deleteMissing?: boolean, options?: CommonOptions): Promise<true>;
}
declare class LogRequest extends BaseModel {
url: string;
method: string;
status: number;
auth: string;
remoteIp: string;
userIp: string;
referer: string;
userAgent: string;
meta: {
[key: string]: any;
};
/**
* @inheritdoc
*/
$load(data: {
[key: string]: any;
}): void;
}
interface HourlyStats {

@@ -893,11 +858,11 @@ total: number;

*/
getRequestsList(page?: number, perPage?: number, queryParams?: ListQueryParams): Promise<ListResult<LogRequest>>;
getRequestsList(page?: number, perPage?: number, options?: ListOptions): Promise<ListResult<LogRequestModel>>;
/**
* Returns a single logged request by its id.
*/
getRequest(id: string, queryParams?: BaseQueryParams): Promise<LogRequest>;
getRequest(id: string, options?: CommonOptions): Promise<LogRequestModel>;
/**
* Returns request logs statistics.
*/
getRequestsStats(queryParams?: LogStatsQueryParams): Promise<Array<HourlyStats>>;
getRequestsStats(options?: LogStatsOptions): Promise<Array<HourlyStats>>;
}

@@ -915,3 +880,3 @@ interface HealthCheckResponse {

*/
check(queryParams?: BaseQueryParams): Promise<HealthCheckResponse>;
check(options?: CommonOptions): Promise<HealthCheckResponse>;
}

@@ -922,7 +887,9 @@ declare class FileService extends BaseService {

*/
getUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
getUrl(record: Pick<{
[key: string]: any;
}, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileOptions): string;
/**
* Requests a new private file access token for the current auth model (admin or record).
*/
getToken(queryParams?: BaseQueryParams): Promise<string>;
getToken(options?: CommonOptions): Promise<string>;
}

@@ -938,15 +905,15 @@ interface BackupFileInfo {

*/
getFullList(queryParams?: BaseQueryParams): Promise<Array<BackupFileInfo>>;
getFullList(options?: CommonOptions): Promise<Array<BackupFileInfo>>;
/**
* Initializes a new backup.
*/
create(basename: string, queryParams?: BaseQueryParams): Promise<boolean>;
create(basename: string, options?: CommonOptions): Promise<boolean>;
/**
* Deletes a single backup file.
*/
delete(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
delete(key: string, options?: CommonOptions): Promise<boolean>;
/**
* Initializes an app data restore from an existing backup.
*/
restore(key: string, queryParams?: BaseQueryParams): Promise<boolean>;
restore(key: string, options?: CommonOptions): Promise<boolean>;
/**

@@ -960,9 +927,2 @@ * Builds a download url for a single existing backup using an

}
interface SendOptions extends RequestInit {
headers?: {
[key: string]: string;
};
body?: any;
params?: BaseQueryParams;
}
interface BeforeSendResult {

@@ -1096,3 +1056,3 @@ [key: string]: any;

*/
cancelRequest(cancelKey: string): Client;
cancelRequest(requestKey: string): Client;
/**

@@ -1106,2 +1066,18 @@ * Cancels all pending requests.

/**
* Legacy alias of `pb.files.getUrl()`.
*/
/**
* Legacy alias of `pb.files.getUrl()`.
*/
getFileUrl(record: Pick<{
[key: string]: any;
}, 'id' | 'collectionId' | 'collectionName'>, filename: string, queryParams?: FileOptions): string;
/**
* Builds a full client url by safely concatenating the provided path.
*/
/**
* Builds a full client url by safely concatenating the provided path.
*/
buildUrl(path: string): string;
/**
* Sends an api http request.

@@ -1112,18 +1088,44 @@ */

*/
send<T = any>(path: string, reqOptions: SendOptions): Promise<T>;
send<T = any>(path: string, options: SendOptions): Promise<T>;
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
/**
* Legacy alias of `pb.files.getUrl()`.
* Shallow copy the provided object and takes care to initialize
* any options required to preserve the backward compatability.
*
* @param {SendOptions} options
* @return {SendOptions}
*/
getFileUrl(record: Pick<Record, "id" | "collectionId" | "collectionName">, filename: string, queryParams?: FileQueryParams): string;
private initSendOptions;
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
/**
* Builds a full client url by safely concatenating the provided path.
* Converts analyzes the provided body and converts it to FormData
* in case a plain object with File/Blob values is used.
*/
buildUrl(path: string): string;
private convertToFormDataIfNeeded;
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
/**
* Checks if the submitted body object has at least one Blob/File field.
*/
private hasBlobField;
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
/**
* Extracts the header with the provided name in case-insensitive manner.
* Returns `null` if no header matching the name is found.
*/
private getHeader;
/**
* Loosely checks if the specified body is a FormData instance.

@@ -1143,2 +1145,2 @@ */

}
export { SendOptions, BeforeSendResult, Client as default };
export { BeforeSendResult, Client as default };

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PocketBase=t()}(this,(function(){"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function __(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}var __assign=function(){return __assign=Object.assign||function __assign(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}function __generator(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function verb(a){return function(c){return function step(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}var e,t=function(e){function ClientResponseError(t){var n,i,o,r,s=this;return(s=e.call(this,"ClientResponseError")||this).url="",s.status=0,s.response={},s.isAbort=!1,s.originalError=null,Object.setPrototypeOf(s,ClientResponseError.prototype),null!==t&&"object"==typeof t&&(s.url="string"==typeof t.url?t.url:"",s.status="number"==typeof t.status?t.status:0,s.isAbort=!!t.isAbort,s.originalError=t.originalError,null!==t.response&&"object"==typeof t.response?s.response=t.response:null!==t.data&&"object"==typeof t.data?s.response=t.data:s.response={}),s.originalError||t instanceof ClientResponseError||(s.originalError=t),"undefined"!=typeof DOMException&&t instanceof DOMException&&(s.isAbort=!0),s.name="ClientResponseError "+s.status,s.message=null===(n=s.response)||void 0===n?void 0:n.message,s.message||(s.isAbort?s.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(r=null===(o=null===(i=s.originalError)||void 0===i?void 0:i.cause)||void 0===o?void 0:o.message)||void 0===r?void 0:r.includes("ECONNREFUSED ::1"))?s.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":s.message="Something went wrong while processing your request."),s}return __extends(ClientResponseError,e),Object.defineProperty(ClientResponseError.prototype,"data",{get:function(){return this.response},enumerable:!1,configurable:!0}),ClientResponseError.prototype.toJSON=function(){return __assign({},this)},ClientResponseError}(Error),n=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(e,t,i){var o=Object.assign({},i||{}),r=o.encode||defaultEncode;if(!n.test(e))throw new TypeError("argument name is invalid");var s=r(t);if(s&&!n.test(s))throw new TypeError("argument val is invalid");var a=e+"="+s;if(null!=o.maxAge){var c=o.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(o.domain){if(!n.test(o.domain))throw new TypeError("option domain is invalid");a+="; Domain="+o.domain}if(o.path){if(!n.test(o.path))throw new TypeError("option path is invalid");a+="; Path="+o.path}if(o.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(o.expires)||isNaN(o.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.priority)switch("string"==typeof o.priority?o.priority.toLowerCase():o.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}function getTokenPayload(t){if(t)try{var n=decodeURIComponent(e(t.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)||{}}catch(e){}return{}}e="function"==typeof atob?atob:function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,o=0,r=0,s="";i=t.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};var i=function(){function BaseModel(e){void 0===e&&(e={}),this.$load(e||{})}return BaseModel.prototype.load=function(e){return this.$load(e)},BaseModel.prototype.$load=function(e){for(var t=0,n=Object.entries(e);t<n.length;t++){var i=n[t],o=i[0],r=i[1];this[o]=r}this.id=void 0!==e.id?e.id:"",this.created=void 0!==e.created?e.created:"",this.updated=void 0!==e.updated?e.updated:""},Object.defineProperty(BaseModel.prototype,"$isNew",{get:function(){return!this.id},enumerable:!1,configurable:!0}),BaseModel.prototype.clone=function(){return this.$clone()},BaseModel.prototype.$clone=function(){var e="function"==typeof structuredClone?structuredClone(this):JSON.parse(JSON.stringify(this));return new this.constructor(e)},BaseModel.prototype.export=function(){return this.$export()},BaseModel.prototype.$export=function(){return"function"==typeof structuredClone?structuredClone(this):Object.assign({},this)},BaseModel}(),o=function(e){function Record(){return null!==e&&e.apply(this,arguments)||this}return __extends(Record,e),Record.prototype.$load=function(t){e.prototype.$load.call(this,t),this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.collectionName="string"==typeof t.collectionName?t.collectionName:"",this._loadExpand(t.expand)},Record.prototype._loadExpand=function(e){for(var t in e=e||{},this.expand={},e)Array.isArray(e[t])?this.expand[t]=e[t].map((function(e){return new Record(e||{})})):this.expand[t]=new Record(e[t]||{})},Record}(i),r=function(e){function Admin(){return null!==e&&e.apply(this,arguments)||this}return __extends(Admin,e),Admin.prototype.$load=function(t){e.prototype.$load.call(this,t),this.avatar="number"==typeof t.avatar?t.avatar:0,this.email="string"==typeof t.email?t.email:""},Admin}(i),s="pb_auth",a=function(e){function LocalAuthStore(t){void 0===t&&(t="pocketbase_auth");var n=e.call(this)||this;return n.storageFallback={},n.storageKey=t,n}return __extends(LocalAuthStore,e),Object.defineProperty(LocalAuthStore.prototype,"token",{get:function(){return(this._storageGet(this.storageKey)||{}).token||""},enumerable:!1,configurable:!0}),Object.defineProperty(LocalAuthStore.prototype,"model",{get:function(){var e,t=this._storageGet(this.storageKey)||{};return null===t||"object"!=typeof t||null===t.model||"object"!=typeof t.model?null:void 0===(null===(e=t.model)||void 0===e?void 0:e.collectionId)?new r(t.model):new o(t.model)},enumerable:!1,configurable:!0}),LocalAuthStore.prototype.save=function(t,n){this._storageSet(this.storageKey,{token:t,model:n}),e.prototype.save.call(this,t,n)},LocalAuthStore.prototype.clear=function(){this._storageRemove(this.storageKey),e.prototype.clear.call(this)},LocalAuthStore.prototype._storageGet=function(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]},LocalAuthStore.prototype._storageSet=function(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){var n=t;"string"!=typeof t&&(n=JSON.stringify(t)),window.localStorage.setItem(e,n)}else this.storageFallback[e]=t},LocalAuthStore.prototype._storageRemove=function(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]},LocalAuthStore}(function(){function BaseAuthStore(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}return Object.defineProperty(BaseAuthStore.prototype,"token",{get:function(){return this.baseToken},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"model",{get:function(){return this.baseModel},enumerable:!1,configurable:!0}),Object.defineProperty(BaseAuthStore.prototype,"isValid",{get:function(){return!function isTokenExpired(e,t){void 0===t&&(t=0);var n=getTokenPayload(e);return!(Object.keys(n).length>0&&(!n.exp||n.exp-t>Date.now()/1e3))}(this.token)},enumerable:!1,configurable:!0}),BaseAuthStore.prototype.save=function(e,t){this.baseToken=e||"",this.baseModel=null!==t&&"object"==typeof t?void 0!==t.collectionId?new o(t):new r(t):null,this.triggerChange()},BaseAuthStore.prototype.clear=function(){this.baseToken="",this.baseModel=null,this.triggerChange()},BaseAuthStore.prototype.loadFromCookie=function(e,t){void 0===t&&(t=s);var n=function cookieParse(e,t){var n={};if("string"!=typeof e)return n;for(var i=Object.assign({},t||{}).decode||defaultDecode,o=0;o<e.length;){var r=e.indexOf("=",o);if(-1===r)break;var s=e.indexOf(";",o);if(-1===s)s=e.length;else if(s<r){o=e.lastIndexOf(";",r-1)+1;continue}var a=e.slice(o,r).trim();if(void 0===n[a]){var c=e.slice(r+1,s).trim();34===c.charCodeAt(0)&&(c=c.slice(1,-1));try{n[a]=i(c)}catch(e){n[a]=c}}o=s+1}return n}(e||"")[t]||"",i={};try{(null===typeof(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))&&(i={})}catch(e){}this.save(i.token||"",i.model||null)},BaseAuthStore.prototype.exportToCookie=function(e,t){var n,i,r;void 0===t&&(t=s);var a={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},c=getTokenPayload(this.token);(null==c?void 0:c.exp)?a.expires=new Date(1e3*c.exp):a.expires=new Date("1970-01-01"),e=Object.assign({},a,e);var u={token:this.token,model:(null===(n=this.model)||void 0===n?void 0:n.export())||null},l=cookieSerialize(t,JSON.stringify(u),e),d="undefined"!=typeof Blob?new Blob([l]).size:l.length;return u.model&&d>4096&&(u.model={id:null===(i=null==u?void 0:u.model)||void 0===i?void 0:i.id,email:null===(r=null==u?void 0:u.model)||void 0===r?void 0:r.email},this.model instanceof o&&(u.model.username=this.model.username,u.model.verified=this.model.verified,u.model.collectionId=this.model.collectionId),l=cookieSerialize(t,JSON.stringify(u),e)),l},BaseAuthStore.prototype.onChange=function(e,t){var n=this;return void 0===t&&(t=!1),this._onChangeCallbacks.push(e),t&&e(this.token,this.model),function(){for(var t=n._onChangeCallbacks.length-1;t>=0;t--)if(n._onChangeCallbacks[t]==e)return delete n._onChangeCallbacks[t],void n._onChangeCallbacks.splice(t,1)}},BaseAuthStore.prototype.triggerChange=function(){for(var e=0,t=this._onChangeCallbacks;e<t.length;e++){var n=t[e];n&&n(this.token,this.model)}},BaseAuthStore}()),c=function c(e){this.client=e},u=function(e){function SettingsService(){return null!==e&&e.apply(this,arguments)||this}return __extends(SettingsService,e),SettingsService.prototype.getAll=function(e){return void 0===e&&(e={}),this.client.send("/api/settings",{method:"GET",params:e}).then((function(e){return e||{}}))},SettingsService.prototype.update=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send("/api/settings",{method:"PATCH",params:t,body:e}).then((function(e){return e||{}}))},SettingsService.prototype.testS3=function(e,t){void 0===e&&(e="storage"),void 0===t&&(t={});var n={filesystem:e};return this.client.send("/api/settings/test/s3",{method:"POST",params:t,body:n}).then((function(){return!0}))},SettingsService.prototype.testEmail=function(e,t,n){void 0===n&&(n={});var i={email:e,template:t};return this.client.send("/api/settings/test/email",{method:"POST",params:n,body:i}).then((function(){return!0}))},SettingsService.prototype.generateAppleClientSecret=function(e,t,n,i,o,r,s){return void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({clientId:e,teamId:t,keyId:n,privateKey:i,duration:o},r),this.client.send("/api/settings/apple/generate-client-secret",{method:"POST",params:s,body:r})},SettingsService}(c),l=function l(e,t,n,i,o){this.page=e>0?e:1,this.perPage=t>=0?t:0,this.totalItems=n>=0?n:0,this.totalPages=i>=0?i:0,this.items=o||[]},d=function(e){function BaseCrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BaseCrudService,e),BaseCrudService.prototype._getFullList=function(e,t,n){var i=this;void 0===t&&(t=500),void 0===n&&(n={}),n=Object.assign({skipTotal:1},n);var o=[],request=function(r){return __awaiter(i,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this._getList(e,r,t||500,n).then((function(e){var t=e.items;return o=o.concat(t),t.length==e.perPage?request(r+1):o}))]}))}))};return request(1)},BaseCrudService.prototype._getList=function(e,t,n,i){var o=this;return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),i=Object.assign({page:t,perPage:n},i),this.client.send(e,{method:"GET",params:i}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=e.items||[];for(var n=0,i=e.items;n<i.length;n++){var r=i[n];t.push(o.decode(r))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},BaseCrudService.prototype._getOne=function(e,t,n){var i=this;return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"GET",params:n}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._getFirstListItem=function(e,n,i){return void 0===i&&(i={}),i=Object.assign({filter:n,skipTotal:1,$cancelKey:"one_by_filter_"+e+"_"+n},i),this._getList(e,1,1,i).then((function(e){var n;if(!(null===(n=null==e?void 0:e.items)||void 0===n?void 0:n.length))throw new t({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))},BaseCrudService.prototype._create=function(e,t,n){var i=this;return void 0===t&&(t={}),void 0===n&&(n={}),this.client.send(e,{method:"POST",params:n,body:t}).then((function(e){return i.decode(e)}))},BaseCrudService.prototype._update=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"PATCH",params:i,body:n}).then((function(e){return o.decode(e)}))},BaseCrudService.prototype._delete=function(e,t,n){return void 0===n&&(n={}),this.client.send(e+"/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},BaseCrudService}(c),h=function(e){function CrudService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CrudService,e),CrudService.prototype.getFullList=function(e,t){if("number"==typeof e)return this._getFullList(this.baseCrudPath,e,t);var n=Object.assign({},e,t),i=500;return n.batch&&(i=n.batch,delete n.batch),this._getFullList(this.baseCrudPath,i,n)},CrudService.prototype.getList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),this._getList(this.baseCrudPath,e,t,n)},CrudService.prototype.getFirstListItem=function(e,t){return void 0===t&&(t={}),this._getFirstListItem(this.baseCrudPath,e,t)},CrudService.prototype.getOne=function(e,t){return void 0===t&&(t={}),this._getOne(this.baseCrudPath,e,t)},CrudService.prototype.create=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this._create(this.baseCrudPath,e,t)},CrudService.prototype.update=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),this._update(this.baseCrudPath,e,t,n)},CrudService.prototype.delete=function(e,t){return void 0===t&&(t={}),this._delete(this.baseCrudPath,e,t)},CrudService}(d),p=function(e){function AdminService(){return null!==e&&e.apply(this,arguments)||this}return __extends(AdminService,e),AdminService.prototype.decode=function(e){return new r(e)},Object.defineProperty(AdminService.prototype,"baseCrudPath",{get:function(){return"/api/admins"},enumerable:!1,configurable:!0}),AdminService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n;return o.client.authStore.model&&void 0===(null===(t=o.client.authStore.model)||void 0===t?void 0:t.collectionId)&&(null===(n=o.client.authStore.model)||void 0===n?void 0:n.id)===(null==e?void 0:e.id)&&o.client.authStore.save(o.client.authStore.token,e),e}))},AdminService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o;return e&&i.client.authStore.model&&void 0===(null===(n=i.client.authStore.model)||void 0===n?void 0:n.collectionId)&&(null===(o=i.client.authStore.model)||void 0===o?void 0:o.id)===t&&i.client.authStore.clear(),e}))},AdminService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})},AdminService.prototype.authWithPassword=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCrudPath+"/auth-with-password",{method:"POST",params:i,body:n}).then(this.authResponse.bind(this))},AdminService.prototype.authRefresh=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/auth-refresh",{method:"POST",params:t,body:e}).then(this.authResponse.bind(this))},AdminService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCrudPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},AdminService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCrudPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},AdminService}(h),v=function(e){function ExternalAuth(){return null!==e&&e.apply(this,arguments)||this}return __extends(ExternalAuth,e),ExternalAuth.prototype.$load=function(t){e.prototype.$load.call(this,t),this.recordId="string"==typeof t.recordId?t.recordId:"",this.collectionId="string"==typeof t.collectionId?t.collectionId:"",this.provider="string"==typeof t.provider?t.provider:"",this.providerId="string"==typeof t.providerId?t.providerId:""},ExternalAuth}(i),f=function(e){function RecordService(t,n){var i=e.call(this,t)||this;return i.collectionIdOrName=n,i}return __extends(RecordService,e),RecordService.prototype.decode=function(e){return new o(e)},Object.defineProperty(RecordService.prototype,"baseCrudPath",{get:function(){return this.baseCollectionPath+"/records"},enumerable:!1,configurable:!0}),Object.defineProperty(RecordService.prototype,"baseCollectionPath",{get:function(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)},enumerable:!1,configurable:!0}),RecordService.prototype.subscribeOne=function(e,t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)]}))}))},RecordService.prototype.subscribe=function(e,t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(i){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),[2,this.client.realtime.subscribe(this.collectionIdOrName,e)];if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");return n=this.collectionIdOrName,"*"!==e&&(n+="/"+e),[2,this.client.realtime.subscribe(n,t)]}))}))},RecordService.prototype.unsubscribe=function(e){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return"*"===e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName)]:e?[2,this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e)]:[2,this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)]}))}))},RecordService.prototype.getFullList=function(t,n){if("number"==typeof t)return e.prototype.getFullList.call(this,t,n);var i=Object.assign({},t,n);return e.prototype.getFullList.call(this,i)},RecordService.prototype.getList=function(t,n,i){return void 0===t&&(t=1),void 0===n&&(n=30),void 0===i&&(i={}),e.prototype.getList.call(this,t,n,i)},RecordService.prototype.getFirstListItem=function(t,n){return void 0===n&&(n={}),e.prototype.getFirstListItem.call(this,t,n)},RecordService.prototype.getOne=function(t,n){return void 0===n&&(n={}),e.prototype.getOne.call(this,t,n)},RecordService.prototype.create=function(t,n){return void 0===t&&(t={}),void 0===n&&(n={}),e.prototype.create.call(this,t,n)},RecordService.prototype.update=function(t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),e.prototype.update.call(this,t,n,i).then((function(e){var t,n,i;return(null===(t=o.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(n=o.client.authStore.model)||void 0===n?void 0:n.collectionId)!==o.collectionIdOrName&&(null===(i=o.client.authStore.model)||void 0===i?void 0:i.collectionName)!==o.collectionIdOrName||o.client.authStore.save(o.client.authStore.token,e),e}))},RecordService.prototype.delete=function(t,n){var i=this;return void 0===n&&(n={}),e.prototype.delete.call(this,t,n).then((function(e){var n,o,r;return!e||(null===(n=i.client.authStore.model)||void 0===n?void 0:n.id)!==t||(null===(o=i.client.authStore.model)||void 0===o?void 0:o.collectionId)!==i.collectionIdOrName&&(null===(r=i.client.authStore.model)||void 0===r?void 0:r.collectionName)!==i.collectionIdOrName||i.client.authStore.clear(),e}))},RecordService.prototype.authResponse=function(e){var t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})},RecordService.prototype.listAuthMethods=function(e){return void 0===e&&(e={}),this.client.send(this.baseCollectionPath+"/auth-methods",{method:"GET",params:e}).then((function(e){return Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})}))},RecordService.prototype.authWithPassword=function(e,t,n,i){var o=this;return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({identity:e,password:t},n),this.client.send(this.baseCollectionPath+"/auth-with-password",{method:"POST",params:i,body:n}).then((function(e){return o.authResponse(e)}))},RecordService.prototype.authWithOAuth2Code=function(e,t,n,i,o,r,s){var a=this;return void 0===o&&(o={}),void 0===r&&(r={}),void 0===s&&(s={}),r=Object.assign({provider:e,code:t,codeVerifier:n,redirectUrl:i,createData:o},r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",{method:"POST",params:s,body:r}).then((function(e){return a.authResponse(e)}))},RecordService.prototype.authWithOAuth2=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s=this;return __generator(this,(function(a){switch(a.label){case 0:return e.length>1||"string"==typeof(null==e?void 0:e[0])?(console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),[2,this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{})]):(n=(null==e?void 0:e[0])||{},[4,this.listAuthMethods()]);case 1:if(i=a.sent(),!(o=i.authProviders.find((function(e){return e.name===n.provider}))))throw new t(new Error('Missing or invalid provider "'.concat(n.provider,'".')));return r=this.client.buildUrl("/api/oauth2-redirect"),[2,new Promise((function(e,i){return __awaiter(s,void 0,void 0,(function(){var s,a,c,u,l,d=this;return __generator(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this.client.realtime.subscribe("@oauth2",(function(a){return __awaiter(d,void 0,void 0,(function(){var c,u,l;return __generator(this,(function(d){switch(d.label){case 0:c=this.client.realtime.clientId,d.label=1;case 1:if(d.trys.push([1,3,,4]),s(),!a.state||c!==a.state)throw new Error("State parameters don't match.");return[4,this.authWithOAuth2Code(o.name,a.code,o.codeVerifier,r,n.createData,n.body,n.query)];case 2:return u=d.sent(),e(u),[3,4];case 3:return l=d.sent(),i(new t(l)),[3,4];case 4:return[2]}}))}))}))];case 1:return s=h.sent(),a={state:this.client.realtime.clientId},(null===(l=n.scopes)||void 0===l?void 0:l.length)&&(a.scope=n.scopes.join(" ")),c=this._replaceQueryParams(o.authUrl+r,a),[4,n.urlCallback?n.urlCallback(c):this._defaultUrlCallback(c)];case 2:return h.sent(),[3,4];case 3:return u=h.sent(),i(new t(u)),[3,4];case 4:return[2]}}))}))}))]}}))}))},RecordService.prototype.authRefresh=function(e,t){var n=this;return void 0===e&&(e={}),void 0===t&&(t={}),this.client.send(this.baseCollectionPath+"/auth-refresh",{method:"POST",params:t,body:e}).then((function(e){return n.authResponse(e)}))},RecordService.prototype.requestPasswordReset=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-password-reset",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmPasswordReset=function(e,t,n,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),i=Object.assign({token:e,password:t,passwordConfirm:n},i),this.client.send(this.baseCollectionPath+"/confirm-password-reset",{method:"POST",params:o,body:i}).then((function(){return!0}))},RecordService.prototype.requestVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({email:e},t),this.client.send(this.baseCollectionPath+"/request-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmVerification=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({token:e},t),this.client.send(this.baseCollectionPath+"/confirm-verification",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.requestEmailChange=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),t=Object.assign({newEmail:e},t),this.client.send(this.baseCollectionPath+"/request-email-change",{method:"POST",params:n,body:t}).then((function(){return!0}))},RecordService.prototype.confirmEmailChange=function(e,t,n,i){return void 0===n&&(n={}),void 0===i&&(i={}),n=Object.assign({token:e,password:t},n),this.client.send(this.baseCollectionPath+"/confirm-email-change",{method:"POST",params:i,body:n}).then((function(){return!0}))},RecordService.prototype.listExternalAuths=function(e,t){return void 0===t&&(t={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",{method:"GET",params:t}).then((function(e){var t=[];if(Array.isArray(e))for(var n=0,i=e;n<i.length;n++){var o=i[n];t.push(new v(o))}return t}))},RecordService.prototype.unlinkExternalAuth=function(e,t,n){return void 0===n&&(n={}),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),{method:"DELETE",params:n}).then((function(){return!0}))},RecordService.prototype._replaceQueryParams=function(e,t){void 0===t&&(t={});var n=e,i="";e.indexOf("?")>=0&&(n=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));for(var o={},r=0,s=i.split("&");r<s.length;r++){var a=s[r];if(""!=a){var c=a.split("=");o[decodeURIComponent(c[0].replace(/\+/g," "))]=decodeURIComponent((c[1]||"").replace(/\+/g," "))}}for(var u in t)t.hasOwnProperty(u)&&(null==t[u]?delete o[u]:o[u]=t[u]);for(var u in i="",o)o.hasOwnProperty(u)&&(""!=i&&(i+="&"),i+=encodeURIComponent(u.replace(/%20/g,"+"))+"="+encodeURIComponent(o[u].replace(/%20/g,"+")));return""!=i?n+"?"+i:n},RecordService.prototype._defaultUrlCallback=function(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new t(new Error("Not in a browser context - please pass a custom urlCallback function."));var n=1024,i=768,o=window.innerWidth,r=window.innerHeight,s=o/2-(n=n>o?o:n)/2,a=r/2-(i=i>r?r:i)/2;window.open(e,"oauth2-popup","width="+n+",height="+i+",top="+a+",left="+s+",resizable,menubar=no")},RecordService}(h),m=function m(e){void 0===e&&(e={}),this.id=void 0!==e.id?e.id:"",this.name=void 0!==e.name?e.name:"",this.type=void 0!==e.type?e.type:"text",this.system=!!e.system,this.required=!!e.required,this.options="object"==typeof e.options&&null!==e.options?e.options:{}},b=function(e){function Collection(){return null!==e&&e.apply(this,arguments)||this}return __extends(Collection,e),Collection.prototype.$load=function(t){e.prototype.$load.call(this,t),this.system=!!t.system,this.name="string"==typeof t.name?t.name:"",this.type="string"==typeof t.type?t.type:"base",this.options=void 0!==t.options&&null!==t.options?t.options:{},this.indexes=Array.isArray(t.indexes)?t.indexes:[],this.listRule="string"==typeof t.listRule?t.listRule:null,this.viewRule="string"==typeof t.viewRule?t.viewRule:null,this.createRule="string"==typeof t.createRule?t.createRule:null,this.updateRule="string"==typeof t.updateRule?t.updateRule:null,this.deleteRule="string"==typeof t.deleteRule?t.deleteRule:null,t.schema=Array.isArray(t.schema)?t.schema:[],this.schema=[];for(var n=0,i=t.schema;n<i.length;n++){var o=i[n];this.schema.push(new m(o))}},Object.defineProperty(Collection.prototype,"isBase",{get:function(){return this.$isBase},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isBase",{get:function(){return"base"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isAuth",{get:function(){return this.$isAuth},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isAuth",{get:function(){return"auth"===this.type},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"isView",{get:function(){return this.$isView},enumerable:!1,configurable:!0}),Object.defineProperty(Collection.prototype,"$isView",{get:function(){return"view"===this.type},enumerable:!1,configurable:!0}),Collection}(i),y=function(e){function CollectionService(){return null!==e&&e.apply(this,arguments)||this}return __extends(CollectionService,e),CollectionService.prototype.decode=function(e){return new b(e)},Object.defineProperty(CollectionService.prototype,"baseCrudPath",{get:function(){return"/api/collections"},enumerable:!1,configurable:!0}),CollectionService.prototype.import=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(i){return[2,this.client.send(this.baseCrudPath+"/import",{method:"PUT",params:n,body:{collections:e,deleteMissing:t}}).then((function(){return!0}))]}))}))},CollectionService}(h),g=function(e){function LogRequest(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogRequest,e),LogRequest.prototype.$load=function(t){e.prototype.$load.call(this,t),t.remoteIp=t.remoteIp||t.ip,this.url="string"==typeof t.url?t.url:"",this.method="string"==typeof t.method?t.method:"GET",this.status="number"==typeof t.status?t.status:200,this.auth="string"==typeof t.auth?t.auth:"guest",this.remoteIp="string"==typeof t.remoteIp?t.remoteIp:"",this.userIp="string"==typeof t.userIp?t.userIp:"",this.referer="string"==typeof t.referer?t.referer:"",this.userAgent="string"==typeof t.userAgent?t.userAgent:"",this.meta="object"==typeof t.meta&&null!==t.meta?t.meta:{}},LogRequest}(i),S=function(e){function LogService(){return null!==e&&e.apply(this,arguments)||this}return __extends(LogService,e),LogService.prototype.getRequestsList=function(e,t,n){return void 0===e&&(e=1),void 0===t&&(t=30),void 0===n&&(n={}),n=Object.assign({page:e,perPage:t},n),this.client.send("/api/logs/requests",{method:"GET",params:n}).then((function(e){var t=[];if(null==e?void 0:e.items){e.items=(null==e?void 0:e.items)||[];for(var n=0,i=e.items;n<i.length;n++){var o=i[n];t.push(new g(o))}}return new l((null==e?void 0:e.page)||1,(null==e?void 0:e.perPage)||0,(null==e?void 0:e.totalItems)||0,(null==e?void 0:e.totalPages)||0,t)}))},LogService.prototype.getRequest=function(e,t){return void 0===t&&(t={}),this.client.send("/api/logs/requests/"+encodeURIComponent(e),{method:"GET",params:t}).then((function(e){return new g(e)}))},LogService.prototype.getRequestsStats=function(e){return void 0===e&&(e={}),this.client.send("/api/logs/requests/stats",{method:"GET",params:e}).then((function(e){return e}))},LogService}(c),w=function(e){function RealtimeService(){var t=null!==e&&e.apply(this,arguments)||this;return t.clientId="",t.eventSource=null,t.subscriptions={},t.lastSentTopics=[],t.maxConnectTimeout=15e3,t.reconnectAttempts=0,t.maxReconnectAttempts=1/0,t.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],t.pendingConnects=[],t}return __extends(RealtimeService,e),Object.defineProperty(RealtimeService.prototype,"isConnected",{get:function(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length},enumerable:!1,configurable:!0}),RealtimeService.prototype.subscribe=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o=this;return __generator(this,(function(r){switch(r.label){case 0:if(!e)throw new Error("topic must be set.");return i=function(e){var n,i=e;try{n=JSON.parse(null==i?void 0:i.data)}catch(e){}t(n||{})},this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(i),this.isConnected?[3,2]:[4,this.connect()];case 1:return r.sent(),[3,5];case 2:return 1!==this.subscriptions[e].length?[3,4]:[4,this.submitSubscriptions()];case 3:return r.sent(),[3,5];case 4:null===(n=this.eventSource)||void 0===n||n.addEventListener(e,i),r.label=5;case 5:return[2,function(){return __awaiter(o,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this.unsubscribeByTopicAndListener(e,i)]}))}))}]}}))}))},RealtimeService.prototype.unsubscribe=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!this.hasSubscriptionListeners(e))return[2];if(e){for(n=0,i=this.subscriptions[e];n<i.length;n++)o=i[n],null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,o);delete this.subscriptions[e]}else this.subscriptions={};return this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3]);case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByPrefix=function(e){var t;return __awaiter(this,void 0,void 0,(function(){var n,i,o,r,s;return __generator(this,(function(a){switch(a.label){case 0:for(i in n=!1,this.subscriptions)if(i.startsWith(e)){for(n=!0,o=0,r=this.subscriptions[i];o<r.length;o++)s=r[o],null===(t=this.eventSource)||void 0===t||t.removeEventListener(i,s);delete this.subscriptions[i]}return n?this.hasSubscriptionListeners()?[4,this.submitSubscriptions()]:[3,2]:[2];case 1:return a.sent(),[3,3];case 2:this.disconnect(),a.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.unsubscribeByTopicAndListener=function(e,t){var n;return __awaiter(this,void 0,void 0,(function(){var i,o;return __generator(this,(function(r){switch(r.label){case 0:if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return[2];for(i=!1,o=this.subscriptions[e].length-1;o>=0;o--)this.subscriptions[e][o]===t&&(i=!0,delete this.subscriptions[e][o],this.subscriptions[e].splice(o,1),null===(n=this.eventSource)||void 0===n||n.removeEventListener(e,t));return i?(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?[3,1]:(this.disconnect(),[3,3])):[2];case 1:return this.hasSubscriptionListeners(e)?[3,3]:[4,this.submitSubscriptions()];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},RealtimeService.prototype.hasSubscriptionListeners=function(e){var t,n;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(var i in this.subscriptions)if(null===(n=this.subscriptions[i])||void 0===n?void 0:n.length)return!0;return!1},RealtimeService.prototype.submitSubscriptions=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(e){return this.clientId?(this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),[2,this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},params:{$cancelKey:this.getSubscriptionsCancelKey()}}).catch((function(e){if(!(null==e?void 0:e.isAbort))throw e}))]):[2]}))}))},RealtimeService.prototype.getSubscriptionsCancelKey=function(){return"realtime_"+this.clientId},RealtimeService.prototype.getNonEmptySubscriptionTopics=function(){var e=[];for(var t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e},RealtimeService.prototype.addAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.removeAllSubscriptionListeners(),this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.addEventListener(e,i)}},RealtimeService.prototype.removeAllSubscriptionListeners=function(){if(this.eventSource)for(var e in this.subscriptions)for(var t=0,n=this.subscriptions[e];t<n.length;t++){var i=n[t];this.eventSource.removeEventListener(e,i)}},RealtimeService.prototype.connect=function(){return __awaiter(this,void 0,void 0,(function(){var e=this;return __generator(this,(function(t){return this.reconnectAttempts>0?[2]:[2,new Promise((function(t,n){e.pendingConnects.push({resolve:t,reject:n}),e.pendingConnects.length>1||e.initConnect()}))]}))}))},RealtimeService.prototype.initConnect=function(){var e=this;this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((function(){e.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=function(t){e.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(function(t){var n=t;e.clientId=null==n?void 0:n.lastEventId,e.submitSubscriptions().then((function(){return __awaiter(e,void 0,void 0,(function(){var e;return __generator(this,(function(t){switch(t.label){case 0:e=3,t.label=1;case 1:return this.hasUnsentSubscriptions()&&e>0?(e--,[4,this.submitSubscriptions()]):[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))}))})).then((function(){for(var t=0,n=e.pendingConnects;t<n.length;t++){n[t].resolve()}e.pendingConnects=[],e.reconnectAttempts=0,clearTimeout(e.reconnectTimeoutId),clearTimeout(e.connectTimeoutId)})).catch((function(t){e.clientId="",e.connectErrorHandler(t)}))}))},RealtimeService.prototype.hasUnsentSubscriptions=function(){var e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(var t=0,n=e;t<n.length;t++){var i=n[t];if(!this.lastSentTopics.includes(i))return!0}return!1},RealtimeService.prototype.connectErrorHandler=function(e){var n=this;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(var i=0,o=this.pendingConnects;i<o.length;i++){o[i].reject(new t(e))}return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);var r=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((function(){n.initConnect()}),r)},RealtimeService.prototype.disconnect=function(e){var t;if(void 0===e&&(e=!1),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(var n=0,i=this.pendingConnects;n<i.length;n++){i[n].resolve()}this.pendingConnects=[]}},RealtimeService}(c),C=function(e){function HealthService(){return null!==e&&e.apply(this,arguments)||this}return __extends(HealthService,e),HealthService.prototype.check=function(e){return void 0===e&&(e={}),this.client.send("/api/health",{method:"GET",params:e})},HealthService}(c),_=function(e){function FileService(){return null!==e&&e.apply(this,arguments)||this}return __extends(FileService,e),FileService.prototype.getUrl=function(e,t,n){void 0===n&&(n={});var i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));var o=this.client.buildUrl(i.join("/"));if(Object.keys(n).length){!1===n.download&&delete n.download;var r=new URLSearchParams(n);o+=(o.includes("?")?"&":"?")+r}return o},FileService.prototype.getToken=function(e){return void 0===e&&(e={}),this.client.send("/api/files/token",{method:"POST",params:e}).then((function(e){return(null==e?void 0:e.token)||""}))},FileService}(c),R=function(e){function BackupService(){return null!==e&&e.apply(this,arguments)||this}return __extends(BackupService,e),BackupService.prototype.getFullList=function(e){return void 0===e&&(e={}),this.client.send("/api/backups",{method:"GET",params:e})},BackupService.prototype.create=function(e,t){void 0===t&&(t={});var n={name:e};return this.client.send("/api/backups",{method:"POST",params:t,body:n}).then((function(){return!0}))},BackupService.prototype.delete=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e)),{method:"DELETE",params:t}).then((function(){return!0}))},BackupService.prototype.restore=function(e,t){return void 0===t&&(t={}),this.client.send("/api/backups/".concat(encodeURIComponent(e),"/restore"),{method:"POST",params:t}).then((function(){return!0}))},BackupService.prototype.getDownloadUrl=function(e,t){return this.client.buildUrl("/api/backups/".concat(encodeURIComponent(t),"?token=").concat(encodeURIComponent(e)))},BackupService}(c);return function(){function Client(e,t,n){void 0===e&&(e="/"),void 0===n&&(n="en-US"),this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=n,this.authStore=t||new a,this.admins=new p(this),this.collections=new y(this),this.files=new _(this),this.logs=new S(this),this.settings=new u(this),this.realtime=new w(this),this.health=new C(this),this.backups=new R(this)}return Client.prototype.collection=function(e){return this.recordServices[e]||(this.recordServices[e]=new f(this,e)),this.recordServices[e]},Client.prototype.autoCancellation=function(e){return this.enableAutoCancellation=!!e,this},Client.prototype.cancelRequest=function(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this},Client.prototype.cancelAllRequests=function(){for(var e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this},Client.prototype.send=function(e,n){var i,o,r,s,a,c,u,l;return __awaiter(this,void 0,void 0,(function(){var d,h,p,v,f,m,b,y,g,S=this;return __generator(this,(function(w){switch(w.label){case 0:return d=Object.assign({method:"GET"},n),this.isFormData(d.body)||(d.body&&"string"!=typeof d.body&&(d.body=JSON.stringify(d.body)),void 0===(null===(i=null==d?void 0:d.headers)||void 0===i?void 0:i["Content-Type"])&&(d.headers=Object.assign({},d.headers,{"Content-Type":"application/json"}))),void 0===(null===(o=null==d?void 0:d.headers)||void 0===o?void 0:o["Accept-Language"])&&(d.headers=Object.assign({},d.headers,{"Accept-Language":this.lang})),(null===(r=this.authStore)||void 0===r?void 0:r.token)&&void 0===(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s.Authorization)&&(d.headers=Object.assign({},d.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&!1!==(null===(a=d.params)||void 0===a?void 0:a.$autoCancel)&&(h=(null===(c=d.params)||void 0===c?void 0:c.$cancelKey)||(d.method||"GET")+e,this.cancelRequest(h),p=new AbortController,this.cancelControllers[h]=p,d.signal=p.signal),null===(u=d.params)||void 0===u||delete u.$autoCancel,null===(l=d.params)||void 0===l||delete l.$cancelKey,v=this.buildUrl(e),void 0!==d.params&&((f=this.serializeQueryParams(d.params))&&(v+=(v.includes("?")?"&":"?")+f),delete d.params),this.beforeSend?(y=(b=Object).assign,g=[{}],[4,this.beforeSend(v,d)]):[3,2];case 1:void 0!==(m=y.apply(b,g.concat([w.sent()]))).url||void 0!==m.options?(v=m.url||v,d=m.options||d):Object.keys(m).length&&(d=m,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.")),w.label=2;case 2:return[2,fetch(v,d).then((function(e){return __awaiter(S,void 0,void 0,(function(){var n;return __generator(this,(function(i){switch(i.label){case 0:n={},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.json()];case 2:return n=i.sent(),[3,4];case 3:return i.sent(),[3,4];case 4:return this.afterSend?[4,this.afterSend(e,n)]:[3,6];case 5:n=i.sent(),i.label=6;case 6:if(e.status>=400)throw new t({url:e.url,status:e.status,data:n});return[2,n]}}))}))})).catch((function(e){throw new t(e)}))]}}))}))},Client.prototype.getFileUrl=function(e,t,n){return void 0===n&&(n={}),this.files.getUrl(e,t,n)},Client.prototype.buildUrl=function(e){var t,n=this.baseUrl;return"undefined"==typeof window||!window.location||n.startsWith("https://")||n.startsWith("http://")||(n=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(n+=window.location.pathname||"/",n+=n.endsWith("/")?"":"/"),n+=this.baseUrl),e&&(n+=n.endsWith("/")?"":"/",n+=e.startsWith("/")?e.substring(1):e),n},Client.prototype.isFormData=function(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)},Client.prototype.serializeQueryParams=function(e){var t=[];for(var n in e)if(null!==e[n]){var i=e[n],o=encodeURIComponent(n);if(Array.isArray(i))for(var r=0,s=i;r<s.length;r++){var a=s[r];t.push(o+"="+encodeURIComponent(a))}else i instanceof Date?t.push(o+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(o+"="+encodeURIComponent(JSON.stringify(i))):t.push(o+"="+encodeURIComponent(i))}return t.join("&")},Client}()}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PocketBase=t()}(this,(function(){"use strict";function __awaiter(e,t,i,s){return new(i||(i=Promise))((function(n,o){function fulfilled(e){try{step(s.next(e))}catch(e){o(e)}}function rejected(e){try{step(s.throw(e))}catch(e){o(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class ClientResponseError extends Error{constructor(e){var t,i,s,n;super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=null===(t=this.response)||void 0===t?void 0:t.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":(null===(n=null===(s=null===(i=this.originalError)||void 0===i?void 0:i.cause)||void 0===s?void 0:s.message)||void 0===n?void 0:n.includes("ECONNREFUSED ::1"))?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return Object.assign({},this)}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,i,s){const n=Object.assign({},s||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(i);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}let t;function getTokenPayload(e){if(e)try{const i=decodeURIComponent(t(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(i)||{}}catch(e){}return{}}t="function"==typeof atob?atob:e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,s,n=0,o=0,r="";s=t.charAt(o++);~s&&(i=n%4?64*i+s:s,n++%4)?r+=String.fromCharCode(255&i>>(-2*n&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return r};const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!function isTokenExpired(e,t=0){let i=getTokenPayload(e);return!(Object.keys(i).length>0&&(!i.exp||i.exp-t>Date.now()/1e3))}(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const i={};if("string"!=typeof e)return i;const s=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n<e.length;){const t=e.indexOf("=",n);if(-1===t)break;let o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<t){n=e.lastIndexOf(";",t-1)+1;continue}const r=e.slice(n,t).trim();if(void 0===i[r]){let n=e.slice(t+1,o).trim();34===n.charCodeAt(0)&&(n=n.slice(1,-1));try{i[r]=s(n)}catch(e){i[r]=n}}n=o+1}return i}(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){var s,n;const o={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},r=getTokenPayload(this.token);(null==r?void 0:r.exp)?o.expires=new Date(1e3*r.exp):o.expires=new Date("1970-01-01"),e=Object.assign({},o,e);const a={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let l=cookieSerialize(t,JSON.stringify(a),e);const c="undefined"!=typeof Blob?new Blob([l]).size:l.length;if(a.model&&c>4096){a.model={id:null===(s=null==a?void 0:a.model)||void 0===s?void 0:s.id,email:null===(n=null==a?void 0:a.model)||void 0===n?void 0:n.email};const i=["collectionId","username","verified"];for(const e in this.model)i.includes(e)&&(a.model[e]=this.model[e]);l=cookieSerialize(t,JSON.stringify(a),e)}return l}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)){let i=t;"string"!=typeof t&&(i=JSON.stringify(t)),window.localStorage.setItem(e,i)}else this.storageFallback[e]=t}_storageRemove(e){var t;"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&(null===(t=window.localStorage)||void 0===t||t.removeItem(e)),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&(null===window||void 0===window?void 0:window.localStorage)&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}testEmail(e,t,i){return i=Object.assign({method:"POST",body:{email:e,template:t}},i),this.client.send("/api/settings/test/email",i).then((()=>!0))}generateAppleClientSecret(e,t,i,s,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:i,privateKey:s,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let i=500;return(t=Object.assign({},e,t)).batch&&(i=t.batch,delete t.batch),this._getFullList(i,t)}getList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send(this.baseCrudPath,i).then((e=>{var t;return e.items=(null===(t=e.items)||void 0===t?void 0:t.map((e=>this.decode(e))))||[],e}))}getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{var t;if(!(null===(t=null==e?void 0:e.items)||void 0===t?void 0:t.length))throw new ClientResponseError({status:404,data:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}getOne(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}update(e,t,i){return i=Object.assign({method:"PATCH",body:t},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),i).then((e=>this.decode(e)))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let i=[],request=s=>__awaiter(this,void 0,void 0,(function*(){return this.getList(s,e||500,t).then((e=>{const t=e.items;return i=i.concat(t),t.length==e.perPage?request(s+1):i}))}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,i,s){const n=void 0!==s;return n||void 0!==i?n?(console.warn(e),t.body=Object.assign({},t.body,i),t.query=Object.assign({},t.query,s),t):t=Object.assign(t,i):t}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)===e.id&&void 0===(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)&&this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s;return t&&(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)===e&&void 0===(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)&&this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.admin)||{});return(null==e?void 0:e.token)&&(null==e?void 0:e.admin)&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",admin:t})}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(email, pass, options?).",n,i,s),this.client.send(this.baseCrudPath+"/auth-with-password",n).then(this.authResponse.bind(this))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",i).then(this.authResponse.bind(this))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCrudPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}subscribeOne(e,t){return __awaiter(this,void 0,void 0,(function*(){return console.warn("PocketBase: subscribeOne(recordId, callback) is deprecated. Please replace it with subscribe(recordId, callback)."),this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t)}))}subscribe(e,t){return __awaiter(this,void 0,void 0,(function*(){if("function"==typeof e)return console.warn("PocketBase: subscribe(callback) is deprecated. Please replace it with subscribe('*', callback)."),this.client.realtime.subscribe(this.collectionIdOrName,e);if(!t)throw new Error("Missing subscription callback.");if(""===e)throw new Error("Missing topic.");let i=this.collectionIdOrName;return"*"!==e&&(i+="/"+e),this.client.realtime.subscribe(i,t)}))}unsubscribe(e){return __awaiter(this,void 0,void 0,(function*(){return"*"===e?this.client.realtime.unsubscribe(this.collectionIdOrName):e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}))}getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const i=Object.assign({},e,t);return super.getFullList(i)}getList(e=1,t=30,i){return super.getList(e,t,i)}getFirstListItem(e,t){return super.getFirstListItem(e,t)}getOne(e,t){return super.getOne(e,t)}create(e,t){return super.create(e,t)}update(e,t,i){return super.update(e,t,i).then((e=>{var t,i,s;return(null===(t=this.client.authStore.model)||void 0===t?void 0:t.id)!==(null==e?void 0:e.id)||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.collectionId)!==this.collectionIdOrName&&(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionName)!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e}))}delete(e,t){return super.delete(e,t).then((t=>{var i,s,n;return!t||(null===(i=this.client.authStore.model)||void 0===i?void 0:i.id)!==e||(null===(s=this.client.authStore.model)||void 0===s?void 0:s.collectionId)!==this.collectionIdOrName&&(null===(n=this.client.authStore.model)||void 0===n?void 0:n.collectionName)!==this.collectionIdOrName||this.client.authStore.clear(),t}))}authResponse(e){const t=this.decode((null==e?void 0:e.record)||{});return this.client.authStore.save(null==e?void 0:e.token,t),Object.assign({},e,{token:(null==e?void 0:e.token)||"",record:t})}listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!(null==e?void 0:e.usernamePassword),emailPassword:!!(null==e?void 0:e.emailPassword),authProviders:Array.isArray(null==e?void 0:e.authProviders)?null==e?void 0:e.authProviders:[]})))}authWithPassword(e,t,i,s){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is depreacted. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}authWithOAuth2Code(e,t,i,s,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:i,redirectUrl:s,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is depreacted. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){return __awaiter(this,void 0,void 0,(function*(){if(e.length>1||"string"==typeof(null==e?void 0:e[0]))return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code((null==e?void 0:e[0])||"",(null==e?void 0:e[1])||"",(null==e?void 0:e[2])||"",(null==e?void 0:e[3])||"",(null==e?void 0:e[4])||{},(null==e?void 0:e[5])||{},(null==e?void 0:e[6])||{});const t=(null==e?void 0:e[0])||{},i=(yield this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!i)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const s=this.client.buildUrl("/api/oauth2-redirect");return new Promise(((e,n)=>__awaiter(this,void 0,void 0,(function*(){var o;try{const r=yield this.client.realtime.subscribe("@oauth2",(o=>__awaiter(this,void 0,void 0,(function*(){const a=this.client.realtime.clientId;try{if(r(),!o.state||a!==o.state)throw new Error("State parameters don't match.");const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const l=yield this.authWithOAuth2Code(i.name,o.code,i.codeVerifier,s,t.createData,n);e(l)}catch(e){n(new ClientResponseError(e))}})))),a={state:this.client.realtime.clientId};(null===(o=t.scopes)||void 0===o?void 0:o.length)&&(a.scope=t.scopes.join(" "));const l=this._replaceQueryParams(i.authUrl+s,a);yield t.urlCallback?t.urlCallback(l):this._defaultUrlCallback(l)}catch(e){n(new ClientResponseError(e))}}))))}))}authRefresh(e,t){let i={method:"POST"};return i=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is depreacted. Consider replacing it with authRefresh(options?).",i,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",i).then((e=>this.authResponse(e)))}requestPasswordReset(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is depreacted. Consider replacing it with requestPasswordReset(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-password-reset",s).then((()=>!0))}confirmPasswordReset(e,t,i,s,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:i}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is depreacted. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,s,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}requestVerification(e,t,i){let s={method:"POST",body:{email:e}};return s=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is depreacted. Consider replacing it with requestVerification(email, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-verification",s).then((()=>!0))}confirmVerification(e,t,i){let s={method:"POST",body:{token:e}};return s=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is depreacted. Consider replacing it with confirmVerification(token, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/confirm-verification",s).then((()=>!0))}requestEmailChange(e,t,i){let s={method:"POST",body:{newEmail:e}};return s=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is depreacted. Consider replacing it with requestEmailChange(newEmail, options?).",s,t,i),this.client.send(this.baseCollectionPath+"/request-email-change",s).then((()=>!0))}confirmEmailChange(e,t,i,s){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is depreacted. Consider replacing it with confirmEmailChange(token, password, options?).",n,i,s),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>!0))}listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}unlinkExternalAuth(e,t,i){return i=Object.assign({method:"DELETE"},i),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),i).then((()=>!0))}_replaceQueryParams(e,t={}){let i=e,s="";e.indexOf("?")>=0&&(i=e.substring(0,e.indexOf("?")),s=e.substring(e.indexOf("?")+1));const n={},o=s.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);s="";for(let e in n)n.hasOwnProperty(e)&&(""!=s&&(s+="&"),s+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=s?i+"?"+s:i}_defaultUrlCallback(e){if("undefined"==typeof window||!(null===window||void 0===window?void 0:window.open))throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,i=768,s=window.innerWidth,n=window.innerHeight;t=t>s?s:t,i=i>n?n:i;let o=s/2-t/2,r=n/2-i/2;window.open(e,"oauth2-popup","width="+t+",height="+i+",top="+r+",left="+o+",resizable,menubar=no")}}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}import(e,t=!1,i){return __awaiter(this,void 0,void 0,(function*(){return i=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},i),this.client.send(this.baseCrudPath+"/import",i).then((()=>!0))}))}}class LogService extends BaseService{getRequestsList(e=1,t=30,i){return(i=Object.assign({method:"GET"},i)).query=Object.assign({page:e,perPage:t},i.query),this.client.send("/api/logs/requests",i)}getRequest(e,t){return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/requests/"+encodeURIComponent(e),t)}getRequestsStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/requests/stats",e)}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentTopics=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}subscribe(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!e)throw new Error("topic must be set.");const listener=function(e){const i=e;let s;try{s=JSON.parse(null==i?void 0:i.data)}catch(e){}t(s||{})};return this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push(listener),this.isConnected?1===this.subscriptions[e].length?yield this.submitSubscriptions():null===(i=this.eventSource)||void 0===i||i.addEventListener(e,listener):yield this.connect(),()=>__awaiter(this,void 0,void 0,(function*(){return this.unsubscribeByTopicAndListener(e,listener)}))}))}unsubscribe(e){var t;return __awaiter(this,void 0,void 0,(function*(){if(this.hasSubscriptionListeners(e)){if(e){for(let i of this.subscriptions[e])null===(t=this.eventSource)||void 0===t||t.removeEventListener(e,i);delete this.subscriptions[e]}else this.subscriptions={};this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect()}}))}unsubscribeByPrefix(e){var t;return __awaiter(this,void 0,void 0,(function*(){let i=!1;for(let s in this.subscriptions)if(s.startsWith(e)){i=!0;for(let e of this.subscriptions[s])null===(t=this.eventSource)||void 0===t||t.removeEventListener(s,e);delete this.subscriptions[s]}i&&(this.hasSubscriptionListeners()?yield this.submitSubscriptions():this.disconnect())}))}unsubscribeByTopicAndListener(e,t){var i;return __awaiter(this,void 0,void 0,(function*(){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)return;let s=!1;for(let n=this.subscriptions[e].length-1;n>=0;n--)this.subscriptions[e][n]===t&&(s=!0,delete this.subscriptions[e][n],this.subscriptions[e].splice(n,1),null===(i=this.eventSource)||void 0===i||i.removeEventListener(e,t));s&&(this.subscriptions[e].length||delete this.subscriptions[e],this.hasSubscriptionListeners()?this.hasSubscriptionListeners(e)||(yield this.submitSubscriptions()):this.disconnect())}))}hasSubscriptionListeners(e){var t,i;if(this.subscriptions=this.subscriptions||{},e)return!!(null===(t=this.subscriptions[e])||void 0===t?void 0:t.length);for(let e in this.subscriptions)if(null===(i=this.subscriptions[e])||void 0===i?void 0:i.length)return!0;return!1}submitSubscriptions(){return __awaiter(this,void 0,void 0,(function*(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentTopics=this.getNonEmptySubscriptionTopics(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentTopics},query:{requestKey:this.getSubscriptionsCancelKey()}}).catch((e=>{if(!(null==e?void 0:e.isAbort))throw e}))}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getNonEmptySubscriptionTopics(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}connect(){return __awaiter(this,void 0,void 0,(function*(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=null==t?void 0:t.lastEventId,this.submitSubscriptions().then((()=>__awaiter(this,void 0,void 0,(function*(){let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,yield this.submitSubscriptions()})))).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionTopics();if(e.length!=this.lastSentTopics.length)return!0;for(const t of e)if(!this.lastSentTopics.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){var t;if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),null===(t=this.eventSource)||void 0===t||t.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class HealthService extends BaseService{check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,i={}){const s=[];s.push("api"),s.push("files"),s.push(encodeURIComponent(e.collectionId||e.collectionName)),s.push(encodeURIComponent(e.id)),s.push(encodeURIComponent(t));let n=this.client.buildUrl(s.join("/"));if(Object.keys(i).length){!1===i.download&&delete i.download;const e=new URLSearchParams(i);n+=(n.includes("?")?"&":"?")+e}return n}getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>(null==e?void 0:e.token)||""))}}class BackupService extends BaseService{getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}const s=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];return class Client{constructor(e="/",t,i="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=i,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}getFileUrl(e,t,i={}){return this.files.getUrl(e,t,i)}buildUrl(e){var t;let i=this.baseUrl;return"undefined"==typeof window||!window.location||i.startsWith("https://")||i.startsWith("http://")||(i=(null===(t=window.location.origin)||void 0===t?void 0:t.endsWith("/"))?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(i+=window.location.pathname||"/",i+=i.endsWith("/")?"":"/"),i+=this.baseUrl),e&&(i+=i.endsWith("/")?"":"/",i+=e.startsWith("/")?e.substring(1):e),i}send(e,t){return __awaiter(this,void 0,void 0,(function*(){t=this.initSendOptions(e,t);let i=this.buildUrl(e);if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(i+=(i.includes("?")?"&":"?")+e),delete t.query}if(this.beforeSend){const e=Object.assign({},yield this.beforeSend(i,t));void 0!==e.url||void 0!==e.options?(i=e.url||i,t=e.options||t):Object.keys(e).length&&(t=e,(null===console||void 0===console?void 0:console.warn)&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(i,t).then((e=>__awaiter(this,void 0,void 0,(function*(){let t={};try{t=yield e.json()}catch(e){}if(this.afterSend&&(t=yield this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})))).catch((e=>{throw new ClientResponseError(e)}))}))}initSendOptions(e,t){(t=Object.assign({method:"GET"},t)).query=t.query||{},t.body=this.convertToFormDataIfNeeded(t.body);for(let e in t)s.includes(e)||(t.query[e]=t[e],delete t[e]);if(t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const i=t.requestKey||(t.method||"GET")+e;this.cancelRequest(i);const s=new AbortController;this.cancelControllers[i]=s,t.signal=s.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(let i in e)t.append(i,e[i]);return t}hasBlobField(e){for(let t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];for(let e of i)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let i in e)if(i.toLowerCase()==t)return e[i];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const i in e){if(null===e[i])continue;const s=e[i],n=encodeURIComponent(i);if(Array.isArray(s))for(const e of s)t.push(n+"="+encodeURIComponent(e));else s instanceof Date?t.push(n+"="+encodeURIComponent(s.toISOString())):null!==typeof s&&"object"==typeof s?t.push(n+"="+encodeURIComponent(JSON.stringify(s))):t.push(n+"="+encodeURIComponent(s))}return t.join("&")}}}));
//# sourceMappingURL=pocketbase.umd.js.map
{
"version": "0.16.0",
"version": "0.17.0-rc1",
"name": "pocketbase",

@@ -30,21 +30,12 @@ "description": "PocketBase JavaScript SDK",

"dev": "rollup -c -w",
"test": "env TS_NODE_PROJECT='tsconfig-test.json' mocha 'tests/**/*.spec.ts' --require=ts-node/register",
"test": "vitest",
"prepublishOnly": "npm run build"
},
"devDependencies": {
"@types/chai": "^4.2.19",
"@types/chai-as-promised": "^7.1.4",
"@types/mocha": "^8.2.2",
"@types/sinon": "^10.0.11",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"mocha": "^9.0.1",
"rollup": "^2.79.1",
"rollup-plugin-terser": "^7.0.0",
"rollup-plugin-ts": "^2.0.0",
"ts-node": "^10.0.0",
"tsconfig-paths": "^4.0.0",
"tslib": "^2.4.0",
"typescript": "4.6.4"
"@rollup/plugin-terser": "^0.4.3",
"rollup": "^3.0.0",
"rollup-plugin-ts": "^3.0.0",
"typescript": "^5.1.6",
"vitest": "^0.34.1"
}
}

@@ -11,3 +11,7 @@ PocketBase JavaScript SDK

- [Error handling](#error-handling)
- [AuthStore](#authstore)
- [Auth store](#auth-store)
- [LocalAuthStore (default)](#localauthstore-default)
- [AsyncAuthStore (_usually used with React Native_)](#asyncauthstore)
- [Custom auth store](#custom-auth-store)
- [Common auth store fields and methods](#common-auth-store-fields-and-methods)
- [Auto cancellation](#auto-cancellation)

@@ -173,8 +177,49 @@ - [Custom Record types](#custom-record-types)

### AuthStore
### Auth store
The SDK keeps track of the authenticated token and auth model for you via the `pb.authStore` instance.
##### LocalAuthStore (default)
The default [`LocalAuthStore`](https://github.com/pocketbase/js-sdk/blob/master/src/stores/LocalAuthStore.ts) uses the browser's `LocalStorage` if available, otherwise - will fallback to runtime/memory (aka. on page refresh or service restart you'll have to authenticate again).
Conveniently, the default store also takes care to automatically sync the auth store state between multiple tabs.
> _**NB!** Deno also supports `LocalStorage` but keep in mind that, unlike in browsers where the client is the only user, by default Deno `LocalStorage` will be shared by all clients making requests to your server!_
##### AsyncAuthStore
The SDK comes also with a helper [`AsyncAuthStore`](https://github.com/pocketbase/js-sdk/blob/master/src/stores/AsyncAuthStore.ts) that you can use to integrate with any 3rd party async storage implementation (_usually this is needed when working with React Native_):
```js
import AsyncStorage from '@react-native-async-storage/async-storage';
import PocketBase, { AsyncAuthStore } from 'pocketbase';
const store = new AsyncAuthStore({
save: async (serialized) => AsyncStorage.setItem('pb_auth', serialized),
initial: await AsyncStorage.getItem('pb_auth'),
});
const pb = new PocketBase('http://127.0.0.1:8090', store)
```
##### Custom auth store
In some situations it could be easier to create your own custom auth store. For this you can extend [`BaseAuthStore`](https://github.com/pocketbase/js-sdk/blob/master/src/stores/BaseAuthStore.ts) and pass the new custom instance as constructor argument to the client:
```js
import PocketBase, { BaseAuthStore } from 'pocketbase';
class CustomAuthStore extends BaseAuthStore {
save(token, model) {
super.save(token, model);
// your custom business logic...
}
}
const pb = new PocketBase('http://127.0.0.1:8090', new CustomAuthStore());
```
##### Common auth store fields and methods
The default `pb.authStore` extends [`BaseAuthStore`](https://github.com/pocketbase/js-sdk/blob/master/src/stores/BaseAuthStore.ts) and has the following public members that you can use:

@@ -185,5 +230,7 @@

// base fields
token: string // the authenticated token
model: Record|Admin|null // the authenticated Record or Admin model
isValid: boolean // checks if the store has existing and unexpired token
model: RecordModel|AdminModel|null // the authenticated auth record or admin model
token: string // the authenticated token
isValid: boolean // checks if the store has existing and unexpired token
isAdmin: boolean // checks if the store state is for admin
isAuthRecord: boolean // checks if the store state is for an auth record

@@ -201,3 +248,3 @@ // main methods

To _"logout"_ an authenticated Record or Admin, you can just call `pb.authStore.clear()`.
To _"logout"_ an authenticated record or admin you can call `pb.authStore.clear()`.

@@ -221,17 +268,3 @@ To _"listen"_ for changes in the auth store, you can register a new listener via `pb.authStore.onChange`, eg:

If you want to create your own `AuthStore`, you can extend [`BaseAuthStore`](https://github.com/pocketbase/js-sdk/blob/master/src/stores/BaseAuthStore.ts) and pass the new custom instance as constructor argument to the client:
```js
import PocketBase, { BaseAuthStore } from 'pocketbase';
class CustomAuthStore extends BaseAuthStore {
save(token, model) {
super.save(token, model);
// your custom business logic...
}
}
const pb = new PocketBase('http://127.0.0.1:8090', new CustomAuthStore());
```
### Auto cancellation

@@ -248,16 +281,15 @@

To change this behavior, you could make use of 2 special query parameters:
To change this behavior per request basis, you can adjust the `requestKey: null|string` special query parameter.
Set it to `null` to unset the default request identifier and to disable auto cancellation for the specific request.
Or set it to a unique string that will be used as request identifier and based on which pending requests will be matched (default to `HTTP_METHOD + path`, eg. "GET /api/users")
- `$autoCancel ` - set it to `false` to disable auto cancellation for this request
- `$cancelKey` - set it to a string that will be used as request identifier and based on which pending requests will be matched (default to `HTTP_METHOD + path`, eg. "GET /api/users")
Example:
```js
pb.collection('example').getList(1, 20); // cancelled
pb.collection('example').getList(1, 20); // executed
pb.collection('example').getList(1, 20, { '$cancelKey': "test" }) // cancelled
pb.collection('example').getList(1, 20, { '$cancelKey': "test" }) // executed
pb.collection('example').getList(1, 20, { '$autoCancel': false }); // executed
pb.collection('example').getList(1, 20, { '$autoCancel': false }) // executed
pb.collection('example').getList(1, 20); // cancelled
pb.collection('example').getList(1, 20); // executed
pb.collection('example').getList(1, 20, { requestKey: "test" }) // cancelled
pb.collection('example').getList(1, 20, { requestKey: "test" }) // executed
pb.collection('example').getList(1, 20, { requestKey: null }) // executed
pb.collection('example').getList(1, 20, { requestKey: null }) // executed

@@ -272,5 +304,5 @@ // globally disable auto cancellation

**If you want to completelly disable the auto cancellation behavior, you could set `pb.autoCancellation(false)`.**
**If you want to globally disable the auto cancellation behavior, you could set `pb.autoCancellation(false)`.**
To manually cancel pending requests, you could use `pb.cancelAllRequests()` or `pb.cancelRequest(cancelKey)`.
To manually cancel pending requests, you could use `pb.cancelAllRequests()` or `pb.cancelRequest(requestKey)`.

@@ -622,9 +654,9 @@

| Method | Description |
|:--------------------------------------------------|:------------------------------------------------------------------------------|
| `pb.send(path, reqConfig = {})` | Sends an api http request. |
| `pb.autoCancellation(enable)` | Globally enable or disable auto cancellation for pending duplicated requests. |
| `pb.cancelAllRequests()` | Cancels all pending requests. |
| `pb.cancelRequest(cancelKey)` | Cancels single request by its cancellation token key. |
| `pb.buildUrl(path, reqConfig = {})` | Builds a full client url by safely concatenating the provided path. |
| Method | Description |
|:----------------------------------|:------------------------------------------------------------------------------|
| `pb.send(path, sendOptions = {})` | Sends an api http request. |
| `pb.autoCancellation(enable)` | Globally enable or disable auto cancellation for pending duplicated requests. |
| `pb.cancelAllRequests()` | Cancels all pending requests. |
| `pb.cancelRequest(cancelKey)` | Cancels single request by its cancellation token key. |
| `pb.buildUrl(path)` | Builds a full client url by safely concatenating the provided path. |

@@ -642,22 +674,22 @@

// Returns a paginated records list.
🔓 pb.collection(collectionIdOrName).getList(page = 1, perPage = 30, queryParams = {});
🔓 pb.collection(collectionIdOrName).getList(page = 1, perPage = 30, options = {});
// Returns a list with all records batch fetched at once
// (by default 200 items per request; to change it set the `batch` query param).
🔓 pb.collection(collectionIdOrName).getFullList(queryParams = {});
// (by default 200 items per request; to change it set the `batch` param).
🔓 pb.collection(collectionIdOrName).getFullList(options = {});
// Returns the first found record matching the specified filter.
🔓 pb.collection(collectionIdOrName).getFirstListItem(filter, queryParams = {});
🔓 pb.collection(collectionIdOrName).getFirstListItem(filter, options = {});
// Returns a single record by its id.
🔓 pb.collection(collectionIdOrName).getOne(recordId, queryParams = {});
🔓 pb.collection(collectionIdOrName).getOne(recordId, options = {});
// Creates (aka. register) a new record.
🔓 pb.collection(collectionIdOrName).create(bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).create(bodyParams = {}, options = {});
// Updates an existing record by its id.
🔓 pb.collection(collectionIdOrName).update(recordId, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).update(recordId, bodyParams = {}, options = {});
// Deletes a single record by its id.
🔓 pb.collection(collectionIdOrName).delete(recordId, queryParams = {});
🔓 pb.collection(collectionIdOrName).delete(recordId, options = {});

@@ -688,6 +720,6 @@ ```

// Returns all available application auth methods.
🔓 pb.collection(collectionIdOrName).listAuthMethods(queryParams = {});
🔓 pb.collection(collectionIdOrName).listAuthMethods(options = {});
// Authenticates a record with their username/email and password.
🔓 pb.collection(collectionIdOrName).authWithPassword(usernameOrEmail, password, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).authWithPassword(usernameOrEmail, password, options = {});

@@ -698,30 +730,30 @@ // Authenticates a record with OAuth2 provider without custom redirects, deeplinks or even page reload.

// Authenticates a record with OAuth2 code.
🔓 pb.collection(collectionIdOrName).authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData = {}, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData = {}, options = {});
// Refreshes the current authenticated record model and auth token.
🔐 pb.collection(collectionIdOrName).authRefresh(bodyParams = {}, queryParams = {});
🔐 pb.collection(collectionIdOrName).authRefresh(bodyParams = {}, options = {});
// Sends a user password reset email.
🔓 pb.collection(collectionIdOrName).requestPasswordReset(email, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).requestPasswordReset(email, options = {});
// Confirms a record password reset request.
🔓 pb.collection(collectionIdOrName).confirmPasswordReset(resetToken, newPassword, newPasswordConfirm, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).confirmPasswordReset(resetToken, newPassword, newPasswordConfirm, options = {});
// Sends a record verification email request.
🔓 pb.collection(collectionIdOrName).requestVerification(email, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).requestVerification(email, options = {});
// Confirms a record email verification request.
🔓 pb.collection(collectionIdOrName).confirmVerification(verificationToken, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).confirmVerification(verificationToken, options = {});
// Sends a record email change request to the provider email.
🔐 pb.collection(collectionIdOrName).requestEmailChange(newEmail, bodyParams = {}, queryParams = {});
🔐 pb.collection(collectionIdOrName).requestEmailChange(newEmail, options = {});
// Confirms record new email address.
🔓 pb.collection(collectionIdOrName).confirmEmailChange(emailChangeToken, userPassword, bodyParams = {}, queryParams = {});
🔓 pb.collection(collectionIdOrName).confirmEmailChange(emailChangeToken, userPassword, options = {});
// Lists all linked external auth providers for the specified record.
🔐 pb.collection(collectionIdOrName).listExternalAuths(recordId, queryParams = {});
🔐 pb.collection(collectionIdOrName).listExternalAuths(recordId, options = {});
// Unlinks a single external auth provider relation from the specified record.
🔐 pb.collection(collectionIdOrName).unlinkExternalAuth(recordId, provider, queryParams = {});
🔐 pb.collection(collectionIdOrName).unlinkExternalAuth(recordId, provider, options = {});
```

@@ -735,6 +767,6 @@

// Builds and returns an absolute record file url for the provided filename.
🔓 pb.files.getUrl(record, filename, queryParams = {});
🔓 pb.files.getUrl(record, filename, options = {});
// Requests a new private file access token for the current auth model (admin or record).
🔐 pb.files.getToken(queryParams = {});
🔐 pb.files.getToken(options = {});
```

@@ -748,34 +780,34 @@

// Authenticates an admin account by its email and password.
🔓 pb.admins.authWithPassword(email, password, bodyParams = {}, queryParams = {});
🔓 pb.admins.authWithPassword(email, password, options = {});
// Refreshes the current admin authenticated model and token.
🔐 pb.admins.authRefresh(bodyParams = {}, queryParams = {});
🔐 pb.admins.authRefresh(options = {});
// Sends an admin password reset email.
🔓 pb.admins.requestPasswordReset(email, bodyParams = {}, queryParams = {});
🔓 pb.admins.requestPasswordReset(email, options = {});
// Confirms an admin password reset request.
🔓 pb.admins.confirmPasswordReset(resetToken, newPassword, newPasswordConfirm, bodyParams = {}, queryParams = {});
🔓 pb.admins.confirmPasswordReset(resetToken, newPassword, newPasswordConfirm, options = {});
// Returns a paginated admins list.
🔐 pb.admins.getList(page = 1, perPage = 30, queryParams = {});
🔐 pb.admins.getList(page = 1, perPage = 30, options = {});
// Returns a list with all admins batch fetched at once
// (by default 200 items per request; to change it set the `batch` query param).
🔐 pb.admins.getFullList(queryParams = {});
🔐 pb.admins.getFullList(options = {});
// Returns the first found admin matching the specified filter.
🔐 pb.admins.getFirstListItem(filter, queryParams = {});
🔐 pb.admins.getFirstListItem(filter, options = {});
// Returns a single admin by their id.
🔐 pb.admins.getOne(id, queryParams = {});
🔐 pb.admins.getOne(id, options = {});
// Creates a new admin.
🔐 pb.admins.create(bodyParams = {}, queryParams = {});
🔐 pb.admins.create(bodyParams = {}, options = {});
// Updates an existing admin by their id.
🔐 pb.admins.update(id, bodyParams = {}, queryParams = {});
🔐 pb.admins.update(id, bodyParams = {}, options = {});
// Deletes a single admin by their id.
🔐 pb.admins.delete(id, queryParams = {});
🔐 pb.admins.delete(id, bodyParams = {}, options = {});
```

@@ -789,25 +821,25 @@

// Returns a paginated collections list.
🔐 pb.collections.getList(page = 1, perPage = 30, queryParams = {});
🔐 pb.collections.getList(page = 1, perPage = 30, options = {});
// Returns a list with all collections batch fetched at once
// (by default 200 items per request; to change it set the `batch` query param).
🔐 pb.collections.getFullList(queryParams = {});
🔐 pb.collections.getFullList(options = {});
// Returns the first found collection matching the specified filter.
🔐 pb.collections.getFirstListItem(filter, queryParams = {});
🔐 pb.collections.getFirstListItem(filter, options = {});
// Returns a single collection by its id.
🔐 pb.collections.getOne(id, queryParams = {});
🔐 pb.collections.getOne(id, options = {});
// Creates (aka. register) a new collection.
🔐 pb.collections.create(bodyParams = {}, queryParams = {});
🔐 pb.collections.create(bodyParams = {}, options = {});
// Updates an existing collection by its id.
🔐 pb.collections.update(id, bodyParams = {}, queryParams = {});
🔐 pb.collections.update(id, bodyParams = {}, options = {});
// Deletes a single collection by its id.
🔐 pb.collections.delete(id, queryParams = {});
🔐 pb.collections.delete(id, options = {});
// Imports the provided collections.
🔐 pb.collections.import(collections, deleteMissing = false, queryParams = {});
🔐 pb.collections.import(collections, deleteMissing = false, options = {});
```

@@ -821,6 +853,6 @@

// Returns a paginated log requests list.
🔐 pb.logs.getRequestsList(page = 1, perPage = 30, queryParams = {});
🔐 pb.logs.getRequestsList(page = 1, perPage = 30, options = {});
// Returns a single log request by its id.
🔐 pb.logs.getRequest(id, queryParams = {});
🔐 pb.logs.getRequest(id, options = {});
```

@@ -834,15 +866,15 @@

// Returns a map with all available app settings.
🔐 pb.settings.getAll(queryParams = {});
🔐 pb.settings.getAll(options = {});
// Bulk updates app settings.
🔐 pb.settings.update(bodyParams = {}, queryParams = {});
🔐 pb.settings.update(bodyParams = {}, options = {});
// Performs a S3 storage connection test.
🔐 pb.settings.testS3(filesystem = "storage", queryParams = {});
🔐 pb.settings.testS3(filesystem = "storage", options = {});
// Sends a test email (verification, password-reset, email-change).
🔐 pb.settings.testEmail(toEmail, template, queryParams = {});
🔐 pb.settings.testEmail(toEmail, template, options = {});
// Generates a new Apple OAuth2 client secret.
🔐 pb.settings.generateAppleClientSecret(clientId, teamId, keyId, privateKey, duration, bodyParams = {}, queryParams = {});
🔐 pb.settings.generateAppleClientSecret(clientId, teamId, keyId, privateKey, duration, options = {});
```

@@ -878,12 +910,12 @@

// Returns list with all available backup files.
🔐 pb.backups.getFullList(queryParams = {});
🔐 pb.backups.getFullList(options = {});
// Initializes a new backup.
🔐 pb.backups.create(basename = "", queryParams = {});
🔐 pb.backups.create(basename = "", options = {});
// Deletes a single backup by its name.
🔐 pb.backups.delete(key, queryParams = {});
🔐 pb.backups.delete(key, options = {});
// Initializes an app data restore from an existing backup.
🔐 pb.backups.restore(key, queryParams = {});
🔐 pb.backups.restore(key, options = {});

@@ -901,3 +933,3 @@ // Builds a download url for a single existing backup using an

// Checks the health status of the api.
🔓 pb.health.check(queryParams = {});
🔓 pb.health.check(options = {});
```

@@ -904,0 +936,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc