create-pmos 0.382.0 → 0.384.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.
Files changed (32) hide show
  1. package/package.json +30 -35
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/REMOTE.md +39 -0
  7. package/workspace/briefing-premium-initiative-test.js +9 -0
  8. package/workspace/briefing-premium-test.js +1 -1
  9. package/workspace/changelog.json +29 -0
  10. package/workspace/guide/briefing-premium.md +6 -1
  11. package/workspace/lib/lead-cli.js +63 -0
  12. package/workspace/lib/my-work-premium.js +29 -3
  13. package/workspace/lib/pmos-verbs.js +3 -0
  14. package/workspace/lib/popup-leads.js +68 -0
  15. package/workspace/lib/routes-briefing-premium.js +4 -1
  16. package/workspace/lib/routes-pm-items.js +5 -2
  17. package/workspace/lib/share-store.js +150 -0
  18. package/workspace/lib/work-assigned.js +12 -1
  19. package/workspace/package-lock.json +2 -2
  20. package/workspace/package.json +1 -1
  21. package/workspace/premium-viewer-share-test.js +208 -0
  22. package/workspace/public/pm/premium-shell.js +19 -0
  23. package/workspace/public/pm/premium-vw-doc.css +30 -0
  24. package/workspace/public/pm/premium-vw-file.js +22 -10
  25. package/workspace/public/pm/premium-vw-share.js +112 -0
  26. package/workspace/public/pm/premium-work.js +18 -3
  27. package/workspace/public/pm/premium.css +11 -0
  28. package/workspace/public/pm/premium.js +3 -1
  29. package/workspace/server.js +65 -0
  30. package/workspace/share-server.js +135 -0
  31. package/workspace/test-lists/popup-context.json +5 -0
  32. package/workspace/test-lists/premium-viewer-share.json +5 -3
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ /* share-store.js — the copies a share link serves (premium-viewer-share slice 2, D97). The workspace server writes them on the PM's press; the share
3
+ * server (share-server.js) reads them and counts views and wrong passwords. Nothing else reads or writes this folder.
4
+ *
5
+ * THE FOLDER. `<runtime state>/shares/<id>/`, in the per-user runtime directory outside every repository, mode 0700:
6
+ * meta.json { id, name, kind, made, ends, pw: 'scrypt$<salt>$<hash>' | null, key, views, last, fails, lockedUntil } mode 0600
7
+ * page.html the copy as a page: an .html file as it is, markdown rendered by the caller, other text in a <pre> mode 0600
8
+ * file the file's own text, for the guest's Download mode 0600
9
+ * id is 128 random bits (base64url, 22 characters). `key` is a random secret per link that signs the guest's cookie. No IP address,
10
+ * header or user agent is stored (D08): a view is a count and a time.
11
+ *
12
+ * create(dir, { name, kind, page, file, days, password, now }) -> { ok, id, ends } | { ok: false, error }
13
+ * list(dir, now) -> [{ id, name, ends, made, views, last, pw }] the newest first; ended links are deleted on the way
14
+ * get(dir, id, now) -> meta | null null for an unknown, malformed or ended id (an ended one is deleted)
15
+ * remove(dir, id) -> boolean
16
+ * checkPassword(dir, id, given, now) -> { ok } | { ok: false, locked, left, until } five wrong tries lock the link for 15 minutes
17
+ * sign(meta, until) · verifyCookie(meta, value, now) the guest's cookie for one link
18
+ * view(dir, id, now) count one view
19
+ * newPassword() three words and two digits, from crypto.randomInt
20
+ */
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const crypto = require('crypto');
24
+
25
+ const DAYS = [1, 7, 30];
26
+ const MAX_TRIES = 5;
27
+ const LOCK_MS = 15 * 60 * 1000;
28
+ const COOKIE_MS = 12 * 60 * 60 * 1000;
29
+ const ID_RX = /^[A-Za-z0-9_-]{22}$/;
30
+ const WORDS = ('amber anchor apple arrow aspen atlas basil beacon birch bison blossom border breeze brook cabin cactus canyon cedar chalk cherry cliff clover '
31
+ + 'cobalt comet coral cotton crane crystal dawn delta desert dune eagle ember falcon fern field flint forest fossil garden ginger glacier granite '
32
+ + 'harbor hazel heron hollow honey island ivory jasmine juniper kettle lagoon lantern lemon lily linen lotus maple marble meadow mesa mint '
33
+ + 'moss nectar oak ocean olive onyx orbit orchid otter pebble pepper pine planet plum pond poppy prairie quartz quill rain raven reef '
34
+ + 'ridge river robin saffron sage salt sand shore silver slate spruce stone summit sun swan thistle thunder tide timber topaz tulip '
35
+ + 'valley velvet violet walnut willow winter wren yarrow zephyr').split(' ');
36
+
37
+ const root = (dir) => path.join(dir, 'shares');
38
+ const at = (dir, id) => path.join(root(dir), id);
39
+ function writeFile(p, data) {
40
+ const tmp = p + '.' + process.pid + '.' + crypto.randomBytes(4).toString('hex') + '.tmp';
41
+ fs.writeFileSync(tmp, data, { mode: 0o600 });
42
+ fs.renameSync(tmp, p);
43
+ }
44
+ function readMeta(dir, id) {
45
+ if (!ID_RX.test(String(id || ''))) return null;
46
+ try { const st = fs.lstatSync(at(dir, id)); if (!st.isDirectory()) return null; return JSON.parse(fs.readFileSync(path.join(at(dir, id), 'meta.json'), 'utf8')); }
47
+ catch { return null; }
48
+ }
49
+ function writeMeta(dir, m) { writeFile(path.join(at(dir, m.id), 'meta.json'), JSON.stringify(m)); }
50
+
51
+ function hashPassword(pw, salt = crypto.randomBytes(16)) {
52
+ const h = crypto.scryptSync(String(pw), salt, 32, { N: 16384, r: 8, p: 1 });
53
+ return 'scrypt$' + salt.toString('base64') + '$' + h.toString('base64');
54
+ }
55
+ function samePassword(stored, given) {
56
+ const [kind, s, h] = String(stored || '').split('$');
57
+ if (kind !== 'scrypt' || !s || !h) return false;
58
+ const want = Buffer.from(h, 'base64');
59
+ const got = crypto.scryptSync(String(given), Buffer.from(s, 'base64'), want.length, { N: 16384, r: 8, p: 1 });
60
+ return got.length === want.length && crypto.timingSafeEqual(got, want);
61
+ }
62
+ function newPassword() {
63
+ const w = () => WORDS[crypto.randomInt(WORDS.length)];
64
+ return `${w()}-${w()}-${w()}-${String(crypto.randomInt(100)).padStart(2, '0')}`;
65
+ }
66
+
67
+ function create(dir, o = {}) {
68
+ const days = Number(o.days);
69
+ if (!DAYS.includes(days)) return { ok: false, error: 'days must be 1, 7 or 30' };
70
+ if (!['html', 'markdown', 'text'].includes(o.kind)) return { ok: false, error: 'kind must be html, markdown or text' };
71
+ if (typeof o.page !== 'string' || typeof o.file !== 'string') return { ok: false, error: 'there is nothing to share' };
72
+ if (o.password != null) {
73
+ const p = String(o.password);
74
+ if (p.length < 8 || p.length > 128) return { ok: false, error: 'the password needs 8 to 128 characters' };
75
+ }
76
+ const now = o.now || Date.now();
77
+ const id = crypto.randomBytes(16).toString('base64url');
78
+ const name = String(o.name || 'file').replace(/[\\/\r\n\0]/g, '-').slice(0, 160);
79
+ const meta = { id, name, kind: o.kind, made: new Date(now).toISOString(), ends: new Date(now + days * 86400000).toISOString(),
80
+ pw: o.password == null ? null : hashPassword(o.password), key: crypto.randomBytes(32).toString('base64'), views: 0, last: null, fails: 0, lockedUntil: null };
81
+ try {
82
+ fs.mkdirSync(root(dir), { recursive: true, mode: 0o700 });
83
+ fs.mkdirSync(at(dir, id), { mode: 0o700 });
84
+ writeFile(path.join(at(dir, id), 'page.html'), o.page);
85
+ writeFile(path.join(at(dir, id), 'file'), o.file);
86
+ writeMeta(dir, meta);
87
+ } catch (e) {
88
+ remove(dir, id);
89
+ return { ok: false, error: 'the copy could not be saved (' + String((e && e.code) || 'write failed') + ')' };
90
+ }
91
+ return { ok: true, id, ends: meta.ends };
92
+ }
93
+ function remove(dir, id) {
94
+ if (!ID_RX.test(String(id || ''))) return false;
95
+ try { fs.rmSync(at(dir, id), { recursive: true, force: true }); return true; } catch { return false; }
96
+ }
97
+ const ended = (m, now) => !m || !m.ends || Date.parse(m.ends) <= now;
98
+ function get(dir, id, now = Date.now()) {
99
+ const m = readMeta(dir, id);
100
+ if (!m) return null;
101
+ if (ended(m, now)) { remove(dir, id); return null; }
102
+ return m;
103
+ }
104
+ function list(dir, now = Date.now()) {
105
+ let ids = [];
106
+ try { ids = fs.readdirSync(root(dir)).filter((x) => ID_RX.test(x)); } catch { return []; }
107
+ const out = [];
108
+ for (const id of ids) {
109
+ const m = get(dir, id, now);
110
+ if (m) out.push({ id: m.id, name: m.name, kind: m.kind, made: m.made, ends: m.ends, views: m.views || 0, last: m.last || null, pw: !!m.pw });
111
+ }
112
+ return out.sort((a, b) => String(b.made).localeCompare(String(a.made)));
113
+ }
114
+ function readPart(dir, id, part) {
115
+ if (!['page.html', 'file'].includes(part) || !ID_RX.test(String(id || ''))) return null;
116
+ try { return fs.readFileSync(path.join(at(dir, id), part), 'utf8'); } catch { return null; }
117
+ }
118
+ function checkPassword(dir, id, given, now = Date.now()) {
119
+ const m = get(dir, id, now);
120
+ if (!m || !m.pw) return { ok: false, locked: false, left: 0 };
121
+ if (m.lockedUntil && Date.parse(m.lockedUntil) > now) return { ok: false, locked: true, left: 0, until: m.lockedUntil };
122
+ if (samePassword(m.pw, String(given || '').slice(0, 256))) {
123
+ if (m.fails || m.lockedUntil) { m.fails = 0; m.lockedUntil = null; writeMeta(dir, m); }
124
+ return { ok: true };
125
+ }
126
+ m.fails = (m.lockedUntil && Date.parse(m.lockedUntil) <= now ? 0 : m.fails || 0) + 1;
127
+ m.lockedUntil = null;
128
+ if (m.fails >= MAX_TRIES) { m.fails = 0; m.lockedUntil = new Date(now + LOCK_MS).toISOString(); }
129
+ writeMeta(dir, m);
130
+ return m.lockedUntil ? { ok: false, locked: true, left: 0, until: m.lockedUntil } : { ok: false, locked: false, left: MAX_TRIES - m.fails };
131
+ }
132
+ function sign(m, until) {
133
+ const exp = String(Math.floor(until));
134
+ return exp + '.' + crypto.createHmac('sha256', Buffer.from(m.key, 'base64')).update(m.id + '.' + exp).digest('base64url');
135
+ }
136
+ function verifyCookie(m, value, now = Date.now()) {
137
+ const [exp, sig] = String(value || '').split('.');
138
+ if (!/^\d{10,16}$/.test(exp || '') || !sig || Number(exp) <= now) return false;
139
+ const want = Buffer.from(sign(m, Number(exp)).split('.')[1]), got = Buffer.from(sig);
140
+ return want.length === got.length && crypto.timingSafeEqual(want, got);
141
+ }
142
+ function view(dir, id, now = Date.now()) {
143
+ const m = get(dir, id, now);
144
+ if (!m) return;
145
+ m.views = (m.views || 0) + 1; m.last = new Date(now).toISOString();
146
+ try { writeMeta(dir, m); } catch { /* a missed count is not worth a failed page */ }
147
+ }
148
+
149
+ module.exports = { create, list, get, remove, readPart, checkPassword, sign, verifyCookie, view, newPassword, hashPassword, samePassword,
150
+ DAYS, MAX_TRIES, LOCK_MS, COOKIE_MS, ID_RX };
@@ -125,6 +125,17 @@ function findBriefItem(readBrief, id, nowMs, days = 7) {
125
125
  return null;
126
126
  }
