thumbgate 0.9.9
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/.claude-plugin/README.md +134 -0
- package/.claude-plugin/bundle/icon.png +0 -0
- package/.claude-plugin/bundle/icon.svg +18 -0
- package/.claude-plugin/bundle/server/index.js +24 -0
- package/.claude-plugin/marketplace.json +36 -0
- package/.claude-plugin/plugin.json +21 -0
- package/.well-known/mcp/server-card.json +231 -0
- package/LICENSE +21 -0
- package/README.md +375 -0
- package/adapters/README.md +9 -0
- package/adapters/amp/skills/rlhf-feedback/SKILL.md +22 -0
- package/adapters/chatgpt/INSTALL.md +83 -0
- package/adapters/chatgpt/openapi.yaml +1281 -0
- package/adapters/claude/.mcp.json +14 -0
- package/adapters/codex/config.toml +9 -0
- package/adapters/gemini/function-declarations.json +224 -0
- package/adapters/mcp/server-stdio.js +788 -0
- package/adapters/opencode/opencode.json +15 -0
- package/bin/cli.js +1483 -0
- package/bin/memory.sh +64 -0
- package/bin/obsidian-sync.sh +20 -0
- package/bin/postinstall.js +37 -0
- package/config/build-metadata.json +4 -0
- package/config/e2e-critical-flows.json +45 -0
- package/config/gate-templates.json +77 -0
- package/config/gates/claim-verification.json +29 -0
- package/config/gates/computer-use.json +39 -0
- package/config/gates/default.json +117 -0
- package/config/github-about.json +25 -0
- package/config/mcp-allowlists.json +135 -0
- package/config/model-tiers.json +33 -0
- package/config/partner-routing.json +132 -0
- package/config/policy-bundles/constrained-v1.json +64 -0
- package/config/policy-bundles/default-v1.json +91 -0
- package/config/rubrics/default-v1.json +52 -0
- package/config/skill-packs/react-testing.json +23 -0
- package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
- package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
- package/config/skill-specs/pr-reviewer.json +9 -0
- package/config/skill-specs/release-status.json +9 -0
- package/config/skill-specs/ticket-triage.json +9 -0
- package/config/subagent-profiles.json +32 -0
- package/config/tessl-tiles.json +29 -0
- package/config/thumbgate-settings.managed.json +12 -0
- package/openapi/openapi.yaml +1281 -0
- package/package.json +286 -0
- package/plugins/amp-skill/INSTALL.md +52 -0
- package/plugins/amp-skill/SKILL.md +64 -0
- package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
- package/plugins/claude-codex-bridge/.mcp.json +12 -0
- package/plugins/claude-codex-bridge/INSTALL.md +43 -0
- package/plugins/claude-codex-bridge/README.md +46 -0
- package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
- package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
- package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
- package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
- package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
- package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
- package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
- package/plugins/claude-skill/INSTALL.md +55 -0
- package/plugins/claude-skill/SKILL.md +46 -0
- package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
- package/plugins/codex-profile/.mcp.json +12 -0
- package/plugins/codex-profile/AGENTS.md +20 -0
- package/plugins/codex-profile/INSTALL.md +66 -0
- package/plugins/codex-profile/README.md +37 -0
- package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
- package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
- package/plugins/cursor-marketplace/LICENSE +21 -0
- package/plugins/cursor-marketplace/README.md +124 -0
- package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
- package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
- package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
- package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
- package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
- package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
- package/plugins/cursor-marketplace/mcp.json +12 -0
- package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
- package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
- package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
- package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
- package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
- package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
- package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
- package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
- package/plugins/gemini-extension/INSTALL.md +92 -0
- package/plugins/gemini-extension/gemini_prompt.txt +14 -0
- package/plugins/gemini-extension/tool_contract.json +45 -0
- package/plugins/opencode-profile/INSTALL.md +57 -0
- package/public/assets/instagram-card.png +0 -0
- package/public/assets/tiktok-agent-memory.mp4 +0 -0
- package/public/blog.html +400 -0
- package/public/dashboard.html +1093 -0
- package/public/guide.html +317 -0
- package/public/index.html +1195 -0
- package/public/learn/agent-harness-pattern.html +180 -0
- package/public/learn/ai-agent-persistent-memory.html +202 -0
- package/public/learn/learn.css +45 -0
- package/public/learn/mcp-pre-action-gates-explained.html +172 -0
- package/public/learn/stop-ai-agent-force-push.html +134 -0
- package/public/learn/vibe-coding-safety-net.html +142 -0
- package/public/learn.html +213 -0
- package/public/lessons.html +650 -0
- package/public/vercel.json +8 -0
- package/scripts/__pycache__/train_from_feedback.cpython-314.pyc +0 -0
- package/scripts/a2ui-engine.js +73 -0
- package/scripts/access-anomaly-detector.js +12 -0
- package/scripts/adk-consolidator.js +266 -0
- package/scripts/agent-readiness.js +220 -0
- package/scripts/agent-security-hardening.js +227 -0
- package/scripts/agentic-data-pipeline.js +847 -0
- package/scripts/analytics-report.js +328 -0
- package/scripts/analytics-window.js +158 -0
- package/scripts/async-job-runner.js +1001 -0
- package/scripts/audit-trail.js +398 -0
- package/scripts/auto-promote-gates.js +293 -0
- package/scripts/auto-wire-hooks.js +316 -0
- package/scripts/autonomous-sales-agent.js +39 -0
- package/scripts/autoresearch-runner.js +216 -0
- package/scripts/background-agent-governance.js +237 -0
- package/scripts/behavioral-extraction.js +93 -0
- package/scripts/belief-update.js +84 -0
- package/scripts/billing.js +2438 -0
- package/scripts/bot-detector.js +50 -0
- package/scripts/budget-guard.js +173 -0
- package/scripts/build-claude-mcpb.js +189 -0
- package/scripts/build-metadata.js +97 -0
- package/scripts/check-congruence.js +322 -0
- package/scripts/cli-feedback.js +135 -0
- package/scripts/cli-telemetry.js +87 -0
- package/scripts/cloudflare-dynamic-sandbox.js +315 -0
- package/scripts/code-reasoning.js +350 -0
- package/scripts/codegraph-context.js +466 -0
- package/scripts/commercial-offer.js +56 -0
- package/scripts/computer-use-firewall.js +250 -0
- package/scripts/context-engine.js +694 -0
- package/scripts/contextfs.js +1287 -0
- package/scripts/conversation-context.js +119 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/daily-digest.js +11 -0
- package/scripts/dashboard-render-spec.js +395 -0
- package/scripts/dashboard.js +1058 -0
- package/scripts/data-governance.js +173 -0
- package/scripts/delegation-runtime.js +900 -0
- package/scripts/deploy-gcp.sh +44 -0
- package/scripts/deploy-policy.js +231 -0
- package/scripts/disagreement-mining.js +315 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +44 -0
- package/scripts/dpo-optimizer.js +206 -0
- package/scripts/ensure-repo-bootstrap.js +129 -0
- package/scripts/ephemeral-agent-store.js +219 -0
- package/scripts/eval-harness.js +56 -0
- package/scripts/evolution-state.js +241 -0
- package/scripts/experiment-tracker.js +267 -0
- package/scripts/export-databricks-bundle.js +242 -0
- package/scripts/export-dpo-pairs.js +344 -0
- package/scripts/export-kto-pairs.js +309 -0
- package/scripts/export-training.js +450 -0
- package/scripts/failure-diagnostics.js +558 -0
- package/scripts/feedback-attribution.js +313 -0
- package/scripts/feedback-fallback.js +110 -0
- package/scripts/feedback-history-distiller.js +391 -0
- package/scripts/feedback-inbox-read.js +162 -0
- package/scripts/feedback-loop.js +1887 -0
- package/scripts/feedback-paths.js +145 -0
- package/scripts/feedback-quality.js +139 -0
- package/scripts/feedback-root-consolidator.js +238 -0
- package/scripts/feedback-schema.js +426 -0
- package/scripts/feedback-session.js +286 -0
- package/scripts/feedback-to-memory.js +185 -0
- package/scripts/feedback-to-rules.js +164 -0
- package/scripts/filesystem-search.js +405 -0
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-satisfy.js +42 -0
- package/scripts/gate-stats.js +116 -0
- package/scripts/gate-templates.js +70 -0
- package/scripts/gates-engine.js +816 -0
- package/scripts/generate-paperbanana-diagrams.sh +99 -0
- package/scripts/generate-pretool-hook.sh +40 -0
- package/scripts/github-about.js +350 -0
- package/scripts/github-outreach.js +65 -0
- package/scripts/gtm-revenue-loop.js +520 -0
- package/scripts/hallucination-detector.js +226 -0
- package/scripts/hf-papers.js +317 -0
- package/scripts/history-distiller.js +200 -0
- package/scripts/hook-auto-capture.sh +100 -0
- package/scripts/hook-stop-pr-thread-check.sh +68 -0
- package/scripts/hook-stop-self-score.sh +51 -0
- package/scripts/hook-stop-verify-deploy.sh +31 -0
- package/scripts/hook-thumbgate-cache-updater.js +48 -0
- package/scripts/hook-verify-before-done.sh +20 -0
- package/scripts/hosted-config.js +156 -0
- package/scripts/hybrid-feedback-context.js +675 -0
- package/scripts/install-mcp.js +159 -0
- package/scripts/intent-router.js +392 -0
- package/scripts/internal-agent-bootstrap.js +490 -0
- package/scripts/jsonl-watcher.js +155 -0
- package/scripts/lesson-db.js +613 -0
- package/scripts/lesson-inference.js +310 -0
- package/scripts/lesson-retrieval.js +95 -0
- package/scripts/lesson-rotation.js +137 -0
- package/scripts/lesson-search.js +644 -0
- package/scripts/lesson-synthesis.js +196 -0
- package/scripts/license.js +50 -0
- package/scripts/local-model-profile.js +384 -0
- package/scripts/markdown-escape.js +12 -0
- package/scripts/marketing-experiment.js +671 -0
- package/scripts/mcp-config.js +149 -0
- package/scripts/mcp-policy.js +99 -0
- package/scripts/memalign-recall.js +111 -0
- package/scripts/memory-firewall.js +222 -0
- package/scripts/memory-migration.js +296 -0
- package/scripts/meta-policy.js +190 -0
- package/scripts/metered-billing.js +16 -0
- package/scripts/model-tier-router.js +301 -0
- package/scripts/money-watcher.js +71 -0
- package/scripts/multi-hop-recall.js +240 -0
- package/scripts/natural-language-harness.js +330 -0
- package/scripts/obsidian-export.js +713 -0
- package/scripts/operational-dashboard.js +103 -0
- package/scripts/operational-summary.js +93 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/org-dashboard.js +201 -0
- package/scripts/partner-orchestration.js +146 -0
- package/scripts/per-step-scoring.js +165 -0
- package/scripts/perplexity-marketing.js +466 -0
- package/scripts/pii-scanner.js +153 -0
- package/scripts/plan-gate.js +154 -0
- package/scripts/post-everywhere.js +308 -0
- package/scripts/post-to-x-retry.sh +22 -0
- package/scripts/post-to-x.js +369 -0
- package/scripts/pr-manager.js +236 -0
- package/scripts/predictive-insights.js +356 -0
- package/scripts/principle-extractor.js +162 -0
- package/scripts/pro-features.js +40 -0
- package/scripts/pro-local-dashboard.js +174 -0
- package/scripts/problem-detail.js +53 -0
- package/scripts/product-feedback.js +134 -0
- package/scripts/profile-router.js +245 -0
- package/scripts/prompt-dlp.js +221 -0
- package/scripts/prompt-guard.js +83 -0
- package/scripts/prove-adapters.js +863 -0
- package/scripts/prove-attribution.js +365 -0
- package/scripts/prove-automation.js +653 -0
- package/scripts/prove-autoresearch.js +304 -0
- package/scripts/prove-claim-verification.js +277 -0
- package/scripts/prove-cloudflare-sandbox.js +163 -0
- package/scripts/prove-data-pipeline.js +410 -0
- package/scripts/prove-data-quality.js +227 -0
- package/scripts/prove-evolution.js +352 -0
- package/scripts/prove-harnesses.js +287 -0
- package/scripts/prove-intelligence.js +259 -0
- package/scripts/prove-lancedb.js +371 -0
- package/scripts/prove-local-intelligence.js +342 -0
- package/scripts/prove-loop-closure.js +263 -0
- package/scripts/prove-predictive-insights.js +357 -0
- package/scripts/prove-runtime.js +350 -0
- package/scripts/prove-seo-gsd.js +234 -0
- package/scripts/prove-settings.js +279 -0
- package/scripts/prove-subway-upgrades.js +277 -0
- package/scripts/prove-tessl.js +229 -0
- package/scripts/prove-training-export.js +327 -0
- package/scripts/prove-workflow-contract.js +116 -0
- package/scripts/prove-xmemory.js +332 -0
- package/scripts/publish-decision.js +133 -0
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +125 -0
- package/scripts/reddit-dm-outreach.js +182 -0
- package/scripts/reddit-monitor-cron.sh +26 -0
- package/scripts/reflector-agent.js +221 -0
- package/scripts/reminder-engine.js +132 -0
- package/scripts/revenue-status.js +472 -0
- package/scripts/risk-scorer.js +459 -0
- package/scripts/rlaif-self-audit.js +129 -0
- package/scripts/rlhf_session_start.sh +32 -0
- package/scripts/rubric-engine.js +230 -0
- package/scripts/schedule-manager.js +251 -0
- package/scripts/secret-scanner.js +414 -0
- package/scripts/self-heal.js +147 -0
- package/scripts/self-healing-check.js +188 -0
- package/scripts/semantic-layer.js +98 -0
- package/scripts/seo-gsd.js +1153 -0
- package/scripts/settings-hierarchy.js +214 -0
- package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
- package/scripts/skill-exporter.js +262 -0
- package/scripts/skill-generator.js +446 -0
- package/scripts/skill-materializer.js +134 -0
- package/scripts/skill-packs.js +136 -0
- package/scripts/skill-proposer.js +99 -0
- package/scripts/skill-quality-tracker.js +282 -0
- package/scripts/slo-alert-engine.js +14 -0
- package/scripts/slow-loop.js +72 -0
- package/scripts/social-analytics/db/schema.sql +32 -0
- package/scripts/social-analytics/db/social-analytics.db +0 -0
- package/scripts/social-analytics/digest.js +256 -0
- package/scripts/social-analytics/generate-instagram-card.js +97 -0
- package/scripts/social-analytics/instagram-thumbgate-post.js +107 -0
- package/scripts/social-analytics/load-env.js +46 -0
- package/scripts/social-analytics/mcp-server.js +289 -0
- package/scripts/social-analytics/normalizer.js +580 -0
- package/scripts/social-analytics/notify.js +162 -0
- package/scripts/social-analytics/poll-all.js +92 -0
- package/scripts/social-analytics/pollers/github.js +195 -0
- package/scripts/social-analytics/pollers/instagram.js +253 -0
- package/scripts/social-analytics/pollers/linkedin.js +330 -0
- package/scripts/social-analytics/pollers/plausible.js +247 -0
- package/scripts/social-analytics/pollers/reddit.js +306 -0
- package/scripts/social-analytics/pollers/threads.js +233 -0
- package/scripts/social-analytics/pollers/tiktok.js +203 -0
- package/scripts/social-analytics/pollers/x.js +227 -0
- package/scripts/social-analytics/pollers/youtube.js +304 -0
- package/scripts/social-analytics/pollers/zernio.js +183 -0
- package/scripts/social-analytics/publish-instagram-thumbgate.js +98 -0
- package/scripts/social-analytics/publish-thumbgate-launch.js +316 -0
- package/scripts/social-analytics/publishers/devto.js +122 -0
- package/scripts/social-analytics/publishers/instagram.js +317 -0
- package/scripts/social-analytics/publishers/linkedin.js +294 -0
- package/scripts/social-analytics/publishers/reddit.js +390 -0
- package/scripts/social-analytics/publishers/threads.js +275 -0
- package/scripts/social-analytics/publishers/tiktok.js +217 -0
- package/scripts/social-analytics/publishers/x.js +259 -0
- package/scripts/social-analytics/publishers/youtube.js +223 -0
- package/scripts/social-analytics/publishers/zernio.js +378 -0
- package/scripts/social-analytics/run-digest.js +34 -0
- package/scripts/social-analytics/store.js +257 -0
- package/scripts/social-analytics/utm.js +143 -0
- package/scripts/social-pipeline.js +2628 -0
- package/scripts/social-quality-gate.js +18 -0
- package/scripts/social-reply-monitor.js +445 -0
- package/scripts/status-dashboard.js +155 -0
- package/scripts/statusline-lesson.js +16 -0
- package/scripts/statusline-tower.js +8 -0
- package/scripts/statusline.sh +116 -0
- package/scripts/stripe-live-status.js +115 -0
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/sync-gh-secrets-from-env.sh +70 -0
- package/scripts/sync-github-about.js +52 -0
- package/scripts/sync-version.js +447 -0
- package/scripts/synthetic-dpo.js +234 -0
- package/scripts/telemetry-analytics.js +821 -0
- package/scripts/tessl-export.js +371 -0
- package/scripts/test-coverage.js +120 -0
- package/scripts/thompson-sampling.js +417 -0
- package/scripts/thumbgate-search.js +189 -0
- package/scripts/tool-kpi-tracker.js +12 -0
- package/scripts/tool-registry.js +811 -0
- package/scripts/train_from_feedback.py +933 -0
- package/scripts/user-profile.js +78 -0
- package/scripts/validate-feedback.js +581 -0
- package/scripts/validate-workflow-contract.js +287 -0
- package/scripts/vector-store.js +197 -0
- package/scripts/verification-loop.js +291 -0
- package/scripts/verify-obsidian-setup.sh +269 -0
- package/scripts/verify-run.js +269 -0
- package/scripts/webhook-delivery.js +62 -0
- package/scripts/weekly-auto-post.js +124 -0
- package/scripts/workflow-runs.js +154 -0
- package/scripts/workflow-sprint-intake.js +475 -0
- package/scripts/workspace-evolver.js +374 -0
- package/scripts/x-autonomous-marketing.js +139 -0
- package/scripts/xmemory-lite.js +405 -0
- package/skills/agent-memory/SKILL.md +97 -0
- package/skills/rlhf-feedback/SKILL.md +49 -0
- package/skills/solve-architecture-autonomy/SKILL.md +17 -0
- package/skills/solve-architecture-autonomy/tool.js +33 -0
- package/skills/thumbgate/SKILL.md +114 -0
- package/src/api/server.js +4206 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* zernio.js
|
|
5
|
+
* Unified publisher via Zernio API.
|
|
6
|
+
*
|
|
7
|
+
* Required env vars:
|
|
8
|
+
* ZERNIO_API_KEY — Bearer token for https://zernio.com/api/v1
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const fs = require('node:fs');
|
|
12
|
+
const path = require('node:path');
|
|
13
|
+
const { tagUrlsInText } = require('../utm');
|
|
14
|
+
const { loadLocalEnv } = require('../load-env');
|
|
15
|
+
|
|
16
|
+
const ZERNIO_UTM = { source: 'zernio', medium: 'social', campaign: 'organic' };
|
|
17
|
+
|
|
18
|
+
const ZERNIO_BASE = 'https://zernio.com/api/v1';
|
|
19
|
+
|
|
20
|
+
loadLocalEnv();
|
|
21
|
+
|
|
22
|
+
function requireApiKey() {
|
|
23
|
+
const key = process.env.ZERNIO_API_KEY;
|
|
24
|
+
if (!key) {
|
|
25
|
+
throw new Error('ZERNIO_API_KEY environment variable is required');
|
|
26
|
+
}
|
|
27
|
+
return key;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function resolveAccountId(account) {
|
|
31
|
+
if (!account || typeof account !== 'object') {
|
|
32
|
+
return '';
|
|
33
|
+
}
|
|
34
|
+
return String(account.accountId || account._id || account.id || '').trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function normalizeAccount(account) {
|
|
38
|
+
if (!account || typeof account !== 'object') {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const platform = String(account.platform || '').trim();
|
|
42
|
+
const accountId = resolveAccountId(account);
|
|
43
|
+
return {
|
|
44
|
+
...account,
|
|
45
|
+
platform,
|
|
46
|
+
accountId,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalizePlatforms(platforms) {
|
|
51
|
+
return platforms
|
|
52
|
+
.map(normalizeAccount)
|
|
53
|
+
.filter(Boolean)
|
|
54
|
+
.map((platform) => ({
|
|
55
|
+
platform: platform.platform,
|
|
56
|
+
accountId: platform.accountId,
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function groupAccountsByPlatform(accounts) {
|
|
61
|
+
const groups = new Map();
|
|
62
|
+
for (const account of accounts) {
|
|
63
|
+
if (!account || !account.platform || !account.accountId) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const existing = groups.get(account.platform) || [];
|
|
67
|
+
existing.push({
|
|
68
|
+
platform: account.platform,
|
|
69
|
+
accountId: account.accountId,
|
|
70
|
+
});
|
|
71
|
+
groups.set(account.platform, existing);
|
|
72
|
+
}
|
|
73
|
+
return groups;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function inferContentType(filePath) {
|
|
77
|
+
const ext = path.extname(String(filePath || '')).toLowerCase();
|
|
78
|
+
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
|
|
79
|
+
if (ext === '.png') return 'image/png';
|
|
80
|
+
if (ext === '.webp') return 'image/webp';
|
|
81
|
+
if (ext === '.gif') return 'image/gif';
|
|
82
|
+
if (ext === '.mp4') return 'video/mp4';
|
|
83
|
+
if (ext === '.mov') return 'video/quicktime';
|
|
84
|
+
if (ext === '.webm') return 'video/webm';
|
|
85
|
+
return 'application/octet-stream';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function inferMediaType(contentType) {
|
|
89
|
+
if (String(contentType || '').startsWith('video/')) {
|
|
90
|
+
return 'video';
|
|
91
|
+
}
|
|
92
|
+
return 'image';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function normalizePostResult(payload) {
|
|
96
|
+
const data = payload && typeof payload === 'object' ? (payload.data ?? payload) : {};
|
|
97
|
+
const post = data.post && typeof data.post === 'object' ? data.post : null;
|
|
98
|
+
const id = data.id || data._id || post?._id || post?.id || null;
|
|
99
|
+
return {
|
|
100
|
+
...data,
|
|
101
|
+
id,
|
|
102
|
+
post: post || data.post,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function zernioFetch(method, endpoint, body = null) {
|
|
107
|
+
const apiKey = requireApiKey();
|
|
108
|
+
const url = `${ZERNIO_BASE}${endpoint}`;
|
|
109
|
+
|
|
110
|
+
const options = {
|
|
111
|
+
method,
|
|
112
|
+
headers: {
|
|
113
|
+
Authorization: `Bearer ${apiKey}`,
|
|
114
|
+
'Content-Type': 'application/json',
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
if (body !== null) {
|
|
119
|
+
options.body = JSON.stringify(body);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const res = await fetch(url, options);
|
|
123
|
+
|
|
124
|
+
if (!res.ok) {
|
|
125
|
+
const errorText = await res.text().catch(() => '');
|
|
126
|
+
throw new Error(`Zernio API ${res.status} for ${method} ${endpoint}: ${errorText}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return res.json();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function requestMediaPresign(filename, contentType, size) {
|
|
133
|
+
if (!filename) throw new Error('requestMediaPresign: filename is required');
|
|
134
|
+
if (!contentType) throw new Error('requestMediaPresign: contentType is required');
|
|
135
|
+
|
|
136
|
+
const json = await zernioFetch('POST', '/media/presign', {
|
|
137
|
+
filename,
|
|
138
|
+
contentType,
|
|
139
|
+
size,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
return json.data ?? json;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function uploadLocalMedia(filePath, options = {}) {
|
|
146
|
+
const resolvedPath = path.resolve(String(filePath || ''));
|
|
147
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
148
|
+
throw new Error(`uploadLocalMedia: file not found at ${resolvedPath}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const stats = fs.statSync(resolvedPath);
|
|
152
|
+
const filename = options.filename || path.basename(resolvedPath);
|
|
153
|
+
const contentType = options.contentType || inferContentType(resolvedPath);
|
|
154
|
+
const presign = await requestMediaPresign(filename, contentType, stats.size);
|
|
155
|
+
|
|
156
|
+
if (!presign.uploadUrl || !presign.publicUrl) {
|
|
157
|
+
throw new Error('uploadLocalMedia: presign response missing uploadUrl or publicUrl');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const uploadResponse = await fetch(presign.uploadUrl, {
|
|
161
|
+
method: 'PUT',
|
|
162
|
+
headers: {
|
|
163
|
+
'Content-Type': contentType,
|
|
164
|
+
},
|
|
165
|
+
body: fs.readFileSync(resolvedPath),
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
if (!uploadResponse.ok) {
|
|
169
|
+
const errorText = await uploadResponse.text().catch(() => '');
|
|
170
|
+
throw new Error(`uploadLocalMedia: upload failed with ${uploadResponse.status}: ${errorText}`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
contentType,
|
|
175
|
+
key: presign.key || '',
|
|
176
|
+
size: stats.size,
|
|
177
|
+
type: presign.type || inferMediaType(contentType),
|
|
178
|
+
url: presign.publicUrl,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Publishes a post immediately to one or more platforms.
|
|
184
|
+
* @param {string} content
|
|
185
|
+
* @param {Array<{platform: string, accountId: string}>} platforms
|
|
186
|
+
* @returns {Promise<object>}
|
|
187
|
+
*/
|
|
188
|
+
async function publishPost(content, platforms, options = {}) {
|
|
189
|
+
if (!content) throw new Error('publishPost: content is required');
|
|
190
|
+
if (!Array.isArray(platforms) || platforms.length === 0) {
|
|
191
|
+
throw new Error('publishPost: platforms must be a non-empty array');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const normalizedPlatforms = normalizePlatforms(platforms);
|
|
195
|
+
if (normalizedPlatforms.length === 0 || normalizedPlatforms.some((entry) => !entry.platform || !entry.accountId)) {
|
|
196
|
+
throw new Error('publishPost: each platform entry requires platform and accountId');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Tag trackable URLs with Zernio UTM parameters before publishing
|
|
200
|
+
content = tagUrlsInText(content, options.utm || ZERNIO_UTM);
|
|
201
|
+
|
|
202
|
+
const qualityGate = require('../../social-quality-gate');
|
|
203
|
+
const gateResult = qualityGate.gatePost(content);
|
|
204
|
+
if (!gateResult.allowed) {
|
|
205
|
+
const reasons = gateResult.findings.map(f => f.reason).join(', ');
|
|
206
|
+
console.error(`[zernio:publisher] BLOCKED by quality gate: ${reasons}`);
|
|
207
|
+
return { blocked: true, reasons: gateResult.findings };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
console.log(`[zernio:publisher] Publishing to ${normalizedPlatforms.length} platform(s): ${normalizedPlatforms.map((p) => p.platform).join(', ')}`);
|
|
211
|
+
|
|
212
|
+
const json = await zernioFetch('POST', '/posts', {
|
|
213
|
+
content,
|
|
214
|
+
firstComment: options.firstComment,
|
|
215
|
+
mediaItems: options.mediaItems,
|
|
216
|
+
publishNow: true,
|
|
217
|
+
platforms: normalizedPlatforms,
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const data = normalizePostResult(json);
|
|
221
|
+
console.log(`[zernio:publisher] Post published. id=${data.id ?? 'unknown'}`);
|
|
222
|
+
return data;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Schedules a post for future publication.
|
|
227
|
+
* @param {string} content
|
|
228
|
+
* @param {Array<{platform: string, accountId: string}>} platforms
|
|
229
|
+
* @param {string} scheduledFor ISO 8601 datetime
|
|
230
|
+
* @param {string} timezone IANA timezone string
|
|
231
|
+
* @returns {Promise<object>}
|
|
232
|
+
*/
|
|
233
|
+
async function schedulePost(content, platforms, scheduledFor, timezone, options = {}) {
|
|
234
|
+
if (!content) throw new Error('schedulePost: content is required');
|
|
235
|
+
if (!Array.isArray(platforms) || platforms.length === 0) {
|
|
236
|
+
throw new Error('schedulePost: platforms must be a non-empty array');
|
|
237
|
+
}
|
|
238
|
+
if (!scheduledFor) throw new Error('schedulePost: scheduledFor is required');
|
|
239
|
+
if (!timezone) throw new Error('schedulePost: timezone is required');
|
|
240
|
+
|
|
241
|
+
const normalizedPlatforms = normalizePlatforms(platforms);
|
|
242
|
+
if (normalizedPlatforms.length === 0 || normalizedPlatforms.some((entry) => !entry.platform || !entry.accountId)) {
|
|
243
|
+
throw new Error('schedulePost: each platform entry requires platform and accountId');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
content = tagUrlsInText(content, options.utm || ZERNIO_UTM);
|
|
247
|
+
|
|
248
|
+
console.log(`[zernio:publisher] Scheduling post for ${scheduledFor} (${timezone}) to ${normalizedPlatforms.length} platform(s)`);
|
|
249
|
+
|
|
250
|
+
const json = await zernioFetch('POST', '/posts', {
|
|
251
|
+
content,
|
|
252
|
+
firstComment: options.firstComment,
|
|
253
|
+
mediaItems: options.mediaItems,
|
|
254
|
+
publishNow: false,
|
|
255
|
+
platforms: normalizedPlatforms,
|
|
256
|
+
scheduledFor,
|
|
257
|
+
timezone,
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const data = normalizePostResult(json);
|
|
261
|
+
console.log(`[zernio:publisher] Post scheduled. id=${data.id ?? 'unknown'}`);
|
|
262
|
+
return data;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Fetches all connected platform accounts from Zernio.
|
|
267
|
+
* @returns {Promise<Array<{platform: string, accountId: string, name: string}>>}
|
|
268
|
+
*/
|
|
269
|
+
async function getConnectedAccounts() {
|
|
270
|
+
console.log('[zernio:publisher] Fetching connected accounts');
|
|
271
|
+
|
|
272
|
+
const json = await zernioFetch('GET', '/accounts');
|
|
273
|
+
const accounts = (Array.isArray(json) ? json : (json.data ?? json.accounts ?? []))
|
|
274
|
+
.map(normalizeAccount)
|
|
275
|
+
.filter((account) => account && account.platform && account.accountId);
|
|
276
|
+
|
|
277
|
+
console.log(`[zernio:publisher] ${accounts.length} connected account(s) found`);
|
|
278
|
+
return accounts;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Publishes a post to all connected Zernio accounts in one call.
|
|
283
|
+
* @param {string} content
|
|
284
|
+
* @returns {Promise<{ published: object[], errors: object[] }>}
|
|
285
|
+
*/
|
|
286
|
+
async function publishToAllPlatforms(content, options = {}) {
|
|
287
|
+
if (!content) throw new Error('publishToAllPlatforms: content is required');
|
|
288
|
+
|
|
289
|
+
console.log('[zernio:publisher] Fetching all connected accounts for bulk publish');
|
|
290
|
+
const accounts = await getConnectedAccounts();
|
|
291
|
+
|
|
292
|
+
if (accounts.length === 0) {
|
|
293
|
+
console.warn('[zernio:publisher] No connected accounts found — nothing to publish');
|
|
294
|
+
return { published: [], errors: [] };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const published = [];
|
|
298
|
+
const errors = [];
|
|
299
|
+
const requestedPlatforms = Array.isArray(options.platforms) && options.platforms.length > 0
|
|
300
|
+
? new Set(options.platforms.map((platform) => String(platform || '').trim()).filter(Boolean))
|
|
301
|
+
: null;
|
|
302
|
+
const groupedAccounts = groupAccountsByPlatform(accounts);
|
|
303
|
+
|
|
304
|
+
for (const [platform, platformAccounts] of groupedAccounts.entries()) {
|
|
305
|
+
if (requestedPlatforms && !requestedPlatforms.has(platform)) {
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
try {
|
|
310
|
+
const result = await publishPost(content, platformAccounts, {
|
|
311
|
+
utm: {
|
|
312
|
+
source: platform,
|
|
313
|
+
medium: options.medium || ZERNIO_UTM.medium,
|
|
314
|
+
campaign: options.campaign || ZERNIO_UTM.campaign,
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
published.push({ platform, result });
|
|
318
|
+
} catch (err) {
|
|
319
|
+
console.error(`[zernio:publisher] Bulk publish failed for ${platform}: ${err.message}`);
|
|
320
|
+
errors.push({ error: err.message, platform });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
console.log(`[zernio:publisher] Bulk publish complete. published=${published.length} errors=${errors.length}`);
|
|
325
|
+
return { published, errors };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
module.exports = {
|
|
329
|
+
publishPost,
|
|
330
|
+
schedulePost,
|
|
331
|
+
publishToAllPlatforms,
|
|
332
|
+
getConnectedAccounts,
|
|
333
|
+
groupAccountsByPlatform,
|
|
334
|
+
inferContentType,
|
|
335
|
+
inferMediaType,
|
|
336
|
+
normalizeAccount,
|
|
337
|
+
normalizePlatforms,
|
|
338
|
+
normalizePostResult,
|
|
339
|
+
requestMediaPresign,
|
|
340
|
+
resolveAccountId,
|
|
341
|
+
uploadLocalMedia,
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
if (require.main === module) {
|
|
345
|
+
const args = process.argv.slice(2);
|
|
346
|
+
|
|
347
|
+
function getArg(flag) {
|
|
348
|
+
const prefix = `${flag}=`;
|
|
349
|
+
const entry = args.find((a) => a.startsWith(prefix));
|
|
350
|
+
return entry ? entry.slice(prefix.length) : null;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const text = getArg('--text');
|
|
354
|
+
const schedule = getArg('--schedule');
|
|
355
|
+
const timezone = getArg('--timezone') || 'UTC';
|
|
356
|
+
|
|
357
|
+
if (!text) {
|
|
358
|
+
console.error('Usage: node zernio.js --text="..." [--schedule="2026-04-01T10:00:00Z" --timezone="America/New_York"]');
|
|
359
|
+
process.exit(1);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
(async () => {
|
|
363
|
+
try {
|
|
364
|
+
if (schedule) {
|
|
365
|
+
const accounts = await getConnectedAccounts();
|
|
366
|
+
const platforms = accounts.map((a) => ({ platform: a.platform, accountId: a.accountId }));
|
|
367
|
+
const result = await schedulePost(text, platforms, schedule, timezone);
|
|
368
|
+
console.log(`[zernio:publisher] Scheduled. id=${result.id ?? 'unknown'}`);
|
|
369
|
+
} else {
|
|
370
|
+
const result = await publishToAllPlatforms(text);
|
|
371
|
+
console.log(`[zernio:publisher] Done. published=${result.published.length} errors=${result.errors.length}`);
|
|
372
|
+
}
|
|
373
|
+
} catch (err) {
|
|
374
|
+
console.error('[zernio:publisher] Failed:', err.message);
|
|
375
|
+
process.exit(1);
|
|
376
|
+
}
|
|
377
|
+
})();
|
|
378
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const { initDb } = require('./store');
|
|
5
|
+
const { generateDigest, writeDigest } = require('./digest');
|
|
6
|
+
const { sendSlackDigest, formatDigestForConsole } = require('./notify');
|
|
7
|
+
|
|
8
|
+
async function main(argv = process.argv.slice(2)) {
|
|
9
|
+
const days = parseInt(argv.find((a) => a.startsWith('--days='))?.split('=')[1] || '7', 10) || 7;
|
|
10
|
+
const outputDir = path.resolve(__dirname, '..', '..', '.artifacts', 'social', 'digests');
|
|
11
|
+
|
|
12
|
+
console.log(`Generating ${days}-day social analytics digest...`);
|
|
13
|
+
|
|
14
|
+
const db = initDb();
|
|
15
|
+
const digest = generateDigest(db, { days });
|
|
16
|
+
db.close();
|
|
17
|
+
|
|
18
|
+
writeDigest(digest, outputDir);
|
|
19
|
+
console.log(`Digest written to ${outputDir}`);
|
|
20
|
+
|
|
21
|
+
console.log('');
|
|
22
|
+
console.log(formatDigestForConsole(digest));
|
|
23
|
+
|
|
24
|
+
await sendSlackDigest(digest);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (require.main === module) {
|
|
28
|
+
main().catch((err) => {
|
|
29
|
+
console.error(err);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = { main };
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const Database = require('better-sqlite3');
|
|
6
|
+
|
|
7
|
+
const DEFAULT_DB_PATH = path.join(__dirname, 'db', 'social-analytics.db');
|
|
8
|
+
const SCHEMA_PATH = path.join(__dirname, 'db', 'schema.sql');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Opens the SQLite database, applies the schema, and returns the db instance.
|
|
12
|
+
* Idempotent — safe to call multiple times; schema uses IF NOT EXISTS guards.
|
|
13
|
+
*
|
|
14
|
+
* @param {string} [dbPath] - Absolute path to the .db file. Defaults to DEFAULT_DB_PATH.
|
|
15
|
+
* @returns {import('better-sqlite3').Database}
|
|
16
|
+
*/
|
|
17
|
+
function initDb(dbPath = DEFAULT_DB_PATH) {
|
|
18
|
+
const isInMemoryDatabase = dbPath === ':memory:';
|
|
19
|
+
const resolvedPath = isInMemoryDatabase ? dbPath : path.resolve(dbPath);
|
|
20
|
+
const dir = isInMemoryDatabase ? null : path.dirname(resolvedPath);
|
|
21
|
+
|
|
22
|
+
if (dir && !fs.existsSync(dir)) {
|
|
23
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const db = new Database(resolvedPath);
|
|
27
|
+
db.pragma('busy_timeout = 3000');
|
|
28
|
+
|
|
29
|
+
// Enable WAL mode for better concurrent read performance.
|
|
30
|
+
if (!isInMemoryDatabase) {
|
|
31
|
+
db.pragma('journal_mode = WAL');
|
|
32
|
+
}
|
|
33
|
+
db.pragma('foreign_keys = ON');
|
|
34
|
+
|
|
35
|
+
const schema = fs.readFileSync(SCHEMA_PATH, 'utf8');
|
|
36
|
+
db.exec(schema);
|
|
37
|
+
|
|
38
|
+
return db;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Upserts a single engagement metric record.
|
|
43
|
+
* Uses INSERT OR REPLACE to handle the UNIQUE(platform, post_id, metric_date) constraint.
|
|
44
|
+
*
|
|
45
|
+
* @param {import('better-sqlite3').Database} db
|
|
46
|
+
* @param {object} record - Fields matching the engagement_metrics schema.
|
|
47
|
+
* @param {string} record.platform
|
|
48
|
+
* @param {string} record.content_type
|
|
49
|
+
* @param {string} record.post_id
|
|
50
|
+
* @param {string} [record.post_url]
|
|
51
|
+
* @param {string} [record.published_at]
|
|
52
|
+
* @param {string} record.metric_date
|
|
53
|
+
* @param {number} [record.impressions]
|
|
54
|
+
* @param {number} [record.reach]
|
|
55
|
+
* @param {number} [record.likes]
|
|
56
|
+
* @param {number} [record.comments]
|
|
57
|
+
* @param {number} [record.shares]
|
|
58
|
+
* @param {number} [record.saves]
|
|
59
|
+
* @param {number} [record.clicks]
|
|
60
|
+
* @param {number} [record.video_views]
|
|
61
|
+
* @param {number} [record.followers_delta]
|
|
62
|
+
* @param {string|object} [record.extra_json]
|
|
63
|
+
* @param {string} record.fetched_at
|
|
64
|
+
* @returns {import('better-sqlite3').RunResult}
|
|
65
|
+
*/
|
|
66
|
+
function upsertMetric(db, record) {
|
|
67
|
+
if (!record.platform) throw new Error('upsertMetric: record.platform is required');
|
|
68
|
+
if (!record.content_type) throw new Error('upsertMetric: record.content_type is required');
|
|
69
|
+
if (!record.post_id) throw new Error('upsertMetric: record.post_id is required');
|
|
70
|
+
if (!record.metric_date) throw new Error('upsertMetric: record.metric_date is required');
|
|
71
|
+
if (!record.fetched_at) throw new Error('upsertMetric: record.fetched_at is required');
|
|
72
|
+
|
|
73
|
+
const extraJson =
|
|
74
|
+
record.extra_json && typeof record.extra_json === 'object'
|
|
75
|
+
? JSON.stringify(record.extra_json)
|
|
76
|
+
: record.extra_json ?? null;
|
|
77
|
+
|
|
78
|
+
const stmt = db.prepare(`
|
|
79
|
+
INSERT OR REPLACE INTO engagement_metrics (
|
|
80
|
+
platform, content_type, post_id, post_url, published_at, metric_date,
|
|
81
|
+
impressions, reach, likes, comments, shares, saves, clicks,
|
|
82
|
+
video_views, followers_delta, extra_json, fetched_at
|
|
83
|
+
) VALUES (
|
|
84
|
+
@platform, @content_type, @post_id, @post_url, @published_at, @metric_date,
|
|
85
|
+
@impressions, @reach, @likes, @comments, @shares, @saves, @clicks,
|
|
86
|
+
@video_views, @followers_delta, @extra_json, @fetched_at
|
|
87
|
+
)
|
|
88
|
+
`);
|
|
89
|
+
|
|
90
|
+
return stmt.run({
|
|
91
|
+
platform: record.platform,
|
|
92
|
+
content_type: record.content_type,
|
|
93
|
+
post_id: record.post_id,
|
|
94
|
+
post_url: record.post_url ?? null,
|
|
95
|
+
published_at: record.published_at ?? null,
|
|
96
|
+
metric_date: record.metric_date,
|
|
97
|
+
impressions: record.impressions ?? 0,
|
|
98
|
+
reach: record.reach ?? 0,
|
|
99
|
+
likes: record.likes ?? 0,
|
|
100
|
+
comments: record.comments ?? 0,
|
|
101
|
+
shares: record.shares ?? 0,
|
|
102
|
+
saves: record.saves ?? 0,
|
|
103
|
+
clicks: record.clicks ?? 0,
|
|
104
|
+
video_views: record.video_views ?? 0,
|
|
105
|
+
followers_delta: record.followers_delta ?? 0,
|
|
106
|
+
extra_json: extraJson,
|
|
107
|
+
fetched_at: record.fetched_at,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Upserts a follower snapshot.
|
|
113
|
+
*
|
|
114
|
+
* @param {import('better-sqlite3').Database} db
|
|
115
|
+
* @param {{ platform: string, follower_count: number, snapshot_date: string }} snapshot
|
|
116
|
+
* @returns {import('better-sqlite3').RunResult}
|
|
117
|
+
*/
|
|
118
|
+
function upsertFollowerSnapshot(db, { platform, follower_count, snapshot_date }) {
|
|
119
|
+
if (!platform) throw new Error('upsertFollowerSnapshot: platform is required');
|
|
120
|
+
if (follower_count == null) throw new Error('upsertFollowerSnapshot: follower_count is required');
|
|
121
|
+
if (!snapshot_date) throw new Error('upsertFollowerSnapshot: snapshot_date is required');
|
|
122
|
+
|
|
123
|
+
const stmt = db.prepare(`
|
|
124
|
+
INSERT OR REPLACE INTO follower_snapshots (platform, follower_count, snapshot_date)
|
|
125
|
+
VALUES (@platform, @follower_count, @snapshot_date)
|
|
126
|
+
`);
|
|
127
|
+
|
|
128
|
+
return stmt.run({ platform, follower_count, snapshot_date });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Returns aggregated engagement metrics grouped by platform for the last N days.
|
|
133
|
+
*
|
|
134
|
+
* @param {import('better-sqlite3').Database} db
|
|
135
|
+
* @param {{ platform?: string, days?: number }} options
|
|
136
|
+
* @returns {object[]}
|
|
137
|
+
*/
|
|
138
|
+
function queryMetrics(db, { platform, days = 30 } = {}) {
|
|
139
|
+
if (days <= 0) throw new Error('queryMetrics: days must be a positive integer');
|
|
140
|
+
|
|
141
|
+
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
|
|
142
|
+
.toISOString()
|
|
143
|
+
.slice(0, 10);
|
|
144
|
+
|
|
145
|
+
const params = { cutoff };
|
|
146
|
+
let platformClause = '';
|
|
147
|
+
|
|
148
|
+
if (platform) {
|
|
149
|
+
platformClause = 'AND platform = @platform';
|
|
150
|
+
params.platform = platform;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return db
|
|
154
|
+
.prepare(
|
|
155
|
+
`
|
|
156
|
+
SELECT
|
|
157
|
+
platform,
|
|
158
|
+
COUNT(DISTINCT post_id) AS post_count,
|
|
159
|
+
SUM(impressions) AS total_impressions,
|
|
160
|
+
SUM(reach) AS total_reach,
|
|
161
|
+
SUM(likes) AS total_likes,
|
|
162
|
+
SUM(comments) AS total_comments,
|
|
163
|
+
SUM(shares) AS total_shares,
|
|
164
|
+
SUM(saves) AS total_saves,
|
|
165
|
+
SUM(clicks) AS total_clicks,
|
|
166
|
+
SUM(video_views) AS total_video_views,
|
|
167
|
+
ROUND(AVG(impressions), 2) AS avg_impressions,
|
|
168
|
+
ROUND(AVG(likes), 2) AS avg_likes
|
|
169
|
+
FROM engagement_metrics
|
|
170
|
+
WHERE metric_date >= @cutoff
|
|
171
|
+
${platformClause}
|
|
172
|
+
GROUP BY platform
|
|
173
|
+
ORDER BY total_impressions DESC
|
|
174
|
+
`
|
|
175
|
+
)
|
|
176
|
+
.all(params);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Returns top content by total engagement (likes + comments + shares + saves)
|
|
181
|
+
* for the last N days.
|
|
182
|
+
*
|
|
183
|
+
* @param {import('better-sqlite3').Database} db
|
|
184
|
+
* @param {{ days?: number, limit?: number }} options
|
|
185
|
+
* @returns {object[]}
|
|
186
|
+
*/
|
|
187
|
+
function topContent(db, { days = 30, limit = 10 } = {}) {
|
|
188
|
+
if (days <= 0) throw new Error('topContent: days must be a positive integer');
|
|
189
|
+
if (limit <= 0) throw new Error('topContent: limit must be a positive integer');
|
|
190
|
+
|
|
191
|
+
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
|
|
192
|
+
.toISOString()
|
|
193
|
+
.slice(0, 10);
|
|
194
|
+
|
|
195
|
+
return db
|
|
196
|
+
.prepare(
|
|
197
|
+
`
|
|
198
|
+
SELECT
|
|
199
|
+
platform,
|
|
200
|
+
content_type,
|
|
201
|
+
post_id,
|
|
202
|
+
post_url,
|
|
203
|
+
published_at,
|
|
204
|
+
SUM(likes + comments + shares + saves) AS total_engagement,
|
|
205
|
+
SUM(impressions) AS total_impressions,
|
|
206
|
+
SUM(likes) AS total_likes,
|
|
207
|
+
SUM(comments) AS total_comments,
|
|
208
|
+
SUM(shares) AS total_shares,
|
|
209
|
+
SUM(saves) AS total_saves,
|
|
210
|
+
SUM(video_views) AS total_video_views
|
|
211
|
+
FROM engagement_metrics
|
|
212
|
+
WHERE metric_date >= @cutoff
|
|
213
|
+
GROUP BY platform, post_id
|
|
214
|
+
ORDER BY total_engagement DESC
|
|
215
|
+
LIMIT @limit
|
|
216
|
+
`
|
|
217
|
+
)
|
|
218
|
+
.all({ cutoff, limit });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Returns follower snapshots for a platform for the last N days.
|
|
223
|
+
*
|
|
224
|
+
* @param {import('better-sqlite3').Database} db
|
|
225
|
+
* @param {{ platform: string, days?: number }} options
|
|
226
|
+
* @returns {object[]}
|
|
227
|
+
*/
|
|
228
|
+
function getFollowerHistory(db, { platform, days = 30 } = {}) {
|
|
229
|
+
if (!platform) throw new Error('getFollowerHistory: platform is required');
|
|
230
|
+
if (days <= 0) throw new Error('getFollowerHistory: days must be a positive integer');
|
|
231
|
+
|
|
232
|
+
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
|
|
233
|
+
.toISOString()
|
|
234
|
+
.slice(0, 10);
|
|
235
|
+
|
|
236
|
+
return db
|
|
237
|
+
.prepare(
|
|
238
|
+
`
|
|
239
|
+
SELECT platform, follower_count, snapshot_date
|
|
240
|
+
FROM follower_snapshots
|
|
241
|
+
WHERE platform = @platform
|
|
242
|
+
AND snapshot_date >= @cutoff
|
|
243
|
+
ORDER BY snapshot_date ASC
|
|
244
|
+
`
|
|
245
|
+
)
|
|
246
|
+
.all({ platform, cutoff });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
module.exports = {
|
|
250
|
+
DEFAULT_DB_PATH,
|
|
251
|
+
initDb,
|
|
252
|
+
upsertMetric,
|
|
253
|
+
upsertFollowerSnapshot,
|
|
254
|
+
queryMetrics,
|
|
255
|
+
topContent,
|
|
256
|
+
getFollowerHistory,
|
|
257
|
+
};
|