@acryldev/plugin-share 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,880 @@
1
+ import { packagePlugin } from "./package.js";
2
+ import { createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { findSecrets } from "@acryldev/app-persistence";
5
+ import { digestFiles, digestFolder, portabilityIssues } from "@acryldev/blends-core";
6
+ import { NAME } from "@acryldev/extensions";
7
+ import { LOCK_FILE, writeLock } from "@acryldev/manifest/lock";
8
+ import { InvalidPluginSourceError, PluginStore, PullError, bumpVersion, gitCli, githubCli, githubReleasesOverHttps, hostInjectFromSource, httpsDownload, packFolder, parsePluginSource, pullPlugin, readTarball, sharePlugin, storeRootOf } from "@acryldev/plugin-hub-core";
9
+ import { Service } from "@deepseek-ai/cordis";
10
+ import { spawn } from "node:child_process";
11
+ import { createHash } from "node:crypto";
12
+ import { Readable } from "node:stream";
13
+ import { pipeline } from "node:stream/promises";
14
+ import { isMap, isSeq, parseDocument } from "yaml";
15
+ //#region native.ts
16
+ /**
17
+ * A plugin's native packages: large, per-OS npm packages a plugin needs and declares instead of depending on (a pull installs no dependencies). The
18
+ * Office preview plugin is the first: DSH's LibreOffice engine, 150 to 190 MB per OS, which the frame does not install (frame/packages.json `omit`).
19
+ *
20
+ * A plugin's package.json names them, one entry per OS and CPU, each pinned by npm's sha512:
21
+ *
22
+ * "@acryldev/blends": { "native": [
23
+ * { "package": "@deepseek-ai/libreoffice-kit-darwin-arm64", "version": "0.1.5", "os": "darwin", "cpu": "arm64",
24
+ * "integrity": "sha512-...", "size": 153171456 } ] }
25
+ *
26
+ * The pull reads the list (the policy below is pure), downloads only this computer's entry from the npm registry, checks its sha512, unpacks it into
27
+ * the app's home (`<home>/native/<package>@<version>`, so an `npm install` cannot prune it) and links `node_modules/<package>` to it, where the package
28
+ * that needs it resolves it. Only a missing package or the empty placeholder (`@acryldev/absent`) is replaced; a real copy npm installed stays.
29
+ * Removing the plugin takes the link and the download away; an app's start links again what an `npm install` unlinked.
30
+ */
31
+ /** Where a native package is downloaded from: the npm registry, and nothing else. */
32
+ const NATIVE_REGISTRY = "https://registry.npmjs.org";
33
+ /** The most a plugin's native packages may unpack to, all of its entries for one computer together. */
34
+ const NATIVE_MAX_BYTES = 1e9;
35
+ /** The file written last into an unpacked native package: without it the folder is an interrupted download. */
36
+ const COMPLETE = ".acrylblends-native-complete";
37
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
38
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
39
+ const SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u;
40
+ const OSES = [
41
+ "darwin",
42
+ "linux",
43
+ "win32"
44
+ ];
45
+ const CPUS = ["arm64", "x64"];
46
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
47
+ /** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */
48
+ function nativesOf(manifest) {
49
+ const section = manifest.acrylblends;
50
+ if (section === void 0 || isObject(section) && section.native === void 0) return { natives: [] };
51
+ if (!isObject(section) || !Array.isArray(section.native)) return { error: "\"acrylblends.native\" is not a list" };
52
+ const natives = [];
53
+ for (const [index, entry] of section.native.entries()) {
54
+ const at = `acrylblends.native[${index}]`;
55
+ if (!isObject(entry)) return { error: `${at} is not an object` };
56
+ const { package: name, version, os, cpu, integrity, size } = entry;
57
+ if (typeof name !== "string" || !NPM_NAME.test(name)) return { error: `${at}.package is not an npm package name` };
58
+ if (typeof version !== "string" || !EXACT_VERSION.test(version)) return { error: `${at}.version is not an exact version` };
59
+ if (typeof os !== "string" || !OSES.includes(os)) return { error: `${at}.os is not one of ${OSES.join(", ")}` };
60
+ if (cpu !== void 0 && (typeof cpu !== "string" || !CPUS.includes(cpu))) return { error: `${at}.cpu is not one of ${CPUS.join(", ")}` };
61
+ if (typeof integrity !== "string" || !SHA512.test(integrity)) return { error: `${at}.integrity is not npm's sha512 of the tarball` };
62
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size <= 0) return { error: `${at}.size is not a number of bytes` };
63
+ if (size > 1e9) return { error: `${at} unpacks to ${size} bytes, more than a plugin may bring (${NATIVE_MAX_BYTES})` };
64
+ natives.push({
65
+ package: name,
66
+ version,
67
+ os,
68
+ ...cpu === void 0 ? {} : { cpu },
69
+ integrity,
70
+ size
71
+ });
72
+ }
73
+ return { natives };
74
+ }
75
+ /** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */
76
+ function nativeFor(natives, platform = process.platform, arch = process.arch) {
77
+ return natives.find((entry) => entry.os === platform && entry.cpu === arch) ?? natives.find((entry) => entry.os === platform && entry.cpu === void 0);
78
+ }
79
+ /** The tarball's address in the npm registry, the way npm names it. */
80
+ function tarballUrl(native) {
81
+ const base = native.package.slice(native.package.lastIndexOf("/") + 1);
82
+ return `${NATIVE_REGISTRY}/${native.package}/-/${base}-${native.version}.tgz`;
83
+ }
84
+ /** The real ones: https from the npm registry, and the system's tar (macOS, Linux, and Windows 10 and later carry one), which keeps execute bits. */
85
+ function nativePorts() {
86
+ return {
87
+ async download(url, file) {
88
+ if (!url.startsWith(`https://registry.npmjs.org/`)) throw new Error(`${url} is not in the npm registry`);
89
+ const response = await fetch(url);
90
+ if (!response.ok || response.body === null) throw new Error(`the npm registry answered ${response.status} for ${url}`);
91
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(file));
92
+ },
93
+ unpack: (file, dir) => new Promise((done, fail) => {
94
+ const tar = spawn("tar", [
95
+ "-xzf",
96
+ file,
97
+ "-C",
98
+ dir,
99
+ "--strip-components=1"
100
+ ], {
101
+ stdio: [
102
+ "ignore",
103
+ "ignore",
104
+ "pipe"
105
+ ],
106
+ windowsHide: true
107
+ });
108
+ let error = "";
109
+ tar.stderr.on("data", (chunk) => {
110
+ error += chunk.toString();
111
+ });
112
+ tar.once("error", fail);
113
+ tar.once("exit", (code) => code === 0 ? done() : fail(/* @__PURE__ */ new Error(`tar could not unpack ${file}: ${error.trim()}`)));
114
+ })
115
+ };
116
+ }
117
+ /** The folder a native package is unpacked into. */
118
+ function nativeStore(home, native) {
119
+ return join(home, "native", `${native.package.replace("/", "+")}@${native.version}`);
120
+ }
121
+ const linkOf = (root, native) => join(root, "node_modules", ...native.package.split("/"));
122
+ /** What is at the package's place in node_modules: our link, nothing, something we may replace, or a real package someone installed. */
123
+ function placeState(link, store) {
124
+ let stat;
125
+ try {
126
+ stat = lstatSync(link);
127
+ } catch {
128
+ return "missing";
129
+ }
130
+ if (stat.isSymbolicLink()) {
131
+ let target;
132
+ try {
133
+ target = realpathSync(link);
134
+ } catch {
135
+ return "replaceable";
136
+ }
137
+ if (existsSync(store) && target === realpathSync(store)) return "ours";
138
+ if (existsSync(dirname(store)) && dirname(target) === realpathSync(dirname(store))) return "replaceable";
139
+ }
140
+ let name;
141
+ try {
142
+ name = JSON.parse(readFileSync(join(link, "package.json"), "utf8")).name;
143
+ } catch {
144
+ return stat.isSymbolicLink() ? "replaceable" : "foreign";
145
+ }
146
+ return name === "@acryldev/absent" ? "replaceable" : "foreign";
147
+ }
148
+ const sha512Of = async (file) => {
149
+ const hash = createHash("sha512");
150
+ await pipeline(createReadStream(file), hash);
151
+ return `sha512-${hash.digest("base64")}`;
152
+ };
153
+ /** Download, check and unpack into the store; the store appears whole or not at all. */
154
+ async function fetchInto(native, store, ports) {
155
+ mkdirSync(dirname(store), { recursive: true });
156
+ const incoming = mkdtempSync(join(dirname(store), ".incoming-"));
157
+ try {
158
+ const file = join(incoming, "package.tgz");
159
+ await ports.download(tarballUrl(native), file);
160
+ if (await sha512Of(file) !== native.integrity) throw new Error(`${native.package}@${native.version} from npm is not the file the plugin names (its sha512 differs)`);
161
+ const unpacked = join(incoming, "package");
162
+ mkdirSync(unpacked);
163
+ await ports.unpack(file, unpacked);
164
+ const manifest = JSON.parse(readFileSync(join(unpacked, "package.json"), "utf8"));
165
+ if (manifest.name !== native.package || manifest.version !== native.version) throw new Error(`the tarball holds ${String(manifest.name)}@${String(manifest.version)}, not ${native.package}@${native.version}`);
166
+ writeFileSync(join(unpacked, COMPLETE), "");
167
+ rmSync(store, {
168
+ recursive: true,
169
+ force: true
170
+ });
171
+ renameSync(unpacked, store);
172
+ } finally {
173
+ rmSync(incoming, {
174
+ recursive: true,
175
+ force: true
176
+ });
177
+ }
178
+ }
179
+ /** Make the native package resolvable from the app: download it unless the store has it, and link it. @throws when the download fails or differs. */
180
+ async function ensureNative(native, places, ports = nativePorts()) {
181
+ const store = nativeStore(places.home, native);
182
+ const link = linkOf(places.root, native);
183
+ const state = placeState(link, store);
184
+ if (state === "foreign") return "present";
185
+ const complete = existsSync(join(store, COMPLETE));
186
+ if (state === "ours" && complete) return "unchanged";
187
+ if (!complete) await fetchInto(native, store, ports);
188
+ rmSync(link, {
189
+ recursive: true,
190
+ force: true
191
+ });
192
+ mkdirSync(dirname(link), { recursive: true });
193
+ symlinkSync(store, link, process.platform === "win32" ? "junction" : "dir");
194
+ return complete ? "linked" : "downloaded";
195
+ }
196
+ /** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */
197
+ function releaseNative(native, places, keepDownload = false) {
198
+ const store = nativeStore(places.home, native);
199
+ const link = linkOf(places.root, native);
200
+ if (placeState(link, store) === "ours") unlinkSync(link);
201
+ if (!keepDownload) rmSync(store, {
202
+ recursive: true,
203
+ force: true
204
+ });
205
+ }
206
+ //#endregion
207
+ //#region publish.ts
208
+ /** The line a friend copies: it names the bytes, so the check comes for free. */
209
+ const pullLineOf = (owner, repo, version, digest) => `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`;
210
+ /**
211
+ * The same plan: what the person confirmed is what would be published now. `released` only explains the version, and is gone once the next one is packaged.
212
+ * Field by field, so a plan that came back through JSON from another surface (the frame's confirm) is the same plan whatever order its fields arrived in.
213
+ */
214
+ function samePlan(a, b) {
215
+ return a.owner === b.owner && a.repo === b.repo && a.version === b.version && a.visibility === b.visibility && a.license === b.license && a.createsRepository === b.createsRepository && a.integrity === b.integrity && a.digest === b.digest && a.pullLine === b.pullLine && a.files.length === b.files.length && a.files.every((file, index) => file === b.files[index]);
216
+ }
217
+ //#endregion
218
+ //#region pull-check.ts
219
+ /**
220
+ * What decides whether a pulled plugin may enter this app. Pure, over the files of the package: nothing here touches a disk or runs the plugin,
221
+ * so a refusal has nothing to undo (Clean Architecture: policy free of I/O).
222
+ */
223
+ const refuse = (refusal, reason, next) => ({
224
+ ok: false,
225
+ refusal,
226
+ reason,
227
+ next
228
+ });
229
+ const SHA256 = /^[0-9a-f]{64}$/;
230
+ const DIGEST_MARK = "@sha256:";
231
+ /** The source a person wrote, split into where it comes from and the content digest it names. @throws when the digest is malformed. */
232
+ function splitDigest(input) {
233
+ const at = input.lastIndexOf(DIGEST_MARK);
234
+ if (at === -1) return { source: input };
235
+ const digest = input.slice(at + 8);
236
+ if (!SHA256.test(digest)) throw new Error(`"${digest}" is not a content digest: it has 64 lowercase hex characters`);
237
+ return {
238
+ source: input.slice(0, at),
239
+ digest
240
+ };
241
+ }
242
+ /** The entry files the extensions folder loads, in its order. */
243
+ const ENTRIES = [
244
+ "index.ts",
245
+ "index.js",
246
+ "index.mjs"
247
+ ];
248
+ const text = (file) => Buffer.from(file.bytes).toString("utf8");
249
+ /** The first reason this package may not enter the app, or undefined. */
250
+ function pullRefusal(manifest, files, context) {
251
+ const name = String(manifest.name);
252
+ if (!context.nameFits(name)) return refuse("name", `the package is called "${name}", which a folder in plugins/ cannot hold`, "ask its author to release it under lowercase letters, digits and dashes");
253
+ const digest = digestFiles(files);
254
+ if (context.digest !== void 0 && context.digest !== digest) return refuse("digest", `${digest} is not the digest the source names (${context.digest}); these are different bytes`, "ask the person who gave you the digest which release they meant");
255
+ const issues = portabilityIssues(files);
256
+ if (issues.length > 0) return refuse("portability", issues.map((issue) => `${issue.path}: ${issue.reason}`).join("; "), "ask its author to fix this and release again, so it works on every OS");
257
+ const dependencies = Object.keys(manifest.dependencies ?? {});
258
+ if (dependencies.length > 0) return refuse("dependencies", `it needs ${dependencies.join(", ")} installed, and a pull installs nothing`, "ask its author to bundle them or name them as peers");
259
+ const native = nativesOf(manifest);
260
+ if ("error" in native) return refuse("native", native.error, "ask its author to fix \"acrylblends.native\" in its package.json and release again");
261
+ const entry = ENTRIES.flatMap((path) => files.filter((file) => file.path === path))[0];
262
+ if (entry === void 0) return refuse("entry", `it has none of ${ENTRIES.join(", ")} at its top level`, "this package is not a plugin an app can load; ask its author");
263
+ const inject = hostInjectFromSource(text(entry));
264
+ if (inject !== void 0 && "error" in inject) return refuse("inject", `${inject.error}. A pull reads what a plugin needs without running it`, "ask its author to list the services as plain names");
265
+ const missing = (inject?.names ?? []).filter((service) => !context.hasService(service));
266
+ if (missing.length > 0) return missingServices(missing);
267
+ }
268
+ const missingServices = (missing) => refuse("missing-service", `it needs ${missing.join(", ")}, which this app does not have`, "add the plugin that provides it, then pull again");
269
+ //#endregion
270
+ //#region pull-list.ts
271
+ /**
272
+ * A group's list of plugins: one source per line, as each person sends it (`github:<owner>/<repo>@<version>@sha256:<digest>`, or the whole line
273
+ * `plugin publish` prints). The list is text a person or a group keeps (a file in the app, a gist, a file in a repository), so reading it is
274
+ * forgiving about comments, blank lines and the pasted command, and strict about anything else: a line that is not one source is named, not guessed.
275
+ */
276
+ /** A list is a few lines of text: anything larger is not a list of plugins. */
277
+ const LIST_MAX_BYTES = 64 * 1024;
278
+ /** The command a person pastes from `plugin publish`: only its source is kept. */
279
+ const PULL_COMMAND = /^(?:npm run acryl --\s+)?plugin pull\s+/u;
280
+ /** A `#` at the start of a line or after a space begins a comment; a source never holds one there. */
281
+ const COMMENT = /(?:^|\s)#.*$/u;
282
+ /** The sources of a list, in order and without repeats, and the lines that are not a source. */
283
+ function parsePullList(text) {
284
+ const sources = [];
285
+ const problems = [];
286
+ const seen = /* @__PURE__ */ new Set();
287
+ text.split(/\r?\n/u).forEach((raw, index) => {
288
+ const line = index + 1;
289
+ const value = raw.replace(COMMENT, "").trim().replace(PULL_COMMAND, "").trim();
290
+ if (value === "") return;
291
+ if (/\s/u.test(value)) {
292
+ problems.push(`line ${String(line)} holds more than one word ("${value}"); write one source per line`);
293
+ return;
294
+ }
295
+ if (seen.has(value)) return;
296
+ seen.add(value);
297
+ sources.push({
298
+ line,
299
+ source: value
300
+ });
301
+ });
302
+ if (sources.length > 100) problems.push(`the list has ${String(sources.length)} sources; a list holds at most ${String(100)}`);
303
+ return {
304
+ sources,
305
+ problems
306
+ };
307
+ }
308
+ /** @returns undefined for something that is neither (an http: address, a github: source): the caller names what a list may be. */
309
+ function pullListLocation(from) {
310
+ const value = from.trim();
311
+ if (value === "") return void 0;
312
+ if (/^https:\/\//iu.test(value)) return {
313
+ kind: "address",
314
+ url: value
315
+ };
316
+ if (/^[a-z][a-z0-9+.-]+:/iu.test(value) && !/^[a-z]:[\\/]/iu.test(value)) return void 0;
317
+ return {
318
+ kind: "file",
319
+ path: value
320
+ };
321
+ }
322
+ //#endregion
323
+ //#region pulled-records.ts
324
+ /**
325
+ * What an app remembers about the plugins it pulled: their source and digests, in the `plugin-share` row's config of `blend.yaml`. A row's config is
326
+ * resolved into `blend.lock.json` too, so the lock records them with no new format, and a copy of the app can fetch exactly the same bytes. Pure text
327
+ * to text; comments and the person's formatting stay.
328
+ */
329
+ const ROW = "plugin-share";
330
+ const isRecord = (value) => {
331
+ const record = value;
332
+ return typeof record?.source === "string" && typeof record.integrity === "string" && typeof record.digest === "string";
333
+ };
334
+ /** The plugins this definition remembers pulling. */
335
+ function pulledRecords(text) {
336
+ const rows = parseDocument(text).toJS()?.spec?.rows;
337
+ if (!Array.isArray(rows)) return {};
338
+ const pulled = rows.find((row) => row?.name === ROW)?.config?.pulled;
339
+ if (typeof pulled !== "object" || pulled === null) return {};
340
+ return Object.fromEntries(Object.entries(pulled).filter(([, record]) => isRecord(record)));
341
+ }
342
+ /**
343
+ * The definition with one plugin's record written, or taken out when `record` is undefined. Unchanged when it has no `plugin-share` row: an app
344
+ * composed without the row has nowhere to remember.
345
+ */
346
+ function withPulledRecord(text, name, record) {
347
+ const document = parseDocument(text);
348
+ const rows = document.getIn(["spec", "rows"]);
349
+ if (!isSeq(rows)) return text;
350
+ const row = rows.items.find((item) => isMap(item) && item.get("name") === "plugin-share");
351
+ if (!isMap(row)) return text;
352
+ if (record === void 0) {
353
+ if (!row.hasIn([
354
+ "config",
355
+ "pulled",
356
+ name
357
+ ])) return text;
358
+ row.deleteIn([
359
+ "config",
360
+ "pulled",
361
+ name
362
+ ]);
363
+ const left = row.getIn(["config", "pulled"]);
364
+ if (isMap(left) && left.items.length === 0) row.deleteIn(["config", "pulled"]);
365
+ const config = row.get("config");
366
+ if (isMap(config) && config.items.length === 0) row.delete("config");
367
+ } else {
368
+ row.setIn(["config"], row.get("config") ?? document.createNode({}));
369
+ if (!row.hasIn(["config", "pulled"])) row.setIn(["config", "pulled"], document.createNode({}));
370
+ row.setIn([
371
+ "config",
372
+ "pulled",
373
+ name
374
+ ], document.createNode(record));
375
+ }
376
+ return String(document);
377
+ }
378
+ //#endregion
379
+ //#region index.ts
380
+ /**
381
+ * Sharing a plugin between people: `pull(source)` turns a release someone published into a running plugin in this app. It fetches without running
382
+ * anything, decides from the package's files (`pull-check.ts`), and hands a folder to `extensions`, which owns the install and its rollback.
383
+ * Design: docs/plans/plugin-share.md.
384
+ */
385
+ /** The account that released a source: the owner of a `github:<owner>/<repo>@<version>` source or of a release address on github.com. */
386
+ const authorOf = (source) => (/^github:([^/]+)\//u.exec(source) ?? /^https:\/\/github\.com\/([^/]+)\//u.exec(source))?.[1];
387
+ /** The version a plugin folder's `package.json` names, when it names a plain one. */
388
+ function releaseOf(folder) {
389
+ try {
390
+ const version = JSON.parse(readFileSync(join(folder, "package.json"), "utf8")).version;
391
+ return typeof version === "string" && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/u.test(version) ? version : void 0;
392
+ } catch {
393
+ return;
394
+ }
395
+ }
396
+ /** The license a new public plugin is offered under; the plan shows it before the person says yes. */
397
+ const DEFAULT_LICENSE = "MIT";
398
+ const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u;
399
+ const publishRefused = (reason, next) => ({
400
+ ok: false,
401
+ reason,
402
+ next
403
+ });
404
+ const SOURCE_FORMS = "github:<owner>/<repo>[@<version>] or a .tgz path or address";
405
+ /** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */
406
+ function readSource(input, root) {
407
+ const { source, digest } = splitDigest(input.trim());
408
+ const parsed = parsePluginSource(/\.(?:tgz|tar\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source) ? resolve(root, source) : source);
409
+ if (parsed.kind !== "github" && parsed.kind !== "tarball-file" && parsed.kind !== "tarball-url") throw new InvalidPluginSourceError(input, `${parsed.kind === "name" ? "a bare name" : parsed.kind} sources are not offered here; pull ${SOURCE_FORMS}`);
410
+ return {
411
+ source: parsed,
412
+ ...digest === void 0 ? {} : { digest }
413
+ };
414
+ }
415
+ /** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */
416
+ function recordedSource(source, version) {
417
+ if (source.kind === "github") return `github:${source.owner}/${source.repo}@${version}`;
418
+ return source.kind === "tarball-url" ? source.url : void 0;
419
+ }
420
+ const reasonOf = (cause) => {
421
+ if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason;
422
+ return cause instanceof Error ? cause.message : String(cause);
423
+ };
424
+ var PluginShare = class extends Service {
425
+ /** What was fetched again at this start. */
426
+ restored;
427
+ dir;
428
+ releases;
429
+ download;
430
+ ports;
431
+ /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */
432
+ queue = Promise.resolve();
433
+ /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */
434
+ live = /* @__PURE__ */ new Map();
435
+ nativeWork;
436
+ /** The native package each installed plugin brought for this computer: what its removal takes away. */
437
+ natives = /* @__PURE__ */ new Map();
438
+ /**
439
+ * The context the service was constructed with, in the app's realm. Inside a service method `this.ctx` is Cordis's shadow context of the caller: in the
440
+ * frame that is the host's door, which does not see the app's own services (`home`), so a plugin needing them was refused. As `extensions` does.
441
+ */
442
+ own;
443
+ constructor(ctx, config) {
444
+ super(ctx, "pluginShare");
445
+ this.own = ctx;
446
+ this.dir = resolve(config.dir ?? join(ctx.appInstance.root, "plugins"));
447
+ this.releases = config.releases ?? githubReleasesOverHttps();
448
+ this.download = config.download ?? httpsDownload();
449
+ this.nativeWork = config.native ?? nativePorts();
450
+ this.ports = config.publish ?? {
451
+ host: githubCli(),
452
+ git: gitCli()
453
+ };
454
+ ctx.on("extensions/changed", (name, change) => {
455
+ if (change !== "removed") return;
456
+ this.live.delete(name);
457
+ this.remember(name, void 0);
458
+ this.dropNative(name);
459
+ });
460
+ this.restored = this.inTurn(() => this.restore());
461
+ }
462
+ /** Pull a plugin into the running app. Never throws for what a person can act on: a refusal says what is wrong and what to do, and changes nothing. */
463
+ pull(source) {
464
+ return this.inTurn(() => this.pullNow(source));
465
+ }
466
+ /**
467
+ * Pull every source of a list, a file in the app or an https address (a gist, a file in the group's repository): one after the other and each on
468
+ * its own, so a source that is refused, or clashes with a plugin already here, is reported with its reason while the others install and keep running.
469
+ * A list that cannot be read, or has a line that is not one source, pulls nothing.
470
+ */
471
+ async pullList(from) {
472
+ const text = await this.readList(from);
473
+ if (typeof text !== "string") return text;
474
+ const { sources, problems } = parsePullList(text);
475
+ if (problems.length > 0) return refuse("list", `${from}: ${problems.join("; ")}`, "fix the list; nothing was pulled");
476
+ if (sources.length === 0) return refuse("list", `${from} names no plugin`, "write one source per line, e.g. github:someone/pomodoro@0.1.0");
477
+ const entries = [];
478
+ for (const { line, source } of sources) entries.push({
479
+ line,
480
+ source,
481
+ result: await this.pull(source)
482
+ });
483
+ return {
484
+ ok: true,
485
+ from,
486
+ entries
487
+ };
488
+ }
489
+ /** The text of a list, or why it cannot be read. */
490
+ async readList(from) {
491
+ const where = pullListLocation(from);
492
+ if (where === void 0) return refuse("list", `"${from}" is not a list`, "name a file in the app (e.g. group.txt) or an https address of one");
493
+ try {
494
+ let bytes;
495
+ if (where.kind === "address") bytes = await this.download(where.url);
496
+ else {
497
+ const path = resolve(this.own.appInstance.root, where.path);
498
+ if (!existsSync(path) || !statSync(path).isFile()) return refuse("list", `there is no file ${where.path}`, "name a file in the app, or an https address");
499
+ bytes = readFileSync(path);
500
+ }
501
+ if (bytes.length > 65536) return refuse("list", `${from} is larger than ${String(LIST_MAX_BYTES)} bytes, so it is not a list of plugins`, "name the list itself");
502
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
503
+ } catch (cause) {
504
+ return refuse("list", `${from} could not be read: ${reasonOf(cause)}`, "check the address; nothing was pulled");
505
+ }
506
+ }
507
+ /**
508
+ * The content digest of a pulled plugin as it was installed: set before its folder appears, so whoever sees the folder change can tell the release as
509
+ * pulled from an edit (the frame then does not load the app again for it). A pull from a local file has no record in `blend.yaml`; this knows it too.
510
+ */
511
+ pulledDigest(name) {
512
+ return this.live.get(name) ?? this.recorded(name)?.digest;
513
+ }
514
+ /** The plugins installed while the app runs, each pulled one with its source and author. */
515
+ list() {
516
+ const file = join(this.own.appInstance.root, "blend.yaml");
517
+ const records = existsSync(file) ? pulledRecords(readFileSync(file, "utf8")) : {};
518
+ return this.own.extensions.list().map((info) => {
519
+ const record = records[info.name];
520
+ const author = record === void 0 ? void 0 : authorOf(record.source);
521
+ const release = releaseOf(join(this.dir, info.name));
522
+ return {
523
+ ...info,
524
+ ...record === void 0 ? {} : { pulledFrom: record.source },
525
+ ...author === void 0 ? {} : { author },
526
+ ...release === void 0 ? {} : { release }
527
+ };
528
+ });
529
+ }
530
+ /**
531
+ * Take a plugin out of the running app and forget its record. A pulled plugin's folder is deleted when it still holds the release as pulled; a
532
+ * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.
533
+ */
534
+ remove(name) {
535
+ return this.inTurn(() => this.removeNow(name));
536
+ }
537
+ inTurn(step) {
538
+ const run = this.queue.then(step);
539
+ this.queue = run.catch(() => void 0);
540
+ return run;
541
+ }
542
+ /**
543
+ * What publishing this plugin would do, read without sending anything. A plan is the only thing an agent can get: it never confirms for a person.
544
+ */
545
+ planPublish(name, options = {}) {
546
+ return this.inTurn(() => this.planNow(name, options));
547
+ }
548
+ /**
549
+ * Publish exactly the plan a person said yes to: it is made again, and if anything differs (the plugin, the account, a release made meanwhile) nothing
550
+ * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.
551
+ */
552
+ publish(name, confirmed, options = {}) {
553
+ return this.inTurn(async () => {
554
+ const plan = await this.planNow(name, options);
555
+ if ("ok" in plan) return plan;
556
+ if (!samePlan(plan, confirmed)) return publishRefused(`this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`, "look at the new plan and say yes again");
557
+ const { home } = this.own.appInstance;
558
+ try {
559
+ const shared = await sharePlugin(join(this.packages, name), {
560
+ owner: plan.owner,
561
+ repo: plan.repo,
562
+ visibility: plan.visibility,
563
+ kind: "source-plugin"
564
+ }, {
565
+ ...this.ports,
566
+ store: new PluginStore(storeRootOf(home))
567
+ });
568
+ if (shared.status === "refused") return publishRefused(shared.reason, "fix what it names; nothing was sent");
569
+ return {
570
+ ok: true,
571
+ url: shared.url,
572
+ releaseUrl: shared.releaseUrl,
573
+ version: shared.version,
574
+ integrity: shared.integrity,
575
+ digest: plan.digest,
576
+ pullLine: plan.pullLine
577
+ };
578
+ } catch (cause) {
579
+ return publishRefused(reasonOf(cause), "look at the repository; part of this publish may have been sent");
580
+ }
581
+ });
582
+ }
583
+ /** Write one plugin's record into `blend.yaml`, and the lock when the app has one, so the two still match. @returns whether the app holds the record. */
584
+ remember(name, record) {
585
+ const { root } = this.own.appInstance;
586
+ const file = join(root, "blend.yaml");
587
+ if (!existsSync(file)) return false;
588
+ const text = readFileSync(file, "utf8");
589
+ const next = withPulledRecord(text, name, record);
590
+ if (next !== text) {
591
+ writeFileSync(`${file}.tmp`, next);
592
+ renameSync(`${file}.tmp`, file);
593
+ if (existsSync(join(root, LOCK_FILE))) writeLock(root);
594
+ }
595
+ return record === void 0 || pulledRecords(next)[name] !== void 0;
596
+ }
597
+ async removeNow(name) {
598
+ const pulled = this.pulledDigest(name);
599
+ const removed = await this.own.extensions.remove(name);
600
+ if (!removed.ok) return removed;
601
+ const folder = join(this.dir, name);
602
+ if (!existsSync(folder)) return {
603
+ ok: true,
604
+ name,
605
+ folder: "none"
606
+ };
607
+ if (pulled !== void 0 && digestFolder(folder) === pulled) {
608
+ rmSync(folder, {
609
+ recursive: true,
610
+ force: true
611
+ });
612
+ return {
613
+ ok: true,
614
+ name,
615
+ folder: "deleted"
616
+ };
617
+ }
618
+ return {
619
+ ok: true,
620
+ name,
621
+ folder: "kept",
622
+ note: `plugins/${name} ${pulled === void 0 ? "is this app's own plugin" : "was changed after the pull"}, so it stays and the app starts it again at its next start; delete the folder to drop it for good`
623
+ };
624
+ }
625
+ /** What `blend.yaml` remembers about one pulled plugin now. */
626
+ recorded(name) {
627
+ const file = join(this.own.appInstance.root, "blend.yaml");
628
+ return existsSync(file) ? pulledRecords(readFileSync(file, "utf8"))[name] : void 0;
629
+ }
630
+ /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */
631
+ get places() {
632
+ return {
633
+ root: this.own.appInstance.root,
634
+ home: this.own.appInstance.home
635
+ };
636
+ }
637
+ /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */
638
+ keepNative(name, native, before, action) {
639
+ if (before !== void 0 && (native === void 0 || before.version !== native.version || before.package !== native.package)) this.dropNative(name);
640
+ if (native === void 0 || action === void 0) return {};
641
+ this.natives.set(name, native);
642
+ return { native: {
643
+ package: native.package,
644
+ version: native.version,
645
+ size: native.size,
646
+ action
647
+ } };
648
+ }
649
+ /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */
650
+ dropNative(name) {
651
+ const native = this.natives.get(name);
652
+ if (native === void 0) return;
653
+ this.natives.delete(name);
654
+ if (![...this.natives.values()].some((other) => other.package === native.package && other.version === native.version)) releaseNative(native, this.places);
655
+ }
656
+ /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */
657
+ async relinkNative(name) {
658
+ let manifest;
659
+ try {
660
+ manifest = JSON.parse(readFileSync(join(this.dir, name, "package.json"), "utf8"));
661
+ } catch {
662
+ return;
663
+ }
664
+ const declared = nativesOf(manifest);
665
+ const native = "natives" in declared ? nativeFor(declared.natives) : void 0;
666
+ if (native === void 0) return;
667
+ try {
668
+ await ensureNative(native, this.places, this.nativeWork);
669
+ this.natives.set(name, native);
670
+ } catch (cause) {
671
+ console.warn(`plugin-share: ${name}'s ${native.package} was not installed again: ${reasonOf(cause)}`);
672
+ }
673
+ }
674
+ async restore() {
675
+ const file = join(this.own.appInstance.root, "blend.yaml");
676
+ if (!existsSync(file)) return [];
677
+ const outcomes = [];
678
+ for (const [name, record] of Object.entries(pulledRecords(readFileSync(file, "utf8")))) {
679
+ if (existsSync(join(this.dir, name))) {
680
+ await this.relinkNative(name);
681
+ continue;
682
+ }
683
+ const result = await this.pullNow(`${record.source}@sha256:${record.digest}`, record.integrity);
684
+ outcomes.push(result.ok ? {
685
+ name,
686
+ ok: true
687
+ } : {
688
+ name,
689
+ ok: false,
690
+ reason: result.reason,
691
+ next: result.next
692
+ });
693
+ if (!result.ok) console.warn(`plugin-share: ${name} was not fetched again: ${result.reason}. ${result.next}.`);
694
+ }
695
+ return outcomes;
696
+ }
697
+ get packages() {
698
+ return join(this.own.appInstance.home, "plugin-packages");
699
+ }
700
+ async planNow(name, options) {
701
+ const source = join(this.dir, name);
702
+ if (!NAME.test(name) || !existsSync(source)) return publishRefused(`this app has no plugin "${name}" in plugins/`, "name a folder of plugins/");
703
+ try {
704
+ const { host } = this.ports;
705
+ const owner = options.owner ?? host.login();
706
+ const repo = name;
707
+ const description = `The ${name} Cordis plugin.`;
708
+ const license = options.license ?? DEFAULT_LICENSE;
709
+ if (!LICENSE_ID.test(license)) return publishRefused(`"${license}" is not a license id`, "write one such as MIT or Apache-2.0");
710
+ const release = {
711
+ owner,
712
+ repo,
713
+ license
714
+ };
715
+ const existing = host.repository(owner, repo);
716
+ let packaged = await packagePlugin(source, this.packages, name, description, { release });
717
+ const released = existing !== void 0 && host.releaseExists(owner, repo, `v${packaged.version}`) ? packaged.version : void 0;
718
+ if (released !== void 0) packaged = await packagePlugin(source, this.packages, name, description, {
719
+ release,
720
+ version: bumpVersion(released, "patch")
721
+ });
722
+ const secrets = findSecrets(readTarball(packFolder(packaged.dir).tarball).map((file) => ({
723
+ path: file.path,
724
+ text: Buffer.from(file.content).toString("utf8")
725
+ })));
726
+ if (secrets.length > 0) return publishRefused(`the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(", ")}; nothing was sent`, "take them out of the plugin and read them from the app's settings");
727
+ return {
728
+ owner,
729
+ repo,
730
+ version: packaged.version,
731
+ visibility: "public",
732
+ license,
733
+ createsRepository: existing === void 0,
734
+ ...released === void 0 ? {} : { released },
735
+ files: packaged.files,
736
+ integrity: packaged.integrity,
737
+ digest: packaged.digest,
738
+ pullLine: pullLineOf(owner, repo, packaged.version, packaged.digest)
739
+ };
740
+ } catch (cause) {
741
+ return publishRefused(reasonOf(cause), "fix it, or sign in with gh; nothing was sent");
742
+ }
743
+ }
744
+ async pullNow(input, expectIntegrity) {
745
+ const { home, root } = this.own.appInstance;
746
+ let read;
747
+ try {
748
+ read = readSource(input, root);
749
+ } catch (cause) {
750
+ return refuse("source", reasonOf(cause), `write ${SOURCE_FORMS}, with @sha256:<digest> at the end to name the content`);
751
+ }
752
+ mkdirSync(home, { recursive: true });
753
+ const scratch = mkdtempSync(join(home, "plugin-pull-"));
754
+ try {
755
+ let pulled;
756
+ try {
757
+ pulled = await pullPlugin(read.source, {
758
+ store: new PluginStore(scratch),
759
+ releases: this.releases,
760
+ download: this.download
761
+ }, expectIntegrity === void 0 ? {} : { expectIntegrity });
762
+ } catch (cause) {
763
+ return refuse("fetch", reasonOf(cause), "check the source with the person who released it; nothing was installed");
764
+ }
765
+ const files = readTarball(readFileSync(pulled.stored.path)).map(({ path, content }) => ({
766
+ path,
767
+ bytes: content,
768
+ kind: "file"
769
+ }));
770
+ const refused = pullRefusal(pulled.manifest, files, {
771
+ digest: read.digest,
772
+ nameFits: (name) => NAME.test(name),
773
+ hasService: (service) => this.own.get(service) !== void 0
774
+ });
775
+ if (refused !== void 0) return refused;
776
+ const declared = nativesOf(pulled.manifest);
777
+ return await this.install(pulled.stored.name, pulled.stored.version, pulled.stored.integrity, files, recordedSource(read.source, pulled.stored.version), "natives" in declared ? nativeFor(declared.natives) : void 0);
778
+ } finally {
779
+ rmSync(scratch, {
780
+ recursive: true,
781
+ force: true
782
+ });
783
+ }
784
+ }
785
+ /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */
786
+ async install(name, version, integrity, files, source, native) {
787
+ const target = join(this.dir, name);
788
+ const incoming = join(this.dir, `.pulling-${name}`);
789
+ rmSync(incoming, {
790
+ recursive: true,
791
+ force: true
792
+ });
793
+ try {
794
+ for (const file of files) {
795
+ const path = join(incoming, ...file.path.split("/"));
796
+ mkdirSync(dirname(path), { recursive: true });
797
+ writeFileSync(path, file.bytes);
798
+ }
799
+ const digest = digestFolder(incoming);
800
+ const wrote = !existsSync(target);
801
+ const before = this.recorded(name);
802
+ const held = wrote ? void 0 : digestFolder(target);
803
+ if (held !== void 0 && held !== digest) {
804
+ const holder = before === void 0 ? "made in this app" : `pulled from ${before.source}`;
805
+ const next = before !== void 0 && held === before.digest ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again` : `keep it, or move plugins/${name} out of plugins/ and pull again`;
806
+ return refuse("folder-exists", `plugins/${name} holds a different copy of this plugin, ${holder}`, next);
807
+ }
808
+ const liveBefore = this.live.get(name);
809
+ this.live.set(name, digest);
810
+ if (wrote) renameSync(incoming, target);
811
+ const remembered = source !== void 0 && this.remember(name, {
812
+ source,
813
+ integrity,
814
+ digest
815
+ });
816
+ let nativeAction;
817
+ const nativeBefore = this.natives.get(name);
818
+ const undo = () => {
819
+ if (native !== void 0 && (nativeAction === "downloaded" || nativeAction === "linked")) releaseNative(native, this.places, nativeAction === "linked");
820
+ if (wrote) rmSync(target, {
821
+ recursive: true,
822
+ force: true
823
+ });
824
+ if (remembered) this.remember(name, before);
825
+ if (liveBefore === void 0) this.live.delete(name);
826
+ else this.live.set(name, liveBefore);
827
+ };
828
+ if (native !== void 0) try {
829
+ nativeAction = await ensureNative(native, this.places, this.nativeWork);
830
+ } catch (cause) {
831
+ undo();
832
+ return refuse("native", `${native.package}@${native.version} (${Math.round(native.size / 1e6)} MB) could not be installed: ${reasonOf(cause)}`, "check the internet connection and pull again; the plugin was not installed");
833
+ }
834
+ let result;
835
+ try {
836
+ result = await this.own.extensions.install(target);
837
+ } catch (cause) {
838
+ undo();
839
+ return refuse("install", reasonOf(cause), "this app does not install plugins while it runs like this");
840
+ }
841
+ if (!result.ok) {
842
+ undo();
843
+ return refuse("install", result.errors.join("; "), result.next);
844
+ }
845
+ if (result.state === "pending") {
846
+ await this.own.extensions.remove(name);
847
+ undo();
848
+ return missingServices(result.missing);
849
+ }
850
+ return {
851
+ ok: true,
852
+ name,
853
+ version,
854
+ integrity,
855
+ digest,
856
+ action: result.action,
857
+ state: result.state,
858
+ remembered,
859
+ ...this.keepNative(name, native, nativeBefore, nativeAction)
860
+ };
861
+ } finally {
862
+ rmSync(incoming, {
863
+ recursive: true,
864
+ force: true
865
+ });
866
+ }
867
+ }
868
+ };
869
+ const pluginShare = {
870
+ name: "plugin-share",
871
+ inject: ["extensions", "appInstance"],
872
+ apply(ctx, config) {
873
+ if (process.env.NODE_ENV === "production") return;
874
+ new PluginShare(ctx, config ?? {});
875
+ }
876
+ };
877
+ //#endregion
878
+ export { PluginShare, pluginShare };
879
+
880
+ //# sourceMappingURL=index.js.map