127
127
 
128
+ /** The context a brief item carries, for the popup of the Work item made from it: why now, the source, who asked, where,
129
+ * their words, the conversation and the link. Only the fields the brief gave. */
130
+ function briefContext(x) {
131
+ if (!x) return null;
132
+ const o = {};
133
+ for (const k of ['why_now', 'evidence', 'source', 'who', 'where', 'about', 'ask', 'quote', 'link', 'todo']) if (typeof x[k] === 'string' && x[k].trim()) o[k] = x[k];
134
+ if (Array.isArray(x.thread) && x.thread.length) o.thread = x.thread.slice(0, 4).map((m) => ({ who: m.who || null, at: m.at || null, text: String(m.text || '') }));
135
+ if (Array.isArray(x.refs) && x.refs.length) o.refs = x.refs.slice(0, 3).map((r) => ({ label: r.label, source: r.source || null, link: r.link || null, lines: (r.lines || []).slice(0, 5) }));
136
+ return Object.keys(o).length ? o : null;
137
+ }
138
+
128
139
  function fromBrief(brief, todayIso, run = null) {
129
140
  if (!brief || brief.date !== todayIso) return [];
130
141
  const list = [...(Array.isArray(brief.priorities) ? brief.priorities : []), ...(Array.isArray(brief.items) ? brief.items : [])];
@@ -160,4 +171,4 @@ function overlay(item, byId) {
160
171
  return out;
161
172
  }
162
173
 
163
- module.exports = { fromMyWork, fromBrief, addable, createdEvent, overlay, agentOf, briefAgent, briefSuggest, briefDraftSpec, taskAgent, localTaskId, localOffer, localSuggest, localDraftSpec, localAgent, runWith, recentRuns, recentDates, findBriefItem, AGENT };
174
+ module.exports = { fromMyWork, fromBrief, addable, createdEvent, overlay, agentOf, briefAgent, briefSuggest, briefDraftSpec, taskAgent, localTaskId, localOffer, localSuggest, localDraftSpec, localAgent, runWith, recentRuns, recentDates, findBriefItem, briefContext, AGENT };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.382.0",
3
+ "version": "0.384.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.382.0",
9
+ "version": "0.384.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.382.0",
3
+ "version": "0.384.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -0,0 +1,208 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-viewer-share-test.js — share links from the viewer (premium-viewer-share slice 2, D97; PM 2026-10-21: "share (no need login to cloudflare,
4
+ * but I can set password)"). lib/share-store.js keeps the copies, POST /api/shares makes one on a page press, share-server.js serves them.
5
+ * K1 the store: 22-character ids, a scrypt hash and never the password, five wrong tries lock for 15 minutes, a link past its end is deleted,
6
+ * the cookie is signed per link and a changed one fails
7
+ * K2 the routes: an agent session and a request without the page's press headers are refused; a file with a secret is refused and the answer
8
+ * names the rule only; 1, 7 or 30 days only; a made link is listed with its password flag and no hash
9
+ * K3 the share server: the password page names neither the file nor PMOS; a wrong password counts down, five lock, the right one opens; the copy
10
+ * is under a sandbox CSP; Download gives the file's own text; every answer is noindex, no-store, no-referrer; any other path is 404
11
+ * K4 Turn off deletes the copy and the link answers "no longer active"; the workspace server refuses the share hostname
12
+ * K5 the page: the share icon opens the popover with a generated password and 7 days; Create link shows the link; a guest opens it with the
13
+ * password in a browser; Turn off asks once more, then removes it; at 390 the popover is a sheet that fits
14
+ * PMOS_SHOTS=<dir> also saves the popover at 1280 and 390, light and dark, and the guest's pages. */
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const http = require('http');
19
+ const { spawn } = require('child_process');
20
+ const { findBrowser } = require('./lib/find-browser');
21
+ const T = require('./test-run').configure({ name: 'premium-viewer-share' });
22
+ const store = require('./lib/share-store');
23
+
24
+ const BASE = T.BASE;
25
+ const SHARE_PORT = T.port();
26
+ const SBASE = `http://127.0.0.1:${SHARE_PORT}`;
27
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
29
+ const results = [];
30
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
31
+ let srv = null; let browser = null;
32
+ const REPO = path.resolve(__dirname, '..');
33
+ const SECRET_REL = `workspace/.share-test-${process.pid}.md`;
34
+ const finish = async (code) => {
35
+ if (browser) await browser.close().catch(() => {});
36
+ if (srv) { try { srv.kill('SIGTERM'); } catch { /* gone */ } }
37
+ try { fs.unlinkSync(path.join(REPO, SECRET_REL)); } catch { /* not made */ }
38
+ T.killTmux();
39
+ const bad = results.filter((x) => !x.cond).length;
40
+ console.log(`\n${results.length - bad}/${results.length} premium-viewer-share assertions passed`);
41
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
42
+ };
43
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
44
+ const req = (url, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve) => {
45
+ const u = new URL(url);
46
+ const r = http.request({ host: u.hostname, port: u.port, path: u.pathname + u.search, method, headers }, (res) => {
47
+ const parts = []; res.on('data', (c) => parts.push(c)); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(parts).toString('utf8') }));
48
+ });
49
+ r.on('error', (e) => resolve({ status: 0, headers: {}, text: String(e) }));
50
+ if (body) r.write(body);
51
+ r.end();
52
+ });
53
+ const PRD = 'planning/prd/premium-viewer-share-prd.md';
54
+ const SHOTS = process.env.PMOS_SHOTS || '';
55
+
56
+ (async () => {
57
+ // K1 the store, on its own folder
58
+ {
59
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'share-store-'));
60
+ const now = Date.parse('2026-10-21T10:00:00Z');
61
+ const a = store.create(dir, { name: 'n.md', kind: 'markdown', page: '<p>x</p>', file: '# x', days: 7, password: 'cedar-river-tulip-07', now });
62
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8'));
63
+ ok('K1 a link has a 22-character id and ends 7 days on', a.ok && store.ID_RX.test(a.id) && a.ends === '2026-10-28T10:00:00.000Z', JSON.stringify(a));
64
+ ok('K1 the password is kept as a scrypt hash, never as itself', /^scrypt\$/.test(meta.pw) && !fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8').includes('cedar-river'));
65
+ ok('K1 only 1, 7 or 30 days, and a password of 8 or more', !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 365 }).ok && !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 7, password: 'short' }).ok);
66
+ const tries = [1, 2, 3, 4, 5].map(() => store.checkPassword(dir, a.id, 'wrong', now));
67
+ ok('K1 wrong tries count down and the fifth locks the link', tries.slice(0, 4).map((t) => t.left).join() === '4,3,2,1' && tries[4].locked, JSON.stringify(tries));
68
+ ok('K1 while locked even the right password is refused', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + 60000).locked);
69
+ ok('K1 after 15 minutes the right password opens', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + store.LOCK_MS + 1000).ok);
70
+ const m = store.get(dir, a.id, now), c = store.sign(m, now + 1000);
71
+ ok('K1 the cookie is signed for this link, and a changed or late one fails', store.verifyCookie(m, c, now) && !store.verifyCookie(m, c.slice(0, -2) + 'xx', now) && !store.verifyCookie(m, c, now + 2000));
72
+ ok('K1 a link past its end is gone from the list and the disk', store.list(dir, now + 8 * 86400000).length === 0 && !fs.existsSync(path.join(dir, 'shares', a.id)));
73
+ ok('K1 a password is three words and two digits', /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(store.newPassword()));
74
+ fs.rmSync(dir, { recursive: true, force: true });
75
+ }
76
+
77
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore',
78
+ env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SHARE_PORT: String(SHARE_PORT), PMOS_SHARE_HOST: 'share.example.test' }) });
79
+ await T.waitForServer(BASE);
80
+ const H = await T.pressHeaders(BASE);
81
+ const post = (p, body, extra = {}) => req(BASE + p, { method: 'POST', headers: { ...H, ...extra }, body: JSON.stringify(body) });
82
+
83
+ // K2 the routes
84
+ {
85
+ ok('K2 a POST without the page\'s press headers is refused', (await req(BASE + '/api/shares', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: PRD, days: 7 }) })).status === 403);
86
+ ok('K2 an agent session cannot make a link', (await post('/api/shares', { path: PRD, days: 7 }, { 'x-pmos-session': 'sess-1' })).status === 403);
87
+ fs.writeFileSync(path.join(REPO, SECRET_REL), '# Keys\n\naws ' + 'AKIA' + 'ABCDEFGHIJKLMNOP' + ' here\n');
88
+ const sec = await post('/api/shares', { path: SECRET_REL, days: 7, password: null });
89
+ ok('K2 a file with a secret is refused, naming the rule and not the text', sec.status === 422 && /aws-access-key/.test(sec.text) && !/AKIAABCD/.test(sec.text), sec.status + ' ' + sec.text);
90
+ ok('K2 only 1, 7 or 30 days', (await post('/api/shares', { path: PRD, days: 3, password: null })).status === 400);
91
+ ok('K2 a path outside the workspace is not shared', (await post('/api/shares', { path: '../../../etc/hosts', days: 7 })).status === 404);
92
+ }
93
+ const PASS = 'harbor-maple-quartz-42';
94
+ const mk = await post('/api/shares', { path: PRD, days: 7, password: PASS });
95
+ const made = JSON.parse(mk.text || '{}');
96
+ ok('K2 a link is made, on the share hostname', mk.status === 200 && made.ok && /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(made.url), mk.text);
97
+ const listed = JSON.parse((await req(BASE + '/api/shares')).text || '{}');
98
+ const row = (listed.shares || []).find((x) => x.id === made.id);
99
+ ok('K2 the list shows it with its password flag and no hash or key', row && row.pw === true && row.views === 0 && !('key' in row) && !/scrypt/.test(JSON.stringify(listed)) && listed.host === 'share.example.test', JSON.stringify(listed));
100
+ const pw = JSON.parse((await req(BASE + '/api/shares/password')).text || '{}');
101
+ ok('K2 the page can ask for a generated password', pw.ok && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(pw.password));
102
+
103
+ // K3 the share server
104
+ const up = await until(async () => (await req(SBASE + '/robots.txt')).status === 200, 10000, 200);
105
+ ok('K3 the share server starts on its own loopback port once a link exists', !!up);
106
+ const S = '/s/' + made.id;
107
+ const lock = await req(SBASE + S);
108
+ const hdr = (r) => r.headers['x-robots-tag'] === 'noindex, nofollow, noarchive' && /no-store/.test(r.headers['cache-control'] || '') && r.headers['referrer-policy'] === 'no-referrer';
109
+ ok('K3 the password page names neither the file nor PMOS', lock.status === 200 && /This page is protected/.test(lock.text) && !/premium-viewer-share|PMOS|Download and share/.test(lock.text), lock.text.slice(0, 200));
110
+ ok('K3 every answer is noindex, no-store and no-referrer', hdr(lock) && hdr(await req(SBASE + '/nope')) && hdr(await req(SBASE + '/robots.txt')));
111
+ ok('K3 robots.txt disallows everything', (await req(SBASE + '/robots.txt')).text === 'User-agent: *\nDisallow: /\n');
112
+ ok('K3 the copy and the file stay closed without the password', (await req(SBASE + S + '/view')).status === 404 && (await req(SBASE + S + '/file')).status === 404);
113
+ const form = (p) => req(SBASE + S, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'pw=' + encodeURIComponent(p) });
114
+ const w1 = await form('nope');
115
+ ok('K3 a wrong password says how many tries are left', w1.status === 401 && /4 tries left/.test(w1.text), w1.status + ' ' + w1.text.slice(0, 300));
116
+ const right = await form(PASS);
117
+ const cookie = String((right.headers['set-cookie'] || [])[0] || '');
118
+ ok('K3 the right password sets a cookie for this link only', right.status === 303 && new RegExp(`Path=/s/${made.id}`).test(cookie) && /HttpOnly/.test(cookie) && /Secure/.test(cookie) && /Max-Age=43200/.test(cookie), cookie);
119
+ const C = { Cookie: cookie.split(';')[0] };
120
+ const page = await req(SBASE + S, { headers: C });
121
+ ok('K3 with the cookie the page frames the copy, with Download and the end date', page.status === 200 && /<iframe src="\/s\/[^"]+\/view"/.test(page.text) && /Download/.test(page.text) && /The link ends/.test(page.text), page.text.slice(0, 300));
122
+ const view = await req(SBASE + S + '/view', { headers: C });
123
+ ok('K3 the copy is under a sandbox CSP and holds the document\'s words', view.status === 200 && /^sandbox[;\s]/.test(view.headers['content-security-policy'] || '') && /default-src 'none'/.test(view.headers['content-security-policy']) && /Download and share a file from the viewer/.test(view.text), view.headers['content-security-policy']);
124
+ const file = await req(SBASE + S + '/file', { headers: C });
125
+ ok('K3 Download gives the file\'s own text as an attachment', file.status === 200 && /attachment; filename="premium-viewer-share-prd\.md"/.test(file.headers['content-disposition'] || '') && file.text === fs.readFileSync(path.join(REPO, PRD), 'utf8'));
126
+ ok('K3 any other path is 404, including the workspace API', (await req(SBASE + '/')).status === 404 && (await req(SBASE + '/api/shares')).status === 404 && (await req(SBASE + '/s/short')).status === 404 && (await req(SBASE + '/premium.html')).status === 404);
127
+ for (let i = 0; i < 5; i++) await form('wrong-' + i);
128
+ const locked = await form(PASS);
129
+ ok('K3 five wrong tries lock the link, even for the right password', locked.status === 429 && /15 minutes/.test(locked.text), locked.status);
130
+ const views = (JSON.parse((await req(BASE + '/api/shares')).text).shares || []).find((x) => x.id === made.id);
131
+ ok('K3 a view is counted, with no address kept', views && views.views === 1 && !/127\.0\.0\.1/.test(fs.readFileSync(path.join(T.STATE_DIR, 'shares', made.id, 'meta.json'), 'utf8')), JSON.stringify(views));
132
+
133
+ // K4 Turn off, and the workspace refuses the share hostname
134
+ const off = await post('/api/shares/off', { id: made.id });
135
+ ok('K4 Turn off deletes the copy and the link says it is no longer active', off.status === 200 && !fs.existsSync(path.join(T.STATE_DIR, 'shares', made.id)) && /no longer active/.test((await req(SBASE + S)).text));
136
+ const wsHost = await req(BASE + '/api/shares', { headers: { Host: 'share.example.test' } });
137
+ ok('K4 the workspace server refuses a request for the share hostname', wsHost.status === 403, wsHost.status);
138
+
139
+ // K5 the page
140
+ const exe = findBrowser();
141
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the browser part cannot run'); return finish(1); }
142
+ let chromium;
143
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
144
+ browser = await chromium.launch({ executablePath: exe });
145
+ const open = async ({ w = 1280, h = 900, theme = 'light' } = {}) => {
146
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: theme });
147
+ const page = await ctx.newPage();
148
+ const errors = [];
149
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
150
+ await page.route('**/api/brief-page*', (r) => r.fulfill({ contentType: 'application/json', body: '{"ok":false,"error":"off in this suite"}' }));
151
+ await page.goto(BASE + '/premium.html?theme=' + theme);
152
+ await until(() => page.evaluate(() => !!document.querySelector('#dlg')), 15000);
153
+ await page.evaluate(async () => {
154
+ const Sh = await import('/pm/premium-shell.js');
155
+ Sh.openDlg({ eye: 'Your item', title: 'Share plan', say: 'The PRD is in the repo.', noteKey: null, pane: '<article class="paper doc"><p>Item record</p></article>', label: 'Item record' });
156
+ });
157
+ await page.evaluate((f) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'fpath'; b.dataset.file = f; b.textContent = f; document.querySelector('#dBody .stream').append(b); b.click(); }, PRD);
158
+ await until(() => page.$('#dOut .obody.vw:not([hidden]) [data-fsh]'), 10000);
159
+ return { ctx, page, errors };
160
+ };
161
+ const ICON = '#dOut .obody.vw:not([hidden]) [data-fsh]';
162
+ {
163
+ const { page, errors, ctx } = await open();
164
+ await page.click(ICON);
165
+ const st = await until(() => page.evaluate(() => { const m = document.querySelector('.vwshp'), i = m && m.querySelector('#vwsPass'); return i && i.value ? { pass: i.value, days: (m.querySelector('[data-days][aria-pressed="true"]') || {}).textContent, sw: m.querySelector('[data-sh="pw"]').getAttribute('aria-checked') } : null; }), 5000);
166
+ ok('K5 the share icon opens the popover: password on and filled, 7 days', st && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(st.pass) && st.days === '7 days' && st.sw === 'true', JSON.stringify(st));
167
+ if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await page.screenshot({ path: path.join(SHOTS, 'popover-1280-light.png') }); }
168
+ await page.click('.vwshp [data-sh="make"]');
169
+ const link = await until(() => page.evaluate(() => { const u = document.querySelector('.vwshp .vwsu'); return u ? u.textContent : null; }), 8000);
170
+ const pass = st && st.pass;
171
+ ok('K5 Create link shows the link on the share hostname', /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(link || ''), link);
172
+ const n = await page.evaluate(() => (document.querySelector('.vwshp .vwsh:last-of-type') || {}).textContent);
173
+ ok('K5 the open links list shows it', /Open links \(1\)/.test(await page.evaluate(() => document.querySelector('.vwshp').textContent)), n);
174
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, 'made-1280-light.png') });
175
+ // a guest, in another browser context, with no PMOS session
176
+ const g = await browser.newContext({ viewport: { width: 1000, height: 760 } });
177
+ const gp = await g.newPage();
178
+ await gp.goto(SBASE + new URL(link).pathname);
179
+ ok('K5 the guest sees the password page', /This page is protected/.test(await gp.textContent('body')));
180
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-lock.png') });
181
+ await gp.fill('input[name="pw"]', pass);
182
+ await gp.click('button[type="submit"]');
183
+ const fr = await until(async () => { const h = await gp.$('iframe'); const f = h && await h.contentFrame(); return f && /Download and share a file from the viewer/.test(await f.textContent('body').catch(() => '')) ? f : null; }, 8000);
184
+ ok('K5 with the password the guest reads the copy', !!fr);
185
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-page.png') });
186
+ await g.close();
187
+ const id = new URL(link).pathname.split('/').pop();
188
+ await page.click(`.vwshp [data-off="${id}"]`);
189
+ const sure = await page.textContent(`.vwshp [data-off="${id}"]`);
190
+ await page.click(`.vwshp [data-off="${id}"]`);
191
+ const gone = await until(() => page.evaluate((x) => !document.querySelector(`.vwshp [data-off="${x}"]`), id), 5000);
192
+ ok('K5 Turn off asks once more, then removes the link', sure === 'Sure? Turn off' && gone && !fs.existsSync(path.join(T.STATE_DIR, 'shares', id)), sure);
193
+ await page.keyboard.press('Escape');
194
+ ok('K5 Escape closes the popover', !(await page.$('.vwshp')));
195
+ ok('K5 no page errors', errors.length === 0, errors.join(' | '));
196
+ await ctx.close();
197
+ }
198
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const theme of ['light', 'dark']) {
199
+ const { page, ctx } = await open({ w, h, theme });
200
+ await page.click(ICON);
201
+ await until(() => page.evaluate(() => { const i = document.querySelector('.vwshp #vwsPass'); return i && i.value; }), 5000);
202
+ const geo = await page.evaluate(() => { const r = document.querySelector('.vwshp').getBoundingClientRect(); const b = document.querySelector('.vwshp [data-sh="make"]').getBoundingClientRect(); return { l: Math.round(r.left), r: Math.round(r.right), t: Math.round(r.top), b: Math.round(r.bottom), vw: innerWidth, vh: innerHeight, bh: Math.round(b.height), sx: document.documentElement.scrollWidth - innerWidth }; });
203
+ ok(`K5 at ${w} ${theme} the popover fits on screen${w < 700 ? ' as a sheet with 44 px targets' : ''}`, geo.l >= 0 && geo.r <= geo.vw && geo.t >= 0 && geo.b <= geo.vh && geo.sx <= 0 && (w >= 700 || (geo.bh >= 44 && geo.vh - geo.b < 40)), JSON.stringify(geo));
204
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `popover-${w}-${theme}.png`) });
205
+ await ctx.close();
206
+ }
207
+ return finish();
208
+ })();
@@ -440,9 +440,28 @@ function putHtml(el, html) {
440
440
  return true;
441
441
  }
