@officesdk/officesdk-plugin 0.0.0-stage → 1.0.3

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,150 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { DEFAULT_SOURCES, NPM_DEFAULTS, npmOptions, selectProfile } from './download-sources.mjs';
7
+
8
+ /**
9
+ * office-kit downloads for the universal package (spec 261110-universal-package §3.3, §4.2, §4.3): which Kit and
10
+ * editor resources this plugin version needs (its kit-manifest.json), where they live under the plugin data directory,
11
+ * how a Kit is made ready to run, and the downgrade guard.
12
+ */
13
+
14
+ export const platformKey = ({ platform = process.platform, arch = process.arch } = {}) => `${platform}-${arch}`;
15
+
16
+ export function readManifest(packageRoot) {
17
+ try { return JSON.parse(readFileSync(join(packageRoot, 'kit-manifest.json'), 'utf8')); } catch { return undefined; }
18
+ }
19
+
20
+ /**
21
+ * The sources one item tries, in the order its profile lists them (download-sources.json, spec 261111-npm-publish-prep
22
+ * §6): `mirror` (`OFFICESDK_KIT_MIRROR`, a directory with office-kit's release layout; only when set), `release` (the
23
+ * manifest's own sources: office-kit's GitHub release), `npm` (the editor only: the manifest's `editor.npm`).
24
+ */
25
+ function sourcesOf(ids, manifest, { mirror, npm, log }) {
26
+ const version = manifest.officeKit.version;
27
+ const out = [];
28
+ for (const entry of ids) {
29
+ if (entry.id === 'mirror') { if (mirror) out.push({ id: 'mirror', kind: 'url', base: `${mirror.replace(/\/+$/, '')}/${version}/` }); }
30
+ else if (entry.id === 'release') out.push(...manifest.sources);
31
+ else if (entry.id === 'npm') { const source = editorNpmSource(manifest, npm, log, entry); if (source) out.push(source); }
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /** The Kit's sources (the default profile unless `profile` says otherwise). */
37
+ export function kitSources(manifest, { mirror, profile = selectProfile(DEFAULT_SOURCES) } = {}) {
38
+ return sourcesOf(profile.kit, manifest, { mirror });
39
+ }
40
+
41
+ /**
42
+ * office-kit's editor package on npm (kit-manifest.json `editor.npm`), the editor's default source: NPM_DEFAULTS limits
43
+ * (download-sources.json may set its own). `npm`: `off` leaves it out; a URL replaces the registry
44
+ * (`OFFICESDK_EDITOR_NPM`, e.g. a registry mirror). The bytes are trusted only through the manifest's sha512, as from
45
+ * any source.
46
+ */
47
+ export const NPM_CONNECT_TIMEOUT_MS = NPM_DEFAULTS.connectTimeoutMs;
48
+ export const NPM_IDLE_MS = NPM_DEFAULTS.idleMs;
49
+ export function editorNpmSource(manifest, npm, log = () => {}, entry = {}) {
50
+ const pinned = manifest.editor?.npm;
51
+ const value = typeof npm === 'string' ? npm.trim() : '';
52
+ if (!pinned || /^(off|false|0|no|none)$/i.test(value)) return undefined;
53
+ const url = /^https?:\/\//i.test(value);
54
+ if (value && !url) log('warn', `OFFICESDK_EDITOR_NPM=${value} is neither off nor an http(s) URL; the manifest's registry is used`);
55
+ const registry = url ? value : pinned.registry;
56
+ return { id: 'npm', kind: 'npm', registry, package: pinned.package, version: pinned.version, ...npmOptions(entry) };
57
+ }
58
+
59
+ const run = (file, args, { timeout }) => new Promise((resolve, reject) => execFile(file, args, { timeout, windowsHide: true, maxBuffer: 1 << 20 }, (error, stdout, stderr) => (error ? reject(Object.assign(error, { stderr: String(stderr) })) : resolve(String(stdout)))));
60
+
61
+ /**
62
+ * Makes an unpacked Kit runnable and proves it: executable bits; on macOS no `com.apple.quarantine` (a Kit copied in
63
+ * from a browser download would otherwise be stopped by Gatekeeper, §1.4); then `--version --json` must name this
64
+ * manifest's version and protocol. Windows gets a longer first start (Defender scans a new exe).
65
+ */
66
+ export function kitPreparer(manifest, platform, { runFile = run, host = process.platform } = {}) {
67
+ const entry = manifest.kit[platform];
68
+ return async dir => {
69
+ for (const [name, file] of Object.entries(entry.files)) if (file.executable) await chmod(join(dir, ...name.split('/')), 0o755);
70
+ if (host === 'darwin') await runFile('xattr', ['-dr', 'com.apple.quarantine', dir], { timeout: 30_000 }).catch(() => {});
71
+ let info;
72
+ try { info = JSON.parse(await runFile(join(dir, entry.binary), ['--version', '--json'], { timeout: host === 'win32' ? 120_000 : 30_000 })); }
73
+ // Not retried by downloading again: the files were already checked; a slow first start (Defender) or a broken
74
+ // machine is not fixed by the same bytes. The next open runs the check again.
75
+ catch (error) { throw Object.assign(new Error(`the document engine does not start (${error?.code ?? ''} ${String(error?.stderr ?? error?.message ?? error).trim().slice(0, 200)})`), { code: 'kit-selftest', retry: false, final: true }); }
76
+ if (info?.version !== manifest.officeKit.version || info?.compat?.protocolVersion !== manifest.officeKit.protocol) {
77
+ throw Object.assign(new Error(`the document engine reports ${info?.version}/protocol ${info?.compat?.protocolVersion}, expected ${manifest.officeKit.version}/protocol ${manifest.officeKit.protocol}`), { code: 'kit-selftest', retry: false, final: true });
78
+ }
79
+ };
80
+ }
81
+
82
+ /**
83
+ * The two download items of this plugin version on this machine, or `{ unsupported }` when the manifest has no Kit for
84
+ * it. `root` is `<data>/office-kit`; `packageRoot/resources/{kit,office-kit}` is used in place when an offline package
85
+ * carries them.
86
+ */
87
+ export function officeKitItems(manifest, { root, packageRoot, host = {}, mirror, npm, runFile, prepare, log, profile = selectProfile(DEFAULT_SOURCES) } = {}) {
88
+ const platform = platformKey(host);
89
+ const version = manifest.officeKit.version;
90
+ const kit = manifest.kit?.[platform];
91
+ const sources = sourcesOf(profile.kit, manifest, { mirror, log });
92
+ // The editor: in its profile's order (a mirror when set, then npm). The Kit never comes from npm.
93
+ const editorSources = sourcesOf(profile.editor, manifest, { mirror, npm, log });
94
+ const editor = {
95
+ key: `editor/${version}`, label: 'office-kit editor resources', dir: join(root, 'editor', version),
96
+ archive: { file: manifest.editor.file, size: manifest.editor.size, integrity: manifest.editor.integrity },
97
+ files: manifest.editor.files, strip: manifest.editor.root, outside: 'skip', sources: editorSources,
98
+ bundledDir: packageRoot && join(packageRoot, 'resources', 'office-kit'),
99
+ };
100
+ // What the manifest does have, for the message (test platforms are named as such).
101
+ const supported = Object.entries(manifest.kit ?? {}).map(([name, row]) => ({ platform: name, status: row.status }));
102
+ // A platform office-kit builds only a library for (no executable, e.g. OpenHarmony) is not one the plugin can run.
103
+ if (!kit?.binary) return { platform, editor, unsupported: { platform, reason: 'platform', supported: supported.filter(row => manifest.kit[row.platform]?.binary) } };
104
+ return {
105
+ platform, editor,
106
+ kit: {
107
+ key: `kit/${version}/${platform}`, label: `office-kit ${version} (${platform})`, dir: join(root, 'kit', version, platform),
108
+ archive: { file: kit.file, size: kit.size, integrity: kit.integrity }, files: kit.files, sources,
109
+ bundledDir: packageRoot && join(packageRoot, 'resources', 'kit'),
110
+ binary: kit.binary, status: kit.status,
111
+ prepare: prepare ?? kitPreparer(manifest, platform, { runFile, host: host.platform ?? process.platform }),
112
+ },
113
+ };
114
+ }
115
+
116
+ const semver = version => /^(\d+)\.(\d+)\.(\d+)/.exec(version ?? '')?.slice(1).map(Number);
117
+ export const versionBelow = (a, b) => {
118
+ const [x, y] = [semver(a), semver(b)];
119
+ if (!x || !y) return false;
120
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i];
121
+ return false;
122
+ };
123
+
124
+ /**
125
+ * §4.3 downgrade guard. `highest` is what the newest Kit that ever ran here recorded: `{ version, indexVersion,
126
+ * downgradeFloor }`. A Kit may start when its version is at least that floor and it reads that index version.
127
+ */
128
+ export function downgradeProblem(manifest, highest) {
129
+ if (!highest?.version) return undefined;
130
+ const kit = manifest.officeKit;
131
+ const reads = kit.readsIndexVersions ?? [];
132
+ if ((highest.downgradeFloor && versionBelow(kit.version, highest.downgradeFloor)) || (highest.indexVersion !== undefined && reads.length && !reads.includes(highest.indexVersion))) {
133
+ return { version: highest.version, message: `这台机器用过更新的文档引擎 ${highest.version},当前插件的引擎 ${kit.version} 不能再打开它整理过的文档。请更新插件(或安装使用同一引擎版本的插件)。This machine has run the newer document engine ${highest.version}; this plugin's engine ${kit.version} cannot read what it wrote. Update the plugin.` };
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ /** `<root>/highest.json`, written after a Kit started and opened its work directory (never before). */
139
+ export async function readHighest(root) { try { return JSON.parse(await readFile(join(root, 'highest.json'), 'utf8')); } catch { return undefined; } }
140
+ export async function recordHighest(root, manifest) {
141
+ const current = await readHighest(root);
142
+ const kit = manifest.officeKit;
143
+ if (current?.version && !versionBelow(current.version, kit.version)) return current;
144
+ const next = { version: kit.version, indexVersion: kit.indexVersion, downgradeFloor: kit.downgradeFloor };
145
+ await mkdir(root, { recursive: true });
146
+ const tmp = join(root, `highest.json.${randomUUID()}.tmp`);
147
+ await writeFile(tmp, JSON.stringify(next, null, 2));
148
+ await rename(tmp, join(root, 'highest.json'));
149
+ return next;
150
+ }
@@ -0,0 +1,139 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { Downloader } from './downloader.mjs';
4
+ import { downgradeProblem, officeKitItems, readHighest, recordHighest } from './office-kit.mjs';
5
+
6
+ /**
7
+ * The document engine of the universal package (spec 261110-universal-package §4.2–§4.3): office-kit's Kit and editor
8
+ * resources for this plugin version, downloaded on first need (or right after start, in the background), checked,
9
+ * and handed to KitProcess as a path. Progress and failures are kept for the Client (`status()`).
10
+ */
11
+ const PREFETCH_DELAY_MS = 5000;
12
+ const mb = bytes => (bytes / 1048576).toFixed(0);
13
+ /** Whether the package carries every file of `item` (the same test `Downloader.ensure` uses to take the packaged copy). */
14
+ const packaged = item => Boolean(item?.bundledDir && Object.keys(item.files).every(name => existsSync(join(item.bundledDir, ...name.split('/')))));
15
+
16
+ export class OfficeKitRuntime {
17
+ constructor({ manifest, dataRoot, packageRoot, host = {}, mirror, npm, profile, downloader, log = () => {}, runFile }) {
18
+ this.manifest = manifest;
19
+ this.root = join(dataRoot, 'office-kit');
20
+ this.log = log;
21
+ this.downloader = downloader ?? new Downloader({ root: this.root, log });
22
+ const items = officeKitItems(manifest, { root: this.root, packageRoot, host, mirror, npm, runFile, log, ...profile && { profile } });
23
+ Object.assign(this, { kitItem: items.kit, editorItem: items.editor, platform: items.platform, unsupported: items.unsupported });
24
+ this.progress = {};
25
+ this.lifetime = new AbortController();
26
+ this.downloader.on('progress', event => {
27
+ const previous = this.progress[event.key] ?? {};
28
+ this.progress[event.key] = { ...previous, ...event, ...event.phase !== 'failed' && { error: undefined } };
29
+ });
30
+ }
31
+
32
+ /**
33
+ * Whether both items are already here (packaged — the editor resources in every package since 261112-bundle-editor, the
34
+ * Kit in an offline package — or an earlier download): opening a document will not wait.
35
+ */
36
+ ready() {
37
+ const here = item => item && (this.packaged(item) || this.downloader.isComplete(item));
38
+ return Boolean(!this.unsupported && here(this.kitItem) && here(this.editorItem));
39
+ }
40
+
41
+ /**
42
+ * Whether the package carries `item` (1041 files for the editor): checked again by binary() and prune(), remembered
43
+ * for status() and ready(), which the Client polls while a document waits.
44
+ */
45
+ packaged(item, { fresh = false } = {}) {
46
+ this.packagedSeen ??= new Map();
47
+ if (fresh || !this.packagedSeen.has(item)) this.packagedSeen.set(item, packaged(item));
48
+ return this.packagedSeen.get(item);
49
+ }
50
+
51
+ /** The editor resources directory once known; the package's own copy (an offline package) until then. */
52
+ get editorDir() { return this.editorPath; }
53
+
54
+ /**
55
+ * The Kit executable, downloading Kit and the editor resources first when needed (KitProcess calls this before each
56
+ * start). Refuses a Kit below what a newer Kit on this machine requires (§4.3).
57
+ */
58
+ async binary() {
59
+ if (this.unsupported) throw Object.assign(new Error(`OfficeSDK has no document engine for ${this.unsupported.platform}.`), { code: 'unsupported-platform' });
60
+ // A platform office-kit releases a Kit for but nobody has verified here yet: it runs, and says so once.
61
+ if (this.kitItem.status === 'test' && !this.testNoted) { this.testNoted = true; this.log('warn', `the document engine for ${this.platform} is in test (kit-manifest.json status test)`); }
62
+ const refused = downgradeProblem(this.manifest, await readHighest(this.root));
63
+ if (refused) throw Object.assign(new Error(refused.message), { code: 'kit-downgrade' });
64
+ try {
65
+ const signal = this.lifetime.signal;
66
+ for (const item of [this.kitItem, this.editorItem]) this.packaged(item, { fresh: true });
67
+ const [kit, editor] = await Promise.all([this.downloader.ensure(this.kitItem, { signal }), this.downloader.ensure(this.editorItem, { signal })]);
68
+ this.editorPath = editor.dir;
69
+ this.kitDir = kit.dir;
70
+ return join(kit.dir, this.kitItem.binary);
71
+ } catch (error) {
72
+ if (this.lifetime.signal.aborted) throw this.lifetime.signal.reason;
73
+ // The engine downloaded and checked out but would not start (or reports another version): say that, not "download failed".
74
+ const selftest = [error, ...(error?.failures ?? [])].find(item => item?.code === 'kit-selftest');
75
+ if (selftest) throw Object.assign(new Error(`文档引擎下载完成但无法启动:${selftest.message}。可重试;Windows 上可能是安全软件正在检查。The document engine was downloaded but does not start (${selftest.message}).`), { code: 'kit-selftest' });
76
+ // The reason that matters: a source that was tried (network, HTTP, checksum), not one skipped for lack of a token.
77
+ const failures = error?.failures ?? [];
78
+ const reason = (failures.filter(failure => failure.code !== 'no-token').at(-1) ?? failures.at(-1))?.message ?? error?.message ?? String(error);
79
+ throw Object.assign(new Error(`文档引擎下载失败:${reason}。请检查网络后重试。The document engine could not be downloaded (${reason}); retry when online.`), { code: error?.code === 'denied' ? 'denied' : 'download-failed', cause: error });
80
+ }
81
+ }
82
+
83
+ /** Starts the download in the background shortly after start, so the first document seldom waits. */
84
+ prefetch({ delayMs = PREFETCH_DELAY_MS } = {}) {
85
+ if (this.unsupported || this.prefetching) return;
86
+ this.prefetching = setTimeout(() => { void this.binary().catch(error => this.log('warn', error.message)); }, delayMs);
87
+ this.prefetching.unref?.();
88
+ }
89
+
90
+ /** Stops waiting and downloading (the plugin unloads); a later instance resumes from the .part files. */
91
+ dispose() { clearTimeout(this.prefetching); this.lifetime.abort(Object.assign(new Error('The plugin was unloaded.'), { code: 'kit-suspended' })); }
92
+
93
+ /** After a Kit started and opened its work directory: the downgrade record moves up (never on a failed start). */
94
+ async markStarted() { try { await recordHighest(this.root, this.manifest); } catch (error) { this.log('warn', `highest.json not written: ${error?.message}`); } }
95
+
96
+ /**
97
+ * Removes other versions' Kit and editor directories not used for 30 days (§4.3 cleanup). Always kept: this version,
98
+ * the most recently used other version (a rollback needs no download), and a Kit that is running (the work root
99
+ * records which binary it started, `kitWork/.officesdk-kit.running`). Editor directories are not kept when this
100
+ * package carries the editor resources itself.
101
+ */
102
+ async prune({ kitWork, isAlive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } } } = {}) {
103
+ const dirs = [];
104
+ // Hidden names are downloads in progress (`.x.tmp-…`, `.x.old-…`); they are never pruned here.
105
+ const list = dir => { try { return readdirSync(dir).filter(name => !name.startsWith('.')); } catch { return []; } };
106
+ for (const version of list(join(this.root, 'kit'))) for (const platform of list(join(this.root, 'kit', version))) dirs.push(join(this.root, 'kit', version, platform));
107
+ for (const version of list(join(this.root, 'editor'))) dirs.push(join(this.root, 'editor', version));
108
+ // A packaged editor (261112-bundle-editor) needs no data directory copy: an older plugin's download, this version's
109
+ // included, ages out. While the packaged copy is incomplete the download in use stays.
110
+ const editorPackaged = this.packaged(this.editorItem, { fresh: true });
111
+ const keep = new Set([this.kitItem?.dir, !editorPackaged && this.editorItem.dir].filter(Boolean));
112
+ let running;
113
+ try { running = JSON.parse(readFileSync(join(kitWork, '.officesdk-kit.running'), 'utf8')); } catch {}
114
+ if (running?.binary && running.pid && isAlive(running.pid)) keep.add(dirname(running.binary));
115
+ const used = Object.values(this.downloader.readState().items ?? {}).filter(entry => entry?.dir && !keep.has(entry.dir)).sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0));
116
+ for (const kind of editorPackaged ? ['kit'] : ['kit', 'editor']) { const previous = used.find(entry => entry.dir.startsWith(join(this.root, kind))); if (previous) keep.add(previous.dir); }
117
+ return this.downloader.prune({ dirs, keep: dir => keep.has(dir) });
118
+ }
119
+
120
+ /** What the Client shows while a document waits: `{ state, received, total, label?, error? }`. */
121
+ status() {
122
+ if (this.unsupported) return { state: 'unsupported', platform: this.unsupported.platform };
123
+ // Only what has to be downloaded counts: a packaged item is ready and adds nothing to the sizes shown.
124
+ const rows = [this.kitItem, this.editorItem].filter(item => !this.packaged(item)).map(item => ({ item, progress: this.progress[item.key] }));
125
+ const failed = rows.find(row => row.progress?.phase === 'failed');
126
+ const total = rows.reduce((sum, row) => sum + (row.item.archive?.size ?? 0), 0);
127
+ const received = rows.reduce((sum, row) => sum + (this.downloader.isComplete(row.item) || row.progress?.phase === 'ready' ? row.item.archive.size : row.progress?.received ?? 0), 0);
128
+ if (failed) return { state: 'failed', received, total, error: failed.progress.error };
129
+ if (rows.every(row => this.downloader.isComplete(row.item) || row.progress?.phase === 'ready')) return { state: 'ready', received: total, total };
130
+ const busy = rows.find(row => row.progress && row.progress.phase !== 'ready');
131
+ if (!busy) return { state: 'idle', received, total };
132
+ // `source`: where the busy item is coming from; `fallback`: sources it gave up on (a mirror or npm that did not answer).
133
+ const fallback = rows.flatMap(row => (row.progress?.phase !== 'ready' && row.progress?.fallback) || []);
134
+ const testing = this.kitItem?.status === 'test';
135
+ const text = `正在下载文档引擎 ${mb(received)}/${mb(total)} MB${fallback.includes('npm') ? '(npm 源连不上,已改用其他来源下载)' : ''}${testing ? '(此平台测试中)' : ''}`;
136
+ return { state: busy.progress.phase === 'waiting' ? 'waiting' : 'downloading', phase: busy.progress.phase, received, total, text,
137
+ ...busy.progress.source && { source: busy.progress.source }, ...fallback.length && { fallback: [...new Set(fallback)] }, ...testing && { platformStatus: 'test' } };
138
+ }
139
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Where a download comes from (spec 261110-universal-package §4.4). A source is never trusted: whatever it returns is
3
+ * checked against the manifest's size and hashes by the downloader. Each opener resolves to
4
+ * `{ body, total?, etag?, resumed, resumable, format }`: `body` an async iterable of Buffers, `format` `tgz` (an archive
5
+ * whose sha512 the manifest pins) or `tar` (a plain tar stream, checked file by file).
6
+ *
7
+ * url `base + file` over HTTP(S): office-kit's release directory (its GitHub release) or a mirror with the same layout
8
+ * npm `{ registry, package, version }`: the packument's dist.tarball (reserved for office-kit's npm)
9
+ * DSH installs its proxy policy as undici's global dispatcher, so the global fetch here goes through the system proxy.
10
+ */
11
+ export class SourceError extends Error {
12
+ constructor(message, { code = 'source-failed', status, retry = true } = {}) { super(message); this.name = 'SourceError'; this.code = code; this.status = status; this.retry = retry; }
13
+ }
14
+
15
+ const CONNECT_TIMEOUT_MS = 30_000;
16
+ const withTimeout = (signal, ms) => (signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms));
17
+ // Every `//user:password@` in a URL or in an error text that quotes one (fetch names the URL it refused).
18
+ const redactUrl = url => String(url).replace(/(\/\/)[^/@\s]+@/g, '$1');
19
+
20
+ /** Body of a fetch Response as an async iterable of Buffers. */
21
+ async function* bodyOf(response) {
22
+ for await (const chunk of response.body) yield Buffer.from(chunk);
23
+ }
24
+
25
+ async function openUrl(url, { offset = 0, etag, signal, headers = {}, fetchImpl = fetch, format = 'tgz', connectTimeoutMs = CONNECT_TIMEOUT_MS }) {
26
+ const request = { ...headers };
27
+ if (offset > 0 && etag) Object.assign(request, { Range: `bytes=${offset}-`, 'If-Range': etag });
28
+ let response;
29
+ // The connect timeout covers the headers only; the downloader times out a body that stops sending.
30
+ const connect = new AbortController();
31
+ const timer = setTimeout(() => connect.abort(new SourceError(`no answer from ${redactUrl(url)} in ${connectTimeoutMs / 1000} s`, { code: 'timeout' })), connectTimeoutMs);
32
+ try { response = await fetchImpl(url, { headers: request, signal: signal ? AbortSignal.any([signal, connect.signal]) : connect.signal, redirect: 'follow' }); }
33
+ catch (error) {
34
+ if (signal?.aborted) throw signal.reason;
35
+ throw connect.signal.aborted ? connect.signal.reason : new SourceError(redactUrl(`${url}: ${error?.cause?.code ?? error?.message ?? error}`), { code: 'network' });
36
+ } finally { clearTimeout(timer); }
37
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
38
+ throw new SourceError(`${redactUrl(url)}: HTTP ${response.status}`, { status: response.status, code: response.status === 404 ? 'not-found' : 'denied', retry: false });
39
+ }
40
+ if (!response.ok) throw new SourceError(`${redactUrl(url)}: HTTP ${response.status}`, { status: response.status });
41
+ const resumed = response.status === 206;
42
+ const length = Number(response.headers.get('content-length'));
43
+ const total = Number.isFinite(length) && length > 0 ? (resumed ? offset + length : length) : undefined;
44
+ return { body: bodyOf(response), total, etag: response.headers.get('etag') ?? undefined, resumed, resumable: response.headers.get('accept-ranges') === 'bytes' || resumed, format };
45
+ }
46
+
47
+ /**
48
+ * Opens one item from one source. `context`: `{ offset, etag, signal, fetchImpl, spawn }`. A source may set its own
49
+ * `connectTimeoutMs` (answer and headers; default 30 s): the npm copy of the editor uses a short one so a registry that
50
+ * cannot be reached gives way to the next source quickly.
51
+ */
52
+ export async function openSource(source, item, context = {}) {
53
+ item = { ...item, file: item.file ?? item.archive?.file, integrity: item.integrity ?? item.archive?.integrity };
54
+ if (source.connectTimeoutMs) context = { ...context, connectTimeoutMs: source.connectTimeoutMs };
55
+ switch (source.kind) {
56
+ case 'url': {
57
+ if (!item.file) throw new SourceError('a url source needs a file name', { retry: false });
58
+ return openUrl(`${source.base.replace(/\/?$/, '/')}${encodeURI(item.file)}`, context);
59
+ }
60
+ case 'npm': {
61
+ const fetchImpl = context.fetchImpl ?? fetch;
62
+ const registry = source.registry.replace(/\/?$/, '/');
63
+ const headers = source.token ? { Authorization: `Bearer ${source.token}` } : {};
64
+ const limit = context.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
65
+ let response, dist;
66
+ // The packument is small: its whole body counts against the same limit as its headers.
67
+ const packument = withTimeout(context.signal, limit);
68
+ try {
69
+ response = await fetchImpl(`${registry}${source.package.replace('/', '%2F')}`, { headers: { ...headers, Accept: 'application/json' }, signal: packument });
70
+ if (response.ok) dist = (await response.json())?.versions?.[source.version]?.dist;
71
+ } catch (error) {
72
+ if (context.signal?.aborted) throw context.signal.reason;
73
+ const timedOut = packument.aborted;
74
+ throw new SourceError(timedOut ? `no answer from ${redactUrl(registry)} in ${limit / 1000} s` : redactUrl(`${registry}: ${error?.cause?.code ?? error?.message ?? error}`), { code: timedOut ? 'timeout' : 'network' });
75
+ }
76
+ if (!response.ok) throw new SourceError(`${redactUrl(registry)}${source.package}: HTTP ${response.status}`, { status: response.status, retry: response.status >= 500 });
77
+ if (!dist?.tarball) throw new SourceError(`${source.package}@${source.version} is not in ${redactUrl(registry)}`, { code: 'not-found', retry: false });
78
+ // A registry that states an integrity must state the manifest's (GitLab's states only sha1, which is not compared).
79
+ if (dist.integrity?.startsWith('sha512-') && item.integrity && dist.integrity !== item.integrity) throw new SourceError(`${source.package}@${source.version}: registry integrity differs from the manifest`, { code: 'integrity', retry: false });
80
+ return openUrl(dist.tarball, { ...context, headers });
81
+ }
82
+ default:
83
+ throw new SourceError(`unknown source kind ${source.kind}`, { retry: false });
84
+ }
85
+ }
@@ -0,0 +1,235 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { once } from 'node:events';
3
+ import { createWriteStream } from 'node:fs';
4
+ import { chmod, mkdir } from 'node:fs/promises';
5
+ import { dirname, join, resolve, sep } from 'node:path';
6
+ import { createGunzip } from 'node:zlib';
7
+
8
+ /**
9
+ * A small streaming tar reader for the archives the plugin downloads (spec 261110-universal-package §4.2 step 5):
10
+ * office-kit's Kit archives and editor package, and `git archive` output for skills. Node has no tar module and
11
+ * Windows may have no `tar`, so this reads ustar with pax (`x`/`g`) and GNU long-name (`L`/`K`) extensions, including
12
+ * UTF-8 names. Only regular files and directories are accepted: links, devices and anything else are rejected, as are
13
+ * absolute names and names with `..`, so an archive can never write outside the target directory.
14
+ */
15
+
16
+ const BLOCK = 512;
17
+ export class TarError extends Error {
18
+ constructor(message) { super(message); this.name = 'TarError'; this.code = 'bad-archive'; }
19
+ }
20
+
21
+ const field = (block, offset, length) => {
22
+ const raw = block.subarray(offset, offset + length);
23
+ const end = raw.indexOf(0);
24
+ return (end < 0 ? raw : raw.subarray(0, end)).toString('utf8');
25
+ };
26
+ function octal(block, offset, length) {
27
+ const raw = block.subarray(offset, offset + length);
28
+ // GNU base-256 for sizes over 8 GiB: not expected here, refused rather than misread.
29
+ if (raw[0] & 0x80) throw new TarError('base-256 numbers are not supported');
30
+ const text = field(block, offset, length).trim();
31
+ if (!text) return 0;
32
+ if (!/^[0-7]+$/.test(text)) throw new TarError(`bad number ${JSON.stringify(text)}`);
33
+ return parseInt(text, 8);
34
+ }
35
+ function checksumOk(block) {
36
+ const stored = octal(block, 148, 8);
37
+ let sum = 0;
38
+ for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : block[i];
39
+ return sum === stored;
40
+ }
41
+ /** pax records: `<len> <key>=<value>\n`. */
42
+ function parsePax(buffer) {
43
+ const out = {};
44
+ let at = 0;
45
+ while (at < buffer.length) {
46
+ const space = buffer.indexOf(0x20, at);
47
+ if (space < 0) break;
48
+ const length = Number(buffer.subarray(at, space).toString('ascii'));
49
+ if (!Number.isInteger(length) || length <= 0) throw new TarError('bad pax record');
50
+ const record = buffer.subarray(space + 1, at + length - 1).toString('utf8');
51
+ const eq = record.indexOf('=');
52
+ if (eq > 0) out[record.slice(0, eq)] = record.slice(eq + 1);
53
+ at += length;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * The relative path an entry may be written to, or null to skip it. `strip` is a prefix every entry must have
60
+ * (`packages/dsh-adapter/skills/shimo-pptx/` for a git archive, `package/` for an npm tarball); entries outside it
61
+ * are rejected unless `outside: 'skip'`.
62
+ */
63
+ export function safeName(name, { strip = '', outside = 'reject' } = {}) {
64
+ let rel = name.replace(/\\/g, '/').replace(/^(\.\/)+/, '');
65
+ if (!rel || rel === '.') return null;
66
+ if (rel.startsWith('/') || /^[A-Za-z]:/.test(rel)) throw new TarError(`absolute path ${JSON.stringify(name)}`);
67
+ const parts = rel.split('/').filter(part => part !== '' && part !== '.');
68
+ if (parts.some(part => part === '..')) throw new TarError(`path with .. ${JSON.stringify(name)}`);
69
+ rel = parts.join('/');
70
+ if (strip) {
71
+ const prefix = strip.replace(/\/+$/, '');
72
+ if (rel === prefix) return null;
73
+ if (!rel.startsWith(`${prefix}/`)) {
74
+ if (outside === 'skip') return null;
75
+ throw new TarError(`${JSON.stringify(name)} is outside ${prefix}/`);
76
+ }
77
+ rel = rel.slice(prefix.length + 1);
78
+ }
79
+ return rel || null;
80
+ }
81
+
82
+ /**
83
+ * Reads a tar (gzip when `gzip`) from an async iterable of Buffers. For each regular file calls
84
+ * `onFile({ name, size, mode, executable }, chunks)` where `chunks` is an async iterable of its bytes that must be
85
+ * consumed before the next entry. Returns the number of files.
86
+ */
87
+ export async function readTar(source, onFile, { gzip = false, strip = '', outside = 'reject', onDirectory = () => {} } = {}) {
88
+ const input = gzip ? source.pipe ? source.pipe(createGunzip()) : gunzipIterable(source) : source;
89
+ const reader = new ChunkReader(input[Symbol.asyncIterator]());
90
+ let pax = {};
91
+ let globalPax = {};
92
+ let longName;
93
+ let count = 0;
94
+ for (;;) {
95
+ const block = await reader.read(BLOCK);
96
+ if (!block) throw new TarError('archive ended without its end blocks');
97
+ if (block.every(byte => byte === 0)) break;
98
+ if (!checksumOk(block)) throw new TarError('header checksum mismatch (not a tar, or corrupted)');
99
+ const type = String.fromCharCode(block[156] || 0x30);
100
+ let size = octal(block, 124, 12);
101
+ const headerPadded = Math.ceil(size / BLOCK) * BLOCK;
102
+ if (type === 'x' || type === 'g' || type === 'L' || type === 'K') {
103
+ const data = await reader.read(headerPadded);
104
+ if (!data) throw new TarError('archive ended inside an extended header');
105
+ const body = data.subarray(0, size);
106
+ if (type === 'x') pax = parsePax(body);
107
+ else if (type === 'g') globalPax = { ...globalPax, ...parsePax(body) };
108
+ else if (type === 'L') longName = field(body, 0, body.length);
109
+ // 'K' (long link name) only matters for links, which are rejected below.
110
+ continue;
111
+ }
112
+ const prefix = field(block, 345, 155);
113
+ let name = longName ?? pax.path ?? globalPax.path ?? (prefix ? `${prefix}/${field(block, 0, 100)}` : field(block, 0, 100));
114
+ if (pax.size !== undefined) size = Number(pax.size);
115
+ const mode = octal(block, 100, 8);
116
+ const entry = { pax, type };
117
+ pax = {};
118
+ longName = undefined;
119
+ if (!Number.isSafeInteger(size) || size < 0) throw new TarError(`bad size for ${JSON.stringify(name)}`);
120
+ const dataLength = Math.ceil(size / BLOCK) * BLOCK;
121
+ if (type === '5') {
122
+ // The prefix's own parent directories (git archive lists them) are not content: skipped, never rejected.
123
+ const rel = safeName(name, { strip, outside: 'skip' });
124
+ if (rel) onDirectory(rel);
125
+ await reader.skip(dataLength);
126
+ continue;
127
+ }
128
+ if (type !== '0' && type !== '\0' && type !== '7') throw new TarError(`${JSON.stringify(name)} is not a regular file (type ${JSON.stringify(type)}); links are not accepted`);
129
+ const rel = safeName(name, { strip, outside });
130
+ // macOS AppleDouble companions (`._name`, written by a Mac's tar for extended attributes) are not content; office-kit's
131
+ // Mac archive carries them, and npm drops them from packages, so they are skipped everywhere.
132
+ if (!rel || rel.split('/').at(-1).startsWith('._')) { await reader.skip(dataLength); continue; }
133
+ let left = size;
134
+ const chunks = (async function* () {
135
+ while (left > 0) {
136
+ const chunk = await reader.readSome(left);
137
+ if (!chunk) throw new TarError(`archive ended inside ${rel}`);
138
+ left -= chunk.length;
139
+ yield chunk;
140
+ }
141
+ })();
142
+ await onFile({ name: rel, size, mode, executable: Boolean(mode & 0o111) }, chunks);
143
+ // A caller that stopped reading early: drain the rest of the file.
144
+ for await (const _ of chunks) { /* drain */ }
145
+ await reader.skip(dataLength - size);
146
+ count++;
147
+ }
148
+ return count;
149
+ }
150
+
151
+ async function* gunzipIterable(source) {
152
+ const gunzip = createGunzip();
153
+ const feed = (async () => { try { for await (const chunk of source) if (!gunzip.write(chunk)) await new Promise(r => gunzip.once('drain', r)); gunzip.end(); } catch (error) { gunzip.destroy(error); } })();
154
+ yield* gunzip;
155
+ await feed;
156
+ }
157
+
158
+ class ChunkReader {
159
+ constructor(iterator) { this.iterator = iterator; this.buffer = Buffer.alloc(0); this.done = false; }
160
+ async fill(n) {
161
+ while (this.buffer.length < n && !this.done) {
162
+ const { value, done } = await this.iterator.next();
163
+ if (done) { this.done = true; break; }
164
+ this.buffer = this.buffer.length ? Buffer.concat([this.buffer, value]) : Buffer.from(value);
165
+ }
166
+ }
167
+ async read(n) {
168
+ if (n === 0) return Buffer.alloc(0);
169
+ await this.fill(n);
170
+ if (this.buffer.length < n) return null;
171
+ const out = this.buffer.subarray(0, n);
172
+ this.buffer = this.buffer.subarray(n);
173
+ return out;
174
+ }
175
+ async readSome(max) {
176
+ if (!this.buffer.length) await this.fill(1);
177
+ if (!this.buffer.length) return null;
178
+ const out = this.buffer.subarray(0, Math.min(max, this.buffer.length));
179
+ this.buffer = this.buffer.subarray(out.length);
180
+ return out;
181
+ }
182
+ async skip(n) {
183
+ while (n > 0) {
184
+ const chunk = await this.readSome(n);
185
+ if (!chunk) throw new TarError('archive ended early');
186
+ n -= chunk.length;
187
+ }
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Extracts into `dest` (which must exist or is created), hashing each file as it is written. Returns
193
+ * `{ files: { [rel]: { size, sha256, sha512, executable } } }`; `sha256`/`sha512` are SRI strings (`sha256-<base64>`).
194
+ * `keep(rel)` may skip files (return false).
195
+ */
196
+ export async function extractTar(source, dest, { gzip = false, strip = '', outside = 'reject', keep = () => true } = {}) {
197
+ const root = resolve(dest);
198
+ await mkdir(root, { recursive: true });
199
+ const files = {};
200
+ await readTar(source, async (entry, chunks) => {
201
+ if (!keep(entry.name)) return;
202
+ if (Object.hasOwn(files, entry.name)) throw new TarError(`${entry.name} appears twice`);
203
+ const target = join(root, ...entry.name.split('/'));
204
+ if (target !== root && !target.startsWith(root + sep)) throw new TarError(`${entry.name} escapes the target`);
205
+ await mkdir(dirname(target), { recursive: true });
206
+ const h256 = createHash('sha256');
207
+ const h512 = createHash('sha512');
208
+ const out = createWriteStream(target, { flags: 'wx', mode: entry.executable ? 0o755 : 0o644 });
209
+ const closed = new Promise((ok, fail) => { out.once('close', ok); out.once('error', fail); });
210
+ try {
211
+ for await (const chunk of chunks) {
212
+ h256.update(chunk); h512.update(chunk);
213
+ // events.once rejects on 'error' and removes both listeners afterwards.
214
+ if (!out.write(chunk)) await once(out, 'drain');
215
+ }
216
+ } finally { out.end(); }
217
+ await closed;
218
+ if (entry.executable) await chmod(target, 0o755);
219
+ files[entry.name] = { size: entry.size, sha256: `sha256-${h256.digest('base64')}`, sha512: `sha512-${h512.digest('base64')}`, executable: entry.executable };
220
+ }, { gzip, strip, outside });
221
+ return { files };
222
+ }
223
+
224
+ /** Lists and hashes every file without writing anything (tooling: manifests from an archive in memory). */
225
+ export async function hashTar(source, { gzip = false, strip = '', outside = 'reject' } = {}) {
226
+ const files = {};
227
+ await readTar(source, async (entry, chunks) => {
228
+ const h256 = createHash('sha256');
229
+ const h512 = createHash('sha512');
230
+ for await (const chunk of chunks) { h256.update(chunk); h512.update(chunk); }
231
+ if (Object.hasOwn(files, entry.name)) throw new TarError(`${entry.name} appears twice`);
232
+ files[entry.name] = { size: entry.size, sha256: `sha256-${h256.digest('base64')}`, sha512: `sha512-${h512.digest('base64')}`, executable: entry.executable };
233
+ }, { gzip, strip, outside });
234
+ return { files };
235
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.