@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/configuration.d.ts +16 -47
  3. package/configuration.js +13 -25
  4. package/debug.js +4 -4
  5. package/errors.d.ts +28 -38
  6. package/errors.js +33 -47
  7. package/events/event_manager.d.ts +2 -2
  8. package/events/event_manager.js +7 -6
  9. package/events/index.d.ts +1 -0
  10. package/events/local_event_manager.d.ts +1 -8
  11. package/events/local_event_manager.js +13 -13
  12. package/events/system_info.d.ts +38 -0
  13. package/index.d.ts +2 -8
  14. package/index.js +4 -8
  15. package/internal.d.ts +8 -0
  16. package/internal.js +9 -0
  17. package/log.d.ts +10 -11
  18. package/log.js +52 -20
  19. package/memory-storage/memory-storage.d.ts +15 -18
  20. package/memory-storage/memory-storage.js +80 -58
  21. package/memory-storage/resource-clients/dataset.d.ts +1 -6
  22. package/memory-storage/resource-clients/dataset.js +23 -31
  23. package/memory-storage/resource-clients/key-value-store.d.ts +1 -10
  24. package/memory-storage/resource-clients/key-value-store.js +43 -67
  25. package/memory-storage/resource-clients/request-queue.d.ts +1 -42
  26. package/memory-storage/resource-clients/request-queue.js +109 -117
  27. package/owned_or_injected.d.ts +1 -3
  28. package/owned_or_injected.js +17 -17
  29. package/package.json +17 -20
  30. package/proxy_configuration.d.ts +21 -26
  31. package/proxy_configuration.js +35 -25
  32. package/recoverable_state.d.ts +104 -47
  33. package/recoverable_state.js +199 -74
  34. package/request.d.ts +20 -107
  35. package/request.js +78 -244
  36. package/serialization.js +17 -16
  37. package/service_locator.d.ts +22 -10
  38. package/service_locator.js +59 -48
  39. package/storages/batched_adds.d.ts +37 -0
  40. package/storages/batched_adds.js +73 -0
  41. package/storages/dataset.d.ts +13 -8
  42. package/storages/dataset.js +149 -40
  43. package/storages/index.d.ts +4 -4
  44. package/storages/index.js +2 -4
  45. package/storages/key_value_store.d.ts +16 -35
  46. package/storages/key_value_store.js +223 -110
  47. package/storages/key_value_store_codec.js +6 -11
  48. package/storages/request_dedup_cache.d.ts +1 -4
  49. package/storages/request_dedup_cache.js +15 -15
  50. package/storages/request_list.d.ts +9 -104
  51. package/storages/request_list.js +236 -233
  52. package/storages/request_loader.d.ts +49 -18
  53. package/storages/request_loader.js +36 -1
  54. package/storages/request_manager.d.ts +86 -0
  55. package/storages/request_manager_tandem.d.ts +14 -38
  56. package/storages/request_manager_tandem.js +67 -64
  57. package/storages/request_queue.d.ts +23 -50
  58. package/storages/request_queue.js +371 -226
  59. package/storages/storage_instance_manager.d.ts +2 -4
  60. package/storages/storage_instance_manager.js +21 -21
  61. package/storages/storage_stats.d.ts +1 -1
  62. package/storages/storage_stats.js +4 -4
  63. package/storages/transaction.d.ts +270 -0
  64. package/storages/transaction.js +296 -0
  65. package/storages/utils.d.ts +6 -3
  66. package/storages/utils.js +11 -2
  67. package/system-info/runtime.js +7 -7
  68. package/url.d.ts +9 -0
  69. package/url.js +11 -0
  70. package/validators.d.ts +23 -25
  71. package/validators.js +14 -25
  72. package/autoscaling/autoscaled_pool.d.ts +0 -213
  73. package/autoscaling/autoscaled_pool.js +0 -378
  74. package/autoscaling/client_load_signal.d.ts +0 -59
  75. package/autoscaling/client_load_signal.js +0 -73
  76. package/autoscaling/concurrency_system.d.ts +0 -283
  77. package/autoscaling/concurrency_system.js +0 -350
  78. package/autoscaling/cpu_load_signal.d.ts +0 -44
  79. package/autoscaling/cpu_load_signal.js +0 -46
  80. package/autoscaling/event_loop_load_signal.d.ts +0 -54
  81. package/autoscaling/event_loop_load_signal.js +0 -60
  82. package/autoscaling/index.d.ts +0 -9
  83. package/autoscaling/index.js +0 -9
  84. package/autoscaling/load_signal.d.ts +0 -99
  85. package/autoscaling/load_signal.js +0 -103
  86. package/autoscaling/memory_load_signal.d.ts +0 -56
  87. package/autoscaling/memory_load_signal.js +0 -106
  88. package/autoscaling/snapshotter.d.ts +0 -87
  89. package/autoscaling/snapshotter.js +0 -67
  90. package/autoscaling/system_status.d.ts +0 -161
  91. package/autoscaling/system_status.js +0 -139
  92. package/autoscaling/weighted_avg.d.ts +0 -5
  93. package/autoscaling/weighted_avg.js +0 -14
  94. package/cookie_utils.d.ts +0 -44
  95. package/cookie_utils.js +0 -122
  96. package/crawlers/context_pipeline.d.ts +0 -70
  97. package/crawlers/context_pipeline.js +0 -122
  98. package/crawlers/crawler_commons.d.ts +0 -257
  99. package/crawlers/crawler_commons.js +0 -107
  100. package/crawlers/error_snapshotter.d.ts +0 -59
  101. package/crawlers/error_snapshotter.js +0 -117
  102. package/crawlers/error_tracker.d.ts +0 -54
  103. package/crawlers/error_tracker.js +0 -308
  104. package/crawlers/index.d.ts +0 -5
  105. package/crawlers/index.js +0 -5
  106. package/crawlers/internals/types.d.ts +0 -7
  107. package/crawlers/statistics.d.ts +0 -209
  108. package/crawlers/statistics.js +0 -350
  109. package/enqueue_links/enqueue_links.d.ts +0 -264
  110. package/enqueue_links/enqueue_links.js +0 -271
  111. package/enqueue_links/index.d.ts +0 -2
  112. package/enqueue_links/index.js +0 -2
  113. package/enqueue_links/shared.d.ts +0 -83
  114. package/enqueue_links/shared.js +0 -221
  115. package/router.d.ts +0 -309
  116. package/router.js +0 -309
  117. package/session_pool/consts.d.ts +0 -3
  118. package/session_pool/consts.js +0 -3
  119. package/session_pool/errors.d.ts +0 -7
  120. package/session_pool/errors.js +0 -11
  121. package/session_pool/fingerprint.d.ts +0 -9
  122. package/session_pool/fingerprint.js +0 -30
  123. package/session_pool/index.d.ts +0 -4
  124. package/session_pool/index.js +0 -4
  125. package/session_pool/session.d.ts +0 -161
  126. package/session_pool/session.js +0 -218
  127. package/session_pool/session_pool.d.ts +0 -246
  128. package/session_pool/session_pool.js +0 -386
  129. package/storages/access_checking.d.ts +0 -12
  130. package/storages/access_checking.js +0 -17
  131. package/storages/sitemap_request_loader.d.ts +0 -249
  132. package/storages/sitemap_request_loader.js +0 -432
  133. /package/{crawlers/internals/types.js → events/system_info.js} +0 -0