442
442
  function clearHtml(el) { el.__h = undefined; el.classList.remove('still'); el.innerHTML = ''; }
443
+ /* popup context slice 3: Claude's lead for a popup, written ahead from stored reads, comes first. Refresh asks the popup's own
444
+ * session to write it again; nothing runs when the popup opens. */
445
+ const leadAsk = (key) => 'Refresh the short lead for this popup. In 1 to 3 sentences say why it matters now, what is asked or blocking, and what you would do. '
446
+ + 'Use only stored reads (pmos source show, the repository files) and say which. Save it with: pmos lead put --key ' + key + ' --text "<the lead>" --cite "<what you read, when>". Then give the lead here.';
447
+ const leadTime = (iso) => { const d = new Date(iso); if (Number.isNaN(d.getTime())) return ''; const p = (n) => String(n).padStart(2, '0'); return (d.toDateString() === new Date().toDateString() ? '' : d.getDate() + ' ' + d.toLocaleString('en-GB', { month: 'short' }) + ' ') + p(d.getHours()) + ':' + p(d.getMinutes()); };
448
+ function leadHtml(lead) {
449
+ if (!lead) return `<div class="plead none"><p class="fine2">No lead is written for this yet.</p><button type="button" class="xtb" data-lead="refresh">Write the lead</button></div>`;
450
+ return `<div class="plead"><p>${esc(lead.text)}</p><p class="fine2">Lead · written ${esc(leadTime(lead.at))}${lead.cites && lead.cites.length ? ' · from ' + esc(lead.cites.join('; ')) : ''}</p><button type="button" class="xtb" data-lead="refresh">Refresh</button></div>`;
451
+ }
452
+ function drawLead(box, th) {
453
+ if (!('lead' in th)) return;
454
+ let l = $('#leadT', box); if (!l) { box.insertAdjacentHTML('afterbegin', '<div id="leadT"></div>'); l = $('#leadT', box); }
455
+ putHtml(l, leadHtml(th.lead));
456
+ }
457
+ $('#dBody').addEventListener('click', async (e) => {
458
+ const b = e.target.closest('[data-lead="refresh"]'); if (!b || !S.key || !S.key.startsWith('pop:')) return;
459
+ b.disabled = true; await sendText(S.key, leadAsk(S.key));
460
+ });
443
461
  export function drawThread(th, key, conv) {
444
462
  if (S.key !== key) return;
445
463
  const box = $('#dBody .stream'); if (!box) return;
464
+ drawLead(box, th);
446
465
  let t = $('#thr', box); if (!t) { box.insertAdjacentHTML('beforeend', '<div id="thr"></div>'); t = $('#thr', box); }
447
466
  const b = $('#dBody'), atEnd = b.scrollHeight - b.scrollTop - b.clientHeight < 80;
448
467
  putHtml(t, threadHtml(th) + sessionHtml(conv, th.goal));
@@ -197,3 +197,33 @@
197
197
  iframe.vwprint{position:fixed;right:0;bottom:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none}
198
198
  @media (hover:hover){.vwib:hover{background:var(--well);color:var(--ink)}}
199
199
  @media (max-width:640px){.vwib{width:44px;height:44px}.vwdlm button{min-height:44px}}
200
+ /* the share popover (premium-viewer-share S1, S8, P1): under the icons on a desktop, a sheet at the bottom on a phone */
201
+ .vwshp{position:absolute;right:0;top:calc(100% + 4px);z-index:6;width:340px;max-width:min(340px,calc(100vw - 32px));padding:8px;border-radius:8px;background:var(--card-solid);border:1px solid var(--hair);box-shadow:var(--card-shadow);display:grid;gap:4px;font-size:var(--fs-2);color:var(--ink)}
202
+ .vwshp .i{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;color:var(--ink-3)}
203
+ .vwsh{font:500 var(--fs-1) var(--mono);letter-spacing:.08em;text-transform:uppercase;color:var(--ink-3);padding:6px 8px 2px}
204
+ .vwsm{display:flex;align-items:center;gap:10px;min-height:40px;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--ink);font:inherit;text-align:left;cursor:pointer}
205
+ .vwsm small{margin-left:auto;font:500 var(--fs-1) var(--mono);color:var(--ink-3)}
206
+ .vwsrow2{display:flex;align-items:center;gap:10px;min-height:40px;padding:2px 8px}.vwsrow2>span{flex:1}
207
+ .vwsw{position:relative;width:40px;height:24px;flex:none;border-radius:6px;border:1px solid var(--hair);background:var(--well);cursor:pointer;padding:0}
208
+ .vwsw::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:6px;background:var(--ink-3);transition:left .15s}
209
+ .vwsw[aria-checked="true"]{background:var(--ok);border-color:transparent}.vwsw[aria-checked="true"]::after{left:19px;background:var(--card-solid)}
210
+ .vwspwi{display:flex;gap:6px;padding:0 8px}.vwspwi input{flex:1;min-width:0;min-height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--hair);background:var(--well);color:var(--ink);font:500 var(--fs-2) var(--mono)}
211
+ .vwsn{margin:2px 8px;color:var(--ink-3);font-size:var(--fs-1);line-height:1.45}
212
+ .vwserr{margin:2px 8px;color:var(--bad);font-size:var(--fs-1);line-height:1.45}
213
+ .vwsgo{margin:4px 8px 4px;justify-content:center}
214
+ .vwssep{height:1px;background:var(--hair);margin:4px 4px}
215
+ .vwsrow{display:flex;align-items:center;gap:10px;padding:6px 8px}.vwsrow>span{flex:1;min-width:0}
216
+ .vwsrow b{display:block;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vwsrow em{font-style:normal;color:var(--ink-3);font-size:var(--fs-1)}
217
+ .vwsoff{flex:none;min-height:30px;padding:0 10px;border-radius:6px;border:1px solid var(--hair);background:transparent;color:var(--bad);font:500 var(--fs-1) var(--sans);cursor:pointer}
218
+ .vwslnk{margin:2px 8px 6px;padding:10px;border:1px solid var(--hair);border-radius:8px;display:grid;gap:8px}
219
+ .vwslnk code{font:500 var(--fs-1) var(--mono);overflow-wrap:anywhere;user-select:all}
220
+ .vwspw{display:flex;align-items:center;gap:8px}
221
+ .vwsr{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.vwsok{color:var(--ok);font-size:var(--fs-1)}
222
+ .vwslnk .vwsn{margin:0}
223
+ .vwshp :focus-visible{outline:2px solid var(--ember);outline-offset:2px}
224
+ @media (hover:hover){.vwsm:hover{background:var(--well)}}
225
+ @media (max-width:640px){
226
+ .vwshp{position:fixed;left:8px;right:8px;top:auto;bottom:calc(8px + env(safe-area-inset-bottom,0px));width:auto;max-width:none;max-height:80dvh;overflow:auto;border-radius:8px;z-index:60}
227
+ .vwsm,.vwsrow2,.vwsoff,.vwshp .vwseg,.vwsgo{min-height:44px}.vwsw{width:48px;height:30px}.vwsw::after{width:22px;height:22px}.vwsw[aria-checked="true"]::after{left:23px}
228
+ }
229
+ @media (prefers-reduced-motion:reduce){.vwsw::after{transition:none}}
@@ -5,6 +5,7 @@
5
5
  * changed, so a file Claude is still writing stays current. Nothing here writes.
6
6
  * A download icon sits at the right of the file's title (premium-viewer-share D1-D5): one format saves at once, more open a small menu with the original
7
7
  * first. The original is saved from the text already read; Word comes from GET /api/doc/export; PDF is the browser's print of the page, in a sandboxed frame.
8
+ * A share icon beside it opens the share popover (premium-vw-share.js: Send a copy on a phone, a public link with a password and an end date, open links).
8
9
  * openChatFile(path, { session, ws }) -> the tab's pane */
9
10
  import { vwOpen, vwStyle } from './premium-viewer.js';
10
11
  import { bodyHtml, pageHead, splitDoc, readMinutes } from './premium-vw-doc-model.js';
@@ -41,27 +42,35 @@ export function downloadsOf(f) {
41
42
  return [orig];
42
43
  }
43
44
  const DL_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg>';
45
+ const SH_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 15V4M8 8l4-4 4 4M6 12v7h12v-7"/></svg>';
44
46
  /** The title row: the name, and the download icon when the file was read. */
45
47
  function headHtml(f, title) {
46
48
  const n = downloadsOf(f).length;
47
- const dl = n ? `<div class="vwacts"><button type="button" class="vwib" data-fdl aria-label="Download${n > 1 ? '…' : ''}" title="Download"${n > 1 ? ' aria-haspopup="menu" aria-expanded="false"' : ''}>${DL_ICON}</button></div>` : '';
49
+ const dl = n ? `<div class="vwacts"><button type="button" class="vwib" data-fdl aria-label="Download${n > 1 ? '…' : ''}" title="Download"${n > 1 ? ' aria-haspopup="menu" aria-expanded="false"' : ''}>${DL_ICON}</button>`
50
+ + `<button type="button" class="vwib" data-fsh aria-label="Share…" title="Share" aria-haspopup="dialog" aria-expanded="false">${SH_ICON}</button></div>` : '';
48
51
  return `<header class="cfh vwfh"><h1 class="cft">${esc(title)}</h1>${dl}</header>`;
49
52
  }
50
53
  /** The MIME type the original is saved with. */
51
54
  export function mimeOf(f) { return isHtml(f) ? 'text/html' : f.kind === 'markdown' ? 'text/markdown' : 'text/plain'; }
52
- /** The page a PDF is printed from, as the srcdoc of a sandboxed frame: an .html file as it is, markdown as a clean page of its words.
53
- * It prints itself once it has loaded; the frame's CSP still blocks every network fetch. Pure. */
54
- export function printSrc(f) {
55
- const go = '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>';
55
+ /** A file as one standalone page, for the print frame and for a share link's copy (premium-viewer-share D3, S2): an .html file as it is, markdown as a
56
+ * clean page of its words, other text in a <pre>. With print, the page prints itself once it has loaded. The viewer's CSP always comes first. Pure. */
57
+ export function pageSrc(f, print = false) {
58
+ const go = print ? '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>' : '';
56
59
  if (isHtml(f)) return framedSrc(String(f.text || '') + go);
57
- const h = pageHead(f.text), sd = splitDoc(f.text);
58
- const body = bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
59
- // a plain document for the printer: the browser's own heading sizes and black text, no app colours (the frame cannot load the app's stylesheets)
60
- const css = 'body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
60
+ const title = f.kind === 'markdown' ? pageHead(f.text).title || f.name : f.name;
61
+ let body;
62
+ if (f.kind === 'markdown') {
63
+ const h = pageHead(f.text), sd = splitDoc(f.text);
64
+ body = `<h1>${esc(title)}</h1>` + bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
65
+ } else body = `<h1>${esc(title)}</h1><pre>${esc(f.text)}</pre>`;
66
+ // a plain document: the browser's own heading sizes and black on white, no app colours (the frame cannot load the app's stylesheets)
67
+ const css = ':root{color-scheme:light}body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
61
68
  + 'table{border-collapse:collapse;width:100%}th,td{border:1px solid;padding:5px 9px;text-align:left;vertical-align:top}'
62
69
  + 'pre,code{font:13px ui-monospace,Menlo,monospace;white-space:pre-wrap}img{max-width:100%}@page{margin:18mm}';
63
- return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc((h.title || f.name || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body><h1>${esc(h.title || f.name)}</h1>${body}${go}</body></html>`);
70
+ return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(String(title || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body>${body}${go}</body></html>`);
64
71
  }
72
+ /** The page a PDF is printed from, as the srcdoc of a sandboxed frame. Pure. */
73
+ export const printSrc = (f) => pageSrc(f, true);
65
74
  function saveBlob(text, name, type) {
66
75
  const url = URL.createObjectURL(new Blob([text], { type: type + ';charset=utf-8' }));
67
76
  const a = document.createElement('a'); a.href = url; a.download = name; a.hidden = true; document.body.append(a); a.click(); a.remove();
@@ -129,11 +138,14 @@ export function openChatFile(p, ctx = {}) {
129
138
  el.onclick = (e) => {
130
139
  const d = e.target.closest('[data-fdl]');
131
140
  if (d) { const opts = downloadsOf(st.f); if (opts.length === 1) download(st.f, opts[0].fmt); else dlMenu(d, opts); return; }
141
+ const sh = e.target.closest('[data-fsh]');
142
+ if (sh) { const k = sh.parentElement.querySelector('.vmenu'); if (k) k.remove(); import('./premium-vw-share.js').then((M) => M.shareMenu(sh, st.f)); return; }
132
143
  const b = e.target.closest('[data-fv]'); if (!b || b.dataset.fv === st.view) return; st.view = b.dataset.fv; draw();
133
144
  };
134
145
  };
135
146
  const dlMenu = (btn, opts) => {
136
147
  const box = btn.parentElement; let m = box.querySelector('.vmenu');
148
+ const sp = box.querySelector('.vwshp'); if (sp) { sp.remove(); const sb = box.querySelector('[data-fsh]'); if (sb) sb.setAttribute('aria-expanded', 'false'); }
137
149
  const close = (focus) => { const k = box.querySelector('.vmenu'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
138
150
  if (m) return close();
139
151
  m = document.createElement('div'); m.className = 'vmenu vwdlm'; m.setAttribute('role', 'menu'); m.setAttribute('aria-label', 'Download as'); m.dataset.escLayer = '1';