@apify/utilities 2.35.10 → 3.0.0-beta.0

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 (52) hide show
  1. package/code_hash_manager.d.ts +34 -0
  2. package/code_hash_manager.js +66 -0
  3. package/code_hash_manager.js.map +1 -0
  4. package/crypto.d.ts +35 -0
  5. package/crypto.js +58 -0
  6. package/crypto.js.map +1 -0
  7. package/exponential_backoff.d.ts +9 -0
  8. package/exponential_backoff.js +47 -0
  9. package/exponential_backoff.js.map +1 -0
  10. package/health_checker.d.ts +61 -0
  11. package/health_checker.js +132 -0
  12. package/health_checker.js.map +1 -0
  13. package/hmac.d.ts +20 -0
  14. package/hmac.js +59 -0
  15. package/hmac.js.map +1 -0
  16. package/index.d.ts +14 -0
  17. package/index.js +15 -0
  18. package/index.js.map +1 -0
  19. package/package.json +16 -21
  20. package/parse_boolean.d.ts +10 -0
  21. package/parse_boolean.js +25 -0
  22. package/parse_boolean.js.map +1 -0
  23. package/parse_jsonl_stream.d.ts +25 -0
  24. package/parse_jsonl_stream.js +79 -0
  25. package/parse_jsonl_stream.js.map +1 -0
  26. package/storages.d.ts +29 -0
  27. package/storages.js +37 -0
  28. package/storages.js.map +1 -0
  29. package/streams_utilities.d.ts +10 -0
  30. package/streams_utilities.js +26 -0
  31. package/streams_utilities.js.map +1 -0
  32. package/url_params_utils.d.ts +7 -0
  33. package/url_params_utils.js +11 -0
  34. package/url_params_utils.js.map +1 -0
  35. package/usernames.d.ts +10 -0
  36. package/usernames.js +1137 -0
  37. package/usernames.js.map +1 -0
  38. package/utilities.client.d.ts +125 -0
  39. package/utilities.client.js +408 -0
  40. package/utilities.client.js.map +1 -0
  41. package/utilities.d.ts +111 -0
  42. package/utilities.js +263 -0
  43. package/utilities.js.map +1 -0
  44. package/webhook_payload_template.d.ts +114 -0
  45. package/webhook_payload_template.js +245 -0
  46. package/webhook_payload_template.js.map +1 -0
  47. package/cjs/index.cjs +0 -2402
  48. package/cjs/index.cjs.map +0 -1
  49. package/cjs/index.d.ts +0 -609
  50. package/esm/index.d.mts +0 -609
  51. package/esm/index.mjs +0 -2314
  52. package/esm/index.mjs.map +0 -1