@@ -1,28 +1,28 @@
1
1
  import type { ProxyInfo } from '@crawlee/types';
2
- import type { Request } from './request.js';
3
2
  export interface ProxyConfigurationFunction {
4
- (options?: {
5
- request?: Request;
6
- }): string | null | Promise<string | null>;
3
+ (): string | null | Promise<string | null>;
7
4
  }
8
- type UrlList = (string | null)[];
9
5
  export interface ProxyConfigurationOptions {
10
6
  /**
11
7
  * An array of custom proxy URLs to be rotated.
12
8
  * Custom proxies are not compatible with Apify Proxy and an attempt to use both
13
9
  * configuration options will cause an error to be thrown on initialize.
14
10
  */
15
- proxyUrls?: UrlList;
11
+ proxyUrls?: (string | null)[];
16
12
  /**
17
- * Custom function that allows you to generate the new proxy URL dynamically. It gets an optional parameter with the `Request` object when applicable.
13
+ * Custom function that allows you to generate the new proxy URL dynamically.
18
14
  * Can return either stringified proxy URL or `null` if the proxy should not be used. Can be asynchronous.
19
15
  *
20
16
  * This function is used to generate the URL when {@link ProxyConfiguration.newUrl} or {@link ProxyConfiguration.newProxyInfo} is called.
21
17
  */
22
18
  newUrlFunction?: ProxyConfigurationFunction;
23
- }
24
- interface NewUrlOptions {
25
- request?: Request;
19
+ /**
20
+ * When truthy, the constructor throws unless one of `proxyUrls` / `newUrlFunction` was given. Falsy by
21
+ * default, so a bare `ProxyConfiguration` can be constructed. Set by the Apify SDK, which builds the options
22
+ * object itself; declared here only so that it stays type-checkable.
23
+ * @internal
24
+ */
25
+ validateRequired?: boolean;
26
26
  }
