my-durable 0.0.37 → 0.0.39

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.
@@ -13,6 +13,10 @@ import type {
13
13
  ModelInfo,
14
14
  Page,
15
15
  SendResult,
16
+ DeviceUsageReport,
17
+ ProjectPatchBody,
18
+ SessionSearchMatch,
19
+ SessionSearchResult,
16
20
  SessionSummary,
17
21
  TaskNode,
18
22
  TaskOutcome,
@@ -28,11 +32,21 @@ import {
28
32
  THINKING_LEVELS,
29
33
  type CompactionSettings,
30
34
  } from "../../dpi-sdk/src/api.js";
31
- import { lastAssistantText, messageText, toMarkdown, toTranscript } from "../../dpi-sdk/src/transcript.js";
35
+ import {
36
+ lastAssistantText,
37
+ messageText,
38
+ sumUsage,
39
+ toMarkdown,
40
+ toTranscript,
41
+ type UsageSummary,
42
+ } from "../../dpi-sdk/src/transcript.js";
32
43
  import { ApiFault, invalid, notFound } from "./errors.js";
33
- import { git, gitDirtyMarks, onGitDirty } from "./git.js";
44
+ import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
34
45
  import { DatabaseSync } from "node:sqlite";
35
46
  import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
47
+ import { deviceVitals, type DeviceVitals } from "./vitals.js";
48
+ import { ProjectRegistry, type ProjectRecord } from "./projects.js";
49
+ import { zipSync, type ZipEntry } from "./zip.js";
36
50
  import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
37
51
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
38
52
  import { join, dirname, relative, resolve } from "node:path";
@@ -109,6 +123,44 @@ export interface StoreOptions {
109
123
  /** Agent documents a client may read or stream, by kind. */
110
124
  /** apps/dpi-backend/src → the checkout root. */
111
125
  const CODE_DIR = resolve(import.meta.dirname, "../../..");
126
+
127
+ /** Session search result cap: one screen of matches, not a transcript dump. */
128
+ const SEARCH_LIMIT = 50;
129
+
130
+ /** Starting point for a per-model usage accumulator. */
131
+ const ZERO_USAGE: UsageSummary = {
132
+ tokens: 0,
133
+ cost: 0,
134
+ input: 0,
135
+ output: 0,
136
+ cacheRead: 0,
137
+ cacheWrite: 0,
138
+ inputCost: 0,
139
+ outputCost: 0,
140
+ cacheReadCost: 0,
141
+ cacheWriteCost: 0,
142
+ };
143
+
144
+ /** A bundle for a session whose store is closed (archived or restarting) still exports its record. */
145
+ const NOT_OPENED_README = [
146
+ "This bundle was exported while the session's store was closed.",
147
+ "",
148
+ "It contains manifest.json and session.json only. Start the device and re-export",
149
+ "from the running session to include per-agent transcripts and configs.",
150
+ "",
151
+ ].join("\n");
152
+
153
+ /** "My session #1" → "my-session-1" for the download name. */
154
+ function slugName(input: string): string {
155
+ const slug = input
156
+ .normalize("NFKD")
157
+ .replace(/[^\w.-]+/g, "-")
158
+ .replace(/^-+|-+$/g, "")
159
+ .slice(0, 60)
160
+ .toLowerCase();
161
+ return slug || "session";
162
+ }
163
+
112
164
  const AGENT_DOCS = { [JOB_RUNS_DOC]: JobRuns, "demo.workspace": Workspace } as const;
113
165
  export const AGENT_DOC_KINDS = Object.keys(AGENT_DOCS);
114
166
  export const DEVICE_DOC_KINDS = ["app.shared-state"];
@@ -172,6 +224,9 @@ export class Store {
172
224
  readonly catalog: DatabaseSync;
173
225
  readonly startedAt = Date.now();
174
226
  shared!: SharedState;
227
+ /** Projects (Wave 2): a registry of roots with labels, grouped by the cwd a
228
+ * session starts in. Opened with the store so routes never see a half state. */
229
+ projects!: ProjectRegistry;
175
230
  uid!: string;
176
231
  modelList: ModelInfo[] = [];
177
232
  private unlockCatalog: () => void;
@@ -194,6 +249,9 @@ export class Store {
194
249
  get archiveDir() {
195
250
  return join(this.options.dataDir, "archive");
196
251
  }
252
+ get projectsPath() {
253
+ return join(this.options.dataDir, "projects.json");
254
+ }
197
255
  get name() {
198
256
  return this.options.name;
199
257
  }
@@ -242,6 +300,17 @@ export class Store {
242
300
  // Start dirs are where new sessions begin; create any that do not exist yet.
243
301
  await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
244
302
  try {
303
+ store.projects = await ProjectRegistry.open(store.projectsPath, {
304
+ warn: (m) => process.emitWarning(`projects: ${m}`),
305
+ });
306
+ // Seed the registry from history: a device that predates projects still
307
+ // shows every root its sessions already live in (idempotent by rootPath).
308
+ for (const row of store.list()) {
309
+ const status = await gitStatus(row.cwd).catch(() => undefined);
310
+ await store.projects
311
+ .ensure({ rootPath: status?.repo ? (status.root ?? row.cwd) : row.cwd, kind: status?.repo ? "git" : "plain" })
312
+ .catch(() => undefined);
313
+ }
245
314
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
246
315
  store.shared = await SharedState.open(store.sharedStatePath);
247
316
  store.shared.harness.subscribeCommits(() => store.notify());
@@ -555,6 +624,12 @@ export class Store {
555
624
  } catch {
556
625
  throw invalid(`cwd must be an existing folder on ${this.name}`);
557
626
  }
627
+ // Every session roots a project: the registry is the tree's group-by-cwd,
628
+ // promoted to an entity you can name, label and archive (paseo model).
629
+ const status = await gitStatus(cwd).catch(() => undefined);
630
+ await this.projects
631
+ .ensure({ rootPath: status?.repo ? (status.root ?? cwd) : cwd, kind: status?.repo ? "git" : "plain" })
632
+ .catch(() => undefined);
558
633
  const model = this.validateModel(body.model);
559
634
  if (body.thinkingLevel !== undefined && !THINKING_LEVELS.includes(body.thinkingLevel))
560
635
  throw invalid("Invalid thinking level");
@@ -1430,6 +1505,203 @@ export class Store {
1430
1505
  return { uid: this.uid, name: this.name, sessions, at: Date.now(), ...(git.length ? { git } : {}) };
1431
1506
  }
1432
1507
 
1508
+ // ------------------------------------------- ops: vitals, search, export
1509
+
1510
+ /** One-shot host health (herdr/piggery shape) — asked for, never polled. */
1511
+ async vitals(): Promise<DeviceVitals & { counts: { sessions: number; archived: number } }> {
1512
+ const archived = await readdir(this.archiveDir).catch(() => [] as string[]);
1513
+ return {
1514
+ ...deviceVitals(this.options.dataDir, this.startedAt),
1515
+ counts: { sessions: this.list().length, archived: archived.length },
1516
+ };
1517
+ }
1518
+
1519
+ /**
1520
+ * Session search over names, cwds and models — the cheap half of paseo's
1521
+ * history search. Transcript text is deliberately NOT scanned: at volume it
1522
+ * needs an FTS index, and a naive LIKE over every entry would make the device
1523
+ * slow exactly when a human is typing.
1524
+ */
1525
+ searchSessions(rawQuery: string): SessionSearchResult {
1526
+ const query = String(rawQuery ?? "").trim();
1527
+ const needle = query.toLowerCase();
1528
+ if (needle.length < 2) return { query, matches: [] };
1529
+ const matches: SessionSearchMatch[] = [];
1530
+ for (const row of this.list()) {
1531
+ const where: SessionSearchMatch["where"] = [];
1532
+ if (row.name.toLowerCase().includes(needle)) where.push("name");
1533
+ if (row.cwd.toLowerCase().includes(needle)) where.push("cwd");
1534
+ if (row.model.toLowerCase().includes(needle)) where.push("model");
1535
+ if (!where.length) continue;
1536
+ const base = this.sessionSummaryBase(row);
1537
+ matches.push({
1538
+ id: base.id,
1539
+ name: base.name,
1540
+ cwd: base.cwd,
1541
+ model: base.model,
1542
+ createdAt: base.createdAt,
1543
+ dbPath: base.dbPath,
1544
+ ...(base.compaction ? { compaction: base.compaction } : {}),
1545
+ where,
1546
+ });
1547
+ }
1548
+ // Name hits first (what a human means by "search my sessions"), then the newest.
1549
+ matches.sort(
1550
+ (a, b) => Number(b.where.includes("name")) - Number(a.where.includes("name")) || b.createdAt - a.createdAt,
1551
+ );
1552
+ return { query, matches: matches.slice(0, SEARCH_LIMIT) };
1553
+ }
1554
+
1555
+ /**
1556
+ * One downloadable archive of a session: manifest, session record, and every
1557
+ * agent's transcript + config (paseo `exports.ts` shape). Text only, zipped by
1558
+ * our own writer — the device has no archive dependency.
1559
+ */
1560
+ async exportSession(
1561
+ row: SessionRow,
1562
+ ): Promise<{ filename: string; mime: string; bytes: number; base64: string }> {
1563
+ const agents = this.opened.has(row.id) ? await this.agents(row) : [];
1564
+ const files: ZipEntry[] = [];
1565
+ const manifest = {
1566
+ format: "dpi-session-bundle",
1567
+ version: 1,
1568
+ exportedAt: new Date().toISOString(),
1569
+ device: {
1570
+ uid: this.uid,
1571
+ name: this.name,
1572
+ hostname: hostname(),
1573
+ platform: `${platform()} node ${process.version}`,
1574
+ durableVersion: DURABLE_VERSION,
1575
+ },
1576
+ session: { id: row.id, name: row.name, cwd: row.cwd, model: row.model, createdAt: row.createdAt },
1577
+ agents: agents.map((a) => ({ id: a.id, name: a.name, kind: a.kind })),
1578
+ };
1579
+ files.push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
1580
+ files.push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
1581
+ const opened = this.opened.get(row.id);
1582
+ for (const agent of agents) {
1583
+ const c = opened ? await opened.harness.conversation(agent.id as ConversationId, ctx) : undefined;
1584
+ if (!c) continue;
1585
+ const dir = `agents/${agent.id}`;
1586
+ files.push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
1587
+ const md = await this.transcript(c, "markdown");
1588
+ if (typeof md.text === "string") files.push({ path: `${dir}/transcript.md`, text: md.text });
1589
+ files.push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
1590
+ }
1591
+ if (!agents.length) files.push({ path: "README.txt", text: NOT_OPENED_README });
1592
+ const zip = zipSync(files);
1593
+ return {
1594
+ filename: `${slugName(row.name || row.id)}.bundle.zip`,
1595
+ mime: "application/zip",
1596
+ bytes: zip.length,
1597
+ base64: zip.toString("base64"),
1598
+ };
1599
+ }
1600
+
1601
+ // ------------------------------------------------- projects (Wave 2)
1602
+
1603
+ /** Projects, newest activity first: the tree's group-by-cwd as an entity. */
1604
+ projectList(includeArchived = false): ProjectRecord[] {
1605
+ return this.projects.list({ includeArchived });
1606
+ }
1607
+
1608
+ /**
1609
+ * Rename/label a project. `customName` wins over the derived basename, and
1610
+ * labels are what humans filter by — paseo's rule that reconciliation never
1611
+ * touches either.
1612
+ */
1613
+ async updateProject(id: string, patch: ProjectPatchBody): Promise<ProjectRecord> {
1614
+ // Only the keys the caller actually sent: passing `customName: undefined`
1615
+ // must not read as "clear the name" (that is `customName: ""`).
1616
+ const next: { customName?: string; labels?: string[] } = {};
1617
+ if (patch.customName !== undefined) next.customName = patch.customName;
1618
+ if (patch.labels !== undefined) next.labels = patch.labels;
1619
+ return this.projects.update(id, next);
1620
+ }
1621
+
1622
+ async archiveProject(id: string): Promise<ProjectRecord> {
1623
+ this.notify();
1624
+ return this.projects.archive(id);
1625
+ }
1626
+
1627
+ async unarchiveProject(id: string): Promise<ProjectRecord> {
1628
+ this.notify();
1629
+ return this.projects.unarchive(id);
1630
+ }
1631
+
1632
+ /**
1633
+ * Usage rollup (orca `usage/`, our data): every live session's harness usage,
1634
+ * summed per session, per model and per project. Archived sessions are closed
1635
+ * stores, so they are not counted — this is "what this device is spending on
1636
+ * the work it still holds", not a lifetime invoice.
1637
+ */
1638
+ async usageReport(): Promise<DeviceUsageReport> {
1639
+ const models = new Map<string, UsageSummary>();
1640
+ const projects = new Map<string, DeviceUsageReport["projects"][number]>();
1641
+ const sessions: DeviceUsageReport["sessions"] = [];
1642
+ let tokens = 0;
1643
+ let cost = 0;
1644
+
1645
+ for (const row of this.list()) {
1646
+ const opened = this.opened.get(row.id);
1647
+ if (!opened) continue;
1648
+ const raw = await this.usage(opened.harness);
1649
+ const usage = sumUsage(raw);
1650
+ for (const [key, u] of Object.entries(raw.models ?? {})) {
1651
+ const prev = models.get(key) ?? ZERO_USAGE;
1652
+ models.set(key, {
1653
+ tokens: prev.tokens + (u.totalTokens ?? 0),
1654
+ cost: prev.cost + (u.cost?.total ?? 0),
1655
+ input: prev.input + (u.input ?? 0),
1656
+ output: prev.output + (u.output ?? 0),
1657
+ cacheRead: prev.cacheRead + (u.cacheRead ?? 0),
1658
+ cacheWrite: prev.cacheWrite + (u.cacheWrite ?? 0),
1659
+ inputCost: prev.inputCost + (u.cost?.input ?? 0),
1660
+ outputCost: prev.outputCost + (u.cost?.output ?? 0),
1661
+ cacheReadCost: prev.cacheReadCost + (u.cost?.cacheRead ?? 0),
1662
+ cacheWriteCost: prev.cacheWriteCost + (u.cost?.cacheWrite ?? 0),
1663
+ });
1664
+ }
1665
+ const project = this.projects.findByPath(row.cwd) ?? this.projects.findByPath(dirname(row.cwd));
1666
+ sessions.push({
1667
+ id: row.id,
1668
+ name: row.name,
1669
+ cwd: row.cwd,
1670
+ project: project ? (project.customName ?? project.name) : undefined,
1671
+ tokens: usage.tokens,
1672
+ cost: usage.cost,
1673
+ agents: (await this.agents(row)).length,
1674
+ });
1675
+ tokens += usage.tokens;
1676
+ cost += usage.cost;
1677
+ if (project) {
1678
+ const prev = projects.get(project.id) ?? {
1679
+ rootPath: project.rootPath,
1680
+ name: project.customName ?? project.name,
1681
+ tokens: 0,
1682
+ cost: 0,
1683
+ sessions: 0,
1684
+ };
1685
+ projects.set(project.id, {
1686
+ ...prev,
1687
+ tokens: prev.tokens + usage.tokens,
1688
+ cost: prev.cost + usage.cost,
1689
+ sessions: prev.sessions + 1,
1690
+ });
1691
+ }
1692
+ }
1693
+
1694
+ return {
1695
+ at: Date.now(),
1696
+ totals: { tokens, cost },
1697
+ models: [...models.entries()]
1698
+ .map(([key, value]) => ({ key, ...value }))
1699
+ .sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1700
+ sessions: sessions.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1701
+ projects: [...projects.values()].sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1702
+ };
1703
+ }
1704
+
1433
1705
  // ------------------------------------------------------------ demo extension
1434
1706
 
1435
1707
  async demoState(c: Conversation, body: Record<string, unknown>) {
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Device vitals: the one screen that answers "is this box healthy?" without
3
+ * opening a terminal. Mirrors the shape herdr prints for a device (`uptime`,
4
+ * `since`) and piggery's `top`, and reuses the statfs disk guard pattern from
5
+ * the hub's audit volume check (`audit.ts` `volumeFreeBytes`).
6
+ *
7
+ * Everything here is cheap and synchronous — no polling on our side, the UIs
8
+ * ask when they are looked at.
9
+ */
10
+ import { statfsSync } from "node:fs";
11
+ import { cpus, loadavg, uptime as osUptime, freemem, totalmem } from "node:os";
12
+
13
+ export interface DiskVitals {
14
+ path: string;
15
+ totalBytes: number;
16
+ freeBytes: number;
17
+ /** False when the platform/filesystem cannot answer (Windows without statfs). */
18
+ known: boolean;
19
+ }
20
+
21
+ export interface DeviceVitals {
22
+ /** Seconds the host has been up. */
23
+ uptime: number;
24
+ /** Seconds the device process has been running (the daemon's own age). */
25
+ processUptime: number;
26
+ /** 1/5/15-minute load averages; zeros on Windows, which has no equivalent. */
27
+ loadavg: [number, number, number];
28
+ cpuCount: number;
29
+ memory: { totalBytes: number; freeBytes: number; usedBytes: number; processRssBytes: number; heapUsedBytes: number };
30
+ disk: DiskVitals;
31
+ pid: number;
32
+ at: number;
33
+ }
34
+
35
+ /** Free/total bytes for the volume holding `path`; `known: false` instead of throwing. */
36
+ export function diskVitals(path: string): DiskVitals {
37
+ try {
38
+ const stats = statfsSync(path);
39
+ const total = stats.blocks * stats.bsize;
40
+ const free = stats.bavail * stats.bsize;
41
+ // Some filesystems report 0 blocks (synthetic mounts) — treat as unknown
42
+ // rather than claiming the disk is full.
43
+ if (!Number.isFinite(total) || total <= 0) return { path, totalBytes: 0, freeBytes: 0, known: false };
44
+ return { path, totalBytes: total, freeBytes: free, known: true };
45
+ } catch {
46
+ return { path, totalBytes: 0, freeBytes: 0, known: false };
47
+ }
48
+ }
49
+
50
+ export function deviceVitals(diskPath: string, startedAt: number, now = Date.now()): DeviceVitals {
51
+ const load = loadavg();
52
+ const total = totalmem();
53
+ const free = freemem();
54
+ const memory = process.memoryUsage();
55
+ return {
56
+ uptime: Math.round(osUptime()),
57
+ processUptime: Math.max(0, Math.round((now - startedAt) / 1000)),
58
+ loadavg: [load[0] ?? 0, load[1] ?? 0, load[2] ?? 0],
59
+ cpuCount: cpus().length,
60
+ memory: {
61
+ totalBytes: total,
62
+ freeBytes: free,
63
+ usedBytes: Math.max(0, total - free),
64
+ processRssBytes: memory.rss,
65
+ heapUsedBytes: memory.heapUsed,
66
+ },
67
+ disk: diskVitals(diskPath),
68
+ pid: process.pid,
69
+ at: now,
70
+ };
71
+ }
72
+
73
+ /** "3d 4h", "12m", "45s" — the compact form both the CLI and the web card show. */
74
+ export function humanDuration(seconds: number): string {
75
+ const s = Math.max(0, Math.floor(seconds));
76
+ if (s < 60) return `${s}s`;
77
+ const m = Math.floor(s / 60);
78
+ if (m < 60) return `${m}m`;
79
+ const h = Math.floor(m / 60);
80
+ if (h < 24) return `${h}h ${m % 60}m`;
81
+ return `${Math.floor(h / 24)}d ${h % 24}h`;
82
+ }
83
+
84
+ export function humanBytes(bytes: number): string {
85
+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
86
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
87
+ let value = bytes;
88
+ let unit = 0;
89
+ while (value >= 1024 && unit < units.length - 1) {
90
+ value /= 1024;
91
+ unit += 1;
92
+ }
93
+ return `${value >= 100 || unit === 0 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
94
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A minimal ZIP writer: no dependencies, no shelling out to `zip`.
3
+ *
4
+ * Export bundles need to be one downloadable file, and the device has no
5
+ * archive library. The format only needs the three records a reader actually
6
+ * walks — local header, central directory, end-of-central-directory — so it is
7
+ * cheaper to write them here than to add a dependency for one button.
8
+ *
9
+ * Entries are deflated (`zlib.deflateRawSync`, method 8) or stored (method 0)
10
+ * when deflating makes them bigger (already-compressed or tiny payloads).
11
+ */
12
+ import { deflateRawSync } from "node:zlib";
13
+
14
+ export interface ZipEntry {
15
+ /** Forward-slash relative path inside the archive. */
16
+ path: string;
17
+ /** UTF-8 text payload. */
18
+ text: string;
19
+ }
20
+
21
+ const LOCAL_SIG = 0x04034b50;
22
+ const CENTRAL_SIG = 0x02014b50;
23
+ const EOCD_SIG = 0x06054b50;
24
+ /** Bit 11: file names are UTF-8 (we write non-ASCII session names). */
25
+ const FLAG_UTF8 = 0x0800;
26
+ const VERSION = 20;
27
+
28
+ const CRC_TABLE = (() => {
29
+ const table = new Uint32Array(256);
30
+ for (let i = 0; i < 256; i += 1) {
31
+ let c = i;
32
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
33
+ table[i] = c >>> 0;
34
+ }
35
+ return table;
36
+ })();
37
+
38
+ export function crc32(data: Uint8Array): number {
39
+ let crc = 0xffffffff;
40
+ for (let i = 0; i < data.length; i += 1) crc = CRC_TABLE[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
41
+ return (crc ^ 0xffffffff) >>> 0;
42
+ }
43
+
44
+ /** MS-DOS time/date: 2-second resolution, 1980 epoch. */
45
+ function dosStamp(date: Date): { time: number; date: number } {
46
+ const year = Math.max(1980, date.getFullYear());
47
+ return {
48
+ time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),
49
+ date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
50
+ };
51
+ }
52
+
53
+ /** Build one ZIP archive from text entries. Deterministic apart from the timestamps. */
54
+ export function zipSync(entries: readonly ZipEntry[], at: Date = new Date()): Buffer {
55
+ const stamp = dosStamp(at);
56
+ const locals: Buffer[] = [];
57
+ const centrals: Buffer[] = [];
58
+ let offset = 0;
59
+
60
+ for (const entry of entries) {
61
+ const name = Buffer.from(entry.path.replace(/^\/+/, ""), "utf8");
62
+ const raw = Buffer.from(entry.text, "utf8");
63
+ const deflated = deflateRawSync(raw);
64
+ const useDeflate = deflated.length < raw.length;
65
+ const body = useDeflate ? deflated : raw;
66
+ const crc = crc32(raw);
67
+
68
+ const local = Buffer.alloc(30);
69
+ local.writeUInt32LE(LOCAL_SIG, 0);
70
+ local.writeUInt16LE(VERSION, 4);
71
+ local.writeUInt16LE(FLAG_UTF8, 6);
72
+ local.writeUInt16LE(useDeflate ? 8 : 0, 8);
73
+ local.writeUInt16LE(stamp.time, 10);
74
+ local.writeUInt16LE(stamp.date, 12);
75
+ local.writeUInt32LE(crc, 14);
76
+ local.writeUInt32LE(body.length, 18);
77
+ local.writeUInt32LE(raw.length, 22);
78
+ local.writeUInt16LE(name.length, 26);
79
+ local.writeUInt16LE(0, 28);
80
+
81
+ const central = Buffer.alloc(46);
82
+ central.writeUInt32LE(CENTRAL_SIG, 0);
83
+ central.writeUInt16LE(VERSION, 4);
84
+ central.writeUInt16LE(VERSION, 6);
85
+ central.writeUInt16LE(FLAG_UTF8, 8);
86
+ central.writeUInt16LE(useDeflate ? 8 : 0, 10);
87
+ central.writeUInt16LE(stamp.time, 12);
88
+ central.writeUInt16LE(stamp.date, 14);
89
+ central.writeUInt32LE(crc, 16);
90
+ central.writeUInt32LE(body.length, 20);
91
+ central.writeUInt32LE(raw.length, 24);
92
+ central.writeUInt16LE(name.length, 28);
93
+ central.writeUInt16LE(0, 30); // extra
94
+ central.writeUInt16LE(0, 32); // comment
95
+ central.writeUInt16LE(0, 34); // disk start
96
+ central.writeUInt16LE(0, 36); // internal attrs
97
+ central.writeUInt32LE(0o644 << 16, 38); // external attrs: rw-r--r--
98
+ central.writeUInt32LE(offset, 42);
99
+
100
+ locals.push(local, name, body);
101
+ centrals.push(central, name);
102
+ offset += local.length + name.length + body.length;
103
+ }
104
+
105
+ const centralBuf = Buffer.concat(centrals);
106
+ const eocd = Buffer.alloc(22);
107
+ eocd.writeUInt32LE(EOCD_SIG, 0);
108
+ eocd.writeUInt16LE(0, 4); // this disk
109
+ eocd.writeUInt16LE(0, 6); // disk with central directory
110
+ eocd.writeUInt16LE(entries.length, 8);
111
+ eocd.writeUInt16LE(entries.length, 10);
112
+ eocd.writeUInt32LE(centralBuf.length, 12);
113
+ eocd.writeUInt32LE(offset, 16);
114
+ eocd.writeUInt16LE(0, 20); // comment length
115
+
116
+ return Buffer.concat([...locals, centralBuf, eocd]);
117
+ }