@doccov/api 0.4.0 → 0.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @doccov/api
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - feat: add spec routes with caching/diff, auth system, cleanup unused pages
8
+
9
+ ## 0.5.0
10
+
11
+ ### Minor Changes
12
+
13
+ - Enhanced quality rules, filtering, github context, analysis reports, new API routes (ai, billing, demo, github-app, invites, orgs), trends command, diff capabilities
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies
18
+ - @doccov/sdk@0.18.0
19
+ - @openpkg-ts/spec@0.10.0
20
+ - @doccov/db@0.1.0
21
+
3
22
  ## 0.4.0
4
23
 
5
24
  ### Minor Changes
package/api/index.ts CHANGED
@@ -12,9 +12,10 @@ import type {
12
12
  BuildPlanStep,
13
13
  BuildPlanStepResult,
14
14
  BuildPlanTarget,
15
+ EnrichedOpenPkg,
15
16
  GitHubProjectContext,
16
17
  } from '@doccov/sdk';
17
- import { fetchGitHubContext, parseScanGitHubUrl } from '@doccov/sdk';
18
+ import { enrichSpec, fetchGitHubContext, parseScanGitHubUrl } from '@doccov/sdk';
18
19
  import type { OpenPkg } from '@openpkg-ts/spec';
19
20
  import type { VercelRequest, VercelResponse } from '@vercel/node';
20
21
  import { Sandbox } from '@vercel/sandbox';
@@ -163,6 +164,9 @@ const LOCAL_BINARIES = new Set([
163
164
  'publint',
164
165
  'attw',
165
166
  'are-the-types-wrong',
167
+ // Monorepo tools
168
+ 'lerna',
169
+ 'nx',
166
170
  ]);
167
171
 
