import type { AnalysisResourceConstraintError } from "../analysisErrorCore.js"; import { failedJavaScriptStaticAnalysis, detectVendors, registrationKey, stringValue, } from "./javascriptStaticAnalysisHelpers.js"; import type { JavaScriptMemberMutationAllowance } from "./javascriptSemanticWorkAllowance.js"; import { JAVASCRIPT_SEMANTIC_PRECISION_DEFAULTS, type JavaScriptSemanticPrecisionInput, } from "./javascriptSemanticPrecision.js"; import { createXhrOpenRequestQuery } from "./javascriptNetworkRequests.js"; import { uniqueSortedBy } from "../canonicalOrdering.js"; import * as t from "@babel/types"; import { JavaScriptRouteScan } from "./javascriptRouteScan.js"; import type { JavaScriptRouteSourceFacts } from "./javascriptRouteFacts.js"; import { RETURNED_REFERENCE_WIDENING_LIMITATION } from "./javascriptSemanticCoverage.js"; import { collectElectronWrappedCallPathsSteps } from "./electronWrappedCallPaths.js"; import { ELECTRON_IDENTITY_LIMITATION, referencesElectronModule, } from "./javascriptElectronMemberWrites.js"; import { traverseJavaScriptAstSteps } from "./javascriptSemanticTraversal.js"; import { electronRendererLoadAuthority, resolveElectronBrowserWindowReceiver, } from "./electronStaticRenderer.js"; import { finishElectronNativeBindingsSteps } from "./electronStaticAnalysisNative.js"; import { finishElectronDynamicCodeSteps } from "./electronStaticAnalysisDynamicCode.js"; import { finishElectronIpcChannels } from "./electronStaticAnalysisIpc.js"; import { inspectElectronStaticNode } from "./electronStaticAnalysis.js"; import { hasPossibleCommonJsDelegateWrite, semanticFactoryLoaderMemberAt, } from "./javascriptSemanticRequireOrigin.js"; import { semanticPrecisionControls, semanticResourceLimitReason, } from "./javascriptSemanticResourceLimits.js"; import { createStaticPathIntrinsicQuery } from "./javascriptStaticPathIntrinsics.js"; import { createSemanticExpressionShapeResolver } from "./javascriptSemanticExpressionShapes.js"; import { finishElectronBrowserWindowsSteps } from "./electronStaticAnalysisBrowser.js"; import { addReference, addEndpoint, addSourceMapDirectives, finishPartialNetworkEndpoints, finishModuleRequireCalls, finishSqliteStorageCalls, inspectCall, inspectRpcNode, finishRpcScanSteps, indexVitePreloadDependencyTable, } from "./javascriptStaticAnalysisCalls.js"; import { finishBundlerExports, inspectBundlerRegistration, inspectBundlerBootstrap, inspectEsbuildWrapper, } from "./javascriptStaticAnalysisBundler.js"; import { finalizeLocatedFindings } from "./javascriptStaticAnalysisFindings.js"; import { createJavaScriptAnalysisAccumulator, type JavaScriptAnalysisAccumulator as AnalysisAccumulator, type JavaScriptFindingContext, } from "./javascriptStaticAnalysisState.js"; import type { JavaScriptStaticAnalysis } from "./javascriptStaticAnalysisTypes.js"; import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js"; import { indexJavaScriptElectronIdentitySteps, indexJavaScriptBindingsWithReceiversSteps, } from "./javascriptSemanticAnalysis.js"; import { commonJsWrapperRedeclarationCount, javaScriptSourceLoaderCondition, recoveredJavaScriptSyntaxErrorCount, type ParsedJavaScriptSource, } from "./javascriptSourceParser.js"; import { createJavaScriptRpcScan } from "./javascriptRpcEndpoints.js"; import { hasUncertainTypeOnlyModuleSideEffect, TYPE_ONLY_MODULE_SIDE_EFFECT_LIMITATION, semanticStaticModuleSource, semanticImportEqualsSpecifier, } from "./javascriptModuleDeclaration.js"; import { javaScriptStaticParseStatus, type JavaScriptStaticCoverage, } from "./javascriptStaticCoverage.js"; /** * Syntax-level facts for a parsed source whose member-mutation phase was * refused. Every finding that reads mutation facts is unexamined, so its * absence here is not evidence of absence; parser, comment and text facts * remain, marked with the refused phase. */ export const memberMutationRefusedJavaScriptStaticAnalysis = ( source: string, file: ParsedJavaScriptSource, refusal: AnalysisResourceConstraintError, ): JavaScriptStaticAnalysis => { const parserErrors = recoveredJavaScriptSyntaxErrorCount(file.errors); const wrapperRedeclarations = commonJsWrapperRedeclarationCount(file.errors); const loaderCondition = javaScriptSourceLoaderCondition(file.program); const accumulator = createJavaScriptAnalysisAccumulator(source.length); addSourceMapDirectives(source, file.comments ?? [], accumulator); const reason = `The member-mutation phase was refused (${refusal.reason}); findings that depend on member-mutation facts were not examined.`; const coverage: JavaScriptStaticCoverage = { syntax: parserErrors === 0 ? { status: "complete", error_count: 0 } : { status: "recovered", error_count: parserErrors }, semantics: { unknown_findings: null, uncertainty: [ ...(loaderCondition === undefined ? [] : ["conditional-loader" as const]), ...(wrapperRedeclarations === 0 ? [] : ["commonjs-wrapper-redeclaration" as const]), ], }, examination: { status: "not-examined", semantic_resource_limits: [], electron_call_paths_limited: false, refused_phase: "member-mutations", }, applicability: { electron: "unknown" }, unexamined_reason: reason, }; return { ...failedJavaScriptStaticAnalysis(), parse_status: javaScriptStaticParseStatus(coverage), analysis_coverage: coverage, parse_error_count: parserErrors, source_map_urls: accumulator.sourceMaps, vendors: detectVendors(source), ...(loaderCondition === undefined ? {} : { loaderCondition }), limitations: [ ...(loaderCondition === undefined ? [] : [loaderCondition]), `${reason} Absence of findings is not evidence of absence.`, ...(parserErrors > 0 ? [ "The parser recovered from syntax errors; affected bindings are partial.", ] : []), "JavaScript syntax was parsed as data and was never evaluated.", ], }; }; /** Static analysis that yields during its source traversal; results are unchanged. */ export function* analyzeParsedJavaScriptStaticSourceSteps( source: string, file: ParsedJavaScriptSource, precision?: JavaScriptSemanticPrecisionInput, memberMutationAllowance?: JavaScriptMemberMutationAllowance, ): Generator { const accumulator = createJavaScriptAnalysisAccumulator(source.length); // One definitions pass serves receiver classification and binding lookup. const index = yield* indexJavaScriptBindingsWithReceiversSteps( file.program, undefined, precision, memberMutationAllowance, ); const { bindings, receivers } = index; yield* index.indexAmbientWritesSteps(); if (hasPossibleCommonJsDelegateWrite(bindings)) yield* index.indexMemberMutationFactsSteps(); const electronIdentity = yield* indexJavaScriptElectronIdentitySteps( file.program, bindings, ); const findings: JavaScriptFindingContext = { xhrOpenRequest: createXhrOpenRequestQuery(index), pathIntrinsics: createStaticPathIntrinsicQuery(index), browserWindowReceiver: (node, site, suffix) => resolveElectronBrowserWindowReceiver(node, site, suffix, findings, index), rendererLoad: (callee, site) => electronRendererLoadAuthority(callee, site, findings, index), source, accumulator, vitePreloadDependencyTable: indexVitePreloadDependencyTable( file.program, bindings, ), openReceiverFacts: receivers.openReceivers, electronBindings: electronIdentity.bindings, electronCandidateBindings: electronIdentity.candidateBindings, electronExportIntact: electronIdentity.intactExport, electronInvocationPath: electronIdentity.invocationPath, electronAppPathChangePossible: electronIdentity.mayChangeAppPath, electronCandidateAppPathChangePossible: electronIdentity.candidateMayChangeAppPath, rpcScan: createJavaScriptRpcScan(source, receivers.rpcClientRoots, index), expressionShapes: createSemanticExpressionShapeResolver(bindings), }; const routeScan = yield* JavaScriptRouteScan.createSteps( file, index, (fact) => addEndpoint(findings, { ...fact, kind: "route" }), ); yield* traverseStaticSourceSteps(file, findings, bindings, routeScan); const routes = yield* routeScan.finishSteps(); if (accumulator.bundlerExportHelpersObserved) yield* index.indexMemberMutationFactsSteps(); finishBundlerExports(accumulator, index); yield* finishElectronNativeBindingsSteps(findings, index); yield* finishElectronBrowserWindowsSteps(findings, index); yield* finishElectronDynamicCodeSteps(findings, index); if (accumulator.pendingModuleRequireCalls.length > 0) { yield* index.indexMemberMutationFactsSteps(); finishModuleRequireCalls(findings, index); } if ( accumulator.pendingNetworkCalls.length > 0 || accumulator.pendingSqliteCalls.length > 0 ) { yield* index.indexMemberMutationFactsSteps(); finishPartialNetworkEndpoints(findings, bindings, index); finishSqliteStorageCalls(findings, bindings, index); } accumulator.electronCallPaths = yield* collectElectronWrappedCallPathsSteps( file.program, bindings, source, accumulator, electronIdentity, () => index.indexMemberMutationFactsSteps(), ); if (accumulator.pendingIpcChannels.size > 0) { yield* index.indexMemberMutationFactsSteps(); finishElectronIpcChannels(accumulator, bindings); } addSourceMapDirectives(source, file.comments ?? [], accumulator); return finalizeStaticAnalysis(source, file, accumulator, bindings, routes); } function* traverseStaticSourceSteps( file: ParsedJavaScriptSource, findings: JavaScriptFindingContext, bindings: JavaScriptSemanticAnalysisState, routeScan: JavaScriptRouteScan, ): Generator { yield* traverseJavaScriptAstSteps(file, { // Code that never runs under the bundler convention yields no findings. skip: (node) => findings.accumulator.unusedFactoryDefaults.has(node), enter: (node, parent) => { findings.accumulator.visitedNodes += 1; routeScan.inspect(node, parent); if (!bindings.erasedSyntaxNodes.has(node)) inspectNode(node, findings, bindings); return undefined; }, }); yield* finishRpcScanSteps(findings); } const finalizeStaticAnalysis = ( source: string, file: ParsedJavaScriptSource, accumulator: AnalysisAccumulator, bindings: JavaScriptSemanticAnalysisState, routes: JavaScriptRouteSourceFacts, ): JavaScriptStaticAnalysis => { const parserErrors = recoveredJavaScriptSyntaxErrorCount(file.errors); const wrapperRedeclarations = commonJsWrapperRedeclarationCount(file.errors); const typeOnlySideEffect = hasUncertainTypeOnlyModuleSideEffect(file.program); const electronObserved = referencesElectronModule(accumulator.references); const resourceLimits = [...bindings.valueResourceLimits].sort(); const controls = semanticPrecisionControls( resourceLimits, accumulator.electronCallPathLimits ?? [], bindings.precision, ); const candidateElectron = [ ...accumulator.browserWindows, ...accumulator.contextBridgeApis, ...accumulator.ipc, ...accumulator.utilityProcesses, ...accumulator.protocols, ...accumulator.appPathChanges, ].some(({ value }) => value.loader_authority === "candidate"); const loaderCondition = javaScriptSourceLoaderCondition(file.program); const coverage: JavaScriptStaticCoverage = { syntax: parserErrors === 0 ? { status: "complete", error_count: 0 } : { status: "recovered", error_count: parserErrors }, semantics: { unknown_findings: accumulator.unknownFindings, uncertainty: [ ...(loaderCondition === undefined ? [] : ["conditional-loader" as const]), ...(accumulator.unknownFindings > 0 ? ["dynamic-findings" as const] : []), ...(bindings.returnedReferenceWidenings.size > 0 ? ["returned-reference-widening" as const] : []), ...(typeOnlySideEffect ? ["type-only-module-side-effect" as const] : []), ...(wrapperRedeclarations === 0 ? [] : ["commonjs-wrapper-redeclaration" as const]), ], }, examination: { status: resourceLimits.length > 0 || (accumulator.electronCallPathLimits?.size ?? 0) > 0 ? "limited" : "complete", semantic_resource_limits: resourceLimits, ...(bindings.precision === JAVASCRIPT_SEMANTIC_PRECISION_DEFAULTS ? {} : { semantic_precision: bindings.precision }), electron_call_paths_limited: (accumulator.electronCallPathLimits?.size ?? 0) > 0, ...(controls.length === 0 ? {} : { controls }), }, applicability: { electron: electronObserved ? "observed" : "unknown" }, }; const limitations = [ ...(loaderCondition === undefined ? [] : [loaderCondition]), ...(bindings.valueResourceLimits.has("alias-selections") ? [semanticResourceLimitReason("alias-selections", bindings.precision)] : []), ...(bindings.returnedReferenceWidenings.size > 0 ? [RETURNED_REFERENCE_WIDENING_LIMITATION] : []), ...(accumulator.electronCallPaths?.length ? [ "Bundled Electron call paths use static argument and closure substitutions. Conditions, ambient helper overrides, runtime reachability and arbitrary side effects remain unproven.", ] : []), ...[...(accumulator.electronCallPathLimits ?? [])] .sort() .map( (control) => `Electron wrapper expansion reached semantic_precision.${control}=${String(bindings.precision[control])}. Increase semantic_precision.${control} on the next analyze_javascript_application call; coverage records the control. No REA restart is required. Worker memory and transfer admission remain independent; cyclic or unsupported paths remain unknown.`, ), ...(parserErrors === 0 ? [] : [ "The parser recovered from syntax errors; affected facts are partial.", ]), ...(wrapperRedeclarations === 0 ? [] : [ "A top-level lexical declaration redeclares a CommonJS wrapper parameter, so this module cannot evaluate. Recovered syntax was examined completely.", ]), ...(accumulator.unknownFindings === 0 ? [] : [ "One or more static keys, expressions, or Electron boundary values were dynamic and remain unknown.", ]), ...(typeOnlySideEffect ? [TYPE_ONLY_MODULE_SIDE_EFFECT_LIMITATION] : []), ...(electronObserved ? [ELECTRON_IDENTITY_LIMITATION] : []), ...(candidateElectron ? [ "Some Electron syntax depends on an unproved CommonJS loader; its Electron identity remains conditional.", ] : []), "JavaScript syntax was parsed as data and was never evaluated.", ]; return { parse_status: javaScriptStaticParseStatus(coverage), analysis_coverage: coverage, parse_error_count: parserErrors, visited_ast_nodes: accumulator.visitedNodes, references: finalizeLocatedFindings( accumulator.references, accumulator.moduleRangeIndex, ), endpoints: finalizeLocatedFindings( accumulator.endpoints, accumulator.moduleRangeIndex, ), routes, storage: finalizeLocatedFindings( accumulator.storage, accumulator.moduleRangeIndex, ), bundler_registrations: uniqueSortedBy( accumulator.registrations, registrationKey, ), role_paths: finalizeLocatedFindings( accumulator.roles, accumulator.moduleRangeIndex, ), source_map_urls: accumulator.sourceMaps, vendors: detectVendors(source), electron: { ...(accumulator.appPathChanges.length > 0 ? { app_path_changes: finalizeLocatedFindings( accumulator.appPathChanges, accumulator.moduleRangeIndex, ), } : {}), ...(accumulator.electronCallPaths?.length ? { call_paths: accumulator.electronCallPaths } : {}), browser_windows: finalizeLocatedFindings( accumulator.browserWindows, accumulator.moduleRangeIndex, ), context_bridge_apis: finalizeLocatedFindings( accumulator.contextBridgeApis, accumulator.moduleRangeIndex, ), ipc: finalizeLocatedFindings( accumulator.ipc, accumulator.moduleRangeIndex, ), sender_validations: finalizeLocatedFindings( accumulator.senderValidations, accumulator.moduleRangeIndex, ), utility_processes: finalizeLocatedFindings( accumulator.utilityProcesses, accumulator.moduleRangeIndex, ), native_addon_bindings: finalizeLocatedFindings( accumulator.nativeAddonBindings, accumulator.moduleRangeIndex, ), ...(accumulator.dynamicCode.length > 0 ? { dynamic_code: finalizeLocatedFindings( accumulator.dynamicCode, accumulator.moduleRangeIndex, ), } : {}), protocols: finalizeLocatedFindings( accumulator.protocols, accumulator.moduleRangeIndex, ), }, ...(loaderCondition === undefined ? {} : { loaderCondition }), limitations, }; }; const inspectNode = ( node: t.Node, findings: JavaScriptFindingContext, bindings: JavaScriptSemanticAnalysisState, ): void => { const { source, accumulator } = findings; inspectElectronStaticNode(node, findings); if (t.isCallExpression(node)) { inspectBundlerBootstrap(source, node, accumulator, bindings); inspectBundlerRegistration(source, node, accumulator, bindings); inspectEsbuildWrapper(source, node, accumulator, bindings); if ( semanticFactoryLoaderMemberAt( node, bindings, accumulator.factoryRequireBindingIds, "d", ) === "factory-loader" ) accumulator.bundlerExportHelpersObserved = true; inspectCall(source, node, findings, bindings); } else if (t.isOptionalCallExpression(node)) { inspectCall(source, node, findings, bindings); } else if (t.isNewExpression(node)) inspectCall(source, node, findings, bindings); if (t.isTSImportEqualsDeclaration(node)) { const specifier = semanticImportEqualsSpecifier(node); if (specifier !== null) addReference(findings, { node, kind: "require", specifier }); } else { const moduleSource = semanticStaticModuleSource(node); if (moduleSource !== null) addReference(findings, { node, kind: "static-import", specifier: moduleSource.value, }); } if (t.isImportExpression(node)) addReference(findings, { node, kind: "dynamic-import", specifier: stringValue(node.source), }); inspectRpcNode(node, findings); };