casper-context 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +253 -0
  2. package/dist/index.js +9 -0
  3. package/dist/lifecycle/post.js +239 -0
  4. package/dist/lifecycle/pre.js +113 -0
  5. package/dist/plugin.js +57 -0
  6. package/dist/transforms/autoContextTransform.js +1 -0
  7. package/dist/transforms/contextTransform.js +1 -0
  8. package/dist/transforms/stateTransform.js +1 -0
  9. package/dist/types/plugin.d.js +1 -0
  10. package/dist/utils/astHelpers.js +644 -0
  11. package/dist/utils/constants.js +111 -0
  12. package/dist/utils/names.js +1 -0
  13. package/dist/utils/scope.js +1 -0
  14. package/dist/utils/utilityHelpers.js +606 -0
  15. package/dist/visitors/AssignmentExpression.js +104 -0
  16. package/dist/visitors/CallExpression.js +1 -0
  17. package/dist/visitors/FunctionDeclaration.js +116 -0
  18. package/dist/visitors/Identifier.js +123 -0
  19. package/dist/visitors/JSXElement.js +1 -0
  20. package/dist/visitors/Program.js +278 -0
  21. package/dist/visitors/ReturnStatement.js +81 -0
  22. package/dist/visitors/VariableDeclaration.js +209 -0
  23. package/package.json +60 -0
  24. package/src/index.js +2 -0
  25. package/src/lifecycle/post.js +237 -0
  26. package/src/lifecycle/pre.js +103 -0
  27. package/src/plugin.js +51 -0
  28. package/src/transforms/autoContextTransform.js +0 -0
  29. package/src/transforms/contextTransform.js +0 -0
  30. package/src/transforms/stateTransform.js +0 -0
  31. package/src/types/plugin.d.ts +0 -0
  32. package/src/utils/astHelpers.js +767 -0
  33. package/src/utils/constants.js +102 -0
  34. package/src/utils/names.js +0 -0
  35. package/src/utils/scope.js +0 -0
  36. package/src/utils/utilityHelpers.js +636 -0
  37. package/src/visitors/AssignmentExpression.js +100 -0
  38. package/src/visitors/CallExpression.js +0 -0
  39. package/src/visitors/FunctionDeclaration.js +114 -0
  40. package/src/visitors/Identifier.js +142 -0
  41. package/src/visitors/JSXElement.js +0 -0
  42. package/src/visitors/Program.js +280 -0
  43. package/src/visitors/ReturnStatement.js +75 -0
  44. package/src/visitors/VariableDeclaration.js +216 -0
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = assignmentExpressionVisitor;
7
+ var _constants = require("../utils/constants");
8
+ var _utilityHelpers = require("../utils/utilityHelpers");
9
+ var _astHelpers = require("../utils/astHelpers");
10
+ /**
11
+ * @fileoverview Transformation Logic & Node Orchestration.
12
+ * This module integrates AST helpers with utility validators to perform
13
+ * the actual replacement of custom global variables (`_$_`) with
14
+ * React-compatible State and Context setters.
15
+ */
16
+
17
+ /**
18
+ * Core Constants
19
+ * @description
20
+ * - IDENTIFIER: Used to validate if the left-hand side of an assignment is a variable.
21
+ * - _CCTX_EMPTY: Fallback value for filenames or uninitialized state strings.
22
+ */
23
+
24
+ /**
25
+ * Utility & Validation Helpers
26
+ * @description
27
+ * - findContextByVar: Maps a `_$_` variable to its corresponding Context instance name.
28
+ * - isExcludeFile: Security/Performance gate to prevent processing ignored files.
29
+ */
30
+
31
+ /**
32
+ * AST Transformation Utilities
33
+ * @description The functional "engine" of the plugin that manipulates the Babel tree.
34
+ * - buildSpreadObject: Creates the updated state object for setters.
35
+ * - replaceWithSetState: Handles local component state updates.
36
+ * - buildUseContextInstance: Injects `useContext` hooks when variables are cross-component.
37
+ * - replaceWithContextSetState: Handles global/context-based state updates.
38
+ * - getComponentName: Identifies the immediate parent function.
39
+ * - getRootParentComponent: Recursively climbs the tree to find the top-level React Component.
40
+ */
41
+
42
+ /**
43
+ * @module Logger
44
+ * @description Provides a controlled logging interface for the Babel transformation process.
45
+ */
46
+
47
+ /**
48
+ * Babel visitor function for handling assignment expressions in the AST.
49
+ *
50
+ * This visitor inspects assignments in the code and replaces or augments them
51
+ * with state/context updates for variables registered in the `virtualRegistry`.
52
+ * It handles both direct component state updates and global/shared context updates.
53
+ *
54
+ * @param {NodePath} path - The Babel AST path representing the current node.
55
+ * @param {Object} state - Plugin state, including file info, config, and import metadata.
56
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate AST nodes.
57
+ * @param {Object<string, Object>} virtualRegistry - Registry of components and their
58
+ * registered variables/context info.
59
+ *
60
+ * @returns {void}
61
+ * Updates AST nodes in place and sets plugin state flags; no return value.
62
+ *
63
+ * @important
64
+ * - Only handles assignments where the left-hand identifier starts with the configured prefix.
65
+ * - Supports both direct component `useState` updates and context-based updates.
66
+ * - Automatically marks that a global context is needed (`state.needsGblContext = true`).
67
+ * - Injects `useState` import if missing.
68
+ * - Silent error handling; consider logging `e` for debugging.
69
+ */
70
+ function assignmentExpressionVisitor(path, state, t, virtualRegistry) {
71
+ try {
72
+ const fileName = state.filename || _constants._CCTX_EMPTY;
73
+ if (!(0, _utilityHelpers.isExcludeFile)(fileName, this.opts)) return;
74
+ if (path.node.left.type === _constants.IDENTIFIER) {
75
+ if (path.node.left.name?.startsWith(state.casperConfig.prefix)) {
76
+ state.needsGblContext = true;
77
+ const ctxName = (0, _utilityHelpers.findContextByVar)(path.node.left.name, virtualRegistry);
78
+ if (!ctxName) return;
79
+ let {
80
+ currentFuncParent,
81
+ componentName
82
+ } = (0, _astHelpers.getRootParentComponent)(path);
83
+ if (!componentName) return;
84
+ let isSameCMP = false;
85
+ if (ctxName.startsWith(componentName)) {
86
+ isSameCMP = true;
87
+ }
88
+ state.needsGblContext = true;
89
+ if (!state.importState.reactId && !state.importState.useStateId) {
90
+ state.needUseStateImport = true;
91
+ }
92
+ const updateFunction = (0, _astHelpers.buildSpreadObject)(path, t);
93
+ if (isSameCMP) {
94
+ (0, _astHelpers.replaceWithSetState)(path, t, ctxName, updateFunction);
95
+ } else {
96
+ (0, _astHelpers.buildUseContextInstance)(currentFuncParent, state, t, ctxName);
97
+ (0, _astHelpers.replaceWithContextSetState)(path, t, ctxName, updateFunction);
98
+ }
99
+ }
100
+ }
101
+ } catch (e) {
102
+ (0, _utilityHelpers.log)('error', '[::assignmentExpressionVisitor::]', e.message);
103
+ }
104
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.functionDeclarationExit = functionDeclarationExit;
7
+ var _utilityHelpers = require("../utils/utilityHelpers");
8
+ var _VariableDeclaration = require("./VariableDeclaration");
9
+ var _ReturnStatement = require("./ReturnStatement");
10
+ var _astHelpers = require("../utils/astHelpers");
11
+ var _constants = require("../utils/constants");
12
+ /**
13
+ * @fileoverview Logic Orchestration for Function Transformation.
14
+ * This module coordinates the 'Exit' phase of function traversal. It integrates
15
+ * specialized visitors for variable declarations and return statements to
16
+ * aggregate state metadata before injecting final React Hook declarations.
17
+ */
18
+
19
+ /**
20
+ * Validation & Hashing Utilities
21
+ * @description
22
+ * - isExcludeFile: Determines if the current file should be bypassed based on plugin configuration.
23
+ * - getFilePathHASH: Generates a unique identifier based on the file path to prevent naming collisions.
24
+ */
25
+
26
+ /**
27
+ * Specialized Sub-Visitors
28
+ * @description These visitors are manually invoked during the function's traversal
29
+ * to target specific node types within the component body.
30
+ * - functionReturnVariableDelarationVisitor: Extracts state-relevant variable data.
31
+ * - functionDeclarationReturnStatementVisitor: Processes JSX or return values for context binding.
32
+ */
33
+
34
+ /**
35
+ * AST Construction Helpers
36
+ * @description
37
+ * - buildCtxUseStateDeclaration: Physically constructs and injects the `useState`
38
+ * node into the Abstract Syntax Tree.
39
+ */
40
+
41
+ /**
42
+ * Core Constants
43
+ * @description
44
+ * - _CCTX_EMPTY: Provides a safe string fallback for file naming and path resolution.
45
+ */
46
+
47
+ /**
48
+ * @module Logger
49
+ * @description Provides a controlled logging interface for the Babel transformation process.
50
+ */
51
+
52
+ /**
53
+ * @important
54
+ * The coordination between these imports ensures that state is only injected
55
+ * once per component, and only if the component contains variables prefixed
56
+ * with the library's global identifier.
57
+ */
58
+
59
+ /**
60
+ * Babel visitor exit handler for `FunctionDeclaration` nodes.
61
+ *
62
+ * This function is invoked when exiting a function declaration during AST traversal.
63
+ * It inspects the function for any state variables registered in the `virtualRegistry`
64
+ * and transforms them into React `useState` declarations or context state as needed.
65
+ *
66
+ * @param {NodePath} path - The Babel AST path representing the current function declaration.
67
+ * @param {Object} state - Plugin state, including file info, config, and import metadata.
68
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate AST nodes.
69
+ * @param {Object<string, Object>} virtualRegistry - Registry of components and their
70
+ * registered variables/context info. Each key is `${componentName}_${fileHash}`.
71
+ *
72
+ * @returns {void}
73
+ * Modifies AST nodes in place to inject state declarations and context usage;
74
+ * does not return a value.
75
+ *
76
+ * @important
77
+ * - Skips files excluded by `isExcludeFile`.
78
+ * - Only processes functions with a valid name.
79
+ * - Collects local state variable declarations and return statements using
80
+ * `functionReturnVariableDelarationVisitor` and `functionDeclarationReturnStatementVisitor`.
81
+ * - Converts collected variables into an object expression for `buildCtxUseStateDeclaration`.
82
+ * - Silent error handling; errors are caught but ignored.
83
+ *
84
+ * @example
85
+ * ```js
86
+ * // During Babel traversal:
87
+ * functionDeclarationExit(path, state, t, virtualRegistry);
88
+ * // Injects useState or context declarations for local state variables in the function
89
+ * ```
90
+ */
91
+ function functionDeclarationExit(path, state, t, virtualRegistry) {
92
+ try {
93
+ const fileName = state.filename || _constants._CCTX_EMPTY;
94
+ if (!(0, _utilityHelpers.isExcludeFile)(fileName, this.opts)) return;
95
+ const name = path.node.id?.name;
96
+ if (!name) return;
97
+ const filePathHASH = (0, _utilityHelpers.getFilePathHASH)(fileName);
98
+ const key = `${name}_${filePathHASH}`;
99
+ const entry = virtualRegistry[key];
100
+ if (!entry || !entry.varNames.length) return;
101
+ const localStateVars = [];
102
+ path.traverse({
103
+ VariableDeclarator(varPath) {
104
+ _VariableDeclaration.functionReturnVariableDelarationVisitor.call(this, varPath, state, t, localStateVars);
105
+ },
106
+ ReturnStatement(retPath) {
107
+ _ReturnStatement.functionDeclarationReturnStatementVisitor.call(this, retPath, state, t, entry);
108
+ }
109
+ });
110
+ if (localStateVars.length === 0) return;
111
+ const objProps = localStateVars.map(v => t.objectProperty(t.identifier(v.name), v.init || t.nullLiteral()));
112
+ (0, _astHelpers.buildCtxUseStateDeclaration)(path, t, state, objProps, key);
113
+ } catch (e) {
114
+ (0, _utilityHelpers.log)('error', '[::functionDeclarationExit::]', e.message);
115
+ }
116
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = identifierVisitor;
7
+ var _constants = require("../utils/constants");
8
+ var _utilityHelpers = require("../utils/utilityHelpers");
9
+ var _astHelpers = require("../utils/astHelpers");
10
+ /**
11
+ * @fileoverview Variable Reference & Usage Orchestration.
12
+ * This module manages the detection and transformation of custom context variables
13
+ * when they are referenced in expressions. It handles the replacement of `_$_`
14
+ * identifiers with either local state accessors or injected Context hooks.
15
+ */
16
+
17
+ /**
18
+ * AST Node & Property Constants
19
+ * @description Identifiers for specific nodes and keys used to navigate the AST
20
+ * during variable resolution and replacement.
21
+ */
22
+
23
+ /**
24
+ * Validation & Discovery Utilities
25
+ * @description
26
+ * - isExcludeFile: Ensures the transformation doesn't run on ignored directories.
27
+ * - findContextByVar: Locates the specific Context instance associated with a variable name.
28
+ */
29
+
30
+ /**
31
+ * AST Transformation & Scope Helpers
32
+ * @description Functions that physically modify the code and resolve component hierarchy.
33
+ * - replaceWithContextState: Replaces a reference with a Context-based accessor.
34
+ * - replaceWithState: Replaces a reference with a local `useState` accessor.
35
+ * - buildUseContextInstance: Injects the `useContext` hook if the variable is defined elsewhere.
36
+ * - getRootParentComponent: Finds the top-level React Component to ensure hooks are valid.
37
+ */
38
+
39
+ /**
40
+ * @module Logger
41
+ * @description Provides a controlled logging interface for the Babel transformation process.
42
+ */
43
+
44
+ /**
45
+ * @important
46
+ * This module is highly sensitive to Scope. It must distinguish between a variable
47
+ * being "written to" (Assignment) and "read from" (Reference) to prevent
48
+ * infinite loops in the Babel transformation.
49
+ */
50
+
51
+ /**
52
+ * Babel visitor for handling identifier nodes in the AST.
53
+ *
54
+ * This visitor inspects identifiers that start with the configured Casper prefix.
55
+ * It determines whether the identifier corresponds to a registered component or
56
+ * context variable and replaces it with the appropriate state or context access
57
+ * expression. This handles both component-local state and global/shared context usage.
58
+ *
59
+ * @param {NodePath} path - The Babel AST path representing the current identifier node.
60
+ * @param {Object} state - Plugin state, including file info, configuration, and import metadata.
61
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate AST nodes.
62
+ * @param {Set<Node>} seen - A Set tracking identifiers that have already been processed to avoid duplicates.
63
+ * @param {Object<string, Object>} virtualRegistry - Registry of components and their
64
+ * registered variables/context info.
65
+ *
66
+ * @returns {void}
67
+ * Modifies AST nodes in place by replacing identifiers with either direct state access
68
+ * or context-based access. Does not return a value.
69
+ *
70
+ * @important
71
+ * - Skips identifiers that are part of declarations, assignments, object keys, or JSX expressions.
72
+ * - Only processes referenced identifiers matching the configured Casper prefix.
73
+ * - Sets `state.needsGblContext` when global context usage is required.
74
+ * - Automatically injects `useState` import if missing.
75
+ * - Differentiates between same-component state and context usage across components.
76
+ * - Errors are silently caught.
77
+ *
78
+ * @example
79
+ * ```js
80
+ * import identifierVisitor from './identifierVisitor';
81
+ *
82
+ * identifierVisitor(path, state, t, seen, virtualRegistry);
83
+ * // Replaces matching identifiers with state or context references
84
+ * ```
85
+ */
86
+ function identifierVisitor(path, state, t, seen, virtualRegistry) {
87
+ try {
88
+ const fileName = state.filename || _constants._CCTX_EMPTY;
89
+ if (!(0, _utilityHelpers.isExcludeFile)(fileName, this.opts)) return;
90
+ if (path.node?.name?.startsWith(state.casperConfig.prefix)) {
91
+ if (path.parent.type === _constants.VARIABLE_DECLARATOR && path.parentKey === _constants._CCTX_ID || path.parent.type === _constants.ASSIGNMENT_EXPRESSION && path.parentKey === _constants._CCTX_LEFT || path.parent.type === _constants.UPDATE_EXPRESSION && path.parentKey === _constants._CCTX_ARGUMENT) return;
92
+ if (path.parentPath.isObjectProperty() && path.parentKey === _constants._CCTX_KEY && !path.parent.computed) return;
93
+ if (path.findParent(p => p.isJSXExpressionContainer() || p.isJSXAttribute() || p.isJSXOpeningElement() || p.isJSXClosingElement() || p.isJSXMemberExpression())) return;
94
+ if (!path.isReferencedIdentifier()) return;
95
+ if (!seen.has(path.node)) {
96
+ seen.add(path.node);
97
+ state.needsGblContext = true;
98
+ let {
99
+ currentFuncParent,
100
+ componentName
101
+ } = (0, _astHelpers.getRootParentComponent)(path);
102
+ const ctxName = (0, _utilityHelpers.findContextByVar)(path.node.name, virtualRegistry);
103
+ if (!ctxName) return;
104
+ let isSameCMP = false;
105
+ if (ctxName.startsWith(componentName)) {
106
+ isSameCMP = true;
107
+ }
108
+ state.needsGblContext = true;
109
+ if (!state.importState.reactId && !state.importState.useStateId) {
110
+ state.needUseStateImport = true;
111
+ }
112
+ if (isSameCMP) {
113
+ (0, _astHelpers.replaceWithState)(path, t, ctxName);
114
+ } else {
115
+ (0, _astHelpers.buildUseContextInstance)(currentFuncParent, state, t, ctxName);
116
+ (0, _astHelpers.replaceWithContextState)(path, t, ctxName);
117
+ }
118
+ }
119
+ }
120
+ } catch (e) {
121
+ (0, _utilityHelpers.log)('error', '[::identifierVisitor::]', e.message);
122
+ }
123
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.programEnter = programEnter;
7
+ exports.programExit = programExit;
8
+ var _constants = require("../utils/constants");
9
+ var _utilityHelpers = require("../utils/utilityHelpers");
10
+ var _astHelpers = require("../utils/astHelpers");
11
+ /**
12
+ * @fileoverview Library Initialization & Dependency Injection Orchestrator.
13
+ * This module manages the "Prep Phase" of the transformation, ensuring that
14
+ * required React hooks and internal global context bridges are correctly
15
+ * imported or required before any code modifications occur.
16
+ */
17
+
18
+ /**
19
+ * Dependency & Alias Constants
20
+ * @description Identifiers for React and internal library references used to
21
+ * avoid naming collisions with user-defined variables.
22
+ */
23
+
24
+ /**
25
+ * File System & Lifecycle Utilities
26
+ * @description
27
+ * - CONTEXT_FILE_PATH: The absolute path to the generated context bridge.
28
+ * - resetVarsForFile: Cleanup utility to clear tracking caches between file traversals.
29
+ * - isExcludeFile: Security gate to prevent transformation of ignored files.
30
+ * - getFilePathHASH: Generates a unique, stable ID for the current file's state bucket.
31
+ */
32
+
33
+ /**
34
+ * AST Injection Helpers
35
+ * @description
36
+ * - buildRequireDeclaration: Injects CommonJS `require` statements at the top of the file.
37
+ */
38
+
39
+ /**
40
+ * @module Logger
41
+ * @description Provides a controlled logging interface for the Babel transformation process.
42
+ */
43
+
44
+ /**
45
+ * @important
46
+ * This module is responsible for "Stateful Reset." Every time a new file is
47
+ * entered, `resetVarsForFile` must be called to ensure that context variables
48
+ * from the previous file do not leak into the current transformation scope.
49
+ */
50
+
51
+ /**
52
+ * Resolves and collects React import information from a file's AST.
53
+ *
54
+ * This function inspects all import declarations in the given file's AST
55
+ * and identifies the React import. It tracks whether React was imported as
56
+ * a default import, named import, or namespace import, and whether `useState`
57
+ * is explicitly imported.
58
+ *
59
+ * @param {NodePath} path - The Babel AST path representing the file/program node.
60
+ * @param {Object} state - Plugin state object where resolved import information
61
+ * will be stored under `state.importState`.
62
+ * @param {Object} t - Babel types helper (`@babel/types`) used for AST type checks.
63
+ *
64
+ * @returns {void}
65
+ * Updates `state.importState` with the following structure:
66
+ * ```js
67
+ * {
68
+ * reactId: Identifier | null, // Local identifier for React import
69
+ * useStateId: Identifier | null, // Local identifier for useState import
70
+ * isDefault: boolean, // True if React is default-imported
71
+ * isNamed: boolean, // True if useState is explicitly named-imported
72
+ * isNamespace: boolean, // True if React is namespace-imported
73
+ * reactImportPath: ImportDeclaration | null, // AST node of React import
74
+ * }
75
+ * ```
76
+ *
77
+ * @important
78
+ * - Only resolves imports where `source.value` equals `REACT_IMPORT_CORE_NAME`.
79
+ * - Handles three import forms:
80
+ * - `import React from 'react'`
81
+ * - `import { useState } from 'react'`
82
+ * - `import * as ReactNS from 'react'`
83
+ * - Errors are silently caught; unresolved imports will leave `state.importState` with nulls.
84
+ *
85
+ * @example
86
+ * ```js
87
+ * importStateResolver(path, state, t);
88
+ * console.log(state.importState.reactId); // Identifier for React import
89
+ * console.log(state.importState.useStateId); // Identifier for useState if imported
90
+ * ```
91
+ */
92
+ function importStateResolver(path, state, t) {
93
+ try {
94
+ const importState = {
95
+ reactId: null,
96
+ useStateId: null,
97
+ isDefault: false,
98
+ isNamed: false,
99
+ isNamespace: false,
100
+ reactImportPath: null
101
+ };
102
+ path.node.body.forEach(node => {
103
+ if (!t.isImportDeclaration(node)) return;
104
+ if (node.source.value !== _constants.REACT_IMPORT_CORE_NAME) return;
105
+ importState.reactImportPath = node;
106
+ node.specifiers.forEach(spec => {
107
+ // import React from 'react'
108
+ if (t.isImportDefaultSpecifier(spec)) {
109
+ importState.reactId = spec.local;
110
+ importState.isDefault = true;
111
+ }
112
+
113
+ // import { useState } from 'react'
114
+ if (t.isImportSpecifier(spec)) {
115
+ if (spec.imported.name === _constants.REACT_IMPORT_USE_STATE_HOOKS_NAME) {
116
+ importState.useStateId = spec.local;
117
+ importState.isNamed = true;
118
+ }
119
+ }
120
+
121
+ // import * as ReactNS from 'react'
122
+ if (t.isImportNamespaceSpecifier(spec)) {
123
+ importState.reactId = spec.local;
124
+ importState.isNamespace = true;
125
+ }
126
+ });
127
+ });
128
+ state.importState = importState;
129
+ } catch (e) {
130
+ (0, _utilityHelpers.log)('error', '[::importStateResolver::]', e.message);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Resets the variable registry for the current file during AST traversal.
136
+ *
137
+ * This function clears any registered state variables in the `virtualRegistry`
138
+ * that are associated with the current file. It is useful for ensuring that
139
+ * state tracking does not leak across files when processing multiple files
140
+ * in the plugin.
141
+ *
142
+ * @param {Object} state - Plugin state, including the filename and plugin options.
143
+ * @param {Object<string, Object>} virtualRegistry - Registry of components and
144
+ * their registered variables/context info.
145
+ *
146
+ * @returns {void}
147
+ * Updates the `virtualRegistry` in place, resetting all variable names and
148
+ * default values associated with the current file.
149
+ *
150
+ * @important
151
+ * - Skips files excluded by `isExcludeFile`.
152
+ * - Uses a hash of the filename to identify the relevant registry entries.
153
+ * - Errors are silently caught.
154
+ *
155
+ * @example
156
+ * ```js
157
+ * resetRegisteryProcess(state, virtualRegistry);
158
+ * // Clears all state variables for the current file in the virtualRegistry
159
+ * ```
160
+ */
161
+ function resetRegisteryProcess(state, virtualRegistry) {
162
+ try {
163
+ const fileName = state.filename || _constants._CCTX_EMPTY;
164
+ if (!(0, _utilityHelpers.isExcludeFile)(fileName, this.opts)) return;
165
+ const hash = (0, _utilityHelpers.getFilePathHASH)(fileName);
166
+ (0, _utilityHelpers.resetVarsForFile)(virtualRegistry, hash);
167
+ } catch (e) {
168
+ (0, _utilityHelpers.log)('error', '[::resetRegisteryProcess::]', e.message);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Babel visitor handler for the `Program` node when entering a file.
174
+ *
175
+ * This function initializes plugin state for the file, resolves React imports,
176
+ * and resets the variable registry for the current file. It is typically used
177
+ * at the beginning of processing each file to ensure a clean state.
178
+ *
179
+ * @param {NodePath} path - The Babel AST path representing the Program node.
180
+ * @param {Object} state - Plugin state, including filename, import metadata, and configuration.
181
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate or check AST nodes.
182
+ * @param {Object<string, Object>} virtualRegistry - Registry of components and their
183
+ * registered variables/context info.
184
+ * @param {Object} config - The plugin configuration for the current file.
185
+ *
186
+ * @returns {void}
187
+ * - Updates `state.casperConfig` with the provided config.
188
+ * - Populates `state.importState` with resolved React imports.
189
+ * - Resets the variable registry for the current file in `virtualRegistry`.
190
+ *
191
+ * @important
192
+ * - Must be called at the entry of each Program node to ensure correct setup.
193
+ * - Errors are silently caught; consider logging during debugging.
194
+ *
195
+ * @example
196
+ * ```js
197
+ * programEnter(path, state, t, virtualRegistry, pluginConfig);
198
+ * // Initializes plugin state, resolves React imports, resets file-specific registry
199
+ * ```
200
+ */
201
+ function programEnter(path, state, t, virtualRegistry, config) {
202
+ try {
203
+ state.casperConfig = config;
204
+ importStateResolver(path, state, t);
205
+ resetRegisteryProcess.call(this, state, virtualRegistry);
206
+ } catch (e) {
207
+ (0, _utilityHelpers.log)('error', '[::programEnter::]', e.message);
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Injects required imports for React and global context if they are missing.
213
+ *
214
+ * This function ensures that the necessary modules are imported at the top of
215
+ * the file when the AST traversal detects that `useState` or global context usage
216
+ * is needed. It adds the imports only when required, avoiding duplicate or
217
+ * unnecessary imports.
218
+ *
219
+ * @param {NodePath} path - The Babel AST path where imports should be injected.
220
+ * @param {Object} state - Plugin state, containing flags `needUseStateImport` and `needsGblContext`.
221
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate AST nodes.
222
+ *
223
+ * @returns {void}
224
+ * - Conditionally injects `React` import if `useState` is required.
225
+ * - Conditionally injects global context import if any global context is used.
226
+ * - Uses `buildRequireDeclaration` to insert the import statements at the top of the file.
227
+ *
228
+ * @important
229
+ * - Checks `state.needUseStateImport` and `state.needsGblContext` to determine necessity.
230
+ * - Errors are silently caught; no exception is thrown if import insertion fails.
231
+ *
232
+ * @example
233
+ * ```js
234
+ * bindMissingImport(path, state, t);
235
+ * // Injects React and global context imports if they are missing
236
+ * ```
237
+ */
238
+ function bindMissingImport(path, state, t) {
239
+ try {
240
+ if (state?.needUseStateImport) (0, _astHelpers.buildRequireDeclaration)(path, t, _constants._CCTX_UNDUS_CORE_REACT, _constants._CCTX_REACT);
241
+ if (state?.needsGblContext) (0, _astHelpers.buildRequireDeclaration)(path, t, _constants._CCTX_UNDUS_CORE_GBL_CONTEXT, _utilityHelpers.CONTEXT_FILE_PATH);
242
+ } catch (e) {
243
+ (0, _utilityHelpers.log)('error', '[::bindMissingImport::]', e.message);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Babel visitor handler for the `Program` node when exiting a file.
249
+ *
250
+ * This function is called after the AST traversal of the entire file is complete.
251
+ * Its primary purpose is to inject any missing imports for React or global context
252
+ * that were flagged as required during traversal.
253
+ *
254
+ * @param {NodePath} path - The Babel AST path representing the Program node.
255
+ * @param {Object} state - Plugin state, including flags `needUseStateImport` and `needsGblContext`.
256
+ * @param {Object} t - Babel types helper (`@babel/types`) used to generate AST nodes.
257
+ *
258
+ * @returns {void}
259
+ * Modifies the AST in place by calling `bindMissingImport` to insert necessary imports.
260
+ *
261
+ * @important
262
+ * - Should be paired with `programEnter` at the start of traversal.
263
+ * - Only injects imports if flagged during traversal (`state.needUseStateImport` or `state.needsGblContext`).
264
+ * - Errors are silently caught; AST modifications fail gracefully if errors occur.
265
+ *
266
+ * @example
267
+ * ```js
268
+ * programExit(path, state, t);
269
+ * // Ensures React and global context imports are added if needed
270
+ * ```
271
+ */
272
+ function programExit(path, state, t) {
273
+ try {
274
+ bindMissingImport(path, state, t);
275
+ } catch (e) {
276
+ (0, _utilityHelpers.log)('error', '[::programExit::]', e.message);
277
+ }
278
+ }