mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 11:56:20 +00:00
Completes exhaustive business-code memory optimization stacked on Phase 1-2 (#4476), reaching the business-code floor before Electron-level optimization: Round 1 - Renderer Cold Start & Preload Minification: - Enable esbuild minification in scripts/build-preload.mjs (368 KB -> 103 KB, -72%) - Remove eager requestIdleCallback TerminalLayer mount in AppMounts.tsx - Add compact capability lookup maps to toolNameIndex.json so permissionGrants drops static cattyToolSpecs.json (126 KB) from startup - Lazy-load pinyin-pro (447 KB) on first CJK text via usePinyinMatcherVersion hook (synchronous createRequire in Node/test mode, zero top-level await) Round 2 & 3 - Main Process & terminalWorker Zero-Dead-Weight Startup: - Lazy-load all third-party npm packages on startup (0 npm packages loaded at boot; require.cache 657 -> 234 modules, -64.4%; main heapTotal 54 -> 23.3 MiB): ajv/ajv-formats/plugin-contract schema, electron-updater, jsqr, ws, webmDurationPatch, terminalPerformanceDiagnostics, ssh2, ssh2-sftp-client, iconv-lite, zmodem.js, node-pty/serialport (Electron-gated so Node Module._load mocks stay 100% intact), 11 AI SDK drivers, CodexAppServerRuntime, codebuddy, aiPrivacyService, re2js, external MCP setup, 17 capability modules, and 7 systemManager/*Ops modules - Clean up windowManager readiness/unhealthy maps on BrowserWindow closed Round 4 - Renderer Startup Bundle Decomposition: - Lazy-load HostDetailsPanel (134 KB), GroupDetailsPanel (29 KB), KnownHostsManager, QuickConnectWizard, SerialConnectModal, Serial/LocalHostDetailsPanel, ImportVaultDialog, VaultImportProgressPanel, domain/vaultImport (55 KB), TerminalHostTreeSidebar (35 KB), ToolCall (26 KB), vaultAgentBridgeClient (47 KB) - Tree-shake package.json in cloudSync (-32 KB from useUpdateCheck) - Main App-*.js chunk: 1,550 KB -> 714.6 KB (-53.9%) Round 5 - Active Multi-Terminal Memory Optimization: - Remove unconditional requestIdleCallback preload of AIChatSidePanel (~1.5 MB JS / vendor-ai + globalAgentRuntime + tool specs) in TerminalLayerSupport.tsx - Remove eager 67-spec Fig autocomplete preloading (1.25 MB raw JS imported into main-process ESM cache + renderer specCache) in useTerminalAutocomplete.ts; specs load on demand via completionEngine.ts loadSpec() Verified Clean-VM Benchmarks (0-host idle, 3x median, vs Blank Electron 97.6 MiB PrivDirty): - Total Private Dirty RAM: 324.8 -> 234.6 (Phase 1-2) -> 184.2 MiB (-43.3%, 61.9% of all Netcatty overhead above Blank Electron eliminated) - Renderer v8/main/heap: 24.84 -> 9.35 MiB (-62.4%); jsHeapUsedMB: 35.98 -> 12.76 MiB (only +3.22 MiB above about:blank) - Active 5 local terminals + 1,000-line ANSI burst: Peak PrivDirty -25.6 MiB (395.9 -> 370.3 MiB), main PrivDirty -11.3 MiB, renderer PrivDirty -14.2 MiB, zero xterm/canvas/listener/per-session heap leaks across 2x5 open/close cycles
170 lines
6.9 KiB
JavaScript
170 lines
6.9 KiB
JavaScript
"use strict";
|
|
|
|
let _ajv = null;
|
|
function getAjv() {
|
|
if (!_ajv) {
|
|
const Ajv2020 = require("ajv/dist/2020").default;
|
|
_ajv = new Ajv2020({
|
|
allErrors: true,
|
|
strict: true,
|
|
validateFormats: false,
|
|
});
|
|
}
|
|
return _ajv;
|
|
}
|
|
|
|
const MAX_SCHEMA_DEPTH = 8;
|
|
const MAX_SCHEMA_NODES = 256;
|
|
const MAX_ENUM_ITEMS = 256;
|
|
const MAX_PROPERTY_NAME_LENGTH = 128;
|
|
const FORBIDDEN_PROPERTY_NAMES = new Set(["__proto__", "constructor", "prototype"]);
|
|
const ALLOWED_TYPES = new Set(["array", "boolean", "integer", "null", "number", "object", "string"]);
|
|
const ALLOWED_KEYWORDS = new Set([
|
|
"additionalProperties",
|
|
"const",
|
|
"enum",
|
|
"items",
|
|
"maxItems",
|
|
"maxLength",
|
|
"maximum",
|
|
"minItems",
|
|
"minLength",
|
|
"minimum",
|
|
"properties",
|
|
"required",
|
|
"type",
|
|
"writeOnly",
|
|
]);
|
|
|
|
function isPlainRecord(value) {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
const prototype = Object.getPrototypeOf(value);
|
|
return prototype === Object.prototype || prototype === null;
|
|
}
|
|
|
|
function assertSafeName(name, label) {
|
|
if (typeof name !== "string" || name.length < 1 || name.length > MAX_PROPERTY_NAME_LENGTH
|
|
|| FORBIDDEN_PROPERTY_NAMES.has(name) || name.includes("\0")) {
|
|
throw new TypeError(`${label} is invalid`);
|
|
}
|
|
}
|
|
|
|
function assertIntegerKeyword(schema, name) {
|
|
if (schema[name] === undefined) return;
|
|
if (!Number.isSafeInteger(schema[name]) || schema[name] < 0) {
|
|
throw new TypeError(`Restricted setting schema ${name} must be a non-negative safe integer`);
|
|
}
|
|
}
|
|
|
|
function assertNumberKeyword(schema, name) {
|
|
if (schema[name] === undefined) return;
|
|
if (typeof schema[name] !== "number" || !Number.isFinite(schema[name])) {
|
|
throw new TypeError(`Restricted setting schema ${name} must be finite`);
|
|
}
|
|
}
|
|
|
|
function assertRestrictedJsonSchema(root, options = {}) {
|
|
const rootType = options.rootType ?? null;
|
|
const stack = [{ schema: root, depth: 0, label: "valueSchema" }];
|
|
let nodes = 0;
|
|
while (stack.length) {
|
|
const current = stack.pop();
|
|
if (!current || !isPlainRecord(current.schema)) {
|
|
throw new TypeError("Restricted setting schemas must contain plain objects");
|
|
}
|
|
nodes += 1;
|
|
if (nodes > MAX_SCHEMA_NODES || current.depth > MAX_SCHEMA_DEPTH) {
|
|
throw new TypeError("Restricted setting schema is too complex");
|
|
}
|
|
const schema = current.schema;
|
|
for (const keyword of Object.keys(schema)) {
|
|
if (!ALLOWED_KEYWORDS.has(keyword)) {
|
|
throw new TypeError(`Restricted setting schema keyword is not allowed: ${keyword}`);
|
|
}
|
|
}
|
|
if (!ALLOWED_TYPES.has(schema.type)) {
|
|
throw new TypeError("Every restricted setting schema node must declare one supported type");
|
|
}
|
|
if (current.depth === 0 && rootType && schema.type !== rootType) {
|
|
throw new TypeError(`Restricted setting schema root must use type ${rootType}`);
|
|
}
|
|
if (schema.enum !== undefined) {
|
|
if (!Array.isArray(schema.enum) || schema.enum.length < 1 || schema.enum.length > MAX_ENUM_ITEMS) {
|
|
throw new TypeError("Restricted setting schema enum is invalid");
|
|
}
|
|
}
|
|
assertIntegerKeyword(schema, "minItems");
|
|
assertIntegerKeyword(schema, "maxItems");
|
|
assertIntegerKeyword(schema, "minLength");
|
|
assertIntegerKeyword(schema, "maxLength");
|
|
assertNumberKeyword(schema, "minimum");
|
|
assertNumberKeyword(schema, "maximum");
|
|
if (schema.minItems !== undefined && schema.maxItems !== undefined && schema.minItems > schema.maxItems) {
|
|
throw new TypeError("Restricted setting schema minItems exceeds maxItems");
|
|
}
|
|
if (schema.minLength !== undefined && schema.maxLength !== undefined && schema.minLength > schema.maxLength) {
|
|
throw new TypeError("Restricted setting schema minLength exceeds maxLength");
|
|
}
|
|
if (schema.minimum !== undefined && schema.maximum !== undefined && schema.minimum > schema.maximum) {
|
|
throw new TypeError("Restricted setting schema minimum exceeds maximum");
|
|
}
|
|
if (schema.type === "integer" && schema.minimum !== undefined && schema.maximum !== undefined
|
|
&& Math.ceil(schema.minimum) > Math.floor(schema.maximum)) {
|
|
throw new TypeError("Restricted integer setting schema has no valid value");
|
|
}
|
|
if (schema.type === "array") {
|
|
if (!isPlainRecord(schema.items)) throw new TypeError("Restricted array schemas require one items schema");
|
|
stack.push({ schema: schema.items, depth: current.depth + 1, label: `${current.label}.items` });
|
|
} else if (schema.items !== undefined || schema.minItems !== undefined || schema.maxItems !== undefined) {
|
|
throw new TypeError("Restricted setting schema array keywords require type array");
|
|
}
|
|
if (schema.type === "object") {
|
|
if (!isPlainRecord(schema.properties)) throw new TypeError("Restricted object schemas require properties");
|
|
if (schema.additionalProperties !== false) {
|
|
throw new TypeError("Restricted object schemas must set additionalProperties to false");
|
|
}
|
|
const propertyNames = Object.keys(schema.properties);
|
|
for (const name of propertyNames) {
|
|
assertSafeName(name, "Restricted setting schema property name");
|
|
stack.push({ schema: schema.properties[name], depth: current.depth + 1, label: `${current.label}.${name}` });
|
|
}
|
|
if (schema.required !== undefined) {
|
|
if (!Array.isArray(schema.required) || new Set(schema.required).size !== schema.required.length
|
|
|| schema.required.some((name) => typeof name !== "string" || !Object.hasOwn(schema.properties, name))) {
|
|
throw new TypeError("Restricted object schema required fields are invalid");
|
|
}
|
|
}
|
|
} else if (schema.properties !== undefined || schema.required !== undefined || schema.additionalProperties !== undefined) {
|
|
throw new TypeError("Restricted setting schema object keywords require type object");
|
|
}
|
|
if (schema.type !== "string" && (schema.minLength !== undefined || schema.maxLength !== undefined)) {
|
|
throw new TypeError("Restricted setting schema string keywords require type string");
|
|
}
|
|
if (!["integer", "number"].includes(schema.type) && (schema.minimum !== undefined || schema.maximum !== undefined)) {
|
|
throw new TypeError("Restricted setting schema numeric keywords require type number or integer");
|
|
}
|
|
}
|
|
return root;
|
|
}
|
|
|
|
function compileRestrictedJsonSchema(schema, options = {}) {
|
|
assertRestrictedJsonSchema(schema, options);
|
|
const ajv = getAjv();
|
|
let validate;
|
|
try { validate = ajv.compile(schema); }
|
|
catch (error) { throw new TypeError(`Restricted setting schema is invalid: ${error?.message ?? error}`); }
|
|
return (value) => {
|
|
if (validate(value)) return true;
|
|
const details = ajv.errorsText(validate.errors, { separator: "; " });
|
|
throw new TypeError(`Value does not match its restricted setting schema: ${details}`);
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
ALLOWED_KEYWORDS,
|
|
MAX_SCHEMA_DEPTH,
|
|
MAX_SCHEMA_NODES,
|
|
assertRestrictedJsonSchema,
|
|
compileRestrictedJsonSchema,
|
|
};
|