superbased 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +31 -0
- package/README.md +84 -0
- package/SUPERBASED_SKILL.md +358 -0
- package/dist/electron/ai/ai-client.d.ts +45 -0
- package/dist/electron/ai/ai-client.d.ts.map +1 -0
- package/dist/electron/ai/ai-client.js +205 -0
- package/dist/electron/ai/ai-client.js.map +1 -0
- package/dist/electron/ai/context-builder.d.ts +8 -0
- package/dist/electron/ai/context-builder.d.ts.map +1 -0
- package/dist/electron/ai/context-builder.js +28 -0
- package/dist/electron/ai/context-builder.js.map +1 -0
- package/dist/electron/ai/instruction-parser.d.ts +11 -0
- package/dist/electron/ai/instruction-parser.d.ts.map +1 -0
- package/dist/electron/ai/instruction-parser.js +47 -0
- package/dist/electron/ai/instruction-parser.js.map +1 -0
- package/dist/electron/ai/orchestrator.d.ts +17 -0
- package/dist/electron/ai/orchestrator.d.ts.map +1 -0
- package/dist/electron/ai/orchestrator.js +53 -0
- package/dist/electron/ai/orchestrator.js.map +1 -0
- package/dist/electron/ai/providers/anthropic.d.ts +6 -0
- package/dist/electron/ai/providers/anthropic.d.ts.map +1 -0
- package/dist/electron/ai/providers/anthropic.js +67 -0
- package/dist/electron/ai/providers/anthropic.js.map +1 -0
- package/dist/electron/ai/providers/azure-openai.d.ts +12 -0
- package/dist/electron/ai/providers/azure-openai.d.ts.map +1 -0
- package/dist/electron/ai/providers/azure-openai.js +87 -0
- package/dist/electron/ai/providers/azure-openai.js.map +1 -0
- package/dist/electron/ai/providers/gemini.d.ts +6 -0
- package/dist/electron/ai/providers/gemini.d.ts.map +1 -0
- package/dist/electron/ai/providers/gemini.js +49 -0
- package/dist/electron/ai/providers/gemini.js.map +1 -0
- package/dist/electron/ai/providers/openai.d.ts +6 -0
- package/dist/electron/ai/providers/openai.d.ts.map +1 -0
- package/dist/electron/ai/providers/openai.js +68 -0
- package/dist/electron/ai/providers/openai.js.map +1 -0
- package/dist/electron/core/auth-store.d.ts +15 -0
- package/dist/electron/core/auth-store.d.ts.map +1 -0
- package/dist/electron/core/auth-store.js +86 -0
- package/dist/electron/core/auth-store.js.map +1 -0
- package/dist/electron/core/config.d.ts +6 -0
- package/dist/electron/core/config.d.ts.map +1 -0
- package/dist/electron/core/config.js +81 -0
- package/dist/electron/core/config.js.map +1 -0
- package/dist/electron/core/file-logger.d.ts +17 -0
- package/dist/electron/core/file-logger.d.ts.map +1 -0
- package/dist/electron/core/file-logger.js +74 -0
- package/dist/electron/core/file-logger.js.map +1 -0
- package/dist/electron/core/json-store.d.ts +4 -0
- package/dist/electron/core/json-store.d.ts.map +1 -0
- package/dist/electron/core/json-store.js +118 -0
- package/dist/electron/core/json-store.js.map +1 -0
- package/dist/electron/core/paths.d.ts +17 -0
- package/dist/electron/core/paths.d.ts.map +1 -0
- package/dist/electron/core/paths.js +117 -0
- package/dist/electron/core/paths.js.map +1 -0
- package/dist/electron/core/platform.d.ts +21 -0
- package/dist/electron/core/platform.d.ts.map +1 -0
- package/dist/electron/core/platform.js +18 -0
- package/dist/electron/core/platform.js.map +1 -0
- package/dist/electron/core/process-coord.d.ts +19 -0
- package/dist/electron/core/process-coord.d.ts.map +1 -0
- package/dist/electron/core/process-coord.js +124 -0
- package/dist/electron/core/process-coord.js.map +1 -0
- package/dist/electron/db/database.d.ts +154 -0
- package/dist/electron/db/database.d.ts.map +1 -0
- package/dist/electron/db/database.js +637 -0
- package/dist/electron/db/database.js.map +1 -0
- package/dist/electron/db/models.d.ts +26 -0
- package/dist/electron/db/models.d.ts.map +1 -0
- package/dist/electron/db/models.js +4 -0
- package/dist/electron/db/models.js.map +1 -0
- package/dist/electron/logger.d.ts +9 -0
- package/dist/electron/logger.d.ts.map +1 -0
- package/dist/electron/logger.js +18 -0
- package/dist/electron/logger.js.map +1 -0
- package/dist/electron/main.js +3286 -0
- package/dist/electron/modules/active-window.d.ts +6 -0
- package/dist/electron/modules/active-window.d.ts.map +1 -0
- package/dist/electron/modules/active-window.js +68 -0
- package/dist/electron/modules/active-window.js.map +1 -0
- package/dist/electron/modules/api-server.d.ts +8 -0
- package/dist/electron/modules/api-server.d.ts.map +1 -0
- package/dist/electron/modules/api-server.js +1324 -0
- package/dist/electron/modules/api-server.js.map +1 -0
- package/dist/electron/modules/auth.d.ts +28 -0
- package/dist/electron/modules/auth.d.ts.map +1 -0
- package/dist/electron/modules/auth.js +150 -0
- package/dist/electron/modules/auth.js.map +1 -0
- package/dist/electron/modules/azure-speech-realtime.d.ts +38 -0
- package/dist/electron/modules/azure-speech-realtime.d.ts.map +1 -0
- package/dist/electron/modules/azure-speech-realtime.js +354 -0
- package/dist/electron/modules/azure-speech-realtime.js.map +1 -0
- package/dist/electron/modules/capture-modes.d.ts +19 -0
- package/dist/electron/modules/capture-modes.d.ts.map +1 -0
- package/dist/electron/modules/capture-modes.js +100 -0
- package/dist/electron/modules/capture-modes.js.map +1 -0
- package/dist/electron/modules/capture.d.ts +16 -0
- package/dist/electron/modules/capture.d.ts.map +1 -0
- package/dist/electron/modules/capture.js +139 -0
- package/dist/electron/modules/capture.js.map +1 -0
- package/dist/electron/modules/clipboard.d.ts +6 -0
- package/dist/electron/modules/clipboard.d.ts.map +1 -0
- package/dist/electron/modules/clipboard.js +26 -0
- package/dist/electron/modules/clipboard.js.map +1 -0
- package/dist/electron/modules/color-picker.d.ts +4 -0
- package/dist/electron/modules/color-picker.d.ts.map +1 -0
- package/dist/electron/modules/color-picker.js +233 -0
- package/dist/electron/modules/color-picker.js.map +1 -0
- package/dist/electron/modules/dictation.d.ts +25 -0
- package/dist/electron/modules/dictation.d.ts.map +1 -0
- package/dist/electron/modules/dictation.js +1058 -0
- package/dist/electron/modules/dictation.js.map +1 -0
- package/dist/electron/modules/error-reporter.d.ts +7 -0
- package/dist/electron/modules/error-reporter.d.ts.map +1 -0
- package/dist/electron/modules/error-reporter.js +65 -0
- package/dist/electron/modules/error-reporter.js.map +1 -0
- package/dist/electron/modules/hotkeys.d.ts +4 -0
- package/dist/electron/modules/hotkeys.d.ts.map +1 -0
- package/dist/electron/modules/hotkeys.js +40 -0
- package/dist/electron/modules/hotkeys.js.map +1 -0
- package/dist/electron/modules/keystroke.d.ts +7 -0
- package/dist/electron/modules/keystroke.d.ts.map +1 -0
- package/dist/electron/modules/keystroke.js +53 -0
- package/dist/electron/modules/keystroke.js.map +1 -0
- package/dist/electron/modules/license.d.ts +25 -0
- package/dist/electron/modules/license.d.ts.map +1 -0
- package/dist/electron/modules/license.js +175 -0
- package/dist/electron/modules/license.js.map +1 -0
- package/dist/electron/modules/mcp-config.d.ts +16 -0
- package/dist/electron/modules/mcp-config.d.ts.map +1 -0
- package/dist/electron/modules/mcp-config.js +146 -0
- package/dist/electron/modules/mcp-config.js.map +1 -0
- package/dist/electron/modules/ocr.d.ts +3 -0
- package/dist/electron/modules/ocr.d.ts.map +1 -0
- package/dist/electron/modules/ocr.js +176 -0
- package/dist/electron/modules/ocr.js.map +1 -0
- package/dist/electron/modules/pin-window.d.ts +3 -0
- package/dist/electron/modules/pin-window.d.ts.map +1 -0
- package/dist/electron/modules/pin-window.js +63 -0
- package/dist/electron/modules/pin-window.js.map +1 -0
- package/dist/electron/modules/recording/ai-analysis.d.ts +8 -0
- package/dist/electron/modules/recording/ai-analysis.d.ts.map +1 -0
- package/dist/electron/modules/recording/ai-analysis.js +88 -0
- package/dist/electron/modules/recording/ai-analysis.js.map +1 -0
- package/dist/electron/modules/recording/capture-queue.d.ts +48 -0
- package/dist/electron/modules/recording/capture-queue.d.ts.map +1 -0
- package/dist/electron/modules/recording/capture-queue.js +376 -0
- package/dist/electron/modules/recording/capture-queue.js.map +1 -0
- package/dist/electron/modules/recording/cli.d.ts +13 -0
- package/dist/electron/modules/recording/cli.d.ts.map +1 -0
- package/dist/electron/modules/recording/cli.js +135 -0
- package/dist/electron/modules/recording/cli.js.map +1 -0
- package/dist/electron/modules/recording/http-api.d.ts +3 -0
- package/dist/electron/modules/recording/http-api.d.ts.map +1 -0
- package/dist/electron/modules/recording/http-api.js +236 -0
- package/dist/electron/modules/recording/http-api.js.map +1 -0
- package/dist/electron/modules/recording/index.d.ts +15 -0
- package/dist/electron/modules/recording/index.d.ts.map +1 -0
- package/dist/electron/modules/recording/index.js +148 -0
- package/dist/electron/modules/recording/index.js.map +1 -0
- package/dist/electron/modules/recording/input-hook-provider.d.ts +15 -0
- package/dist/electron/modules/recording/input-hook-provider.d.ts.map +1 -0
- package/dist/electron/modules/recording/input-hook-provider.js +5 -0
- package/dist/electron/modules/recording/input-hook-provider.js.map +1 -0
- package/dist/electron/modules/recording/mcp-tool.d.ts +13 -0
- package/dist/electron/modules/recording/mcp-tool.d.ts.map +1 -0
- package/dist/electron/modules/recording/mcp-tool.js +81 -0
- package/dist/electron/modules/recording/mcp-tool.js.map +1 -0
- package/dist/electron/modules/recording/providers/periodic-provider.d.ts +15 -0
- package/dist/electron/modules/recording/providers/periodic-provider.d.ts.map +1 -0
- package/dist/electron/modules/recording/providers/periodic-provider.js +55 -0
- package/dist/electron/modules/recording/providers/periodic-provider.js.map +1 -0
- package/dist/electron/modules/recording/providers/provider-factory.d.ts +9 -0
- package/dist/electron/modules/recording/providers/provider-factory.d.ts.map +1 -0
- package/dist/electron/modules/recording/providers/provider-factory.js +70 -0
- package/dist/electron/modules/recording/providers/provider-factory.js.map +1 -0
- package/dist/electron/modules/recording/providers/uiohook-provider.d.ts +19 -0
- package/dist/electron/modules/recording/providers/uiohook-provider.d.ts.map +1 -0
- package/dist/electron/modules/recording/providers/uiohook-provider.js +263 -0
- package/dist/electron/modules/recording/providers/uiohook-provider.js.map +1 -0
- package/dist/electron/modules/recording/recording-session.d.ts +25 -0
- package/dist/electron/modules/recording/recording-session.d.ts.map +1 -0
- package/dist/electron/modules/recording/recording-session.js +317 -0
- package/dist/electron/modules/recording/recording-session.js.map +1 -0
- package/dist/electron/modules/recording/session-alignment.d.ts +32 -0
- package/dist/electron/modules/recording/session-alignment.d.ts.map +1 -0
- package/dist/electron/modules/recording/session-alignment.js +103 -0
- package/dist/electron/modules/recording/session-alignment.js.map +1 -0
- package/dist/electron/modules/recording/session-export.d.ts +2 -0
- package/dist/electron/modules/recording/session-export.d.ts.map +1 -0
- package/dist/electron/modules/recording/session-export.js +287 -0
- package/dist/electron/modules/recording/session-export.js.map +1 -0
- package/dist/electron/modules/recording/trigger-engine.d.ts +62 -0
- package/dist/electron/modules/recording/trigger-engine.d.ts.map +1 -0
- package/dist/electron/modules/recording/trigger-engine.js +546 -0
- package/dist/electron/modules/recording/trigger-engine.js.map +1 -0
- package/dist/electron/modules/recording/visual-diff.d.ts +17 -0
- package/dist/electron/modules/recording/visual-diff.d.ts.map +1 -0
- package/dist/electron/modules/recording/visual-diff.js +109 -0
- package/dist/electron/modules/recording/visual-diff.js.map +1 -0
- package/dist/electron/modules/redact.d.ts +34 -0
- package/dist/electron/modules/redact.d.ts.map +1 -0
- package/dist/electron/modules/redact.js +583 -0
- package/dist/electron/modules/redact.js.map +1 -0
- package/dist/electron/modules/scroll-capture.d.ts +19 -0
- package/dist/electron/modules/scroll-capture.d.ts.map +1 -0
- package/dist/electron/modules/scroll-capture.js +185 -0
- package/dist/electron/modules/scroll-capture.js.map +1 -0
- package/dist/electron/modules/store.d.ts +59 -0
- package/dist/electron/modules/store.d.ts.map +1 -0
- package/dist/electron/modules/store.js +100 -0
- package/dist/electron/modules/store.js.map +1 -0
- package/dist/electron/modules/tce/content-analyzer.d.ts +20 -0
- package/dist/electron/modules/tce/content-analyzer.d.ts.map +1 -0
- package/dist/electron/modules/tce/content-analyzer.js +123 -0
- package/dist/electron/modules/tce/content-analyzer.js.map +1 -0
- package/dist/electron/modules/tce/index.d.ts +54 -0
- package/dist/electron/modules/tce/index.d.ts.map +1 -0
- package/dist/electron/modules/tce/index.js +174 -0
- package/dist/electron/modules/tce/index.js.map +1 -0
- package/dist/electron/modules/tce/layout-engine.d.ts +68 -0
- package/dist/electron/modules/tce/layout-engine.d.ts.map +1 -0
- package/dist/electron/modules/tce/layout-engine.js +313 -0
- package/dist/electron/modules/tce/layout-engine.js.map +1 -0
- package/dist/electron/modules/tce/renderer.d.ts +16 -0
- package/dist/electron/modules/tce/renderer.d.ts.map +1 -0
- package/dist/electron/modules/tce/renderer.js +196 -0
- package/dist/electron/modules/tce/renderer.js.map +1 -0
- package/dist/electron/modules/tce/themes.d.ts +14 -0
- package/dist/electron/modules/tce/themes.d.ts.map +1 -0
- package/dist/electron/modules/tce/themes.js +68 -0
- package/dist/electron/modules/tce/themes.js.map +1 -0
- package/dist/electron/modules/tce/token-estimator.d.ts +30 -0
- package/dist/electron/modules/tce/token-estimator.d.ts.map +1 -0
- package/dist/electron/modules/tce/token-estimator.js +59 -0
- package/dist/electron/modules/tce/token-estimator.js.map +1 -0
- package/dist/electron/modules/telemetry.d.ts +44 -0
- package/dist/electron/modules/telemetry.d.ts.map +1 -0
- package/dist/electron/modules/telemetry.js +316 -0
- package/dist/electron/modules/telemetry.js.map +1 -0
- package/dist/electron/modules/tray.d.ts +22 -0
- package/dist/electron/modules/tray.d.ts.map +1 -0
- package/dist/electron/modules/tray.js +221 -0
- package/dist/electron/modules/tray.js.map +1 -0
- package/dist/electron/modules/updater.d.ts +14 -0
- package/dist/electron/modules/updater.d.ts.map +1 -0
- package/dist/electron/modules/updater.js +102 -0
- package/dist/electron/modules/updater.js.map +1 -0
- package/dist/electron/modules/usage-link.d.ts +7 -0
- package/dist/electron/modules/usage-link.d.ts.map +1 -0
- package/dist/electron/modules/usage-link.js +63 -0
- package/dist/electron/modules/usage-link.js.map +1 -0
- package/dist/electron/modules/version-check.d.ts +3 -0
- package/dist/electron/modules/version-check.d.ts.map +1 -0
- package/dist/electron/modules/version-check.js +76 -0
- package/dist/electron/modules/version-check.js.map +1 -0
- package/dist/electron/modules/window-picker.d.ts +6 -0
- package/dist/electron/modules/window-picker.d.ts.map +1 -0
- package/dist/electron/modules/window-picker.js +192 -0
- package/dist/electron/modules/window-picker.js.map +1 -0
- package/dist/headless/electron/ai/ai-client.js +204 -0
- package/dist/headless/electron/ai/context-builder.js +27 -0
- package/dist/headless/electron/ai/instruction-parser.js +46 -0
- package/dist/headless/electron/core/auth-store.js +85 -0
- package/dist/headless/electron/core/config.js +80 -0
- package/dist/headless/electron/core/file-logger.js +73 -0
- package/dist/headless/electron/core/json-store.js +117 -0
- package/dist/headless/electron/core/paths.js +116 -0
- package/dist/headless/electron/core/platform.js +17 -0
- package/dist/headless/electron/core/process-coord.js +123 -0
- package/dist/headless/electron/db/database.js +636 -0
- package/dist/headless/electron/db/models.js +3 -0
- package/dist/headless/electron/logger.js +17 -0
- package/dist/headless/electron/modules/active-window.js +67 -0
- package/dist/headless/electron/modules/api-server.js +1323 -0
- package/dist/headless/electron/modules/auth.js +149 -0
- package/dist/headless/electron/modules/azure-speech-realtime.js +353 -0
- package/dist/headless/electron/modules/capture.js +138 -0
- package/dist/headless/electron/modules/clipboard.js +25 -0
- package/dist/headless/electron/modules/dictation.js +1057 -0
- package/dist/headless/electron/modules/keystroke.js +52 -0
- package/dist/headless/electron/modules/license.js +174 -0
- package/dist/headless/electron/modules/mcp-config.js +145 -0
- package/dist/headless/electron/modules/ocr.js +175 -0
- package/dist/headless/electron/modules/recording/ai-analysis.js +87 -0
- package/dist/headless/electron/modules/recording/capture-queue.js +375 -0
- package/dist/headless/electron/modules/recording/cli.js +134 -0
- package/dist/headless/electron/modules/recording/http-api.js +235 -0
- package/dist/headless/electron/modules/recording/index.js +147 -0
- package/dist/headless/electron/modules/recording/input-hook-provider.js +4 -0
- package/dist/headless/electron/modules/recording/mcp-tool.js +80 -0
- package/dist/headless/electron/modules/recording/providers/periodic-provider.js +54 -0
- package/dist/headless/electron/modules/recording/providers/provider-factory.js +69 -0
- package/dist/headless/electron/modules/recording/providers/uiohook-provider.js +262 -0
- package/dist/headless/electron/modules/recording/recording-session.js +316 -0
- package/dist/headless/electron/modules/recording/session-alignment.js +102 -0
- package/dist/headless/electron/modules/recording/session-export.js +286 -0
- package/dist/headless/electron/modules/recording/trigger-engine.js +545 -0
- package/dist/headless/electron/modules/recording/visual-diff.js +108 -0
- package/dist/headless/electron/modules/redact.js +582 -0
- package/dist/headless/electron/modules/store.js +99 -0
- package/dist/headless/electron/modules/tce/content-analyzer.js +122 -0
- package/dist/headless/electron/modules/tce/index.js +173 -0
- package/dist/headless/electron/modules/tce/layout-engine.js +312 -0
- package/dist/headless/electron/modules/tce/renderer.js +195 -0
- package/dist/headless/electron/modules/tce/themes.js +67 -0
- package/dist/headless/electron/modules/tce/token-estimator.js +58 -0
- package/dist/headless/electron/modules/telemetry.js +315 -0
- package/dist/headless/headless/capture-hotkey.js +155 -0
- package/dist/headless/headless/cli-auth.js +158 -0
- package/dist/headless/headless/cli.js +220 -0
- package/dist/headless/headless/dictation-hotkey.js +360 -0
- package/dist/headless/headless/mic-capture.js +312 -0
- package/dist/headless/headless/platform-headless.js +121 -0
- package/dist/headless/headless/server.js +159 -0
- package/dist/headless/mic-capture.d.ts +29 -0
- package/dist/headless/mic-capture.d.ts.map +1 -0
- package/dist/headless/mic-capture.js +313 -0
- package/dist/headless/mic-capture.js.map +1 -0
- package/dist/headless/shared/constants.js +63 -0
- package/dist/headless/shared/design-tokens.js +189 -0
- package/dist/headless/shared/recording-types.js +93 -0
- package/dist/headless/shared/types.js +3 -0
- package/dist/shared/constants.d.ts +98 -0
- package/dist/shared/constants.d.ts.map +1 -0
- package/dist/shared/constants.js +64 -0
- package/dist/shared/constants.js.map +1 -0
- package/dist/shared/design-tokens.d.ts +112 -0
- package/dist/shared/design-tokens.d.ts.map +1 -0
- package/dist/shared/design-tokens.js +190 -0
- package/dist/shared/design-tokens.js.map +1 -0
- package/dist/shared/recording-types.d.ts +174 -0
- package/dist/shared/recording-types.d.ts.map +1 -0
- package/dist/shared/recording-types.js +94 -0
- package/dist/shared/recording-types.js.map +1 -0
- package/dist/shared/types.d.ts +135 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +4 -0
- package/dist/shared/types.js.map +1 -0
- package/mcp-server/dist/api-client.js +261 -0
- package/mcp-server/dist/index.js +824 -0
- package/mcp-server/package.json +16 -0
- package/package.json +125 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Token Compression Engine — Text Canvas Renderer
|
|
3
|
+
// Renders text into images using sharp SVG overlay. No BrowserWindow needed.
|
|
4
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
6
|
+
};
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.convertFormat = convertFormat;
|
|
9
|
+
exports.renderPages = renderPages;
|
|
10
|
+
exports.destroyRenderer = destroyRenderer;
|
|
11
|
+
const logger_1 = __importDefault(require("../../logger"));
|
|
12
|
+
const themes_1 = require("./themes");
|
|
13
|
+
/** Escape XML special characters for SVG text */
|
|
14
|
+
function escXml(text) {
|
|
15
|
+
return text
|
|
16
|
+
.replace(/&/g, '&')
|
|
17
|
+
.replace(/</g, '<')
|
|
18
|
+
.replace(/>/g, '>')
|
|
19
|
+
.replace(/"/g, '"')
|
|
20
|
+
.replace(/'/g, ''');
|
|
21
|
+
}
|
|
22
|
+
/** Truncate a line to fit within maxChars */
|
|
23
|
+
function truncateLine(line, maxChars) {
|
|
24
|
+
if (line.length <= maxChars)
|
|
25
|
+
return line;
|
|
26
|
+
return line.slice(0, maxChars - 1) + '\u2026';
|
|
27
|
+
}
|
|
28
|
+
/** Split a line into wrapped segments that fit within maxChars */
|
|
29
|
+
function wrapLine(line, maxChars) {
|
|
30
|
+
if (maxChars <= 0 || line.length <= maxChars)
|
|
31
|
+
return [line];
|
|
32
|
+
const segments = [];
|
|
33
|
+
for (let i = 0; i < line.length; i += maxChars) {
|
|
34
|
+
segments.push(line.slice(i, i + maxChars));
|
|
35
|
+
}
|
|
36
|
+
return segments;
|
|
37
|
+
}
|
|
38
|
+
/** Render a single page to a PNG buffer using sharp SVG overlay */
|
|
39
|
+
async function renderPage(page, settings, theme, contentType, presetWidth, presetHeight, columnCount, cropToContent = false) {
|
|
40
|
+
const sharp = require('sharp');
|
|
41
|
+
const lineHeightPx = settings.fontSize * settings.lineHeight;
|
|
42
|
+
const isCode = contentType !== 'prose';
|
|
43
|
+
const charWidth = settings.fontSize * 0.6;
|
|
44
|
+
const lineNumWidth = settings.showLineNumbers && isCode ? settings.lineNumberWidth : 0;
|
|
45
|
+
// Calculate column geometry
|
|
46
|
+
const contentWidth = presetWidth - 2 * settings.padding;
|
|
47
|
+
const contentHeight = presetHeight - 2 * settings.padding - (page.totalPages > 1 ? settings.footerHeight : 0);
|
|
48
|
+
const gutterTotal = (columnCount - 1) * settings.gutterWidth;
|
|
49
|
+
const colWidth = (contentWidth - gutterTotal) / columnCount;
|
|
50
|
+
const textWidth = colWidth - lineNumWidth - 8; // 8px padding for line number
|
|
51
|
+
const maxCharsPerCol = Math.floor(textWidth / charWidth);
|
|
52
|
+
const linesPerColumn = Math.floor(contentHeight / lineHeightPx);
|
|
53
|
+
// Build SVG elements
|
|
54
|
+
const svgParts = [];
|
|
55
|
+
// Column separator lines
|
|
56
|
+
for (let c = 1; c < columnCount; c++) {
|
|
57
|
+
const x = settings.padding + c * colWidth + (c - 0.5) * settings.gutterWidth;
|
|
58
|
+
svgParts.push(`<line x1="${x}" y1="${settings.padding}" x2="${x}" y2="${settings.padding + contentHeight}" stroke="${theme.gutterColor}" stroke-width="1" />`);
|
|
59
|
+
}
|
|
60
|
+
// Render lines into columns (with wrapping support)
|
|
61
|
+
const doWrap = settings.lineWrapping === 'wrap';
|
|
62
|
+
let lineIdx = 0;
|
|
63
|
+
let maxColUsed = 0; // track highest column index with content
|
|
64
|
+
let maxRowUsed = 0; // track highest row index across all columns
|
|
65
|
+
for (let col = 0; col < columnCount && lineIdx < page.lines.length; col++) {
|
|
66
|
+
const colX = settings.padding + col * (colWidth + settings.gutterWidth);
|
|
67
|
+
let row = 0;
|
|
68
|
+
maxColUsed = col;
|
|
69
|
+
while (row < linesPerColumn && lineIdx < page.lines.length) {
|
|
70
|
+
const globalLineNum = page.startLine + lineIdx + 1;
|
|
71
|
+
const isOverlap = lineIdx < page.overlapStart;
|
|
72
|
+
const rawLine = page.lines[lineIdx];
|
|
73
|
+
// Get visual segments (wrapped or truncated)
|
|
74
|
+
const segments = doWrap ? wrapLine(rawLine, maxCharsPerCol) : [truncateLine(rawLine, maxCharsPerCol)];
|
|
75
|
+
// Check if all segments fit in remaining column space
|
|
76
|
+
if (row + segments.length > linesPerColumn && row > 0) {
|
|
77
|
+
break; // start this line in the next column
|
|
78
|
+
}
|
|
79
|
+
for (let seg = 0; seg < segments.length && row < linesPerColumn; seg++, row++) {
|
|
80
|
+
const y = settings.padding + (row + 1) * lineHeightPx - (lineHeightPx * 0.25);
|
|
81
|
+
// Overlap background
|
|
82
|
+
if (isOverlap) {
|
|
83
|
+
svgParts.push(`<rect x="${colX}" y="${settings.padding + row * lineHeightPx}" width="${colWidth}" height="${lineHeightPx}" fill="${theme.overlapBg}" />`);
|
|
84
|
+
}
|
|
85
|
+
// Line number (only on first segment of a logical line)
|
|
86
|
+
if (lineNumWidth > 0 && seg === 0) {
|
|
87
|
+
svgParts.push(`<text x="${colX + lineNumWidth - 4}" y="${y}" text-anchor="end" fill="${theme.lineNumberColor}" font-family="monospace" font-size="${settings.fontSize - 1}px">${globalLineNum}</text>`);
|
|
88
|
+
}
|
|
89
|
+
// Line content — continuation lines indented slightly
|
|
90
|
+
const textX = colX + lineNumWidth + 4 + (seg > 0 ? charWidth * 2 : 0);
|
|
91
|
+
svgParts.push(`<text x="${textX}" y="${y}" fill="${theme.foreground}" font-family="monospace" font-size="${settings.fontSize}px">${escXml(segments[seg])}</text>`);
|
|
92
|
+
}
|
|
93
|
+
// Overlap label at end of overlap region
|
|
94
|
+
if (isOverlap && lineIdx === page.overlapStart - 1) {
|
|
95
|
+
const labelY = settings.padding + row * lineHeightPx + lineHeightPx * 0.3;
|
|
96
|
+
svgParts.push(`<text x="${colX + lineNumWidth + 4}" y="${labelY}" fill="${theme.overlapLabel}" font-family="monospace" font-size="${Math.max(9, settings.fontSize - 3)}px" font-style="italic">\u2191 continued from previous page</text>`);
|
|
97
|
+
}
|
|
98
|
+
lineIdx++;
|
|
99
|
+
}
|
|
100
|
+
if (row > maxRowUsed)
|
|
101
|
+
maxRowUsed = row;
|
|
102
|
+
}
|
|
103
|
+
// Calculate actual content dimensions for cropping
|
|
104
|
+
const usedCols = maxColUsed + 1;
|
|
105
|
+
const usedWidth = Math.min(presetWidth, settings.padding * 2 + usedCols * colWidth + Math.max(0, usedCols - 1) * settings.gutterWidth);
|
|
106
|
+
const usedHeight = Math.min(presetHeight, settings.padding * 2 + maxRowUsed * lineHeightPx + (page.totalPages > 1 ? settings.footerHeight : 0));
|
|
107
|
+
// Footer
|
|
108
|
+
if (page.totalPages > 1) {
|
|
109
|
+
const footerY = presetHeight - settings.padding - 4;
|
|
110
|
+
svgParts.push(`<text x="${presetWidth / 2}" y="${footerY}" text-anchor="middle" fill="${theme.footerColor}" font-family="monospace" font-size="10px">Page ${page.pageNumber}/${page.totalPages} \u2022 Lines ${page.startLine + 1}\u2013${page.endLine}</text>`);
|
|
111
|
+
}
|
|
112
|
+
const svg = `<svg width="${presetWidth}" height="${presetHeight}" xmlns="http://www.w3.org/2000/svg">
|
|
113
|
+
${svgParts.join('\n')}
|
|
114
|
+
</svg>`;
|
|
115
|
+
// Render: create background, composite SVG text on top
|
|
116
|
+
const fullBuffer = await sharp({
|
|
117
|
+
create: {
|
|
118
|
+
width: presetWidth,
|
|
119
|
+
height: presetHeight,
|
|
120
|
+
channels: 4,
|
|
121
|
+
background: hexToRgba(theme.background),
|
|
122
|
+
},
|
|
123
|
+
})
|
|
124
|
+
.composite([{ input: Buffer.from(svg), top: 0, left: 0 }])
|
|
125
|
+
.png()
|
|
126
|
+
.toBuffer();
|
|
127
|
+
// Crop last page to actual content bounds to save tokens
|
|
128
|
+
if (cropToContent && (usedWidth < presetWidth - 10 || usedHeight < presetHeight - 10)) {
|
|
129
|
+
const cropW = Math.max(100, Math.ceil(usedWidth));
|
|
130
|
+
const cropH = Math.max(100, Math.ceil(usedHeight));
|
|
131
|
+
logger_1.default.info(`[TCE] Cropping last page: ${presetWidth}x${presetHeight} → ${cropW}x${cropH} (${Math.round((1 - (cropW * cropH) / (presetWidth * presetHeight)) * 100)}% area saved)`);
|
|
132
|
+
const cropped = await sharp(fullBuffer)
|
|
133
|
+
.extract({ left: 0, top: 0, width: cropW, height: cropH })
|
|
134
|
+
.png()
|
|
135
|
+
.toBuffer();
|
|
136
|
+
return { buffer: cropped, usedWidth: cropW, usedHeight: cropH };
|
|
137
|
+
}
|
|
138
|
+
return { buffer: fullBuffer, usedWidth: presetWidth, usedHeight: presetHeight };
|
|
139
|
+
}
|
|
140
|
+
/** Convert hex color to RGBA object for sharp */
|
|
141
|
+
function hexToRgba(hex) {
|
|
142
|
+
const h = hex.replace('#', '');
|
|
143
|
+
return {
|
|
144
|
+
r: parseInt(h.substring(0, 2), 16) || 0,
|
|
145
|
+
g: parseInt(h.substring(2, 4), 16) || 0,
|
|
146
|
+
b: parseInt(h.substring(4, 6), 16) || 0,
|
|
147
|
+
alpha: 255,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/** Convert a PNG buffer to the requested format */
|
|
151
|
+
async function convertFormat(pngBuffer, format, quality = 92) {
|
|
152
|
+
if (format === 'png')
|
|
153
|
+
return pngBuffer;
|
|
154
|
+
try {
|
|
155
|
+
const sharp = require('sharp');
|
|
156
|
+
if (format === 'jpeg')
|
|
157
|
+
return sharp(pngBuffer).jpeg({ quality }).toBuffer();
|
|
158
|
+
if (format === 'webp')
|
|
159
|
+
return sharp(pngBuffer).webp({ quality }).toBuffer();
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// sharp unavailable, return PNG
|
|
163
|
+
}
|
|
164
|
+
return pngBuffer;
|
|
165
|
+
}
|
|
166
|
+
/** Render all pages and return image buffers */
|
|
167
|
+
async function renderPages(pages, settings, themeName, contentType, presetWidth, presetHeight, tokensPerImage, columnCount) {
|
|
168
|
+
const theme = themes_1.THEMES[themeName] || themes_1.THEMES.dark;
|
|
169
|
+
const results = [];
|
|
170
|
+
logger_1.default.info(`[TCE] Rendering ${pages.length} pages at ${presetWidth}x${presetHeight}, ${columnCount}-col (${themeName} theme)`);
|
|
171
|
+
const startTime = Date.now();
|
|
172
|
+
for (let i = 0; i < pages.length; i++) {
|
|
173
|
+
const page = pages[i];
|
|
174
|
+
const isLast = i === pages.length - 1;
|
|
175
|
+
const { buffer, usedWidth, usedHeight } = await renderPage(page, settings, theme, contentType, presetWidth, presetHeight, columnCount, isLast);
|
|
176
|
+
// Use actual dimensions for token calculation on cropped pages
|
|
177
|
+
const actualTokens = (usedWidth === presetWidth && usedHeight === presetHeight)
|
|
178
|
+
? tokensPerImage
|
|
179
|
+
: Math.round((usedWidth * usedHeight) / 750);
|
|
180
|
+
results.push({
|
|
181
|
+
pageNumber: page.pageNumber,
|
|
182
|
+
totalPages: page.totalPages,
|
|
183
|
+
imageTokens: actualTokens,
|
|
184
|
+
lineRange: [page.startLine + 1, page.endLine],
|
|
185
|
+
buffer,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
const totalTokens = results.reduce((sum, r) => sum + r.imageTokens, 0);
|
|
189
|
+
logger_1.default.info(`[TCE] Rendered ${pages.length} pages in ${Date.now() - startTime}ms (total ${totalTokens} img tokens)`);
|
|
190
|
+
return results;
|
|
191
|
+
}
|
|
192
|
+
/** No-op — sharp renderer has no persistent state to clean up */
|
|
193
|
+
function destroyRenderer() {
|
|
194
|
+
// Nothing to destroy — sharp is stateless
|
|
195
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Token Compression Engine — Themes
|
|
3
|
+
// Built-in visual themes for the text canvas renderer.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.THEMES = void 0;
|
|
6
|
+
exports.THEMES = {
|
|
7
|
+
dark: {
|
|
8
|
+
name: 'Dark',
|
|
9
|
+
background: '#1E1E2E',
|
|
10
|
+
foreground: '#CDD6F4',
|
|
11
|
+
gutterColor: '#45475A',
|
|
12
|
+
lineNumberColor: '#6C7086',
|
|
13
|
+
overlapBg: 'rgba(137, 180, 250, 0.06)',
|
|
14
|
+
overlapLabel: '#6C7086',
|
|
15
|
+
footerColor: '#585B70',
|
|
16
|
+
fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace",
|
|
17
|
+
proseFontFamily: "Inter, 'Segoe UI', Arial, sans-serif",
|
|
18
|
+
},
|
|
19
|
+
light: {
|
|
20
|
+
name: 'Light',
|
|
21
|
+
background: '#EFF1F5',
|
|
22
|
+
foreground: '#4C4F69',
|
|
23
|
+
gutterColor: '#BCC0CC',
|
|
24
|
+
lineNumberColor: '#8C8FA1',
|
|
25
|
+
overlapBg: 'rgba(30, 102, 245, 0.06)',
|
|
26
|
+
overlapLabel: '#8C8FA1',
|
|
27
|
+
footerColor: '#9CA0B0',
|
|
28
|
+
fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace",
|
|
29
|
+
proseFontFamily: "Inter, 'Segoe UI', Arial, sans-serif",
|
|
30
|
+
},
|
|
31
|
+
terminal: {
|
|
32
|
+
name: 'Terminal Green',
|
|
33
|
+
background: '#0C0C0C',
|
|
34
|
+
foreground: '#33FF33',
|
|
35
|
+
gutterColor: '#1A3A1A',
|
|
36
|
+
lineNumberColor: '#1A6A1A',
|
|
37
|
+
overlapBg: 'rgba(51, 255, 51, 0.04)',
|
|
38
|
+
overlapLabel: '#1A6A1A',
|
|
39
|
+
footerColor: '#1A5A1A',
|
|
40
|
+
fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace",
|
|
41
|
+
proseFontFamily: "'JetBrains Mono', Consolas, monospace",
|
|
42
|
+
},
|
|
43
|
+
'high-contrast': {
|
|
44
|
+
name: 'High Contrast',
|
|
45
|
+
background: '#000000',
|
|
46
|
+
foreground: '#FFFFFF',
|
|
47
|
+
gutterColor: '#333333',
|
|
48
|
+
lineNumberColor: '#888888',
|
|
49
|
+
overlapBg: 'rgba(255, 255, 255, 0.05)',
|
|
50
|
+
overlapLabel: '#666666',
|
|
51
|
+
footerColor: '#555555',
|
|
52
|
+
fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace",
|
|
53
|
+
proseFontFamily: "Inter, 'Segoe UI', Arial, sans-serif",
|
|
54
|
+
},
|
|
55
|
+
paper: {
|
|
56
|
+
name: 'Paper',
|
|
57
|
+
background: '#FFFFF8',
|
|
58
|
+
foreground: '#333333',
|
|
59
|
+
gutterColor: '#E0E0D8',
|
|
60
|
+
lineNumberColor: '#AAAAAA',
|
|
61
|
+
overlapBg: 'rgba(0, 0, 0, 0.03)',
|
|
62
|
+
overlapLabel: '#BBBBBB',
|
|
63
|
+
footerColor: '#AAAAAA',
|
|
64
|
+
fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace",
|
|
65
|
+
proseFontFamily: "Georgia, 'Times New Roman', serif",
|
|
66
|
+
},
|
|
67
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Token Compression Engine — Token Estimator
|
|
3
|
+
// Estimates text token counts and image token costs using Claude's vision formula.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.PRESETS = void 0;
|
|
6
|
+
exports.estimateTextTokens = estimateTextTokens;
|
|
7
|
+
exports.imageTokens = imageTokens;
|
|
8
|
+
exports.shouldCompress = shouldCompress;
|
|
9
|
+
/** Fast heuristic: ~4 characters per token, accurate within ~15% for English text and code */
|
|
10
|
+
function estimateTextTokens(text) {
|
|
11
|
+
return Math.ceil(text.length / 4);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Calculate image token cost using Claude's vision formula.
|
|
15
|
+
* Applies downscaling rules: max edge 1568px, max ~1.15MP.
|
|
16
|
+
*/
|
|
17
|
+
function imageTokens(width, height) {
|
|
18
|
+
let scale = 1.0;
|
|
19
|
+
// Max edge constraint: 1568px
|
|
20
|
+
const maxEdge = Math.max(width, height);
|
|
21
|
+
if (maxEdge > 1568) {
|
|
22
|
+
scale = Math.min(scale, 1568 / maxEdge);
|
|
23
|
+
}
|
|
24
|
+
// Max resolution constraint: ~1.15MP
|
|
25
|
+
const scaledArea = width * height * scale * scale;
|
|
26
|
+
if (scaledArea > 1_150_000) {
|
|
27
|
+
scale = Math.min(scale, Math.sqrt(1_150_000 / (width * height)));
|
|
28
|
+
}
|
|
29
|
+
const effectiveW = Math.round(width * scale);
|
|
30
|
+
const effectiveH = Math.round(height * scale);
|
|
31
|
+
return Math.round((effectiveW * effectiveH) / 750);
|
|
32
|
+
}
|
|
33
|
+
exports.PRESETS = {
|
|
34
|
+
micro: { name: 'Micro', width: 200, height: 200, tokens: 54, description: 'Ultra-low tokens' },
|
|
35
|
+
tiny: { name: 'Tiny', width: 320, height: 240, tokens: 103, description: 'Minimal cost' },
|
|
36
|
+
small: { name: 'Small', width: 480, height: 360, tokens: 231, description: 'Short snippets' },
|
|
37
|
+
compact: { name: 'Compact', width: 640, height: 480, tokens: 410, description: 'Balanced' },
|
|
38
|
+
standard: { name: 'Standard', width: 800, height: 600, tokens: 640, description: 'Code files, configs' },
|
|
39
|
+
tall: { name: 'Tall', width: 800, height: 900, tokens: 960, description: 'Long code files' },
|
|
40
|
+
wide: { name: 'Wide', width: 1200, height: 800, tokens: 1280, description: 'Dashboards, UIs' },
|
|
41
|
+
full: { name: 'Full', width: 1092, height: 1092, tokens: 1590, description: 'Max density' },
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Determine whether compression is worthwhile.
|
|
45
|
+
* Requires ratio ≥ 1.5 AND text tokens above threshold.
|
|
46
|
+
*/
|
|
47
|
+
function shouldCompress(textTokens, totalImageTokens, pageCount, threshold) {
|
|
48
|
+
const ratio = totalImageTokens > 0 ? textTokens / totalImageTokens : 0;
|
|
49
|
+
const savingsPercent = textTokens > 0 ? (1 - totalImageTokens / textTokens) * 100 : 0;
|
|
50
|
+
return {
|
|
51
|
+
recommend: ratio >= 1.5 && textTokens >= threshold,
|
|
52
|
+
ratio,
|
|
53
|
+
savingsPercent,
|
|
54
|
+
textTokens,
|
|
55
|
+
totalImageTokens,
|
|
56
|
+
pageCount,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Analytics telemetry forwarder.
|
|
3
|
+
//
|
|
4
|
+
// Buffers usage events locally and flushes them to the backend on a fixed
|
|
5
|
+
// interval. The same queue is used for both signed-in and anonymous users —
|
|
6
|
+
// at flush time we pick the right endpoint based on auth state.
|
|
7
|
+
//
|
|
8
|
+
// Defaults to enabled (opt-out). Users can disable via Settings > Privacy >
|
|
9
|
+
// "Share usage analytics" (persists as `analyticsOptOut`). The previous
|
|
10
|
+
// `telemetryOptIn` setting is left in place for backwards compatibility but
|
|
11
|
+
// no longer gates anything.
|
|
12
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
13
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
14
|
+
};
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.analyticsEnabled = analyticsEnabled;
|
|
17
|
+
exports.trackEvent = trackEvent;
|
|
18
|
+
exports.startTelemetry = startTelemetry;
|
|
19
|
+
exports.stopTelemetry = stopTelemetry;
|
|
20
|
+
exports.flushNow = flushNow;
|
|
21
|
+
exports.backfillLocalAnalytics = backfillLocalAnalytics;
|
|
22
|
+
const logger_1 = __importDefault(require("../logger"));
|
|
23
|
+
const auth_1 = require("./auth");
|
|
24
|
+
const license_1 = require("./license");
|
|
25
|
+
const store_1 = require("./store");
|
|
26
|
+
const API_BASE = 'https://api.superbased.app/api/v1';
|
|
27
|
+
const BATCH_INTERVAL = 60 * 1000; // 1 minute — short enough that admin sees fresh data
|
|
28
|
+
const MAX_QUEUE_SIZE = 500;
|
|
29
|
+
let eventQueue = [];
|
|
30
|
+
let batchTimer = null;
|
|
31
|
+
// When the historical-backfill flow is in progress, live flushes are paused
|
|
32
|
+
// so we don't race with the wipe-and-reupload sequence. Any events that come
|
|
33
|
+
// in during the window are written to local SQLite (via trackAnalytics) and
|
|
34
|
+
// will be picked up by the in-progress backfill read of analytics_events,
|
|
35
|
+
// then dropped from the queue at the end of backfill.
|
|
36
|
+
let backfillInProgress = false;
|
|
37
|
+
/**
|
|
38
|
+
* Returns true if usage analytics are enabled. Defaults to enabled — only
|
|
39
|
+
* disabled when the user has explicitly opted out in Settings > Privacy.
|
|
40
|
+
*/
|
|
41
|
+
function analyticsEnabled() {
|
|
42
|
+
return (0, store_1.getSetting)('analyticsOptOut') !== true;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Enqueue an analytics event. Called from `trackAnalytics()` in db/database.ts
|
|
46
|
+
* so every local hourly bucket also gets forwarded upstream. Also callable
|
|
47
|
+
* directly for one-off events that don't need local aggregation.
|
|
48
|
+
*/
|
|
49
|
+
function trackEvent(eventType, opts) {
|
|
50
|
+
if (!analyticsEnabled())
|
|
51
|
+
return;
|
|
52
|
+
eventQueue.push({
|
|
53
|
+
eventType,
|
|
54
|
+
eventSubtype: opts?.eventSubtype,
|
|
55
|
+
eventData: opts?.eventData,
|
|
56
|
+
appName: opts?.appName,
|
|
57
|
+
valueInt: opts?.valueInt,
|
|
58
|
+
});
|
|
59
|
+
if (eventQueue.length > MAX_QUEUE_SIZE) {
|
|
60
|
+
eventQueue = eventQueue.slice(-MAX_QUEUE_SIZE);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Start the periodic flush timer. Called once at app startup. Re-callable —
|
|
65
|
+
* subsequent calls are a no-op while a timer is already active.
|
|
66
|
+
*/
|
|
67
|
+
function startTelemetry() {
|
|
68
|
+
if (batchTimer)
|
|
69
|
+
return;
|
|
70
|
+
batchTimer = setInterval(flushEvents, BATCH_INTERVAL);
|
|
71
|
+
logger_1.default.info('[Telemetry] Started — flushing every 60s');
|
|
72
|
+
}
|
|
73
|
+
function stopTelemetry() {
|
|
74
|
+
if (batchTimer) {
|
|
75
|
+
clearInterval(batchTimer);
|
|
76
|
+
batchTimer = null;
|
|
77
|
+
}
|
|
78
|
+
// Best-effort flush on shutdown so we don't lose the last batch.
|
|
79
|
+
flushEvents().catch(() => { });
|
|
80
|
+
}
|
|
81
|
+
async function flushEvents() {
|
|
82
|
+
if (backfillInProgress) {
|
|
83
|
+
// Backfill owns the world right now — don't double-send.
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (eventQueue.length === 0)
|
|
87
|
+
return;
|
|
88
|
+
if (!analyticsEnabled()) {
|
|
89
|
+
// User flipped the toggle off mid-session — drop the queue rather than
|
|
90
|
+
// sending events they no longer consent to.
|
|
91
|
+
eventQueue = [];
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const events = [...eventQueue];
|
|
95
|
+
eventQueue = [];
|
|
96
|
+
const deviceId = (0, license_1.getMachineId)();
|
|
97
|
+
const appVersion = getAppVersion();
|
|
98
|
+
const eventsPayload = events.map((e) => ({
|
|
99
|
+
eventType: e.eventType,
|
|
100
|
+
eventSubtype: e.eventSubtype,
|
|
101
|
+
eventData: e.eventData,
|
|
102
|
+
appName: e.appName,
|
|
103
|
+
valueInt: e.valueInt,
|
|
104
|
+
appVersion,
|
|
105
|
+
}));
|
|
106
|
+
const authed = (0, auth_1.isAuthenticated)();
|
|
107
|
+
const url = authed ? `${API_BASE}/usage/event` : `${API_BASE}/anon/usage/event`;
|
|
108
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
109
|
+
if (authed) {
|
|
110
|
+
const token = (0, auth_1.getAuthToken)();
|
|
111
|
+
if (token)
|
|
112
|
+
headers['Authorization'] = `Bearer ${token}`;
|
|
113
|
+
}
|
|
114
|
+
const body = authed
|
|
115
|
+
? JSON.stringify({ events: eventsPayload.map((e) => ({ ...e, deviceId })) })
|
|
116
|
+
: JSON.stringify({ deviceId, events: eventsPayload });
|
|
117
|
+
try {
|
|
118
|
+
const response = await fetch(url, { method: 'POST', headers, body });
|
|
119
|
+
if (!response.ok) {
|
|
120
|
+
// Re-queue so we can try again on the next tick. Cap at MAX_QUEUE_SIZE
|
|
121
|
+
// so a long-running outage doesn't blow up memory.
|
|
122
|
+
eventQueue.unshift(...events);
|
|
123
|
+
if (eventQueue.length > MAX_QUEUE_SIZE) {
|
|
124
|
+
eventQueue = eventQueue.slice(-MAX_QUEUE_SIZE);
|
|
125
|
+
}
|
|
126
|
+
// Capture the response body so server-side errors aren't opaque.
|
|
127
|
+
// Truncated to keep noisy traffic from blowing up the log file.
|
|
128
|
+
let bodyText = '';
|
|
129
|
+
try {
|
|
130
|
+
bodyText = (await response.text()).slice(0, 500);
|
|
131
|
+
}
|
|
132
|
+
catch { /* ignore */ }
|
|
133
|
+
logger_1.default.warn(`[Telemetry] Flush failed: HTTP ${response.status} ${url} → ${bodyText}`);
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
logger_1.default.info(`[Telemetry] Flushed ${events.length} events to ${authed ? 'usage/event' : 'anon/usage/event'}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
eventQueue.unshift(...events);
|
|
141
|
+
if (eventQueue.length > MAX_QUEUE_SIZE) {
|
|
142
|
+
eventQueue = eventQueue.slice(-MAX_QUEUE_SIZE);
|
|
143
|
+
}
|
|
144
|
+
logger_1.default.warn('[Telemetry] Flush error:', err);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function getAppVersion() {
|
|
148
|
+
try {
|
|
149
|
+
return require('../../package.json').version;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return 'unknown';
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Manual force-flush — useful for tests or shutdown handlers.
|
|
157
|
+
*/
|
|
158
|
+
async function flushNow() {
|
|
159
|
+
await flushEvents();
|
|
160
|
+
}
|
|
161
|
+
// Bumped to 2 in v1.3.12 — the v1 backfill (=1) double-counted any events
|
|
162
|
+
// that landed via live flush before the backfill ran on the same launch,
|
|
163
|
+
// because both the live flush and the local SQLite hourly bucket pointed at
|
|
164
|
+
// the same logical events. v2 wipes the device's existing backend events
|
|
165
|
+
// before re-running so the backfill becomes the canonical source.
|
|
166
|
+
const BACKFILL_VERSION = 2;
|
|
167
|
+
/**
|
|
168
|
+
* One-shot historical backfill — uploads the local SQLite analytics_events
|
|
169
|
+
* hourly buckets to the backend so the admin console sees the same numbers
|
|
170
|
+
* as the user's local desktop Analytics tab.
|
|
171
|
+
*
|
|
172
|
+
* Self-healing: detects when an older backfill version (v1.3.11) ran and
|
|
173
|
+
* left double-counted data on the backend, wipes this device's existing
|
|
174
|
+
* events, then re-runs cleanly.
|
|
175
|
+
*
|
|
176
|
+
* Resumable: persists progress in the `analyticsBackfilledThroughHour`
|
|
177
|
+
* setting after each successful chunk so a partial upload doesn't have to
|
|
178
|
+
* restart from scratch on the next launch.
|
|
179
|
+
*
|
|
180
|
+
* Skipped on subsequent launches once `analyticsBackfillVersion` matches
|
|
181
|
+
* the current version. Skipped if the user has opted out of analytics.
|
|
182
|
+
*/
|
|
183
|
+
async function backfillLocalAnalytics() {
|
|
184
|
+
if (!analyticsEnabled())
|
|
185
|
+
return;
|
|
186
|
+
const currentVersion = (0, store_1.getSetting)('analyticsBackfillVersion') || 0;
|
|
187
|
+
if (currentVersion >= BACKFILL_VERSION)
|
|
188
|
+
return;
|
|
189
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
190
|
+
const { getLocalAnalyticsForBackfill } = require('../db/database');
|
|
191
|
+
const deviceId = (0, license_1.getMachineId)();
|
|
192
|
+
if (!deviceId || deviceId === 'unknown')
|
|
193
|
+
return;
|
|
194
|
+
const appVersion = getAppVersion();
|
|
195
|
+
const authed = (0, auth_1.isAuthenticated)();
|
|
196
|
+
const url = authed ? `${API_BASE}/usage/event` : `${API_BASE}/anon/usage/event`;
|
|
197
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
198
|
+
if (authed) {
|
|
199
|
+
const token = (0, auth_1.getAuthToken)();
|
|
200
|
+
if (token)
|
|
201
|
+
headers['Authorization'] = `Bearer ${token}`;
|
|
202
|
+
}
|
|
203
|
+
// Pause live flushes so we don't race the wipe-and-reupload.
|
|
204
|
+
backfillInProgress = true;
|
|
205
|
+
try {
|
|
206
|
+
// Step 1: wipe this device's existing backend events. Multi-device safe
|
|
207
|
+
// (deletes only events with this clerk_user_id + device_id, leaving
|
|
208
|
+
// other devices' events intact).
|
|
209
|
+
if (authed) {
|
|
210
|
+
try {
|
|
211
|
+
const wipeRes = await fetch(`${API_BASE}/usage/my-events`, {
|
|
212
|
+
method: 'DELETE',
|
|
213
|
+
headers,
|
|
214
|
+
body: JSON.stringify({ deviceId }),
|
|
215
|
+
});
|
|
216
|
+
if (wipeRes.ok) {
|
|
217
|
+
const body = await wipeRes.json().catch(() => ({}));
|
|
218
|
+
logger_1.default.info(`[Telemetry] Backfill wipe: deleted ${body.deleted ?? 0} stale rows for this device`);
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
let bodyText = '';
|
|
222
|
+
try {
|
|
223
|
+
bodyText = (await wipeRes.text()).slice(0, 500);
|
|
224
|
+
}
|
|
225
|
+
catch { /* ignore */ }
|
|
226
|
+
logger_1.default.warn(`[Telemetry] Backfill wipe failed: HTTP ${wipeRes.status} → ${bodyText}`);
|
|
227
|
+
// Continue anyway — the wipe is best-effort. Worst case we get
|
|
228
|
+
// some duplicates, which is no worse than what we have now.
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
logger_1.default.warn('[Telemetry] Backfill wipe error:', err);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// Step 2: reset the resume marker so we start from the beginning.
|
|
236
|
+
(0, store_1.setSetting)('analyticsBackfilledThroughHour', '');
|
|
237
|
+
// Step 3: walk local SQLite in 100-row chunks and upload.
|
|
238
|
+
let throughHour = '';
|
|
239
|
+
let totalSent = 0;
|
|
240
|
+
for (let iter = 0; iter < 500; iter++) {
|
|
241
|
+
const rows = getLocalAnalyticsForBackfill(throughHour, 100);
|
|
242
|
+
if (rows.length === 0)
|
|
243
|
+
break;
|
|
244
|
+
const events = rows.map((r) => ({
|
|
245
|
+
eventType: r.event_type,
|
|
246
|
+
eventSubtype: r.event_subtype || undefined,
|
|
247
|
+
appName: r.value_text || undefined,
|
|
248
|
+
valueInt: r.value_int || undefined,
|
|
249
|
+
count: r.count || 1,
|
|
250
|
+
occurredAt: hourBucketToISO(r.hour),
|
|
251
|
+
appVersion,
|
|
252
|
+
}));
|
|
253
|
+
const body = authed
|
|
254
|
+
? JSON.stringify({ events: events.map((e) => ({ ...e, deviceId })) })
|
|
255
|
+
: JSON.stringify({ deviceId, events });
|
|
256
|
+
try {
|
|
257
|
+
const response = await fetch(url, { method: 'POST', headers, body });
|
|
258
|
+
if (!response.ok) {
|
|
259
|
+
let bodyText = '';
|
|
260
|
+
try {
|
|
261
|
+
bodyText = (await response.text()).slice(0, 500);
|
|
262
|
+
}
|
|
263
|
+
catch { /* ignore */ }
|
|
264
|
+
logger_1.default.warn(`[Telemetry] Backfill chunk failed: HTTP ${response.status} → ${bodyText}`);
|
|
265
|
+
return; // bail; will retry on next launch
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
logger_1.default.warn('[Telemetry] Backfill chunk error:', err);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
throughHour = rows[rows.length - 1].hour;
|
|
273
|
+
(0, store_1.setSetting)('analyticsBackfilledThroughHour', throughHour);
|
|
274
|
+
totalSent += rows.length;
|
|
275
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
276
|
+
}
|
|
277
|
+
// Step 4: mark version 2 complete. Future launches will be no-ops.
|
|
278
|
+
(0, store_1.setSetting)('analyticsBackfillVersion', BACKFILL_VERSION);
|
|
279
|
+
(0, store_1.setSetting)('analyticsBackfillCompleted', true);
|
|
280
|
+
if (totalSent > 0) {
|
|
281
|
+
logger_1.default.info(`[Telemetry] Historical backfill v${BACKFILL_VERSION} complete: ${totalSent} hourly buckets sent`);
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
logger_1.default.info(`[Telemetry] Historical backfill v${BACKFILL_VERSION}: nothing to send`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
// Step 5: drop any events that came in during the backfill window.
|
|
289
|
+
// Those events ARE in the local SQLite (via trackAnalytics) and were
|
|
290
|
+
// therefore already covered by step 3's read of analytics_events.
|
|
291
|
+
// Sending them via live flush would double-count.
|
|
292
|
+
eventQueue = [];
|
|
293
|
+
backfillInProgress = false;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** Convert the local SQLite hour bucket label ("YYYY-MM-DD HH:00") into an
|
|
297
|
+
* ISO timestamp the backend can parse. The local label is in local time
|
|
298
|
+
* (per currentHourBucket() in db/database.ts), so we construct a local
|
|
299
|
+
* Date and let toISOString() emit the UTC equivalent. */
|
|
300
|
+
function hourBucketToISO(hour) {
|
|
301
|
+
try {
|
|
302
|
+
const [datePart, timePart] = hour.split(' ');
|
|
303
|
+
if (!datePart || !timePart)
|
|
304
|
+
return new Date().toISOString();
|
|
305
|
+
const [y, mo, d] = datePart.split('-').map(Number);
|
|
306
|
+
const [h, m] = timePart.split(':').map(Number);
|
|
307
|
+
const dt = new Date(y, (mo || 1) - 1, d || 1, h || 0, m || 0);
|
|
308
|
+
if (isNaN(dt.getTime()))
|
|
309
|
+
return new Date().toISOString();
|
|
310
|
+
return dt.toISOString();
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
return new Date().toISOString();
|
|
314
|
+
}
|
|
315
|
+
}
|