react-native-worklets 0.11.1 → 0.12.0-nightly-20260717-55ef079be

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 (32) hide show
  1. package/Common/cpp/worklets/NativeModules/JSIWorkletsModuleProxy.cpp +13 -9
  2. package/Common/cpp/worklets/WorkletRuntime/RuntimeManager.cpp +7 -4
  3. package/Common/cpp/worklets/WorkletRuntime/RuntimeManager.h +2 -1
  4. package/Common/cpp/worklets/WorkletRuntime/WorkletRuntime.cpp +15 -4
  5. package/Common/cpp/worklets/WorkletRuntime/WorkletRuntime.h +19 -5
  6. package/android/build.gradle.kts +19 -5
  7. package/compatibility.json +4 -1
  8. package/lib/module/WorkletsModule/NativeWorklets.native.js +2 -2
  9. package/lib/module/WorkletsModule/NativeWorklets.native.js.map +1 -1
  10. package/lib/module/debug/jsVersion.js +1 -1
  11. package/lib/module/debug/jsVersion.js.map +1 -1
  12. package/lib/module/memory/serializable.native.js +2 -1
  13. package/lib/module/memory/serializable.native.js.map +1 -1
  14. package/lib/module/runtimes.native.js +7 -2
  15. package/lib/module/runtimes.native.js.map +1 -1
  16. package/lib/typescript/WorkletsModule/NativeWorklets.native.d.ts.map +1 -1
  17. package/lib/typescript/WorkletsModule/workletsModuleProxy.d.ts +1 -1
  18. package/lib/typescript/WorkletsModule/workletsModuleProxy.d.ts.map +1 -1
  19. package/lib/typescript/debug/jsVersion.d.ts +1 -1
  20. package/lib/typescript/debug/jsVersion.d.ts.map +1 -1
  21. package/lib/typescript/memory/serializable.native.d.ts.map +1 -1
  22. package/lib/typescript/runtimes.native.d.ts.map +1 -1
  23. package/lib/typescript/types.d.ts +38 -8
  24. package/lib/typescript/types.d.ts.map +1 -1
  25. package/package.json +5 -5
  26. package/plugin/index.js +1624 -1595
  27. package/src/WorkletsModule/NativeWorklets.native.ts +4 -2
  28. package/src/WorkletsModule/workletsModuleProxy.ts +2 -1
  29. package/src/debug/jsVersion.ts +1 -1
  30. package/src/memory/serializable.native.ts +6 -2
  31. package/src/runtimes.native.ts +12 -2
  32. package/src/types.ts +42 -8
package/plugin/index.js CHANGED
@@ -25,6 +25,174 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  mod
26
26
  ));
27
27
 
28
+ // lib/directives.js
29
+ var require_directives = __commonJS({
30
+ "lib/directives.js"(exports2) {
31
+ "use strict";
32
+ Object.defineProperty(exports2, "__esModule", { value: true });
33
+ exports2.addDirective = addDirective;
34
+ exports2.replaceImplicitReturnWithBlock = replaceImplicitReturnWithBlock;
35
+ var types_12 = require("@babel/types");
36
+ function addDirective(node, dir) {
37
+ if (!node.directives.some((functionDirective) => functionDirective.value.value === dir)) {
38
+ node.directives.push((0, types_12.directive)((0, types_12.directiveLiteral)(dir)));
39
+ }
40
+ }
41
+ function replaceImplicitReturnWithBlock(path) {
42
+ if (!(0, types_12.isBlockStatement)(path.body)) {
43
+ path.body = (0, types_12.blockStatement)([(0, types_12.returnStatement)(path.body)]);
44
+ }
45
+ }
46
+ }
47
+ });
48
+
49
+ // lib/types.js
50
+ var require_types = __commonJS({
51
+ "lib/types.js"(exports2) {
52
+ "use strict";
53
+ Object.defineProperty(exports2, "__esModule", { value: true });
54
+ exports2.generatedWorkletsDir = exports2.workletClassFactorySuffix = exports2.WorkletizableObject = exports2.WorkletizableFunction = void 0;
55
+ exports2.isWorkletizableFunctionPath = isWorkletizableFunctionPath;
56
+ exports2.isWorkletizableFunctionNode = isWorkletizableFunctionNode;
57
+ exports2.isWorkletizableObjectPath = isWorkletizableObjectPath;
58
+ exports2.isWorkletizableObjectNode = isWorkletizableObjectNode;
59
+ var types_12 = require("@babel/types");
60
+ exports2.WorkletizableFunction = "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod";
61
+ exports2.WorkletizableObject = "ObjectExpression";
62
+ function isWorkletizableFunctionPath(path) {
63
+ return path.isFunctionDeclaration() || path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isObjectMethod();
64
+ }
65
+ function isWorkletizableFunctionNode(node) {
66
+ return (0, types_12.isFunctionDeclaration)(node) || (0, types_12.isFunctionExpression)(node) || (0, types_12.isArrowFunctionExpression)(node) || (0, types_12.isObjectMethod)(node);
67
+ }
68
+ function isWorkletizableObjectPath(path) {
69
+ return path.isObjectExpression();
70
+ }
71
+ function isWorkletizableObjectNode(node) {
72
+ return (0, types_12.isObjectExpression)(node);
73
+ }
74
+ exports2.workletClassFactorySuffix = "__classFactory";
75
+ exports2.generatedWorkletsDir = ".worklets";
76
+ }
77
+ });
78
+
79
+ // lib/referencedWorklets.js
80
+ var require_referencedWorklets = __commonJS({
81
+ "lib/referencedWorklets.js"(exports2) {
82
+ "use strict";
83
+ Object.defineProperty(exports2, "__esModule", { value: true });
84
+ exports2.findReferencedWorklet = findReferencedWorklet;
85
+ var types_12 = require("@babel/types");
86
+ var types_2 = require_types();
87
+ function findReferencedWorklet(workletIdentifier, acceptWorkletizableFunction, acceptObject, state) {
88
+ const workletName = workletIdentifier.node.name;
89
+ const scope = workletIdentifier.scope;
90
+ const workletBinding = scope.getBinding(workletName);
91
+ if (!workletBinding) {
92
+ return void 0;
93
+ }
94
+ if (state.opts.bundleMode && bindingIsWorklet(workletBinding)) {
95
+ return void 0;
96
+ }
97
+ if (acceptWorkletizableFunction && workletBinding.path.isFunctionDeclaration()) {
98
+ return workletBinding.path;
99
+ }
100
+ const isConstant = workletBinding.constant;
101
+ if (isConstant) {
102
+ return findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state);
103
+ }
104
+ return findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state);
105
+ }
106
+ function findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
107
+ const workletDeclaration = workletBinding.path;
108
+ if (!workletDeclaration.isVariableDeclarator()) {
109
+ return void 0;
110
+ }
111
+ const worklet = workletDeclaration.get("init");
112
+ if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(worklet)) {
113
+ return worklet;
114
+ }
115
+ if (acceptObject && (0, types_2.isWorkletizableObjectPath)(worklet)) {
116
+ return worklet;
117
+ }
118
+ if (worklet.isIdentifier() && worklet.isReferencedIdentifier()) {
119
+ return findReferencedWorklet(worklet, acceptWorkletizableFunction, acceptObject, state);
120
+ }
121
+ return void 0;
122
+ }
123
+ function findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
124
+ const workletDeclaration = workletBinding.constantViolations.reverse().find((constantViolation) => constantViolation.isAssignmentExpression() && (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(constantViolation.get("right")) || acceptObject && (0, types_2.isWorkletizableObjectPath)(constantViolation.get("right"))));
125
+ if (!workletDeclaration || !workletDeclaration.isAssignmentExpression()) {
126
+ return void 0;
127
+ }
128
+ const workletDefinition = workletDeclaration.get("right");
129
+ if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(workletDefinition)) {
130
+ return workletDefinition;
131
+ }
132
+ if (acceptObject && (0, types_2.isWorkletizableObjectPath)(workletDefinition)) {
133
+ return workletDefinition;
134
+ }
135
+ if (workletDefinition.isIdentifier() && workletDefinition.isReferencedIdentifier()) {
136
+ return findReferencedWorklet(workletDefinition, acceptWorkletizableFunction, acceptObject, state);
137
+ }
138
+ return void 0;
139
+ }
140
+ function bindingIsWorklet(binding) {
141
+ return binding.referencePaths.some((refPath) => !Array.isArray(refPath.container) && (0, types_12.isMemberExpression)(refPath.container) && refPath.container.object === refPath.node && (0, types_12.isIdentifier)(refPath.container.property) && refPath.container.property.name === "__workletHash");
142
+ }
143
+ }
144
+ });
145
+
146
+ // lib/findWorklet.js
147
+ var require_findWorklet = __commonJS({
148
+ "lib/findWorklet.js"(exports2) {
149
+ "use strict";
150
+ Object.defineProperty(exports2, "__esModule", { value: true });
151
+ exports2.findWorklet = findWorklet;
152
+ exports2.forEachWorkletizableFunction = forEachWorkletizableFunction;
153
+ exports2.forEachWorkletizableObjectProperty = forEachWorkletizableObjectProperty;
154
+ var referencedWorklets_1 = require_referencedWorklets();
155
+ var types_12 = require_types();
156
+ function findWorklet(nodePath, state, acceptWorkletizableFunction, acceptObject) {
157
+ if (acceptWorkletizableFunction && (0, types_12.isWorkletizableFunctionPath)(nodePath)) {
158
+ return nodePath;
159
+ }
160
+ if (acceptObject && (0, types_12.isWorkletizableObjectPath)(nodePath)) {
161
+ return nodePath;
162
+ }
163
+ if (nodePath.isIdentifier() && nodePath.isReferencedIdentifier()) {
164
+ const worklet = (0, referencedWorklets_1.findReferencedWorklet)(nodePath, acceptWorkletizableFunction, acceptObject, state);
165
+ return worklet;
166
+ }
167
+ return void 0;
168
+ }
169
+ function forEachWorkletizableFunction(arg, state, acceptWorkletizableFunction, acceptObject, callback) {
170
+ const maybeWorklet = findWorklet(arg, state, acceptWorkletizableFunction, acceptObject);
171
+ if (!maybeWorklet) {
172
+ return;
173
+ }
174
+ if ((0, types_12.isWorkletizableFunctionPath)(maybeWorklet)) {
175
+ callback(maybeWorklet);
176
+ } else if ((0, types_12.isWorkletizableObjectPath)(maybeWorklet)) {
177
+ forEachWorkletizableObjectProperty(maybeWorklet, state, callback);
178
+ }
179
+ }
180
+ function forEachWorkletizableObjectProperty(path, state, callback) {
181
+ const properties = path.get("properties");
182
+ for (const property of properties) {
183
+ if (property.isObjectMethod()) {
184
+ callback(property);
185
+ } else if (property.isObjectProperty()) {
186
+ const value = property.get("value");
187
+ forEachWorkletizableFunction(value, state, true, false, callback);
188
+ } else {
189
+ throw new Error(`'${property.type}' as to-be workletized argument is not supported for object hooks.`);
190
+ }
191
+ }
192
+ }
193
+ }
194
+ });
195
+
28
196
  // lib/gestureHandlerAutoworkletization.js
