blast-studio 0.0.0-stage → 0.1.1

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.
Files changed (256) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +138 -2
  3. package/bin/bstudio.mjs +13 -0
  4. package/dist/agent-env.js +177 -0
  5. package/dist/brief.js +53 -0
  6. package/dist/budget/ledger.js +153 -0
  7. package/dist/campaign-zip.js +93 -0
  8. package/dist/cli.js +118 -0
  9. package/dist/commands/accept.js +64 -0
  10. package/dist/commands/auth.js +77 -0
  11. package/dist/commands/brief.js +117 -0
  12. package/dist/commands/budget.js +22 -0
  13. package/dist/commands/dashboard.js +9 -0
  14. package/dist/commands/doctor.js +57 -0
  15. package/dist/commands/export.js +42 -0
  16. package/dist/commands/init.js +24 -0
  17. package/dist/commands/install-skills.js +52 -0
  18. package/dist/commands/library.js +12 -0
  19. package/dist/commands/make.js +71 -0
  20. package/dist/commands/mark.js +44 -0
  21. package/dist/commands/new.js +25 -0
  22. package/dist/commands/plan.js +57 -0
  23. package/dist/commands/render-preview.js +43 -0
  24. package/dist/commands/render.js +243 -0
  25. package/dist/commands/review.js +119 -0
  26. package/dist/commands/revise.js +73 -0
  27. package/dist/commands/sources.js +33 -0
  28. package/dist/commands/status.js +34 -0
  29. package/dist/config.js +141 -0
  30. package/dist/dashboard/server.js +171 -0
  31. package/dist/dashboard/static/app.css +1 -0
  32. package/dist/dashboard/static/app.js +52 -0
  33. package/dist/dashboard/static/index.html +8 -0
  34. package/dist/env.js +47 -0
  35. package/dist/export.js +110 -0
  36. package/dist/fetch-text.js +64 -0
  37. package/dist/io.js +1 -0
  38. package/dist/keychain.js +41 -0
  39. package/dist/library.js +49 -0
  40. package/dist/packs.js +91 -0
  41. package/dist/plan.js +75 -0
  42. package/dist/posts.js +40 -0
  43. package/dist/providers/images.js +116 -0
  44. package/dist/providers/voice.js +55 -0
  45. package/dist/render/bins.js +21 -0
  46. package/dist/render/ffmpeg.js +102 -0
  47. package/dist/render/metrics.js +109 -0
  48. package/dist/render/stills.js +175 -0
  49. package/dist/render/template.js +20 -0
  50. package/dist/render/video.js +175 -0
  51. package/dist/review/gates.js +201 -0
  52. package/dist/review/reviewer.js +79 -0
  53. package/dist/review/score.js +21 -0
  54. package/dist/review/slop.js +17 -0
  55. package/dist/review-hash.js +21 -0
  56. package/dist/types.js +29 -0
  57. package/dist/updater/check.js +140 -0
  58. package/dist/updater/propose.js +144 -0
  59. package/dist/workspace.js +142 -0
  60. package/package.json +45 -4
  61. package/platforms/bluesky/guide.md +94 -0
  62. package/platforms/bluesky/pack.yml +150 -0
  63. package/platforms/dailydev/guide.md +82 -0
  64. package/platforms/dailydev/pack.yml +152 -0
  65. package/platforms/devto/guide.md +93 -0
  66. package/platforms/devto/pack.yml +119 -0
  67. package/platforms/gist/guide.md +92 -0
  68. package/platforms/gist/pack.yml +119 -0
  69. package/platforms/github-discussion/guide.md +92 -0
  70. package/platforms/github-discussion/pack.yml +122 -0
  71. package/platforms/hashnode/guide.md +93 -0
  72. package/platforms/hashnode/pack.yml +124 -0
  73. package/platforms/hn/guide.md +48 -0
  74. package/platforms/hn/pack.yml +59 -0
  75. package/platforms/instagram/guide.md +95 -0
  76. package/platforms/instagram/pack.yml +136 -0
  77. package/platforms/lemmy/guide.md +88 -0
  78. package/platforms/lemmy/pack.yml +141 -0
  79. package/platforms/linkedin/guide.md +93 -0
  80. package/platforms/linkedin/pack.yml +145 -0
  81. package/platforms/mastodon/guide.md +92 -0
  82. package/platforms/mastodon/pack.yml +138 -0
  83. package/platforms/medium/guide.md +92 -0
  84. package/platforms/medium/pack.yml +119 -0
  85. package/platforms/newsletter/guide.md +94 -0
  86. package/platforms/newsletter/pack.yml +144 -0
  87. package/platforms/producthunt/guide.md +92 -0
  88. package/platforms/producthunt/pack.yml +166 -0
  89. package/platforms/reddit/guide.md +92 -0
  90. package/platforms/reddit/pack.yml +151 -0
  91. package/platforms/snapshots/.gitkeep +0 -0
  92. package/platforms/snapshots/bluesky-10.sha256 +1 -0
  93. package/platforms/snapshots/bluesky-10.txt +1 -0
  94. package/platforms/snapshots/bluesky-11.sha256 +1 -0
  95. package/platforms/snapshots/bluesky-11.txt +1 -0
  96. package/platforms/snapshots/bluesky-12.sha256 +1 -0
  97. package/platforms/snapshots/bluesky-12.txt +1 -0
  98. package/platforms/snapshots/bluesky-13.sha256 +1 -0
  99. package/platforms/snapshots/bluesky-13.txt +1 -0
  100. package/platforms/snapshots/bluesky-14.sha256 +1 -0
  101. package/platforms/snapshots/bluesky-14.txt +1 -0
  102. package/platforms/snapshots/cross-platform-63.sha256 +1 -0
  103. package/platforms/snapshots/cross-platform-63.txt +1 -0
  104. package/platforms/snapshots/cross-platform-64.sha256 +1 -0
  105. package/platforms/snapshots/cross-platform-64.txt +1 -0
  106. package/platforms/snapshots/dailydev-55.sha256 +1 -0
  107. package/platforms/snapshots/dailydev-55.txt +1 -0
  108. package/platforms/snapshots/dailydev-56.sha256 +1 -0
  109. package/platforms/snapshots/dailydev-56.txt +1 -0
  110. package/platforms/snapshots/dailydev-57.sha256 +1 -0
  111. package/platforms/snapshots/dailydev-57.txt +1 -0
  112. package/platforms/snapshots/devto-26.sha256 +1 -0
  113. package/platforms/snapshots/devto-26.txt +1 -0
  114. package/platforms/snapshots/devto-27.sha256 +1 -0
  115. package/platforms/snapshots/devto-27.txt +1 -0
  116. package/platforms/snapshots/devto-28.sha256 +1 -0
  117. package/platforms/snapshots/devto-28.txt +1 -0
  118. package/platforms/snapshots/devto-29.sha256 +1 -0
  119. package/platforms/snapshots/devto-29.txt +1 -0
  120. package/platforms/snapshots/gist-52.sha256 +1 -0
  121. package/platforms/snapshots/gist-52.txt +1 -0
  122. package/platforms/snapshots/gist-53.sha256 +1 -0
  123. package/platforms/snapshots/gist-53.txt +1 -0
  124. package/platforms/snapshots/gist-54.sha256 +1 -0
  125. package/platforms/snapshots/gist-54.txt +1 -0
  126. package/platforms/snapshots/github-discussion-policy.sha256 +1 -0
  127. package/platforms/snapshots/github-discussion-policy.txt +1 -0
  128. package/platforms/snapshots/hashnode-30.sha256 +1 -0
  129. package/platforms/snapshots/hashnode-30.txt +1 -0
  130. package/platforms/snapshots/hashnode-31.sha256 +1 -0
  131. package/platforms/snapshots/hashnode-31.txt +1 -0
  132. package/platforms/snapshots/hashnode-32.sha256 +1 -0
  133. package/platforms/snapshots/hashnode-32.txt +1 -0
  134. package/platforms/snapshots/hn-23.sha256 +1 -0
  135. package/platforms/snapshots/hn-23.txt +1 -0
  136. package/platforms/snapshots/hn-24.sha256 +1 -0
  137. package/platforms/snapshots/hn-24.txt +1 -0
  138. package/platforms/snapshots/hn-25.sha256 +1 -0
  139. package/platforms/snapshots/hn-25.txt +1 -0
  140. package/platforms/snapshots/hyperframes-releases.sha256 +1 -0
  141. package/platforms/snapshots/hyperframes-releases.txt +1 -0
  142. package/platforms/snapshots/instagram-43.sha256 +1 -0
  143. package/platforms/snapshots/instagram-43.txt +1 -0
  144. package/platforms/snapshots/instagram-47.sha256 +1 -0
  145. package/platforms/snapshots/instagram-47.txt +1 -0
  146. package/platforms/snapshots/lemmy-policy.sha256 +1 -0
  147. package/platforms/snapshots/lemmy-policy.txt +1 -0
  148. package/platforms/snapshots/linkedin-1.sha256 +1 -0
  149. package/platforms/snapshots/linkedin-1.txt +1 -0
  150. package/platforms/snapshots/linkedin-2.sha256 +1 -0
  151. package/platforms/snapshots/linkedin-2.txt +1 -0
  152. package/platforms/snapshots/linkedin-3.sha256 +1 -0
  153. package/platforms/snapshots/linkedin-3.txt +1 -0
  154. package/platforms/snapshots/linkedin-4.sha256 +1 -0
  155. package/platforms/snapshots/linkedin-4.txt +1 -0
  156. package/platforms/snapshots/mastodon-15.sha256 +1 -0
  157. package/platforms/snapshots/mastodon-15.txt +1 -0
  158. package/platforms/snapshots/mastodon-16.sha256 +1 -0
  159. package/platforms/snapshots/mastodon-16.txt +1 -0
  160. package/platforms/snapshots/mastodon-17.sha256 +1 -0
  161. package/platforms/snapshots/mastodon-17.txt +1 -0
  162. package/platforms/snapshots/medium-34.sha256 +1 -0
  163. package/platforms/snapshots/medium-34.txt +1 -0
  164. package/platforms/snapshots/medium-35.sha256 +1 -0
  165. package/platforms/snapshots/medium-35.txt +1 -0
  166. package/platforms/snapshots/medium-36.sha256 +1 -0
  167. package/platforms/snapshots/medium-36.txt +1 -0
  168. package/platforms/snapshots/newsletter-58.sha256 +1 -0
  169. package/platforms/snapshots/newsletter-58.txt +1 -0
  170. package/platforms/snapshots/newsletter-59.sha256 +1 -0
  171. package/platforms/snapshots/newsletter-59.txt +1 -0
  172. package/platforms/snapshots/newsletter-60.sha256 +1 -0
  173. package/platforms/snapshots/newsletter-60.txt +1 -0
  174. package/platforms/snapshots/newsletter-61.sha256 +1 -0
  175. package/platforms/snapshots/newsletter-61.txt +1 -0
  176. package/platforms/snapshots/newsletter-62.sha256 +1 -0
  177. package/platforms/snapshots/newsletter-62.txt +1 -0
  178. package/platforms/snapshots/openai-image-pricing.sha256 +1 -0
  179. package/platforms/snapshots/openai-image-pricing.txt +1 -0
  180. package/platforms/snapshots/playwright-releases.sha256 +1 -0
  181. package/platforms/snapshots/playwright-releases.txt +1 -0
  182. package/platforms/snapshots/producthunt-37.sha256 +1 -0
  183. package/platforms/snapshots/producthunt-37.txt +1 -0
  184. package/platforms/snapshots/producthunt-38.sha256 +1 -0
  185. package/platforms/snapshots/producthunt-38.txt +1 -0
  186. package/platforms/snapshots/producthunt-39.sha256 +1 -0
  187. package/platforms/snapshots/producthunt-39.txt +1 -0
  188. package/platforms/snapshots/reddit-20.sha256 +1 -0
  189. package/platforms/snapshots/reddit-20.txt +1 -0
  190. package/platforms/snapshots/reddit-21.sha256 +1 -0
  191. package/platforms/snapshots/reddit-21.txt +1 -0
  192. package/platforms/snapshots/reddit-22.sha256 +1 -0
  193. package/platforms/snapshots/reddit-22.txt +1 -0
  194. package/platforms/snapshots/substack-policy.sha256 +1 -0
  195. package/platforms/snapshots/substack-policy.txt +1 -0
  196. package/platforms/snapshots/threads-18.sha256 +1 -0
  197. package/platforms/snapshots/threads-18.txt +1 -0
  198. package/platforms/snapshots/threads-19.sha256 +1 -0
  199. package/platforms/snapshots/threads-19.txt +1 -0
  200. package/platforms/snapshots/tiktok-50.sha256 +1 -0
  201. package/platforms/snapshots/tiktok-50.txt +1 -0
  202. package/platforms/snapshots/tiktok-51.sha256 +1 -0
  203. package/platforms/snapshots/tiktok-51.txt +1 -0
  204. package/platforms/snapshots/x-5.sha256 +1 -0
  205. package/platforms/snapshots/x-5.txt +1 -0
  206. package/platforms/snapshots/x-6.sha256 +1 -0
  207. package/platforms/snapshots/x-6.txt +1 -0
  208. package/platforms/snapshots/x-7.sha256 +1 -0
  209. package/platforms/snapshots/x-7.txt +1 -0
  210. package/platforms/snapshots/x-8.sha256 +1 -0
  211. package/platforms/snapshots/x-8.txt +1 -0
  212. package/platforms/snapshots/x-9.sha256 +1 -0
  213. package/platforms/snapshots/x-9.txt +1 -0
  214. package/platforms/snapshots/youtube-shorts-40.sha256 +1 -0
  215. package/platforms/snapshots/youtube-shorts-40.txt +1 -0
  216. package/platforms/snapshots/youtube-shorts-41.sha256 +1 -0
  217. package/platforms/snapshots/youtube-shorts-41.txt +1 -0
  218. package/platforms/snapshots/youtube-shorts-42.sha256 +1 -0
  219. package/platforms/snapshots/youtube-shorts-42.txt +1 -0
  220. package/platforms/sources.yml +947 -0
  221. package/platforms/substack/guide.md +94 -0
  222. package/platforms/substack/pack.yml +116 -0
  223. package/platforms/threads/guide.md +93 -0
  224. package/platforms/threads/pack.yml +148 -0
  225. package/platforms/tiktok/guide.md +92 -0
  226. package/platforms/tiktok/pack.yml +129 -0
  227. package/platforms/x/guide.md +94 -0
  228. package/platforms/x/pack.yml +130 -0
  229. package/platforms/youtube-shorts/guide.md +92 -0
  230. package/platforms/youtube-shorts/pack.yml +138 -0
  231. package/providers/prices.yml +31 -0
  232. package/schemas/campaign.v2.json +26 -0
  233. package/schemas/manifest.v1.json +37 -0
  234. package/schemas/pack.schema.json +601 -0
  235. package/schemas/review.schema.json +31 -0
  236. package/skills/studio-reviewer/SKILL.md +13 -0
  237. package/skills/studio-updater/SKILL.md +8 -0
  238. package/skills/studio-video/SKILL.md +20 -0
  239. package/skills/studio-visual/SKILL.md +12 -0
  240. package/skills/studio-writer/SKILL.md +14 -0
  241. package/templates/README.md +7 -0
  242. package/templates/card.html +1 -0
  243. package/templates/carousel-closing.html +1 -0
  244. package/templates/carousel-content.html +1 -0
  245. package/templates/carousel-title.html +1 -0
  246. package/templates/code.html +1 -0
  247. package/templates/fonts/IBM-Plex-OFL.txt +93 -0
  248. package/templates/fonts/IBMPlexMono.woff2 +0 -0
  249. package/templates/fonts/IBMPlexSans.woff2 +0 -0
  250. package/templates/fonts/Space-Grotesk-OFL.txt +93 -0
  251. package/templates/fonts/SpaceGrotesk.woff2 +0 -0
  252. package/templates/poster.html +1 -0
  253. package/templates/quote.html +1 -0
  254. package/templates/thumbnail.html +1 -0
  255. package/test/fixtures/reviews/calibration.json +22 -0
  256. package/test/fixtures/reviews/grounding/cases.json +17 -0
