@profullstack/gov-contracts 0.0.0-stage → 0.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/LICENSE +9 -0
- package/README.md +78 -2
- package/bin/gov-contracts.js +225 -0
- package/package.json +50 -4
- package/src/ai.js +46 -0
- package/src/app.js +337 -0
- package/src/auth.js +109 -0
- package/src/fit.js +127 -0
- package/src/http.js +86 -0
- package/src/index.js +12 -0
- package/src/mcp.js +159 -0
- package/src/niche.js +196 -0
- package/src/pages.js +380 -0
- package/src/pipeline.js +141 -0
- package/src/profile.js +308 -0
- package/src/propose.js +260 -0
- package/src/safety.js +48 -0
- package/src/server.js +17 -0
- package/src/service.js +27 -0
- package/src/sources/digest.js +119 -0
- package/src/sources/index.js +59 -0
- package/src/sources/lacounty.js +100 -0
- package/src/sources/sam.js +178 -0
- package/src/spider.js +218 -0
- package/src/store.js +390 -0
- package/src/version.js +3 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bid digests forwarded by email (MyGovWatch weekly digests and the like).
|
|
3
|
+
* Optional source: an operator POSTs the plain-text body (or the CLI reads a
|
|
4
|
+
* file / stdin) and every listed solicitation is queued. Tracking links in the
|
|
5
|
+
* digest are never stored or opened; the buyer's own page is found by a person.
|
|
6
|
+
*
|
|
7
|
+
* MyGovWatch's layout is parsed deterministically. Any other digest goes to a
|
|
8
|
+
* model with a fixed JSON shape (when one is configured).
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { prefilter } from '../fit.js';
|
|
13
|
+
|
|
14
|
+
export const ID = 'email.digest';
|
|
15
|
+
|
|
16
|
+
const clean = (s) => String(s || '').replace(/\s+/g, ' ').replace(/^[*\s]+|[*\s]+$/g, '').trim();
|
|
17
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 20);
|
|
18
|
+
|
|
19
|
+
/** "12/09/2026" -> "2026-12-09" */
|
|
20
|
+
const usDate = (v) => {
|
|
21
|
+
const m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(String(v || ''));
|
|
22
|
+
return m ? `${m[3]}-${m[1].padStart(2, '0')}-${m[2].padStart(2, '0')}` : null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Federal / state / county / city from a buyer line like "Yolo County, CA" or "State of California". */
|
|
26
|
+
export function levelOf(buyer) {
|
|
27
|
+
const b = String(buyer).toLowerCase();
|
|
28
|
+
if (/\b(state of|department of|california state|caltrans|calpers)\b/.test(b) || /^state\b/.test(b)) return 'state';
|
|
29
|
+
if (/\bcounty\b/.test(b)) return 'county';
|
|
30
|
+
if (/\b(federal|u\.s\.|united states|dept of|army|navy|air force)\b/.test(b)) return 'federal';
|
|
31
|
+
return 'city';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const regionOf = (buyer) => (/\b(CA|California)\b/.test(buyer) ? 'CA' : null);
|
|
35
|
+
|
|
36
|
+
function solicitation(buyer, title, due, extra = {}) {
|
|
37
|
+
const t = clean(title).replace(/^\W+/, '');
|
|
38
|
+
const b = clean(buyer);
|
|
39
|
+
const s = {
|
|
40
|
+
source: 'digest',
|
|
41
|
+
ext_id: hash(`${b.toLowerCase()}|${t.toLowerCase()}`),
|
|
42
|
+
number: /\b(RF[PQIB]|IFB|ITB)[\s-]*[A-Z0-9][\w.-]*\d[\w.-]*/i.exec(t)?.[0] || null,
|
|
43
|
+
title: t,
|
|
44
|
+
agency: b,
|
|
45
|
+
level: levelOf(b),
|
|
46
|
+
region: regionOf(b),
|
|
47
|
+
url: null,
|
|
48
|
+
notice_type: /\bRFI\b/i.test(t) ? 'Request for Information' : /\bRFQ\b/i.test(t) ? 'Request for Quote' : /\bRFP\b/i.test(t) ? 'Request for Proposal' : null,
|
|
49
|
+
posted_at: null,
|
|
50
|
+
due_at: due,
|
|
51
|
+
description: `Listed in a forwarded bid digest${extra.from ? ` (${extra.from})` : ''}. Find the solicitation on the buyer's own procurement page.`,
|
|
52
|
+
...extra.fields,
|
|
53
|
+
};
|
|
54
|
+
s.prefilter = prefilter(s);
|
|
55
|
+
return s;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* MyGovWatch: a buyer line wrapped in asterisks ("* Los Angeles County, CA *"),
|
|
60
|
+
* the title on the following line(s), then "* Due Date: *12/09/2026".
|
|
61
|
+
*/
|
|
62
|
+
export function parseMyGovWatch(text) {
|
|
63
|
+
const lines = String(text).replace(/\r/g, '').split('\n').map((l) => l.trim());
|
|
64
|
+
const out = [];
|
|
65
|
+
for (let i = 0; i < lines.length; i++) {
|
|
66
|
+
const buyer = /^\*\s*([^*]+?)\s*\*$/.exec(lines[i]);
|
|
67
|
+
if (!buyer || /due date|notified/i.test(buyer[1])) continue;
|
|
68
|
+
const titleLines = [];
|
|
69
|
+
let due = null;
|
|
70
|
+
let j = i + 1;
|
|
71
|
+
for (; j < lines.length && j < i + 12; j++) {
|
|
72
|
+
const l = lines[j];
|
|
73
|
+
if (!l) { if (titleLines.length) continue; else continue; }
|
|
74
|
+
const d = /due date:\s*\*?\s*(\d{1,2}\/\d{1,2}\/\d{4})/i.exec(l);
|
|
75
|
+
if (d) { due = usDate(d[1]); break; }
|
|
76
|
+
if (/^\*\s*[^*]+\*$/.test(l) || /^\[image|^<https?:|^https?:/i.test(l)) break;
|
|
77
|
+
titleLines.push(l);
|
|
78
|
+
}
|
|
79
|
+
if (titleLines.length && due) {
|
|
80
|
+
out.push(solicitation(buyer[1], titleLines.join(' '), due, { from: 'MyGovWatch' }));
|
|
81
|
+
i = j;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DigestSchema = z.object({
|
|
88
|
+
solicitations: z.array(z.object({ buyer: z.string(), title: z.string(), due_date: z.string().nullable().default(null), number: z.string().nullable().default(null) })),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/** Parse a forwarded digest. Deterministic first; a model only for unknown layouts. */
|
|
92
|
+
export async function parseDigest(text, { ai } = {}) {
|
|
93
|
+
const body = String(text || '').replace(/https?:\/\/\S+/g, ''); // never keep tracking links
|
|
94
|
+
const mgw = parseMyGovWatch(body);
|
|
95
|
+
if (mgw.length) return { parser: 'mygovwatch', solicitations: mgw };
|
|
96
|
+
if (!ai) return { parser: 'none', solicitations: [] };
|
|
97
|
+
const r = await ai.generateObject({
|
|
98
|
+
system: 'Extract every government solicitation (RFP, RFQ, RFI, bid) listed in this email. Buyer = the agency. due_date as YYYY-MM-DD or null. JSON only.',
|
|
99
|
+
user: body.slice(0, 12000),
|
|
100
|
+
schema: DigestSchema,
|
|
101
|
+
jsonSchema: z.toJSONSchema(DigestSchema),
|
|
102
|
+
name: 'digest',
|
|
103
|
+
feature: 'gov-contracts:digest',
|
|
104
|
+
maxTokens: 2500,
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
parser: 'ai',
|
|
108
|
+
solicitations: r.object.solicitations
|
|
109
|
+
.filter((x) => x.title && x.buyer)
|
|
110
|
+
.map((x) => solicitation(x.buyer, x.title, /^\d{4}-\d{2}-\d{2}$/.test(x.due_date || '') ? x.due_date : usDate(x.due_date), { fields: x.number ? { number: x.number } : {} })),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function readDocs(sol) {
|
|
115
|
+
return {
|
|
116
|
+
docs: [{ kind: 'notice', name: 'Digest listing', text: `${sol.title}\nBuyer: ${sol.agency}\nDue: ${sol.due_at}\n${sol.description || ''}` }],
|
|
117
|
+
fields: {},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sources. WHERE to look is Datamart's contracts registry (the Profullstack
|
|
3
|
+
* connector's `contracts_sources` tool, served at mcp.profullstack.com/contracts);
|
|
4
|
+
* this package adds HOW to read the ones that have a public feed. A registry
|
|
5
|
+
* entry without an adapter stays a link for a person.
|
|
6
|
+
*/
|
|
7
|
+
import { http } from '../http.js';
|
|
8
|
+
import * as digest from './digest.js';
|
|
9
|
+
import * as lacounty from './lacounty.js';
|
|
10
|
+
import * as sam from './sam.js';
|
|
11
|
+
|
|
12
|
+
export const REGISTRY_URL = process.env.CONTRACTS_REGISTRY_URL || 'https://mcp.profullstack.com/contracts';
|
|
13
|
+
|
|
14
|
+
/** Adapters by short source name. `provider` is the Datamart provider id. */
|
|
15
|
+
export const ADAPTERS = {
|
|
16
|
+
sam: { provider: sam.ID, level: 'federal', name: 'SAM.gov contract opportunities', every: '6h', ingest: sam.ingest, readDocs: sam.readDocs, scheduled: true },
|
|
17
|
+
lacounty: { provider: lacounty.ID, level: 'county', name: 'County of Los Angeles open solicitations (LACoBids)', every: '6h', ingest: lacounty.ingest, readDocs: lacounty.readDocs, scheduled: true, officialUrl: lacounty.LIST_URL },
|
|
18
|
+
digest: { provider: digest.ID, level: 'any', name: 'Forwarded bid digests (email)', ingest: null, readDocs: digest.readDocs, scheduled: false },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const adapterFor = (source) => ADAPTERS[source] || null;
|
|
22
|
+
|
|
23
|
+
let cache = { at: 0, providers: null };
|
|
24
|
+
|
|
25
|
+
/** Datamart's registry, cached for an hour; the last good copy on error. */
|
|
26
|
+
export async function registry({ fetcher = http() } = {}) {
|
|
27
|
+
if (process.env.GOV_OFFLINE === '1') return cache.providers || [];
|
|
28
|
+
if (cache.providers && Date.now() - cache.at < 3600_000) return cache.providers;
|
|
29
|
+
try {
|
|
30
|
+
const doc = await fetcher.json(REGISTRY_URL);
|
|
31
|
+
cache = { at: Date.now(), providers: Array.isArray(doc?.providers) ? doc.providers : [] };
|
|
32
|
+
} catch {
|
|
33
|
+
cache.at = Date.now() - 3000_000; // retry in ~10 min
|
|
34
|
+
}
|
|
35
|
+
return cache.providers || [];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Registry entries joined with what gov-contracts can read today. */
|
|
39
|
+
export async function listSources(opts) {
|
|
40
|
+
const providers = await registry(opts);
|
|
41
|
+
const byProvider = Object.fromEntries(Object.entries(ADAPTERS).map(([key, a]) => [a.provider, { ...a, key }]));
|
|
42
|
+
const rows = providers.map((p) => ({
|
|
43
|
+
id: p.id,
|
|
44
|
+
name: p.name,
|
|
45
|
+
organization: p.organization,
|
|
46
|
+
level: p.jurisdiction?.level ?? null,
|
|
47
|
+
official_url: p.official_url ?? null,
|
|
48
|
+
datamart_state: p.headline_state ?? null,
|
|
49
|
+
gov_contracts: byProvider[p.id] ? { source: byProvider[p.id].key, ingest: byProvider[p.id].scheduled ? `every ${byProvider[p.id].every}` : 'on demand' } : null,
|
|
50
|
+
}));
|
|
51
|
+
for (const [name, a] of Object.entries(ADAPTERS)) {
|
|
52
|
+
if (!rows.some((r) => r.id === a.provider)) {
|
|
53
|
+
rows.push({ id: a.provider, name: a.name, organization: null, level: a.level, official_url: a.officialUrl ?? null, datamart_state: null, gov_contracts: { source: name, ingest: a.scheduled ? `every ${a.every}` : 'on demand' } });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return rows;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export { digest, lacounty, sam };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* County of Los Angeles open solicitations (LACoBids). The county publishes a
|
|
3
|
+
* CSV of every open solicitation, linked from its public bid list; one GET per
|
|
4
|
+
* run, every six hours. Bid documents sit behind the county's bid detail page
|
|
5
|
+
* (a session form), so they stay a link for a person to open.
|
|
6
|
+
*/
|
|
7
|
+
import { http } from '../http.js';
|
|
8
|
+
import { prefilter } from '../fit.js';
|
|
9
|
+
|
|
10
|
+
export const ID = 'us.ca.lacounty.bids';
|
|
11
|
+
export const CSV_URL = 'https://camisvr.co.la.ca.us/LACoBids/Download/Rpt_Listing/OpenBidList.csv';
|
|
12
|
+
export const LIST_URL = 'https://camisvr.co.la.ca.us/LACoBids/BidLookUp/OpenBidList';
|
|
13
|
+
|
|
14
|
+
/** RFC 4180 CSV (quoted fields, doubled quotes, newlines inside quotes). */
|
|
15
|
+
export function parseCsv(text) {
|
|
16
|
+
const rows = [];
|
|
17
|
+
let row = [];
|
|
18
|
+
let field = '';
|
|
19
|
+
let quoted = false;
|
|
20
|
+
const s = String(text).replace(/^/, '');
|
|
21
|
+
for (let i = 0; i < s.length; i++) {
|
|
22
|
+
const ch = s[i];
|
|
23
|
+
if (quoted) {
|
|
24
|
+
if (ch === '"') {
|
|
25
|
+
if (s[i + 1] === '"') { field += '"'; i++; } else quoted = false;
|
|
26
|
+
} else field += ch;
|
|
27
|
+
} else if (ch === '"') quoted = true;
|
|
28
|
+
else if (ch === ',') { row.push(field); field = ''; }
|
|
29
|
+
else if (ch === '\n' || ch === '\r') {
|
|
30
|
+
if (ch === '\r' && s[i + 1] === '\n') i++;
|
|
31
|
+
row.push(field); field = '';
|
|
32
|
+
if (row.some((c) => c !== '')) rows.push(row);
|
|
33
|
+
row = [];
|
|
34
|
+
} else field += ch;
|
|
35
|
+
}
|
|
36
|
+
if (field !== '' || row.length) { row.push(field); if (row.some((c) => c !== '')) rows.push(row); }
|
|
37
|
+
return rows;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** "12/09/2026 12:00PM" -> "2026-12-09". */
|
|
41
|
+
export function usDate(v) {
|
|
42
|
+
const m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(String(v || ''));
|
|
43
|
+
return m ? `${m[3]}-${m[1].padStart(2, '0')}-${m[2].padStart(2, '0')}` : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function fromCsv(text) {
|
|
47
|
+
const rows = parseCsv(text);
|
|
48
|
+
const head = rows.shift() || [];
|
|
49
|
+
const col = (name) => head.findIndex((h) => h.trim().toLowerCase() === name);
|
|
50
|
+
const c = {
|
|
51
|
+
url: col('bid url'), number: col('bid number'), title: col('bid title'), type: col('bid type'), dept: col('department'),
|
|
52
|
+
desc: col('bid description'), comm: col('commodity description'), open: col('open date'), close: col('closing date'),
|
|
53
|
+
cname: col('contact name'), cphone: col('contact phone'), cemail: col('contact email'),
|
|
54
|
+
};
|
|
55
|
+
if (c.number < 0 || c.title < 0) throw new Error('LA County CSV columns changed');
|
|
56
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const r of rows) {
|
|
59
|
+
const get = (k) => (c[k] >= 0 ? String(r[c[k]] ?? '').trim() : '');
|
|
60
|
+
const url = get('url');
|
|
61
|
+
const ext = /biddocidi=(\d+)/i.exec(url)?.[1] || get('number');
|
|
62
|
+
const due = usDate(get('close'));
|
|
63
|
+
if (!ext || !get('title') || (due && due < today)) continue;
|
|
64
|
+
const commodity = get('comm');
|
|
65
|
+
const s = {
|
|
66
|
+
source: 'lacounty',
|
|
67
|
+
ext_id: ext,
|
|
68
|
+
number: get('number') || null,
|
|
69
|
+
title: get('title'),
|
|
70
|
+
agency: `County of Los Angeles${get('dept') ? ' / ' + get('dept') : ''}`,
|
|
71
|
+
level: 'county',
|
|
72
|
+
region: 'CA',
|
|
73
|
+
url: url || LIST_URL,
|
|
74
|
+
notice_type: get('type') || null,
|
|
75
|
+
posted_at: usDate(get('open')),
|
|
76
|
+
due_at: due,
|
|
77
|
+
description: [get('desc'), commodity && `Commodity: ${commodity}`, get('close') && `Closes: ${get('close')} (Pacific)`].filter(Boolean).join('\n'),
|
|
78
|
+
contacts: get('cname') || get('cemail') ? [{ name: get('cname'), email: get('cemail'), phone: get('cphone'), role: 'buyer' }] : [],
|
|
79
|
+
};
|
|
80
|
+
s.prefilter = prefilter(s);
|
|
81
|
+
out.push(s);
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function ingest({ fetcher = http() } = {}) {
|
|
87
|
+
const r = await fetcher.text(CSV_URL);
|
|
88
|
+
return fromCsv(r.text);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The CSV already carries the description and contact; the documents need a person on the county site. */
|
|
92
|
+
export async function readDocs(sol) {
|
|
93
|
+
return {
|
|
94
|
+
docs: [
|
|
95
|
+
{ kind: 'notice', name: 'County listing', url: sol.url, text: sol.description || '' },
|
|
96
|
+
{ kind: 'link', name: 'Bid documents (LACoBids bid page: attachments open there)', url: sol.url },
|
|
97
|
+
],
|
|
98
|
+
fields: {},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SAM.gov contract opportunities (federal). Datamart provider us.sam.opportunities.
|
|
3
|
+
*
|
|
4
|
+
* With SAM_API_KEY (a free key from a SAM.gov account) the official Get
|
|
5
|
+
* Opportunities v2 API is used. Without one, the public, unauthenticated
|
|
6
|
+
* search that sam.gov's own pages read (robots.txt does not disallow /api/),
|
|
7
|
+
* at a few queries every six hours, one request at a time with a delay.
|
|
8
|
+
* Read only: SAM.gov has no submission API and we would not use one.
|
|
9
|
+
*/
|
|
10
|
+
import { htmlToText, fetchBytes, http, pdfText } from '../http.js';
|
|
11
|
+
import { prefilter } from '../fit.js';
|
|
12
|
+
|
|
13
|
+
export const ID = 'us.sam.opportunities';
|
|
14
|
+
const SEARCH = 'https://sam.gov/api/prod/sgs/v1/search/';
|
|
15
|
+
const DETAIL = (id) => `https://sam.gov/api/prod/opps/v2/opportunities/${id}`;
|
|
16
|
+
const RESOURCES = (id) => `https://sam.gov/api/prod/opps/v3/opportunities/${id}/resources`;
|
|
17
|
+
const FILE = (rid) => `https://sam.gov/api/prod/opps/v3/opportunities/resources/files/${rid}/download`;
|
|
18
|
+
export const noticeUrl = (id) => `https://sam.gov/opp/${id}/view`;
|
|
19
|
+
|
|
20
|
+
/** Queries matching the niche focus (software, security, automation, hardware rental). */
|
|
21
|
+
export const QUERIES = [
|
|
22
|
+
'software development',
|
|
23
|
+
'cybersecurity',
|
|
24
|
+
'information technology services',
|
|
25
|
+
'automation artificial intelligence',
|
|
26
|
+
'case management system',
|
|
27
|
+
'cloud hosting',
|
|
28
|
+
'GPU computing',
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/** Notice types worth bidding on: solicitation, combined synopsis, presolicitation, sources sought, special notice. */
|
|
32
|
+
const KEEP_TYPES = new Set(['o', 'k', 'p', 'r', 's']);
|
|
33
|
+
|
|
34
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
35
|
+
|
|
36
|
+
/** sam.gov answers 406 to a bare `Accept: application/json`; the browser's list works. */
|
|
37
|
+
const ACCEPT = { accept: 'application/json, text/plain, */*' };
|
|
38
|
+
|
|
39
|
+
function agencyFrom(org) {
|
|
40
|
+
if (!Array.isArray(org)) return null;
|
|
41
|
+
const names = org.map((o) => o?.name).filter(Boolean);
|
|
42
|
+
if (!names.length) return null;
|
|
43
|
+
return names.length > 1 ? `${names[0]} / ${names[names.length - 1]}` : names[0];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Map one public-search result to a solicitation, or null when it is not open and biddable. */
|
|
47
|
+
export function fromSearch(r) {
|
|
48
|
+
if (!r || r.isCanceled || r.isActive === false) return null;
|
|
49
|
+
if (!KEEP_TYPES.has(r.type?.code)) return null;
|
|
50
|
+
const due = r.responseDate ? String(r.responseDate).slice(0, 10) : null;
|
|
51
|
+
if (due && due < today()) return null;
|
|
52
|
+
if (!due) {
|
|
53
|
+
// Special notices and sources sought without a deadline: keep only recent ones.
|
|
54
|
+
const posted = Date.parse(r.publishDate || '');
|
|
55
|
+
if (!posted || Date.now() - posted > 30 * 86400_000) return null;
|
|
56
|
+
}
|
|
57
|
+
const description = htmlToText(r.descriptions?.[0]?.content || '').slice(0, 6000);
|
|
58
|
+
const s = {
|
|
59
|
+
source: 'sam',
|
|
60
|
+
ext_id: r._id,
|
|
61
|
+
number: r.solicitationNumber || null,
|
|
62
|
+
title: String(r.title || '').trim(),
|
|
63
|
+
agency: agencyFrom(r.organizationHierarchy),
|
|
64
|
+
level: 'federal',
|
|
65
|
+
region: 'US',
|
|
66
|
+
url: noticeUrl(r._id),
|
|
67
|
+
notice_type: r.type?.value || null,
|
|
68
|
+
posted_at: r.publishDate || null,
|
|
69
|
+
due_at: r.responseDate || null,
|
|
70
|
+
description,
|
|
71
|
+
};
|
|
72
|
+
if (!s.title) return null;
|
|
73
|
+
s.prefilter = prefilter(s);
|
|
74
|
+
return s;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Map one official v2 API record. */
|
|
78
|
+
export function fromApi(r) {
|
|
79
|
+
const due = r.responseDeadLine ? String(r.responseDeadLine).slice(0, 10) : null;
|
|
80
|
+
if (r.active === 'No' || (due && due < today())) return null;
|
|
81
|
+
const s = {
|
|
82
|
+
source: 'sam',
|
|
83
|
+
ext_id: r.noticeId,
|
|
84
|
+
number: r.solicitationNumber || null,
|
|
85
|
+
title: String(r.title || '').trim(),
|
|
86
|
+
agency: r.fullParentPathName ? r.fullParentPathName.split('.').filter(Boolean).slice(0, 1).concat(r.fullParentPathName.split('.').slice(-1)).join(' / ') : null,
|
|
87
|
+
level: 'federal',
|
|
88
|
+
region: 'US',
|
|
89
|
+
url: r.uiLink || noticeUrl(r.noticeId),
|
|
90
|
+
notice_type: r.type || null,
|
|
91
|
+
posted_at: r.postedDate || null,
|
|
92
|
+
due_at: r.responseDeadLine || null,
|
|
93
|
+
naics: r.naicsCode || null,
|
|
94
|
+
set_aside: r.typeOfSetAsideDescription || null,
|
|
95
|
+
contacts: (r.pointOfContact || []).map((c) => ({ name: c.fullName, email: c.email, phone: c.phone, role: c.type })),
|
|
96
|
+
description: '',
|
|
97
|
+
};
|
|
98
|
+
s.prefilter = prefilter(s);
|
|
99
|
+
return s.title ? s : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** One ingest pass. Returns solicitations (deduped by id). */
|
|
103
|
+
export async function ingest({ fetcher = http(), queries = QUERIES, size = 25, apiKey = process.env.SAM_API_KEY } = {}) {
|
|
104
|
+
const out = new Map();
|
|
105
|
+
if (apiKey) {
|
|
106
|
+
const fmt = (d) => `${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}/${d.getFullYear()}`;
|
|
107
|
+
const to = new Date();
|
|
108
|
+
const from = new Date(Date.now() - 30 * 86400_000);
|
|
109
|
+
for (const ncode of ['541511', '541512', '541513', '541519', '518210']) {
|
|
110
|
+
const u = new URL('https://api.sam.gov/opportunities/v2/search');
|
|
111
|
+
Object.entries({ api_key: apiKey, postedFrom: fmt(from), postedTo: fmt(to), ncode, limit: '200' }).forEach(([k, v]) => u.searchParams.set(k, v));
|
|
112
|
+
const doc = await fetcher.json(u.toString(), ACCEPT);
|
|
113
|
+
for (const r of doc.opportunitiesData || []) {
|
|
114
|
+
const s = fromApi(r);
|
|
115
|
+
if (s) out.set(s.ext_id, s);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [...out.values()];
|
|
119
|
+
}
|
|
120
|
+
for (const q of queries) {
|
|
121
|
+
const u = new URL(SEARCH);
|
|
122
|
+
Object.entries({ index: 'opp', page: '0', size: String(size), mode: 'search', is_active: 'true', sort: '-modifiedDate', q }).forEach(([k, v]) => u.searchParams.set(k, v));
|
|
123
|
+
const doc = await fetcher.json(u.toString(), ACCEPT);
|
|
124
|
+
for (const r of doc?._embedded?.results || []) {
|
|
125
|
+
const s = fromSearch(r);
|
|
126
|
+
if (s && !out.has(s.ext_id)) out.set(s.ext_id, s);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return [...out.values()];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Read a notice in full: its description, NAICS, set-aside and contacts, and the
|
|
134
|
+
* text of up to `maxFiles` public PDF/text attachments.
|
|
135
|
+
*/
|
|
136
|
+
export async function readDocs(sol, { fetcher = http(), maxFiles = 3 } = {}) {
|
|
137
|
+
const docs = [];
|
|
138
|
+
const fields = {};
|
|
139
|
+
try {
|
|
140
|
+
const d = await fetcher.json(DETAIL(sol.ext_id), ACCEPT);
|
|
141
|
+
const body = Array.isArray(d.description) ? d.description.map((x) => x?.body || '').join('\n') : String(d.description || '');
|
|
142
|
+
const text = htmlToText(body);
|
|
143
|
+
if (text) docs.push({ kind: 'notice', name: 'Notice description', url: sol.url, text: text.slice(0, 60_000), bytes: text.length });
|
|
144
|
+
const n = d.data2?.naics?.[0]?.code?.[0];
|
|
145
|
+
if (n) fields.naics = String(n);
|
|
146
|
+
if (d.data2?.solicitation?.setAside) fields.set_aside = String(d.data2.solicitation.setAside);
|
|
147
|
+
const poc = d.data2?.pointOfContact;
|
|
148
|
+
if (Array.isArray(poc) && poc.length) fields.contacts = poc.map((c) => ({ name: c.fullName, email: c.email, phone: c.phone, role: c.type }));
|
|
149
|
+
} catch (e) {
|
|
150
|
+
docs.push({ kind: 'notice', name: 'Notice description', url: sol.url, error: String(e?.message || e).slice(0, 300) });
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const r = await fetcher.json(RESOURCES(sol.ext_id), ACCEPT);
|
|
154
|
+
const files = (r?._embedded?.opportunityAttachmentList || []).flatMap((l) => l.attachments || []).filter((a) => a.accessLevel === 'public');
|
|
155
|
+
for (const a of files.filter((x) => x.type === 'link').slice(0, 5)) docs.push({ kind: 'link', name: a.name || 'Link', url: a.uri });
|
|
156
|
+
let read = 0;
|
|
157
|
+
for (const a of files.filter((x) => x.type === 'file')) {
|
|
158
|
+
const name = a.name || 'attachment';
|
|
159
|
+
const doc = { kind: 'file', name, url: FILE(a.resourceId), bytes: a.size || null };
|
|
160
|
+
if (read >= maxFiles || !/\.(pdf|txt)$/i.test(name) || (a.size && a.size > 4_000_000)) {
|
|
161
|
+
docs.push(doc);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
read++;
|
|
165
|
+
try {
|
|
166
|
+
const f = await fetchBytes(doc.url);
|
|
167
|
+
doc.text = /\.txt$/i.test(name) ? f.bytes.toString('utf8').slice(0, 60_000) : await pdfText(f.bytes);
|
|
168
|
+
doc.bytes = f.bytes.length;
|
|
169
|
+
} catch (e) {
|
|
170
|
+
doc.error = String(e?.message || e).slice(0, 300);
|
|
171
|
+
}
|
|
172
|
+
docs.push(doc);
|
|
173
|
+
}
|
|
174
|
+
} catch (e) {
|
|
175
|
+
docs.push({ kind: 'link', name: 'Attachments', url: sol.url, error: String(e?.message || e).slice(0, 300) });
|
|
176
|
+
}
|
|
177
|
+
return { docs, fields };
|
|
178
|
+
}
|
package/src/spider.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spider: read a bidder's own website so the niche profile comes from what the
|
|
3
|
+
* company says it does, not a hand-written list.
|
|
4
|
+
*
|
|
5
|
+
* Pages are fetched through c0mpute's `crawl.fetch` workload first (house
|
|
6
|
+
* rule), either through a `c0mpute jobs serve` bridge (C0MPUTE_JOBS_URL +
|
|
7
|
+
* C0MPUTE_JOBS_TOKEN) or the local `c0mpute crawl fetch` CLI
|
|
8
|
+
* (C0MPUTE_CRAWL_CLI=1). When the network has no free crawl worker, or neither
|
|
9
|
+
* is configured, the page is read directly with the polite fetcher (robots.txt,
|
|
10
|
+
* public addresses only, one request at a time per host). Every page records
|
|
11
|
+
* which path read it.
|
|
12
|
+
*
|
|
13
|
+
* Same host only, sitemap first, then links, service/about pages first.
|
|
14
|
+
*/
|
|
15
|
+
import { execFile } from 'node:child_process';
|
|
16
|
+
import { promisify } from 'node:util';
|
|
17
|
+
import { http, htmlToText } from './http.js';
|
|
18
|
+
|
|
19
|
+
const run = promisify(execFile);
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_MAX_PAGES = 40;
|
|
22
|
+
const SKIP_EXT = /\.(png|jpe?g|gif|webp|avif|svg|ico|css|js|mjs|json|xml|rss|atom|pdf|zip|gz|tgz|mp3|mp4|webm|mov|woff2?|ttf|eot|txt|wasm)$/i;
|
|
23
|
+
const SKIP_PATH = /\/(api|auth|login|signin|signup|register|logout|signout|cart|checkout|account|admin|wp-admin|wp-json|feed|tag|tags|cdn-cgi)(\/|$)/i;
|
|
24
|
+
const PRIORITY = /(service|solution|about|capabilit|expertise|what-we-do|work|case-stud|portfolio|industr|consult|agentic|\bai\b|security|automation|product|offering|stack|team|company|government|public-sector|hire)/i;
|
|
25
|
+
|
|
26
|
+
/** "profullstack.com", "https://profullstack.com/x" -> https://profullstack.com/ */
|
|
27
|
+
export function siteRoot(domain) {
|
|
28
|
+
const raw = String(domain || '').trim();
|
|
29
|
+
if (!raw) throw new Error('domain required');
|
|
30
|
+
const u = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`);
|
|
31
|
+
if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(u.hostname)) throw new Error(`not a public domain: ${u.hostname}`);
|
|
32
|
+
return new URL(`${u.protocol}//${u.host}/`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const sameSite = (a, b) => a.replace(/^www\./, '') === b.replace(/^www\./, '');
|
|
36
|
+
|
|
37
|
+
/** Canonical form for de-duplication: no hash, no tracking query, no trailing slash. */
|
|
38
|
+
export function canonical(url) {
|
|
39
|
+
const u = new URL(url);
|
|
40
|
+
u.hash = '';
|
|
41
|
+
for (const k of [...u.searchParams.keys()]) if (/^(utm_|ref$|fbclid|gclid|mc_)/i.test(k)) u.searchParams.delete(k);
|
|
42
|
+
let s = u.toString();
|
|
43
|
+
if (s.endsWith('/') && u.pathname !== '/') s = s.slice(0, -1);
|
|
44
|
+
return s;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Same-site page links in an HTML document. */
|
|
48
|
+
export function extractLinks(html, base) {
|
|
49
|
+
const root = new URL(base);
|
|
50
|
+
const out = new Set();
|
|
51
|
+
for (const m of String(html || '').matchAll(/<a\b[^>]*?\bhref\s*=\s*(["'])(.*?)\1/gi)) {
|
|
52
|
+
const href = m[2].trim();
|
|
53
|
+
if (!href || /^(mailto|tel|javascript|data):/i.test(href) || href.startsWith('#')) continue;
|
|
54
|
+
let u;
|
|
55
|
+
try { u = new URL(href, root); } catch { continue; }
|
|
56
|
+
if (!/^https?:$/.test(u.protocol) || !sameSite(u.hostname, root.hostname)) continue;
|
|
57
|
+
if (SKIP_EXT.test(u.pathname) || SKIP_PATH.test(u.pathname)) continue;
|
|
58
|
+
if ([...u.searchParams.keys()].length > 2) continue;
|
|
59
|
+
out.add(canonical(u.toString()));
|
|
60
|
+
}
|
|
61
|
+
return [...out];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** <loc> entries of a sitemap (or sitemap index). */
|
|
65
|
+
export function parseSitemap(xml) {
|
|
66
|
+
return [...String(xml || '').matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/gi)].map((m) => m[1].replace(/&/g, '&'));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const tag = (html, re) => (re.exec(html)?.[1] || '').replace(/\s+/g, ' ').trim();
|
|
70
|
+
|
|
71
|
+
/** What the profile step needs from a page: title, description, headings, text. */
|
|
72
|
+
export function pageSummary(url, html) {
|
|
73
|
+
const title = htmlToText(tag(html, /<title[^>]*>([\s\S]*?)<\/title>/i)).slice(0, 200);
|
|
74
|
+
const description = htmlToText(
|
|
75
|
+
tag(html, /<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["']/i) || tag(html, /<meta[^>]+property=["']og:description["'][^>]+content=["']([^"']*)["']/i),
|
|
76
|
+
).slice(0, 500);
|
|
77
|
+
const headings = [...String(html).matchAll(/<h[1-3][^>]*>([\s\S]*?)<\/h[1-3]>/gi)].map((m) => htmlToText(m[1]).replace(/\s+/g, ' ').trim()).filter(Boolean).slice(0, 30);
|
|
78
|
+
const main = /<main[\s\S]*?<\/main>/i.exec(html)?.[0] || String(html).replace(/<(nav|header|footer)[\s\S]*?<\/\1>/gi, ' ');
|
|
79
|
+
const text = htmlToText(main).slice(0, 12_000);
|
|
80
|
+
return { url, title, description, headings, text };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/* ------------------------------------------------------------ page fetchers -- */
|
|
84
|
+
|
|
85
|
+
/** crawl.fetch through a `c0mpute jobs serve` bridge. */
|
|
86
|
+
async function viaBridge(url, env) {
|
|
87
|
+
const timeoutMs = Number(env.C0MPUTE_CRAWL_TIMEOUT_MS || 25_000);
|
|
88
|
+
const r = await fetch(`${env.C0MPUTE_JOBS_URL.replace(/\/$/, '')}/v1/jobs`, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers: { authorization: `Bearer ${env.C0MPUTE_JOBS_TOKEN}`, 'content-type': 'application/json' },
|
|
91
|
+
body: JSON.stringify({ workload: 'crawl.fetch', spec: { v: 1, url, timeout_ms: Math.min(timeoutMs, 20_000) }, max_price: Number(env.C0MPUTE_CRAWL_MAX_PRICE || 0.01), timeout_ms: timeoutMs }),
|
|
92
|
+
signal: AbortSignal.timeout(timeoutMs + 5_000),
|
|
93
|
+
});
|
|
94
|
+
const j = await r.json().catch(() => ({}));
|
|
95
|
+
if (!r.ok) throw Object.assign(new Error(j.error || `bridge HTTP ${r.status}`), { busy: j.error === 'network_busy' || r.status === 503 });
|
|
96
|
+
const res = j.result || {};
|
|
97
|
+
if (!res.ok) throw new Error(res.error || 'crawl.fetch failed');
|
|
98
|
+
return { status: res.output?.status, body: typeof res.output?.body === 'string' ? res.output.body : '', worker: j.worker };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** crawl.fetch through the local c0mpute CLI. */
|
|
102
|
+
async function viaCli(url, env) {
|
|
103
|
+
const secs = Math.ceil(Number(env.C0MPUTE_CRAWL_TIMEOUT_MS || 25_000) / 1000);
|
|
104
|
+
try {
|
|
105
|
+
const { stdout } = await run(env.C0MPUTE_BIN || 'c0mpute', ['crawl', 'fetch', url, '--max-price', String(env.C0MPUTE_CRAWL_MAX_PRICE || 0.01), '--timeout-secs', String(secs)], {
|
|
106
|
+
timeout: (secs + 15) * 1000, maxBuffer: 8_000_000, env: { ...process.env, RUST_LOG: 'error' },
|
|
107
|
+
});
|
|
108
|
+
const j = JSON.parse(stdout);
|
|
109
|
+
if (!j.ok) throw new Error(j.error || 'crawl.fetch failed');
|
|
110
|
+
return { status: j.output?.status, body: typeof j.output?.body === 'string' ? j.output.body : '' };
|
|
111
|
+
} catch (e) {
|
|
112
|
+
const msg = String(e?.stderr || e?.message || e);
|
|
113
|
+
throw Object.assign(new Error(/network_busy/.test(msg) ? 'network_busy' : msg.split('\n').filter(Boolean).pop()?.slice(0, 200) || 'c0mpute crawl failed'), { busy: /network_busy|NoPeers/.test(msg) });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function c0mputeCrawlMode(env = process.env) {
|
|
118
|
+
if (env.C0MPUTE_CRAWL === '0') return null;
|
|
119
|
+
if (env.C0MPUTE_JOBS_URL && env.C0MPUTE_JOBS_TOKEN) return 'bridge';
|
|
120
|
+
if (env.C0MPUTE_CRAWL_CLI === '1') return 'cli';
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A page fetcher that tries c0mpute, then reads directly. After the network
|
|
126
|
+
* says it is busy twice, the rest of this crawl goes direct (each busy answer
|
|
127
|
+
* costs ~45 s).
|
|
128
|
+
*/
|
|
129
|
+
export function makePageFetcher(env = process.env) {
|
|
130
|
+
const mode = c0mputeCrawlMode(env);
|
|
131
|
+
let busy = 0;
|
|
132
|
+
const notes = [];
|
|
133
|
+
async function fetchPage(url) {
|
|
134
|
+
if (mode && busy < 2) {
|
|
135
|
+
try {
|
|
136
|
+
const r = mode === 'bridge' ? await viaBridge(url, env) : await viaCli(url, env);
|
|
137
|
+
if (r.status && r.status >= 400) throw new Error(`HTTP ${r.status}`);
|
|
138
|
+
busy = 0;
|
|
139
|
+
return { html: r.body, via: `c0mpute:${mode}` };
|
|
140
|
+
} catch (e) {
|
|
141
|
+
if (e.busy) busy++;
|
|
142
|
+
if (notes.length < 5) notes.push(`c0mpute ${mode}: ${String(e.message).slice(0, 160)}`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const r = await http().text(url, { accept: 'text/html,application/xhtml+xml' });
|
|
146
|
+
if (r.status >= 400) throw new Error(`HTTP ${r.status}`);
|
|
147
|
+
return { html: r.text, via: 'direct' };
|
|
148
|
+
}
|
|
149
|
+
fetchPage.mode = mode;
|
|
150
|
+
fetchPage.notes = notes;
|
|
151
|
+
return fetchPage;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Crawl one site. Returns { root, pages: [{url, title, description, headings, text, via}], errors, via, notes }.
|
|
156
|
+
* `fetchPage(url) -> {html, via}` can be passed in (tests, the CLI).
|
|
157
|
+
*/
|
|
158
|
+
const sitemapText = async (url) => {
|
|
159
|
+
const r = await http().text(url, { accept: 'application/xml,text/xml' });
|
|
160
|
+
return r.status < 400 ? r.text : '';
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export async function crawlSite(domain, { maxPages = DEFAULT_MAX_PAGES, fetchPage = makePageFetcher(), fetchSitemap = sitemapText, onPage } = {}) {
|
|
164
|
+
const root = siteRoot(domain);
|
|
165
|
+
const cap = Math.max(1, Math.min(Number(maxPages) || DEFAULT_MAX_PAGES, 200));
|
|
166
|
+
const queue = [canonical(root.toString())];
|
|
167
|
+
const seen = new Set(queue);
|
|
168
|
+
const pages = [];
|
|
169
|
+
const errors = [];
|
|
170
|
+
const push = (u) => {
|
|
171
|
+
if (seen.has(u) || seen.size > cap * 6) return;
|
|
172
|
+
seen.add(u);
|
|
173
|
+
queue.push(u);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// Sitemap first: it lists the pages the owner thinks matter.
|
|
177
|
+
try {
|
|
178
|
+
const sm = await fetchSitemap(new URL('/sitemap.xml', root).toString());
|
|
179
|
+
if (sm) {
|
|
180
|
+
let locs = parseSitemap(sm);
|
|
181
|
+
const nested = locs.filter((l) => /\.xml(\?|$)/i.test(l)).slice(0, 3);
|
|
182
|
+
for (const n of nested) {
|
|
183
|
+
try { locs = locs.concat(parseSitemap(await fetchSitemap(n))); } catch { /* a missing child sitemap is fine */ }
|
|
184
|
+
}
|
|
185
|
+
for (const l of locs) {
|
|
186
|
+
try {
|
|
187
|
+
const u = new URL(l);
|
|
188
|
+
if (sameSite(u.hostname, root.hostname) && !SKIP_EXT.test(u.pathname) && !SKIP_PATH.test(u.pathname)) push(canonical(u.toString()));
|
|
189
|
+
} catch { /* skip bad loc */ }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
} catch { /* no sitemap */ }
|
|
193
|
+
|
|
194
|
+
const next = () => {
|
|
195
|
+
// Service and about pages before blog posts.
|
|
196
|
+
const i = queue.findIndex((u) => PRIORITY.test(new URL(u).pathname));
|
|
197
|
+
return queue.splice(i >= 0 && pages.length > 0 ? i : 0, 1)[0];
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
while (queue.length && pages.length < cap) {
|
|
201
|
+
const url = next();
|
|
202
|
+
try {
|
|
203
|
+
const { html, via } = await fetchPage(url);
|
|
204
|
+
if (!/<html|<body|<title|<h1/i.test(html)) continue;
|
|
205
|
+
const p = { ...pageSummary(url, html), via };
|
|
206
|
+
if (p.text.length < 40 && !p.title) continue;
|
|
207
|
+
pages.push(p);
|
|
208
|
+
onPage?.(p);
|
|
209
|
+
for (const l of extractLinks(html, url)) push(l);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
errors.push({ url, error: String(e?.message || e).slice(0, 200) });
|
|
212
|
+
if (errors.length > cap) break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const via = {};
|
|
216
|
+
for (const p of pages) via[p.via] = (via[p.via] || 0) + 1;
|
|
217
|
+
return { root: root.toString(), pages, errors: errors.slice(0, 20), via, notes: fetchPage.notes || [] };
|
|
218
|
+
}
|