@eduardbar/drift 1.1.0 → 1.2.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/dist/saas.js ADDED
@@ -0,0 +1,321 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ const STORE_VERSION = 1;
4
+ const ACTIVE_WINDOW_DAYS = 30;
5
+ export const DEFAULT_SAAS_POLICY = {
6
+ freeUserThreshold: 7500,
7
+ maxRunsPerWorkspacePerMonth: 500,
8
+ maxReposPerWorkspace: 20,
9
+ retentionDays: 90,
10
+ };
11
+ export function resolveSaasPolicy(policy) {
12
+ return {
13
+ ...DEFAULT_SAAS_POLICY,
14
+ ...(policy ?? {}),
15
+ };
16
+ }
17
+ export function defaultSaasStorePath(root = '.') {
18
+ return resolve(root, '.drift-cloud', 'store.json');
19
+ }
20
+ function ensureStoreFile(storeFile, policy) {
21
+ const dir = dirname(storeFile);
22
+ if (!existsSync(dir))
23
+ mkdirSync(dir, { recursive: true });
24
+ if (!existsSync(storeFile)) {
25
+ const initial = createEmptyStore(policy);
26
+ writeFileSync(storeFile, JSON.stringify(initial, null, 2), 'utf8');
27
+ }
28
+ }
29
+ function createEmptyStore(policy) {
30
+ return {
31
+ version: STORE_VERSION,
32
+ policy: resolveSaasPolicy(policy),
33
+ users: {},
34
+ workspaces: {},
35
+ repos: {},
36
+ snapshots: [],
37
+ };
38
+ }
39
+ function monthKey(isoDate) {
40
+ const date = new Date(isoDate);
41
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
42
+ return `${date.getUTCFullYear()}-${month}`;
43
+ }
44
+ function daysAgo(days) {
45
+ const now = Date.now();
46
+ return now - days * 24 * 60 * 60 * 1000;
47
+ }
48
+ function applyRetention(store) {
49
+ const cutoff = daysAgo(store.policy.retentionDays);
50
+ store.snapshots = store.snapshots.filter((snapshot) => {
51
+ return new Date(snapshot.createdAt).getTime() >= cutoff;
52
+ });
53
+ }
54
+ function saveStore(storeFile, store) {
55
+ writeFileSync(storeFile, JSON.stringify(store, null, 2), 'utf8');
56
+ }
57
+ function loadStoreInternal(storeFile, policy) {
58
+ ensureStoreFile(storeFile, policy);
59
+ const raw = readFileSync(storeFile, 'utf8');
60
+ const parsed = JSON.parse(raw);
61
+ const merged = createEmptyStore(parsed.policy);
62
+ merged.version = parsed.version ?? STORE_VERSION;
63
+ merged.users = parsed.users ?? {};
64
+ merged.workspaces = parsed.workspaces ?? {};
65
+ merged.repos = parsed.repos ?? {};
66
+ merged.snapshots = parsed.snapshots ?? [];
67
+ merged.policy = resolveSaasPolicy({ ...merged.policy, ...policy });
68
+ applyRetention(merged);
69
+ return merged;
70
+ }
71
+ function isWorkspaceActive(workspace) {
72
+ return new Date(workspace.lastSeenAt).getTime() >= daysAgo(ACTIVE_WINDOW_DAYS);
73
+ }
74
+ function isRepoActive(repo) {
75
+ return new Date(repo.lastSeenAt).getTime() >= daysAgo(ACTIVE_WINDOW_DAYS);
76
+ }
77
+ function assertGuardrails(store, options, nowIso) {
78
+ const usersRegistered = Object.keys(store.users).length;
79
+ const isFreePhase = usersRegistered < store.policy.freeUserThreshold;
80
+ if (!isFreePhase)
81
+ return;
82
+ if (!store.users[options.userId] && usersRegistered + 1 > store.policy.freeUserThreshold) {
83
+ throw new Error(`Free threshold reached (${store.policy.freeUserThreshold} users).`);
84
+ }
85
+ const workspace = store.workspaces[options.workspaceId];
86
+ const repoName = options.repoName ?? 'default';
87
+ const repoId = `${options.workspaceId}:${repoName}`;
88
+ const repoExists = Boolean(store.repos[repoId]);
89
+ const repoCount = workspace?.repoIds.length ?? 0;
90
+ if (!repoExists && repoCount >= store.policy.maxReposPerWorkspace) {
91
+ throw new Error(`Workspace '${options.workspaceId}' reached max repos (${store.policy.maxReposPerWorkspace}).`);
92
+ }
93
+ const currentMonth = monthKey(nowIso);
94
+ const runsThisMonth = store.snapshots.filter((snapshot) => {
95
+ return snapshot.workspaceId === options.workspaceId && monthKey(snapshot.createdAt) === currentMonth;
96
+ }).length;
97
+ if (runsThisMonth >= store.policy.maxRunsPerWorkspacePerMonth) {
98
+ throw new Error(`Workspace '${options.workspaceId}' reached max monthly runs (${store.policy.maxRunsPerWorkspacePerMonth}).`);
99
+ }
100
+ }
101
+ export function ingestSnapshotFromReport(report, options) {
102
+ const storeFile = resolve(options.storeFile ?? defaultSaasStorePath());
103
+ const store = loadStoreInternal(storeFile, options.policy);
104
+ const nowIso = new Date().toISOString();
105
+ assertGuardrails(store, options, nowIso);
106
+ const user = store.users[options.userId];
107
+ if (user) {
108
+ user.lastSeenAt = nowIso;
109
+ }
110
+ else {
111
+ store.users[options.userId] = {
112
+ id: options.userId,
113
+ createdAt: nowIso,
114
+ lastSeenAt: nowIso,
115
+ };
116
+ }
117
+ const workspace = store.workspaces[options.workspaceId];
118
+ if (workspace) {
119
+ workspace.lastSeenAt = nowIso;
120
+ if (!workspace.userIds.includes(options.userId))
121
+ workspace.userIds.push(options.userId);
122
+ }
123
+ else {
124
+ store.workspaces[options.workspaceId] = {
125
+ id: options.workspaceId,
126
+ createdAt: nowIso,
127
+ lastSeenAt: nowIso,
128
+ userIds: [options.userId],
129
+ repoIds: [],
130
+ };
131
+ }
132
+ const repoName = options.repoName ?? 'default';
133
+ const repoId = `${options.workspaceId}:${repoName}`;
134
+ const repo = store.repos[repoId];
135
+ if (repo) {
136
+ repo.lastSeenAt = nowIso;
137
+ }
138
+ else {
139
+ store.repos[repoId] = {
140
+ id: repoId,
141
+ workspaceId: options.workspaceId,
142
+ name: repoName,
143
+ createdAt: nowIso,
144
+ lastSeenAt: nowIso,
145
+ };
146
+ const ws = store.workspaces[options.workspaceId];
147
+ if (!ws.repoIds.includes(repoId))
148
+ ws.repoIds.push(repoId);
149
+ }
150
+ const snapshot = {
151
+ id: `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`,
152
+ createdAt: nowIso,
153
+ scannedAt: report.scannedAt,
154
+ workspaceId: options.workspaceId,
155
+ userId: options.userId,
156
+ repoId,
157
+ repoName,
158
+ targetPath: report.targetPath,
159
+ totalScore: report.totalScore,
160
+ totalIssues: report.totalIssues,
161
+ totalFiles: report.totalFiles,
162
+ summary: {
163
+ errors: report.summary.errors,
164
+ warnings: report.summary.warnings,
165
+ infos: report.summary.infos,
166
+ },
167
+ };
168
+ store.snapshots.push(snapshot);
169
+ applyRetention(store);
170
+ saveStore(storeFile, store);
171
+ return snapshot;
172
+ }
173
+ export function getSaasSummary(options) {
174
+ const storeFile = resolve(options?.storeFile ?? defaultSaasStorePath());
175
+ const store = loadStoreInternal(storeFile, options?.policy);
176
+ saveStore(storeFile, store);
177
+ const usersRegistered = Object.keys(store.users).length;
178
+ const workspacesActive = Object.values(store.workspaces).filter(isWorkspaceActive).length;
179
+ const reposActive = Object.values(store.repos).filter(isRepoActive).length;
180
+ const runsPerMonth = {};
181
+ for (const snapshot of store.snapshots) {
182
+ const key = monthKey(snapshot.createdAt);
183
+ runsPerMonth[key] = (runsPerMonth[key] ?? 0) + 1;
184
+ }
185
+ const thresholdReached = usersRegistered >= store.policy.freeUserThreshold;
186
+ return {
187
+ policy: store.policy,
188
+ usersRegistered,
189
+ workspacesActive,
190
+ reposActive,
191
+ runsPerMonth,
192
+ totalSnapshots: store.snapshots.length,
193
+ phase: thresholdReached ? 'paid' : 'free',
194
+ thresholdReached,
195
+ freeUsersRemaining: Math.max(0, store.policy.freeUserThreshold - usersRegistered),
196
+ };
197
+ }
198
+ function escapeHtml(value) {
199
+ return value
200
+ .replaceAll('&', '&amp;')
201
+ .replaceAll('<', '&lt;')
202
+ .replaceAll('>', '&gt;')
203
+ .replaceAll('"', '&quot;')
204
+ .replaceAll("'", '&#39;');
205
+ }
206
+ export function generateSaasDashboardHtml(options) {
207
+ const storeFile = resolve(options?.storeFile ?? defaultSaasStorePath());
208
+ const store = loadStoreInternal(storeFile, options?.policy);
209
+ const summary = getSaasSummary(options);
210
+ const workspaceStats = Object.values(store.workspaces)
211
+ .map((workspace) => {
212
+ const snapshots = store.snapshots.filter((snapshot) => snapshot.workspaceId === workspace.id);
213
+ const runs = snapshots.length;
214
+ const avgScore = runs === 0
215
+ ? 0
216
+ : Math.round(snapshots.reduce((sum, snapshot) => sum + snapshot.totalScore, 0) / runs);
217
+ const lastRun = snapshots.sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0]?.createdAt ?? 'n/a';
218
+ return {
219
+ id: workspace.id,
220
+ runs,
221
+ avgScore,
222
+ lastRun,
223
+ };
224
+ })
225
+ .sort((a, b) => b.avgScore - a.avgScore);
226
+ const repoStats = Object.values(store.repos)
227
+ .map((repo) => {
228
+ const snapshots = store.snapshots.filter((snapshot) => snapshot.repoId === repo.id);
229
+ const runs = snapshots.length;
230
+ const avgScore = runs === 0
231
+ ? 0
232
+ : Math.round(snapshots.reduce((sum, snapshot) => sum + snapshot.totalScore, 0) / runs);
233
+ return {
234
+ workspaceId: repo.workspaceId,
235
+ name: repo.name,
236
+ runs,
237
+ avgScore,
238
+ };
239
+ })
240
+ .sort((a, b) => b.avgScore - a.avgScore)
241
+ .slice(0, 15);
242
+ const runsRows = Object.entries(summary.runsPerMonth)
243
+ .sort(([a], [b]) => a.localeCompare(b))
244
+ .map(([month, count]) => {
245
+ const width = Math.max(8, count * 8);
246
+ return `<tr><td>${escapeHtml(month)}</td><td>${count}</td><td><div class="bar" style="width:${width}px"></div></td></tr>`;
247
+ })
248
+ .join('');
249
+ const workspaceRows = workspaceStats
250
+ .map((workspace) => `<tr><td>${escapeHtml(workspace.id)}</td><td>${workspace.runs}</td><td>${workspace.avgScore}</td><td>${escapeHtml(workspace.lastRun)}</td></tr>`)
251
+ .join('');
252
+ const repoRows = repoStats
253
+ .map((repo) => `<tr><td>${escapeHtml(repo.workspaceId)}</td><td>${escapeHtml(repo.name)}</td><td>${repo.runs}</td><td>${repo.avgScore}</td></tr>`)
254
+ .join('');
255
+ return `<!doctype html>
256
+ <html lang="en">
257
+ <head>
258
+ <meta charset="utf-8" />
259
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
260
+ <title>drift cloud dashboard</title>
261
+ <style>
262
+ :root { color-scheme: light; }
263
+ body { margin: 0; font-family: "Segoe UI", Arial, sans-serif; background: #f4f7fb; color: #0f172a; }
264
+ main { max-width: 980px; margin: 0 auto; padding: 24px; }
265
+ h1 { margin: 0 0 6px; }
266
+ p.meta { margin: 0 0 20px; color: #475569; }
267
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 18px; }
268
+ .card { background: #ffffff; border-radius: 10px; padding: 14px; border: 1px solid #dbe3ef; }
269
+ .card .label { font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.08em; }
270
+ .card .value { font-size: 26px; font-weight: 700; margin-top: 4px; }
271
+ table { width: 100%; border-collapse: collapse; margin-top: 10px; background: #ffffff; border: 1px solid #dbe3ef; border-radius: 10px; overflow: hidden; }
272
+ th, td { padding: 10px; border-bottom: 1px solid #e2e8f0; text-align: left; font-size: 14px; }
273
+ th { background: #eef2f9; }
274
+ .section { margin-top: 18px; }
275
+ .bar { height: 10px; background: linear-gradient(90deg, #0ea5e9, #22c55e); border-radius: 999px; }
276
+ .pill { display: inline-block; border-radius: 999px; padding: 4px 10px; font-size: 12px; font-weight: 600; }
277
+ .pill.free { background: #dcfce7; color: #166534; }
278
+ .pill.paid { background: #fee2e2; color: #991b1b; }
279
+ </style>
280
+ </head>
281
+ <body>
282
+ <main>
283
+ <h1>drift cloud dashboard</h1>
284
+ <p class="meta">Store: ${escapeHtml(storeFile)}</p>
285
+ <div class="cards">
286
+ <div class="card"><div class="label">Plan Phase</div><div class="value"><span class="pill ${summary.phase}">${summary.phase.toUpperCase()}</span></div></div>
287
+ <div class="card"><div class="label">Users</div><div class="value">${summary.usersRegistered}</div></div>
288
+ <div class="card"><div class="label">Active Workspaces</div><div class="value">${summary.workspacesActive}</div></div>
289
+ <div class="card"><div class="label">Active Repos</div><div class="value">${summary.reposActive}</div></div>
290
+ <div class="card"><div class="label">Snapshots</div><div class="value">${summary.totalSnapshots}</div></div>
291
+ <div class="card"><div class="label">Free Seats Left</div><div class="value">${summary.freeUsersRemaining}</div></div>
292
+ </div>
293
+
294
+ <section class="section">
295
+ <h2>Runs Per Month</h2>
296
+ <table>
297
+ <thead><tr><th>Month</th><th>Runs</th><th>Trend</th></tr></thead>
298
+ <tbody>${runsRows || '<tr><td colspan="3">No runs yet</td></tr>'}</tbody>
299
+ </table>
300
+ </section>
301
+
302
+ <section class="section">
303
+ <h2>Workspace Hotspots</h2>
304
+ <table>
305
+ <thead><tr><th>Workspace</th><th>Runs</th><th>Avg Score</th><th>Last Run</th></tr></thead>
306
+ <tbody>${workspaceRows || '<tr><td colspan="4">No workspace data</td></tr>'}</tbody>
307
+ </table>
308
+ </section>
309
+
310
+ <section class="section">
311
+ <h2>Repo Hotspots</h2>
312
+ <table>
313
+ <thead><tr><th>Workspace</th><th>Repo</th><th>Runs</th><th>Avg Score</th></tr></thead>
314
+ <tbody>${repoRows || '<tr><td colspan="4">No repo data</td></tr>'}</tbody>
315
+ </table>
316
+ </section>
317
+ </main>
318
+ </body>
319
+ </html>`;
320
+ }
321
+ //# sourceMappingURL=saas.js.map
package/dist/types.d.ts CHANGED
@@ -121,6 +121,12 @@ export interface DriftConfig {
121
121
  serviceNoHttp?: boolean;
122
122
  maxFunctionLines?: number;
123
123
  };
124
+ saas?: {
125
+ freeUserThreshold?: number;
126
+ maxRunsPerWorkspacePerMonth?: number;
127
+ maxReposPerWorkspace?: number;
128
+ retentionDays?: number;
129
+ };
124
130
  }
125
131
  export interface PluginRuleContext {
126
132
  projectRoot: string;