@apify/actor-memory-expression 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 0.1.0 (2025-11-25)
7
+
8
+
9
+ ### Features
10
+
11
+ * add function to calculate dynamic default Actor memory ([#570](https://github.com/apify/apify-shared-js/issues/570)) ([f3a97bf](https://github.com/apify/apify-shared-js/commit/f3a97bf86b14cc548c958a21a75720e4e4724b65))
package/dist/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018 Apify Technologies s.r.o.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # Apify shared library
2
+
3
+ [![Build Status](https://github.com/apify/apify-shared-js/actions/workflows/test_and_release.yaml/badge.svg?branch=master)](https://github.com/apify/apify-shared-js/actions/workflows/test_and_release.yaml)
4
+
5
+ package | version
6
+ --------|--------
7
+ `@apify/consts` | [![NPM version](https://img.shields.io/npm/v/@apify/consts.svg)](https://www.npmjs.com/package/@apify/consts)
8
+ `@apify/datastructures` | [![NPM version](https://img.shields.io/npm/v/@apify/datastructures.svg)](https://www.npmjs.com/package/@apify/datastructures)
9
+ `@apify/git` | [![NPM version](https://img.shields.io/npm/v/@apify/git.svg)](https://www.npmjs.com/package/@apify/git)
10
+ `@apify/hubspot_client` | [![NPM version](https://img.shields.io/npm/v/@apify/hubspot_client.svg)](https://www.npmjs.com/package/@apify/hubspot_client)
11
+ `@apify/input_schema` | [![NPM version](https://img.shields.io/npm/v/@apify/input_schema.svg)](https://www.npmjs.com/package/@apify/input_schema)
12
+ `@apify/input_secrets` | [![NPM version](https://img.shields.io/npm/v/@apify/input_secrets.svg)](https://www.npmjs.com/package/@apify/input_secrets)
13
+ `@apify/image_proxy_client` | [![NPM version](https://img.shields.io/npm/v/@apify/image_proxy_client.svg)](https://www.npmjs.com/package/@apify/image_proxy_client)
14
+ `@apify/json_schemas` | [![NPM version](https://img.shields.io/npm/v/@apify/json_schemas.svg)](https://www.npmjs.com/package/@apify/json_schemas)
15
+ `@apify/log` | [![NPM version](https://img.shields.io/npm/v/@apify/log.svg)](https://www.npmjs.com/package/@apify/log)
16
+ `@apify/markdown` | [![NPM version](https://img.shields.io/npm/v/@apify/markdown.svg)](https://www.npmjs.com/package/@apify/markdown)
17
+ `@apify/payment_qr_codes` | [![NPM version](https://img.shields.io/npm/v/@apify/payment_qr_codes.svg)](https://www.npmjs.com/package/@apify/payment_qr_codes)
18
+ `@apify/pseudo_url` | [![NPM version](https://img.shields.io/npm/v/@apify/pseudo_url.svg)](https://www.npmjs.com/package/@apify/pseudo_url)
19
+ `@apify/utilities` | [![NPM version](https://img.shields.io/npm/v/@apify/utilities.svg)](https://www.npmjs.com/package/@apify/utilities)
20
+ `@apify/timeout` | [![NPM version](https://img.shields.io/npm/v/@apify/timeout.svg)](https://www.npmjs.com/package/@apify/timeout)
21
+
22
+ Internal utilities and constants shared across <a href="https://www.apify.com">Apify</a> projects.
23
+ Unless you work at Apify ([interested?](https://apify.com/jobs)), you shouldn't use this package directly,
24
+ as things might break for you any time without deprecation warning.
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH: () => DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH,
25
+ calculateRunDynamicMemory: () => calculateRunDynamicMemory
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/memory_calculator.ts
30
+ var import_mathjs = require("mathjs");
31
+ var import_consts = require("@apify/consts");
32
+ var DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1e3;
33
+ var ALLOWED_RUN_OPTION_KEYS = /* @__PURE__ */ new Set([
34
+ "build",
35
+ "timeoutSecs",
36
+ "memoryMbytes",
37
+ "diskMbytes",
38
+ "maxItems",
39
+ "maxTotalChargeUsd",
40
+ "restartOnError"
41
+ ]);
42
+ var math = (0, import_mathjs.create)({
43
+ // expression dependencies
44
+ // Required for compiling and evaluating root expressions.
45
+ // We disable it below to prevent users from calling `evaluate()` inside their expressions.
46
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
47
+ compileDependencies: import_mathjs.compileDependencies,
48
+ evaluateDependencies: import_mathjs.evaluateDependencies,
49
+ // arithmetic dependencies
50
+ addDependencies: import_mathjs.addDependencies,
51
+ subtractDependencies: import_mathjs.subtractDependencies,
52
+ multiplyDependencies: import_mathjs.multiplyDependencies,
53
+ divideDependencies: import_mathjs.divideDependencies,
54
+ // statistics dependencies
55
+ maxDependencies: import_mathjs.maxDependencies,
56
+ minDependencies: import_mathjs.minDependencies,
57
+ // logical dependencies
58
+ andDependencies: import_mathjs.andDependencies,
59
+ notDependencies: import_mathjs.notDependencies,
60
+ orDependencies: import_mathjs.orDependencies,
61
+ xorDependencies: import_mathjs.xorDependencies,
62
+ // without that dependency 'null ?? 5', won't work
63
+ nullishDependencies: import_mathjs.nullishDependencies
64
+ });
65
+ var { compile } = math;
66
+ math.import({
67
+ // We disable evaluate to prevent users from calling it inside their expressions.
68
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
69
+ evaluate() {
70
+ throw new Error("Function evaluate is disabled.");
71
+ },
72
+ compile() {
73
+ throw new Error("Function compile is disabled.");
74
+ },
75
+ // We need to disable it, because compileDependencies imports parseDependencies.
76
+ parse() {
77
+ throw new Error("Function parse is disabled.");
78
+ }
79
+ }, { override: true });
80
+ var customGetFunc = /* @__PURE__ */ __name((obj, path, defaultVal) => {
81
+ return path.split(".").reduce((current, key) => current?.[key], obj) ?? defaultVal;
82
+ }, "customGetFunc");
83
+ var roundToClosestPowerOf2 = /* @__PURE__ */ __name((num) => {
84
+ if (typeof num !== "number" || Number.isNaN(num) || !Number.isFinite(num)) {
85
+ throw new Error(`Calculated memory value is not a valid number: ${num}.`);
86
+ }
87
+ if (num <= 0) {
88
+ throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);
89
+ }
90
+ const log2n = Math.log2(num);
91
+ const roundedLog = Math.round(log2n);
92
+ const result = 2 ** roundedLog;
93
+ return Math.max(import_consts.ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, import_consts.ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));
94
+ }, "roundToClosestPowerOf2");
95
+ var processTemplateVariables = /* @__PURE__ */ __name((defaultMemoryMbytes) => {
96
+ const variableRegex = /{{\s*([a-zA-Z0-9_.]+)\s*}}/g;
97
+ const processedExpression = defaultMemoryMbytes.replace(
98
+ variableRegex,
99
+ (_, variableName) => {
100
+ if (variableName.startsWith("input.")) {
101
+ return variableName;
102
+ }
103
+ if (variableName.startsWith("runOptions.")) {
104
+ const key = variableName.slice("runOptions.".length);
105
+ if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
106
+ throw new Error(
107
+ `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(", ")}.`
108
+ );
109
+ }
110
+ return variableName;
111
+ }
112
+ throw new Error(
113
+ `Invalid variable '{{${variableName}}}' in expression.`
114
+ );
115
+ }
116
+ );
117
+ return processedExpression;
118
+ }, "processTemplateVariables");
119
+ var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) => {
120
+ if (!cache) {
121
+ return compile(expression);
122
+ }
123
+ let compiledExpression = await cache.get(expression);
124
+ if (!compiledExpression) {
125
+ compiledExpression = compile(expression);
126
+ await cache.set(expression, compiledExpression);
127
+ }
128
+ return compiledExpression;
129
+ }, "getCompiledExpression");
130
+ var calculateRunDynamicMemory = /* @__PURE__ */ __name(async (defaultMemoryMbytes, context, options = void 0) => {
131
+ if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {
132
+ throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);
133
+ }
134
+ const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);
135
+ const preparedContext = {
136
+ ...context,
137
+ get: customGetFunc
138
+ };
139
+ const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);
140
+ let finalResult = compiledExpression.evaluate(preparedContext);
141
+ if (finalResult && typeof finalResult === "object" && "entries" in finalResult) {
142
+ const { entries } = finalResult;
143
+ finalResult = entries[entries.length - 1];
144
+ }
145
+ return roundToClosestPowerOf2(finalResult);
146
+ }, "calculateRunDynamicMemory");
147
+ // Annotate the CommonJS export names for ESM import in node:
148
+ 0 && (module.exports = {
149
+ DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH,
150
+ calculateRunDynamicMemory
151
+ });
152
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/memory_calculator.ts"],"sourcesContent":["export * from './memory_calculator';\n","// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n type EvalFunction,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n // @ts-expect-error nullishDependencies is not declared in types. https://github.com/josdejong/mathjs/issues/3597\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import({\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() { throw new Error('Function evaluate is disabled.'); },\n compile() { throw new Error('Function compile is disabled.'); },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() { throw new Error('Function parse is disabled.'); },\n}, { override: true });\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n*/\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return (path.split('.').reduce((current, key) => current?.[key], obj)) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n*/\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(\n variableRegex,\n (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression.`,\n );\n },\n );\n\n return processedExpression;\n};\n\n/*\n* Retrieves a compiled expression from the cache or compiles it if not present.\n*\n* @param expression The expression string to compile.\n* @param cache An optional cache to store/retrieve compiled expressions.\n* @returns The compiled EvalFunction.\n*/\nconst getCompiledExpression = async (expression: string, cache: CompilationCache | undefined): Promise<EvalFunction> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n*/\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":"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","names":[]}
@@ -0,0 +1,36 @@
1
+ import { EvalFunction } from 'mathjs';
2
+
3
+ type ActorRunOptions = {
4
+ build?: string;
5
+ timeoutSecs?: number;
6
+ memoryMbytes?: number;
7
+ diskMbytes?: number;
8
+ maxItems?: number;
9
+ maxTotalChargeUsd?: number;
10
+ restartOnError?: boolean;
11
+ };
12
+ type MemoryEvaluationContext = {
13
+ runOptions: ActorRunOptions;
14
+ input: Record<string, unknown>;
15
+ };
16
+ type CompilationCache = {
17
+ get: (expression: string) => Promise<EvalFunction | null>;
18
+ set: (expression: string, compilationResult: EvalFunction) => Promise<void>;
19
+ size: () => Promise<number>;
20
+ };
21
+
22
+ declare const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;
23
+ /**
24
+ * Evaluates a dynamic memory expression string using the provided context.
25
+ * Result is rounded to the closest power of 2 and clamped within allowed limits.
26
+ *
27
+ * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).
28
+ * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.
29
+ * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.
30
+ * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.
31
+ */
32
+ declare const calculateRunDynamicMemory: (defaultMemoryMbytes: string, context: MemoryEvaluationContext, options?: {
33
+ cache: CompilationCache;
34
+ } | undefined) => Promise<number>;
35
+
36
+ export { DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH, calculateRunDynamicMemory };
@@ -0,0 +1,36 @@
1
+ import { EvalFunction } from 'mathjs';
2
+
3
+ type ActorRunOptions = {
4
+ build?: string;
5
+ timeoutSecs?: number;
6
+ memoryMbytes?: number;
7
+ diskMbytes?: number;
8
+ maxItems?: number;
9
+ maxTotalChargeUsd?: number;
10
+ restartOnError?: boolean;
11
+ };
12
+ type MemoryEvaluationContext = {
13
+ runOptions: ActorRunOptions;
14
+ input: Record<string, unknown>;
15
+ };
16
+ type CompilationCache = {
17
+ get: (expression: string) => Promise<EvalFunction | null>;
18
+ set: (expression: string, compilationResult: EvalFunction) => Promise<void>;
19
+ size: () => Promise<number>;
20
+ };
21
+
22
+ declare const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;
23
+ /**
24
+ * Evaluates a dynamic memory expression string using the provided context.
25
+ * Result is rounded to the closest power of 2 and clamped within allowed limits.
26
+ *
27
+ * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).
28
+ * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.
29
+ * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.
30
+ * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.
31
+ */
32
+ declare const calculateRunDynamicMemory: (defaultMemoryMbytes: string, context: MemoryEvaluationContext, options?: {
33
+ cache: CompilationCache;
34
+ } | undefined) => Promise<number>;
35
+
36
+ export { DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH, calculateRunDynamicMemory };
@@ -0,0 +1,141 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/memory_calculator.ts
5
+ import {
6
+ addDependencies,
7
+ andDependencies,
8
+ compileDependencies,
9
+ create,
10
+ divideDependencies,
11
+ evaluateDependencies,
12
+ maxDependencies,
13
+ minDependencies,
14
+ multiplyDependencies,
15
+ notDependencies,
16
+ nullishDependencies,
17
+ orDependencies,
18
+ subtractDependencies,
19
+ xorDependencies
20
+ } from "mathjs";
21
+ import { ACTOR_LIMITS } from "@apify/consts";
22
+ var DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1e3;
23
+ var ALLOWED_RUN_OPTION_KEYS = /* @__PURE__ */ new Set([
24
+ "build",
25
+ "timeoutSecs",
26
+ "memoryMbytes",
27
+ "diskMbytes",
28
+ "maxItems",
29
+ "maxTotalChargeUsd",
30
+ "restartOnError"
31
+ ]);
32
+ var math = create({
33
+ // expression dependencies
34
+ // Required for compiling and evaluating root expressions.
35
+ // We disable it below to prevent users from calling `evaluate()` inside their expressions.
36
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
37
+ compileDependencies,
38
+ evaluateDependencies,
39
+ // arithmetic dependencies
40
+ addDependencies,
41
+ subtractDependencies,
42
+ multiplyDependencies,
43
+ divideDependencies,
44
+ // statistics dependencies
45
+ maxDependencies,
46
+ minDependencies,
47
+ // logical dependencies
48
+ andDependencies,
49
+ notDependencies,
50
+ orDependencies,
51
+ xorDependencies,
52
+ // without that dependency 'null ?? 5', won't work
53
+ nullishDependencies
54
+ });
55
+ var { compile } = math;
56
+ math.import({
57
+ // We disable evaluate to prevent users from calling it inside their expressions.
58
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
59
+ evaluate() {
60
+ throw new Error("Function evaluate is disabled.");
61
+ },
62
+ compile() {
63
+ throw new Error("Function compile is disabled.");
64
+ },
65
+ // We need to disable it, because compileDependencies imports parseDependencies.
66
+ parse() {
67
+ throw new Error("Function parse is disabled.");
68
+ }
69
+ }, { override: true });
70
+ var customGetFunc = /* @__PURE__ */ __name((obj, path, defaultVal) => {
71
+ return path.split(".").reduce((current, key) => current?.[key], obj) ?? defaultVal;
72
+ }, "customGetFunc");
73
+ var roundToClosestPowerOf2 = /* @__PURE__ */ __name((num) => {
74
+ if (typeof num !== "number" || Number.isNaN(num) || !Number.isFinite(num)) {
75
+ throw new Error(`Calculated memory value is not a valid number: ${num}.`);
76
+ }
77
+ if (num <= 0) {
78
+ throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);
79
+ }
80
+ const log2n = Math.log2(num);
81
+ const roundedLog = Math.round(log2n);
82
+ const result = 2 ** roundedLog;
83
+ return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));
84
+ }, "roundToClosestPowerOf2");
85
+ var processTemplateVariables = /* @__PURE__ */ __name((defaultMemoryMbytes) => {
86
+ const variableRegex = /{{\s*([a-zA-Z0-9_.]+)\s*}}/g;
87
+ const processedExpression = defaultMemoryMbytes.replace(
88
+ variableRegex,
89
+ (_, variableName) => {
90
+ if (variableName.startsWith("input.")) {
91
+ return variableName;
92
+ }
93
+ if (variableName.startsWith("runOptions.")) {
94
+ const key = variableName.slice("runOptions.".length);
95
+ if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
96
+ throw new Error(
97
+ `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(", ")}.`
98
+ );
99
+ }
100
+ return variableName;
101
+ }
102
+ throw new Error(
103
+ `Invalid variable '{{${variableName}}}' in expression.`
104
+ );
105
+ }
106
+ );
107
+ return processedExpression;
108
+ }, "processTemplateVariables");
109
+ var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) => {
110
+ if (!cache) {
111
+ return compile(expression);
112
+ }
113
+ let compiledExpression = await cache.get(expression);
114
+ if (!compiledExpression) {
115
+ compiledExpression = compile(expression);
116
+ await cache.set(expression, compiledExpression);
117
+ }
118
+ return compiledExpression;
119
+ }, "getCompiledExpression");
120
+ var calculateRunDynamicMemory = /* @__PURE__ */ __name(async (defaultMemoryMbytes, context, options = void 0) => {
121
+ if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {
122
+ throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);
123
+ }
124
+ const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);
125
+ const preparedContext = {
126
+ ...context,
127
+ get: customGetFunc
128
+ };
129
+ const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);
130
+ let finalResult = compiledExpression.evaluate(preparedContext);
131
+ if (finalResult && typeof finalResult === "object" && "entries" in finalResult) {
132
+ const { entries } = finalResult;
133
+ finalResult = entries[entries.length - 1];
134
+ }
135
+ return roundToClosestPowerOf2(finalResult);
136
+ }, "calculateRunDynamicMemory");
137
+ export {
138
+ DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH,
139
+ calculateRunDynamicMemory
140
+ };
141
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/memory_calculator.ts"],"sourcesContent":["// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n type EvalFunction,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n // @ts-expect-error nullishDependencies is not declared in types. https://github.com/josdejong/mathjs/issues/3597\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import({\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() { throw new Error('Function evaluate is disabled.'); },\n compile() { throw new Error('Function compile is disabled.'); },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() { throw new Error('Function parse is disabled.'); },\n}, { override: true });\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n*/\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return (path.split('.').reduce((current, key) => current?.[key], obj)) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n*/\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(\n variableRegex,\n (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression.`,\n );\n },\n );\n\n return processedExpression;\n};\n\n/*\n* Retrieves a compiled expression from the cache or compiles it if not present.\n*\n* @param expression The expression string to compile.\n* @param cache An optional cache to store/retrieve compiled expressions.\n* @returns The compiled EvalFunction.\n*/\nconst getCompiledExpression = async (expression: string, cache: CompilationCache | undefined): Promise<EvalFunction> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n*/\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":";;;;AACA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,oBAAoB;AAOtB,IAAM,8CAA8C;AAM3D,IAAM,0BAA0B,oBAAI,IAA2B;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAMD,IAAM,OAAO,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKhB;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACJ,CAAC;AACD,IAAM,EAAE,QAAQ,IAAI;AAGpB,KAAK,OAAO;AAAA;AAAA;AAAA,EAGR,WAAW;AAAE,UAAM,IAAI,MAAM,gCAAgC;AAAA,EAAG;AAAA,EAChE,UAAU;AAAE,UAAM,IAAI,MAAM,+BAA+B;AAAA,EAAG;AAAA;AAAA,EAE9D,QAAQ;AAAE,UAAM,IAAI,MAAM,6BAA6B;AAAA,EAAG;AAC9D,GAAG,EAAE,UAAU,KAAK,CAAC;AAarB,IAAM,gBAAgB,wBAAC,KAAU,MAAc,eAAwB;AACnE,SAAQ,KAAK,MAAM,GAAG,EAAE,OAAO,CAAC,SAAS,QAAQ,UAAU,GAAG,GAAG,GAAG,KAAM;AAC9E,GAFsB;AAUtB,IAAM,yBAAyB,wBAAC,QAAwB;AACpD,MAAI,OAAO,QAAQ,YAAY,OAAO,MAAM,GAAG,KAAK,CAAC,OAAO,SAAS,GAAG,GAAG;AACvE,UAAM,IAAI,MAAM,kDAAkD,GAAG,GAAG;AAAA,EAC5E;AAGA,MAAI,OAAO,GAAG;AACV,UAAM,IAAI,MAAM,2EAA2E,GAAG,GAAG;AAAA,EACrG;AAEA,QAAM,QAAQ,KAAK,KAAK,GAAG;AAE3B,QAAM,aAAa,KAAK,MAAM,KAAK;AACnC,QAAM,SAAS,KAAK;AAEpB,SAAO,KAAK,IAAI,aAAa,uBAAuB,KAAK,IAAI,QAAQ,aAAa,qBAAqB,CAAC;AAC5G,GAhB+B;AAoC/B,IAAM,2BAA2B,wBAAC,wBAAwC;AACtE,QAAM,gBAAgB;AAEtB,QAAM,sBAAsB,oBAAoB;AAAA,IAC5C;AAAA,IACA,CAAC,GAAG,iBAAyB;AAGzB,UAAI,aAAa,WAAW,QAAQ,GAAG;AACnC,eAAO;AAAA,MACX;AAGA,UAAI,aAAa,WAAW,aAAa,GAAG;AACxC,cAAM,MAAM,aAAa,MAAM,cAAc,MAAM;AACnD,YAAI,CAAC,wBAAwB,IAAI,GAA4B,GAAG;AAC5D,gBAAM,IAAI;AAAA,YACN,uBAAuB,YAAY,iEAAiE,MAAM,KAAK,uBAAuB,EAAE,IAAI,CAAC,MAAM,cAAc,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA,UACpL;AAAA,QACJ;AACA,eAAO;AAAA,MACX;AAGA,YAAM,IAAI;AAAA,QACN,uBAAuB,YAAY;AAAA,MACvC;AAAA,IACJ;AAAA,EACJ;AAEA,SAAO;AACX,GA/BiC;AAwCjC,IAAM,wBAAwB,8BAAO,YAAoB,UAA+D;AACpH,MAAI,CAAC,OAAO;AACR,WAAO,QAAQ,UAAU;AAAA,EAC7B;AAEA,MAAI,qBAAqB,MAAM,MAAM,IAAI,UAAU;AAEnD,MAAI,CAAC,oBAAoB;AACrB,yBAAqB,QAAQ,UAAU;AACvC,UAAM,MAAM,IAAI,YAAY,kBAAmB;AAAA,EACnD;AAEA,SAAO;AACX,GAb8B;AAwBvB,IAAM,4BAA4B,8BACrC,qBACA,SACA,UAAmD,WAClD;AACD,MAAI,oBAAoB,SAAS,6CAA6C;AAC1E,UAAM,IAAI,MAAM,iEAAiE,2CAA2C,cAAc;AAAA,EAC9I;AAIA,QAAM,yBAAyB,yBAAyB,mBAAmB;AAE3E,QAAM,kBAAkB;AAAA,IACpB,GAAG;AAAA,IACH,KAAK;AAAA,EACT;AAEA,QAAM,qBAAqB,MAAM,sBAAsB,wBAAwB,SAAS,KAAK;AAE7F,MAAI,cAA8C,mBAAmB,SAAS,eAAe;AAI7F,MAAI,eAAe,OAAO,gBAAgB,YAAY,aAAa,aAAa;AAC5E,UAAM,EAAE,QAAQ,IAAI;AACpB,kBAAc,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAC5C;AAEA,SAAO,uBAAuB,WAAW;AAC7C,GA9ByC;","names":[]}
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@apify/actor-memory-expression",
3
+ "version": "0.1.0",
4
+ "description": "Utility to evaluate dynamic memory expressions for Apify actors.",
5
+ "main": "./cjs/index.cjs",
6
+ "module": "./esm/index.mjs",
7
+ "typings": "./cjs/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./esm/index.d.mts",
12
+ "default": "./esm/index.mjs"
13
+ },
14
+ "require": {
15
+ "types": "./cjs/index.d.ts",
16
+ "default": "./cjs/index.cjs"
17
+ }
18
+ }
19
+ },
20
+ "keywords": [
21
+ "apify"
22
+ ],
23
+ "author": {
24
+ "name": "Apify",
25
+ "email": "support@apify.com",
26
+ "url": "https://apify.com"
27
+ },
28
+ "contributors": [
29
+ "Jan Curn <jan@apify.com>",
30
+ "Marek Trunkát <marek@apify.com>"
31
+ ],
32
+ "license": "Apache-2.0",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/apify/apify-shared-js"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/apify/apify-shared-js/issues"
39
+ },
40
+ "homepage": "https://apify.com",
41
+ "scripts": {
42
+ "build": "npm run clean && npm run compile && npm run copy",
43
+ "clean": "rimraf ./dist",
44
+ "compile": "tsup",
45
+ "copy": "ts-node -T ../../scripts/copy.ts"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@apify/consts": "^2.47.0",
52
+ "@apify/log": "^2.5.26",
53
+ "mathjs": "^15.1.0"
54
+ }
55
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@apify/actor-memory-expression",
3
+ "version": "0.1.0",
4
+ "description": "Utility to evaluate dynamic memory expressions for Apify actors.",
5
+ "main": "./dist/cjs/index.cjs",
6
+ "module": "./dist/esm/index.mjs",
7
+ "typings": "./dist/cjs/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/esm/index.d.mts",
12
+ "default": "./dist/esm/index.mjs"
13
+ },
14
+ "require": {
15
+ "types": "./dist/cjs/index.d.ts",
16
+ "default": "./dist/cjs/index.cjs"
17
+ }
18
+ }
19
+ },
20
+ "keywords": [
21
+ "apify"
22
+ ],
23
+ "author": {
24
+ "name": "Apify",
25
+ "email": "support@apify.com",
26
+ "url": "https://apify.com"
27
+ },
28
+ "contributors": [
29
+ "Jan Curn <jan@apify.com>",
30
+ "Marek Trunkát <marek@apify.com>"
31
+ ],
32
+ "license": "Apache-2.0",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/apify/apify-shared-js"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/apify/apify-shared-js/issues"
39
+ },
40
+ "homepage": "https://apify.com",
41
+ "scripts": {
42
+ "build": "npm run clean && npm run compile && npm run copy",
43
+ "clean": "rimraf ./dist",
44
+ "compile": "tsup",
45
+ "copy": "ts-node -T ../../scripts/copy.ts"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@apify/consts": "^2.47.0",
52
+ "@apify/log": "^2.5.26",
53
+ "mathjs": "^15.1.0"
54
+ }
55
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './memory_calculator';
@@ -0,0 +1,235 @@
1
+ // MathJS bundle with only numbers is ~2x smaller than the default one.
2
+ import {
3
+ addDependencies,
4
+ andDependencies,
5
+ compileDependencies,
6
+ create,
7
+ divideDependencies,
8
+ type EvalFunction,
9
+ evaluateDependencies,
10
+ maxDependencies,
11
+ minDependencies,
12
+ multiplyDependencies,
13
+ notDependencies,
14
+ // @ts-expect-error nullishDependencies is not declared in types. https://github.com/josdejong/mathjs/issues/3597
15
+ nullishDependencies,
16
+ orDependencies,
17
+ subtractDependencies,
18
+ xorDependencies,
19
+ } from 'mathjs';
20
+
21
+ import { ACTOR_LIMITS } from '@apify/consts';
22
+
23
+ import type { ActorRunOptions, CompilationCache, MemoryEvaluationContext } from './types.js';
24
+
25
+ // In theory, users could create expressions longer than 1000 characters,
26
+ // but in practice, it's unlikely anyone would need that much complexity.
27
+ // Later we can increase this limit if needed.
28
+ export const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;
29
+
30
+ /**
31
+ * A Set of allowed keys from ActorRunOptions that can be used in
32
+ * the {{runOptions.variable}} syntax.
33
+ */
34
+ const ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([
35
+ 'build',
36
+ 'timeoutSecs',
37
+ 'memoryMbytes',
38
+ 'diskMbytes',
39
+ 'maxItems',
40
+ 'maxTotalChargeUsd',
41
+ 'restartOnError',
42
+ ]);
43
+
44
+ /**
45
+ * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.
46
+ * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html
47
+ */
48
+ const math = create({
49
+ // expression dependencies
50
+ // Required for compiling and evaluating root expressions.
51
+ // We disable it below to prevent users from calling `evaluate()` inside their expressions.
52
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
53
+ compileDependencies,
54
+ evaluateDependencies,
55
+
56
+ // arithmetic dependencies
57
+ addDependencies,
58
+ subtractDependencies,
59
+ multiplyDependencies,
60
+ divideDependencies,
61
+ // statistics dependencies
62
+ maxDependencies,
63
+ minDependencies,
64
+ // logical dependencies
65
+ andDependencies,
66
+ notDependencies,
67
+ orDependencies,
68
+ xorDependencies,
69
+ // without that dependency 'null ?? 5', won't work
70
+ nullishDependencies,
71
+ });
72
+ const { compile } = math;
73
+
74
+ // Disable potentially dangerous functions
75
+ math.import({
76
+ // We disable evaluate to prevent users from calling it inside their expressions.
77
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
78
+ evaluate() { throw new Error('Function evaluate is disabled.'); },
79
+ compile() { throw new Error('Function compile is disabled.'); },
80
+ // We need to disable it, because compileDependencies imports parseDependencies.
81
+ parse() { throw new Error('Function parse is disabled.'); },
82
+ }, { override: true });
83
+
84
+ /**
85
+ * Safely retrieves a nested property from an object using a dot-notation string path.
86
+ *
87
+ * This is custom function designed to be injected into the math expression evaluator,
88
+ * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.
89
+ *
90
+ * @param obj The source object to search within.
91
+ * @param path A dot-separated string representing the nested path (e.g., "input.payload.size").
92
+ * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.
93
+ * @returns The retrieved value, or `defaultVal` if the path is unreachable.
94
+ */
95
+ const customGetFunc = (obj: any, path: string, defaultVal?: number) => {
96
+ return (path.split('.').reduce((current, key) => current?.[key], obj)) ?? defaultVal;
97
+ };
98
+
99
+ /**
100
+ * Rounds a number to the closest power of 2.
101
+ * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).
102
+ * @param num The number to round.
103
+ * @returns The closest power of 2 within min/max range.
104
+ */
105
+ const roundToClosestPowerOf2 = (num: number): number => {
106
+ if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {
107
+ throw new Error(`Calculated memory value is not a valid number: ${num}.`);
108
+ }
109
+
110
+ // Handle 0 or negative values.
111
+ if (num <= 0) {
112
+ throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);
113
+ }
114
+
115
+ const log2n = Math.log2(num);
116
+
117
+ const roundedLog = Math.round(log2n);
118
+ const result = 2 ** roundedLog;
119
+
120
+ return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));
121
+ };
122
+
123
+ /**
124
+ * Replaces all `{{variable}}` placeholders in an expression into direct
125
+ * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).
126
+ *
127
+ * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).
128
+ *
129
+ * Note: While not really needed for Math.js, this approach allows developers
130
+ * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`
131
+ * across the Apify platform. We also want to avoid compiling the expression with the
132
+ * actual values as that would make caching less effective.
133
+ *
134
+ * @example
135
+ * // Returns "runOptions.memoryMbytes + 1024"
136
+ * preprocessDefaultMemoryExpression("{{runOptions.memoryMbytes}} + 1024");
137
+ *
138
+ * @param defaultMemoryMbytes The raw string expression, e.g., "{{runOptions.memoryMbytes}} * 2".
139
+ * @returns A safe, processed expression for evaluation, e.g., "runOptions.memoryMbytes * 2".
140
+ */
141
+ const processTemplateVariables = (defaultMemoryMbytes: string): string => {
142
+ const variableRegex = /{{\s*([a-zA-Z0-9_.]+)\s*}}/g;
143
+
144
+ const processedExpression = defaultMemoryMbytes.replace(
145
+ variableRegex,
146
+ (_, variableName: string) => {
147
+ // 1. Check if the variable is accessing input (e.g. {{input.someValue}})
148
+ // We do not validate the specific property name because `input` is dynamic.
149
+ if (variableName.startsWith('input.')) {
150
+ return variableName;
151
+ }
152
+
153
+ // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.
154
+ if (variableName.startsWith('runOptions.')) {
155
+ const key = variableName.slice('runOptions.'.length);
156
+ if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {
157
+ throw new Error(
158
+ `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(', ')}.`,
159
+ );
160
+ }
161
+ return variableName;
162
+ }
163
+
164
+ // 3. Throw error for unrecognized variables (e.g. {{someVariable}})
165
+ throw new Error(
166
+ `Invalid variable '{{${variableName}}}' in expression.`,
167
+ );
168
+ },
169
+ );
170
+
171
+ return processedExpression;
172
+ };
173
+
174
+ /*
175
+ * Retrieves a compiled expression from the cache or compiles it if not present.
176
+ *
177
+ * @param expression The expression string to compile.
178
+ * @param cache An optional cache to store/retrieve compiled expressions.
179
+ * @returns The compiled EvalFunction.
180
+ */
181
+ const getCompiledExpression = async (expression: string, cache: CompilationCache | undefined): Promise<EvalFunction> => {
182
+ if (!cache) {
183
+ return compile(expression);
184
+ }
185
+
186
+ let compiledExpression = await cache.get(expression);
187
+
188
+ if (!compiledExpression) {
189
+ compiledExpression = compile(expression);
190
+ await cache.set(expression, compiledExpression!);
191
+ }
192
+
193
+ return compiledExpression;
194
+ };
195
+
196
+ /**
197
+ * Evaluates a dynamic memory expression string using the provided context.
198
+ * Result is rounded to the closest power of 2 and clamped within allowed limits.
199
+ *
200
+ * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).
201
+ * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.
202
+ * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.
203
+ * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.
204
+ */
205
+ export const calculateRunDynamicMemory = async (
206
+ defaultMemoryMbytes: string,
207
+ context: MemoryEvaluationContext,
208
+ options: { cache: CompilationCache } | undefined = undefined,
209
+ ) => {
210
+ if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {
211
+ throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);
212
+ }
213
+
214
+ // Replaces all occurrences of {{variable}} with variable
215
+ // e.g., "{{runOptions.memoryMbytes}} + 1024" becomes "runOptions.memoryMbytes + 1024"
216
+ const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);
217
+
218
+ const preparedContext = {
219
+ ...context,
220
+ get: customGetFunc,
221
+ };
222
+
223
+ const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);
224
+
225
+ let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);
226
+
227
+ // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.
228
+ // Note: one-line expressions return a number directly.
229
+ if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {
230
+ const { entries } = finalResult;
231
+ finalResult = entries[entries.length - 1];
232
+ }
233
+
234
+ return roundToClosestPowerOf2(finalResult);
235
+ };
package/src/types.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { EvalFunction } from 'mathjs';
2
+
3
+ export type ActorRunOptions = {
4
+ build?: string;
5
+ timeoutSecs?: number;
6
+ memoryMbytes?: number; // probably no one will need it, but let's keep it consistent
7
+ diskMbytes?: number; // probably no one will need it, but let's keep it consistent
8
+ maxItems?: number;
9
+ maxTotalChargeUsd?: number;
10
+ restartOnError?: boolean;
11
+ }
12
+
13
+ export type MemoryEvaluationContext = {
14
+ runOptions: ActorRunOptions;
15
+ input: Record<string, unknown>;
16
+ }
17
+
18
+ export type CompilationCache = {
19
+ get: (expression: string) => Promise<EvalFunction | null>;
20
+ set: (expression: string, compilationResult: EvalFunction) => Promise<void>;
21
+ size: () => Promise<number>;
22
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.build.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "emitDeclarationOnly": true
6
+ },
7
+ "include": ["src/**/*"]
8
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "include": ["src/**/*"]
4
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { createTsupConfig } from '../../scripts/tsup.config';
2
+
3
+ // eslint-disable-next-line import/no-default-export
4
+ export default createTsupConfig({});