27
27
  /**
28
28
  * Minimal contract that any object passed to a crawler as its `proxyConfiguration`
@@ -36,10 +36,14 @@ interface NewUrlOptions {
36
36
  */
37
37
  export interface IProxyConfiguration {
38
38
  /**
39
- * Creates a new {@link ProxyInfo} object describing the proxy to use for the given
40
- * request. Returns `undefined` when no proxy should be used.
39
+ * Creates a new {@link ProxyInfo} object describing the proxy to use.
40
+ * Returns `undefined` when no proxy should be used.
41
+ *
42
+ * @param proxyInfo A previously created `ProxyInfo`, e.g. one restored with a persisted session. Implementations
43
+ * should return an equivalent `ProxyInfo` that is usable in the current environment, or the argument itself when
44
+ * there is nothing to refresh.
41
45
  */
42
- newProxyInfo(options?: NewUrlOptions): Promise<ProxyInfo | undefined>;
46
+ newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
43
47
  }
44
48
  /**
45
49
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
@@ -70,10 +74,8 @@ export interface IProxyConfiguration {
70
74
  * @category Scaling
71
75
  */
72
76
  export declare class ProxyConfiguration implements IProxyConfiguration {
77
+ #private;
73
78
  readonly isManInTheMiddle = false;
74
- private nextCustomUrlIndex;
75
- private proxyUrls?;
76
- private newUrlFunction?;
77
79
  /**
78
80
  * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
79
81
  * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -102,22 +104,15 @@ export declare class ProxyConfiguration implements IProxyConfiguration {
102
104
  * Use it if you want to work with a rich representation of a proxy URL.
103
105
  * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
104
106
  *
107
+ * @param proxyInfo A previously created `ProxyInfo`, returned unchanged.
105
108
  * @return Represents information about used proxy and its configuration.
106
109
  */
107
- newProxyInfo(options?: NewUrlOptions): Promise<ProxyInfo | undefined>;
110
+ newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
108
111
  /**
109
112
  * Returns a new proxy URL based on provided configuration options.
110
113
  *
111
114
  * @return A string with a proxy URL, including authentication credentials and port number.
112
115
  * For example, `http://bob:password123@proxy.example.com:8000`
113
116
  */
114
- newUrl(options?: NewUrlOptions): Promise<string | undefined>;
115
- private handleProxyUrlsList;
116
- /**
117
- * Calls the custom newUrlFunction and checks format of its return value
118
- */
119
- private callNewUrlFunction;
120
- private throwCannotCombineCustomMethods;
121
- private throwNoOptionsProvided;
117
+ newUrl(): Promise<string | undefined>;
122
118
  }