@@ -0,0 +1,171 @@
1
+ import { createServer } from 'node:http';
2
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { existsSync, readFileSync, realpathSync, statSync, createReadStream } from 'node:fs';
4
+ import { dirname, extname, join, relative, resolve, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { loadConfig, projectDir, writeConfigField } from "../config.js";
7
+ import { loadLibrary, projectDetails, latestSources } from "../library.js";
8
+ import { monthToDate, projectTotal, providerTotals } from "../budget/ledger.js";
9
+ const staticDir = join(dirname(fileURLToPath(import.meta.url)), 'static');
10
+ const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webm': 'video/webm', '.pdf': 'application/pdf', '.vtt': 'text/vtt; charset=utf-8' };
11
+ function send(res, status, value) {
12
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
13
+ res.end(JSON.stringify(value));
14
+ }
15
+ function equal(a, b) { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); }
16
+ async function body(req) {
17
+ let data = '';
18
+ for await (const chunk of req) {
19
+ data += chunk;
20
+ if (data.length > 16384)
21
+ throw new Error('Request too large');
22
+ }
23
+ const result = JSON.parse(data);
24
+ if (!result || typeof result !== 'object' || Array.isArray(result))
25
+ throw new Error('Expected an object');
26
+ return result;
27
+ }
28
+ function serveFile(req, res, path, media = false) {
29
+ const size = statSync(path).size, type = types[extname(path).toLowerCase()] ?? 'application/octet-stream';
30
+ const headers = { 'Content-Type': type, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', ...(media ? { 'Content-Security-Policy': "sandbox; default-src 'none'" } : {}) };
31
+ const range = req.headers.range;
32
+ if (range && type.startsWith('video/')) {
33
+ const m = /^bytes=(\d*)-(\d*)$/.exec(range);
34
+ if (!m || (!m[1] && !m[2])) {
35
+ res.writeHead(416, { 'Content-Range': `bytes */${size}` });
36
+ res.end();
37
+ return;
38
+ }
39
+ const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));
40
+ const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
41
+ if (start >= size || end < start) {
42
+ res.writeHead(416, { 'Content-Range': `bytes */${size}` });
43
+ res.end();
44
+ return;
45
+ }
46
+ res.writeHead(206, { ...headers, 'Accept-Ranges': 'bytes', 'Content-Range': `bytes ${start}-${end}/${size}`, 'Content-Length': end - start + 1 });
47
+ createReadStream(path, { start, end }).pipe(res);
48
+ return;
49
+ }
50
+ res.writeHead(200, { ...headers, 'Content-Length': size, ...(type.startsWith('video/') ? { 'Accept-Ranges': 'bytes' } : {}) });
51
+ createReadStream(path).pipe(res);
52
+ }
53
+ export async function startDashboard(io, options = {}) {
54
+ const host = options.host ?? '127.0.0.1';
55
+ if (host !== '127.0.0.1')
56
+ throw new Error('Dashboard may only bind to 127.0.0.1');
57
+ const token = randomBytes(32).toString('hex'), session = randomBytes(32).toString('hex');
58
+ let unused = true;
59
+ const server = createServer(async (req, res) => {
60
+ const address = server.address();
61
+ const port = typeof address === 'object' && address ? address.port : options.port ?? 4848;
62
+ if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(req.headers.host ?? '')) {
63
+ send(res, 421, { error: 'Invalid host' });
64
+ return;
65
+ }
66
+ try {
67
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);
68
+ if (req.method === 'GET' && url.pathname === '/' && url.searchParams.has('t')) {
69
+ if (!unused || !equal(url.searchParams.get('t') ?? '', token)) {
70
+ send(res, 401, { error: 'Invalid token' });
71
+ return;
72
+ }
73
+ unused = false;
74
+ res.writeHead(302, { 'Set-Cookie': `bs=${session}; HttpOnly; SameSite=Strict; Path=/`, Location: '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
75
+ res.end();
76
+ return;
77
+ }
78
+ const cookie = (req.headers.cookie ?? '').split(';').map(s => s.trim()).find(s => s.startsWith('bs='))?.slice(3) ?? '';
79
+ if (!equal(cookie, session)) {
80
+ send(res, 401, { error: 'Authentication required' });
81
+ return;
82
+ }
83
+ const rawPath = (req.url ?? '').split('?')[0];
84
+ if (rawPath.startsWith('/media/') && decodeURIComponent(rawPath).split(/[\\/]/).some(part => part === '..' || part === '.')) {
85
+ send(res, 403, { error: 'Forbidden' });
86
+ return;
87
+ }
88
+ const config = loadConfig(io), pathname = url.pathname;
89
+ if (req.method === 'GET') {
90
+ if (pathname === '/api/library') {
91
+ send(res, 200, loadLibrary(config, url.searchParams.get('q') ?? ''));
92
+ return;
93
+ }
94
+ if (pathname === '/api/budget') {
95
+ send(res, 200, { cap: config.budget.monthlyUsd, perProject: config.budget.perProjectUsd, mtd: monthToDate(config.root), providerTotals: providerTotals(config.root), projects: Object.fromEntries(loadLibrary(config).map(p => [p.slug, projectTotal(config.root, p.slug)])), providers: { images: config.images.provider, voice: config.voice.provider }, brand: config.brand });
96
+ return;
97
+ }
98
+ if (pathname === '/api/sources') {
99
+ send(res, 200, latestSources(config));
100
+ return;
101
+ }
102
+ if (pathname.startsWith('/api/project/')) {
103
+ const slug = decodeURIComponent(pathname.slice(13));
104
+ const dir = projectDir(config, slug);
105
+ if (!existsSync(dir)) {
106
+ send(res, 404, { error: 'Project not found' });
107
+ return;
108
+ }
109
+ send(res, 200, projectDetails(config, slug));
110
+ return;
111
+ }
112
+ if (pathname.startsWith('/media/')) {
113
+ const parts = pathname.slice(7).split('/').map(decodeURIComponent), slug = parts.shift() ?? '';
114
+ const project = projectDir(config, slug), base = realpathSync(project), root = realpathSync(join(config.root, 'projects'));
115
+ if (relative(root, base).startsWith('..') || parts.some(p => p === '..' || p === '.' || p.includes('/') || p.includes('\\'))) {
116
+ send(res, 403, { error: 'Forbidden' });
117
+ return;
118
+ }
119
+ const file = realpathSync(resolve(base, ...parts)), rel = relative(base, file);
120
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || !statSync(file).isFile()) {
121
+ send(res, 403, { error: 'Forbidden' });
122
+ return;
123
+ }
124
+ serveFile(req, res, file, true);
125
+ return;
126
+ }
127
+ const staticFile = pathname === '/' ? 'index.html' : pathname === '/app.js' ? 'app.js' : pathname === '/app.css' ? 'app.css' : '';
128
+ if (staticFile) {
129
+ serveFile(req, res, join(staticDir, staticFile));
130
+ return;
131
+ }
132
+ }
133
+ if (req.method === 'PUT' && (pathname === '/api/budget' || pathname === '/api/providers')) {
134
+ if (req.headers['x-requested-with'] !== 'bstudio') {
135
+ send(res, 403, { error: 'Missing request header' });
136
+ return;
137
+ }
138
+ const data = await body(req);
139
+ if (pathname === '/api/budget') {
140
+ if (Object.keys(data).sort().join(',') !== 'monthlyUsd,perProjectUsd' || ![data.monthlyUsd, data.perProjectUsd].every(v => typeof v === 'number' && Number.isFinite(v) && v >= 0)) {
141
+ send(res, 400, { error: 'Budget values must be non-negative numbers' });
142
+ return;
143
+ }
144
+ writeConfigField(config, ['budget', 'monthlyUsd'], data.monthlyUsd);
145
+ writeConfigField(config, ['budget', 'perProjectUsd'], data.perProjectUsd);
146
+ }
147
+ else {
148
+ if (Object.keys(data).sort().join(',') !== 'images,voice' || typeof data.images !== 'string' || !['none', 'gemini', 'openai', 'omp'].includes(data.images) || typeof data.voice !== 'string' || !['none', 'openai'].includes(data.voice)) {
149
+ send(res, 400, { error: 'Invalid providers' });
150
+ return;
151
+ }
152
+ writeConfigField(config, ['images', 'provider'], data.images);
153
+ writeConfigField(config, ['voice', 'provider'], data.voice);
154
+ }
155
+ send(res, 200, { ok: true });
156
+ return;
157
+ }
158
+ send(res, 404, { error: 'Not found' });
159
+ }
160
+ catch (error) {
161
+ const code = error.code;
162
+ send(res, code === 'ENOENT' || code === 'ENOTDIR' ? 404 : 400, { error: error.message });
163
+ }
164
+ });
165
+ await new Promise((resolveListen, reject) => { server.once('error', reject); server.listen(options.port ?? 4848, host, () => { server.off('error', reject); resolveListen(); }); });
166
+ const address = server.address();
167
+ if (!address || typeof address === 'string')
168
+ throw new Error('No server address');
169
+ const url = `http://127.0.0.1:${address.port}/?t=${token}`;
170
+ return { server, url, token, port: address.port };
171
+ }
@@ -0,0 +1 @@
1
+ :root{--ink:#1a1a1a;--paper:#fff;--accent:#315efb;--line:#d9dfe8;--muted:#526073;--wash:#f2f5f9;font-family:system-ui,-apple-system,sans-serif;color:var(--ink);background:var(--paper);font-size:16px}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,select:focus-visible,a:focus-visible{outline:3px solid var(--accent);outline-offset:3px}::selection{background:#b9cbff}.top{height:72px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 32px}.wordmark{display:flex;align-items:center;gap:12px;font-weight:750}.wordmark small{display:block;color:var(--muted);font-size:.75rem;font-weight:500}.mark{display:grid;place-items:center;background:var(--accent);color:white;width:36px;height:36px;border-radius:8px}.local{color:var(--muted);font-size:.85rem}.layout{display:grid;grid-template-columns:225px minmax(0,1fr);min-height:calc(100vh - 72px)}aside{background:var(--wash);padding:32px 16px;display:flex;flex-direction:column;justify-content:space-between}nav{display:grid;gap:4px}.nav{border:0;text-align:left;background:transparent;padding:12px 16px;border-radius:6px;color:var(--ink)}.nav:hover,.nav.active{background:white}.nav.active{font-weight:700;box-shadow:0 1px 4px #28374818}.aside-note{font-size:.8rem;color:var(--muted);padding:0 16px}main{padding:48px clamp(24px,5vw,72px);max-width:1500px;width:100%}h1{font-size:2rem;letter-spacing:-.025em;margin:0 0 8px}h2{font-size:1.15rem;margin:0 0 12px}p{color:var(--muted);line-height:1.55;margin:0 0 20px}.section-head{display:flex;justify-content:space-between;align-items:end;gap:24px;margin-bottom:36px}.section-head p{margin-bottom:0}label{display:grid;gap:8px;font-size:.875rem;font-weight:650}input,select{border:1px solid #aab5c3;border-radius:6px;background:white;color:#192231;padding:10px 12px;min-width:0}input:focus,select:focus{border-color:var(--accent)}.search{width:min(300px,100%)}.list-head,.project-row{display:grid;grid-template-columns:2fr 1fr 1fr;gap:24px;align-items:center}.list-head{padding:12px 16px;color:var(--muted);font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid var(--line)}.project-row{width:100%;text-align:left;border:0;border-bottom:1px solid var(--line);background:transparent;padding:20px 16px;color:inherit}.project-row:hover{background:var(--wash)}.project-row strong{display:block;font-size:1rem}.project-row small,.subtle{display:block;color:var(--muted);margin-top:5px;font-size:.85rem}.project-row span{font-size:.9rem}.empty{padding:32px 16px;color:var(--muted)}.text-button{background:none;border:0;padding:0;color:var(--accent);font-weight:700;margin-bottom:28px}.panel,.platform{border:1px solid var(--line);border-radius:8px;padding:24px;background:var(--paper)}.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:32px}form{display:grid;gap:20px;margin-top:24px}form small{font-weight:400;color:var(--muted)}form button{justify-self:start;border:0;border-radius:6px;background:var(--accent);color:white;font-weight:700;padding:11px 18px}form button:hover{filter:brightness(.85)}.meter{height:8px;border-radius:8px;background:#e4e9f0;overflow:hidden;margin:12px 0}.meter span{display:block;height:100%;background:var(--accent)}.spend-amount{font-size:1.6rem;font-weight:750}.platforms{display:grid;gap:16px;margin-top:28px}.platform header{display:flex;justify-content:space-between;gap:16px;align-items:center}.badge{background:#eaf0ff;color:#243e9b;border-radius:20px;padding:5px 10px;font-size:.8rem;font-weight:700}.post-text{white-space:pre-wrap;line-height:1.6;max-width:75ch;margin:20px 0}.media{display:flex;gap:12px;overflow:auto}.media img,.media video{max-width:320px;max-height:250px;object-fit:contain;background:#eef1f5}.review-table{width:100%;border-collapse:collapse;margin-top:20px;font-size:.875rem}.review-table th,.review-table td{text-align:left;padding:10px;border-bottom:1px solid var(--line);vertical-align:top}.review-table th{color:var(--muted)}.table-wrap{overflow:auto}#message:not(:empty){background:#eef4ff;padding:12px;margin-bottom:20px;border-radius:6px}.source-list{white-space:pre-wrap;color:var(--ink)}@media(max-width:700px){.top{padding:0 20px}.layout{display:block}aside{padding:12px 16px}nav{display:flex;overflow:auto}.nav{white-space:nowrap}.aside-note{display:none}main{padding:32px 20px}.section-head{display:block}.search{margin-top:24px}.list-head,.project-row{grid-template-columns:1fr auto}.list-head span:last-child,.project-row>span:last-child{display:none}.settings-grid{grid-template-columns:1fr}.local{display:none}}
@@ -0,0 +1,52 @@
1
+ const $ = selector => document.querySelector(selector);
2
+ const el = (tag, text, className) => { const node = document.createElement(tag); if (text != null) node.textContent = text; if (className) node.className = className; return node; };
3
+ const money = n => `$${Number(n).toFixed(2)}`;
4
+ async function api(path, options) { const response = await fetch(path, options); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Request failed'); return data; }
5
+ function message(text) { $('#message').textContent = text; }
6
+ function show(view) { document.querySelectorAll('.view').forEach(node => { node.hidden = node.id !== view; }); document.querySelectorAll('.nav').forEach(node => node.classList.toggle('active', node.dataset.view === (view === 'project' ? 'projects' : view))); }
7
+ function mediaUrl(slug, path) { return `/media/${encodeURIComponent(slug)}/${path.split('/').map(encodeURIComponent).join('/')}`; }
8
+ async function library() {
9
+ const projects = await api(`/api/library?q=${encodeURIComponent($('#search').value)}`), list = $('#project-list'); list.replaceChildren();
10
+ if (!projects.length) { list.append(el('p', 'No projects found. Create a project or try another search.', 'empty')); return; }
11
+ for (const project of projects) { const row = el('button', null, 'project-row'); row.type = 'button'; const title = el('span'); title.append(el('strong', project.slug), el('small', project.inputs.join(' · ') || 'No brief inputs', 'subtle')); row.append(title, el('span', project.posts.map(p => p.platform).join(', ') || 'No posts'), el('span', project.assets.length ? `${project.assets.length} assets` : 'No assets')); row.addEventListener('click', () => openProject(project.slug).catch(error => message(error.message))); list.append(row); }
12
+ }
13
+ async function openProject(slug) {
14
+ const project = await api(`/api/project/${encodeURIComponent(slug)}`), container = $('#project-detail'); container.replaceChildren(el('h1', slug), el('p', project.inputs.join(' · ') || 'Project overview'));
15
+ const platforms = el('div', null, 'platforms');
16
+ for (const post of project.posts) {
17
+ const review = project.reviews.find(r => r.platform === post.platform), card = el('article', null, 'platform'), header = el('header');
18
+ header.append(el('h2', post.platform), el('span', review ? `${review.verdict} · ${review.total == null ? 'N/A' : `${review.total.toFixed(1)}/100`}` : 'Unreviewed', 'badge')); card.append(header);
19
+ if (post.title) card.append(el('h3', post.title)); card.append(el('div', post.body, 'post-text'));
20
+ const media = el('div', null, 'media');
21
+ for (const item of post.media) { let node; if (item.kind === 'video') { node = el('video'); node.controls = true; node.setAttribute('aria-label', item.alt || 'Video'); } else if (item.kind === 'document' || item.file.toLowerCase().endsWith('.pdf')) { node = el('a', item.alt || 'Open PDF'); node.href = mediaUrl(slug, item.file); } else { node = el('img'); node.alt = item.alt; } if (node.tagName !== 'A') node.src = mediaUrl(slug, item.file); media.append(node); } card.append(media);
22
+ if (review?.scores?.length) { const wrap = el('div', null, 'table-wrap'), table = el('table', null, 'review-table'), head = el('tr'); for (const title of ['Criterion', 'Score', 'Evidence', 'Fix']) head.append(el('th', title)); const thead = el('thead'); thead.append(head); table.append(thead); const tbody = el('tbody'); for (const score of review.scores) { const row = el('tr'); for (const value of [score.criterion, score.score ?? 'N/A', score.evidence, score.fix]) row.append(el('td', String(value ?? ''))); tbody.append(row); } table.append(tbody); wrap.append(table); card.append(wrap); } platforms.append(card);
23
+ }
24
+ if (!project.posts.length) platforms.append(el('p', 'No posts yet. Make a project to see its platform drafts.', 'empty')); container.append(platforms);
25
+ if (project.assets.length) {
26
+ const section = el('section', null, 'platforms'); section.append(el('h2', 'Assets'));
27
+ for (const asset of project.assets) {
28
+ const card = el('article', null, 'panel'); card.append(el('h3', `${asset.id} · ${asset.kind}`), el('p', `${asset.aiGenerated ? 'AI generated' : 'Not AI generated'} · ${asset.costUsd == null ? 'Cost unavailable' : money(asset.costUsd)}`));
29
+ const previews = el('div', null, 'media');
30
+ for (const output of asset.outputs || []) {
31
+ const path = `assets/${asset.id}/${output.file}`, name = output.file.toLowerCase(); let node;
32
+ if (/\.(png|jpe?g|gif|webp|svg)$/.test(name)) { node = el('img'); node.alt = `${asset.id} preview`; node.src = mediaUrl(slug, path); }
33
+ else if (/\.(mp4|webm)$/.test(name)) { node = el('video'); node.controls = true; node.setAttribute('aria-label', `${asset.id} video`); node.src = mediaUrl(slug, path); }
34
+ else { node = el('a', output.file); node.href = mediaUrl(slug, path); }
35
+ previews.append(node);
36
+ }
37
+ card.append(previews); section.append(card);
38
+ }
39
+ container.append(section);
40
+ }
41
+ show('project');
42
+ }
43
+ async function settings() {
44
+ const data = await api('/api/budget'), spend = $('#spend'); spend.replaceChildren(el('div', `${money(data.mtd)} of ${money(data.cap)}`, 'spend-amount'), el('span', 'spent this month', 'subtle')); const meter = el('div', null, 'meter'), fill = el('span'); fill.style.width = `${data.cap ? Math.min(100, data.mtd / data.cap * 100) : 0}%`; meter.append(fill); spend.append(meter); $('#budget-form').elements.monthlyUsd.value = data.cap; $('#budget-form').elements.perProjectUsd.value = data.perProject; $('#providers-form').elements.images.value = data.providers.images; $('#providers-form').elements.voice.value = data.providers.voice;
45
+ const totals = $('#provider-totals'); totals.replaceChildren(); for (const [name, value] of Object.entries(data.providerTotals)) totals.append(el('p', `${name}: ${money(value)}`));
46
+ const colors = data.brand.colors || {}; for (const name of ['ink', 'paper', 'accent']) if (/^#[0-9a-f]{6}$/i.test(colors[name] || '')) document.documentElement.style.setProperty(`--${name}`, colors[name]);
47
+ }
48
+ async function sources() { const data = await api('/api/sources'), target = $('#source-detail'); target.replaceChildren(el('h2', `Last checked: ${data.lastCheck || 'Never'}`)); for (const key of ['changed', 'failed', 'unverified']) { target.append(el('h3', key[0].toUpperCase() + key.slice(1)), el('div', data[key].join('\n') || 'None reported', 'source-list')); } }
49
+ for (const nav of document.querySelectorAll('.nav')) nav.addEventListener('click', async () => { show(nav.dataset.view); try { if (nav.dataset.view === 'projects') await library(); if (nav.dataset.view === 'settings') await settings(); if (nav.dataset.view === 'sources') await sources(); } catch (error) { message(error.message); } });
50
+ $('#back').addEventListener('click', () => show('projects')); $('#search').addEventListener('input', () => library().catch(error => message(error.message)));
51
+ for (const [id, path] of [['budget-form', '/api/budget'], ['providers-form', '/api/providers']]) $( `#${id}` ).addEventListener('submit', async event => { event.preventDefault(); const form = event.currentTarget, values = Object.fromEntries(new FormData(form)); if (id === 'budget-form') { values.monthlyUsd = Number(values.monthlyUsd); values.perProjectUsd = Number(values.perProjectUsd); } try { await api(path, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'bstudio' }, body: JSON.stringify(values) }); message('Settings saved.'); await settings(); } catch (error) { message(error.message); } });
52
+ Promise.all([library(), settings()]).catch(error => message(error.message));
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Blast Studio</title><link rel="stylesheet" href="/app.css"><script defer src="/app.js"></script></head>
3
+ <body><header class="top"><div class="wordmark"><span class="mark" aria-hidden="true">B</span><span>Blast Studio <small>Workspace</small></span></div><span class="local">Local workspace</span></header>
4
+ <div class="layout"><aside><nav aria-label="Workspace"><button class="nav active" data-view="projects">Projects</button><button class="nav" data-view="settings">Budget &amp; providers</button><button class="nav" data-view="sources">Source updates</button></nav><p class="aside-note">Your work stays on this device.</p></aside>
5
+ <main><div id="message" role="status" aria-live="polite"></div><section id="projects" class="view"><div class="section-head"><div><h1>Projects</h1><p>Everything you’re making, in one place.</p></div><label class="search">Search projects<input id="search" type="search" placeholder="Search by title, text or asset"></label></div><div class="list-head"><span>Project</span><span>Platforms</span><span>Assets</span></div><div id="project-list" class="project-list" aria-live="polite"></div></section>
6
+ <section id="project" class="view" hidden><button id="back" class="text-button">← All projects</button><div id="project-detail"></div></section>
7
+ <section id="settings" class="view" hidden><h1>Budget &amp; providers</h1><p>Manage spending limits and generation providers.</p><div class="settings-grid"><section class="panel"><h2>Monthly spending</h2><div id="spend"></div><form id="budget-form"><label>Monthly cap (USD)<input name="monthlyUsd" type="number" min="0" step="any" required></label><label>Per-project cap (USD)<input name="perProjectUsd" type="number" min="0" step="any" required><small>Zero means no project limit.</small></label><button type="submit">Save budget</button></form><div id="provider-totals"></div></section><section class="panel"><h2>Providers</h2><p>Choose which services generate new assets.</p><form id="providers-form"><label>Images<select name="images"><option>none</option><option>gemini</option><option>openai</option><option>omp</option></select></label><label>Voice<select name="voice"><option>none</option><option>openai</option></select></label><button type="submit">Save providers</button></form></section></div></section>
8
+ <section id="sources" class="view" hidden><h1>Source updates</h1><p>Platform guidance and source health from the latest check.</p><div id="source-detail" class="panel"></div></section></main></div></body></html>
package/dist/env.js ADDED
@@ -0,0 +1,47 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ export function parseDotenv(text) {
4
+ const out = {};
5
+ for (const line of text.split(/\r?\n/)) {
6
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
7
+ if (!match)
8
+ continue;
9
+ let value = match[2].trim();
10
+ const quoted = value.match(/^(['"])(.*?)\1(?:\s*#.*)?\s*$/);
11
+ value = quoted ? quoted[2] : value.replace(/\s+#.*$/, "").trim();
12
+ out[match[1]] = value;
13
+ }
14
+ return out;
15
+ }
16
+ export function loadEnv(root, processEnv = process.env, keychain) {
17
+ const file = join(root, ".env");
18
+ const env = existsSync(file) ? parseDotenv(readFileSync(file, "utf8")) : {};
19
+ for (const [key, value] of Object.entries(processEnv))
20
+ if (value)
21
+ env[key] = value;
22
+ for (const key of ["GEMINI_API_KEY", "OPENAI_API_KEY"])
23
+ if (!env[key])
24
+ env[key] = keychain?.(key);
25
+ return env;
26
+ }
27
+ export function loadEnvWithSources(root, processEnv, keychain, keys) {
28
+ const file = join(root, ".env");
29
+ const fileEnv = existsSync(file) ? parseDotenv(readFileSync(file, "utf8")) : {};
30
+ const env = {};
31
+ const sources = {};
32
+ for (const key of keys) {
33
+ if (processEnv[key]) {
34
+ env[key] = processEnv[key];
35
+ sources[key] = "shell";
36
+ }
37
+ else if (fileEnv[key]) {
38
+ env[key] = fileEnv[key];
39
+ sources[key] = ".env";
40
+ }
41
+ else {
42
+ env[key] = keychain?.(key);
43
+ sources[key] = env[key] ? "keychain" : "unset";
44
+ }
45
+ }
46
+ return { env, sources };
47
+ }
package/dist/export.js ADDED
@@ -0,0 +1,110 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Ajv2020 } from 'ajv/dist/2020.js';
6
+ import { parse } from 'yaml';
7
+ import { readBrief } from "./brief.js";
8
+ import { runGates } from "./review/gates.js";
9
+ import { writeCampaignZip } from "./campaign-zip.js";
10
+ import { loadPacks } from "./packs.js";
11
+ import { loadPosts } from "./posts.js";
12
+ import { mediaContentHash, reviewHash } from "./review-hash.js";
13
+ import { UserError } from "./types.js";
14
+ const root = fileURLToPath(new URL('../', import.meta.url));
15
+ const schema = JSON.parse(readFileSync(join(root, 'schemas/manifest.v1.json'), 'utf8'));
16
+ const ajv = new Ajv2020({ allErrors: true });
17
+ ajv.addFormat('date-time', { type: 'string', validate: (s) => Number.isFinite(Date.parse(s)) });
18
+ const validate = ajv.compile(schema);
19
+ function sourceFile(project, path) {
20
+ if (!path || isAbsolute(path))
21
+ throw new UserError(`Invalid project media path: ${path}`);
22
+ try {
23
+ const base = realpathSync(project), file = realpathSync(resolve(base, path)), rel = relative(base, file);
24
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || !statSync(file).isFile())
25
+ throw new Error();
26
+ return file;
27
+ }
28
+ catch {
29
+ throw new UserError(`Invalid or missing project media: ${path}`);
30
+ }
31
+ }
32
+ function copyMedia(project, target, path) {
33
+ const source = sourceFile(project, path);
34
+ const name = join('media', createHash('sha256').update(path).digest('hex').slice(0, 16), basename(path));
35
+ const dest = join(target, name);
36
+ mkdirSync(dirname(dest), { recursive: true });
37
+ copyFileSync(source, dest);
38
+ return name.split(sep).join('/');
39
+ }
40
+ function handoff(project, post, name, notes, guide) {
41
+ const dir = join(project, 'exports', post.platform);
42
+ mkdirSync(dir, { recursive: true });
43
+ const media = post.media.map(item => ({ ...item, file: copyMedia(project, dir, item.file), ...(item.captions ? { captions: copyMedia(project, dir, item.captions) } : {}) }));
44
+ writeFileSync(join(dir, 'post.md'), [post.title ? `# ${post.title}\n` : '', post.body, ...(post.thread ?? []).map(t => `\n---\n\n${t}`)].join('\n') + '\n');
45
+ const checklist = guide.match(/## Checklist\s*\n([\s\S]*?)(?=\n## |$)/)?.[1]?.trim() ?? '';
46
+ const disclosures = Object.entries(post.disclosure ?? {}).map(([key, value]) => `- ${key}: ${value}`);
47
+ writeFileSync(join(dir, 'README.md'), [`# ${name} manual handoff`, '', '- [ ] Open the platform publishing interface and select the correct account.', '- [ ] Copy the text from post.md and attach the listed media.', '- [ ] Enter the provided alt text, captions and disclosure where applicable.', '- [ ] Review and publish manually, then record the URL with bstudio mark when supported.', '', '## Media', ...media.map(m => `- ${m.file} (${m.kind}; alt: ${m.alt})${'captions' in m && m.captions ? `; captions: ${m.captions}` : ''}`), '', '## Disclosure', ...(disclosures.length ? disclosures : ['- None specified.']), '', '## Platform notes', ...notes.map(n => `- ${n}`), '', '## Platform checklist', checklist, ''].join('\n'));
48
+ }
49
+ export function exportProject(project, slug, config, directory = false) {
50
+ const posts = loadPosts(project), packs = loadPacks(), briefSections = readBrief(project);
51
+ const assetsDir = join(project, 'assets');
52
+ const assets = existsSync(assetsDir) ? readdirSync(assetsDir).flatMap(id => {
53
+ const file = join(assetsDir, id, 'asset.yml');
54
+ return existsSync(file) ? [parse(readFileSync(file, 'utf8'))] : [];
55
+ }) : [];
56
+ if (!posts.size)
57
+ throw new UserError('No posts to export');
58
+ const prepared = [...posts.values()].map(post => {
59
+ let review;
60
+ try {
61
+ review = JSON.parse(readFileSync(join(project, 'reviews', `${post.platform}.json`), 'utf8'));
62
+ }
63
+ catch {
64
+ throw new UserError(`${post.platform}: review missing or invalid; re-run review`);
65
+ }
66
+ const requiredGates = ['policy', 'disclosure', 'specs', 'accessibility', 'fabricated-metrics', 'rights'];
67
+ if (!review || review.platform !== post.platform || !['pass', 'accepted'].includes(review.verdict) || !Array.isArray(review.gates) || review.gates.some(g => !g || g.pass !== true) || requiredGates.some(id => !review.gates.some(g => g.id === id)))
68
+ throw new UserError(`${post.platform}: review is not passing; re-run review`);
69
+ const hash = reviewHash({ ...post, media: post.media.map(m => ({ path: m.file, alt: m.alt })) });
70
+ if (hash !== review.postHash)
71
+ throw new UserError(`${post.platform}: review is stale; re-run review`);
72
+ if (review.mediaHash !== mediaContentHash(project, post.media))
73
+ throw new UserError(`${post.platform}: review media is stale; re-run review`);
74
+ const pack = packs.get(post.platform);
75
+ if (!pack)
76
+ throw new UserError(`${post.platform}: pack missing`);
77
+ if (runGates(post, pack, assets, briefSections, config, project).some(g => !g.pass))
78
+ throw new UserError(`${post.platform}: current gates failed; re-run review`);
79
+ for (const m of post.media) {
80
+ if ((m.cover !== undefined && typeof m.cover !== 'boolean') || (m.lang !== undefined && (typeof m.lang !== 'string' || !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(m.lang))) || (m.captions !== undefined && (m.kind !== 'video' || typeof m.captions !== 'string' || !/\.vtt$/i.test(m.captions))))
81
+ throw new UserError(`${post.platform}: invalid media metadata`);
82
+ sourceFile(project, m.file);
83
+ if (m.captions)
84
+ sourceFile(project, m.captions);
85
+ }
86
+ return { post, review, hash, pack };
87
+ });
88
+ if (!directory)
89
+ return writeCampaignZip(project, slug, prepared, sourceFile);
90
+ const dir = join(project, 'export');
91
+ mkdirSync(dir, { recursive: true });
92
+ const brief = readFileSync(join(project, 'brief.md'), 'utf8');
93
+ const entries = prepared.flatMap(({ post, review, hash, pack }) => {
94
+ const needsHandoff = !pack.marketBlaster || !!post.thread?.length || (post.platform === 'linkedin' && post.media.some(m => m.kind === 'document' && m.file.toLowerCase().endsWith('.pdf')));
95
+ if (needsHandoff)
96
+ handoff(project, post, pack.name, pack.notes ?? [], readFileSync(join(root, 'platforms', post.platform, 'guide.md'), 'utf8'));
97
+ if (!pack.marketBlaster)
98
+ return [];
99
+ const media = post.media.map(m => ({ path: copyMedia(project, dir, m.file), alt: m.alt, kind: m.kind,
100
+ ...(m.cover === undefined ? {} : { cover: m.cover }), ...(m.lang === undefined ? {} : { lang: m.lang }), ...(m.captions === undefined ? {} : { captions: copyMedia(project, dir, m.captions) }) }));
101
+ return [{ platform: post.platform, destination: pack.marketBlaster, ...(post.title === undefined ? {} : { title: post.title }), ...(post.tags === undefined ? {} : { tags: post.tags }), body: post.body, evidence: post.evidence,
102
+ ...(post.disclosure === undefined ? {} : { disclosure: post.disclosure }), media, ...(post.thread === undefined ? {} : { thread: post.thread }), review: { verdict: review.verdict, total: review.total, reviewHash: hash } }];
103
+ });
104
+ const manifest = { version: 1, slug, generatedAt: new Date().toISOString(), brief: 'brief.md', posts: entries };
105
+ if (!validate(manifest))
106
+ throw new UserError(`Invalid export manifest: ${ajv.errorsText(validate.errors)}`);
107
+ writeFileSync(join(dir, 'brief.md'), brief);
108
+ writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
109
+ return dir;
110
+ }
@@ -0,0 +1,64 @@
1
+ import { UserError } from "./types.js";
2
+ const MAX_BYTES = 2 * 1024 * 1024;
3
+ const TIMEOUT_MS = 15_000;
4
+ /** Fetch an external page as bounded, readable text. */
5
+ export async function fetchText(url, io) {
6
+ let parsed;
7
+ try {
8
+ parsed = new URL(url);
9
+ }
10
+ catch {
11
+ throw new UserError(`Invalid URL: ${url}`);
12
+ }
13
+ if (!["http:", "https:"].includes(parsed.protocol))
14
+ throw new UserError("URL must use HTTP or HTTPS");
15
+ const controller = new AbortController();
16
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
17
+ try {
18
+ const response = await io.fetch(parsed, { signal: controller.signal, headers: { accept: "text/html, text/plain;q=0.9" } });
19
+ if (!response.ok)
20
+ throw new UserError(`Fetching ${url} failed: HTTP ${response.status}`);
21
+ const length = Number(response.headers.get("content-length"));
22
+ if (length > MAX_BYTES)
23
+ throw new UserError(`Fetching ${url} exceeded the size limit`);
24
+ const reader = response.body?.getReader();
25
+ const chunks = [];
26
+ let size = 0;
27
+ if (reader) {
28
+ try {
29
+ while (true) {
30
+ const { done, value } = await reader.read();
31
+ if (done)
32
+ break;
33
+ size += value.byteLength;
34
+ if (size > MAX_BYTES) {
35
+ await reader.cancel();
36
+ throw new UserError(`Fetching ${url} exceeded the size limit`);
37
+ }
38
+ chunks.push(value);
39
+ }
40
+ }
41
+ finally {
42
+ reader.releaseLock();
43
+ }
44
+ }
45
+ const decoder = new TextDecoder();
46
+ let text = chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join("") + decoder.decode();
47
+ if ((response.headers.get("content-type") ?? "").includes("html") || /<\s*(?:html|body|p|div)\b/i.test(text)) {
48
+ text = text.replace(/<!--[\s\S]*?-->/g, " ")
49
+ .replace(/<(script|style|nav|noscript)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ")
50
+ .replace(/<[^>]*>/g, " ")
51
+ .replace(/&(?:nbsp|amp|lt|gt|quot|#39|#\d+|#x[\da-f]+);/gi, (entity) => {
52
+ const named = { "&nbsp;": " ", "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&#39;": "'" };
53
+ if (named[entity.toLowerCase()])
54
+ return named[entity.toLowerCase()];
55
+ const value = entity[2]?.toLowerCase() === "x" ? parseInt(entity.slice(3, -1), 16) : parseInt(entity.slice(2, -1), 10);
56
+ return Number.isFinite(value) && value > 0 && value <= 0x10ffff && !(value >= 0xd800 && value <= 0xdfff) ? String.fromCodePoint(value) : entity;
57
+ });
58
+ }
59
+ return text.replace(/\s+/g, " ").trim();
60
+ }
61
+ finally {
62
+ clearTimeout(timer);
63
+ }
64
+ }
package/dist/io.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { UserError } from "./types.js";
3
+ const security = (args, input) => execFileSync("security", args, {
4
+ encoding: "utf8", input, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
5
+ });
6
+ function guardTestRunner(runner) {
7
+ if (runner === security && process.env.NODE_TEST_CONTEXT)
8
+ throw new Error("Tests must inject a Keychain runner");
9
+ }
10
+ function available(platform) {
11
+ if (platform !== "darwin")
12
+ throw new UserError("macOS Keychain is unavailable; use a project .env file instead");
13
+ }
14
+ export function keychainGet(key, runner = security, platform = process.platform) {
15
+ available(platform);
16
+ guardTestRunner(runner);
17
+ try {
18
+ return runner(["find-generic-password", "-s", "blast-studio", "-a", key, "-w"])
19
+ .replace(/\r?\n$/, "") || undefined;
20
+ }
21
+ catch (err) {
22
+ if (typeof err === "object" && err !== null && "status" in err && err.status === 44)
23
+ return undefined;
24
+ throw new UserError(`Could not read ${key} from Keychain`);
25
+ }
26
+ }
27
+ export function keychainSet(key, value, runner = security, platform = process.platform) {
28
+ available(platform);
29
+ guardTestRunner(runner);
30
+ // security's interactive parser has a 4096-byte line buffer.
31
+ const command = `add-generic-password -U -s blast-studio -a ${JSON.stringify(key)} -T "" -X ${Buffer.from(value).toString("hex")}\n`;
32
+ if (Buffer.byteLength(command) >= 4096)
33
+ throw new UserError(`Could not save ${key} in Keychain: credential is too long`);
34
+ try {
35
+ // Hex avoids interpreting password quotes, backslashes or newlines as commands.
36
+ runner(["-i"], command);
37
+ }
38
+ catch {
39
+ throw new UserError(`Could not save ${key} in Keychain`);
40
+ }
41
+ }
@@ -0,0 +1,49 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { readBrief } from "./brief.js";
5
+ import { loadPosts } from "./posts.js";
6
+ import { loadPacks, loadSources } from "./packs.js";
7
+ import { repoRoot } from "./updater/check.js";
8
+ const dirs = (path) => existsSync(path) ? readdirSync(path, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name).sort() : [];
9
+ export function projectDetails(config, slug) {
10
+ const dir = join(config.root, 'projects', slug);
11
+ const posts = [...loadPosts(dir).values()];
12
+ const reviewsDir = join(dir, 'reviews');
13
+ const reviews = existsSync(reviewsDir) ? readdirSync(reviewsDir).filter(f => f.endsWith('.json')).sort().map(f => JSON.parse(readFileSync(join(reviewsDir, f), 'utf8'))) : [];
14
+ const assets = dirs(join(dir, 'assets')).flatMap(id => {
15
+ const file = join(dir, 'assets', id, 'asset.yml');
16
+ return existsSync(file) ? [parse(readFileSync(file, 'utf8'))] : [];
17
+ });
18
+ const brief = join(dir, 'brief.md');
19
+ const marksFile = join(dir, 'published.json');
20
+ return { slug, created: statSync(dir).birthtime.toISOString(), inputs: existsSync(brief) ? readBrief(dir).map(s => s.title) : [], posts, reviews, assets, exported: existsSync(join(dir, 'export', 'manifest.json')), published: existsSync(marksFile) ? JSON.parse(readFileSync(marksFile, 'utf8')) : [] };
21
+ }
22
+ export function loadLibrary(config, query = '') {
23
+ const needle = query.toLocaleLowerCase();
24
+ return dirs(join(config.root, 'projects')).map(slug => projectDetails(config, slug)).filter(p => !needle || [p.slug, ...p.inputs, ...p.posts.flatMap(post => [post.title ?? '', post.body]), ...p.assets.map(a => a.kind)].some(s => s.toLocaleLowerCase().includes(needle)));
25
+ }
26
+ export function latestSources(config) {
27
+ const paths = [join(config.root, 'updates'), join(repoRoot, 'updates')];
28
+ const files = paths.flatMap(dir => existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('.md')).map(f => ({ name: f, path: join(dir, f) })) : []).sort((a, b) => b.name.localeCompare(a.name));
29
+ const manual = new Set(loadSources().filter(source => source.detector.kind === 'manual').map(source => source.id));
30
+ const unverified = [];
31
+ function visit(value, path) {
32
+ if (!value || typeof value !== 'object')
33
+ return;
34
+ if (!Array.isArray(value) && 'source' in value && typeof value.source === 'string' && !manual.has(value.source) && !('verified' in value))
35
+ unverified.push(path);
36
+ if (!Array.isArray(value) && 'aiSource' in value && typeof value.aiSource === 'string' && !manual.has(value.aiSource) && !('aiLastVerified' in value))
37
+ unverified.push(`${path}.ai`);
38
+ for (const [key, child] of Object.entries(value))
39
+ visit(child, `${path}.${key}`);
40
+ }
41
+ for (const [id, pack] of loadPacks())
42
+ visit(pack, id);
43
+ if (!files.length)
44
+ return { lastCheck: null, changed: [], failed: [], unverified, report: '' };
45
+ const report = readFileSync(files[0].path, 'utf8');
46
+ const rows = report.split(/\r?\n/);
47
+ const find = (word) => rows.filter(line => new RegExp(`^## .*: ${word}\\s*$`, 'i').test(line));
48
+ return { lastCheck: files[0].name.replace(/\.md$/, ''), changed: find('changed'), failed: find('failed'), unverified, report };
49
+ }