168
172
  /**
@@ -213,28 +217,53 @@ interface SpecSummary {
213
217
  types: number;
214
218
  documented: number;
215
219
  undocumented: number;
220
+ driftCount: number;
221
+ topUndocumented: string[];
222
+ topDrift: Array<{ name: string; issue: string }>;
216
223
  }
217
224
 
218
225
  function createSpecSummary(spec: OpenPkg): SpecSummary {
219
- const exports = spec.exports?.length ?? 0;
220
- const types = spec.types?.length ?? 0;
226
+ // Enrich spec to get coverage and drift data
227
+ const enriched = enrichSpec(spec) as EnrichedOpenPkg;
221
228
 
222
- // Count documented vs undocumented exports
223
- const documented =
224
- spec.exports?.filter((e) => e.description && e.description.trim().length > 0).length ?? 0;
225
- const undocumented = exports - documented;
229
+ const totalExports = enriched.exports?.length ?? 0;
230
+ const types = enriched.types?.length ?? 0;
226
231
 
227
- // Calculate coverage (documented / total * 100)
228
- const coverage = exports > 0 ? Math.round((documented / exports) * 100) : 0;
232
+ // Use SDK coverage data
233
+ const coverageScore = enriched.docs?.coverageScore ?? 0;
234
+ const documented = enriched.docs?.documented ?? 0;
235
+ const undocumented = totalExports - documented;
236
+
237
+ // Collect drift issues from enriched exports
238
+ const driftItems: Array<{ name: string; issue: string }> = [];
239
+ const undocumentedNames: string[] = [];
240
+
241
+ for (const exp of enriched.exports ?? []) {
242
+ // Collect undocumented exports (no description)
243
+ if (!exp.description || exp.description.trim().length === 0) {
244
+ undocumentedNames.push(exp.name);
245
+ }
246
+
247
+ // Collect drift issues
248
+ for (const drift of exp.docs?.drift ?? []) {
249
+ driftItems.push({
250
+ name: exp.name,
251
+ issue: drift.issue ?? 'Documentation drift detected',
252
+ });
253
+ }
254
+ }
229
255
 
230
256
  return {
231
- name: spec.meta?.name ?? 'unknown',
232
- version: spec.meta?.version ?? '0.0.0',
233
- coverage,
234
- exports,
257
+ name: enriched.meta?.name ?? 'unknown',
258
+ version: enriched.meta?.version ?? '0.0.0',
259
+ coverage: coverageScore,
260
+ exports: totalExports,
235
261
  types,
236
262
  documented,
237
263
  undocumented,
264
+ driftCount: driftItems.length,
265
+ topUndocumented: undocumentedNames.slice(0, 5),
266
+ topDrift: driftItems.slice(0, 5),
238
267
  };
239
268
  }
240
269
 
@@ -345,6 +374,27 @@ Install Commands by Package Manager:
345
374
  - bun with lockfile: ["bun", "install", "--frozen-lockfile"]
346
375
  - bun without lockfile: ["bun", "install"]
347
376
 
377
+ Monorepo Build Strategy (CRITICAL):
378
+ When a target package is specified in a monorepo, ONLY build that package and its dependencies:
379
+
380
+ - Lerna monorepos: Use "lerna run build --scope=<package-name> --include-dependencies"
381
+ Example for @stacks/transactions: ["lerna", "run", "build", "--scope=@stacks/transactions", "--include-dependencies"]
382
+
383
+ - Turbo monorepos: Use "turbo run build --filter=<package-name>"
384
+ Example: ["turbo", "run", "build", "--filter=@stacks/transactions"]
385
+
386
+ - Nx monorepos: Use "nx run <project>:build"
387
+ Example: ["nx", "run", "transactions:build"]
388
+
389
+ - pnpm workspaces: Use "pnpm --filter <package-name> run build"
390
+ Example: ["pnpm", "--filter", "@stacks/transactions", "run", "build"]
391
+
392
+ - yarn workspaces: Use "yarn workspace <package-name> run build"
393
+ Example: ["yarn", "workspace", "@stacks/transactions", "run", "build"]
394
+
395
+ NEVER run a full monorepo build (npm run build at root) when a target package is specified.
396
+ This avoids building 20+ packages when we only need one.
397
+
348
398
  General Guidelines:
349
399
  - For TypeScript projects, look for "types" or "exports" fields in package.json
350
400
  - For monorepos, focus on the target package if specified
@@ -386,11 +436,22 @@ function transformToBuildPlan(
386
436
  context: GitHubProjectContext,
387
437
  options: GenerateBuildPlanOptions,
388
438
  ): BuildPlan {
439
+ // Derive package directory from entry points (e.g., "packages/transactions/src/index.ts" -> "packages/transactions")
440
+ let rootPath: string | undefined;
441
+ if (options.targetPackage && output.entryPoints.length > 0) {
442
+ const firstEntry = output.entryPoints[0];
443
+ // Match patterns like "packages/foo/src/..." or "packages/foo/dist/..."
444
+ const match = firstEntry.match(/^(packages\/[^/]+)\//);
445
+ if (match) {
446
+ rootPath = match[1];
447
+ }
448
+ }
449
+
389
450
  const target: BuildPlanTarget = {
390
451
  type: 'github',
391
452
  repoUrl: `https://github.com/${context.metadata.owner}/${context.metadata.repo}`,
392
453
  ref: context.ref,
393
- rootPath: options.targetPackage,
454
+ rootPath,
394
455
  entryPoints: output.entryPoints,
395
456
  };
396
457
 
@@ -745,13 +806,22 @@ async function handleExecute(req: VercelRequest, res: VercelResponse): Promise<v
745
806
  const specFilePath = plan.target.rootPath
746
807
  ? `${plan.target.rootPath}/openpkg.json`
747
808
  : 'openpkg.json';
748
- const specStream = await sandbox.readFile({ path: specFilePath });
749
- const chunks: Buffer[] = [];
750
- for await (const chunk of specStream as AsyncIterable<Buffer>) {
751
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
809
+
810
+ let spec: OpenPkg;
811
+ try {
812
+ const specStream = await sandbox.readFile({ path: specFilePath });
813
+ const chunks: Buffer[] = [];
814
+ for await (const chunk of specStream as AsyncIterable<Buffer>) {
815
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
816
+ }
817
+ const specContent = Buffer.concat(chunks).toString('utf-8');
818
+ spec = JSON.parse(specContent) as OpenPkg;
819
+ } catch (readError) {
820
+ console.error(`Failed to read ${specFilePath}:`, readError);
821
+ throw new Error(
822
+ `Failed to read spec file (${specFilePath}): ${readError instanceof Error ? readError.message : 'Unknown error'}`,
823
+ );
752
824
  }
753
- const specContent = Buffer.concat(chunks).toString('utf-8');
754
- const spec = JSON.parse(specContent) as OpenPkg;
755
825
  const summary = createSpecSummary(spec);
756
826
 
757
827
  const result = {
@@ -931,13 +1001,22 @@ async function handleExecuteStream(req: VercelRequest, res: VercelResponse): Pro
931
1001
  const specFilePath = plan.target.rootPath
932
1002
  ? `${plan.target.rootPath}/openpkg.json`
933
1003
  : 'openpkg.json';
934
- const specStream = await sandbox.readFile({ path: specFilePath });
935
- const chunks: Buffer[] = [];
936
- for await (const chunk of specStream as AsyncIterable<Buffer>) {
937
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1004
+
1005
+ let spec: OpenPkg;
1006
+ try {
1007
+ const specStream = await sandbox.readFile({ path: specFilePath });
1008
+ const chunks: Buffer[] = [];
1009
+ for await (const chunk of specStream as AsyncIterable<Buffer>) {
1010
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1011
+ }
1012
+ const specContent = Buffer.concat(chunks).toString('utf-8');
1013
+ spec = JSON.parse(specContent) as OpenPkg;
1014
+ } catch (readError) {
1015
+ console.error(`Failed to read ${specFilePath}:`, readError);
1016
+ throw new Error(
1017
+ `Failed to read spec file (${specFilePath}): ${readError instanceof Error ? readError.message : 'Unknown error'}`,
1018
+ );
938
1019
  }
939
- const specContent = Buffer.concat(chunks).toString('utf-8');
940
- const spec = JSON.parse(specContent) as OpenPkg;
941
1020
  const summary = createSpecSummary(spec);
942
1021
 
943
1022
  const result = {
@@ -0,0 +1,41 @@
1
+ import type { Kysely } from 'kysely';
2
+
3
+ /**
4
+ * Create coverage_snapshots table with SDK-aligned field names.
5
+ */
6
+ export async function up(db: Kysely<unknown>): Promise<void> {
7
+ await db.schema
8
+ .createTable('coverage_snapshots')
9
+ .addColumn('id', 'text', (col) => col.primaryKey())
10
+ .addColumn('project_id', 'text', (col) =>
11
+ col.notNull().references('projects.id').onDelete('cascade'),
12
+ )
13
+ .addColumn('version', 'text')
14
+ .addColumn('branch', 'text')
15
+ .addColumn('commit_sha', 'text')
16
+ // SDK-aligned field names
17
+ .addColumn('coverage_score', 'integer', (col) => col.notNull())
18
+ .addColumn('documented_exports', 'integer', (col) => col.notNull())
19
+ .addColumn('total_exports', 'integer', (col) => col.notNull())
20
+ .addColumn('drift_count', 'integer', (col) => col.notNull().defaultTo(0))
21
+ .addColumn('source', 'text', (col) => col.notNull().defaultTo('manual'))
22
+ .addColumn('created_at', 'timestamptz', (col) => col.defaultTo(db.fn('now')))
23
+ .execute();
24
+
25
+ // Index for efficient project history queries
26
+ await db.schema
27
+ .createIndex('idx_coverage_snapshots_project_id')
28
+ .on('coverage_snapshots')
29
+ .column('project_id')
30
+ .execute();
31
+
32
+ await db.schema
33
+ .createIndex('idx_coverage_snapshots_created_at')
34
+ .on('coverage_snapshots')
35
+ .column('created_at')
36
+ .execute();
37
+ }
38
+
39
+ export async function down(db: Kysely<unknown>): Promise<void> {
40
+ await db.schema.dropTable('coverage_snapshots').execute();
41
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doccov/api",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "DocCov API - Badge endpoint and coverage services",
5
5
  "keywords": [
6
6
  "doccov",
@@ -29,10 +29,9 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@ai-sdk/anthropic": "^2.0.55",
32
- "@doccov/db": "workspace:*",
33
- "@doccov/sdk": "^0.15.0",
32
+ "@doccov/sdk": "^0.18.0",
34
33
  "@hono/node-server": "^1.14.3",
35
- "@openpkg-ts/spec": "^0.9.0",
34
+ "@openpkg-ts/spec": "^0.10.0",
36
35
  "@polar-sh/hono": "^0.5.3",
37
36
  "@vercel/sandbox": "^1.0.3",
38
37
  "ai": "^5.0.111",
@@ -42,6 +41,7 @@
42
41
  "ms": "^2.1.3",
43
42
  "nanoid": "^5.0.0",
44
43
  "pg": "^8.13.0",
44
+ "vercel": "^50.1.3",
45
45
  "zod": "^3.25.0"
46
46
  },
47
47
  "devDependencies": {
package/src/index.ts CHANGED
@@ -1,16 +1,23 @@
1
1
  import { Hono } from 'hono';
2
2
  import { cors } from 'hono/cors';
3
3
  import { logger } from 'hono/logger';
4
+ import { anonymousRateLimit } from './middleware/anonymous-rate-limit';
4
5
  import { requireApiKey } from './middleware/api-key-auth';
5
6
  import { orgRateLimit } from './middleware/org-rate-limit';
6
7
  import { rateLimit } from './middleware/rate-limit';
8
+ import { aiRoute } from './routes/ai';
7
9
  import { apiKeysRoute } from './routes/api-keys';
8
10
  import { authRoute } from './routes/auth';
9
11
  import { badgeRoute } from './routes/badge';
10
12
  import { billingRoute } from './routes/billing';
11
13
  import { coverageRoute } from './routes/coverage';
14
+ import { demoRoute } from './routes/demo';
15
+ import { githubAppRoute } from './routes/github-app';
16
+ import { invitesRoute } from './routes/invites';
12
17
  import { orgsRoute } from './routes/orgs';
13
18
  import { planRoute } from './routes/plan';
19
+ import { specRoute } from './routes/spec';
20
+ import { specV1Route } from './routes/spec-v1';
14
21
 
15
22
  const app = new Hono();
16
23
 
@@ -45,9 +52,15 @@ app.get('/', (c) => {
45
52
  badge: '/badge/:owner/:repo',
46
53
  billing: '/billing/*',
47
54
  coverage: '/coverage/*',
55
+ github: '/github/* (App install, webhooks)',
56
+ invites: '/invites/:token',
48
57
  orgs: '/orgs/*',
49
58
  plan: '/plan',
50
- v1: '/v1/* (API key required)',
59
+ spec: '/spec/diff (POST, session auth)',
60
+ v1: {
61
+ ai: '/v1/ai/generate (POST), /v1/ai/quota (GET)',
62
+ spec: '/v1/spec/diff (POST, API key)',
63
+ },
51
64
  health: '/health',
52
65
  },
53
66
  });
@@ -58,8 +71,27 @@ app.get('/health', (c) => {
58
71
  });
59
72
 
60
73
  // Public endpoints (no auth)
74
+ // Anonymous rate limit: 10 requests per day per IP
75
+ app.use(
76
+ '/badge/*',
77
+ anonymousRateLimit({
78
+ windowMs: 24 * 60 * 60 * 1000, // 24 hours
79
+ max: 10,
80
+ message: 'Rate limit reached. Sign up free for 100/day.',
81
+ upgradeUrl: 'https://doccov.com/signup',
82
+ }),
83
+ );
61
84
  app.route('/badge', badgeRoute);
62
85
 
86
+ // Semi-public endpoints (invite info is public, acceptance requires auth)
87
+ app.route('/invites', invitesRoute);
88
+
89
+ // GitHub App (install/callback need auth, webhook is public)
90
+ app.route('/github', githubAppRoute);
91
+
92
+ // Demo endpoint (public, rate-limited)
93
+ app.route('/demo', demoRoute);
94
+
63
95
  // Dashboard endpoints (session auth)
64
96
  app.route('/auth', authRoute);
65
97
  app.route('/api-keys', apiKeysRoute);
@@ -67,10 +99,12 @@ app.route('/billing', billingRoute);
67
99
  app.route('/coverage', coverageRoute);
68
100
  app.route('/orgs', orgsRoute);
69
101
  app.route('/plan', planRoute);
102
+ app.route('/spec', specRoute);
70
103
 
71
104
  // API endpoints (API key required)
72
105
  app.use('/v1/*', requireApiKey(), orgRateLimit());
73
- // TODO: app.route('/v1/analyze', analyzeRoute);
106
+ app.route('/v1/ai', aiRoute);
107
+ app.route('/v1/spec', specV1Route);
74
108
 
75
109
  // Vercel serverless handler + Bun auto-serves this export
76
110
  export default app;
@@ -0,0 +1,131 @@
1
+ import type { Context, MiddlewareHandler, Next } from 'hono';
2
+
3
+ interface AnonymousRateLimitOptions {
4
+ /** Time window in milliseconds (default: 24 hours) */
5
+ windowMs: number;
6
+ /** Max requests per window */
7
+ max: number;
8
+ /** Message to return when rate limited */
9
+ message?: string;
10
+ /** URL for upgrade CTA */
11
+ upgradeUrl?: string;
12
+ }
13
+
14
+ interface RateLimitEntry {
15
+ count: number;
16
+ resetAt: number;
17
+ }
18
+
19
+ /**
20
+ * In-memory store for anonymous rate limiting
21
+ */
22
+ class AnonymousRateLimitStore {
23
+ private store = new Map<string, RateLimitEntry>();
24
+
25
+ get(key: string): RateLimitEntry | undefined {
26
+ const entry = this.store.get(key);
27
+ if (entry && Date.now() > entry.resetAt) {
28
+ this.store.delete(key);
29
+ return undefined;
30
+ }
31
+ return entry;
32
+ }
33
+
34
+ increment(key: string, windowMs: number): RateLimitEntry {
35
+ const now = Date.now();
36
+ const existing = this.get(key);
37
+
38
+ if (existing) {
39
+ existing.count++;
40
+ return existing;
41
+ }
42
+
43
+ const entry: RateLimitEntry = {
44
+ count: 1,
45
+ resetAt: now + windowMs,
46
+ };
47
+ this.store.set(key, entry);
48
+ return entry;
49
+ }
50
+
51
+ cleanup(): void {
52
+ const now = Date.now();
53
+ for (const [key, entry] of this.store.entries()) {
54
+ if (now > entry.resetAt) {
55
+ this.store.delete(key);
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ const store = new AnonymousRateLimitStore();
62
+
63
+ // Cleanup expired entries every minute
64
+ setInterval(() => store.cleanup(), 60 * 1000).unref();
65
+
66
+ /**
67
+ * Get client IP from request headers
68
+ */
69
+ function getClientIp(c: Context): string {
70
+ const forwarded = c.req.header('x-forwarded-for');
71
+ if (forwarded) {
72
+ return forwarded.split(',')[0].trim();
73
+ }
74
+
75
+ const realIp = c.req.header('x-real-ip');
76
+ if (realIp) {
77
+ return realIp;
78
+ }
79
+
80
+ const vercelIp = c.req.header('x-vercel-forwarded-for');
81
+ if (vercelIp) {
82
+ return vercelIp.split(',')[0].trim();
83
+ }
84
+
85
+ return 'unknown';
86
+ }
87
+
88
+ /**
89
+ * Anonymous IP-based rate limiting middleware
90
+ * Skips authenticated requests (with API key)
91
+ * Returns upgrade CTA when limit reached
92
+ */
93
+ export function anonymousRateLimit(options: AnonymousRateLimitOptions): MiddlewareHandler {
94
+ const {
95
+ windowMs,
96
+ max,
97
+ message = 'Rate limit reached. Sign up free for 100/day.',
98
+ upgradeUrl = 'https://doccov.com/signup',
99
+ } = options;
100
+
101
+ return async (c: Context, next: Next) => {
102
+ // Skip if authenticated (has API key)
103
+ if (c.get('apiKey')) {
104
+ return next();
105
+ }
106
+
107
+ const ip = getClientIp(c);
108
+ const key = `anon:${ip}`;
109
+
110
+ const entry = store.increment(key, windowMs);
111
+
112
+ // Set rate limit headers
113
+ c.header('X-RateLimit-Limit', String(max));
114
+ c.header('X-RateLimit-Remaining', String(Math.max(0, max - entry.count)));
115
+ c.header('X-RateLimit-Reset', String(Math.ceil(entry.resetAt / 1000)));
116
+
117
+ if (entry.count > max) {
118
+ return c.json(
119
+ {
120
+ error: message,
121
+ limit: max,
122
+ resetAt: new Date(entry.resetAt).toISOString(),
123
+ upgrade: upgradeUrl,
124
+ },
125
+ 429,
126
+ );
127
+ }
128
+
129
+ await next();
130
+ };
131
+ }