@hypersocial/decks-cli 0.9.28 → 0.9.30

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.
@@ -0,0 +1,145 @@
1
+ // What this CLI says when it, or the hyperdecks skill an agent reads, is behind.
2
+ //
3
+ // - The skill copies on this machine: every folder `skill install` writes
4
+ // (agentTable) plus any copy the install record knows. Local, no network.
5
+ // - A copy older than this CLI: run `hyperdecks skill install`. (The CLI
6
+ // refreshes the copies it wrote by itself; what is left is a copy edited by
7
+ // hand or one it could not write.) A copy that is a link: update what it
8
+ // points to. A copy that can't be read: reinstall it.
9
+ // - A copy newer than this CLI: a newer CLI wrote it, so this one is behind.
10
+ // - `--json` output carries these as `notices` (main() in commands.mjs), so an
11
+ // agent that never reads stderr still sees them.
12
+ import { realpathSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { isLinked, readSkill, recordedCopyPaths, SKILL_NAME } from "./skillFreshness.mjs";
16
+ import { compareVersions, parseVersion, UPGRADE, UPGRADE_COMMAND } from "./update.mjs";
17
+
18
+ export const SKILL_INSTALL = "hyperdecks skill install";
19
+
20
+ const real = (p) => {
21
+ try {
22
+ return realpathSync(p);
23
+ } catch {
24
+ return p;
25
+ }
26
+ };
27
+
28
+ // [{ agent, path, version, linked, target?, unreadable? }] for each hyperdecks
29
+ // skill copy found. `agents`: agentTable(...) rows ({ label, skills }). A copy
30
+ // two agents share (a link) is listed once, under the first agent. A SKILL.md
31
+ // that is there but can't be read, in an agent's hyperdecks folder, is listed
32
+ // with `unreadable` (why); another skill's SKILL.md is not ours and is skipped.
33
+ export function skillCopies({ agents = [], home = homedir() } = {}) {
34
+ const seen = new Set();
35
+ const out = [];
36
+ const add = (path, agent) => {
37
+ const r = readSkill(path);
38
+ if (r.state === "missing" || (r.state === "ok" && r.name !== SKILL_NAME)) return;
39
+ const key = real(path);
40
+ if (seen.has(key)) return;
41
+ seen.add(key);
42
+ const linked = isLinked(path);
43
+ out.push({
44
+ agent,
45
+ path,
46
+ version: r.state === "ok" ? r.version : null,
47
+ linked,
48
+ ...(linked ? { target: key } : {}),
49
+ ...(r.state === "unreadable" ? { unreadable: r.why } : {}),
50
+ });
51
+ };
52
+ for (const a of agents) add(join(a.skills, SKILL_NAME), a.label ?? a.id ?? null);
53
+ for (const p of recordedCopyPaths(home)) add(p, null);
54
+ return out;
55
+ }
56
+
57
+ const where = (copies) => copies.map((c) => c.path).join(", ");
58
+ // The lowest (or highest) version among copies; an unversioned copy counts as 0.0.0.
59
+ const pick = (copies, sign) => copies.map((c) => c.version ?? "0.0.0").reduce((a, b) => (compareVersions(b, a) * sign > 0 ? b : a));
60
+ // Can't be read, or says a version that isn't one ("banana").
61
+ const unreadable = (c) => !!c.unreadable || (!!c.version && !parseVersion(c.version));
62
+
63
+ // The notices the skill copies raise against this CLI's version, at most one
64
+ // of each kind:
65
+ // - skill-unreadable: a SKILL.md that can't be read (run skill install);
66
+ // - skill-link-unreadable: the same through a link (fix it where it points);
67
+ // - skill-behind: older copies the CLI may replace (run skill install);
68
+ // - skill-link-behind: an older copy that is a link, often into a repo
69
+ // checkout (skill install would replace the link): update what it points to;
70
+ // - cli-behind-skill: a newer copy, so a newer CLI is out (update the CLI).
71
+ export function skillNotices(version, copies) {
72
+ const notices = [];
73
+ const badLinks = copies.filter((c) => unreadable(c) && c.linked);
74
+ const bad = copies.filter((c) => unreadable(c) && !c.linked);
75
+ const ok = copies.filter((c) => !unreadable(c));
76
+ const older = ok.filter((c) => compareVersions(c.version ?? "0.0.0", version) < 0);
77
+ const behind = older.filter((c) => !c.linked);
78
+ const links = older.filter((c) => c.linked);
79
+ const ahead = ok.filter((c) => c.version && compareVersions(c.version, version) > 0);
80
+ if (bad.length) {
81
+ notices.push({
82
+ kind: "skill-unreadable",
83
+ cli: version,
84
+ paths: bad.map((c) => c.path),
85
+ run: SKILL_INSTALL,
86
+ message: `the hyperdecks skill at ${bad.map((c) => `${c.path} (${c.unreadable ?? `version "${c.version}" isn't a version`})`).join(", ")} can't be read: run \`${SKILL_INSTALL}\``,
87
+ });
88
+ }
89
+ if (badLinks.length) {
90
+ // A link: skill install would replace it, so the fix is where it points.
91
+ notices.push({
92
+ kind: "skill-link-unreadable",
93
+ cli: version,
94
+ paths: badLinks.map((c) => c.path),
95
+ targets: badLinks.map((c) => c.target),
96
+ message: `the hyperdecks skill at ${badLinks.map((c) => `${c.path} (a link to ${c.target}: ${c.unreadable ?? `version "${c.version}" isn't a version`})`).join(", ")} can't be read: fix it where it points (skill install would replace the link)`,
97
+ });
98
+ }
99
+ if (behind.length) {
100
+ const skill = pick(behind, -1);
101
+ notices.push({
102
+ kind: "skill-behind",
103
+ cli: version,
104
+ skill,
105
+ paths: behind.map((c) => c.path),
106
+ run: SKILL_INSTALL,
107
+ message: `the hyperdecks skill at ${where(behind)} is ${behind.every((c) => !c.version) ? "unversioned" : skill}, older than this CLI (${version}): run \`${SKILL_INSTALL}\``,
108
+ });
109
+ }
110
+ if (links.length) {
111
+ const skill = pick(links, -1);
112
+ notices.push({
113
+ kind: "skill-link-behind",
114
+ cli: version,
115
+ skill,
116
+ paths: links.map((c) => c.path),
117
+ targets: links.map((c) => c.target),
118
+ message: `the hyperdecks skill at ${links.map((c) => `${c.path} (a link to ${c.target})`).join(", ")} is ${skill}, older than this CLI (${version}): update it where it points (skill install would replace the link)`,
119
+ });
120
+ }
121
+ if (ahead.length) {
122
+ const skill = pick(ahead, 1);
123
+ notices.push({
124
+ kind: "cli-behind-skill",
125
+ cli: version,
126
+ skill,
127
+ paths: ahead.map((c) => c.path),
128
+ run: UPGRADE_COMMAND,
129
+ message: `hyperdecks ${version} is older than its skill at ${where(ahead)} (${skill}), so a newer CLI is out: ${UPGRADE}`,
130
+ });
131
+ }
132
+ return notices;
133
+ }
134
+
135
+ // One line for whoami and init: "0.9.29 (Claude Code, Codex)", grouped by version.
136
+ export function skillSummary(copies) {
137
+ if (!copies.length) return `not installed (\`${SKILL_INSTALL}\` adds it)`;
138
+ const groups = new Map();
139
+ for (const c of copies) {
140
+ const v = unreadable(c) ? "unreadable" : c.version ?? "unversioned";
141
+ if (!groups.has(v)) groups.set(v, []);
142
+ groups.get(v).push(`${c.agent ?? c.path}${c.linked ? `, a link to ${c.target}` : ""}`);
143
+ }
144
+ return [...groups].map(([v, names]) => `${v} (${names.join(", ")})`).join(", ");
145
+ }
package/src/ops.mjs CHANGED
@@ -1121,7 +1121,7 @@ export async function importDeckFromBytes(opts = {}, fields = {}, adapter = {})
1121
1121
  assets: parsed.assets.length,
1122
1122
  bytes: htmlBytes.byteLength,
1123
1123
  usesPlayer: player.usesPlayer,
1124
- warnings: player.usesPlayer ? [] : [importPlayerWarning(player.ownScript)],
1124
+ warnings: [...(parsed.warnings ?? []), ...(player.usesPlayer ? [] : [importPlayerWarning(player.ownScript)])],
1125
1125
  deployment: t.name,
1126
1126
  // The owner-facing dashboard view (Preview / Stats / Share / Present), not
1127
1127
  // the raw /d/<slug> storage redirect.
package/src/runtime.mjs CHANGED
@@ -1,15 +1,16 @@
1
1
  import { execFile, spawnSync } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { createServer } from "node:http";
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { ConvexHttpClient } from "convex/browser";
9
9
  import { makeFunctionReference } from "convex/server";
10
- import { recordSkillInstall } from "./skillFreshness.mjs";
10
+ import { recordSkillInstall, skillStamp } from "./skillFreshness.mjs";
11
+ import { compareVersions, parseVersion, UPGRADE } from "./update.mjs";
11
12
 
12
- export const VERSION = "0.9.28";
13
+ export const VERSION = "0.9.30";
13
14
 
14
15
  // Sent on the CLI's calls to our routes and to Convex, so the server can see
15
16
  // which CLI versions are still out there (not used to refuse anything).
@@ -553,6 +554,22 @@ export function installHyperdecksSkill(opts = {}, extraArgs = [], { spawn = spaw
553
554
  }
554
555
 
555
556
  const { agents, source } = chooseAgents(opts, extraArgs, { home, env });
557
+ // Never downgrade: a copy newer than this CLI came from a newer CLI, and it
558
+ // is also the only local sign that this one is old. --force does it anyway,
559
+ // after saving each newer copy (with any edits) as the refresh does.
560
+ const all = agentTable({ home, env });
561
+ const newer = (agents[0] === "*" ? all : all.filter((a) => agents.includes(a.id)))
562
+ .map((a) => ({ id: a.id, dir: join(a.skills, "hyperdecks"), version: skillStamp(join(a.skills, "hyperdecks"))?.version }))
563
+ .filter((c) => parseVersion(c.version) && compareVersions(c.version, VERSION) > 0);
564
+ if (newer.length && !opts.force) {
565
+ throw new Error(`the hyperdecks skill at ${newer.map((c) => `${c.dir} (${c.version})`).join(", ")} is newer than this CLI (${VERSION}), so installing would downgrade it. Update the CLI first (${UPGRADE}). --force installs ${VERSION} anyway, replacing that copy and any edits made to it (the old copy is saved to ~/.hyperdecks/skill-backups/)`);
566
+ }
567
+ for (const c of newer) {
568
+ const backup = join(home ?? homedir(), ".hyperdecks", "skill-backups", `${c.id}-${c.version}-${Date.now()}-${process.pid}`);
569
+ mkdirSync(dirname(backup), { recursive: true });
570
+ cpSync(c.dir, backup, { recursive: true });
571
+ if (!quiet) log(`saved the newer hyperdecks skill at ${c.dir} (${c.version}) to ${backup}`);
572
+ }
556
573
  if (source === "default" && !quiet) log(`no agent found in your home directory; installing for ${agents.join(", ")}`);
557
574
  const args = ["-y", "skills@latest", "add", PACKAGED_SKILLS_DIR, "-g"];
558
575
  args.push("-a", ...agents, "-s", "hyperdecks", "--copy", "-y", "--full-depth");
@@ -17,7 +17,7 @@ import { createHash } from "node:crypto";
17
17
  import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
18
  import { homedir } from "node:os";
19
19
  import { basename, dirname, join, relative } from "node:path";
20
- import { compareVersions, DAY_MS } from "./update.mjs";
20
+ import { compareVersions, DAY_MS, parseVersion } from "./update.mjs";
21
21
 
22
22
  export const SKILL_NAME = "hyperdecks";
23
23
 
@@ -39,23 +39,38 @@ export function skillHash(dir) {
39
39
  return h.digest("hex");
40
40
  }
41
41
 
42
- // The frontmatter of a SKILL.md: `name`, and `version` from `metadata.version`
43
- // (or a top-level `version`). Missing fields are null.
44
- export function skillStamp(dir) {
42
+ // What a skill folder's SKILL.md says: { state: "missing" } (no file),
43
+ // { state: "unreadable", why } (there, but it can't be read or has no
44
+ // frontmatter), or { state: "ok", name, version } where `version` comes from
45
+ // `metadata.version` (or a top-level `version`) and missing fields are null.
46
+ export function readSkill(dir) {
47
+ const file = join(dir, "SKILL.md");
45
48
  let text;
46
49
  try {
47
- text = readFileSync(join(dir, "SKILL.md"), "utf8");
48
- } catch {
49
- return null;
50
+ text = readFileSync(file, "utf8");
51
+ } catch (e) {
52
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return { state: "missing" };
53
+ return { state: "unreadable", why: e?.code ?? e?.message ?? String(e) };
50
54
  }
51
- const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
55
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
56
+ if (fm === undefined) return { state: "unreadable", why: "no frontmatter" };
52
57
  const field = (re) => re.exec(fm)?.[1]?.trim().replace(/^["']|["']$/g, "") ?? null;
58
+ const name = field(/^name:\s*(.+)$/m);
59
+ if (!name) return { state: "unreadable", why: "no name in its frontmatter" };
53
60
  return {
54
- name: field(/^name:\s*(.+)$/m),
55
- version: field(/^metadata:\s*\n(?:[ \t]+.*\n)*?[ \t]+version:\s*(.+)$/m) ?? field(/^version:\s*(.+)$/m),
61
+ state: "ok",
62
+ name,
63
+ // Indented lines and blank lines may sit between `metadata:` and `version:`.
64
+ version: field(/^metadata:[ \t]*\r?\n(?:(?:[ \t]+.*)?\r?\n)*?[ \t]+version:\s*(.+)$/m) ?? field(/^version:\s*(.+)$/m),
56
65
  };
57
66
  }
58
67
 
68
+ // { name, version } of a readable SKILL.md; null when it is missing or unreadable.
69
+ export function skillStamp(dir) {
70
+ const r = readSkill(dir);
71
+ return r.state === "ok" ? { name: r.name, version: r.version } : null;
72
+ }
73
+
59
74
  function readRecord(home) {
60
75
  try {
61
76
  const r = JSON.parse(readFileSync(recordFile(home), "utf8"));
@@ -65,6 +80,11 @@ function readRecord(home) {
65
80
  }
66
81
  }
67
82
 
83
+ // Every copy the install record knows (whatever its state now).
84
+ export function recordedCopyPaths(home = homedir()) {
85
+ return Object.keys(readRecord(home).copies);
86
+ }
87
+
68
88
  function writeRecord(home, record) {
69
89
  try {
70
90
  mkdirSync(dirname(recordFile(home)), { recursive: true });
@@ -185,7 +205,7 @@ export function refreshSkillCopies({ version, bundledDir, skillsDirs = [], home
185
205
  }
186
206
 
187
207
  // A symlink, or a folder that resolves somewhere other than <its skills folder>/hyperdecks.
188
- function isLinked(path) {
208
+ export function isLinked(path) {
189
209
  try {
190
210
  if (lstatSync(path).isSymbolicLink()) return true;
191
211
  } catch {
@@ -214,14 +234,27 @@ function warnFailed(dir, e, { record, now, log, state }) {
214
234
  }
215
235
 
216
236
  function refreshOne(dir, { version, bundledDir, home, now, log, record, state }) {
217
- const stamp = skillStamp(dir);
218
- if (!stamp) {
237
+ const read = readSkill(dir);
238
+ if (read.state === "missing") {
219
239
  // Uninstalled since: forget it.
220
240
  if (record.copies[dir]) { delete record.copies[dir]; state.changed = true; }
221
241
  return null;
222
242
  }
243
+ // There but unreadable: leave it (and its record); notices say so.
244
+ if (read.state === "unreadable") return { dir, action: "unreadable" };
245
+ const stamp = { name: read.name, version: read.version };
223
246
  if (stamp.name !== SKILL_NAME) return null;
224
247
  const rec = record.copies[dir]?.hash ? record.copies[dir] : null;
248
+ // A version that isn't one ("banana"): not ours to judge, so never replaced.
249
+ if (stamp.version && !parseVersion(stamp.version)) {
250
+ const note = (record.copies[dir] ??= {});
251
+ if (!(typeof note.badVersionAt === "number" && now - note.badVersionAt < DAY_MS && now >= note.badVersionAt)) {
252
+ log(`⚠ the hyperdecks skill at ${dir} says its version is "${stamp.version}", which isn't a version, so it was left as is; \`hyperdecks skill install\` replaces it`);
253
+ note.badVersionAt = now;
254
+ state.changed = true;
255
+ }
256
+ return { dir, action: "unparsable" };
257
+ }
225
258
  if (compareVersions(stamp.version ?? "0.0.0", version) >= 0) {
226
259
  // Current, or newer (from a newer CLI: never downgrade it). Adopt an
227
260
  // unrecorded copy that is byte-for-byte the bundled one, so a later edit to
package/src/source.mjs CHANGED
@@ -10,8 +10,10 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
10
10
  import { tmpdir } from "node:os";
11
11
  import { basename, extname, join, resolve } from "node:path";
12
12
  import { api, client, uploadBytes } from "./runtime.mjs";
13
- import { HOSTED_LAYOUT_WHY, MESSAGES } from "./checkRules.mjs";
13
+ import { HOSTED_LAYOUT_WHY, MESSAGES, deckFiles, deckPath, hostedFileRemedy, scriptLoads, uploadReport } from "./checkRules.mjs";
14
+ import { deckFolder } from "./check.mjs";
14
15
  import { withLoadingBlock } from "./loadingBlock.mjs";
16
+ import { ASSET_KINDS, ASSET_TYPES, assetTypeForPath, isScriptType } from "./assetTypes.mjs";
15
17
  import { TRIMS, barsLine, measureBars, trimFile } from "./bars.mjs";
16
18
  import { SOURCE_FILES, getDeckSource, hostedCheck, hostedRelease, uploadDeckAsset, writeDeckSource } from "./hosted.mjs";
17
19
 
@@ -48,8 +50,9 @@ export async function hostedCheckCli(opts, args, io = {}) {
48
50
  if (!opts.layout) return result;
49
51
  const layout = await hostedLayoutCheck(opts, args, io);
50
52
  const errors = [...result.errors, ...layout.errors];
51
- const unchecked = MESSAGES.layoutUnchecked(HOSTED_LAYOUT_WHY);
52
- return { ...result, errors, passed: errors.length === 0, warnings: [...new Set([...result.warnings.filter((w) => w !== unchecked), ...layout.warnings])] };
53
+ // The hosted check's "not measured here" note, in this version's words or a deploy's older ones (both say a browser is needed).
54
+ const unchecked = (w) => w === MESSAGES.layoutUnchecked(HOSTED_LAYOUT_WHY) || (w.startsWith(MESSAGES.layoutUnchecked("")) && /need a browser/.test(w));
55
+ return { ...result, errors, passed: errors.length === 0, warnings: [...new Set([...result.warnings.filter((w) => !unchecked(w)), ...layout.warnings])] };
53
56
  }
54
57
 
55
58
  async function hostedFix(opts, { slug } = {}) {
@@ -110,10 +113,50 @@ export async function sourcePush(pos, opts = {}, { log = (line) => console.log(l
110
113
  }
111
114
  for (const f of fixed) log(`✓ the draft fixed ${f}; \`hyperdecks source pull ${slug}\` to bring it into the folder`);
112
115
  log(`✓ pushed ${files.join(", ")} to ${slug}: rev ${rev}`);
113
- return { slug, rev, files };
116
+ // Only the source files go up: say which files the deck loads from the folder,
117
+ // so a release that can't play them isn't a surprise.
118
+ // The push already went through, so a folder the walk can't read is a warning, not a failure.
119
+ let notPushed = [];
120
+ try {
121
+ notPushed = filesLeftBehind(readFileSync(join(/*turbopackIgnore: true*/ dir, "index.html"), "utf8"), dir, files);
122
+ } catch (e) {
123
+ log(` ⚠ could not list the files the deck loads from ${dir}: ${e.message}`);
124
+ }
125
+ const byFolder = new Map();
126
+ for (const f of notPushed) {
127
+ const key = `${f.from}\n${f.path.slice(0, f.path.lastIndexOf("/") + 1)}\n${hostedFileRemedy(f.path, { worker: f.worker })}`; // one folder, one remedy
128
+ if (!byFolder.has(key)) byFolder.set(key, []);
129
+ byFolder.get(key).push(f);
130
+ }
131
+ for (const fs of byFolder.values()) {
132
+ const groups = fs.length > 3 ? [fs] : fs.map((f) => [f]);
133
+ for (const g of groups) log(` ⚠ ${MESSAGES.notPushed(g.map((f) => f.path), g[0].from, { worker: g[0].worker })}`);
134
+ }
135
+ return { slug, rev, files, notPushed: notPushed.map((f) => f.path) };
136
+ }
137
+
138
+ // The files in `dir` the deck loads (not a link's target, not a missing file) that a push of `pushed` left out.
139
+ function filesLeftBehind(html, dir, pushed) {
140
+ const folder = deckFolder(dir);
141
+ const links = new Set([...html.matchAll(/<a\b[^>]*\shref\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].map((m) => deckPath("", m[1] ?? m[2])).filter(Boolean));
142
+ // A worker's script gets its own remedy (it must be same-origin): which files are loaded as one,
143
+ // from index.html's scripts or a script in the folder, against the page or the script's folder.
144
+ const workers = new Map();
145
+ const readWorkers = (src, dirs) => {
146
+ for (const l of scriptLoads(src)) if (l.worker) for (const d of dirs) { const p = deckPath(d, l.ref); if (p) workers.set(p, l.worker); }
147
+ };
148
+ for (const [, attrs, body] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) if (!/\ssrc\s*=/i.test(attrs)) readWorkers(body, [""]);
149
+ const walked = deckFiles(html, folder).files;
150
+ for (const from of new Set(walked.map((f) => f.from).filter((p) => /\.m?js$/i.test(p)))) {
151
+ try { readWorkers(folder.read(from), ["", from.slice(0, from.lastIndexOf("/") + 1)]); } catch { /* unreadable: the plain remedy stands */ }
152
+ }
153
+ return walked
154
+ .filter((f) => !pushed.includes(f.path) && folder.pathExists(f.path) === true && !(f.from === "html" && links.has(f.path)))
155
+ .map((f) => ({ path: f.path, from: f.from === "html" ? "index.html" : f.from, ...(workers.get(f.path) ? { worker: workers.get(f.path) } : {}) }));
114
156
  }
115
157
 
116
- const TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".svg": "image/svg+xml", ".mp4": "video/mp4", ".webm": "video/webm", ".woff2": "font/woff2", ".woff": "font/woff", ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".json": "application/json" };
158
+ // asset add takes what every route takes (assetTypes.mjs), keyed here as extname gives it.
159
+ const TYPES = Object.fromEntries(Object.entries(ASSET_TYPES).map(([ext, type]) => [`.${ext}`, type]));
117
160
 
118
161
  // Measured for bars (bars.mjs): pictures ffmpeg reads (not SVG) and clips.
119
162
  const MEASURED = /^(image\/(png|jpeg|gif|webp|avif)|video\/)/;
@@ -132,7 +175,7 @@ async function fetchForTrim(url, fetchImpl) {
132
175
  const res = await fetchImpl(url, { signal: AbortSignal.timeout(60_000) });
133
176
  if (!res.ok) throw new Error(`${url} returned HTTP ${res.status}`);
134
177
  const declared = (res.headers.get("content-type") || "").split(";")[0].trim().toLowerCase();
135
- const byExt = TYPES[extname(new URL(url).pathname).toLowerCase()];
178
+ const byExt = assetTypeForPath(new URL(url).pathname);
136
179
  const contentType = MEASURED.test(declared) ? declared : byExt;
137
180
  const bytes = Buffer.from(await res.arrayBuffer());
138
181
  if (bytes.byteLength > MAX_FETCH_BYTES) throw new Error(`${url} is over 25 MB`);
@@ -162,8 +205,8 @@ export async function assetAdd(pos, opts = {}, { log = (line) => console.log(lin
162
205
  if (!name) name = basename(new URL(from).pathname) || "asset";
163
206
  } else {
164
207
  const path = resolve(/*turbopackIgnore: true*/ cwd, from);
165
- contentType = TYPES[extname(path).toLowerCase()];
166
- if (!contentType) throw new Error(`${from}: asset add takes images, video, audio, fonts and JSON (${Object.keys(TYPES).join(" ")})`);
208
+ contentType = assetTypeForPath(basename(path));
209
+ if (!contentType) throw new Error(`${from}: asset add takes ${ASSET_KINDS} (${Object.keys(TYPES).join(" ")})`);
167
210
  bytes = readFileSync(path);
168
211
  if (!name) name = basename(path);
169
212
  }
@@ -194,7 +237,7 @@ export async function assetAdd(pos, opts = {}, { log = (line) => console.log(lin
194
237
  }
195
238
  } else if (opts.trim) throw new Error(`${from}: --trim takes a picture or clip, not ${contentType}`);
196
239
  const saved = await upload(opts, { slug, name, bytes, contentType });
197
- out = { url: saved.url, name: saved.name, contentType, bytes: bytes.byteLength, ...(bars ? { bars } : {}), ...(trimmed ? { trimmed } : {}), ...(unmeasured ? { barsUnmeasured: unmeasured } : {}) };
240
+ out = { url: saved.url, name: saved.name, contentType, replaced: !!saved.replaced, ...uploadReport(bytes, contentType, saved.name ?? name), bytes: bytes.byteLength, ...(bars ? { bars } : {}), ...(trimmed ? { trimmed } : {}), ...(unmeasured ? { barsUnmeasured: unmeasured } : {}) };
198
241
  if (trimmed) log(`trimmed: ${barsLine(bars).slice("bars: ".length)} cut away; uploaded ${trimmed.to.width}x${trimmed.to.height}`);
199
242
  else if (bars?.reported) log(`${barsLine(bars)}; add --trim to upload it without them`);
200
243
  else if (opts.trim) log("no bars to trim; uploaded as it is");
@@ -202,5 +245,10 @@ export async function assetAdd(pos, opts = {}, { log = (line) => console.log(lin
202
245
  // The file (or URL) it came from beside its new URL, so uploads in a loop stay told apart.
203
246
  out = { ...out, file: from };
204
247
  log(`${from} → ${out.url}`);
248
+ // A same name on the deck replaces the earlier asset, whose URL then stops loading.
249
+ if (out.replaced) log(` replaced the earlier ${out.name} on ${slug}; its old URL no longer loads (--name gives this one its own)`);
250
+ if (isScriptType(out.contentType)) log(` in the deck: import("${out.url}") for a module, <script src="${out.url}"> for a classic script`);
251
+ // Paths inside an uploaded script or stylesheet: read here from disk, by the server from a URL.
252
+ if (out.warning) log(` ⚠ ${out.warning}`);
205
253
  return out;
206
254
  }
package/src/update.mjs CHANGED
@@ -2,11 +2,13 @@
2
2
  // once a day and keeps the answer in ~/.hyperdecks/update-check.json.
3
3
  //
4
4
  // - A newer `latest` prints one stderr line, at most once a day. A slow or failed
5
- // check is silent and never blocks a command. HYPERDECKS_NO_UPDATE_CHECK=1 and
6
- // CI skip the line.
5
+ // check is silent and never blocks a command. The opt-out
6
+ // (HYPERDECKS_NO_UPDATE_CHECK=1|true) and CI skip the line, and the request
7
+ // for every command but the gated ones.
7
8
  // - Below `minimum`, the commands that make or ship a deck (GATED) refuse and
8
- // exit 1, whatever the opt-out says; HYPERDECKS_ALLOW_OLD=1 runs them anyway,
9
- // with a warning. Unknown (never reached the server): they run.
9
+ // exit 1, whatever the opt-out or CI says (they still ask the server: the
10
+ // minimum is a safety gate, not a nag); HYPERDECKS_ALLOW_OLD=1 runs them
11
+ // anyway, with a warning. Unknown (never reached the server): they run.
10
12
  // - It never installs anything: it prints the command.
11
13
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
14
  import { homedir } from "node:os";
@@ -21,17 +23,21 @@ export const UPDATE_STATE_FILE = join(homedir(), ".hyperdecks", "update-check.js
21
23
  // list, share links, stats) keeps working on any version.
22
24
  export const GATED = new Set(["narrate", "check", "release", "deck new", "preview create", "init"]);
23
25
 
24
- export const UPGRADE = "npm i -g hyperdecks@latest, or use npx hyperdecks@latest";
26
+ export const UPGRADE_COMMAND = "npm i -g hyperdecks@latest";
27
+ export const UPGRADE = `${UPGRADE_COMMAND}, or use npx hyperdecks@latest`;
25
28
 
26
- // "1.2.3" vs "1.10.0": numeric x.y.z; a prerelease (1.2.3-beta) sorts below its
27
- // release. Anything unparsable compares as 0.0.0.
29
+ // "1.2.3", "v1.2", "1.2.3-beta.1", "1.2.3+build" → [major, minor, patch, release?];
30
+ // null when it is not a version at all ("banana"). A missing patch is 0; build
31
+ // metadata (+…) is ignored; a prerelease sorts below its release.
32
+ export function parseVersion(v) {
33
+ const m = /^v?(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(v ?? "").trim());
34
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0), m[4] ? 0 : 1] : null;
35
+ }
36
+
37
+ // "1.2.3" vs "1.10.0", numerically. Anything unparsable compares as 0.0.0.
28
38
  export function compareVersions(a, b) {
29
- const parts = (v) => {
30
- const m = /^v?(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(String(v ?? "").trim());
31
- return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? 0 : 1] : [0, 0, 0, 1];
32
- };
33
- const x = parts(a);
34
- const y = parts(b);
39
+ const x = parseVersion(a) ?? [0, 0, 0, 1];
40
+ const y = parseVersion(b) ?? [0, 0, 0, 1];
35
41
  for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
36
42
  return 0;
37
43
  }
@@ -46,7 +52,15 @@ export const noticeLine = (latest, version) => `hyperdecks ${latest} is out (you
46
52
  export const refusalLine = (command, minimum, version) =>
47
53
  `hyperdecks ${version} is too old to \`${command}\` (the minimum is ${minimum}): ${UPGRADE}. In an emergency, HYPERDECKS_ALLOW_OLD=1 runs it anyway.`;
48
54
 
49
- const quietEnv = (env) => env.HYPERDECKS_NO_UPDATE_CHECK === "1" || /^(1|true)$/i.test(env.CI ?? "");
55
+ // A newer CLI is out: what `--json` output carries in `notices`.
56
+ export const cliNotice = (latest, version) => ({ kind: "cli-behind", cli: version, latest, run: UPGRADE_COMMAND, message: noticeLine(latest, version) });
57
+
58
+ // Set and not "0"/"false"/empty: CI tools set these to "true", "True", a URL or a version.
59
+ const isSet = (v) => typeof v === "string" && v.trim() !== "" && !/^(0|false|no)$/i.test(v.trim());
60
+ const CI_VARS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TF_BUILD", "TEAMCITY_VERSION"];
61
+ // The opt-out (=1 or =true) or a CI run: no version request at all, no daily
62
+ // line, no skill refresh.
63
+ export const quietEnv = (env) => /^(1|true|yes)$/i.test(String(env.HYPERDECKS_NO_UPDATE_CHECK ?? "").trim()) || CI_VARS.some((k) => isSet(env[k]));
50
64
 
51
65
  function readState(file) {
52
66
  try {
@@ -57,33 +71,84 @@ function readState(file) {
57
71
  }
58
72
  }
59
73
 
74
+ // true when written. A read-only home only costs the cache.
60
75
  function writeState(file, state) {
61
76
  try {
62
77
  mkdirSync(dirname(file), { recursive: true });
63
78
  writeFileSync(file, JSON.stringify(state, null, 2));
79
+ return true;
64
80
  } catch {
65
- // A read-only home only costs the cache.
81
+ return false;
66
82
  }
67
83
  }
68
84
 
69
85
  const VERSION_RE = /^\d+\.\d+\.\d+(-[\w.]+)?$/;
70
86
 
71
- // { latest, minimum, notes } from the server, or null (slow, offline, bad body).
87
+ // The answer is a few hundred bytes; anything past these caps is not it.
88
+ export const MAX_BODY_BYTES = 16 * 1024;
89
+ export const MAX_NOTES = 500;
90
+
91
+ // The body as text, or null past `max` bytes (never reads further).
92
+ async function cappedText(res, max) {
93
+ if (Number(res.headers?.get?.("content-length")) > max) return null;
94
+ if (!res.body?.getReader) {
95
+ const t = await res.text();
96
+ return t.length > max ? null : t;
97
+ }
98
+ const reader = res.body.getReader();
99
+ const chunks = [];
100
+ let size = 0;
101
+ for (;;) {
102
+ const { done, value } = await reader.read();
103
+ if (done) break;
104
+ size += value.byteLength;
105
+ if (size > max) {
106
+ reader.cancel().catch(() => {});
107
+ return null;
108
+ }
109
+ chunks.push(value);
110
+ }
111
+ return Buffer.concat(chunks.map((c) => Buffer.from(c))).toString("utf8");
112
+ }
113
+
114
+ // { latest, minimum, notes } from the server, or null (slow, offline, bad or oversized body).
72
115
  export async function fetchVersionInfo(base, { fetchImpl = fetch, timeoutMs = CHECK_TIMEOUT_MS, headers = {} } = {}) {
73
116
  try {
74
117
  const res = await fetchImpl(`${base}/api/cli/version`, { headers, signal: AbortSignal.timeout(timeoutMs) });
75
118
  if (!res.ok) return null;
76
- const body = await res.json();
119
+ const text = await cappedText(res, MAX_BODY_BYTES);
120
+ if (text === null) return null;
121
+ const body = JSON.parse(text);
77
122
  if (!VERSION_RE.test(body?.latest ?? "") || !VERSION_RE.test(body?.minimum ?? "")) return null;
78
- return { latest: body.latest, minimum: body.minimum, notes: typeof body.notes === "string" ? body.notes : "" };
123
+ return { latest: body.latest, minimum: body.minimum, notes: typeof body.notes === "string" ? body.notes.slice(0, MAX_NOTES) : "" };
79
124
  } catch {
80
125
  return null;
81
126
  }
82
127
  }
83
128
 
84
- // Runs before a command. Returns { refuse } (the command must not run) and
85
- // `after()`, which prints the daily notice once the command is done (so the
86
- // check overlaps the command instead of delaying it).
129
+ // Is the once-a-day line `key` due? Not when the state file says it printed in
130
+ // the last day (a stamp from the future does not count).
131
+ export function dueToday(key, { stateFile = UPDATE_STATE_FILE, now = Date.now() } = {}) {
132
+ const last = readState(stateFile)[key];
133
+ return !(typeof last === "number" && now - last < DAY_MS && now >= last);
134
+ }
135
+
136
+ // Print `line` if it is due, recording it first. When the record can't be
137
+ // written (a read-only home) it stays quiet: else it would print on every command.
138
+ export function onceADay(key, line, { stateFile = UPDATE_STATE_FILE, now = Date.now(), warn = (l) => console.error(l) } = {}) {
139
+ if (!dueToday(key, { stateFile, now })) return false;
140
+ if (!writeState(stateFile, { ...readState(stateFile), [key]: now })) return false;
141
+ warn(line);
142
+ return true;
143
+ }
144
+
145
+ // Runs before a command. Returns { refuse } (the command must not run),
146
+ // `cached` (the notice from the answer already on disk, or null) and
147
+ // `after({ announce })`, which (announce, the default) prints the daily line
148
+ // once the command is done (so the check overlaps the command instead of
149
+ // delaying it) and returns the notice (cliNotice) whenever a newer CLI is out,
150
+ // printed today or not, for `--json`. Quiet (opt-out or CI): no notice, and no
151
+ // request except for a gated command, which still needs the minimum.
87
152
  export async function updatePreflight(pos, {
88
153
  version,
89
154
  base,
@@ -119,22 +184,20 @@ export async function updatePreflight(pos, {
119
184
  if (minimum && compareVersions(version, minimum) < 0) {
120
185
  if (env.HYPERDECKS_ALLOW_OLD !== "1") {
121
186
  warn(`✗ ${refusalLine(command, minimum, version)}`);
122
- return { refuse: true, after: async () => {} };
187
+ return { refuse: true, cached: null, after: async () => null };
123
188
  }
124
189
  warn(`⚠ HYPERDECKS_ALLOW_OLD=1: running \`${command}\` on hyperdecks ${version}, below the minimum ${minimum}. It may ship retired templates or known bugs. Update: ${UPGRADE}`);
125
190
  }
126
191
  }
127
192
 
193
+ const noticeFrom = (got) => (!quiet && got.latest && compareVersions(got.latest, version) > 0 ? cliNotice(got.latest, version) : null);
128
194
  return {
129
195
  refuse: false,
130
- after: async () => {
131
- if (quiet) return;
132
- const got = await info;
133
- if (!got.latest || compareVersions(got.latest, version) <= 0) return;
134
- const last = readState(stateFile).notifiedAt;
135
- if (typeof last === "number" && now - last < DAY_MS && now >= last) return;
136
- warn(noticeLine(got.latest, version));
137
- writeState(stateFile, { ...readState(stateFile), notifiedAt: now });
196
+ cached: noticeFrom(state),
197
+ after: async ({ announce = true } = {}) => {
198
+ const notice = noticeFrom(await info);
199
+ if (notice && announce) onceADay("notifiedAt", notice.message, { stateFile, now, warn });
200
+ return notice;
138
201
  },
139
202
  };
140
203
  }
@@ -330,20 +330,20 @@ d.addEventListener("readystatechange",go);go()})();</script>
330
330
  -webkit-mask-image: radial-gradient(circle at 100% 0, #000 45%, rgba(0,0,0,.4) 100%); mask-image: radial-gradient(circle at 100% 0, #000 45%, rgba(0,0,0,.4) 100%); }
331
331
  .l-closer.bg-corner::before { --corner-r: 460px; }
332
332
  .on-ink.bg-corner::before { --corner-a: 22%; }
333
- :is(.l-split, .l-product, .l-chart, .l-quote, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-cover-band, .l-cover-poster, .l-cover-split, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-corner::before { content: none; }
333
+ :is(.l-split, .l-product, .l-chart, .l-quote, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-statement, .l-pictures, .l-scale, .l-sieve, .l-cover-band, .l-cover-poster, .l-cover-split, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-corner::before { content: none; }
334
334
  /* bg-stage: a rounded dot plate exactly the picture's column plus 32px, so the frame or the phones stand on it; on the hero a tile behind the stickers. */
335
335
  .slide.bg-stage::before { inset: auto; background: radial-gradient(color-mix(in srgb, currentColor var(--stage-a, 24%), transparent) 2.4px, transparent 2.9px) 0 0 / 22px 22px; border-radius: calc(40 * var(--round)); }
336
336
  .l-product.bg-stage::before { position: relative; grid-area: frame; align-self: stretch; margin: var(--stage-m, -32px -24px -32px -40px); }
337
337
  .l-phones.bg-stage::before { position: relative; grid-area: row; align-self: stretch; margin: var(--stage-m, -32px); }
338
338
  .l-hero.bg-stage::before { right: 110px; top: 110px; width: 410px; height: 350px; }
339
- :is(.l-split, .l-chart, .l-quote, .l-closer, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-cover-band, .l-cover-poster, .l-cover-split, .l-cover-type, .l-cover-frame, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-stage::before { content: none; }
339
+ :is(.l-split, .l-chart, .l-quote, .l-closer, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-statement, .l-pictures, .l-scale, .l-sieve, .l-cover-band, .l-cover-poster, .l-cover-split, .l-cover-type, .l-cover-frame, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-stage::before { content: none; }
340
340
  /* bg-mark: the slide number, set as style="--mark:'04'" on the section, huge in --display, faint,
341
341
  cropped by the top edge; right on the hero, in the indent on slot-left slides. A signature: cover, an opener, closer. */
342
342
  .slide.bg-mark::before { content: var(--mark, ""); inset: auto; right: 24px; top: -.26em; font: var(--display-weight, 700) var(--mark-size, 560px)/1 var(--display, var(--font)); font-synthesis: none; letter-spacing: var(--display-tracking, -.05em); white-space: nowrap;
343
343
  color: color-mix(in srgb, currentColor var(--mark-a, 8%), transparent); }
344
344
  .slide.on-ink.bg-mark::before { --mark-a: 6%; }
345
345
  .slide.slot-left.bg-mark::before { right: auto; left: -.08em; font-size: var(--mark-size, 440px); } /* ends inside the 500px indent, clear of the title */
346
- :is(.l-split, .l-product, .l-chart, .l-phones, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-cover-band, .l-cover-poster, .l-cover-split, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-mark::before { content: none; }
346
+ :is(.l-split, .l-product, .l-chart, .l-phones, .l-number, .l-features, .l-team, .l-timeline, .l-compare, .l-statement, .l-pictures, .l-scale, .l-sieve, .l-cover-band, .l-cover-poster, .l-cover-split, .l-phone-stage, .l-tap-through, .l-screens, .l-zoom, .l-video-full, .l-video-beats, .l-picture-full, .l-wall, .l-portrait, .l-embed, .l-sentence, .l-strike, .l-spotlight, .l-funnel, .l-scorecard, .l-bento, .l-two-by-two, .l-staircase, .l-rail, .l-loop, .l-lanes, .l-two-bars, .l-stack, .l-question-choice, .l-question-text).bg-mark::before { content: none; }
347
347
  /* Pieces. .sticker: a logo or icon tile, tilted (--tilt), ink edge, hard offset
348
348
  shadow (.sticker.photo for a face or an app icon that fills it). .ticks: a short
349
349
  list with accent-square bullets. .panel: a quiet card. .pill: a small tag. */