29
197
  var require_gestureHandlerAutoworkletization = __commonJS({
30
198
  "lib/gestureHandlerAutoworkletization.js"(exports2) {
@@ -251,124 +419,179 @@ var require_layoutAnimationAutoworkletization = __commonJS({
251
419
  }
252
420
  });
253
421
 
254
- // lib/types.js
255
- var require_types = __commonJS({
256
- "lib/types.js"(exports2) {
422
+ // lib/autoworkletization.js
423
+ var require_autoworkletization = __commonJS({
424
+ "lib/autoworkletization.js"(exports2) {
257
425
  "use strict";
258
426
  Object.defineProperty(exports2, "__esModule", { value: true });
259
- exports2.generatedWorkletsDir = exports2.workletClassFactorySuffix = exports2.WorkletizableObject = exports2.WorkletizableFunction = void 0;
260
- exports2.isWorkletizableFunctionPath = isWorkletizableFunctionPath;
261
- exports2.isWorkletizableFunctionNode = isWorkletizableFunctionNode;
262
- exports2.isWorkletizableObjectPath = isWorkletizableObjectPath;
263
- exports2.isWorkletizableObjectNode = isWorkletizableObjectNode;
427
+ exports2.addDirectivesToKnownCallback = addDirectivesToKnownCallback;
428
+ exports2.handleWorkletizableCallback = handleWorkletizableCallback;
264
429
  var types_12 = require("@babel/types");
265
- exports2.WorkletizableFunction = "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod";
266
- exports2.WorkletizableObject = "ObjectExpression";
267
- function isWorkletizableFunctionPath(path) {
268
- return path.isFunctionDeclaration() || path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isObjectMethod();
430
+ var directives_1 = require_directives();
431
+ var findWorklet_1 = require_findWorklet();
432
+ var gestureHandlerAutoworkletization_1 = require_gestureHandlerAutoworkletization();
433
+ var layoutAnimationAutoworkletization_1 = require_layoutAnimationAutoworkletization();
434
+ var reanimatedObjectHooks = /* @__PURE__ */ new Set([
435
+ "useAnimatedScrollHandler",
436
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks)
437
+ ]);
438
+ var reanimatedFunctionHooks = /* @__PURE__ */ new Set([
439
+ "useFrameCallback",
440
+ "useAnimatedStyle",
441
+ "useAnimatedProps",
442
+ "createAnimatedPropAdapter",
443
+ "useDerivedValue",
444
+ "useAnimatedScrollHandler",
445
+ "useAnimatedReaction",
446
+ // animations' callbacks
447
+ "withTiming",
448
+ "withSpring",
449
+ "withDecay",
450
+ "withRepeat",
451
+ // scheduling functions
452
+ "runOnUI",
453
+ "executeOnUIRuntimeSync",
454
+ "scheduleOnUI",
455
+ "runOnUISync",
456
+ "runOnUIAsync",
457
+ "runOnRuntime",
458
+ "runOnRuntimeSync",
459
+ "runOnRuntimeAsync",
460
+ "scheduleOnRuntime",
461
+ "runOnRuntimeSyncWithId",
462
+ "scheduleOnRuntimeWithId"
463
+ ]);
464
+ var reanimatedFunctionArgsToWorkletize = new Map([
465
+ ["useFrameCallback", [0]],
466
+ ["useAnimatedStyle", [0]],
467
+ ["useAnimatedProps", [0]],
468
+ ["createAnimatedPropAdapter", [0]],
469
+ ["useDerivedValue", [0]],
470
+ ["useAnimatedScrollHandler", [0]],
471
+ ["useAnimatedReaction", [0, 1]],
472
+ ["withTiming", [2]],
473
+ ["withSpring", [2]],
474
+ ["withDecay", [1]],
475
+ ["withRepeat", [3]],
476
+ ["runOnUI", [0]],
477
+ ["executeOnUIRuntimeSync", [0]],
478
+ ["scheduleOnUI", [0]],
479
+ ["runOnUISync", [0]],
480
+ ["runOnUIAsync", [0]],
481
+ ["runOnRuntime", [1]],
482
+ ["runOnRuntimeSync", [1]],
483
+ ["runOnRuntimeAsync", [1]],
484
+ ["scheduleOnRuntime", [1]],
485
+ ["runOnRuntimeSyncWithId", [1]],
486
+ ["scheduleOnRuntimeWithId", [1]],
487
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks).map((name) => [name, [0]]),
488
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerBuilderMethods).map((name) => [name, [0]])
489
+ ]);
490
+ function addDirectivesToKnownCallback(path) {
491
+ if ((0, gestureHandlerAutoworkletization_1.isGestureHandlerEventCallback)(path) || (0, layoutAnimationAutoworkletization_1.isLayoutAnimationCallback)(path)) {
492
+ addDirectives(path);
493
+ }
269
494
  }
270
- function isWorkletizableFunctionNode(node) {
271
- return (0, types_12.isFunctionDeclaration)(node) || (0, types_12.isFunctionExpression)(node) || (0, types_12.isArrowFunctionExpression)(node) || (0, types_12.isObjectMethod)(node);
495
+ function handleWorkletizableCallback(path, state) {
496
+ const callee = (0, types_12.isSequenceExpression)(path.node.callee) ? path.node.callee.expressions[path.node.callee.expressions.length - 1] : path.node.callee;
497
+ const name = "name" in callee ? callee.name : "property" in callee && "name" in callee.property ? callee.property.name : void 0;
498
+ if (name === void 0) {
499
+ return;
500
+ }
501
+ if (reanimatedFunctionHooks.has(name) || reanimatedObjectHooks.has(name)) {
502
+ const acceptWorkletizableFunction = reanimatedFunctionHooks.has(name);
503
+ const acceptObject = reanimatedObjectHooks.has(name);
504
+ const argIndices = reanimatedFunctionArgsToWorkletize.get(name);
505
+ const args = path.get("arguments").filter((_, index) => argIndices.includes(index));
506
+ addDirectivesToArgs(args, state, acceptWorkletizableFunction, acceptObject);
507
+ } else if (!(0, types_12.isV8IntrinsicIdentifier)(callee) && (0, gestureHandlerAutoworkletization_1.isGestureObjectEventCallbackMethod)(callee)) {
508
+ const args = path.get("arguments");
509
+ addDirectivesToArgs(args, state, true, true);
510
+ }
272
511
  }
273
- function isWorkletizableObjectPath(path) {
274
- return path.isObjectExpression();
512
+ function addDirectivesToArgs(args, state, acceptWorkletizableFunction, acceptObject) {
513
+ args.forEach((arg) => {
514
+ (0, findWorklet_1.forEachWorkletizableFunction)(arg, state, acceptWorkletizableFunction, acceptObject, addDirectives);
515
+ });
275
516
  }
276
- function isWorkletizableObjectNode(node) {
277
- return (0, types_12.isObjectExpression)(node);
517
+ function addDirectives(path) {
518
+ if (path.isArrowFunctionExpression()) {
519
+ (0, directives_1.replaceImplicitReturnWithBlock)(path.node);
520
+ }
521
+ (0, directives_1.addDirective)(path.node.body, "worklet");
278
522
  }
279
- exports2.workletClassFactorySuffix = "__classFactory";
280
- exports2.generatedWorkletsDir = ".worklets";
281
523
  }
282
524
  });
283
525
 
284
- // lib/referencedWorklets.js
285
- var require_referencedWorklets = __commonJS({
286
- "lib/referencedWorklets.js"(exports2) {
526
+ // lib/bundleMode.js
527
+ var require_bundleMode = __commonJS({
528
+ "lib/bundleMode.js"(exports2) {
287
529
  "use strict";
288
530
  Object.defineProperty(exports2, "__esModule", { value: true });
289
- exports2.findReferencedWorklet = findReferencedWorklet;
531
+ exports2.toggleBundleMode = toggleBundleMode;
290
532
  var types_12 = require("@babel/types");
291
- var types_2 = require_types();
292
- function findReferencedWorklet(workletIdentifier, acceptWorkletizableFunction, acceptObject, state) {
293
- const workletName = workletIdentifier.node.name;
294
- const scope = workletIdentifier.scope;
295
- const workletBinding = scope.getBinding(workletName);
296
- if (!workletBinding) {
297
- return void 0;
298
- }
299
- if (state.opts.bundleMode && bindingIsWorklet(workletBinding)) {
300
- return void 0;
301
- }
302
- if (acceptWorkletizableFunction && workletBinding.path.isFunctionDeclaration()) {
303
- return workletBinding.path;
304
- }
305
- const isConstant = workletBinding.constant;
306
- if (isConstant) {
307
- return findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state);
308
- }
309
- return findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state);
310
- }
311
- function findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
312
- const workletDeclaration = workletBinding.path;
313
- if (!workletDeclaration.isVariableDeclarator()) {
314
- return void 0;
315
- }
316
- const worklet = workletDeclaration.get("init");
317
- if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(worklet)) {
318
- return worklet;
319
- }
320
- if (acceptObject && (0, types_2.isWorkletizableObjectPath)(worklet)) {
321
- return worklet;
322
- }
323
- if (worklet.isIdentifier() && worklet.isReferencedIdentifier()) {
324
- return findReferencedWorklet(worklet, acceptWorkletizableFunction, acceptObject, state);
325
- }
326
- return void 0;
327
- }
328
- function findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
329
- const workletDeclaration = workletBinding.constantViolations.reverse().find((constantViolation) => constantViolation.isAssignmentExpression() && (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(constantViolation.get("right")) || acceptObject && (0, types_2.isWorkletizableObjectPath)(constantViolation.get("right"))));
330
- if (!workletDeclaration || !workletDeclaration.isAssignmentExpression()) {
331
- return void 0;
533
+ var path_1 = require("path");
534
+ var WORKLETS_PACKAGE = "react-native-worklets";
535
+ var WORKLETS_SRC_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "src");
536
+ var WORKLETS_LIB_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "lib", "module");
537
+ var togglePaths = [
538
+ (0, path_1.join)(WORKLETS_SRC_DIR, "index.ts"),
539
+ (0, path_1.join)(WORKLETS_SRC_DIR, "debug", "bundleMode.native.ts"),
540
+ (0, path_1.join)(WORKLETS_LIB_DIR, "index.js"),
541
+ (0, path_1.join)(WORKLETS_LIB_DIR, "debug", "bundleMode.native.js")
542
+ ];
543
+ function toggleBundleMode(path, state) {
544
+ if (!state.opts.bundleMode || !togglePaths.some((togglePath) => {
545
+ var _a;
546
+ return (_a = state.filename) === null || _a === void 0 ? void 0 : _a.endsWith(togglePath);
547
+ })) {
548
+ return;
332
549
  }
333
- const workletDefinition = workletDeclaration.get("right");
334
- if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(workletDefinition)) {
335
- return workletDefinition;
550
+ const expressionPath = path.get("expression");
551
+ if (!expressionPath.isAssignmentExpression()) {
552
+ return;
336
553
  }
337
- if (acceptObject && (0, types_2.isWorkletizableObjectPath)(workletDefinition)) {
338
- return workletDefinition;
554
+ const left = expressionPath.get("left");
555
+ if (!left.isMemberExpression()) {
556
+ return;
339
557
  }
340
- if (workletDefinition.isIdentifier() && workletDefinition.isReferencedIdentifier()) {
341
- return findReferencedWorklet(workletDefinition, acceptWorkletizableFunction, acceptObject, state);
558
+ const object = left.get("object");
559
+ const property = left.get("property");
560
+ if (!object.isIdentifier() || object.node.name !== "globalThis" || !property.isIdentifier() || property.node.name !== "_WORKLETS_BUNDLE_MODE_ENABLED") {
561
+ return;
342
562
  }
343
- return void 0;
344
- }
345
- function bindingIsWorklet(binding) {
346
- return binding.referencePaths.some((refPath) => !Array.isArray(refPath.container) && (0, types_12.isMemberExpression)(refPath.container) && refPath.container.object === refPath.node && (0, types_12.isIdentifier)(refPath.container.property) && refPath.container.property.name === "__workletHash");
563
+ const right = expressionPath.get("right");
564
+ right.replaceWith((0, types_12.booleanLiteral)(true));
347
565
  }
348
566
  }
349
567
  });
350
568
 
351
- // lib/findWorklet.js
352
- var require_findWorklet = __commonJS({
353
- "lib/findWorklet.js"(exports2) {
569
+ // lib/transform.js
570
+ var require_transform = __commonJS({
571
+ "lib/transform.js"(exports2) {
354
572
  "use strict";
573
+ var __rest = exports2 && exports2.__rest || function(s, e) {
574
+ var t = {};
575
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
576
+ t[p] = s[p];
577
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
578
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
579
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
580
+ t[p[i]] = s[p[i]];
581
+ }
582
+ return t;
583
+ };
355
584
  Object.defineProperty(exports2, "__esModule", { value: true });
356
- exports2.findWorklet = findWorklet;
357
- var referencedWorklets_1 = require_referencedWorklets();
358
- var types_12 = require_types();
359
- function findWorklet(nodePath, state, acceptWorkletizableFunction, acceptObject) {
360
- if (acceptWorkletizableFunction && (0, types_12.isWorkletizableFunctionPath)(nodePath)) {
361
- return nodePath;
362
- }
363
- if (acceptObject && (0, types_12.isWorkletizableObjectPath)(nodePath)) {
364
- return nodePath;
365
- }
366
- if (nodePath.isIdentifier() && nodePath.isReferencedIdentifier()) {
367
- const worklet = (0, referencedWorklets_1.findReferencedWorklet)(nodePath, acceptWorkletizableFunction, acceptObject, state);
368
- return worklet;
369
- }
370
- return void 0;
585
+ exports2.workletTransformSync = workletTransformSync;
586
+ var core_1 = require("@babel/core");
587
+ function workletTransformSync(code, opts) {
588
+ const { extraPlugins = [], extraPresets = [] } = opts, rest = __rest(opts, ["extraPlugins", "extraPresets"]);
589
+ return (0, core_1.transformSync)(code, Object.assign(Object.assign({}, rest), { plugins: [...defaultPlugins, ...extraPlugins], presets: [...defaultPresets, ...extraPresets] }));
371
590
  }
591
+ var defaultPresets = [
592
+ require.resolve("@babel/preset-typescript")
593
+ ];
594
+ var defaultPlugins = [];
372
595
  }
373
596
  });
374
597
 
@@ -401,1695 +624,1478 @@ var require_utils = __commonJS({
401
624
  }
402
625
  });
403
626
 
404
- // lib/globals.js
405
- var require_globals = __commonJS({
406
- "lib/globals.js"(exports2) {
627
+ // lib/class.js
628
+ var require_class = __commonJS({
629
+ "lib/class.js"(exports2) {
407
630
  "use strict";
408
631
  var __importDefault = exports2 && exports2.__importDefault || function(mod) {
409
632
  return mod && mod.__esModule ? mod : { "default": mod };
410
633
  };
411
634
  Object.defineProperty(exports2, "__esModule", { value: true });
412
- exports2.globals = exports2.defaultGlobals = void 0;
413
- exports2.initializeState = initializeState;
414
- exports2.isGeneratedWorkletFile = isGeneratedWorkletFile;
415
- exports2.initializeGlobals = initializeGlobals;
416
- exports2.addCustomGlobals = addCustomGlobals;
417
- var path_1 = __importDefault(require("path"));
418
- var autoworkletization_12 = require_autoworkletization();
419
- var types_12 = require_types();
420
- var notCapturedIdentifiers = [
421
- // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
422
- // Note that objects' properties don't need to be listed since we always only capture the whole object,
423
- // e.g. `global.__ErrorUtils` or `Intl.DateTimeFormat`.
424
- // Value properties
425
- "globalThis",
426
- "Infinity",
427
- "NaN",
428
- "undefined",
429
- // Function properties
430
- "eval",
431
- "isFinite",
432
- "isNaN",
433
- "parseFloat",
434
- "parseInt",
435
- "decodeURI",
436
- "decodeURIComponent",
437
- "encodeURI",
438
- "encodeURIComponent",
439
- "escape",
440
- "unescape",
441
- // Fundamental objects
442
- "Object",
443
- "Function",
444
- "Boolean",
445
- "Symbol",
446
- // Error objects
447
- "Error",
448
- "AggregateError",
449
- "EvalError",
450
- "RangeError",
451
- "ReferenceError",
452
- "SyntaxError",
453
- "TypeError",
454
- "URIError",
455
- "InternalError",
456
- // Numbers and dates
457
- "Number",
458
- "BigInt",
459
- "Math",
460
- "Date",
461
- // Text processing
462
- "String",
463
- "RegExp",
464
- // Indexed collections
465
- "Array",
466
- "Int8Array",
467
- "Uint8Array",
468
- "Uint8ClampedArray",
469
- "Int16Array",
470
- "Uint16Array",
471
- "Int32Array",
472
- "Uint32Array",
473
- "BigInt64Array",
474
- "BigUint64Array",
475
- "Float32Array",
476
- "Float64Array",
477
- // Keyed collections
478
- "Map",
479
- "Set",
480
- "WeakMap",
481
- "WeakSet",
482
- // Structured data
483
- "ArrayBuffer",
484
- "SharedArrayBuffer",
485
- "DataView",
486
- "Atomics",
487
- "JSON",
488
- // Managing memory
489
- "WeakRef",
490
- "FinalizationRegistry",
491
- // Control abstraction objects
492
- "Iterator",
493
- "AsyncIterator",
494
- "Promise",
495
- "GeneratorFunction",
496
- "AsyncGeneratorFunction",
497
- "Generator",
498
- "AsyncGenerator",
499
- "AsyncFunction",
500
- // Reflection
501
- "Reflect",
502
- "Proxy",
503
- // Internationalization
504
- "Intl",
505
- // Other stuff
506
- "null",
507
- "this",
508
- "global",
509
- "window",
510
- "globalThis",
511
- "self",
512
- "console",
513
- "performance",
514
- "arguments",
515
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
516
- "require",
517
- "fetch",
518
- "XMLHttpRequest",
519
- "WebSocket",
520
- // Run loop
521
- "queueMicrotask",
522
- "requestAnimationFrame",
523
- "cancelAnimationFrame",
524
- "setTimeout",
525
- "clearTimeout",
526
- "setImmediate",
527
- "clearImmediate",
528
- "setInterval",
529
- "clearInterval",
530
- // Hermes
531
- "HermesInternal",
532
- // Worklets
533
- "_WORKLET"
534
- ];
535
- function initializeState(state) {
536
- var _a, _b;
537
- state.skipFile = isGeneratedWorkletFile(state.file.opts.filename);
538
- if (state.skipFile) {
539
- return;
635
+ exports2.processIfWorkletClass = processIfWorkletClass;
636
+ var generator_1 = __importDefault(require("@babel/generator"));
637
+ var traverse_1 = __importDefault(require("@babel/traverse"));
638
+ var types_12 = require("@babel/types");
639
+ var assert_1 = require("assert");
640
+ var transform_1 = require_transform();
641
+ var types_2 = require_types();
642
+ var utils_1 = require_utils();
643
+ var classWorkletMarker = "__workletClass";
644
+ function processIfWorkletClass(classPath, state) {
645
+ if (!isWorkletizableClass(classPath, state) || state.opts.bundleMode) {
646
+ return false;
540
647
  }
541
- state.workletNumber = 1;
542
- state.classesToWorkletize = [];
543
- state.autoworkletizationPlugin = {
544
- name: "worklets-autoworkletization",
545
- visitor: {
546
- CallExpression: {
547
- enter(nodePath) {
548
- (0, autoworkletization_12.processCalleesAutoworkletizableCallbacks)(nodePath, state);
549
- }
648
+ removeWorkletClassMarker(classPath.node.body);
649
+ processClass(classPath, state);
650
+ return true;
651
+ }
652
+ function processClass(classPath, state) {
653
+ (0, assert_1.strict)(classPath.node.id);
654
+ const className = classPath.node.id.name;
655
+ const polyfilledClassAst = getPolyfilledAst(classPath.node, state);
656
+ sortPolyfills(polyfilledClassAst);
657
+ appendWorkletDirectiveToPolyfills(polyfilledClassAst.program.body);
658
+ replaceClassDeclarationWithFactoryAndCall(polyfilledClassAst.program.body, className);
659
+ polyfilledClassAst.program.body.push((0, types_12.returnStatement)((0, types_12.identifier)(className)));
660
+ const factoryFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([...polyfilledClassAst.program.body]));
661
+ const factoryCall = (0, types_12.callExpression)(factoryFactory, []);
662
+ (0, utils_1.replaceWithFactoryCall)(classPath, className, factoryCall);
663
+ }
664
+ function getPolyfilledAst(classNode, state) {
665
+ var _a;
666
+ const classCode = (0, generator_1.default)(classNode).code;
667
+ const classWithPolyfills = (0, transform_1.workletTransformSync)(classCode, {
668
+ extraPlugins: [
669
+ "@babel/plugin-transform-class-properties",
670
+ "@babel/plugin-transform-classes",
671
+ "@babel/plugin-transform-unicode-regex",
672
+ ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
673
+ ],
674
+ extraPresets: state.opts.extraPresets,
675
+ filename: state.file.opts.filename,
676
+ ast: true,
677
+ babelrc: false,
678
+ configFile: false
679
+ });
680
+ (0, assert_1.strict)(classWithPolyfills && classWithPolyfills.ast);
681
+ return classWithPolyfills.ast;
682
+ }
683
+ function appendWorkletDirectiveToPolyfills(statements) {
684
+ statements.forEach((statement) => {
685
+ if ((0, types_12.isFunctionDeclaration)(statement)) {
686
+ const workletDirective = (0, types_12.directive)((0, types_12.directiveLiteral)("worklet"));
687
+ statement.body.directives.push(workletDirective);
688
+ }
689
+ });
690
+ }
691
+ function replaceClassDeclarationWithFactoryAndCall(statements, className) {
692
+ const classFactoryName = className + types_2.workletClassFactorySuffix;
693
+ const classDeclarationIndex = getPolyfilledClassDeclarationIndex(statements, className);
694
+ const classDeclarationToReplace = statements[classDeclarationIndex];
695
+ const classDeclarationInit = classDeclarationToReplace.declarations[0].init;
696
+ const classFactoryDeclaration = (0, types_12.functionDeclaration)((0, types_12.identifier)(classFactoryName), [], (0, types_12.blockStatement)([
697
+ (0, types_12.variableDeclaration)("const", [
698
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(className), classDeclarationInit)
699
+ ]),
700
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(className), (0, types_12.identifier)(classFactoryName)), (0, types_12.identifier)(classFactoryName))),
701
+ (0, types_12.returnStatement)((0, types_12.identifier)(className))
702
+ ], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
703
+ const newClassDeclaration = (0, types_12.variableDeclaration)("const", [
704
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(className), (0, types_12.callExpression)((0, types_12.identifier)(classFactoryName), []))
705
+ ]);
706
+ statements.splice(classDeclarationIndex, 1, classFactoryDeclaration, newClassDeclaration);
707
+ }
708
+ function getPolyfilledClassDeclarationIndex(statements, className) {
709
+ const index = statements.findIndex((statement) => (0, types_12.isVariableDeclaration)(statement) && statement.declarations.some((declaration) => (0, types_12.isIdentifier)(declaration.id) && declaration.id.name === className));
710
+ (0, assert_1.strict)(index >= 0);
711
+ return index;
712
+ }
713
+ function hasWorkletClassMarker(classBody) {
714
+ return classBody.body.some((statement) => (0, types_12.isClassProperty)(statement) && (0, types_12.isIdentifier)(statement.key) && statement.key.name === classWorkletMarker);
715
+ }
716
+ function removeWorkletClassMarker(classBody) {
717
+ classBody.body = classBody.body.filter((statement) => !(0, types_12.isClassProperty)(statement) || !(0, types_12.isIdentifier)(statement.key) || statement.key.name !== classWorkletMarker);
718
+ }
719
+ function sortPolyfills(ast) {
720
+ const toSort = getPolyfillsToSort(ast);
721
+ const sorted = topoSort(toSort);
722
+ const toSortIndices = toSort.map((element) => element.index);
723
+ const sortedIndices = sorted.map((element) => element.index);
724
+ const statements = ast.program.body;
725
+ const oldStatements = [...statements];
726
+ for (let i = 0; i < toSort.length; i++) {
727
+ const sourceIndex = sortedIndices[i];
728
+ const targetIndex = toSortIndices[i];
729
+ const source = oldStatements[sourceIndex];
730
+ statements[targetIndex] = source;
731
+ }
732
+ }
733
+ function getPolyfillsToSort(ast) {
734
+ const polyfills = [];
735
+ (0, traverse_1.default)(ast, {
736
+ Program: {
737
+ enter: (functionPath) => {
738
+ const statements = functionPath.get("body");
739
+ statements.forEach((statement, index) => {
740
+ var _a;
741
+ const bindingIdentifiers = statement.getBindingIdentifiers();
742
+ if (!statement.isFunctionDeclaration() || !((_a = statement.node.id) === null || _a === void 0 ? void 0 : _a.name)) {
743
+ return;
744
+ }
745
+ const element = {
746
+ name: statement.node.id.name,
747
+ index,
748
+ dependencies: /* @__PURE__ */ new Set()
749
+ };
750
+ polyfills.push(element);
751
+ statement.traverse({
752
+ Identifier(path) {
753
+ if (isOutsideDependency(path, bindingIdentifiers, statement)) {
754
+ element.dependencies.add(path.node.name);
755
+ }
756
+ }
757
+ });
758
+ });
550
759
  }
551
760
  }
552
- };
553
- if (!state.opts.strictGlobal) {
554
- initializeGlobals();
555
- addCustomGlobals(state);
761
+ });
762
+ return polyfills;
763
+ }
764
+ function topoSort(toSort) {
765
+ const sorted = [];
766
+ const stack = /* @__PURE__ */ new Set();
767
+ for (const element of toSort) {
768
+ recursiveTopoSort(element, toSort, sorted, stack);
556
769
  }
557
- const userImportForwarding = state.opts.importForwarding;
558
- state.opts.importForwarding = {
559
- relativePaths: [
560
- ...defaultAllowedPaths,
561
- ...(_a = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.relativePaths) !== null && _a !== void 0 ? _a : []
562
- ],
563
- moduleNames: [
564
- ...defaultAllowedModules,
565
- ...(_b = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.moduleNames) !== null && _b !== void 0 ? _b : []
566
- ]
567
- };
770
+ return sorted;
568
771
  }
569
- function isGeneratedWorkletFile(filename) {
570
- if (!filename) {
571
- return false;
772
+ function recursiveTopoSort(current, toSort, sorted, stack) {
773
+ if (stack.has(current.name)) {
774
+ throw new Error("Cycle detected. This should never happen.");
572
775
  }
573
- const generatedWorkletsDirPath = path_1.default.join("react-native-worklets", types_12.generatedWorkletsDir);
574
- return filename.includes(generatedWorkletsDirPath);
776
+ if (sorted.find((element) => element.name === current.name)) {
777
+ return;
778
+ }
779
+ stack.add(current.name);
780
+ for (const dependency of current.dependencies) {
781
+ if (!sorted.find((element) => element.name === dependency)) {
782
+ const next = toSort.find((element) => element.name === dependency);
783
+ (0, assert_1.strict)(next);
784
+ recursiveTopoSort(next, toSort, sorted, stack);
785
+ }
786
+ }
787
+ sorted.push(current);
788
+ stack.delete(current.name);
575
789
  }
576
- exports2.defaultGlobals = new Set(notCapturedIdentifiers);
577
- function initializeGlobals() {
578
- exports2.globals = new Set(exports2.defaultGlobals);
790
+ function isOutsideDependency(identifierPath, bindingIdentifiers, functionPath) {
791
+ return (
792
+ // We don't care about identifiers that were just declared.
793
+ identifierPath.isReferencedIdentifier() && // We don't care about identifiers that are bound in the scope.
794
+ !(identifierPath.node.name in bindingIdentifiers) && // This I don't exactly understand, but the function identifier itself isn't in `bindingIdentifiers`,
795
+ // but it return true on `hasOwnBinding`.
796
+ !functionPath.scope.hasOwnBinding(identifierPath.node.name) && // `hasReference` returns true for global identifiers, like `Object`,
797
+ // we don't want to include those.
798
+ functionPath.scope.hasReference(identifierPath.node.name)
799
+ );
579
800
  }
580
- var defaultAllowedPaths = ["react-native-worklets"];
581
- var defaultAllowedModules = [
582
- "react-native-worklets",
583
- "react-native/Libraries/Core/setUpXHR"
584
- ];
585
- function addCustomGlobals(state) {
586
- if (state.opts && Array.isArray(state.opts.globals)) {
587
- state.opts.globals.forEach((name) => {
588
- exports2.globals.add(name);
589
- });
801
+ function isWorkletizableClass(classPath, state) {
802
+ var _a;
803
+ const className = (_a = classPath.node.id) === null || _a === void 0 ? void 0 : _a.name;
804
+ const classNode = classPath.node;
805
+ if (!className) {
806
+ return false;
590
807
  }
808
+ const isMarked = hasWorkletClassMarker(classNode.body);
809
+ const isMemoizedNode = state.classesToWorkletize.some((record) => record.node === classNode);
810
+ const isTopLevelMemoizedName = classPath.parentPath.isProgram() && state.classesToWorkletize.some((record) => record.name === className);
811
+ state.classesToWorkletize = state.classesToWorkletize.filter((record) => record.node !== classNode && record.name !== className);
812
+ const result = isMarked || isMemoizedNode || isTopLevelMemoizedName;
813
+ return result;
591
814
  }
592
815
  }
593
816
  });
594
817
 
595
- // lib/imports.js
596
- var require_imports = __commonJS({
597
- "lib/imports.js"(exports2) {
818
+ // lib/classMethod.js
819
+ var require_classMethod = __commonJS({
820
+ "lib/classMethod.js"(exports2) {
598
821
  "use strict";
599
822
  Object.defineProperty(exports2, "__esModule", { value: true });
600
- exports2.updateRelativeRequires = updateRelativeRequires;
601
- exports2.isImport = isImport;
602
- exports2.isImportRelative = isImportRelative;
603
- exports2.canForwardModuleImport = canForwardModuleImport;
604
- exports2.canForwardRelativeImport = canForwardRelativeImport;
605
- exports2.createImportPathLiteral = createImportPathLiteral;
606
- var core_1 = require("@babel/core");
823
+ exports2.processIfWorkletMethod = processIfWorkletMethod;
607
824
  var types_12 = require("@babel/types");
608
- var path_1 = require("path");
609
- var types_2 = require_types();
610
- function updateRelativeRequires(node, state) {
611
- (0, core_1.traverse)(node, {
612
- noScope: true,
613
- CallExpression(nodePath) {
614
- var _a;
615
- if (nodePath.get("callee").isIdentifier({ name: "require" }) && ((_a = nodePath.get("arguments")[0]) === null || _a === void 0 ? void 0 : _a.isStringLiteral())) {
616
- const requiredModule = nodePath.get("arguments")[0];
617
- if (requiredModule.node.value.startsWith(".") && canForwardRelativeImport(state.file.opts.filename || "", state.opts.importForwarding.relativePaths)) {
618
- requiredModule.replaceWith(createImportPathLiteral(requiredModule.node.value, state));
619
- }
620
- }
621
- }
622
- });
825
+ var assert_1 = require("assert");
826
+ function processIfWorkletMethod(path) {
827
+ if (path.node.body.directives.some((d) => d.value.value === "worklet")) {
828
+ (0, assert_1.strict)((0, types_12.isIdentifier)(path.node.key), "ClassMethod key must be an Identifier");
829
+ const methodIdentifier = path.node.key;
830
+ path.replaceWith((0, types_12.classProperty)((0, types_12.cloneNode)(methodIdentifier, true), (0, types_12.functionExpression)((0, types_12.cloneNode)(methodIdentifier, true), path.node.params.filter((p) => (0, types_12.isFunctionParameter)(p)).map((p) => (0, types_12.cloneNode)(p, true)), (0, types_12.cloneNode)(path.node.body, true), path.node.generator, path.node.async)));
831
+ }
623
832
  }
624
- function isImport(binding) {
625
- return binding.kind === "module" && binding.constant && (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration();
833
+ }
834
+ });
835
+
836
+ // lib/contextObject.js
837
+ var require_contextObject = __commonJS({
838
+ "lib/contextObject.js"(exports2) {
839
+ "use strict";
840
+ Object.defineProperty(exports2, "__esModule", { value: true });
841
+ exports2.contextObjectMarker = void 0;
842
+ exports2.processIfWorkletContextObject = processIfWorkletContextObject;
843
+ exports2.isContextObject = isContextObject;
844
+ var types_12 = require("@babel/types");
845
+ exports2.contextObjectMarker = "__workletContextObject";
846
+ function processIfWorkletContextObject(path, _state) {
847
+ if (!isContextObject(path.node)) {
848
+ return false;
849
+ }
850
+ removeContextObjectMarker(path.node);
851
+ processWorkletContextObject(path.node);
852
+ return true;
626
853
  }
627
- function isImportRelative(imported) {
628
- return imported.path.parentPath.node.source.value.startsWith(".");
629
- }
630
- function canForwardModuleImport(moduleName, forwardableModuleNames) {
631
- return forwardableModuleNames.some((forwardableModuleName) => moduleName === forwardableModuleName || moduleName.startsWith(forwardableModuleName + "/"));
632
- }
633
- function canForwardRelativeImport(modulePath, relativePaths) {
634
- return !!modulePath && relativePaths.some((relativePath) => matchesFilenameSegment(modulePath, relativePath));
854
+ function isContextObject(objectExpression) {
855
+ return objectExpression.properties.some((property) => (0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker);
635
856
  }
636
- function matchesFilenameSegment(filename, allowedPath) {
637
- const pkgSegments = allowedPath.split(path_1.posix.sep);
638
- let fileSegments = filename.split(path_1.sep);
639
- const lastNodeModules = fileSegments.lastIndexOf("node_modules");
640
- if (lastNodeModules !== -1) {
641
- fileSegments = fileSegments.slice(lastNodeModules + 1);
642
- }
643
- for (let i = 0; i <= fileSegments.length - pkgSegments.length; i++) {
644
- if (pkgSegments.every((segment, segmentIndex) => fileSegments[i + segmentIndex] === segment)) {
645
- return true;
646
- }
647
- }
648
- return false;
857
+ function processWorkletContextObject(objectExpression) {
858
+ const workletObjectFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([(0, types_12.returnStatement)((0, types_12.cloneNode)(objectExpression))], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
859
+ objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${exports2.contextObjectMarker}Factory`), workletObjectFactory));
649
860
  }
650
- function createImportPathLiteral(originalPath, state) {
651
- const generatedWorkletsDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
652
- const resolved = (0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), originalPath);
653
- const relativePath = (0, path_1.relative)(generatedWorkletsDirPath, resolved);
654
- return (0, types_12.stringLiteral)(path_1.sep === "/" ? relativePath : relativePath.split(path_1.sep).join("/"));
861
+ function removeContextObjectMarker(objectExpression) {
862
+ objectExpression.properties = objectExpression.properties.filter((property) => !((0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker));
655
863
  }
656
864
  }
657
865
  });
658
866
 
659
- // lib/closure.js
660
- var require_closure = __commonJS({
661
- "lib/closure.js"(exports2) {
867
+ // lib/file.js
868
+ var require_file = __commonJS({
869
+ "lib/file.js"(exports2) {
662
870
  "use strict";
663
871
  Object.defineProperty(exports2, "__esModule", { value: true });
664
- exports2.getClosure = getClosure;
872
+ exports2.processIfWorkletFile = processIfWorkletFile;
873
+ exports2.isImplicitContextObject = isImplicitContextObject;
665
874
  var types_12 = require("@babel/types");
666
- var globals_12 = require_globals();
667
- var imports_1 = require_imports();
668
- function getClosure(funPath, state) {
669
- const capturedNames = /* @__PURE__ */ new Set();
670
- const closureVariables = new Array();
671
- const moduleBindingsToImport = /* @__PURE__ */ new Set();
672
- const relativeBindingsToImport = /* @__PURE__ */ new Set();
673
- let recrawled = false;
674
- funPath.traverse({
675
- "TSType|TSTypeAliasDeclaration|TSInterfaceDeclaration"(typePath) {
676
- typePath.skip();
677
- },
678
- ReferencedIdentifier(idPath) {
679
- if (idPath.isJSXIdentifier() && !state.opts.bundleMode) {
680
- return;
681
- }
682
- const name = idPath.node.name;
683
- if (capturedNames.has(name)) {
684
- return;
685
- }
686
- let binding = idPath.scope.getBinding(name);
687
- if (!binding && !recrawled) {
688
- recrawled = true;
689
- idPath.scope.crawl();
690
- binding = idPath.scope.getBinding(name);
691
- }
692
- if (!binding) {
693
- if (state.opts.strictGlobal || globals_12.globals.has(name)) {
694
- return;
695
- }
696
- capturedNames.add(name);
697
- closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
698
- return;
699
- }
700
- if ("id" in funPath.node) {
701
- const id = idPath.scope.getBindingIdentifier(name);
702
- if (id && id === funPath.node.id) {
703
- return;
704
- }
705
- }
706
- let scope = idPath.scope;
707
- while (scope !== funPath.scope.parent) {
708
- if (scope.hasOwnBinding(name)) {
709
- return;
710
- }
711
- scope = scope.parent;
712
- }
713
- if (state.opts.bundleMode && (0, imports_1.isImport)(binding)) {
714
- if ((0, imports_1.isImportRelative)(binding) && (0, imports_1.canForwardRelativeImport)(state.filename, state.opts.importForwarding.relativePaths)) {
715
- capturedNames.add(name);
716
- relativeBindingsToImport.add(binding);
717
- return;
718
- }
719
- const source = binding.path.parentPath.node.source.value;
720
- if ((0, imports_1.canForwardModuleImport)(source, state.opts.importForwarding.moduleNames)) {
721
- capturedNames.add(name);
722
- moduleBindingsToImport.add(binding);
723
- return;
724
- }
725
- }
726
- capturedNames.add(name);
727
- closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
875
+ var contextObject_12 = require_contextObject();
876
+ var directives_1 = require_directives();
877
+ var types_2 = require_types();
878
+ function processIfWorkletFile(path, state) {
879
+ if (!path.node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
880
+ return false;
881
+ }
882
+ path.node.directives = path.node.directives.filter((functionDirective) => functionDirective.value.value !== "worklet");
883
+ processWorkletFile(path, state);
884
+ return true;
885
+ }
886
+ function processWorkletFile(programPath, state) {
887
+ const statements = programPath.get("body");
888
+ dehoistCommonJSExports(programPath.node);
889
+ statements.forEach((statement) => {
890
+ const candidatePath = getCandidate(statement);
891
+ processWorkletizableEntity(candidatePath, state);
892
+ });
893
+ }
894
+ function getCandidate(statementPath) {
895
+ if (statementPath.isExportNamedDeclaration() || statementPath.isExportDefaultDeclaration()) {
896
+ return statementPath.get("declaration");
897
+ } else {
898
+ return statementPath;
899
+ }
900
+ }
901
+ function processWorkletizableEntity(nodePath, state) {
902
+ var _a;
903
+ if ((0, types_2.isWorkletizableFunctionPath)(nodePath)) {
904
+ if (nodePath.isArrowFunctionExpression()) {
905
+ (0, directives_1.replaceImplicitReturnWithBlock)(nodePath.node);
728
906
  }
729
- }, state);
730
- return {
731
- closureVariables,
732
- moduleBindingsToImport,
733
- relativeBindingsToImport
734
- };
907
+ (0, directives_1.addDirective)(nodePath.node.body, "worklet");
908
+ } else if ((0, types_2.isWorkletizableObjectPath)(nodePath)) {
909
+ if (isImplicitContextObject(nodePath)) {
910
+ appendWorkletContextObjectMarker(nodePath.node);
911
+ } else {
912
+ processWorkletAggregator(nodePath, state);
913
+ }
914
+ } else if (nodePath.isVariableDeclaration()) {
915
+ processVariableDeclaration(nodePath, state);
916
+ } else if (nodePath.isClassDeclaration()) {
917
+ appendWorkletClassMarker(nodePath.node.body);
918
+ if ((_a = nodePath.node.id) === null || _a === void 0 ? void 0 : _a.name) {
919
+ state.classesToWorkletize.push({
920
+ node: nodePath.node,
921
+ name: nodePath.node.id.name
922
+ });
923
+ }
924
+ }
925
+ }
926
+ function processVariableDeclaration(variableDeclarationPath, state) {
927
+ const declarations = variableDeclarationPath.get("declarations");
928
+ declarations.forEach((declaration) => {
929
+ const initPath = declaration.get("init");
930
+ if (initPath.isExpression()) {
931
+ processWorkletizableEntity(initPath, state);
932
+ }
933
+ });
934
+ }
935
+ function processWorkletAggregator(objectPath, state) {
936
+ const properties = objectPath.get("properties");
937
+ properties.forEach((property) => {
938
+ if (property.isObjectMethod()) {
939
+ (0, directives_1.addDirective)(property.node.body, "worklet");
940
+ } else if (property.isObjectProperty()) {
941
+ const valuePath = property.get("value");
942
+ processWorkletizableEntity(valuePath, state);
943
+ }
944
+ });
945
+ }
946
+ function appendWorkletContextObjectMarker(objectExpression) {
947
+ if (objectExpression.properties.some((value) => (0, types_12.isObjectProperty)(value) && (0, types_12.isIdentifier)(value.key) && value.key.name === contextObject_12.contextObjectMarker)) {
948
+ return;
949
+ }
950
+ objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${contextObject_12.contextObjectMarker}`), (0, types_12.booleanLiteral)(true)));
951
+ }
952
+ function isImplicitContextObject(path) {
953
+ const propertyPaths = path.get("properties");
954
+ return propertyPaths.some((propertyPath) => {
955
+ if (!propertyPath.isObjectMethod()) {
956
+ return false;
957
+ }
958
+ return hasThisExpression(propertyPath);
959
+ });
960
+ }
961
+ function hasThisExpression(path) {
962
+ let result = false;
963
+ path.traverse({
964
+ ThisExpression(thisPath) {
965
+ result = true;
966
+ thisPath.stop();
967
+ }
968
+ });
969
+ return result;
970
+ }
971
+ function appendWorkletClassMarker(classBody) {
972
+ classBody.body.push((0, types_12.classProperty)((0, types_12.identifier)("__workletClass"), (0, types_12.booleanLiteral)(true)));
973
+ }
974
+ function dehoistCommonJSExports(program) {
975
+ const statements = program.body;
976
+ let end = statements.length;
977
+ let current = 0;
978
+ while (current < end) {
979
+ const statement = statements[current];
980
+ if (!isCommonJSExport(statement)) {
981
+ current++;
982
+ continue;
983
+ }
984
+ const exportStatement = statements.splice(current, 1);
985
+ statements.push(...exportStatement);
986
+ end--;
987
+ }
988
+ }
989
+ function isCommonJSExport(statement) {
990
+ return (0, types_12.isExpressionStatement)(statement) && (0, types_12.isAssignmentExpression)(statement.expression) && (0, types_12.isMemberExpression)(statement.expression.left) && (0, types_12.isIdentifier)(statement.expression.left.object) && statement.expression.left.object.name === "exports";
735
991
  }
736
992
  }
737
993
  });
738
994
 
739
- // lib/generate.js
740
- var require_generate = __commonJS({
741
- "lib/generate.js"(exports2) {
995
+ // lib/globals.js
996
+ var require_globals = __commonJS({
997
+ "lib/globals.js"(exports2) {
742
998
  "use strict";
743
999
  var __importDefault = exports2 && exports2.__importDefault || function(mod) {
744
1000
  return mod && mod.__esModule ? mod : { "default": mod };
745
1001
  };
746
1002
  Object.defineProperty(exports2, "__esModule", { value: true });
747
- exports2.generateWorkletFile = generateWorkletFile;
748
- var core_1 = require("@babel/core");
749
- var types_12 = require("@babel/types");
750
- var assert_1 = __importDefault(require("assert"));
751
- var fs_1 = require("fs");
752
- var path_1 = require("path");
753
- var imports_1 = require_imports();
754
- var types_2 = require_types();
755
- function generateWorkletFile(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state) {
756
- var _a;
757
- const libraryImports = Array.from(moduleBindingsToImport).filter((binding) => (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, types_12.stringLiteral)(binding.path.parentPath.node.source.value)));
758
- const filesDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
759
- const relativeImports = Array.from(relativeBindingsToImport).filter((binding) => binding.path.isImportSpecifier() && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, imports_1.createImportPathLiteral)(binding.path.parentPath.node.source.value, state)));
760
- const imports = [...libraryImports, ...relativeImports];
761
- const newProg = (0, types_12.program)([...imports, (0, types_12.exportDefaultDeclaration)(factory)]);
762
- const transformedProg = (_a = (0, core_1.transformFromAstSync)(newProg, void 0, {
763
- filename: state.file.opts.filename,
764
- presets: [resolvePresetTypescript()],
765
- plugins: [state.autoworkletizationPlugin, stripJsxDevAttributesPlugin],
766
- ast: false,
767
- babelrc: false,
768
- configFile: false,
769
- comments: false
770
- })) === null || _a === void 0 ? void 0 : _a.code;
771
- (0, assert_1.default)(transformedProg, "[Worklets] `transformedProg` is undefined.");
772
- const dedicatedFilePath = (0, path_1.resolve)(filesDirPath, `${workletHash}.js`);
773
- (0, fs_1.writeFileSync)(dedicatedFilePath, transformedProg);
774
- }
775
- function resolvePresetTypescript() {
776
- try {
777
- return require.resolve("@babel/preset-typescript");
778
- } catch (_a) {
779
- return require.resolve("@babel/preset-typescript", {
780
- paths: [(0, path_1.dirname)(require.resolve("react-native-worklets/package.json"))]
781
- });
782
- }
783
- }
784
- var stripJsxDevAttributesPlugin = {
785
- name: "worklets-strip-jsx-dev-attributes",
786
- visitor: {
787
- JSXAttribute(path) {
788
- const name = path.node.name;
789
- if (name.type !== "JSXIdentifier") {
790
- return;
791
- }
792
- if (name.name !== "__self" && name.name !== "__source") {
793
- return;
794
- }
795
- path.remove();
796
- }
797
- }
798
- };
799
- }
800
- });
801
-
802
- // lib/hermesBytecode.js
803
- var require_hermesBytecode = __commonJS({
804
- "lib/hermesBytecode.js"(exports2) {
805
- "use strict";
806
- Object.defineProperty(exports2, "__esModule", { value: true });
807
- exports2.compileWorkletToHbc = compileWorkletToHbc;
808
- var core_1 = require("@babel/core");
809
- var child_process_1 = require("child_process");
810
- function compileWorkletToHbc(funString, workletHash, state) {
811
- if (compilationCache.has(workletHash)) {
812
- return compilationCache.get(workletHash);
813
- }
814
- const result = compile(funString, state);
815
- compilationCache.set(workletHash, result);
816
- return result;
817
- }
818
- function compile(funString, state) {
819
- const hermesc = resolveHbcBinary(state);
820
- if (!hermesc) {
821
- return null;
822
- }
823
- try {
824
- return runHermesc(hermesc, funString);
825
- } catch (error) {
826
- if (getErrorOutput(error).includes("JSX")) {
827
- const transformed = transformJsx(funString);
828
- if (transformed !== null) {
829
- try {
830
- return runHermesc(hermesc, transformed);
831
- } catch (retryError) {
832
- return warnFallback(retryError);
833
- }
834
- }
835
- }
836
- return warnFallback(error);
837
- }
838
- }
839
- var MAX_BYTECODE_BYTES = 256 * 1024 * 1024;
840
- var compilationCache = /* @__PURE__ */ new Map();
841
- var warnedMessages = /* @__PURE__ */ new Set();
842
- function warnOnce(message) {
843
- if (warnedMessages.has(message)) {
844
- return;
845
- }
846
- warnedMessages.add(message);
847
- console.warn(`[Worklets] ${message}`);
848
- }
849
- function resolveHbcBinary(state) {
850
- const { getHBCBinary } = state.opts;
851
- if (!getHBCBinary) {
852
- warnOnce("The `getHBCBinary` plugin option is required to compile worklets to Hermes bytecode. Falling back to shipping worklets as source strings.");
853
- return null;
854
- }
855
- try {
856
- const binary = getHBCBinary();
857
- if (!binary) {
858
- throw new Error("`getHBCBinary` returned an empty path.");
859
- }
860
- return binary;
861
- } catch (error) {
862
- warnOnce(`Calling \`getHBCBinary\` failed, falling back to a source string. ${error instanceof Error ? error.message : String(error)}`);
863
- return null;
864
- }
865
- }
866
- function runHermesc(hermesc, source) {
867
- return (0, child_process_1.execFileSync)(hermesc, ["-g0", "-emit-binary", "-O", "-w", "-"], {
868
- input: source,
869
- maxBuffer: MAX_BYTECODE_BYTES,
870
- stdio: ["pipe", "pipe", "pipe"]
871
- });
872
- }
873
- function getErrorOutput(error) {
874
- const stderr = error === null || error === void 0 ? void 0 : error.stderr;
875
- if (stderr) {
876
- return stderr.toString();
877
- }
878
- return error instanceof Error ? error.message : String(error);
879
- }
880
- function warnFallback(error) {
881
- const reason = getErrorOutput(error).trim().split("\n")[0];
882
- warnOnce(`Could not compile a worklet to Hermes bytecode, falling back to a source string. ${reason}`);
883
- return null;
884
- }
885
- var jsxPluginPath;
886
- function resolveJsxPlugin() {
887
- if (jsxPluginPath === void 0) {
888
- try {
889
- jsxPluginPath = require.resolve("@babel/plugin-transform-react-jsx");
890
- } catch (_a) {
891
- jsxPluginPath = null;
892
- }
893
- }
894
- return jsxPluginPath;
895
- }
896
- function transformJsx(source) {
897
- var _a;
898
- const plugin = resolveJsxPlugin();
899
- if (!plugin) {
900
- return null;
901
- }
902
- try {
903
- const result = (0, core_1.transformSync)(source, {
904
- babelrc: false,
905
- configFile: false,
906
- compact: true,
907
- plugins: [plugin]
908
- });
909
- return (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : null;
910
- } catch (_b) {
911
- return null;
912
- }
913
- }
914
- }
915
- });
916
-
917
- // lib/transform.js
918
- var require_transform = __commonJS({
919
- "lib/transform.js"(exports2) {
920
- "use strict";
921
- var __rest = exports2 && exports2.__rest || function(s, e) {
922
- var t = {};
923
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
924
- t[p] = s[p];
925
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
926
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
927
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
928
- t[p[i]] = s[p[i]];
929
- }
930
- return t;
931
- };
932
- Object.defineProperty(exports2, "__esModule", { value: true });
933
- exports2.workletTransformSync = workletTransformSync;
934
- var core_1 = require("@babel/core");
935
- function workletTransformSync(code, opts) {
936
- const { extraPlugins = [], extraPresets = [] } = opts, rest = __rest(opts, ["extraPlugins", "extraPresets"]);
937
- return (0, core_1.transformSync)(code, Object.assign(Object.assign({}, rest), { plugins: [...defaultPlugins, ...extraPlugins], presets: [...defaultPresets, ...extraPresets] }));
938
- }
939
- var defaultPresets = [
940
- require.resolve("@babel/preset-typescript")
941
- ];
942
- var defaultPlugins = [];
943
- }
944
- });
945
-
946
- // lib/workletStringCode.js
947
- var require_workletStringCode = __commonJS({
948
- "lib/workletStringCode.js"(exports2) {
949
- "use strict";
950
- var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
951
- if (k2 === void 0) k2 = k;
952
- var desc = Object.getOwnPropertyDescriptor(m, k);
953
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
954
- desc = { enumerable: true, get: function() {
955
- return m[k];
956
- } };
957
- }
958
- Object.defineProperty(o, k2, desc);
959
- }) : (function(o, m, k, k2) {
960
- if (k2 === void 0) k2 = k;
961
- o[k2] = m[k];
962
- }));
963
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
964
- Object.defineProperty(o, "default", { enumerable: true, value: v });
965
- }) : function(o, v) {
966
- o["default"] = v;
967
- });
968
- var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
969
- var ownKeys = function(o) {
970
- ownKeys = Object.getOwnPropertyNames || function(o2) {
971
- var ar = [];
972
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
973
- return ar;
974
- };
975
- return ownKeys(o);
976
- };
977
- return function(mod) {
978
- if (mod && mod.__esModule) return mod;
979
- var result = {};
980
- if (mod != null) {
981
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
982
- }
983
- __setModuleDefault(result, mod);
984
- return result;
985
- };
986
- })();
987
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
988
- return mod && mod.__esModule ? mod : { "default": mod };
989
- };
990
- Object.defineProperty(exports2, "__esModule", { value: true });
991
- exports2.buildWorkletString = buildWorkletString;
992
- var core_1 = require("@babel/core");
993
- var generator_1 = __importDefault(require("@babel/generator"));
994
- var types_12 = require("@babel/types");
995
- var assert_1 = require("assert");
996
- var convertSourceMap = __importStar(require("convert-source-map"));
997
- var fs = __importStar(require("fs"));
998
- var transform_1 = require_transform();
999
- var types_2 = require_types();
1000
- var utils_1 = require_utils();
1001
- var MOCK_SOURCE_MAP = "mock source map";
1002
- var querySuffixRE = /[?#].*$/;
1003
- function buildWorkletString(fun, state, closureVariables, workletName, inputMap) {
1004
- var _a;
1005
- restoreRecursiveCalls(fun, workletName);
1006
- const draftExpression = fun.program.body.find((obj) => (0, types_12.isFunctionDeclaration)(obj)) || fun.program.body.find((obj) => (0, types_12.isExpressionStatement)(obj));
1007
- (0, assert_1.strict)(draftExpression, "`draftExpression` is undefined.");
1008
- const expression = (0, types_12.isFunctionDeclaration)(draftExpression) ? draftExpression : draftExpression.expression;
1009
- (0, assert_1.strict)("params" in expression, "'params' property is undefined in 'expression'");
1010
- (0, assert_1.strict)((0, types_12.isBlockStatement)(expression.body), "`expression.body` is not a `BlockStatement`");
1011
- const parsedClasses = /* @__PURE__ */ new Set();
1012
- if (!state.opts.disableWorkletClasses) {
1013
- (0, core_1.traverse)(fun, {
1014
- NewExpression(path) {
1015
- if (!(0, types_12.isIdentifier)(path.node.callee)) {
1016
- return;
1017
- }
1018
- const constructorName = path.node.callee.name;
1019
- if (!closureVariables.some((variable) => variable.name === constructorName) || parsedClasses.has(constructorName)) {
1020
- return;
1021
- }
1022
- const index = closureVariables.findIndex((variable) => variable.name === constructorName);
1023
- closureVariables.splice(index, 1);
1024
- const workletClassFactoryName = constructorName + types_2.workletClassFactorySuffix;
1025
- closureVariables.push((0, types_12.identifier)(workletClassFactoryName));
1026
- (0, types_12.assertBlockStatement)(expression.body);
1027
- expression.body.body.unshift((0, types_12.variableDeclaration)("const", [
1028
- (0, types_12.variableDeclarator)((0, types_12.identifier)(constructorName), (0, types_12.callExpression)((0, types_12.identifier)(workletClassFactoryName), []))
1029
- ]));
1030
- parsedClasses.add(constructorName);
1031
- }
1032
- });
1033
- }
1034
- const workletFunction = (0, types_12.functionExpression)((0, types_12.identifier)(workletName), expression.params, expression.body, expression.generator, expression.async);
1035
- const code = (0, generator_1.default)(workletFunction).code;
1036
- (0, assert_1.strict)(inputMap, "`inputMap` is undefined.");
1037
- const includeSourceMap = !((0, utils_1.isRelease)(state) || state.opts.disableSourceMaps);
1038
- if (includeSourceMap) {
1039
- inputMap.sourcesContent = [];
1040
- for (const sourceFile of inputMap.sources) {
1041
- inputMap.sourcesContent.push(fs.readFileSync(sourceFile.replace(querySuffixRE, "")).toString("utf-8"));
1042
- }
1043
- }
1044
- const transformed = (0, transform_1.workletTransformSync)(code, {
1045
- filename: state.file.opts.filename,
1046
- extraPlugins: [
1047
- getClosurePlugin(closureVariables),
1048
- ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1049
- ],
1050
- extraPresets: state.opts.extraPresets,
1051
- compact: true,
1052
- sourceMaps: includeSourceMap,
1053
- inputSourceMap: inputMap,
1054
- ast: false,
1055
- babelrc: false,
1056
- configFile: false,
1057
- comments: false
1058
- });
1059
- (0, assert_1.strict)(transformed, "`transformed` is null.");
1060
- let sourceMap;
1061
- if (includeSourceMap) {
1062
- if (shouldMockSourceMap()) {
1063
- sourceMap = MOCK_SOURCE_MAP;
1064
- } else {
1065
- sourceMap = convertSourceMap.fromObject(transformed.map).toObject();
1066
- delete sourceMap.sourcesContent;
1067
- }
1068
- }
1069
- const wrappedCode = `(${transformed.code})`;
1070
- return [wrappedCode, JSON.stringify(sourceMap)];
1071
- }
1072
- function restoreRecursiveCalls(file, newName) {
1073
- (0, core_1.traverse)(file, {
1074
- FunctionExpression(path) {
1075
- if (!path.node.id) {
1076
- path.stop();
1077
- return;
1078
- }
1079
- const oldName = path.node.id.name;
1080
- const scope = path.scope;
1081
- scope.rename(oldName, newName);
1082
- }
1083
- });
1084
- }
1085
- function shouldMockSourceMap() {
1086
- return process.env.WORKLETS_JEST_SHOULD_MOCK_SOURCE_MAP === "1";
1087
- }
1088
- function prependClosure(path, closureVariables, closureDeclaration) {
1089
- if (closureVariables.length === 0 || !(0, types_12.isProgram)(path.parent)) {
1090
- return;
1091
- }
1092
- if (!(0, types_12.isExpression)(path.node.body)) {
1093
- path.node.body.body.unshift(closureDeclaration);
1094
- }
1095
- }
1096
- function prependRecursiveDeclaration(path) {
1097
- var _a;
1098
- if ((0, types_12.isProgram)(path.parent) && !(0, types_12.isArrowFunctionExpression)(path.node) && !(0, types_12.isObjectMethod)(path.node) && path.node.id && path.scope.parent) {
1099
- const hasRecursiveCalls = ((_a = path.scope.parent.bindings[path.node.id.name]) === null || _a === void 0 ? void 0 : _a.references) > 0;
1100
- if (hasRecursiveCalls) {
1101
- path.node.body.body.unshift((0, types_12.variableDeclaration)("const", [
1102
- (0, types_12.variableDeclarator)((0, types_12.identifier)(path.node.id.name), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("_recur")))
1103
- ]));
1104
- }
1105
- }
1106
- }
1107
- function getClosurePlugin(closureVariables) {
1108
- const closureDeclaration = (0, types_12.variableDeclaration)("const", [
1109
- (0, types_12.variableDeclarator)((0, types_12.objectPattern)(closureVariables.map((variable) => (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.identifier)(variable.name), false, true))), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("__closure")))
1110
- ]);
1111
- return {
1112
- visitor: {
1113
- "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod": (path) => {
1114
- prependClosure(path, closureVariables, closureDeclaration);
1115
- prependRecursiveDeclaration(path);
1116
- }
1117
- }
1118
- };
1119
- }
1120
- }
1121
- });
1122
-
1123
- // lib/workletFactory.js
1124
- var require_workletFactory = __commonJS({
1125
- "lib/workletFactory.js"(exports2) {
1126
- "use strict";
1127
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1128
- return mod && mod.__esModule ? mod : { "default": mod };
1129
- };
1130
- Object.defineProperty(exports2, "__esModule", { value: true });
1131
- exports2.makeWorkletFactory = makeWorkletFactory;
1132
- var generator_1 = __importDefault(require("@babel/generator"));
1133
- var types_12 = require("@babel/types");
1134
- var assert_1 = require("assert");
1135
- var path_1 = require("path");
1136
- var closure_1 = require_closure();
1137
- var generate_1 = require_generate();
1138
- var hermesBytecode_1 = require_hermesBytecode();
1139
- var imports_1 = require_imports();
1140
- var transform_1 = require_transform();
1141
- var types_2 = require_types();
1142
- var utils_1 = require_utils();
1143
- var workletStringCode_1 = require_workletStringCode();
1144
- var REAL_VERSION = require("../package.json").version;
1145
- var MOCK_VERSION = "x.y.z";
1146
- function makeWorkletFactory(fun, state) {
1147
- var _a;
1148
- const includeClosure = state.opts.bundleMode || !hasDirective(fun, "no-worklet-closure");
1149
- const limitInitDataHoisting = hasDirective(fun, "limit-init-data-hoisting");
1150
- stripWorkletDirectives(fun);
1151
- (0, assert_1.strict)(state.file.opts.filename, "`state.file.opts.filename` is undefined.");
1152
- const codeObject = (0, generator_1.default)(fun.node, {
1153
- sourceMaps: true,
1154
- sourceFileName: state.file.opts.filename
1155
- });
1156
- codeObject.code = "(" + (fun.isObjectMethod() ? "function " : "") + codeObject.code + "\n)";
1157
- const transformed = (0, transform_1.workletTransformSync)(codeObject.code, {
1158
- extraPlugins: [...extraPlugins, ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []],
1159
- extraPresets: state.opts.extraPresets,
1160
- filename: state.file.opts.filename,
1161
- ast: true,
1162
- babelrc: false,
1163
- configFile: false,
1164
- inputSourceMap: codeObject.map
1165
- });
1166
- (0, assert_1.strict)(transformed, "`transformed` is undefined.");
1167
- (0, assert_1.strict)(transformed.ast, "`transformed.ast` is undefined.");
1168
- const { closureVariables, moduleBindingsToImport, relativeBindingsToImport } = includeClosure ? (0, closure_1.getClosure)(fun, state) : {
1169
- closureVariables: [],
1170
- moduleBindingsToImport: /* @__PURE__ */ new Set(),
1171
- relativeBindingsToImport: /* @__PURE__ */ new Set()
1172
- };
1173
- const clone = (0, types_12.cloneNode)(fun.node);
1174
- const funExpression = (0, types_12.isBlockStatement)(clone.body) ? (0, types_12.functionExpression)(null, clone.params, clone.body, clone.generator, clone.async) : clone;
1175
- const { workletName, reactName } = makeWorkletName(fun, state);
1176
- let mutatedClosureVariables;
1177
- if (state.opts.bundleMode) {
1178
- mutatedClosureVariables = closureVariables.map((variable) => (0, types_12.cloneNode)(variable, true));
1179
- } else {
1180
- mutatedClosureVariables = closureVariables;
1181
- }
1182
- let [funString, sourceMapString] = (0, workletStringCode_1.buildWorkletString)(transformed.ast, state, mutatedClosureVariables, workletName, transformed.map);
1183
- (0, assert_1.strict)(funString, "`funString` is undefined.");
1184
- const workletHash = hash(funString);
1185
- let lineOffset = 1;
1186
- if (closureVariables.length > 0) {
1187
- lineOffset -= closureVariables.length + 2;
1188
- }
1189
- const pathForStringDefinitions = fun.parentPath.isProgram() ? fun : fun.findParent((path) => {
1190
- var _a2, _b;
1191
- return (_b = (_a2 = path.parentPath) === null || _a2 === void 0 ? void 0 : _a2.isProgram()) !== null && _b !== void 0 ? _b : false;
1192
- });
1193
- (0, assert_1.strict)(pathForStringDefinitions, "`pathForStringDefinitions` is null.");
1194
- (0, assert_1.strict)(pathForStringDefinitions.parentPath, "`pathForStringDefinitions.parentPath` is null.");
1195
- const initDataId = pathForStringDefinitions.parentPath.scope.generateUidIdentifier(`worklet_${workletHash}_init_data`);
1196
- const shouldIncludeInitData = !state.opts.omitNativeOnlyData && !state.opts.bundleMode;
1197
- const shouldEmitBytecode = !!state.opts.hermesBytecode && (0, utils_1.isRelease)(state) && shouldIncludeInitData;
1198
- const bytecode = shouldEmitBytecode ? (0, hermesBytecode_1.compileWorkletToHbc)(funString, workletHash, state) : null;
1199
- const initDataObjectExpression = (0, types_12.objectExpression)(bytecode ? [
1200
- (0, types_12.objectProperty)((0, types_12.identifier)("bytecode"), (0, types_12.memberExpression)((0, types_12.newExpression)((0, types_12.identifier)("Uint8Array"), [
1201
- (0, types_12.arrayExpression)(Array.from(bytecode, (byte) => (0, types_12.numericLiteral)(byte)))
1202
- ]), (0, types_12.identifier)("buffer")))
1203
- ] : [(0, types_12.objectProperty)((0, types_12.identifier)("code"), (0, types_12.stringLiteral)(funString))]);
1204
- const shouldInjectLocation = !(0, utils_1.isRelease)(state);
1205
- if (shouldInjectLocation) {
1206
- let location = state.file.opts.filename;
1207
- if (state.opts.relativeSourceLocation) {
1208
- location = (0, path_1.relative)(state.cwd, location);
1209
- sourceMapString = sourceMapString === null || sourceMapString === void 0 ? void 0 : sourceMapString.replace(toPosix(state.file.opts.filename), toPosix(location));
1210
- }
1211
- location = toPosix(location);
1212
- initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("location"), (0, types_12.stringLiteral)(location)));
1213
- }
1214
- if (!bytecode && sourceMapString) {
1215
- initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("sourceMap"), (0, types_12.stringLiteral)(sourceMapString)));
1216
- }
1217
- if (shouldIncludeInitData) {
1218
- const initDataDeclaration = (0, types_12.variableDeclaration)("const", [
1219
- (0, types_12.variableDeclarator)(initDataId, initDataObjectExpression)
1220
- ]);
1221
- if (limitInitDataHoisting) {
1222
- fun.getFunctionParent().node.body.body.unshift(initDataDeclaration);
1223
- } else {
1224
- pathForStringDefinitions.insertBefore(initDataDeclaration);
1225
- }
1226
- }
1227
- (0, assert_1.strict)(!(0, types_12.isFunctionDeclaration)(funExpression), "`funExpression` is a `FunctionDeclaration`.");
1228
- (0, assert_1.strict)(!(0, types_12.isObjectMethod)(funExpression), "`funExpression` is an `ObjectMethod`.");
1229
- const statements = [
1230
- (0, types_12.variableDeclaration)("const", [
1231
- (0, types_12.variableDeclarator)((0, types_12.identifier)(reactName), funExpression)
1232
- ]),
1233
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__closure"), false), (0, types_12.objectExpression)(closureVariables.map((variable) => !state.opts.bundleMode && variable.name.endsWith(types_2.workletClassFactorySuffix) ? (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.memberExpression)((0, types_12.identifier)(variable.name.slice(0, variable.name.length - types_2.workletClassFactorySuffix.length)), (0, types_12.identifier)(variable.name))) : (0, types_12.objectProperty)((0, types_12.cloneNode)(variable, true), (0, types_12.cloneNode)(variable, true), false, true))))),
1234
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__workletHash"), false), (0, types_12.numericLiteral)(workletHash)))
1235
- ];
1236
- const shouldInjectVersion = !(0, utils_1.isRelease)(state);
1237
- if (shouldInjectVersion) {
1238
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__pluginVersion")), (0, types_12.stringLiteral)(shouldMockVersion() ? MOCK_VERSION : REAL_VERSION))));
1239
- }
1240
- if (shouldIncludeInitData) {
1241
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__initData"), false), (0, types_12.cloneNode)(initDataId, true))));
1242
- }
1243
- if (!(0, utils_1.isRelease)(state) && !state.opts.bundleMode) {
1244
- statements.unshift((0, types_12.variableDeclaration)("const", [
1245
- (0, types_12.variableDeclarator)((0, types_12.identifier)("_e"), (0, types_12.arrayExpression)([
1246
- (0, types_12.newExpression)((0, types_12.memberExpression)((0, types_12.identifier)("global"), (0, types_12.identifier)("Error")), []),
1247
- (0, types_12.numericLiteral)(lineOffset),
1248
- (0, types_12.numericLiteral)(-27)
1249
- // the placement of opening bracket after Exception in line that defined '_e' variable
1250
- ]))
1251
- ]));
1252
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__stackDetails"), false), (0, types_12.identifier)("_e"))));
1253
- }
1254
- statements.push((0, types_12.returnStatement)((0, types_12.identifier)(reactName)));
1255
- const factoryParams = closureVariables.map((variableId) => {
1256
- const clonedId = (0, types_12.cloneNode)(variableId, true);
1257
- if (!state.opts.bundleMode && clonedId.name.endsWith(types_2.workletClassFactorySuffix)) {
1258
- clonedId.name = clonedId.name.slice(0, clonedId.name.length - types_2.workletClassFactorySuffix.length);
1259
- }
1260
- return clonedId;
1261
- });
1262
- if (shouldIncludeInitData) {
1263
- factoryParams.unshift((0, types_12.cloneNode)(initDataId, true));
1003
+ exports2.globals = exports2.defaultGlobals = void 0;
1004
+ exports2.initializeState = initializeState;
1005
+ exports2.isGeneratedWorkletFile = isGeneratedWorkletFile;
1006
+ exports2.initializeGlobals = initializeGlobals;
1007
+ exports2.addCustomGlobals = addCustomGlobals;
1008
+ var path_1 = __importDefault(require("path"));
1009
+ var types_12 = require_types();
1010
+ var notCapturedIdentifiers = [
1011
+ // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
1012
+ // Note that objects' properties don't need to be listed since we always only capture the whole object,
1013
+ // e.g. `global.__ErrorUtils` or `Intl.DateTimeFormat`.
1014
+ // Value properties
1015
+ "globalThis",
1016
+ "Infinity",
1017
+ "NaN",
1018
+ "undefined",
1019
+ // Function properties
1020
+ "eval",
1021
+ "isFinite",
1022
+ "isNaN",
1023
+ "parseFloat",
1024
+ "parseInt",
1025
+ "decodeURI",
1026
+ "decodeURIComponent",
1027
+ "encodeURI",
1028
+ "encodeURIComponent",
1029
+ "escape",
1030
+ "unescape",
1031
+ // Fundamental objects
1032
+ "Object",
1033
+ "Function",
1034
+ "Boolean",
1035
+ "Symbol",
1036
+ // Error objects
1037
+ "Error",
1038
+ "AggregateError",
1039
+ "EvalError",
1040
+ "RangeError",
1041
+ "ReferenceError",
1042
+ "SyntaxError",
1043
+ "TypeError",
1044
+ "URIError",
1045
+ "InternalError",
1046
+ // Numbers and dates
1047
+ "Number",
1048
+ "BigInt",
1049
+ "Math",
1050
+ "Date",
1051
+ // Text processing
1052
+ "String",
1053
+ "RegExp",
1054
+ // Indexed collections
1055
+ "Array",
1056
+ "Int8Array",
1057
+ "Uint8Array",
1058
+ "Uint8ClampedArray",
1059
+ "Int16Array",
1060
+ "Uint16Array",
1061
+ "Int32Array",
1062
+ "Uint32Array",
1063
+ "BigInt64Array",
1064
+ "BigUint64Array",
1065
+ "Float32Array",
1066
+ "Float64Array",
1067
+ // Keyed collections
1068
+ "Map",
1069
+ "Set",
1070
+ "WeakMap",
1071
+ "WeakSet",
1072
+ // Structured data
1073
+ "ArrayBuffer",
1074
+ "SharedArrayBuffer",
1075
+ "DataView",
1076
+ "Atomics",
1077
+ "JSON",
1078
+ // Managing memory
1079
+ "WeakRef",
1080
+ "FinalizationRegistry",
1081
+ // Control abstraction objects
1082
+ "Iterator",
1083
+ "AsyncIterator",
1084
+ "Promise",
1085
+ "GeneratorFunction",
1086
+ "AsyncGeneratorFunction",
1087
+ "Generator",
1088
+ "AsyncGenerator",
1089
+ "AsyncFunction",
1090
+ // Reflection
1091
+ "Reflect",
1092
+ "Proxy",
1093
+ // Internationalization
1094
+ "Intl",
1095
+ // Other stuff
1096
+ "null",
1097
+ "this",
1098
+ "global",
1099
+ "window",
1100
+ "globalThis",
1101
+ "self",
1102
+ "console",
1103
+ "performance",
1104
+ "arguments",
1105
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
1106
+ "require",
1107
+ "fetch",
1108
+ "XMLHttpRequest",
1109
+ "WebSocket",
1110
+ // Run loop
1111
+ "queueMicrotask",
1112
+ "requestAnimationFrame",
1113
+ "cancelAnimationFrame",
1114
+ "setTimeout",
1115
+ "clearTimeout",
1116
+ "setImmediate",
1117
+ "clearImmediate",
1118
+ "setInterval",
1119
+ "clearInterval",
1120
+ // Hermes
1121
+ "HermesInternal",
1122
+ // Worklets
1123
+ "_WORKLET"
1124
+ ];
1125
+ function initializeState(state) {
1126
+ var _a, _b;
1127
+ state.skipFile = isGeneratedWorkletFile(state.file.opts.filename);
1128
+ if (state.skipFile) {
1129
+ return;
1264
1130
  }
1265
- const factoryParamObjectPattern = (0, types_12.objectPattern)(factoryParams.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1266
- const factory = (0, types_12.functionExpression)((0, types_12.identifier)(workletName + "Factory"), [factoryParamObjectPattern], (0, types_12.blockStatement)(statements));
1267
- const factoryCallArgs = factoryParams.map((param) => (0, types_12.cloneNode)(param, true));
1268
- const factoryCallParamPack = (0, types_12.objectExpression)(factoryCallArgs.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1269
- if (state.opts.bundleMode) {
1270
- (0, imports_1.updateRelativeRequires)(factory, state);
1271
- (0, generate_1.generateWorkletFile)(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state);
1131
+ state.workletNumber = 1;
1132
+ state.classesToWorkletize = [];
1133
+ if (!state.opts.strictGlobal) {
1134
+ initializeGlobals();
1135
+ addCustomGlobals(state);
1272
1136
  }
1273
- factory.workletized = true;
1274
- return { factory, factoryCallParamPack, workletHash };
1137
+ const userImportForwarding = state.opts.importForwarding;
1138
+ state.opts.importForwarding = {
1139
+ relativePaths: [
1140
+ ...defaultAllowedPaths,
1141
+ ...(_a = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.relativePaths) !== null && _a !== void 0 ? _a : []
1142
+ ],
1143
+ moduleNames: [
1144
+ ...defaultAllowedModules,
1145
+ ...(_b = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.moduleNames) !== null && _b !== void 0 ? _b : []
1146
+ ]
1147
+ };
1275
1148
  }
1276
- function hasDirective(path, directiveText) {
1277
- if (!path.node.body) {
1149
+ function isGeneratedWorkletFile(filename) {
1150
+ if (!filename) {
1278
1151
  return false;
1279
1152
  }
1280
- const bodyPath = path.get("body");
1281
- let has = false;
1282
- if (bodyPath.isBlockStatement()) {
1283
- has = bodyPath.get("directives").some((directivePath) => {
1284
- if (directivePath.isDirective() && directivePath.node.value.value === directiveText) {
1285
- return true;
1286
- }
1287
- });
1288
- }
1289
- return has;
1290
- }
1291
- function stripWorkletDirectives(fun) {
1292
- fun.traverse({
1293
- DirectiveLiteral(nodePath) {
1294
- if ((nodePath.node.value === "worklet" || nodePath.node.value === "no-worklet-closure" || nodePath.node.value === "limit-init-data-hoisting") && nodePath.getFunctionParent() === fun) {
1295
- nodePath.parentPath.remove();
1296
- }
1297
- }
1298
- });
1299
- }
1300
- function shouldMockVersion() {
1301
- return process.env.WORKLETS_JEST_SHOULD_MOCK_VERSION === "1";
1302
- }
1303
- function hash(str) {
1304
- let i = str.length;
1305
- let hash1 = 5381;
1306
- let hash2 = 52711;
1307
- while (i--) {
1308
- const char = str.charCodeAt(i);
1309
- hash1 = hash1 * 33 ^ char;
1310
- hash2 = hash2 * 33 ^ char;
1311
- }
1312
- return (hash1 >>> 0) * 4096 + (hash2 >>> 0);
1313
- }
1314
- function makeWorkletName(fun, state) {
1315
- let source = "unknownFile";
1316
- if (state.file.opts.filename) {
1317
- const filepath = state.file.opts.filename;
1318
- source = (0, path_1.basename)(filepath);
1319
- const splitFilepath = filepath.split(/[\\/]/);
1320
- const nodeModulesIndex = splitFilepath.indexOf("node_modules");
1321
- if (nodeModulesIndex !== -1) {
1322
- const libraryName = splitFilepath[nodeModulesIndex + 1];
1323
- source = `${libraryName}_${source}`;
1324
- }
1325
- }
1326
- const suffix = `${source}${state.workletNumber++}`;
1327
- let reactName = "";
1328
- if ((0, types_12.isObjectMethod)(fun.node) && (0, types_12.isIdentifier)(fun.node.key)) {
1329
- reactName = fun.node.key.name;
1330
- } else if (((0, types_12.isFunctionDeclaration)(fun.node) || (0, types_12.isFunctionExpression)(fun.node)) && (0, types_12.isIdentifier)(fun.node.id)) {
1331
- reactName = fun.node.id.name;
1332
- }
1333
- const workletName = reactName ? (0, types_12.toIdentifier)(`${reactName}_${suffix}`) : (0, types_12.toIdentifier)(suffix);
1334
- reactName = reactName || (0, types_12.toIdentifier)(suffix);
1335
- return { workletName, reactName };
1153
+ const generatedWorkletsDirPath = path_1.default.join("react-native-worklets", types_12.generatedWorkletsDir);
1154
+ return filename.includes(generatedWorkletsDirPath);
1336
1155
  }
1337
- function toPosix(p) {
1338
- return path_1.sep === "/" ? p : p.split(path_1.sep).join("/");
1156
+ exports2.defaultGlobals = new Set(notCapturedIdentifiers);
1157
+ function initializeGlobals() {
1158
+ exports2.globals = new Set(exports2.defaultGlobals);
1339
1159
  }
1340
- var extraPlugins = [
1341
- require.resolve("@babel/plugin-transform-shorthand-properties"),
1342
- require.resolve("@babel/plugin-transform-arrow-functions"),
1343
- require.resolve("@babel/plugin-transform-optional-chaining"),
1344
- require.resolve("@babel/plugin-transform-nullish-coalescing-operator"),
1345
- [
1346
- require.resolve("@babel/plugin-transform-template-literals"),
1347
- { loose: true }
1348
- ]
1160
+ var defaultAllowedPaths = ["react-native-worklets"];
1161
+ var defaultAllowedModules = [
1162
+ "react-native-worklets",
1163
+ "react-native/Libraries/Core/setUpXHR"
1349
1164
  ];
1350
- }
1351
- });
1352
-
1353
- // lib/workletFactoryCall.js
1354
- var require_workletFactoryCall = __commonJS({
1355
- "lib/workletFactoryCall.js"(exports2) {
1356
- "use strict";
1357
- Object.defineProperty(exports2, "__esModule", { value: true });
1358
- exports2.makeWorkletFactoryCall = makeWorkletFactoryCall;
1359
- var types_12 = require("@babel/types");
1360
- var types_2 = require_types();
1361
- var workletFactory_1 = require_workletFactory();
1362
- function makeWorkletFactoryCall(path, state) {
1363
- const { factory, factoryCallParamPack, workletHash } = (0, workletFactory_1.makeWorkletFactory)(path, state);
1364
- let factoryCall;
1365
- if (state.opts.bundleMode) {
1366
- factoryCall = (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
1367
- (0, types_12.stringLiteral)(`react-native-worklets/${types_2.generatedWorkletsDir}/${workletHash}.js`)
1368
- ]), (0, types_12.identifier)("default")), [factoryCallParamPack]);
1369
- } else {
1370
- factoryCall = (0, types_12.callExpression)(factory, [factoryCallParamPack]);
1371
- }
1372
- addStackTraceDataToWorkletFactory(path, factoryCall);
1373
- const replacement = factoryCall;
1374
- return replacement;
1375
- }
1376
- function addStackTraceDataToWorkletFactory(path, workletFactoryCall) {
1377
- const originalWorkletLocation = path.node.loc;
1378
- if (originalWorkletLocation) {
1379
- workletFactoryCall.callee.loc = {
1380
- filename: originalWorkletLocation.filename,
1381
- identifierName: originalWorkletLocation.identifierName,
1382
- start: originalWorkletLocation.start,
1383
- end: originalWorkletLocation.start
1384
- };
1165
+ function addCustomGlobals(state) {
1166
+ if (state.opts && Array.isArray(state.opts.globals)) {
1167
+ state.opts.globals.forEach((name) => {
1168
+ exports2.globals.add(name);
1169
+ });
1385
1170
  }
1386
1171
  }
1387
1172
  }
1388
1173
  });
1389
1174
 
1390
- // lib/workletSubstitution.js
1391
- var require_workletSubstitution = __commonJS({
1392
- "lib/workletSubstitution.js"(exports2) {
1175
+ // lib/inlineStylesWarning.js
1176
+ var require_inlineStylesWarning = __commonJS({
1177
+ "lib/inlineStylesWarning.js"(exports2) {
1393
1178
  "use strict";
1394
1179
  Object.defineProperty(exports2, "__esModule", { value: true });
1395
- exports2.processIfWithWorkletDirective = processIfWithWorkletDirective;
1396
- exports2.processWorklet = processWorklet;
1397
- exports2.substituteObjectMethodWithObjectProperty = substituteObjectMethodWithObjectProperty;
1180
+ exports2.processInlineStylesWarning = processInlineStylesWarning;
1398
1181
  var types_12 = require("@babel/types");
1399
- var types_2 = require_types();
1182
+ var assert_1 = require("assert");
1400
1183
  var utils_1 = require_utils();
1401
- var workletFactoryCall_1 = require_workletFactoryCall();
1402
- function processIfWithWorkletDirective(path, state) {
1403
- if (!(0, types_12.isBlockStatement)(path.node.body)) {
1404
- return false;
1405
- }
1406
- if (!hasWorkletDirective(path.node.body.directives)) {
1407
- return false;
1184
+ function generateInlineStylesWarning(path) {
1185
+ return (0, types_12.callExpression)((0, types_12.arrowFunctionExpression)([], (0, types_12.blockStatement)([
1186
+ (0, types_12.expressionStatement)((0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.identifier)("console"), (0, types_12.identifier)("warn")), [
1187
+ (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
1188
+ (0, types_12.stringLiteral)("react-native-reanimated")
1189
+ ]), (0, types_12.identifier)("getUseOfValueInStyleWarning")), [])
1190
+ ])),
1191
+ (0, types_12.returnStatement)(path.node)
1192
+ ])), []);
1193
+ }
1194
+ function processPropertyValueForInlineStylesWarning(path) {
1195
+ if (path.isMemberExpression() && (0, types_12.isIdentifier)(path.node.property)) {
1196
+ if (!path.node.computed && path.node.property.name === "value") {
1197
+ path.replaceWith(generateInlineStylesWarning(path));
1198
+ }
1408
1199
  }
1409
- processWorklet(path, state);
1410
- return true;
1411
1200
  }
1412
- function processWorklet(path, state) {
1413
- path.traverse({
1414
- // @ts-expect-error TypeScript doesn't like this syntax here.
1415
- [types_2.WorkletizableFunction](subPath, passedState) {
1416
- processIfWithWorkletDirective(subPath, passedState);
1201
+ function processTransformPropertyForInlineStylesWarning(path) {
1202
+ if ((0, types_12.isArrayExpression)(path.node)) {
1203
+ const elements = path.get("elements");
1204
+ (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
1205
+ for (const element of elements) {
1206
+ if (element.isObjectExpression()) {
1207
+ processStyleObjectForInlineStylesWarning(element);
1208
+ }
1417
1209
  }
1418
- }, state);
1419
- const workletFactoryCall = (0, workletFactoryCall_1.makeWorkletFactoryCall)(path, state);
1420
- substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall);
1421
- path.scope.getProgramParent().crawl();
1422
- }
1423
- function hasWorkletDirective(directives) {
1424
- return directives.some((directive) => (0, types_12.isDirectiveLiteral)(directive.value) && directive.value.value === "worklet");
1210
+ }
1425
1211
  }
1426
- function substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall) {
1427
- var _a;
1428
- if (path.isObjectMethod()) {
1429
- substituteObjectMethodWithObjectProperty(path, workletFactoryCall);
1430
- } else {
1431
- const name = "id" in path.node ? (_a = path.node.id) === null || _a === void 0 ? void 0 : _a.name : void 0;
1432
- (0, utils_1.replaceWithFactoryCall)(path, name, workletFactoryCall);
1212
+ function processStyleObjectForInlineStylesWarning(path) {
1213
+ const properties = path.get("properties");
1214
+ for (const property of properties) {
1215
+ if (property.isObjectProperty()) {
1216
+ const value = property.get("value");
1217
+ if ((0, types_12.isIdentifier)(property.node.key) && property.node.key.name === "transform") {
1218
+ processTransformPropertyForInlineStylesWarning(value);
1219
+ } else {
1220
+ processPropertyValueForInlineStylesWarning(value);
1221
+ }
1222
+ }
1433
1223
  }
1434
1224
  }
1435
- function substituteObjectMethodWithObjectProperty(path, workletFactoryCall) {
1436
- const replacement = (0, types_12.objectProperty)(path.node.key, workletFactoryCall);
1437
- path.replaceWith(replacement);
1225
+ function processInlineStylesWarning(path, state) {
1226
+ if ((0, utils_1.isRelease)(state)) {
1227
+ return;
1228
+ }
1229
+ if (state.opts.disableInlineStylesWarning) {
1230
+ return;
1231
+ }
1232
+ if (path.node.name.name !== "style") {
1233
+ return;
1234
+ }
1235
+ if (!(0, types_12.isJSXExpressionContainer)(path.node.value)) {
1236
+ return;
1237
+ }
1238
+ const expression = path.get("value").get("expression");
1239
+ (0, assert_1.strict)(!Array.isArray(expression), "`expression` should not be an array.");
1240
+ if (expression.isArrayExpression()) {
1241
+ const elements = expression.get("elements");
1242
+ (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
1243
+ for (const element of elements) {
1244
+ if (element.isObjectExpression()) {
1245
+ processStyleObjectForInlineStylesWarning(element);
1246
+ }
1247
+ }
1248
+ } else if (expression.isObjectExpression()) {
1249
+ processStyleObjectForInlineStylesWarning(expression);
1250
+ }
1438
1251
  }
1439
1252
  }
1440
1253
  });
1441
1254
 
1442
- // lib/objectWorklets.js
1443
- var require_objectWorklets = __commonJS({
1444
- "lib/objectWorklets.js"(exports2) {
1255
+ // lib/webOptimization.js
1256
+ var require_webOptimization = __commonJS({
1257
+ "lib/webOptimization.js"(exports2) {
1445
1258
  "use strict";
1446
1259
  Object.defineProperty(exports2, "__esModule", { value: true });
1447
- exports2.tryProcessingNode = tryProcessingNode;
1448
- exports2.processWorkletizableObject = processWorkletizableObject;
1449
- var findWorklet_1 = require_findWorklet();
1450
- var types_12 = require_types();
1451
- var workletSubstitution_12 = require_workletSubstitution();
1452
- function tryProcessingNode(arg, state, acceptWorkletizableFunction, acceptObject) {
1453
- var _a;
1454
- const maybeWorklet = (0, findWorklet_1.findWorklet)(arg, state, acceptWorkletizableFunction, acceptObject);
1455
- if (!maybeWorklet || ((_a = maybeWorklet.getFunctionParent()) === null || _a === void 0 ? void 0 : _a.node.workletized)) {
1456
- return;
1457
- }
1458
- if ((0, types_12.isWorkletizableFunctionPath)(maybeWorklet)) {
1459
- (0, workletSubstitution_12.processWorklet)(maybeWorklet, state);
1460
- } else if ((0, types_12.isWorkletizableObjectPath)(maybeWorklet)) {
1461
- processWorkletizableObject(maybeWorklet, state);
1462
- }
1463
- }
1464
- function processWorkletizableObject(path, state) {
1465
- const properties = path.get("properties");
1466
- for (const property of properties) {
1467
- if (property.isObjectMethod()) {
1468
- (0, workletSubstitution_12.processWorklet)(property, state);
1469
- } else if (property.isObjectProperty()) {
1470
- const value = property.get("value");
1471
- tryProcessingNode(
1472
- value,
1473
- state,
1474
- true,
1475
- // acceptWorkletizableFunction
1476
- false
1477
- // acceptObject
1478
- );
1479
- } else {
1480
- throw new Error(`'${property.type}' as to-be workletized argument is not supported for object hooks.`);
1260
+ exports2.substituteWebCallExpression = substituteWebCallExpression;
1261
+ var types_12 = require("@babel/types");
1262
+ function substituteWebCallExpression(path) {
1263
+ const callee = path.node.callee;
1264
+ if ((0, types_12.isIdentifier)(callee)) {
1265
+ const name = callee.name;
1266
+ if (name === "isWeb" || name === "shouldBeUseWeb") {
1267
+ path.replaceWith((0, types_12.booleanLiteral)(true));
1481
1268
  }
1482
1269
  }
1483
1270
  }
1484
1271
  }
1485
1272
  });
1486
1273
 
1487
- // lib/autoworkletization.js
1488
- var require_autoworkletization = __commonJS({
1489
- "lib/autoworkletization.js"(exports2) {
1274
+ // lib/imports.js
1275
+ var require_imports = __commonJS({
1276
+ "lib/imports.js"(exports2) {
1490
1277
  "use strict";
1491
1278
  Object.defineProperty(exports2, "__esModule", { value: true });
1492
- exports2.processIfAutoworkletizableCallback = processIfAutoworkletizableCallback;
1493
- exports2.processCalleesAutoworkletizableCallbacks = processCalleesAutoworkletizableCallbacks;
1279
+ exports2.updateRelativeRequires = updateRelativeRequires;
1280
+ exports2.isImport = isImport;
1281
+ exports2.isImportRelative = isImportRelative;
1282
+ exports2.canForwardModuleImport = canForwardModuleImport;
1283
+ exports2.canForwardRelativeImport = canForwardRelativeImport;
1284
+ exports2.createImportPathLiteral = createImportPathLiteral;
1285
+ var core_1 = require("@babel/core");
1494
1286
  var types_12 = require("@babel/types");
1495
- var gestureHandlerAutoworkletization_1 = require_gestureHandlerAutoworkletization();
1496
- var layoutAnimationAutoworkletization_1 = require_layoutAnimationAutoworkletization();
1497
- var objectWorklets_1 = require_objectWorklets();
1498
- var workletSubstitution_12 = require_workletSubstitution();
1499
- var reanimatedObjectHooks = /* @__PURE__ */ new Set([
1500
- "useAnimatedScrollHandler",
1501
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks)
1502
- ]);
1503
- var reanimatedFunctionHooks = /* @__PURE__ */ new Set([
1504
- "useFrameCallback",
1505
- "useAnimatedStyle",
1506
- "useAnimatedProps",
1507
- "createAnimatedPropAdapter",
1508
- "useDerivedValue",
1509
- "useAnimatedScrollHandler",
1510
- "useAnimatedReaction",
1511
- // animations' callbacks
1512
- "withTiming",
1513
- "withSpring",
1514
- "withDecay",
1515
- "withRepeat",
1516
- // scheduling functions
1517
- "runOnUI",
1518
- "executeOnUIRuntimeSync",
1519
- "scheduleOnUI",
1520
- "runOnUISync",
1521
- "runOnUIAsync",
1522
- "runOnRuntime",
1523
- "runOnRuntimeSync",
1524
- "runOnRuntimeAsync",
1525
- "scheduleOnRuntime",
1526
- "runOnRuntimeSyncWithId",
1527
- "scheduleOnRuntimeWithId"
1528
- ]);
1529
- var reanimatedFunctionArgsToWorkletize = new Map([
1530
- ["useFrameCallback", [0]],
1531
- ["useAnimatedStyle", [0]],
1532
- ["useAnimatedProps", [0]],
1533
- ["createAnimatedPropAdapter", [0]],
1534
- ["useDerivedValue", [0]],
1535
- ["useAnimatedScrollHandler", [0]],
1536
- ["useAnimatedReaction", [0, 1]],
1537
- ["withTiming", [2]],
1538
- ["withSpring", [2]],
1539
- ["withDecay", [1]],
1540
- ["withRepeat", [3]],
1541
- ["runOnUI", [0]],
1542
- ["executeOnUIRuntimeSync", [0]],
1543
- ["scheduleOnUI", [0]],
1544
- ["runOnUISync", [0]],
1545
- ["runOnUIAsync", [0]],
1546
- ["runOnRuntime", [1]],
1547
- ["runOnRuntimeSync", [1]],
1548
- ["runOnRuntimeAsync", [1]],
1549
- ["scheduleOnRuntime", [1]],
1550
- ["runOnRuntimeSyncWithId", [1]],
1551
- ["scheduleOnRuntimeWithId", [1]],
1552
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks).map((name) => [name, [0]]),
1553
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerBuilderMethods).map((name) => [name, [0]])
1554
- ]);
1555
- function processIfAutoworkletizableCallback(path, state) {
1556
- if ((0, gestureHandlerAutoworkletization_1.isGestureHandlerEventCallback)(path) || (0, layoutAnimationAutoworkletization_1.isLayoutAnimationCallback)(path)) {
1557
- (0, workletSubstitution_12.processWorklet)(path, state);
1558
- return true;
1559
- }
1560
- return false;
1287
+ var path_1 = require("path");
1288
+ var types_2 = require_types();
1289
+ function updateRelativeRequires(node, state) {
1290
+ (0, core_1.traverse)(node, {
1291
+ noScope: true,
1292
+ CallExpression(nodePath) {
1293
+ var _a;
1294
+ if (nodePath.get("callee").isIdentifier({ name: "require" }) && ((_a = nodePath.get("arguments")[0]) === null || _a === void 0 ? void 0 : _a.isStringLiteral())) {
1295
+ const requiredModule = nodePath.get("arguments")[0];
1296
+ if (requiredModule.node.value.startsWith(".") && canForwardRelativeImport(state.file.opts.filename || "", state.opts.importForwarding.relativePaths)) {
1297
+ requiredModule.replaceWith(createImportPathLiteral(requiredModule.node.value, state));
1298
+ }
1299
+ }
1300
+ }
1301
+ });
1561
1302
  }
1562
- function processCalleesAutoworkletizableCallbacks(path, state) {
1563
- const callee = (0, types_12.isSequenceExpression)(path.node.callee) ? path.node.callee.expressions[path.node.callee.expressions.length - 1] : path.node.callee;
1564
- const name = "name" in callee ? callee.name : "property" in callee && "name" in callee.property ? callee.property.name : void 0;
1565
- if (name === void 0) {
1566
- return;
1303
+ function isImport(binding) {
1304
+ return binding.kind === "module" && binding.constant && (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration();
1305
+ }
1306
+ function isImportRelative(imported) {
1307
+ return imported.path.parentPath.node.source.value.startsWith(".");
1308
+ }
1309
+ function canForwardModuleImport(moduleName, forwardableModuleNames) {
1310
+ return forwardableModuleNames.some((forwardableModuleName) => moduleName === forwardableModuleName || moduleName.startsWith(forwardableModuleName + "/"));
1311
+ }
1312
+ function canForwardRelativeImport(modulePath, relativePaths) {
1313
+ return !!modulePath && relativePaths.some((relativePath) => matchesFilenameSegment(modulePath, relativePath));
1314
+ }
1315
+ function matchesFilenameSegment(filename, allowedPath) {
1316
+ const pkgSegments = allowedPath.split(path_1.posix.sep);
1317
+ let fileSegments = filename.split(path_1.sep);
1318
+ const lastNodeModules = fileSegments.lastIndexOf("node_modules");
1319
+ if (lastNodeModules !== -1) {
1320
+ fileSegments = fileSegments.slice(lastNodeModules + 1);
1567
1321
  }
1568
- if (reanimatedFunctionHooks.has(name) || reanimatedObjectHooks.has(name)) {
1569
- const acceptWorkletizableFunction = reanimatedFunctionHooks.has(name);
1570
- const acceptObject = reanimatedObjectHooks.has(name);
1571
- const argIndices = reanimatedFunctionArgsToWorkletize.get(name);
1572
- const args = path.get("arguments").filter((_, index) => argIndices.includes(index));
1573
- processArgs(args, state, acceptWorkletizableFunction, acceptObject);
1574
- } else if (!(0, types_12.isV8IntrinsicIdentifier)(callee) && (0, gestureHandlerAutoworkletization_1.isGestureObjectEventCallbackMethod)(callee)) {
1575
- const args = path.get("arguments");
1576
- processArgs(args, state, true, true);
1322
+ for (let i = 0; i <= fileSegments.length - pkgSegments.length; i++) {
1323
+ if (pkgSegments.every((segment, segmentIndex) => fileSegments[i + segmentIndex] === segment)) {
1324
+ return true;
1325
+ }
1577
1326
  }
1327
+ return false;
1578
1328
  }
1579
- function processArgs(args, state, acceptWorkletizableFunction, acceptObject) {
1580
- args.forEach((arg) => {
1581
- (0, objectWorklets_1.tryProcessingNode)(arg, state, acceptWorkletizableFunction, acceptObject);
1582
- });
1329
+ function createImportPathLiteral(originalPath, state) {
1330
+ const generatedWorkletsDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
1331
+ const resolved = (0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), originalPath);
1332
+ const relativePath = (0, path_1.relative)(generatedWorkletsDirPath, resolved);
1333
+ return (0, types_12.stringLiteral)(path_1.sep === "/" ? relativePath : relativePath.split(path_1.sep).join("/"));
1583
1334
  }
1584
1335
  }
1585
1336
  });
1586
1337
 
1587
- // lib/bundleMode.js
1588
- var require_bundleMode = __commonJS({
1589
- "lib/bundleMode.js"(exports2) {
1338
+ // lib/closure.js
1339
+ var require_closure = __commonJS({
1340
+ "lib/closure.js"(exports2) {
1590
1341
  "use strict";
1591
1342
  Object.defineProperty(exports2, "__esModule", { value: true });
1592
- exports2.toggleBundleMode = toggleBundleMode;
1343
+ exports2.getClosure = getClosure;
1593
1344
  var types_12 = require("@babel/types");
1594
- var path_1 = require("path");
1595
- var WORKLETS_PACKAGE = "react-native-worklets";
1596
- var WORKLETS_SRC_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "src");
1597
- var WORKLETS_LIB_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "lib", "module");
1598
- var togglePaths = [
1599
- (0, path_1.join)(WORKLETS_SRC_DIR, "index.ts"),
1600
- (0, path_1.join)(WORKLETS_SRC_DIR, "debug", "bundleMode.native.ts"),
1601
- (0, path_1.join)(WORKLETS_LIB_DIR, "index.js"),
1602
- (0, path_1.join)(WORKLETS_LIB_DIR, "debug", "bundleMode.native.js")
1603
- ];
1604
- function toggleBundleMode(path, state) {
1605
- if (!state.opts.bundleMode || !togglePaths.some((togglePath) => {
1606
- var _a;
1607
- return (_a = state.filename) === null || _a === void 0 ? void 0 : _a.endsWith(togglePath);
1608
- })) {
1609
- return;
1610
- }
1611
- const expressionPath = path.get("expression");
1612
- if (!expressionPath.isAssignmentExpression()) {
1613
- return;
1614
- }
1615
- const left = expressionPath.get("left");
1616
- if (!left.isMemberExpression()) {
1617
- return;
1618
- }
1619
- const object = left.get("object");
1620
- const property = left.get("property");
1621
- if (!object.isIdentifier() || object.node.name !== "globalThis" || !property.isIdentifier() || property.node.name !== "_WORKLETS_BUNDLE_MODE_ENABLED") {
1622
- return;
1623
- }
1624
- const right = expressionPath.get("right");
1625
- right.replaceWith((0, types_12.booleanLiteral)(true));
1345
+ var globals_12 = require_globals();
1346
+ var imports_1 = require_imports();
1347
+ function getClosure(funPath, state) {
1348
+ const capturedNames = /* @__PURE__ */ new Set();
1349
+ const closureVariables = new Array();
1350
+ const moduleBindingsToImport = /* @__PURE__ */ new Set();
1351
+ const relativeBindingsToImport = /* @__PURE__ */ new Set();
1352
+ let recrawled = false;
1353
+ funPath.traverse({
1354
+ "TSType|TSTypeAliasDeclaration|TSInterfaceDeclaration"(typePath) {
1355
+ typePath.skip();
1356
+ },
1357
+ ReferencedIdentifier(idPath) {
1358
+ if (idPath.isJSXIdentifier() && !state.opts.bundleMode) {
1359
+ return;
1360
+ }
1361
+ const name = idPath.node.name;
1362
+ if (capturedNames.has(name)) {
1363
+ return;
1364
+ }
1365
+ let binding = idPath.scope.getBinding(name);
1366
+ if (!binding && !recrawled) {
1367
+ recrawled = true;
1368
+ idPath.scope.crawl();
1369
+ binding = idPath.scope.getBinding(name);
1370
+ }
1371
+ if (!binding) {
1372
+ if (state.opts.strictGlobal || globals_12.globals.has(name)) {
1373
+ return;
1374
+ }
1375
+ capturedNames.add(name);
1376
+ closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
1377
+ return;
1378
+ }
1379
+ if ("id" in funPath.node) {
1380
+ const id = idPath.scope.getBindingIdentifier(name);
1381
+ if (id && id === funPath.node.id) {
1382
+ return;
1383
+ }
1384
+ }
1385
+ let scope = idPath.scope;
1386
+ while (scope !== funPath.scope.parent) {
1387
+ if (scope.hasOwnBinding(name)) {
1388
+ return;
1389
+ }
1390
+ scope = scope.parent;
1391
+ }
1392
+ if (state.opts.bundleMode && (0, imports_1.isImport)(binding)) {
1393
+ if ((0, imports_1.isImportRelative)(binding) && (0, imports_1.canForwardRelativeImport)(state.filename, state.opts.importForwarding.relativePaths)) {
1394
+ capturedNames.add(name);
1395
+ relativeBindingsToImport.add(binding);
1396
+ return;
1397
+ }
1398
+ const source = binding.path.parentPath.node.source.value;
1399
+ if ((0, imports_1.canForwardModuleImport)(source, state.opts.importForwarding.moduleNames)) {
1400
+ capturedNames.add(name);
1401
+ moduleBindingsToImport.add(binding);
1402
+ return;
1403
+ }
1404
+ }
1405
+ capturedNames.add(name);
1406
+ closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
1407
+ }
1408
+ }, state);
1409
+ return {
1410
+ closureVariables,
1411
+ moduleBindingsToImport,
1412
+ relativeBindingsToImport
1413
+ };
1626
1414
  }
1627
1415
  }
1628
1416
  });
1629
1417
 
1630
- // lib/class.js
1631
- var require_class = __commonJS({
1632
- "lib/class.js"(exports2) {
1418
+ // lib/generate.js
1419
+ var require_generate = __commonJS({
1420
+ "lib/generate.js"(exports2) {
1633
1421
  "use strict";
1634
1422
  var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1635
1423
  return mod && mod.__esModule ? mod : { "default": mod };
1636
1424
  };
1637
1425
  Object.defineProperty(exports2, "__esModule", { value: true });
1638
- exports2.processIfWorkletClass = processIfWorkletClass;
1639
- var generator_1 = __importDefault(require("@babel/generator"));
1640
- var traverse_1 = __importDefault(require("@babel/traverse"));
1426
+ exports2.generateWorkletFile = generateWorkletFile;
1427
+ var core_1 = require("@babel/core");
1641
1428
  var types_12 = require("@babel/types");
1642
- var assert_1 = require("assert");
1643
- var transform_1 = require_transform();
1429
+ var assert_1 = __importDefault(require("assert"));
1430
+ var fs_1 = require("fs");
1431
+ var path_1 = require("path");
1432
+ var imports_1 = require_imports();
1644
1433
  var types_2 = require_types();
1645
- var utils_1 = require_utils();
1646
- var classWorkletMarker = "__workletClass";
1647
- function processIfWorkletClass(classPath, state) {
1648
- if (!isWorkletizableClass(classPath, state) || state.opts.bundleMode) {
1649
- return false;
1650
- }
1651
- removeWorkletClassMarker(classPath.node.body);
1652
- processClass(classPath, state);
1653
- return true;
1654
- }
1655
- function processClass(classPath, state) {
1656
- (0, assert_1.strict)(classPath.node.id);
1657
- const className = classPath.node.id.name;
1658
- const polyfilledClassAst = getPolyfilledAst(classPath.node, state);
1659
- sortPolyfills(polyfilledClassAst);
1660
- appendWorkletDirectiveToPolyfills(polyfilledClassAst.program.body);
1661
- replaceClassDeclarationWithFactoryAndCall(polyfilledClassAst.program.body, className);
1662
- polyfilledClassAst.program.body.push((0, types_12.returnStatement)((0, types_12.identifier)(className)));
1663
- const factoryFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([...polyfilledClassAst.program.body]));
1664
- const factoryCall = (0, types_12.callExpression)(factoryFactory, []);
1665
- (0, utils_1.replaceWithFactoryCall)(classPath, className, factoryCall);
1666
- }
1667
- function getPolyfilledAst(classNode, state) {
1434
+ function generateWorkletFile(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state) {
1668
1435
  var _a;
1669
- const classCode = (0, generator_1.default)(classNode).code;
1670
- const classWithPolyfills = (0, transform_1.workletTransformSync)(classCode, {
1671
- extraPlugins: [
1672
- "@babel/plugin-transform-class-properties",
1673
- "@babel/plugin-transform-classes",
1674
- "@babel/plugin-transform-unicode-regex",
1675
- ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1676
- ],
1677
- extraPresets: state.opts.extraPresets,
1436
+ const libraryImports = Array.from(moduleBindingsToImport).filter((binding) => (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, types_12.stringLiteral)(binding.path.parentPath.node.source.value)));
1437
+ const filesDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
1438
+ const relativeImports = Array.from(relativeBindingsToImport).filter((binding) => binding.path.isImportSpecifier() && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, imports_1.createImportPathLiteral)(binding.path.parentPath.node.source.value, state)));
1439
+ const imports = [...libraryImports, ...relativeImports];
1440
+ const newProg = (0, types_12.program)([...imports, (0, types_12.exportDefaultDeclaration)(factory)]);
1441
+ const transformedProg = (_a = (0, core_1.transformFromAstSync)(newProg, void 0, {
1678
1442
  filename: state.file.opts.filename,
1679
- ast: true,
1443
+ presets: [resolvePresetTypescript()],
1444
+ plugins: [stripJsxDevAttributesPlugin],
1445
+ ast: false,
1680
1446
  babelrc: false,
1681
- configFile: false
1682
- });
1683
- (0, assert_1.strict)(classWithPolyfills && classWithPolyfills.ast);
1684
- return classWithPolyfills.ast;
1685
- }
1686
- function appendWorkletDirectiveToPolyfills(statements) {
1687
- statements.forEach((statement) => {
1688
- if ((0, types_12.isFunctionDeclaration)(statement)) {
1689
- const workletDirective = (0, types_12.directive)((0, types_12.directiveLiteral)("worklet"));
1690
- statement.body.directives.push(workletDirective);
1691
- }
1692
- });
1693
- }
1694
- function replaceClassDeclarationWithFactoryAndCall(statements, className) {
1695
- const classFactoryName = className + types_2.workletClassFactorySuffix;
1696
- const classDeclarationIndex = getPolyfilledClassDeclarationIndex(statements, className);
1697
- const classDeclarationToReplace = statements[classDeclarationIndex];
1698
- const classDeclarationInit = classDeclarationToReplace.declarations[0].init;
1699
- const classFactoryDeclaration = (0, types_12.functionDeclaration)((0, types_12.identifier)(classFactoryName), [], (0, types_12.blockStatement)([
1700
- (0, types_12.variableDeclaration)("const", [
1701
- (0, types_12.variableDeclarator)((0, types_12.identifier)(className), classDeclarationInit)
1702
- ]),
1703
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(className), (0, types_12.identifier)(classFactoryName)), (0, types_12.identifier)(classFactoryName))),
1704
- (0, types_12.returnStatement)((0, types_12.identifier)(className))
1705
- ], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
1706
- const newClassDeclaration = (0, types_12.variableDeclaration)("const", [
1707
- (0, types_12.variableDeclarator)((0, types_12.identifier)(className), (0, types_12.callExpression)((0, types_12.identifier)(classFactoryName), []))
1708
- ]);
1709
- statements.splice(classDeclarationIndex, 1, classFactoryDeclaration, newClassDeclaration);
1710
- }
1711
- function getPolyfilledClassDeclarationIndex(statements, className) {
1712
- const index = statements.findIndex((statement) => (0, types_12.isVariableDeclaration)(statement) && statement.declarations.some((declaration) => (0, types_12.isIdentifier)(declaration.id) && declaration.id.name === className));
1713
- (0, assert_1.strict)(index >= 0);
1714
- return index;
1715
- }
1716
- function hasWorkletClassMarker(classBody) {
1717
- return classBody.body.some((statement) => (0, types_12.isClassProperty)(statement) && (0, types_12.isIdentifier)(statement.key) && statement.key.name === classWorkletMarker);
1447
+ configFile: false,
1448
+ comments: false
1449
+ })) === null || _a === void 0 ? void 0 : _a.code;
1450
+ (0, assert_1.default)(transformedProg, "[Worklets] `transformedProg` is undefined.");
1451
+ const dedicatedFilePath = (0, path_1.resolve)(filesDirPath, `${workletHash}.js`);
1452
+ (0, fs_1.writeFileSync)(dedicatedFilePath, transformedProg);
1718
1453
  }
1719
- function removeWorkletClassMarker(classBody) {
1720
- classBody.body = classBody.body.filter((statement) => !(0, types_12.isClassProperty)(statement) || !(0, types_12.isIdentifier)(statement.key) || statement.key.name !== classWorkletMarker);
1454
+ function resolvePresetTypescript() {
1455
+ try {
1456
+ return require.resolve("@babel/preset-typescript");
1457
+ } catch (_a) {
1458
+ return require.resolve("@babel/preset-typescript", {
1459
+ paths: [(0, path_1.dirname)(require.resolve("react-native-worklets/package.json"))]
1460
+ });
1461
+ }
1721
1462
  }
1722
- function sortPolyfills(ast) {
1723
- const toSort = getPolyfillsToSort(ast);
1724
- const sorted = topoSort(toSort);
1725
- const toSortIndices = toSort.map((element) => element.index);
1726
- const sortedIndices = sorted.map((element) => element.index);
1727
- const statements = ast.program.body;
1728
- const oldStatements = [...statements];
1729
- for (let i = 0; i < toSort.length; i++) {
1730
- const sourceIndex = sortedIndices[i];
1731
- const targetIndex = toSortIndices[i];
1732
- const source = oldStatements[sourceIndex];
1733
- statements[targetIndex] = source;
1463
+ var stripJsxDevAttributesPlugin = {
1464
+ name: "worklets-strip-jsx-dev-attributes",
1465
+ visitor: {
1466
+ JSXAttribute(path) {
1467
+ const name = path.node.name;
1468
+ if (name.type !== "JSXIdentifier") {
1469
+ return;
1470
+ }
1471
+ if (name.name !== "__self" && name.name !== "__source") {
1472
+ return;
1473
+ }
1474
+ path.remove();
1475
+ }
1476
+ }
1477
+ };
1478
+ }
1479
+ });
1480
+
1481
+ // lib/hermesBytecode.js
1482
+ var require_hermesBytecode = __commonJS({
1483
+ "lib/hermesBytecode.js"(exports2) {
1484
+ "use strict";
1485
+ Object.defineProperty(exports2, "__esModule", { value: true });
1486
+ exports2.compileWorkletToHbc = compileWorkletToHbc;
1487
+ var core_1 = require("@babel/core");
1488
+ var child_process_1 = require("child_process");
1489
+ function compileWorkletToHbc(funString, workletHash, state) {
1490
+ if (compilationCache.has(workletHash)) {
1491
+ return compilationCache.get(workletHash);
1734
1492
  }
1493
+ const result = compile(funString, state);
1494
+ compilationCache.set(workletHash, result);
1495
+ return result;
1735
1496
  }
1736
- function getPolyfillsToSort(ast) {
1737
- const polyfills = [];
1738
- (0, traverse_1.default)(ast, {
1739
- Program: {
1740
- enter: (functionPath) => {
1741
- const statements = functionPath.get("body");
1742
- statements.forEach((statement, index) => {
1743
- var _a;
1744
- const bindingIdentifiers = statement.getBindingIdentifiers();
1745
- if (!statement.isFunctionDeclaration() || !((_a = statement.node.id) === null || _a === void 0 ? void 0 : _a.name)) {
1746
- return;
1747
- }
1748
- const element = {
1749
- name: statement.node.id.name,
1750
- index,
1751
- dependencies: /* @__PURE__ */ new Set()
1752
- };
1753
- polyfills.push(element);
1754
- statement.traverse({
1755
- Identifier(path) {
1756
- if (isOutsideDependency(path, bindingIdentifiers, statement)) {
1757
- element.dependencies.add(path.node.name);
1758
- }
1759
- }
1760
- });
1761
- });
1497
+ function compile(funString, state) {
1498
+ const hermesc = resolveHbcBinary(state);
1499
+ if (!hermesc) {
1500
+ return null;
1501
+ }
1502
+ try {
1503
+ return runHermesc(hermesc, funString);
1504
+ } catch (error) {
1505
+ if (getErrorOutput(error).includes("JSX")) {
1506
+ const transformed = transformJsx(funString);
1507
+ if (transformed !== null) {
1508
+ try {
1509
+ return runHermesc(hermesc, transformed);
1510
+ } catch (retryError) {
1511
+ return warnFallback(retryError);
1512
+ }
1762
1513
  }
1763
1514
  }
1764
- });
1765
- return polyfills;
1766
- }
1767
- function topoSort(toSort) {
1768
- const sorted = [];
1769
- const stack = /* @__PURE__ */ new Set();
1770
- for (const element of toSort) {
1771
- recursiveTopoSort(element, toSort, sorted, stack);
1515
+ return warnFallback(error);
1772
1516
  }
1773
- return sorted;
1774
1517
  }
1775
- function recursiveTopoSort(current, toSort, sorted, stack) {
1776
- if (stack.has(current.name)) {
1777
- throw new Error("Cycle detected. This should never happen.");
1778
- }
1779
- if (sorted.find((element) => element.name === current.name)) {
1518
+ var MAX_BYTECODE_BYTES = 256 * 1024 * 1024;
1519
+ var compilationCache = /* @__PURE__ */ new Map();
1520
+ var warnedMessages = /* @__PURE__ */ new Set();
1521
+ function warnOnce(message) {
1522
+ if (warnedMessages.has(message)) {
1780
1523
  return;
1781
1524
  }
1782
- stack.add(current.name);
1783
- for (const dependency of current.dependencies) {
1784
- if (!sorted.find((element) => element.name === dependency)) {
1785
- const next = toSort.find((element) => element.name === dependency);
1786
- (0, assert_1.strict)(next);
1787
- recursiveTopoSort(next, toSort, sorted, stack);
1525
+ warnedMessages.add(message);
1526
+ console.warn(`[Worklets] ${message}`);
1527
+ }
1528
+ function resolveHbcBinary(state) {
1529
+ const { getHBCBinary } = state.opts;
1530
+ if (!getHBCBinary) {
1531
+ warnOnce("The `getHBCBinary` plugin option is required to compile worklets to Hermes bytecode. Falling back to shipping worklets as source strings.");
1532
+ return null;
1533
+ }
1534
+ try {
1535
+ const binary = getHBCBinary();
1536
+ if (!binary) {
1537
+ throw new Error("`getHBCBinary` returned an empty path.");
1788
1538
  }
1539
+ return binary;
1540
+ } catch (error) {
1541
+ warnOnce(`Calling \`getHBCBinary\` failed, falling back to a source string. ${error instanceof Error ? error.message : String(error)}`);
1542
+ return null;
1789
1543
  }
1790
- sorted.push(current);
1791
- stack.delete(current.name);
1792
1544
  }
1793
- function isOutsideDependency(identifierPath, bindingIdentifiers, functionPath) {
1794
- return (
1795
- // We don't care about identifiers that were just declared.
1796
- identifierPath.isReferencedIdentifier() && // We don't care about identifiers that are bound in the scope.
1797
- !(identifierPath.node.name in bindingIdentifiers) && // This I don't exactly understand, but the function identifier itself isn't in `bindingIdentifiers`,
1798
- // but it return true on `hasOwnBinding`.
1799
- !functionPath.scope.hasOwnBinding(identifierPath.node.name) && // `hasReference` returns true for global identifiers, like `Object`,
1800
- // we don't want to include those.
1801
- functionPath.scope.hasReference(identifierPath.node.name)
1802
- );
1545
+ function runHermesc(hermesc, source) {
1546
+ return (0, child_process_1.execFileSync)(hermesc, ["-g0", "-emit-binary", "-O", "-w", "-"], {
1547
+ input: source,
1548
+ maxBuffer: MAX_BYTECODE_BYTES,
1549
+ stdio: ["pipe", "pipe", "pipe"]
1550
+ });
1803
1551
  }
1804
- function isWorkletizableClass(classPath, state) {
1552
+ function getErrorOutput(error) {
1553
+ const stderr = error === null || error === void 0 ? void 0 : error.stderr;
1554
+ if (stderr) {
1555
+ return stderr.toString();
1556
+ }
1557
+ return error instanceof Error ? error.message : String(error);
1558
+ }
1559
+ function warnFallback(error) {
1560
+ const reason = getErrorOutput(error).trim().split("\n")[0];
1561
+ warnOnce(`Could not compile a worklet to Hermes bytecode, falling back to a source string. ${reason}`);
1562
+ return null;
1563
+ }
1564
+ var jsxPluginPath;
1565
+ function resolveJsxPlugin() {
1566
+ if (jsxPluginPath === void 0) {
1567
+ try {
1568
+ jsxPluginPath = require.resolve("@babel/plugin-transform-react-jsx");
1569
+ } catch (_a) {
1570
+ jsxPluginPath = null;
1571
+ }
1572
+ }
1573
+ return jsxPluginPath;
1574
+ }
1575
+ function transformJsx(source) {
1805
1576
  var _a;
1806
- const className = (_a = classPath.node.id) === null || _a === void 0 ? void 0 : _a.name;
1807
- const classNode = classPath.node;
1808
- if (!className) {
1809
- return false;
1577
+ const plugin = resolveJsxPlugin();
1578
+ if (!plugin) {
1579
+ return null;
1580
+ }
1581
+ try {
1582
+ const result = (0, core_1.transformSync)(source, {
1583
+ babelrc: false,
1584
+ configFile: false,
1585
+ compact: true,
1586
+ plugins: [plugin]
1587
+ });
1588
+ return (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : null;
1589
+ } catch (_b) {
1590
+ return null;
1810
1591
  }
1811
- const isMarked = hasWorkletClassMarker(classNode.body);
1812
- const isMemoizedNode = state.classesToWorkletize.some((record) => record.node === classNode);
1813
- const isTopLevelMemoizedName = classPath.parentPath.isProgram() && state.classesToWorkletize.some((record) => record.name === className);
1814
- state.classesToWorkletize = state.classesToWorkletize.filter((record) => record.node !== classNode && record.name !== className);
1815
- const result = isMarked || isMemoizedNode || isTopLevelMemoizedName;
1816
- return result;
1817
1592
  }
1818
1593
  }
1819
1594
  });
1820
1595
 
1821
- // lib/contextObject.js
1822
- var require_contextObject = __commonJS({
1823
- "lib/contextObject.js"(exports2) {
1596
+ // lib/workletStringCode.js
1597
+ var require_workletStringCode = __commonJS({
1598
+ "lib/workletStringCode.js"(exports2) {
1824
1599
  "use strict";
1600
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
1601
+ if (k2 === void 0) k2 = k;
1602
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1603
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1604
+ desc = { enumerable: true, get: function() {
1605
+ return m[k];
1606
+ } };
1607
+ }
1608
+ Object.defineProperty(o, k2, desc);
1609
+ }) : (function(o, m, k, k2) {
1610
+ if (k2 === void 0) k2 = k;
1611
+ o[k2] = m[k];
1612
+ }));
1613
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
1614
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1615
+ }) : function(o, v) {
1616
+ o["default"] = v;
1617
+ });
1618
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
1619
+ var ownKeys = function(o) {
1620
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1621
+ var ar = [];
1622
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1623
+ return ar;
1624
+ };
1625
+ return ownKeys(o);
1626
+ };
1627
+ return function(mod) {
1628
+ if (mod && mod.__esModule) return mod;
1629
+ var result = {};
1630
+ if (mod != null) {
1631
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1632
+ }
1633
+ __setModuleDefault(result, mod);
1634
+ return result;
1635
+ };
1636
+ })();
1637
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1638
+ return mod && mod.__esModule ? mod : { "default": mod };
1639
+ };
1825
1640
  Object.defineProperty(exports2, "__esModule", { value: true });
1826
- exports2.contextObjectMarker = void 0;
1827
- exports2.processIfWorkletContextObject = processIfWorkletContextObject;
1828
- exports2.isContextObject = isContextObject;
1641
+ exports2.buildWorkletString = buildWorkletString;
1642
+ var core_1 = require("@babel/core");
1643
+ var generator_1 = __importDefault(require("@babel/generator"));
1829
1644
  var types_12 = require("@babel/types");
1830
- exports2.contextObjectMarker = "__workletContextObject";
1831
- function processIfWorkletContextObject(path, _state) {
1832
- if (!isContextObject(path.node)) {
1833
- return false;
1645
+ var assert_1 = require("assert");
1646
+ var convertSourceMap = __importStar(require("convert-source-map"));
1647
+ var fs = __importStar(require("fs"));
1648
+ var transform_1 = require_transform();
1649
+ var types_2 = require_types();
1650
+ var utils_1 = require_utils();
1651
+ var MOCK_SOURCE_MAP = "mock source map";
1652
+ var querySuffixRE = /[?#].*$/;
1653
+ function buildWorkletString(fun, state, closureVariables, workletName, inputMap) {
1654
+ var _a;
1655
+ restoreRecursiveCalls(fun, workletName);
1656
+ const draftExpression = fun.program.body.find((obj) => (0, types_12.isFunctionDeclaration)(obj)) || fun.program.body.find((obj) => (0, types_12.isExpressionStatement)(obj));
1657
+ (0, assert_1.strict)(draftExpression, "`draftExpression` is undefined.");
1658
+ const expression = (0, types_12.isFunctionDeclaration)(draftExpression) ? draftExpression : draftExpression.expression;
1659
+ (0, assert_1.strict)("params" in expression, "'params' property is undefined in 'expression'");
1660
+ (0, assert_1.strict)((0, types_12.isBlockStatement)(expression.body), "`expression.body` is not a `BlockStatement`");
1661
+ const parsedClasses = /* @__PURE__ */ new Set();
1662
+ if (!state.opts.disableWorkletClasses) {
1663
+ (0, core_1.traverse)(fun, {
1664
+ NewExpression(path) {
1665
+ if (!(0, types_12.isIdentifier)(path.node.callee)) {
1666
+ return;
1667
+ }
1668
+ const constructorName = path.node.callee.name;
1669
+ if (!closureVariables.some((variable) => variable.name === constructorName) || parsedClasses.has(constructorName)) {
1670
+ return;
1671
+ }
1672
+ const index = closureVariables.findIndex((variable) => variable.name === constructorName);
1673
+ closureVariables.splice(index, 1);
1674
+ const workletClassFactoryName = constructorName + types_2.workletClassFactorySuffix;
1675
+ closureVariables.push((0, types_12.identifier)(workletClassFactoryName));
1676
+ (0, types_12.assertBlockStatement)(expression.body);
1677
+ expression.body.body.unshift((0, types_12.variableDeclaration)("const", [
1678
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(constructorName), (0, types_12.callExpression)((0, types_12.identifier)(workletClassFactoryName), []))
1679
+ ]));
1680
+ parsedClasses.add(constructorName);
1681
+ }
1682
+ });
1834
1683
  }
1835
- removeContextObjectMarker(path.node);
1836
- processWorkletContextObject(path.node);
1837
- return true;
1684
+ const workletFunction = (0, types_12.functionExpression)((0, types_12.identifier)(workletName), expression.params, expression.body, expression.generator, expression.async);
1685
+ const code = (0, generator_1.default)(workletFunction).code;
1686
+ (0, assert_1.strict)(inputMap, "`inputMap` is undefined.");
1687
+ const includeSourceMap = !((0, utils_1.isRelease)(state) || state.opts.disableSourceMaps);
1688
+ if (includeSourceMap) {
1689
+ inputMap.sourcesContent = [];
1690
+ for (const sourceFile of inputMap.sources) {
1691
+ inputMap.sourcesContent.push(fs.readFileSync(sourceFile.replace(querySuffixRE, "")).toString("utf-8"));
1692
+ }
1693
+ }
1694
+ const transformed = (0, transform_1.workletTransformSync)(code, {
1695
+ filename: state.file.opts.filename,
1696
+ extraPlugins: [
1697
+ getClosurePlugin(closureVariables),
1698
+ ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1699
+ ],
1700
+ extraPresets: state.opts.extraPresets,
1701
+ compact: true,
1702
+ sourceMaps: includeSourceMap,
1703
+ inputSourceMap: inputMap,
1704
+ ast: false,
1705
+ babelrc: false,
1706
+ configFile: false,
1707
+ comments: false
1708
+ });
1709
+ (0, assert_1.strict)(transformed, "`transformed` is null.");
1710
+ let sourceMap;
1711
+ if (includeSourceMap) {
1712
+ if (shouldMockSourceMap()) {
1713
+ sourceMap = MOCK_SOURCE_MAP;
1714
+ } else {
1715
+ sourceMap = convertSourceMap.fromObject(transformed.map).toObject();
1716
+ delete sourceMap.sourcesContent;
1717
+ }
1718
+ }
1719
+ const wrappedCode = `(${transformed.code})`;
1720
+ return [wrappedCode, JSON.stringify(sourceMap)];
1721
+ }
1722
+ function restoreRecursiveCalls(file, newName) {
1723
+ (0, core_1.traverse)(file, {
1724
+ FunctionExpression(path) {
1725
+ if (!path.node.id) {
1726
+ path.stop();
1727
+ return;
1728
+ }
1729
+ const oldName = path.node.id.name;
1730
+ const scope = path.scope;
1731
+ scope.rename(oldName, newName);
1732
+ }
1733
+ });
1838
1734
  }
1839
- function isContextObject(objectExpression) {
1840
- return objectExpression.properties.some((property) => (0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker);
1735
+ function shouldMockSourceMap() {
1736
+ return process.env.WORKLETS_JEST_SHOULD_MOCK_SOURCE_MAP === "1";
1841
1737
  }
1842
- function processWorkletContextObject(objectExpression) {
1843
- const workletObjectFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([(0, types_12.returnStatement)((0, types_12.cloneNode)(objectExpression))], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
1844
- objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${exports2.contextObjectMarker}Factory`), workletObjectFactory));
1738
+ function prependClosure(path, closureVariables, closureDeclaration) {
1739
+ if (closureVariables.length === 0 || !(0, types_12.isProgram)(path.parent)) {
1740
+ return;
1741
+ }
1742
+ if (!(0, types_12.isExpression)(path.node.body)) {
1743
+ path.node.body.body.unshift(closureDeclaration);
1744
+ }
1845
1745
  }
1846
- function removeContextObjectMarker(objectExpression) {
1847
- objectExpression.properties = objectExpression.properties.filter((property) => !((0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker));
1746
+ function prependRecursiveDeclaration(path) {
1747
+ var _a;
1748
+ if ((0, types_12.isProgram)(path.parent) && !(0, types_12.isArrowFunctionExpression)(path.node) && !(0, types_12.isObjectMethod)(path.node) && path.node.id && path.scope.parent) {
1749
+ const hasRecursiveCalls = ((_a = path.scope.parent.bindings[path.node.id.name]) === null || _a === void 0 ? void 0 : _a.references) > 0;
1750
+ if (hasRecursiveCalls) {
1751
+ path.node.body.body.unshift((0, types_12.variableDeclaration)("const", [
1752
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(path.node.id.name), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("_recur")))
1753
+ ]));
1754
+ }
1755
+ }
1756
+ }
1757
+ function getClosurePlugin(closureVariables) {
1758
+ const closureDeclaration = (0, types_12.variableDeclaration)("const", [
1759
+ (0, types_12.variableDeclarator)((0, types_12.objectPattern)(closureVariables.map((variable) => (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.identifier)(variable.name), false, true))), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("__closure")))
1760
+ ]);
1761
+ return {
1762
+ visitor: {
1763
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod": (path) => {
1764
+ prependClosure(path, closureVariables, closureDeclaration);
1765
+ prependRecursiveDeclaration(path);
1766
+ }
1767
+ }
1768
+ };
1848
1769
  }
1849
1770
  }
1850
1771
  });
1851
1772
 
1852
- // lib/file.js
1853
- var require_file = __commonJS({
1854
- "lib/file.js"(exports2) {
1773
+ // lib/workletFactory.js
1774
+ var require_workletFactory = __commonJS({
1775
+ "lib/workletFactory.js"(exports2) {
1855
1776
  "use strict";
1777
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1778
+ return mod && mod.__esModule ? mod : { "default": mod };
1779
+ };
1856
1780
  Object.defineProperty(exports2, "__esModule", { value: true });
1857
- exports2.processIfWorkletFile = processIfWorkletFile;
1858
- exports2.isImplicitContextObject = isImplicitContextObject;
1781
+ exports2.makeWorkletFactory = makeWorkletFactory;
1782
+ var generator_1 = __importDefault(require("@babel/generator"));
1859
1783
  var types_12 = require("@babel/types");
1860
- var contextObject_12 = require_contextObject();
1784
+ var assert_1 = require("assert");
1785
+ var path_1 = require("path");
1786
+ var closure_1 = require_closure();
1787
+ var generate_1 = require_generate();
1788
+ var hermesBytecode_1 = require_hermesBytecode();
1789
+ var imports_1 = require_imports();
1790
+ var transform_1 = require_transform();
1861
1791
  var types_2 = require_types();
1862
- function processIfWorkletFile(path, state) {
1863
- if (!path.node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
1864
- return false;
1865
- }
1866
- path.node.directives = path.node.directives.filter((functionDirective) => functionDirective.value.value !== "worklet");
1867
- processWorkletFile(path, state);
1868
- return true;
1869
- }
1870
- function processWorkletFile(programPath, state) {
1871
- const statements = programPath.get("body");
1872
- dehoistCommonJSExports(programPath.node);
1873
- statements.forEach((statement) => {
1874
- const candidatePath = getCandidate(statement);
1875
- processWorkletizableEntity(candidatePath, state);
1792
+ var utils_1 = require_utils();
1793
+ var workletStringCode_1 = require_workletStringCode();
1794
+ var REAL_VERSION = require("../package.json").version;
1795
+ var MOCK_VERSION = "x.y.z";
1796
+ function makeWorkletFactory(fun, state) {
1797
+ var _a;
1798
+ const includeClosure = state.opts.bundleMode || !hasDirective(fun, "no-worklet-closure");
1799
+ const limitInitDataHoisting = hasDirective(fun, "limit-init-data-hoisting");
1800
+ stripWorkletDirectives(fun);
1801
+ (0, assert_1.strict)(state.file.opts.filename, "`state.file.opts.filename` is undefined.");
1802
+ const codeObject = (0, generator_1.default)(fun.node, {
1803
+ sourceMaps: true,
1804
+ sourceFileName: state.file.opts.filename
1876
1805
  });
1877
- }
1878
- function getCandidate(statementPath) {
1879
- if (statementPath.isExportNamedDeclaration() || statementPath.isExportDefaultDeclaration()) {
1880
- return statementPath.get("declaration");
1806
+ codeObject.code = "(" + (fun.isObjectMethod() ? "function " : "") + codeObject.code + "\n)";
1807
+ const transformed = (0, transform_1.workletTransformSync)(codeObject.code, {
1808
+ extraPlugins: [...extraPlugins, ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []],
1809
+ extraPresets: state.opts.extraPresets,
1810
+ filename: state.file.opts.filename,
1811
+ ast: true,
1812
+ babelrc: false,
1813
+ configFile: false,
1814
+ inputSourceMap: codeObject.map
1815
+ });
1816
+ (0, assert_1.strict)(transformed, "`transformed` is undefined.");
1817
+ (0, assert_1.strict)(transformed.ast, "`transformed.ast` is undefined.");
1818
+ const { closureVariables, moduleBindingsToImport, relativeBindingsToImport } = includeClosure ? (0, closure_1.getClosure)(fun, state) : {
1819
+ closureVariables: [],
1820
+ moduleBindingsToImport: /* @__PURE__ */ new Set(),
1821
+ relativeBindingsToImport: /* @__PURE__ */ new Set()
1822
+ };
1823
+ const clone = (0, types_12.cloneNode)(fun.node);
1824
+ const funExpression = (0, types_12.isBlockStatement)(clone.body) ? (0, types_12.functionExpression)(null, clone.params, clone.body, clone.generator, clone.async) : clone;
1825
+ const { workletName, reactName } = makeWorkletName(fun, state);
1826
+ let mutatedClosureVariables;
1827
+ if (state.opts.bundleMode) {
1828
+ mutatedClosureVariables = closureVariables.map((variable) => (0, types_12.cloneNode)(variable, true));
1881
1829
  } else {
1882
- return statementPath;
1830
+ mutatedClosureVariables = closureVariables;
1883
1831
  }
1884
- }
1885
- function processWorkletizableEntity(nodePath, state) {
1886
- var _a;
1887
- if ((0, types_2.isWorkletizableFunctionPath)(nodePath)) {
1888
- if (nodePath.isArrowFunctionExpression()) {
1889
- replaceImplicitReturnWithBlock(nodePath.node);
1832
+ let [funString, sourceMapString] = (0, workletStringCode_1.buildWorkletString)(transformed.ast, state, mutatedClosureVariables, workletName, transformed.map);
1833
+ (0, assert_1.strict)(funString, "`funString` is undefined.");
1834
+ const workletHash = hash(funString);
1835
+ let lineOffset = 1;
1836
+ if (closureVariables.length > 0) {
1837
+ lineOffset -= closureVariables.length + 2;
1838
+ }
1839
+ const pathForStringDefinitions = fun.parentPath.isProgram() ? fun : fun.findParent((path) => {
1840
+ var _a2, _b;
1841
+ return (_b = (_a2 = path.parentPath) === null || _a2 === void 0 ? void 0 : _a2.isProgram()) !== null && _b !== void 0 ? _b : false;
1842
+ });
1843
+ (0, assert_1.strict)(pathForStringDefinitions, "`pathForStringDefinitions` is null.");
1844
+ (0, assert_1.strict)(pathForStringDefinitions.parentPath, "`pathForStringDefinitions.parentPath` is null.");
1845
+ const initDataId = pathForStringDefinitions.parentPath.scope.generateUidIdentifier(`worklet_${workletHash}_init_data`);
1846
+ const shouldIncludeInitData = !state.opts.omitNativeOnlyData && !state.opts.bundleMode;
1847
+ const shouldEmitBytecode = !!state.opts.hermesBytecode && (0, utils_1.isRelease)(state) && shouldIncludeInitData;
1848
+ const bytecode = shouldEmitBytecode ? (0, hermesBytecode_1.compileWorkletToHbc)(funString, workletHash, state) : null;
1849
+ const initDataObjectExpression = (0, types_12.objectExpression)(bytecode ? [
1850
+ (0, types_12.objectProperty)((0, types_12.identifier)("bytecode"), (0, types_12.memberExpression)((0, types_12.newExpression)((0, types_12.identifier)("Uint8Array"), [
1851
+ (0, types_12.arrayExpression)(Array.from(bytecode, (byte) => (0, types_12.numericLiteral)(byte)))
1852
+ ]), (0, types_12.identifier)("buffer")))
1853
+ ] : [(0, types_12.objectProperty)((0, types_12.identifier)("code"), (0, types_12.stringLiteral)(funString))]);
1854
+ const shouldInjectLocation = !(0, utils_1.isRelease)(state);
1855
+ if (shouldInjectLocation) {
1856
+ let location = state.file.opts.filename;
1857
+ if (state.opts.relativeSourceLocation) {
1858
+ location = (0, path_1.relative)(state.cwd, location);
1859
+ sourceMapString = sourceMapString === null || sourceMapString === void 0 ? void 0 : sourceMapString.replace(toPosix(state.file.opts.filename), toPosix(location));
1890
1860
  }
1891
- appendWorkletDirective(nodePath.node.body);
1892
- } else if ((0, types_2.isWorkletizableObjectPath)(nodePath)) {
1893
- if (isImplicitContextObject(nodePath)) {
1894
- appendWorkletContextObjectMarker(nodePath.node);
1861
+ location = toPosix(location);
1862
+ initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("location"), (0, types_12.stringLiteral)(location)));
1863
+ }
1864
+ if (!bytecode && sourceMapString) {
1865
+ initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("sourceMap"), (0, types_12.stringLiteral)(sourceMapString)));
1866
+ }
1867
+ if (shouldIncludeInitData) {
1868
+ const initDataDeclaration = (0, types_12.variableDeclaration)("const", [
1869
+ (0, types_12.variableDeclarator)(initDataId, initDataObjectExpression)
1870
+ ]);
1871
+ if (limitInitDataHoisting) {
1872
+ fun.getFunctionParent().node.body.body.unshift(initDataDeclaration);
1895
1873
  } else {
1896
- processWorkletAggregator(nodePath, state);
1897
- }
1898
- } else if (nodePath.isVariableDeclaration()) {
1899
- processVariableDeclaration(nodePath, state);
1900
- } else if (nodePath.isClassDeclaration()) {
1901
- appendWorkletClassMarker(nodePath.node.body);
1902
- if ((_a = nodePath.node.id) === null || _a === void 0 ? void 0 : _a.name) {
1903
- state.classesToWorkletize.push({
1904
- node: nodePath.node,
1905
- name: nodePath.node.id.name
1906
- });
1874
+ pathForStringDefinitions.insertBefore(initDataDeclaration);
1907
1875
  }
1908
1876
  }
1909
- }
1910
- function processVariableDeclaration(variableDeclarationPath, state) {
1911
- const declarations = variableDeclarationPath.get("declarations");
1912
- declarations.forEach((declaration) => {
1913
- const initPath = declaration.get("init");
1914
- if (initPath.isExpression()) {
1915
- processWorkletizableEntity(initPath, state);
1916
- }
1917
- });
1918
- }
1919
- function processWorkletAggregator(objectPath, state) {
1920
- const properties = objectPath.get("properties");
1921
- properties.forEach((property) => {
1922
- if (property.isObjectMethod()) {
1923
- appendWorkletDirective(property.node.body);
1924
- } else if (property.isObjectProperty()) {
1925
- const valuePath = property.get("value");
1926
- processWorkletizableEntity(valuePath, state);
1877
+ (0, assert_1.strict)(!(0, types_12.isFunctionDeclaration)(funExpression), "`funExpression` is a `FunctionDeclaration`.");
1878
+ (0, assert_1.strict)(!(0, types_12.isObjectMethod)(funExpression), "`funExpression` is an `ObjectMethod`.");
1879
+ const statements = [
1880
+ (0, types_12.variableDeclaration)("const", [
1881
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(reactName), funExpression)
1882
+ ]),
1883
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__closure"), false), (0, types_12.objectExpression)(closureVariables.map((variable) => !state.opts.bundleMode && variable.name.endsWith(types_2.workletClassFactorySuffix) ? (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.memberExpression)((0, types_12.identifier)(variable.name.slice(0, variable.name.length - types_2.workletClassFactorySuffix.length)), (0, types_12.identifier)(variable.name))) : (0, types_12.objectProperty)((0, types_12.cloneNode)(variable, true), (0, types_12.cloneNode)(variable, true), false, true))))),
1884
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__workletHash"), false), (0, types_12.numericLiteral)(workletHash)))
1885
+ ];
1886
+ const shouldInjectVersion = !(0, utils_1.isRelease)(state);
1887
+ if (shouldInjectVersion) {
1888
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__pluginVersion")), (0, types_12.stringLiteral)(shouldMockVersion() ? MOCK_VERSION : REAL_VERSION))));
1889
+ }
1890
+ if (shouldIncludeInitData) {
1891
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__initData"), false), (0, types_12.cloneNode)(initDataId, true))));
1892
+ }
1893
+ if (!(0, utils_1.isRelease)(state) && !state.opts.bundleMode) {
1894
+ statements.unshift((0, types_12.variableDeclaration)("const", [
1895
+ (0, types_12.variableDeclarator)((0, types_12.identifier)("_e"), (0, types_12.arrayExpression)([
1896
+ (0, types_12.newExpression)((0, types_12.memberExpression)((0, types_12.identifier)("global"), (0, types_12.identifier)("Error")), []),
1897
+ (0, types_12.numericLiteral)(lineOffset),
1898
+ (0, types_12.numericLiteral)(-27)
1899
+ // the placement of opening bracket after Exception in line that defined '_e' variable
1900
+ ]))
1901
+ ]));
1902
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__stackDetails"), false), (0, types_12.identifier)("_e"))));
1903
+ }
1904
+ statements.push((0, types_12.returnStatement)((0, types_12.identifier)(reactName)));
1905
+ const factoryParams = closureVariables.map((variableId) => {
1906
+ const clonedId = (0, types_12.cloneNode)(variableId, true);
1907
+ if (!state.opts.bundleMode && clonedId.name.endsWith(types_2.workletClassFactorySuffix)) {
1908
+ clonedId.name = clonedId.name.slice(0, clonedId.name.length - types_2.workletClassFactorySuffix.length);
1927
1909
  }
1910
+ return clonedId;
1928
1911
  });
1929
- }
1930
- function replaceImplicitReturnWithBlock(path) {
1931
- if (!(0, types_12.isBlockStatement)(path.body)) {
1932
- path.body = (0, types_12.blockStatement)([(0, types_12.returnStatement)(path.body)]);
1912
+ if (shouldIncludeInitData) {
1913
+ factoryParams.unshift((0, types_12.cloneNode)(initDataId, true));
1933
1914
  }
1934
- }
1935
- function appendWorkletDirective(node) {
1936
- if (!node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
1937
- node.directives.push((0, types_12.directive)((0, types_12.directiveLiteral)("worklet")));
1915
+ const factoryParamObjectPattern = (0, types_12.objectPattern)(factoryParams.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1916
+ const factory = (0, types_12.functionExpression)((0, types_12.identifier)(workletName + "Factory"), [factoryParamObjectPattern], (0, types_12.blockStatement)(statements));
1917
+ const factoryCallArgs = factoryParams.map((param) => (0, types_12.cloneNode)(param, true));
1918
+ const factoryCallParamPack = (0, types_12.objectExpression)(factoryCallArgs.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1919
+ if (state.opts.bundleMode) {
1920
+ (0, imports_1.updateRelativeRequires)(factory, state);
1921
+ (0, generate_1.generateWorkletFile)(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state);
1938
1922
  }
1923
+ factory.workletized = true;
1924
+ return { factory, factoryCallParamPack, workletHash };
1939
1925
  }
1940
- function appendWorkletContextObjectMarker(objectExpression) {
1941
- if (objectExpression.properties.some((value) => (0, types_12.isObjectProperty)(value) && (0, types_12.isIdentifier)(value.key) && value.key.name === contextObject_12.contextObjectMarker)) {
1942
- return;
1926
+ function hasDirective(path, directiveText) {
1927
+ if (!path.node.body) {
1928
+ return false;
1943
1929
  }
1944
- objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${contextObject_12.contextObjectMarker}`), (0, types_12.booleanLiteral)(true)));
1930
+ const bodyPath = path.get("body");
1931
+ let has = false;
1932
+ if (bodyPath.isBlockStatement()) {
1933
+ has = bodyPath.get("directives").some((directivePath) => {
1934
+ if (directivePath.isDirective() && directivePath.node.value.value === directiveText) {
1935
+ return true;
1936
+ }
1937
+ });
1938
+ }
1939
+ return has;
1945
1940
  }
1946
- function isImplicitContextObject(path) {
1947
- const propertyPaths = path.get("properties");
1948
- return propertyPaths.some((propertyPath) => {
1949
- if (!propertyPath.isObjectMethod()) {
1950
- return false;
1941
+ function stripWorkletDirectives(fun) {
1942
+ fun.traverse({
1943
+ DirectiveLiteral(nodePath) {
1944
+ if ((nodePath.node.value === "worklet" || nodePath.node.value === "no-worklet-closure" || nodePath.node.value === "limit-init-data-hoisting") && nodePath.getFunctionParent() === fun) {
1945
+ nodePath.parentPath.remove();
1946
+ }
1951
1947
  }
1952
- return hasThisExpression(propertyPath);
1953
1948
  });
1954
1949
  }
1955
- function hasThisExpression(path) {
1956
- let result = false;
1957
- path.traverse({
1958
- ThisExpression(thisPath) {
1959
- result = true;
1960
- thisPath.stop();
1961
- }
1962
- });
1963
- return result;
1950
+ function shouldMockVersion() {
1951
+ return process.env.WORKLETS_JEST_SHOULD_MOCK_VERSION === "1";
1964
1952
  }
1965
- function appendWorkletClassMarker(classBody) {
1966
- classBody.body.push((0, types_12.classProperty)((0, types_12.identifier)("__workletClass"), (0, types_12.booleanLiteral)(true)));
1953
+ function hash(str) {
1954
+ let i = str.length;
1955
+ let hash1 = 5381;
1956
+ let hash2 = 52711;
1957
+ while (i--) {
1958
+ const char = str.charCodeAt(i);
1959
+ hash1 = hash1 * 33 ^ char;
1960
+ hash2 = hash2 * 33 ^ char;
1961
+ }
1962
+ return (hash1 >>> 0) * 4096 + (hash2 >>> 0);
1967
1963
  }
1968
- function dehoistCommonJSExports(program) {
1969
- const statements = program.body;
1970
- let end = statements.length;
1971
- let current = 0;
1972
- while (current < end) {
1973
- const statement = statements[current];
1974
- if (!isCommonJSExport(statement)) {
1975
- current++;
1976
- continue;
1964
+ function makeWorkletName(fun, state) {
1965
+ let source = "unknownFile";
1966
+ if (state.file.opts.filename) {
1967
+ const filepath = state.file.opts.filename;
1968
+ source = (0, path_1.basename)(filepath);
1969
+ const splitFilepath = filepath.split(/[\\/]/);
1970
+ const nodeModulesIndex = splitFilepath.indexOf("node_modules");
1971
+ if (nodeModulesIndex !== -1) {
1972
+ const libraryName = splitFilepath[nodeModulesIndex + 1];
1973
+ source = `${libraryName}_${source}`;
1977
1974
  }
1978
- const exportStatement = statements.splice(current, 1);
1979
- statements.push(...exportStatement);
1980
- end--;
1981
1975
  }
1976
+ const suffix = `${source}${state.workletNumber++}`;
1977
+ let reactName = "";
1978
+ if ((0, types_12.isObjectMethod)(fun.node) && (0, types_12.isIdentifier)(fun.node.key)) {
1979
+ reactName = fun.node.key.name;
1980
+ } else if (((0, types_12.isFunctionDeclaration)(fun.node) || (0, types_12.isFunctionExpression)(fun.node)) && (0, types_12.isIdentifier)(fun.node.id)) {
1981
+ reactName = fun.node.id.name;
1982
+ }
1983
+ const workletName = reactName ? (0, types_12.toIdentifier)(`${reactName}_${suffix}`) : (0, types_12.toIdentifier)(suffix);
1984
+ reactName = reactName || (0, types_12.toIdentifier)(suffix);
1985
+ return { workletName, reactName };
1982
1986
  }
1983
- function isCommonJSExport(statement) {
1984
- return (0, types_12.isExpressionStatement)(statement) && (0, types_12.isAssignmentExpression)(statement.expression) && (0, types_12.isMemberExpression)(statement.expression.left) && (0, types_12.isIdentifier)(statement.expression.left.object) && statement.expression.left.object.name === "exports";
1987
+ function toPosix(p) {
1988
+ return path_1.sep === "/" ? p : p.split(path_1.sep).join("/");
1985
1989
  }
1990
+ var extraPlugins = [
1991
+ require.resolve("@babel/plugin-transform-shorthand-properties"),
1992
+ require.resolve("@babel/plugin-transform-arrow-functions"),
1993
+ require.resolve("@babel/plugin-transform-optional-chaining"),
1994
+ require.resolve("@babel/plugin-transform-nullish-coalescing-operator"),
1995
+ [
1996
+ require.resolve("@babel/plugin-transform-template-literals"),
1997
+ { loose: true }
1998
+ ]
1999
+ ];
1986
2000
  }
1987
2001
  });
1988
2002
 
1989
- // lib/inlineStylesWarning.js
1990
- var require_inlineStylesWarning = __commonJS({
1991
- "lib/inlineStylesWarning.js"(exports2) {
2003
+ // lib/workletFactoryCall.js
2004
+ var require_workletFactoryCall = __commonJS({
2005
+ "lib/workletFactoryCall.js"(exports2) {
1992
2006
  "use strict";
1993
2007
  Object.defineProperty(exports2, "__esModule", { value: true });
1994
- exports2.processInlineStylesWarning = processInlineStylesWarning;
2008
+ exports2.makeWorkletFactoryCall = makeWorkletFactoryCall;
1995
2009
  var types_12 = require("@babel/types");
1996
- var assert_1 = require("assert");
1997
- var utils_1 = require_utils();
1998
- function generateInlineStylesWarning(path) {
1999
- return (0, types_12.callExpression)((0, types_12.arrowFunctionExpression)([], (0, types_12.blockStatement)([
2000
- (0, types_12.expressionStatement)((0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.identifier)("console"), (0, types_12.identifier)("warn")), [
2001
- (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
2002
- (0, types_12.stringLiteral)("react-native-reanimated")
2003
- ]), (0, types_12.identifier)("getUseOfValueInStyleWarning")), [])
2004
- ])),
2005
- (0, types_12.returnStatement)(path.node)
2006
- ])), []);
2007
- }
2008
- function processPropertyValueForInlineStylesWarning(path) {
2009
- if (path.isMemberExpression() && (0, types_12.isIdentifier)(path.node.property)) {
2010
- if (!path.node.computed && path.node.property.name === "value") {
2011
- path.replaceWith(generateInlineStylesWarning(path));
2012
- }
2013
- }
2014
- }
2015
- function processTransformPropertyForInlineStylesWarning(path) {
2016
- if ((0, types_12.isArrayExpression)(path.node)) {
2017
- const elements = path.get("elements");
2018
- (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
2019
- for (const element of elements) {
2020
- if (element.isObjectExpression()) {
2021
- processStyleObjectForInlineStylesWarning(element);
2022
- }
2023
- }
2024
- }
2025
- }
2026
- function processStyleObjectForInlineStylesWarning(path) {
2027
- const properties = path.get("properties");
2028
- for (const property of properties) {
2029
- if (property.isObjectProperty()) {
2030
- const value = property.get("value");
2031
- if ((0, types_12.isIdentifier)(property.node.key) && property.node.key.name === "transform") {
2032
- processTransformPropertyForInlineStylesWarning(value);
2033
- } else {
2034
- processPropertyValueForInlineStylesWarning(value);
2035
- }
2036
- }
2010
+ var types_2 = require_types();
2011
+ var workletFactory_1 = require_workletFactory();
2012
+ function makeWorkletFactoryCall(path, state) {
2013
+ const { factory, factoryCallParamPack, workletHash } = (0, workletFactory_1.makeWorkletFactory)(path, state);
2014
+ let factoryCall;
2015
+ if (state.opts.bundleMode) {
2016
+ factoryCall = (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
2017
+ (0, types_12.stringLiteral)(`react-native-worklets/${types_2.generatedWorkletsDir}/${workletHash}.js`)
2018
+ ]), (0, types_12.identifier)("default")), [factoryCallParamPack]);
2019
+ } else {
2020
+ factoryCall = (0, types_12.callExpression)(factory, [factoryCallParamPack]);
2037
2021
  }
2022
+ addStackTraceDataToWorkletFactory(path, factoryCall);
2023
+ const replacement = factoryCall;
2024
+ return replacement;
2038
2025
  }
2039
- function processInlineStylesWarning(path, state) {
2040
- if ((0, utils_1.isRelease)(state)) {
2041
- return;
2042
- }
2043
- if (state.opts.disableInlineStylesWarning) {
2044
- return;
2045
- }
2046
- if (path.node.name.name !== "style") {
2047
- return;
2048
- }
2049
- if (!(0, types_12.isJSXExpressionContainer)(path.node.value)) {
2050
- return;
2051
- }
2052
- const expression = path.get("value").get("expression");
2053
- (0, assert_1.strict)(!Array.isArray(expression), "`expression` should not be an array.");
2054
- if (expression.isArrayExpression()) {
2055
- const elements = expression.get("elements");
2056
- (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
2057
- for (const element of elements) {
2058
- if (element.isObjectExpression()) {
2059
- processStyleObjectForInlineStylesWarning(element);
2060
- }
2061
- }
2062
- } else if (expression.isObjectExpression()) {
2063
- processStyleObjectForInlineStylesWarning(expression);
2026
+ function addStackTraceDataToWorkletFactory(path, workletFactoryCall) {
2027
+ const originalWorkletLocation = path.node.loc;
2028
+ if (originalWorkletLocation) {
2029
+ workletFactoryCall.callee.loc = {
2030
+ filename: originalWorkletLocation.filename,
2031
+ identifierName: originalWorkletLocation.identifierName,
2032
+ start: originalWorkletLocation.start,
2033
+ end: originalWorkletLocation.start
2034
+ };
2064
2035
  }
2065
2036
  }
2066
2037
  }
2067
2038
  });
2068
2039
 
2069
- // lib/webOptimization.js
2070
- var require_webOptimization = __commonJS({
2071
- "lib/webOptimization.js"(exports2) {
2040
+ // lib/workletSubstitution.js
2041
+ var require_workletSubstitution = __commonJS({
2042
+ "lib/workletSubstitution.js"(exports2) {
2072
2043
  "use strict";
2073
2044
  Object.defineProperty(exports2, "__esModule", { value: true });
2074
- exports2.substituteWebCallExpression = substituteWebCallExpression;
2045
+ exports2.processIfWithWorkletDirective = processIfWithWorkletDirective;
2046
+ exports2.processWorklet = processWorklet;
2047
+ exports2.substituteObjectMethodWithObjectProperty = substituteObjectMethodWithObjectProperty;
2075
2048
  var types_12 = require("@babel/types");
2076
- function substituteWebCallExpression(path) {
2077
- const callee = path.node.callee;
2078
- if ((0, types_12.isIdentifier)(callee)) {
2079
- const name = callee.name;
2080
- if (name === "isWeb" || name === "shouldBeUseWeb") {
2081
- path.replaceWith((0, types_12.booleanLiteral)(true));
2049
+ var types_2 = require_types();
2050
+ var utils_1 = require_utils();
2051
+ var workletFactoryCall_1 = require_workletFactoryCall();
2052
+ function processIfWithWorkletDirective(path, state) {
2053
+ if (!(0, types_12.isBlockStatement)(path.node.body)) {
2054
+ return false;
2055
+ }
2056
+ if (!hasWorkletDirective(path.node.body.directives)) {
2057
+ return false;
2058
+ }
2059
+ processWorklet(path, state);
2060
+ return true;
2061
+ }
2062
+ function processWorklet(path, state) {
2063
+ path.traverse({
2064
+ // @ts-expect-error TypeScript doesn't like this syntax here.
2065
+ [types_2.WorkletizableFunction](subPath, passedState) {
2066
+ processIfWithWorkletDirective(subPath, passedState);
2082
2067
  }
2068
+ }, state);
2069
+ const workletFactoryCall = (0, workletFactoryCall_1.makeWorkletFactoryCall)(path, state);
2070
+ substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall);
2071
+ path.scope.getProgramParent().crawl();
2072
+ }
2073
+ function hasWorkletDirective(directives) {
2074
+ return directives.some((directive) => (0, types_12.isDirectiveLiteral)(directive.value) && directive.value.value === "worklet");
2075
+ }
2076
+ function substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall) {
2077
+ var _a;
2078
+ if (path.isObjectMethod()) {
2079
+ substituteObjectMethodWithObjectProperty(path, workletFactoryCall);
2080
+ } else {
2081
+ const name = "id" in path.node ? (_a = path.node.id) === null || _a === void 0 ? void 0 : _a.name : void 0;
2082
+ (0, utils_1.replaceWithFactoryCall)(path, name, workletFactoryCall);
2083
2083
  }
2084
2084
  }
2085
+ function substituteObjectMethodWithObjectProperty(path, workletFactoryCall) {
2086
+ const replacement = (0, types_12.objectProperty)(path.node.key, workletFactoryCall);
2087
+ path.replaceWith(replacement);
2088
+ }
2085
2089
  }
2086
2090
  });
2087
2091
 
2088
2092
  // lib/plugin.js
2089
2093
  Object.defineProperty(exports, "__esModule", { value: true });
2094
+ exports.getAutoworkletizationMicroPlugin = getAutoworkletizationMicroPlugin;
2090
2095
  var autoworkletization_1 = require_autoworkletization();
2091
2096
  var bundleMode_1 = require_bundleMode();
2092
2097
  var class_1 = require_class();
2098
+ var classMethod_1 = require_classMethod();
2093
2099
  var contextObject_1 = require_contextObject();
2094
2100
  var file_1 = require_file();
2095
2101
  var globals_1 = require_globals();
@@ -2116,13 +2122,13 @@ module.exports = function WorkletsBabelPlugin() {
2116
2122
  pre() {
2117
2123
  runWithTaggedExceptions(this, () => {
2118
2124
  (0, globals_1.initializeState)(this);
2125
+ this.file.path.traverse(getAutoworkletizationMicroPlugin(), this);
2119
2126
  });
2120
2127
  },
2121
2128
  visitor: {
2122
2129
  CallExpression: {
2123
2130
  enter(path, state) {
2124
2131
  runWithTaggedExceptions(state, () => {
2125
- (0, autoworkletization_1.processCalleesAutoworkletizableCallbacks)(path, state);
2126
2132
  if (state.opts.substituteWebPlatformChecks) {
2127
2133
  (0, webOptimization_1.substituteWebCallExpression)(path);
2128
2134
  }
@@ -2131,7 +2137,9 @@ module.exports = function WorkletsBabelPlugin() {
2131
2137
  },
2132
2138
  [types_1.WorkletizableFunction]: {
2133
2139
  enter(path, state) {
2134
- runWithTaggedExceptions(state, () => (0, workletSubstitution_1.processIfWithWorkletDirective)(path, state) || (0, autoworkletization_1.processIfAutoworkletizableCallback)(path, state));
2140
+ runWithTaggedExceptions(state, () => {
2141
+ (0, workletSubstitution_1.processIfWithWorkletDirective)(path, state);
2142
+ });
2135
2143
  }
2136
2144
  },
2137
2145
  ObjectExpression: {
@@ -2151,6 +2159,13 @@ module.exports = function WorkletsBabelPlugin() {
2151
2159
  });
2152
2160
  }
2153
2161
  },
2162
+ ClassMethod: {
2163
+ enter(path, state) {
2164
+ runWithTaggedExceptions(state, () => {
2165
+ (0, classMethod_1.processIfWorkletMethod)(path);
2166
+ });
2167
+ }
2168
+ },
2154
2169
  Program: {
2155
2170
  enter(path, state) {
2156
2171
  runWithTaggedExceptions(state, () => {
@@ -2173,4 +2188,18 @@ module.exports = function WorkletsBabelPlugin() {
2173
2188
  }
2174
2189
  };
2175
2190
  };
2191
+ function getAutoworkletizationMicroPlugin() {
2192
+ return {
2193
+ CallExpression: {
2194
+ enter(path, state) {
2195
+ (0, autoworkletization_1.handleWorkletizableCallback)(path, state);
2196
+ }
2197
+ },
2198
+ [types_1.WorkletizableFunction]: {
2199
+ enter(path) {
2200
+ (0, autoworkletization_1.addDirectivesToKnownCallback)(path);
2201
+ }
2202
+ }
2203
+ };
2204
+ }
2176
2205
  //# sourceMappingURL=index.js.map