123
- export {};
@@ -1,4 +1,12 @@
1
- import ow from 'ow';
1
+ import { z } from 'zod';
2
+ import { parseArgument, schemas } from './validators.js';
3
+ const proxyConfigurationOptionsSchema = z.strictObject({
4
+ proxyUrls: z
5
+ .array(z.union([z.url(), z.null()]))
6
+ .nonempty()
7
+ .optional(),
8
+ newUrlFunction: schemas.anyFunction.optional(),
9
+ });
2
10
  /**
3
11
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
4
12
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -29,9 +37,9 @@ import ow from 'ow';
29
37
  */
30
38
  export class ProxyConfiguration {
31
39
  isManInTheMiddle = false;
32
- nextCustomUrlIndex = 0;
33
- proxyUrls;
34
- newUrlFunction;
40
+ #nextCustomUrlIndex = 0;
41
+ #proxyUrls;
42
+ #newUrlFunction;
35
43
  /**
36
44
  * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
37
45
  * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -53,22 +61,21 @@ export class ProxyConfiguration {
53
61
  * ```
54
62
  */
55
63
  constructor(options = {}) {
64
+ // `validateRequired` is destructured off before the strict-object parse on purpose: the Apify SDK passes it
65
+ // through a computed key (`['validateRequired' as string]: false`), and leaving it in `rest` would make
66
+ // `Actor.createProxyConfiguration()` fail the `z.strictObject` check with a `ZodError`.
56
67
  const { validateRequired, ...rest } = options;
57
68
  if ('tieredProxyUrls' in rest) {
58
69
  throw new Error('The `tieredProxyUrls` option has been removed in Crawlee v4. ' +
59
70
  'See the v4 upgrading guide for the recommended migration to named sessions.');
60
71
  }
61
- ow(rest, ow.object.exactShape({
62
- proxyUrls: ow.optional.array.nonEmpty.ofType(ow.any(ow.string.url, ow.null)),
63
- newUrlFunction: ow.optional.function,
64
- }));
65
- const { proxyUrls, newUrlFunction } = options;
72
+ const { proxyUrls, newUrlFunction } = parseArgument(rest, proxyConfigurationOptionsSchema);
66
73
  if (proxyUrls && newUrlFunction)
67
- this.throwCannotCombineCustomMethods();
74
+ this.#throwCannotCombineCustomMethods();
68
75
  if (!proxyUrls && !newUrlFunction && validateRequired)
69
- this.throwNoOptionsProvided();
70
- this.proxyUrls = proxyUrls;
71
- this.newUrlFunction = newUrlFunction;
76
+ this.#throwNoOptionsProvided();
77
+ this.#proxyUrls = proxyUrls;
78
+ this.#newUrlFunction = newUrlFunction;
72
79
  }
73
80
  /**
74
81
  * This function creates a new {@link ProxyInfo} info object.
@@ -77,10 +84,13 @@ export class ProxyConfiguration {
77
84
  * Use it if you want to work with a rich representation of a proxy URL.
78
85
  * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
79
86
  *
87
+ * @param proxyInfo A previously created `ProxyInfo`, returned unchanged.
80
88
  * @return Represents information about used proxy and its configuration.
81
89
  */
82
- async newProxyInfo(options) {
83
- const url = await this.newUrl(options);
90
+ async newProxyInfo(proxyInfo) {
91
+ if (proxyInfo)
92
+ return proxyInfo;
93
+ const url = await this.newUrl();
84
94
  if (!url)
85
95
  return undefined;
86
96
  const { username, password, port, hostname } = new URL(url);
@@ -98,20 +108,20 @@ export class ProxyConfiguration {
98
108
  * @return A string with a proxy URL, including authentication credentials and port number.
99
109
  * For example, `http://bob:password123@proxy.example.com:8000`
100
110
  */
101
- async newUrl(options) {
102
- if (this.newUrlFunction) {
103
- return (await this.callNewUrlFunction({ request: options?.request })) ?? undefined;
111
+ async newUrl() {
112
+ if (this.#newUrlFunction) {
113
+ return (await this.#callNewUrlFunction()) ?? undefined;
104
114
  }
105
- return this.handleProxyUrlsList() ?? undefined;
115
+ return this.#handleProxyUrlsList() ?? undefined;
106
116
  }
107
- handleProxyUrlsList() {
108
- return this.proxyUrls[this.nextCustomUrlIndex++ % this.proxyUrls.length];
117
+ #handleProxyUrlsList() {
118
+ return this.#proxyUrls[this.#nextCustomUrlIndex++ % this.#proxyUrls.length];
109
119
  }
110
120
  /**
111
121
  * Calls the custom newUrlFunction and checks format of its return value
112
122
  */
113
- async callNewUrlFunction(options) {
114
- const proxyUrl = await this.newUrlFunction(options);
123
+ async #callNewUrlFunction() {
124
+ const proxyUrl = await this.#newUrlFunction();
115
125
  try {
116
126
  if (proxyUrl) {
117
127
  new URL(proxyUrl); // eslint-disable-line no-new
@@ -122,10 +132,10 @@ export class ProxyConfiguration {
122
132
  throw new Error(`The provided newUrlFunction did not return a valid URL.\nCause: ${err.message}`);
123
133
  }
124
134
  }
125
- throwCannotCombineCustomMethods() {
135
+ #throwCannotCombineCustomMethods() {
126
136
  throw new Error('Cannot combine custom proxies "options.proxyUrls" with custom generating function "options.newUrlFunction".');
127
137
  }
128
- throwNoOptionsProvided() {
138
+ #throwNoOptionsProvided() {
129
139
  throw new Error('One of "options.proxyUrls" or "options.newUrlFunction" needs to be provided.');
130
140
  }
131
141
  }
@@ -1,4 +1,32 @@
1
- import type { Configuration, CrawleeLogger } from '@crawlee/core';
1
+ import type { Configuration } from './configuration.js';
2
+ import type { CrawleeLogger } from './log.js';
3
+ import { KeyValueStore } from './storages/key_value_store.js';
4
+ import type { Awaitable } from '@crawlee/types';
5
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
6
+ /**
7
+ * One direction of the conversion between the state model and its persisted form - either a plain function, or a
8
+ * [Standard Schema](https://standardschema.dev) whose validated output is the result.
9
+ *
10
+ * A schema that fails to validate makes {@link RecoverableState} throw a {@link StateValidationError}. Zod
11
+ * codecs work directly, as their validation *is* the decode direction; use `(state) => codec.encode(state)` for the
12
+ * other one.
13
+ */
14
+ export type StateConversion<TFrom, TTo> = ((value: TFrom) => Awaitable<TTo>) | StandardSchemaV1<TFrom, TTo>;
15
+ /**
16
+ * A {@link StateConversion} for a caller that cannot await one - {@link Statistics}, whose `toJSON()` is
17
+ * synchronous, being the reason this exists.
18
+ *
19
+ * Only the function arm can be narrowed here: a Standard Schema is free to validate asynchronously, so a schema
20
+ * that does is rejected when it runs rather than when it is passed.
21
+ */
22
+ export type SyncStateConversion<TFrom, TTo> = ((value: TFrom) => TTo) | StandardSchemaV1<TFrom, TTo>;
23
+ /**
24
+ * Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
25
+ * the value.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare function convertStateSync<TFrom, TTo>(conversion: SyncStateConversion<TFrom, TTo>, value: TFrom, persistStateKey: string): TTo;
2
30
  export interface RecoverableStatePersistenceOptions {
3
31
  /**
4
32
  * The key under which the state is stored in the KeyValueStore
@@ -9,45 +37,66 @@ export interface RecoverableStatePersistenceOptions {
9
37
  */
10
38
  persistenceEnabled?: boolean;
11
39
  /**
12
- * The name of the KeyValueStore to use for persistence.
13
- * If neither a name nor an id are supplied, the default store will be used.
40
+ * The KeyValueStore to persist into, defaulting to the default store. Accepts a pending
41
+ * {@link KeyValueStore.open} so that callers do not have to be async to point at a specific store.
14
42
  */
15
- persistStateKvsName?: string;
43
+ keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
16
44
  /**
17
- * The identifier of the KeyValueStore to use for persistence.
18
- * If neither a name nor an id are supplied, the default store will be used.
45
+ * Time limit for a single load or save of the state, in milliseconds.
46
+ * @default 60_000
19
47
  */
20
- persistStateKvsId?: string;
48
+ persistenceTimeoutMillis?: number;
21
49
  }
22
50
  /**
23
- * Options for configuring the RecoverableState
51
+ * The fields of {@link RecoverableStateOptions}, without the constraint tying `contentType` to the conversions.
24
52
  */
25
- export interface RecoverableStateOptions<TStateModel = Record<string, unknown>> extends RecoverableStatePersistenceOptions {
53
+ export interface RecoverableStateBaseOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
26
54
  /**
27
- * The default state used if no persisted state is found.
28
- * A deep copy is made each time the state is used.
55
+ * The state used when no persisted state is found, and the state {@link RecoverableState.reset} restores.
56
+ *
57
+ * A plain value is deep-copied with `structuredClone` each time it is used, so pass a factory for a state
58
+ * that `structuredClone` cannot rebuild - one holding class instances, say, or one derived from a schema.
29
59
  */
30
- defaultState: TStateModel;
60
+ defaultState: TStateModel | (() => TStateModel);
31
61
  /**
32
62
  * A logger instance for logging operations related to state persistence
33
63
  */
34
64
  logger?: CrawleeLogger;
35
65
  /**
36
- * Configuration instance to use
66
+ * Configuration instance to use when opening the KeyValueStore
37
67
  */
38
68
  configuration?: Configuration;
39
69
  /**
40
- * Optional function to transform the state to a JSON string before persistence.
41
- * If not provided, JSON.stringify will be used.
70
+ * Optional conversion of the state to a plain JSON-serializable value before it is persisted.
71
+ * If not provided, the state is persisted as is.
72
+ *
73
+ * With {@link RecoverableStateBaseOptions.contentType} set, it has to produce what
74
+ * {@link KeyValueStore.setValue} accepts alongside an explicit content type - a `string`, a `Buffer` or a
75
+ * stream.
76
+ */
77
+ serialize?: StateConversion<TStateModel, TPersistedState>;
78
+ /**
79
+ * Optional conversion of a persisted value back to the state model, and the place to validate a record before
80
+ * trusting it. If not provided, the persisted value is used as is.
81
+ *
82
+ * With {@link RecoverableStateBaseOptions.contentType} set, it receives a `Readable` of the record bytes
83
+ * instead of a parsed value.
42
84
  */
43
- serialize?: (state: TStateModel) => string;
85
+ deserialize?: StateConversion<TPersistedState, TStateModel>;
44
86
  /**
45
- * Optional function to transform a JSON-serialized object back to the state model.
46
- * If not provided, JSON.parse is used.
47
- * It is advisable to perform validation in this function and to throw an exception if it fails.
87
+ * Content type of the persisted record. Setting it hands the record encoding over to
88
+ * {@link RecoverableStateBaseOptions.serialize} and {@link RecoverableStateBaseOptions.deserialize}, both of
89
+ * which are then required - the default JSON codec is bypassed in both directions. Meant for a state too large
90
+ * for `JSON.stringify`, which `serialize` can then stream out instead.
48
91
  */
49
- deserialize?: (serializedState: string) => TStateModel;
92
+ contentType?: string;
50
93
  }
94
+ /**
95
+ * Options for configuring the RecoverableState
96
+ */
97
+ export type RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> = RecoverableStateBaseOptions<TStateModel, TPersistedState> & ({
98
+ contentType?: undefined;
99
+ } | Required<Pick<RecoverableStateBaseOptions<TStateModel, TPersistedState>, 'serialize' | 'deserialize' | 'contentType'>>);
51
100
  /**
52
101
  * A class for managing persistent recoverable state using a plain JavaScript object.
53
102
  *
@@ -58,28 +107,24 @@ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>>
58
107
  * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
59
108
  * The class automatically hooks into the event system to persist state when needed.
60
109
  */
61
- export declare class RecoverableState<TStateModel = Record<string, unknown>> {
62
- private readonly defaultState;
63
- private state;
64
- private readonly persistenceEnabled;
65
- private readonly persistStateKey;
66
- private readonly persistStateKvsName?;
67
- private readonly persistStateKvsId?;
68
- private keyValueStore;
69
- private readonly log;
70
- private readonly serialize;
71
- private readonly deserialize;
110
+ export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
111
+ #private;
72
112
  /**
73
113
  * Initialize a new recoverable state object.
74
114
  *
75
115
  * @param options Configuration options for the recoverable state
76
116
  */
77
- constructor(options: RecoverableStateOptions<TStateModel>);
117
+ constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
78
118
  /**
79
119
  * Initialize the recoverable state.
80
120
  *
81
- * This method must be called before using the recoverable state. It loads the saved state
82
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
121
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
122
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
123
+ * is no record to restore.
124
+ *
125
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
126
+ * listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
127
+ * reloading it would only drop whatever the deserialization leaves out.
83
128
  *
84
129
  * @returns The loaded state object
85
130
  */
@@ -88,33 +133,45 @@ export declare class RecoverableState<TStateModel = Record<string, unknown>> {
88
133
  * Clean up resources used by the recoverable state.
89
134
  *
90
135
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
91
- * and persists the current state one last time.
136
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
137
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
138
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
139
+ * persistence window.
92
140
  */
93
141
  teardown(): Promise<void>;
94
142
  /**
95
143
  * Get the current state.
144
+ *
145
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
146
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
147
+ * constructor gets a usable state right away.
96
148
  */
97
149
  get currentValue(): TStateModel;
98
150
  /**
99
- * Reset the state to the default values and clear any persisted state.
151
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
100
152
  *
101
- * Resets the current state to the default state and, if persistence is enabled,
102
- * clears the persisted state from the KeyValueStore.
153
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
103
154
  */
104
- reset(): Promise<void>;
155
+ reset(): void;
156
+ /**
157
+ * Clear the persisted state record, leaving the in-memory state alone.
158
+ *
159
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
160
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
161
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
162
+ * or {@link RecoverableState.teardown} before clearing the record.
163
+ *
164
+ * A no-op if persistence is disabled.
165
+ */
166
+ resetStore(): Promise<void>;
105
167
  /**
106
168
  * Persist the current state to the KeyValueStore.
107
169
  *
108
170
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
109
- * directly when needed.
171
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
172
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
110
173
  *
111
174
  * @param eventData Optional data associated with a PERSIST_STATE event
112
175
  */
113
- persistState(eventData?: {
114
- isMigrating: boolean;
115
- }): Promise<void>;
116
- /**
117
- * Load the saved state from the KeyValueStore
118
- */
119
- private loadSavedState;
176
+ persistState(eventData?: Record<string, unknown>): Promise<void>;
120
177
  }