package/esm/index.d.mts DELETED
@@ -1,609 +0,0 @@
1
- import { Log } from '@apify/log';
2
- import { Transform, TransformCallback, Readable, PassThrough } from 'node:stream';
3
- import { KeyObject } from 'node:crypto';
4
-
5
- /*!
6
- * This module contains various server utility and helper functions.
7
- * Note that it automatically exports functions from utilities.client.js
8
- *
9
- * Author: Jan Curn (jan@apify.com)
10
- * Copyright(c) 2015 Apify. All rights reserved.
11
- *
12
- */
13
-
14
- /**
15
- * Generates a random cryptographically strong string consisting of 17 alphanumeric characters.
16
- * This string is similar to MongoDB ObjectIds generated by Meteor.
17
- */
18
- declare function cryptoRandomObjectId(length?: number): string;
19
- /**
20
- * Generates unique, deterministic record ID from the provided key with given length (defaults to 17).
21
- */
22
- declare function deterministicUniqueId(key: string, length?: number): string;
23
- /**
24
- * Returns a random integer between 0 and max (excluded, unless it is also 0).
25
- * @param maxExcluded - exclusive upper bound; the returned value is always lower than this
26
- */
27
- declare function getRandomInt(maxExcluded: number): number;
28
- /**
29
- * If 'date' is a String, this function converts and returns it as a Date object.
30
- * Otherwise, the function returns the original 'date' argument.
31
- * This function is useful to convert dates transfered via JSON which doesn't natively support dates.
32
- */
33
- declare function parseDateFromJson(date: string | Date): Date;
34
- /**
35
- * Returns a Promise object that will wait a specific number of milliseconds.
36
- * @param millis - time to wait in milliseconds; if not larger than zero, the promise resolves immediately
37
- */
38
- declare function delayPromise(millis: number): Promise<void>;
39
- /**
40
- * Removes an element from an array.
41
- */
42
- declare function removeFromArray<T>(array: T[], element: T): boolean;
43
- interface RequestLike {
44
- url: string;
45
- }
46
- interface ResponseLike {
47
- status: (code: number) => void;
48
- send: (payload: string) => void;
49
- headersSent?: boolean;
50
- }
51
- /**
52
- * A default route for HTTP 404 error page for API endpoints.
53
- */
54
- declare function http404Route(req: RequestLike, res: ResponseLike): void;
55
- /**
56
- * Default error handler of Express API endpoints.
57
- */
58
- declare function expressErrorHandler(err: Error, req: RequestLike, res: ResponseLike, next: (...a: unknown[]) => unknown): void;
59
- type BetterIntervalID = {
60
- _betterClearInterval: () => void;
61
- };
62
- /**
63
- * Similar to setInterval() but with two important differences:
64
- * First, it assumes the function is asynchronous and only schedules its next invocation AFTER the asynchronous function finished.
65
- * Second, it invokes the function immediately.
66
- * @param func Function to be periodically executed.
67
- * For backwards compatibility reasons, it is passed a callback as its first argument during invocation, however that callback has no effect.
68
- * @param delay The number of milliseconds to wait to next invocation of the function after the current invocation finishes.
69
- * @returns Object that can be passed to betterClearInterval()
70
- */
71
- declare function betterSetInterval(func: ((a: (...args: unknown[]) => unknown) => void) | ((...args: unknown[]) => unknown), delay: number): BetterIntervalID;
72
- declare function betterClearInterval(intervalID: BetterIntervalID): void;
73
- /**
74
- * Escapes a string so that it can be used in regular expression (e.g. converts "myfile.*" to "myfile\\.\\*").
75
- */
76
- declare function escapeRegExp(str: string): string;
77
- /**
78
- * String left pad
79
- */
80
- declare function leftpad(str: string, len: number, ch?: string | number): string;
81
- /**
82
- * Computes weighted average of 2 values.
83
- */
84
- declare function weightedAverage(val1: number, weight1: number, val2: number, weight2: number): number;
85
- /**
86
- * Executes array of promises in sequence and then returns array where Nth item is result of Nth promise.
87
- */
88
- declare function sequentializePromises<T>(promises: (Promise<T> | (() => Promise<T>))[]): Promise<T[]>;
89
- /**
90
- * Helper function for validation if parameter is an instance of given prototype or multiple prototypes.
91
- */
92
- declare function checkParamPrototypeOrThrow(paramVal: any, paramName: string, prototypes: any, prototypeName: string, isOptional?: boolean): void;
93
- interface Server {
94
- removeListener(event: string, cb: (...params: any[]) => any): unknown;
95
- on(event: string, cb: (...params: any[]) => any): unknown;
96
- listen(port: number): unknown;
97
- }
98
- /**
99
- * Starts listening at a port specified in the constructor.
100
- * Unfortunately server.listen() is not a normal function that fails on error, so we need this trickery.
101
- * Returns a function that calls `server.listen(port)` and resolves once server starts listening.
102
- *
103
- * Usage: `promisifyServerListen(server)(1234)`;
104
- */
105
- declare function promisifyServerListen<T extends Server>(server: T): (port: number) => Promise<void>;
106
- declare function configureLogger(givenLog: Log, isProduction?: boolean): void;
107
- /**
108
- * Wraps given promise with timeout.
109
- */
110
- declare function timeoutPromise<T>(promise: Promise<T>, timeoutMillis: number, errorMessage?: string): Promise<unknown>;
111
- /**
112
- * Removes the leading ^ and trailing $ from regex
113
- */
114
- declare function createInjectableRegExp(regex: RegExp): RegExp;
115
-
116
- /*!
117
- * This module contains various client-side utility and helper functions.
118
- *
119
- * Author: Jan Curn (jan@apify.com)
120
- * Copyright(c) 2016 Apify. All rights reserved.
121
- *
122
- */
123
- /**
124
- * Returns true if object equals null or undefined, otherwise returns false.
125
- */
126
- declare function isNullOrUndefined(obj: unknown): boolean;
127
- declare function isBuffer(obj: any): boolean;
128
- /**
129
- * Converts Date object to ISO string.
130
- */
131
- declare function dateToString(date: Date, middleT: boolean): string;
132
- /**
133
- * Ensures a string is shorter than a specified number of character, and truncates it if not,
134
- * appending a specific suffix to it.
135
- * @param str
136
- * @param maxLength
137
- * @param [suffix] Suffix to be appended to truncated string. Defaults to "...[truncated]".
138
- */
139
- declare function truncate(str: string, maxLength: number, suffix?: string): string;
140
- /**
141
- * Gets ordinal suffix for a number (e.g. "nd" for 2).
142
- */
143
- declare function getOrdinalSuffix(num: number): string;
144
- interface Uri {
145
- protocol?: string;
146
- host?: string;
147
- path?: string;
148
- query?: string;
149
- fragment?: string;
150
- fragmentKey?: Record<string, unknown>;
151
- }
152
- /**
153
- * @deprecated use `new URL()` instead
154
- */
155
- declare function parseUrl(str: string): Uri;
156
- declare function normalizeUrl(url: string, keepFragment?: boolean): string | null;
157
- declare function markedSetNofollowLinks(href: string, title: string, text: string, referrerHostname?: string): string;
158
- declare function markedDecreaseHeadsLevel(text: string, level: number): string;
159
- /**
160
- * Converts integer version number previously generated by buildNumberToInt() or versionNumberToInt()
161
- * to string in a form 'MAJOR.MINOR' or 'MAJOR.MINOR.BUILD' in case build number is non-zero.
162
- */
163
- declare function buildOrVersionNumberIntToStr(int: number): string | null;
164
- /**
165
- * If a property name is invalid for MongoDB or BSON, the function transforms
166
- * it to a valid form, which can be (most of the time) reversed back using unescapePropertyName().
167
- * For a detailed list of transformations, see escapeForBson().
168
- * @private
169
- */
170
- declare function escapePropertyName(name: string): string;
171
- /**
172
- * Reverses a string transformed using escapePropertyName() back to its original form.
173
- * Note that the reverse transformation might not be 100% correct for certain unlikely-to-occur strings
174
- * (e.g. string contain null chars).
175
- * @private
176
- */
177
- declare function unescapePropertyName(name: string): string;
178
- /**
179
- * Traverses an object, creates a deep clone if requested and transforms object keys and values using a provided function.
180
- * The `traverseObject` is recursive, hence if the input object has circular references, the function will run into
181
- * and infinite recursion and crash the Node.js process.
182
- * @param obj Object to traverse, it must not contain circular references!
183
- * @param clone If true, object is not modified but cloned.
184
- * @param transformFunc Function used to transform the property names na value.
185
- * It has the following signature: `(key, value) => [key, value]`.
186
- * Beware that the transformed value is only set if it !== old value.
187
- * @returns {*}
188
- * @private
189
- */
190
- declare function traverseObject(obj: Record<string, any>, clone: boolean, transformFunc: (key: string, value: unknown) => [string, unknown]): any[] | Record<string, any>;
191
- /**
192
- * Transforms an object so that it can be stored to MongoDB or serialized to BSON.
193
- * It does so by transforming prohibited property names (e.g. names starting with "$",
194
- * containing "." or null char, equal to "toBSON" or "_bsontype") to equivalent full-width Unicode chars
195
- * which are normally allowed. To revert this transformation, use unescapeFromBson().
196
- * @param obj Object to be transformed. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
197
- * @param clone If true, the function transforms a deep clone of the object rather than the original object.
198
- * @returns {*} Transformed object
199
- */
200
- declare function escapeForBson(obj: Record<string, any>, clone?: boolean): any[] | Record<string, any>;
201
- /**
202
- * Reverts a transformation of object property names performed by escapeForBson().
203
- * Note that the reverse transformation might not be 100% equal to the original object
204
- * for certain unlikely-to-occur property name (e.g. one contain null chars or full-width Unicode chars).
205
- * @param obj Object to be transformed. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
206
- * @param clone If true, the function transforms a deep clone of the object rather than the original object.
207
- * @returns {*} Transformed object.
208
- */
209
- declare function unescapeFromBson(obj: Record<string, any>, clone?: boolean): Record<string, any>;
210
- /**
211
- * Determines whether an object contains property names that cannot be stored to MongoDB.
212
- * See escapeForBson() for more details.
213
- * Note that this function only works with objects that are serializable to JSON!
214
- * @param obj Object to be checked. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
215
- * @returns {boolean} Returns true if object is invalid, otherwise it returns false.
216
- */
217
- declare function isBadForMongo(obj: Record<string, any>): boolean;
218
- declare class JsonVariable {
219
- readonly name: string;
220
- constructor(name: string);
221
- getToken(): string;
222
- }
223
- /**
224
- * Stringifies provided value to JSON with a difference that supports functions that
225
- * are stringified using .toString() method.
226
- *
227
- * In addition to that supports instances of JsonVariable('my.token') that are replaced
228
- * with a {{my.token}}.
229
- */
230
- declare function jsonStringifyExtended(value: Record<string, any>, replacer?: ((k: string, val: unknown) => unknown) | null, space?: number): string;
231
- /**
232
- * Splits a full name into the first name and last name, trimming all internal and external spaces.
233
- * Returns an array with two elements or null if splitting is not possible.
234
- */
235
- declare function splitFullName(fullName: string): (string | null)[];
236
- /**
237
- * Perform a Regex test on a given URL to see if it is relative.
238
- */
239
- declare function isUrlRelative(url: string): boolean;
240
-
241
- /**
242
- * Checks whether username is listed in the forbidden username list
243
- * or looks like an Apify ID.
244
- *
245
- * NOTE: The forbidden list may expand over time, so a username that was
246
- * previously permitted may later become forbidden. Use this function only
247
- * when validating a username change, not as part of normal authentication
248
- * or authorization flow.
249
- */
250
- declare function isForbiddenUsername(username: string): boolean;
251
-
252
- declare class RetryableError extends Error {
253
- readonly error: Error;
254
- constructor(error: Error, ...args: unknown[]);
255
- }
256
- declare function retryWithExpBackoff<T>(params: {
257
- func: (...args: unknown[]) => T | Promise<T>;
258
- expBackoffMillis: number;
259
- expBackoffMaxRepeats: number;
260
- }): Promise<T>;
261
-
262
- declare enum CHECK_TYPES {
263
- MONGODB_PING = "MONGODB_PING",
264
- MONGODB_READ = "MONGODB_READ",
265
- MONGODB_WRITE = "MONGODB_WRITE",
266
- REDIS = "REDIS",// Old alias for 'REDIS_WRITE', deprecated
267
- REDIS_PING = "REDIS_PING",
268
- REDIS_WRITE = "REDIS_WRITE"
269
- }
270
- type CheckType<T extends Record<string, any> = Record<string, any>> = {
271
- client: T;
272
- type: CHECK_TYPES;
273
- };
274
- interface HealthCheckerOptions {
275
- checks: CheckType[];
276
- redisPrefix?: string;
277
- redisTtlSecs?: number;
278
- checkTimeoutMillis?: number;
279
- mongoDbWriteTestCollection?: string;
280
- mongoDbWriteTestRemoveOlderThanSecs?: number;
281
- }
282
- /**
283
- * Provides health-checking functionality to ensure that connection to Redis and MongoDB is working.
284
- *
285
- * Example use:
286
- *
287
- * ```javascript
288
- * const redis = new Redis();
289
- * const mongo = await MongoClient.connect('mongodb://127.0.0.1:3001/my-db');
290
- *
291
- * const checks = [{
292
- * client: redis,
293
- * type: HealthChecker.CHECK_TYPES.REDIS,
294
- * }, {
295
- * client: mongo.db('my-db'),
296
- * type: HealthChecker.CHECK_TYPES.MONGODB_READ,
297
- * }];
298
- *
299
- * const checker = new HealthChecker({ checks });
300
- * setInterval(() => checker.ensureIsHealthy().then(() => console.log('ok'), err => console.log(err)), 5000);
301
- * ```
302
- */
303
- declare class HealthChecker {
304
- private readonly options;
305
- static readonly CHECK_TYPES: typeof CHECK_TYPES;
306
- checks: CheckType[];
307
- redisPrefix: string;
308
- redisTtlSecs: number;
309
- checkTimeoutMillis: number;
310
- mongoDbWriteTestCollection: string;
311
- mongoDbWriteTestRemoveOlderThanSecs: number;
312
- constructor(options: HealthCheckerOptions);
313
- ensureIsHealthy(): Promise<void>;
314
- _validateCheck(check: CheckType): void;
315
- _performCheck(check: CheckType): Promise<void>;
316
- _testMongoDbPing({ client }: CheckType): Promise<void>;
317
- _testMongoDbRead({ client }: CheckType): Promise<void>;
318
- _testMongoDbWrite({ client }: CheckType): Promise<void>;
319
- _testRedisPing({ client }: CheckType): Promise<void>;
320
- _testRedisWrite({ client }: CheckType): Promise<void>;
321
- }
322
-
323
- /**
324
- * A transforming stream which accepts string/Buffer data with JSON Lines objects on input
325
- * and emits 'object' event for every parsed JavaScript objects.
326
- * The stream passes through the original data.
327
- * Each JSON object is expected to be on a separate line, some lines might be empty or contain whitespace.
328
- * After each JSON object there needs to be '\n' or end of stream.
329
- * This stream is especially useful for processing stream from Docker engine, such as:
330
- *
331
- * <pre>
332
- * {"status":"Preparing","progressDetail":{},"id":"e0380bb6c0bb"}
333
- * {"status":"Preparing","progressDetail":{},"id":"9f8566ee5135"}
334
- * {"errorDetail":{"message":"no basic auth credentials"},"error":"no basic auth credentials"}
335
- * </pre>
336
- *
337
- * **WARNING**: You still need to consume the `data` event from the transformed stream,
338
- * otherwise the internal buffers will get full and the stream might be corked.
339
- */
340
- declare class ParseJsonlStream extends Transform {
341
- private pendingChunk;
342
- parseLineAndEmitObject(line: string): void;
343
- _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void;
344
- _flush(callback: TransformCallback): void;
345
- }
346
-
347
- /**
348
- * Concat data from stream to Buffer
349
- */
350
- declare function concatStreamToBuffer(stream: Readable | PassThrough): Promise<Buffer>;
351
- /**
352
- * Flushes the provided stream into a Buffer and transforms
353
- * it to a String using the provided encoding or utf-8 as default.
354
- */
355
- declare function readStreamToString(stream: Readable | PassThrough, encoding?: BufferEncoding): Promise<string>;
356
-
357
- declare class WebhookPayloadTemplateError extends Error {
358
- constructor(message?: string);
359
- }
360
- declare class InvalidJsonError extends WebhookPayloadTemplateError {
361
- constructor(originalError: Error);
362
- }
363
- declare class InvalidVariableError extends Error {
364
- constructor(variable?: string);
365
- }
366
- /**
367
- * WebhookPayloadTemplate enables creation and parsing of webhook payload template strings.
368
- * Template strings are JSON that may include template variables enclosed in double
369
- * curly brackets: `{{variable}}`. When the template is parsed, variables are replaced
370
- * with values from a provided context.
371
- *
372
- * This is useful to create dynamic webhook payloads where a template is saved on webhook
373
- * creation and then variables are dynamically added on webhook dispatch.
374
- *
375
- * **Example:**
376
- * ```js
377
- * const payloadTemplate = `{
378
- * "id": "some-id",
379
- * "createdAt": "2019-05-08T15:22:21.095Z",
380
- * "dataToSend": {{data}}
381
- * }`
382
- *
383
- * const data = {
384
- * status: 200,
385
- * body: 'hello world'
386
- * }
387
- *
388
- * const payloadObject = WebhookPayloadTemplate.parse(payloadTemplate, null, { data })
389
- * ```
390
- *
391
- * **Produces:**
392
- * ```js
393
- * {
394
- * id: "some-id",
395
- * createdAt: '2019-05-08T15:22:21.095Z',
396
- * dataToSend: {
397
- * status: 200,
398
- * body: 'hello world'
399
- * }
400
- * }
401
- * ```
402
- * @hideconstructor
403
- */
404
- declare class WebhookPayloadTemplate {
405
- private readonly template;
406
- private readonly allowedVariables;
407
- private readonly context;
408
- private payload;
409
- readonly replacedVariables: {
410
- variableName: string;
411
- replacement: string;
412
- }[];
413
- constructor(template: string, allowedVariables?: Set<string> | null, context?: Record<string, any>);
414
- /**
415
- * Parse existing webhook payload template string into an object, replacing
416
- * template variables using the provided context.
417
- *
418
- * Parse also validates the template structure, so it can be used
419
- * to check validity of the template JSON and usage of allowedVariables.
420
- */
421
- static parse(payloadTemplate: string, allowedVariables?: Set<string> | null, context?: Record<string, any>, options?: {
422
- interpolateStrings?: boolean;
423
- }): Record<string, any>;
424
- /**
425
- * Stringify an object into a webhook payload template.
426
- * Values created using `getTemplateVariable('foo.bar')`
427
- * will be stringified to `{{foo.bar}}` template variable.
428
- */
429
- static stringify(objectTemplate: Record<string, any>, replacer?: ((_: any) => string) | null, indent?: number): string;
430
- /**
431
- * Produces an instance of a template variable that can be used
432
- * in objects and will be stringified into `{{variableName}}` syntax.
433
- *
434
- * **Example:**
435
- * ```js
436
- * const resourceVariable = WebhookPayloadTemplate.getVariable('resource');
437
- * const objectTemplate = {
438
- * foo: 'foo',
439
- * bar: ['bar'],
440
- * res: resourceVariable,
441
- * }
442
- *
443
- * const payloadTemplate = WebhookPayloadTemplate.stringify(objectTemplate);
444
- * ```
445
- *
446
- * **Produces:**
447
- * ```json
448
- * {
449
- * "foo": "foo",
450
- * "bar": ["bar"],
451
- * "res": {{resource}},
452
- * }
453
- * ```
454
- */
455
- static getVariable(variableName: string): JsonVariable;
456
- private _parse;
457
- private _interpolate;
458
- private _interpolateString;
459
- private _interpolateObject;
460
- private _interpolateArray;
461
- private _findPositionOfNextVariable;
462
- private _isVariableInsideString;
463
- private _countUnescapedDoubleQuotesUpToIndex;
464
- private _replaceVariable;
465
- private _validateVariableName;
466
- private _getVariableValue;
467
- private _getVariableReplacement;
468
- }
469
-
470
- type DecryptOptions = {
471
- privateKey: KeyObject;
472
- encryptedPassword: string;
473
- encryptedValue: string;
474
- };
475
- type EncryptOptions = {
476
- publicKey: KeyObject;
477
- value: string;
478
- };
479
- /**
480
- * It encrypts the given value using AES cipher and the password for encryption using the public key.
481
- * NOTE: The encryption password is a string of encryption key and initial vector used for cipher.
482
- * It returns the encrypted password and encrypted value in BASE64 format.
483
- *
484
- * @param publicKey {KeyObject} Public key used for encryption
485
- * @param value {string} Value to be encrypted
486
- * @returns {Object<encryptedPassword, encryptedValue>}
487
- */
488
- declare function publicEncrypt({ publicKey, value }: EncryptOptions): {
489
- encryptedPassword: string;
490
- encryptedValue: string;
491
- };
492
- /**
493
- * It decrypts encrypted password using private key
494
- * and uses the password(consists of encrypted key and initial vector)
495
- * to decrypt the encrypted value.
496
- *
497
- * @param privateKey {KeyObject} Private key used for decryption
498
- * @param encryptedPassword {string} Password in Base64 encrypted using private key
499
- * @param encryptedValue {string} Content in Base64 encrypted using AES cipher
500
- * @returns {string}
501
- */
502
- declare function privateDecrypt({ privateKey, encryptedPassword, encryptedValue }: DecryptOptions): string;
503
-
504
- /**
505
- * Extract import statements from the code.
506
- */
507
- declare function separateImports(code: string): {
508
- code: string;
509
- imports: string;
510
- };
511
-
512
- declare enum CodeHashMetaKey {
513
- VERSION = "v",
514
- USER = "u"
515
- }
516
- /**
517
- * Allows hashing of an Actor input together with some metadata into a shareable link for the "Run on Apify" button.
518
- * Uses a common secret for checking the signatures.
519
- *
520
- * The hash consists of 3 parts separated by a dot, as in `ABC.DEF.GHI`, each being a base64url encoded string:
521
- * - `meta` object with the `version` and `user` properties.
522
- * - `data` data object (the one that gets encoded)
523
- * - `signature` used for verification of the URL hash, computed from the `meta` and `data` objects
524
- */
525
- declare class CodeHashManager {
526
- private readonly secret;
527
- static readonly SECTION_SEPARATOR = ".";
528
- static readonly VERSION = 1;
529
- constructor(secret: string);
530
- /**
531
- * Encodes object (e.g. input for actor) to a string hash and uses the `secret` to sign the hash.
532
- */
533
- encode<T extends object>(data: T, userId: string): string;
534
- decode(urlHash: string): {
535
- data: any;
536
- meta: {
537
- userId: any;
538
- version: any;
539
- isSignatureValid: boolean;
540
- };
541
- };
542
- private toBase64;
543
- private fromBase64;
544
- private generateSignature;
545
- }
546
-
547
- /**
548
- * Generates an HMAC signature and encodes it using Base62.
549
- * Base62 encoding reduces the signature length.
550
- *
551
- * @param secretKey {string} Secret key used for signing signatures
552
- * @param message {string} Message to be signed
553
- * @returns string
554
- * @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and
555
- * is available in both Node.js and browsers without the need for polyfills.
556
- */
557
- declare function createHmacSignature(secretKey: string, message: string): string;
558
- /**
559
- * Generates an HMAC signature and encodes it using Base62.
560
- * Base62 encoding reduces the signature length.
561
- *
562
- * @param secretKey {string} Secret key used for signing signatures
563
- * @param message {string} Message to be signed
564
- * @returns Promise<string>
565
- */
566
- declare function createHmacSignatureAsync(secretKey: string, message: string): Promise<string>;
567
-
568
- /**
569
- * Creates a secure signature for a resource like a dataset or key-value store.
570
- * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
571
- * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
572
- *
573
- * Note: expiresInMillis is optional. If not provided, the signature will not expire.
574
- *
575
- * @deprecated Use {@link createStorageContentSignatureAsync} instead, which uses Web Crypto API and
576
- * is available in both Node.js and browsers without the need for polyfills.
577
- */
578
- declare function createStorageContentSignature({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
579
- resourceId: string;
580
- urlSigningSecretKey: string;
581
- expiresInMillis?: number;
582
- version?: number;
583
- }): string;
584
- /**
585
- * Creates a secure signature for a resource like a dataset or key-value store.
586
- * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
587
- * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
588
- *
589
- * Note: expiresInMillis is optional. If not provided, the signature will not expire.
590
- */
591
- declare function createStorageContentSignatureAsync({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
592
- resourceId: string;
593
- urlSigningSecretKey: string;
594
- expiresInMillis?: number;
595
- version?: number;
596
- }): Promise<string>;
597
-
598
- /**
599
- * Strictly parses a value to a boolean, returning `null` if the value is invalid.
600
- * - Returns `true` for: `true`, `1`, `'1'`, `'true'` (case-insensitive).
601
- * - Returns `false` for: `false`, `0`, `'0'`, `'false'` (case-insensitive).
602
- * - Returns `null` for any other value.
603
- *
604
- * @param value - The value to parse (unknown type).
605
- * @returns {boolean | null} The parsed boolean or null if the input is invalid.
606
- */
607
- declare const parseBooleanOrNull: (value: unknown) => boolean | null;
608
-
609
- export { type BetterIntervalID, CHECK_TYPES, CodeHashManager, CodeHashMetaKey, HealthChecker, InvalidJsonError, InvalidVariableError, JsonVariable, ParseJsonlStream, RetryableError, WebhookPayloadTemplate, betterClearInterval, betterSetInterval, buildOrVersionNumberIntToStr, checkParamPrototypeOrThrow, concatStreamToBuffer, configureLogger, createHmacSignature, createHmacSignatureAsync, createInjectableRegExp, createStorageContentSignature, createStorageContentSignatureAsync, cryptoRandomObjectId, dateToString, delayPromise, deterministicUniqueId, escapeForBson, escapePropertyName, escapeRegExp, expressErrorHandler, getOrdinalSuffix, getRandomInt, http404Route, isBadForMongo, isBuffer, isForbiddenUsername, isNullOrUndefined, isUrlRelative, jsonStringifyExtended, leftpad, markedDecreaseHeadsLevel, markedSetNofollowLinks, normalizeUrl, parseBooleanOrNull, parseDateFromJson, parseUrl, privateDecrypt, promisifyServerListen, publicEncrypt, readStreamToString, removeFromArray, retryWithExpBackoff, separateImports, sequentializePromises, splitFullName, timeoutPromise, traverseObject, truncate, unescapeFromBson, unescapePropertyName, weightedAverage };