@acryldev/plugin-share 0.1.3 → 0.1.4
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/README.md +6 -0
- package/index.ts +313 -16
- package/lib/index.js +341 -11
- package/lib/index.js.map +1 -1
- package/lib/package.js +3 -3
- package/lib/package.js.map +1 -1
- package/lib/types/index.d.ts +26 -1
- package/lib/types/merge-edits.d.ts +16 -0
- package/lib/types/npm-login.d.ts +7 -0
- package/lib/types/package.d.ts +5 -2
- package/lib/types/publish.d.ts +16 -0
- package/lib/types/registry-source.d.ts +23 -0
- package/merge-edits.ts +85 -0
- package/npm-login.ts +43 -0
- package/package.json +1 -1
- package/package.ts +15 -7
- package/publish.ts +21 -0
- package/registry-source.ts +62 -0
- package/test/plugin-share.test.ts +357 -2
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../native.ts","../publish.ts","../pull-check.ts","../pull-list.ts","../pulled-records.ts","../index.ts"],"sourcesContent":["/**\n * 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\n * 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`).\n *\n * A plugin's package.json names them, one entry per OS and CPU, each pinned by npm's sha512:\n *\n * \"@acryldev/blends\": { \"native\": [\n * { \"package\": \"@deepseek-ai/libreoffice-kit-darwin-arm64\", \"version\": \"0.1.5\", \"os\": \"darwin\", \"cpu\": \"arm64\",\n * \"integrity\": \"sha512-...\", \"size\": 153171456 } ] }\n *\n * 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\n * 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\n * that needs it resolves it. Only a missing package or the empty placeholder (`@acryldev/absent`) is replaced; a real copy npm installed stays.\n * Removing the plugin takes the link and the download away; an app's start links again what an `npm install` unlinked.\n */\nimport { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n symlinkSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\n/** Where a native package is downloaded from: the npm registry, and nothing else. */\nexport const NATIVE_REGISTRY = 'https://registry.npmjs.org'\n\n/** The most a plugin's native packages may unpack to, all of its entries for one computer together. */\nexport const NATIVE_MAX_BYTES = 1_000_000_000\n\n/** The empty package the frame installs in place of an omitted one (frame/packages.json `omit.placeholder`). */\nexport const PLACEHOLDER = '@acryldev/absent'\n\n/** The file written last into an unpacked native package: without it the folder is an interrupted download. */\nconst COMPLETE = '.acrylblends-native-complete'\n\nexport type NativeOs = 'darwin' | 'linux' | 'win32'\nexport type NativeCpu = 'arm64' | 'x64'\n\nexport interface NativePackage {\n /** The npm package, as the package that needs it resolves it. */\n readonly package: string\n /** Its exact version. */\n readonly version: string\n readonly os: NativeOs\n /** Absent: any CPU of that OS (a WebAssembly build). */\n readonly cpu?: NativeCpu\n /** npm's `dist.integrity` of the tarball. */\n readonly integrity: string\n /** npm's `dist.unpackedSize`, in bytes: what a person is told before it is downloaded. */\n readonly size: number\n}\n\nconst NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u\nconst EXACT_VERSION = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u\nconst SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u\nconst OSES: readonly string[] = ['darwin', 'linux', 'win32']\nconst CPUS: readonly string[] = ['arm64', 'x64']\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */\nexport function nativesOf(\n manifest: Readonly<Record<string, unknown>>,\n): { readonly natives: readonly NativePackage[] } | { readonly error: string } {\n const section = manifest.acrylblends\n if (section === undefined || (isObject(section) && section.native === undefined))\n return { natives: [] }\n if (!isObject(section) || !Array.isArray(section.native))\n return { error: '\"acrylblends.native\" is not a list' }\n const natives: NativePackage[] = []\n for (const [index, entry] of section.native.entries()) {\n const at = `acrylblends.native[${index}]`\n if (!isObject(entry)) return { error: `${at} is not an object` }\n const { package: name, version, os, cpu, integrity, size } = entry\n if (typeof name !== 'string' || !NPM_NAME.test(name))\n return { error: `${at}.package is not an npm package name` }\n if (typeof version !== 'string' || !EXACT_VERSION.test(version))\n return { error: `${at}.version is not an exact version` }\n if (typeof os !== 'string' || !OSES.includes(os))\n return { error: `${at}.os is not one of ${OSES.join(', ')}` }\n if (cpu !== undefined && (typeof cpu !== 'string' || !CPUS.includes(cpu)))\n return { error: `${at}.cpu is not one of ${CPUS.join(', ')}` }\n if (typeof integrity !== 'string' || !SHA512.test(integrity))\n return { error: `${at}.integrity is not npm's sha512 of the tarball` }\n if (typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0)\n return { error: `${at}.size is not a number of bytes` }\n if (size > NATIVE_MAX_BYTES)\n return {\n error: `${at} unpacks to ${size} bytes, more than a plugin may bring (${NATIVE_MAX_BYTES})`,\n }\n natives.push({\n package: name,\n version,\n os: os as NativeOs,\n ...(cpu === undefined ? {} : { cpu: cpu as NativeCpu }),\n integrity,\n size,\n })\n }\n return { natives }\n}\n\n/** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */\nexport function nativeFor(\n natives: readonly NativePackage[],\n platform: string = process.platform,\n arch: string = process.arch,\n): NativePackage | undefined {\n return (\n natives.find((entry) => entry.os === platform && entry.cpu === arch) ??\n natives.find((entry) => entry.os === platform && entry.cpu === undefined)\n )\n}\n\n/** The tarball's address in the npm registry, the way npm names it. */\nexport function tarballUrl(native: Pick<NativePackage, 'package' | 'version'>): string {\n const base = native.package.slice(native.package.lastIndexOf('/') + 1)\n return `${NATIVE_REGISTRY}/${native.package}/-/${base}-${native.version}.tgz`\n}\n\n/** What a download and an unpack are, so a test can hand in local ones. */\nexport interface NativePorts {\n /** Write the file at `url` to `file`. */\n readonly download: (url: string, file: string) => Promise<void>\n /** Unpack the `.tgz` at `file` into `dir`, without the archive's top folder (npm's `package/`) and with the files' modes. */\n readonly unpack: (file: string, dir: string) => Promise<void>\n}\n\n/** 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. */\nexport function nativePorts(): NativePorts {\n return {\n async download(url, file) {\n if (!url.startsWith(`${NATIVE_REGISTRY}/`))\n throw new Error(`${url} is not in the npm registry`)\n const response = await fetch(url)\n if (!response.ok || response.body === null)\n throw new Error(`the npm registry answered ${response.status} for ${url}`)\n await pipeline(Readable.fromWeb(response.body as never), createWriteStream(file))\n },\n unpack: (file, dir) =>\n new Promise((done, fail) => {\n const tar = spawn('tar', ['-xzf', file, '-C', dir, '--strip-components=1'], {\n stdio: ['ignore', 'ignore', 'pipe'],\n windowsHide: true,\n })\n let error = ''\n tar.stderr.on('data', (chunk: Buffer) => {\n error += chunk.toString()\n })\n tar.once('error', fail)\n tar.once('exit', (code) =>\n code === 0 ? done() : fail(new Error(`tar could not unpack ${file}: ${error.trim()}`)),\n )\n }),\n }\n}\n\n/** Where the app keeps what it downloaded, and where it links it. */\nexport interface NativePlaces {\n /** The app's folder, whose `node_modules` the link goes into. */\n readonly root: string\n /** The app's home, which keeps the downloads. */\n readonly home: string\n}\n\n/** The folder a native package is unpacked into. */\nexport function nativeStore(\n home: string,\n native: Pick<NativePackage, 'package' | 'version'>,\n): string {\n return join(home, 'native', `${native.package.replace('/', '+')}@${native.version}`)\n}\n\nconst linkOf = (root: string, native: Pick<NativePackage, 'package'>) =>\n join(root, 'node_modules', ...native.package.split('/'))\n\n/** What is at the package's place in node_modules: our link, nothing, something we may replace, or a real package someone installed. */\nfunction placeState(link: string, store: string): 'ours' | 'missing' | 'replaceable' | 'foreign' {\n let stat: ReturnType<typeof lstatSync>\n try {\n stat = lstatSync(link)\n } catch {\n return 'missing'\n }\n if (stat.isSymbolicLink()) {\n let target: string\n try {\n target = realpathSync(link)\n } catch {\n return 'replaceable'\n }\n if (existsSync(store) && target === realpathSync(store)) return 'ours'\n // Another version this app downloaded (the plugin was updated): replaced, never mistaken for a copy npm installed.\n if (existsSync(dirname(store)) && dirname(target) === realpathSync(dirname(store)))\n return 'replaceable'\n }\n let name: unknown\n try {\n name = (JSON.parse(readFileSync(join(link, 'package.json'), 'utf8')) as { name?: unknown }).name\n } catch {\n return stat.isSymbolicLink() ? 'replaceable' : 'foreign'\n }\n return name === PLACEHOLDER ? 'replaceable' : 'foreign'\n}\n\nconst sha512Of = async (file: string): Promise<string> => {\n const hash = createHash('sha512')\n await pipeline(createReadStream(file), hash)\n return `sha512-${hash.digest('base64')}`\n}\n\n/** Download, check and unpack into the store; the store appears whole or not at all. */\nasync function fetchInto(native: NativePackage, store: string, ports: NativePorts): Promise<void> {\n mkdirSync(dirname(store), { recursive: true })\n const incoming = mkdtempSync(join(dirname(store), '.incoming-'))\n try {\n const file = join(incoming, 'package.tgz')\n await ports.download(tarballUrl(native), file)\n const integrity = await sha512Of(file)\n if (integrity !== native.integrity)\n throw new Error(\n `${native.package}@${native.version} from npm is not the file the plugin names (its sha512 differs)`,\n )\n const unpacked = join(incoming, 'package')\n mkdirSync(unpacked)\n await ports.unpack(file, unpacked)\n const manifest = JSON.parse(readFileSync(join(unpacked, 'package.json'), 'utf8')) as {\n name?: unknown\n version?: unknown\n }\n if (manifest.name !== native.package || manifest.version !== native.version)\n throw new Error(\n `the tarball holds ${String(manifest.name)}@${String(manifest.version)}, not ${native.package}@${native.version}`,\n )\n writeFileSync(join(unpacked, COMPLETE), '')\n rmSync(store, { recursive: true, force: true })\n renameSync(unpacked, store)\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n}\n\n/** What `ensureNative` did: downloaded it, only linked a download it had, found it linked, or left a real copy npm installed. */\nexport type NativeAction = 'downloaded' | 'linked' | 'unchanged' | 'present'\n\n/** 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. */\nexport async function ensureNative(\n native: NativePackage,\n places: NativePlaces,\n ports: NativePorts = nativePorts(),\n): Promise<NativeAction> {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n const state = placeState(link, store)\n if (state === 'foreign') return 'present'\n const complete = existsSync(join(store, COMPLETE))\n if (state === 'ours' && complete) return 'unchanged'\n if (!complete) await fetchInto(native, store, ports)\n rmSync(link, { recursive: true, force: true })\n mkdirSync(dirname(link), { recursive: true })\n // A junction on Windows: a directory symlink there needs a privilege a person may not have.\n symlinkSync(store, link, process.platform === 'win32' ? 'junction' : 'dir')\n return complete ? 'linked' : 'downloaded'\n}\n\n/** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */\nexport function releaseNative(\n native: Pick<NativePackage, 'package' | 'version'>,\n places: NativePlaces,\n keepDownload = false,\n): void {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n if (placeState(link, store) === 'ours') unlinkSync(link)\n if (!keepDownload) rmSync(store, { recursive: true, force: true })\n}\n","/**\n * Publishing a plugin: what a person is asked to say yes to, and the comparison that makes the yes mean exactly that. Pure; the service does the I/O.\n */\nimport type { PublishGitPort, RepositoryHostPort } from '@acryldev/plugin-hub-core'\n\n/** Everything that leaves the machine, named before anything does. */\nexport interface PublishPlan {\n readonly owner: string\n readonly repo: string\n readonly version: string\n readonly visibility: 'public'\n readonly license: string\n /** The repository does not exist yet: publishing creates it. */\n readonly createsRepository: boolean\n /** The version already released there; the plan then releases the next patch. */\n readonly released?: string\n readonly files: readonly string[]\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n /** What a friend runs to get exactly these bytes. */\n readonly pullLine: string\n}\n\nexport interface PublishRefused {\n readonly ok: false\n readonly reason: string\n readonly next: string\n}\n\nexport type PublishResult =\n | {\n readonly ok: true\n readonly url: string\n readonly releaseUrl: string\n readonly version: string\n readonly integrity: string\n readonly digest: string\n readonly pullLine: string\n }\n | PublishRefused\n\nexport interface PublishOptions {\n /** The account or organization; the signed-in one when absent. */\n readonly owner?: string\n /** The license the plugin is offered under, as an SPDX id; MIT when absent. The plan shows it before the person says yes. */\n readonly license?: string\n}\n\n/** Where a publish goes through: the person's own `gh` and `git`. A test passes stand-ins, so no test publishes. */\nexport interface PublishPorts {\n readonly host: RepositoryHostPort\n readonly git: PublishGitPort\n}\n\n/** The line a friend copies: it names the bytes, so the check comes for free. */\nexport const pullLineOf = (owner: string, repo: string, version: string, digest: string): string =>\n `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`\n\n/**\n * 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.\n * 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.\n */\nexport function samePlan(a: PublishPlan, b: PublishPlan): boolean {\n return (\n a.owner === b.owner &&\n a.repo === b.repo &&\n a.version === b.version &&\n a.visibility === b.visibility &&\n a.license === b.license &&\n a.createsRepository === b.createsRepository &&\n a.integrity === b.integrity &&\n a.digest === b.digest &&\n a.pullLine === b.pullLine &&\n a.files.length === b.files.length &&\n a.files.every((file, index) => file === b.files[index])\n )\n}\n","/**\n * 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,\n * so a refusal has nothing to undo (Clean Architecture: policy free of I/O).\n */\nimport { digestFiles, type PluginFile, portabilityIssues } from '@acryldev/blends-core'\nimport { hostInjectFromSource } from '@acryldev/plugin-hub-core'\nimport { nativesOf } from './native.ts'\n\nexport type Refusal =\n | 'source'\n | 'fetch'\n | 'name'\n | 'digest'\n | 'portability'\n | 'dependencies'\n /** Its `acrylblends.native` list (native.ts) cannot be used. */\n | 'native'\n | 'entry'\n | 'inject'\n | 'missing-service'\n | 'folder-exists'\n | 'install'\n /** A list of sources that cannot be read, or holds a line that is not one source. */\n | 'list'\n\nexport interface PullRefused {\n readonly ok: false\n readonly refusal: Refusal\n readonly reason: string\n /** What the person can do about it. */\n readonly next: string\n}\n\nexport const refuse = (refusal: Refusal, reason: string, next: string): PullRefused => ({\n ok: false,\n refusal,\n reason,\n next,\n})\n\nconst SHA256 = /^[0-9a-f]{64}$/\nconst DIGEST_MARK = '@sha256:'\n\n/** The source a person wrote, split into where it comes from and the content digest it names. @throws when the digest is malformed. */\nexport function splitDigest(input: string): { readonly source: string; readonly digest?: string } {\n const at = input.lastIndexOf(DIGEST_MARK)\n if (at === -1) return { source: input }\n const digest = input.slice(at + DIGEST_MARK.length)\n if (!SHA256.test(digest))\n throw new Error(`\"${digest}\" is not a content digest: it has 64 lowercase hex characters`)\n return { source: input.slice(0, at), digest }\n}\n\n/** The entry files the extensions folder loads, in its order. */\nconst ENTRIES = ['index.ts', 'index.js', 'index.mjs']\n\nconst text = (file: PluginFile): string => Buffer.from(file.bytes).toString('utf8')\n\nexport interface PullContext {\n /** The content digest the source names. */\n readonly digest?: string | undefined\n /** Whether the extensions folder can hold a plugin of this name. */\n readonly nameFits: (name: string) => boolean\n /** Whether this app has the service right now. */\n readonly hasService: (name: string) => boolean\n}\n\n/** The first reason this package may not enter the app, or undefined. */\nexport function pullRefusal(\n manifest: Readonly<Record<string, unknown>>,\n files: readonly PluginFile[],\n context: PullContext,\n): PullRefused | undefined {\n const name = String(manifest.name)\n if (!context.nameFits(name)) {\n return refuse(\n 'name',\n `the package is called \"${name}\", which a folder in plugins/ cannot hold`,\n 'ask its author to release it under lowercase letters, digits and dashes',\n )\n }\n const digest = digestFiles(files)\n if (context.digest !== undefined && context.digest !== digest) {\n return refuse(\n 'digest',\n `${digest} is not the digest the source names (${context.digest}); these are different bytes`,\n 'ask the person who gave you the digest which release they meant',\n )\n }\n const issues = portabilityIssues(files)\n if (issues.length > 0) {\n return refuse(\n 'portability',\n issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; '),\n 'ask its author to fix this and release again, so it works on every OS',\n )\n }\n const dependencies = Object.keys(\n (manifest.dependencies as Record<string, unknown> | undefined) ?? {},\n )\n if (dependencies.length > 0) {\n return refuse(\n 'dependencies',\n `it needs ${dependencies.join(', ')} installed, and a pull installs nothing`,\n 'ask its author to bundle them or name them as peers',\n )\n }\n const native = nativesOf(manifest)\n if ('error' in native) {\n return refuse(\n 'native',\n native.error,\n 'ask its author to fix \"acrylblends.native\" in its package.json and release again',\n )\n }\n const entry = ENTRIES.flatMap((path) => files.filter((file) => file.path === path))[0]\n if (entry === undefined) {\n return refuse(\n 'entry',\n `it has none of ${ENTRIES.join(', ')} at its top level`,\n 'this package is not a plugin an app can load; ask its author',\n )\n }\n const inject = hostInjectFromSource(text(entry))\n if (inject !== undefined && 'error' in inject) {\n return refuse(\n 'inject',\n `${inject.error}. A pull reads what a plugin needs without running it`,\n 'ask its author to list the services as plain names',\n )\n }\n const missing = (inject?.names ?? []).filter((service) => !context.hasService(service))\n if (missing.length > 0) return missingServices(missing)\n return undefined\n}\n\nexport const missingServices = (missing: readonly string[]): PullRefused =>\n refuse(\n 'missing-service',\n `it needs ${missing.join(', ')}, which this app does not have`,\n 'add the plugin that provides it, then pull again',\n )\n","/**\n * 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\n * `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\n * 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.\n */\n\n/** A list is a few lines of text: anything larger is not a list of plugins. */\nexport const LIST_MAX_BYTES = 64 * 1024\n\n/** More sources than a group has people is a mistake, not a workshop. */\nexport const LIST_MAX_SOURCES = 100\n\n/** The command a person pastes from `plugin publish`: only its source is kept. */\nconst PULL_COMMAND = /^(?:npm run acryl --\\s+)?plugin pull\\s+/u\n\n/** A `#` at the start of a line or after a space begins a comment; a source never holds one there. */\nconst COMMENT = /(?:^|\\s)#.*$/u\n\nexport interface PullListLine {\n /** Its line in the list, from 1, so a problem is easy to find. */\n readonly line: number\n readonly source: string\n}\n\nexport interface ParsedPullList {\n /** The sources in their order, each once. */\n readonly sources: readonly PullListLine[]\n /** Lines that are not one source, each with what is wrong. */\n readonly problems: readonly string[]\n}\n\n/** The sources of a list, in order and without repeats, and the lines that are not a source. */\nexport function parsePullList(text: string): ParsedPullList {\n const sources: PullListLine[] = []\n const problems: string[] = []\n const seen = new Set<string>()\n text.split(/\\r?\\n/u).forEach((raw, index) => {\n const line = index + 1\n const value = raw.replace(COMMENT, '').trim().replace(PULL_COMMAND, '').trim()\n if (value === '') return\n if (/\\s/u.test(value)) {\n problems.push(\n `line ${String(line)} holds more than one word (\"${value}\"); write one source per line`,\n )\n return\n }\n if (seen.has(value)) return\n seen.add(value)\n sources.push({ line, source: value })\n })\n if (sources.length > LIST_MAX_SOURCES)\n problems.push(\n `the list has ${String(sources.length)} sources; a list holds at most ${String(LIST_MAX_SOURCES)}`,\n )\n return { sources, problems }\n}\n\n/** Where a list is read from: an https address, or a file (relative to the app folder). */\nexport type PullListLocation =\n | { readonly kind: 'address'; readonly url: string }\n | { readonly kind: 'file'; readonly path: string }\n\n/** @returns undefined for something that is neither (an http: address, a github: source): the caller names what a list may be. */\nexport function pullListLocation(from: string): PullListLocation | undefined {\n const value = from.trim()\n if (value === '') return undefined\n if (/^https:\\/\\//iu.test(value)) return { kind: 'address', url: value }\n // A drive letter (C:\\...) is a path; any other scheme is not a place a list is read from.\n if (/^[a-z][a-z0-9+.-]+:/iu.test(value) && !/^[a-z]:[\\\\/]/iu.test(value)) return undefined\n return { kind: 'file', path: value }\n}\n","/**\n * 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\n * 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\n * to text; comments and the person's formatting stay.\n */\nimport { isMap, isSeq, parseDocument } from 'yaml'\n\nexport const ROW = 'plugin-share'\n\nexport interface PulledRecord {\n /** `github:<owner>/<repo>@<version>` or an https address: something another machine can fetch. */\n readonly source: string\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n}\n\nconst isRecord = (value: unknown): value is PulledRecord => {\n const record = value as Partial<Record<keyof PulledRecord, unknown>> | null\n return (\n typeof record?.source === 'string' &&\n typeof record.integrity === 'string' &&\n typeof record.digest === 'string'\n )\n}\n\n/** The plugins this definition remembers pulling. */\nexport function pulledRecords(text: string): Readonly<Record<string, PulledRecord>> {\n const rows = (parseDocument(text).toJS() as { spec?: { rows?: unknown } } | null)?.spec?.rows\n if (!Array.isArray(rows)) return {}\n const pulled = (\n rows.find((row: { name?: unknown }) => row?.name === ROW) as\n | { config?: { pulled?: unknown } }\n | undefined\n )?.config?.pulled\n if (typeof pulled !== 'object' || pulled === null) return {}\n return Object.fromEntries(\n Object.entries(pulled).filter(([, record]) => isRecord(record)),\n ) as Record<string, PulledRecord>\n}\n\n/**\n * 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\n * composed without the row has nowhere to remember.\n */\nexport function withPulledRecord(\n text: string,\n name: string,\n record: PulledRecord | undefined,\n): string {\n const document = parseDocument(text)\n const rows = document.getIn(['spec', 'rows'])\n if (!isSeq(rows)) return text\n const row = rows.items.find((item) => isMap(item) && item.get('name') === ROW)\n if (!isMap(row)) return text\n if (record === undefined) {\n if (!row.hasIn(['config', 'pulled', name])) return text\n row.deleteIn(['config', 'pulled', name])\n const left = row.getIn(['config', 'pulled'])\n if (isMap(left) && left.items.length === 0) row.deleteIn(['config', 'pulled'])\n const config = row.get('config')\n if (isMap(config) && config.items.length === 0) row.delete('config')\n } else {\n row.setIn(['config'], row.get('config') ?? document.createNode({}))\n if (!row.hasIn(['config', 'pulled'])) row.setIn(['config', 'pulled'], document.createNode({}))\n row.setIn(['config', 'pulled', name], document.createNode(record))\n }\n return String(document)\n}\n","/**\n * Sharing a plugin between people: `pull(source)` turns a release someone published into a running plugin in this app. It fetches without running\n * anything, decides from the package's files (`pull-check.ts`), and hands a folder to `extensions`, which owns the install and its rollback.\n * Design: docs/plans/plugin-share.md.\n */\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { findSecrets } from '@acryldev/app-persistence'\nimport { digestFolder, type PluginFile } from '@acryldev/blends-core'\nimport { type ExtensionInfo, NAME } from '@acryldev/extensions'\nimport type {} from '@acryldev/instance'\nimport { LOCK_FILE, writeLock } from '@acryldev/manifest/lock'\nimport {\n bumpVersion,\n gitCli,\n githubCli,\n githubReleasesOverHttps,\n httpsDownload,\n InvalidPluginSourceError,\n type PluginSource,\n PluginStore,\n PullError,\n packFolder,\n parsePluginSource,\n pullPlugin,\n type ReleasePort,\n readTarball,\n sharePlugin,\n storeRootOf,\n} from '@acryldev/plugin-hub-core'\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport {\n ensureNative,\n type NativeAction,\n type NativePackage,\n type NativePlaces,\n type NativePorts,\n nativeFor,\n nativePorts,\n nativesOf,\n releaseNative,\n} from './native.ts'\nimport { packagePlugin } from './package.ts'\nimport {\n type PublishOptions,\n type PublishPlan,\n type PublishPorts,\n type PublishRefused,\n type PublishResult,\n pullLineOf,\n samePlan,\n} from './publish.ts'\nimport {\n missingServices,\n type PullRefused,\n pullRefusal,\n refuse,\n splitDigest,\n} from './pull-check.ts'\nimport { LIST_MAX_BYTES, parsePullList, pullListLocation } from './pull-list.ts'\nimport { type PulledRecord, pulledRecords, withPulledRecord } from './pulled-records.ts'\n\nexport type {\n PublishOptions,\n PublishPlan,\n PublishPorts,\n PublishRefused,\n PublishResult,\n} from './publish.ts'\n\n/** One remembered plugin the app fetched again at its start because its folder was gone. */\nexport type RestoreOutcome =\n | { readonly name: string; readonly ok: true }\n | { readonly name: string; readonly ok: false; readonly reason: string; readonly next: string }\n\nexport interface PluginShareConfig {\n /** Where pulled plugins go; must be an extensions source. Defaults to `<project>/plugins`. */\n dir?: string\n /** Where a `github:` source reads releases. Defaults to GitHub over HTTPS. */\n releases?: ReleasePort\n /** Where a publish goes. Defaults to the person's own `gh` and `git`. */\n publish?: PublishPorts\n /** How an https address is read: a release `.tgz` and a list of sources. Defaults to HTTPS with the hub's size and time limits. */\n download?: (url: string) => Promise<Uint8Array>\n /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */\n native?: NativePorts\n}\n\nexport type PullResult =\n | {\n readonly ok: true\n readonly name: string\n readonly version: string\n /** The sha512 of the release's tarball, as the registry lists it. */\n readonly integrity: string\n /** The sha256 of the plugin's content: the same on every OS. A source can name it (`@sha256:<digest>`). */\n readonly digest: string\n readonly action: 'installed' | 'updated' | 'unchanged'\n readonly state: string\n /** Whether the app's `blend.yaml` and lock now name this source, so a copy of the app can fetch it. A local file names nothing to fetch. */\n readonly remembered: boolean\n /** The native package the plugin brought for this computer (native.ts), and what installing it did. */\n readonly native?: {\n readonly package: string\n readonly version: string\n readonly size: number\n readonly action: NativeAction\n }\n }\n | PullRefused\n\n/** One source of a list and what pulling it did. */\nexport interface PullListEntry {\n /** Its line in the list. */\n readonly line: number\n readonly source: string\n readonly result: PullResult\n}\n\n/** A list pulled: every source with its own result (some may be refused while the others install), or the list itself refused. */\nexport type PullListResult =\n | { readonly ok: true; readonly from: string; readonly entries: readonly PullListEntry[] }\n | PullRefused\n\n/** One plugin installed while the app runs, as a person reads the list: what it is and, for one pulled, where it came from and who released it. */\n/** What extensions says about an installed plugin (its state, the services a pending one waits for, ...), and where a pulled one came from. */\nexport interface SharedPluginInfo extends ExtensionInfo {\n /** The source it was pulled from (`github:<owner>/<repo>@<version>` or an address); absent for one made in this app or pulled from a local file. */\n readonly pulledFrom?: string\n /** Who released it: the account of a `github:` source or of a release address on github.com. */\n readonly author?: string\n /** The version its `package.json` names (`version` is the installed content's short digest); absent without one. */\n readonly release?: string\n}\n\n/** What removing a plugin did with its folder in `plugins/`. */\nexport type RemovedFolder =\n /** It held the release as pulled, so nothing of anyone's is lost: the pull line brings it back. */\n | 'deleted'\n /** It is this app's own work, or a pulled plugin changed after the pull: it stays, and the app starts it again at its next start. */\n | 'kept'\n | 'none'\n\nexport type SharedRemoveResult =\n | {\n readonly ok: true\n readonly name: string\n readonly folder: RemovedFolder\n readonly note?: string\n }\n | { readonly ok: false; readonly name: string; readonly errors: readonly string[] }\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n pluginShare: PluginShare\n }\n}\n\n/** The account that released a source: the owner of a `github:<owner>/<repo>@<version>` source or of a release address on github.com. */\nconst authorOf = (source: string): string | undefined =>\n (/^github:([^/]+)\\//u.exec(source) ?? /^https:\\/\\/github\\.com\\/([^/]+)\\//u.exec(source))?.[1]\n\n/** The version a plugin folder's `package.json` names, when it names a plain one. */\nfunction releaseOf(folder: string): string | undefined {\n try {\n const version = (\n JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')) as { version?: unknown }\n ).version\n return typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]+)?$/u.test(version)\n ? version\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** The license a new public plugin is offered under; the plan shows it before the person says yes. */\nconst DEFAULT_LICENSE = 'MIT'\nconst LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u\n\nconst publishRefused = (reason: string, next: string): PublishRefused => ({\n ok: false,\n reason,\n next,\n})\n\nconst SOURCE_FORMS = 'github:<owner>/<repo>[@<version>] or a .tgz path or address'\n\n/** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */\nfunction readSource(\n input: string,\n root: string,\n): { readonly source: PluginSource; readonly digest?: string } {\n const { source, digest } = splitDigest(input.trim())\n const isLocalTarball = /\\.(?:tgz|tar\\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source)\n const parsed = parsePluginSource(isLocalTarball ? resolve(root, source) : source)\n if (parsed.kind !== 'github' && parsed.kind !== 'tarball-file' && parsed.kind !== 'tarball-url') {\n const named = parsed.kind === 'name' ? 'a bare name' : parsed.kind\n throw new InvalidPluginSourceError(\n input,\n `${named} sources are not offered here; pull ${SOURCE_FORMS}`,\n )\n }\n return { source: parsed, ...(digest === undefined ? {} : { digest }) }\n}\n\n/** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */\nfunction recordedSource(source: PluginSource, version: string): string | undefined {\n if (source.kind === 'github') return `github:${source.owner}/${source.repo}@${version}`\n return source.kind === 'tarball-url' ? source.url : undefined\n}\n\nconst reasonOf = (cause: unknown): string => {\n if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason\n return cause instanceof Error ? cause.message : String(cause)\n}\n\nexport class PluginShare extends Service {\n /** What was fetched again at this start. */\n readonly restored: Promise<readonly RestoreOutcome[]>\n private readonly dir: string\n private readonly releases: ReleasePort\n private readonly download: (url: string) => Promise<Uint8Array>\n private readonly ports: PublishPorts\n /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */\n private queue: Promise<unknown> = Promise.resolve()\n /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */\n private readonly live = new Map<string, string>()\n private readonly nativeWork: NativePorts\n /** The native package each installed plugin brought for this computer: what its removal takes away. */\n private readonly natives = new Map<string, NativePackage>()\n\n /**\n * 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\n * 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.\n */\n private readonly own: Context\n\n constructor(ctx: Context, config: PluginShareConfig) {\n super(ctx, 'pluginShare')\n this.own = ctx\n this.dir = resolve(config.dir ?? join(ctx.appInstance.root, 'plugins'))\n this.releases = config.releases ?? githubReleasesOverHttps()\n this.download = config.download ?? httpsDownload()\n this.nativeWork = config.native ?? nativePorts()\n this.ports = config.publish ?? { host: githubCli(), git: gitCli() }\n // Removing a plugin removes its record. Listened to here, not asked of each caller: every way of removing it goes through extensions.\n ctx.on('extensions/changed', (name, change) => {\n if (change !== 'removed') return\n this.live.delete(name)\n this.remember(name, undefined)\n this.dropNative(name)\n })\n // Not awaited by the app's start: a person offline still gets their app, and the warning says what is missing.\n this.restored = this.inTurn(() => this.restore())\n }\n\n /** 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. */\n pull(source: string): Promise<PullResult> {\n return this.inTurn(() => this.pullNow(source))\n }\n\n /**\n * 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\n * 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.\n * A list that cannot be read, or has a line that is not one source, pulls nothing.\n */\n async pullList(from: string): Promise<PullListResult> {\n const text = await this.readList(from)\n if (typeof text !== 'string') return text\n const { sources, problems } = parsePullList(text)\n if (problems.length > 0)\n return refuse('list', `${from}: ${problems.join('; ')}`, 'fix the list; nothing was pulled')\n if (sources.length === 0)\n return refuse(\n 'list',\n `${from} names no plugin`,\n 'write one source per line, e.g. github:someone/pomodoro@0.1.0',\n )\n const entries: PullListEntry[] = []\n for (const { line, source } of sources)\n entries.push({ line, source, result: await this.pull(source) })\n return { ok: true, from, entries }\n }\n\n /** The text of a list, or why it cannot be read. */\n private async readList(from: string): Promise<string | PullRefused> {\n const where = pullListLocation(from)\n if (where === undefined)\n return refuse(\n 'list',\n `\"${from}\" is not a list`,\n 'name a file in the app (e.g. group.txt) or an https address of one',\n )\n try {\n let bytes: Uint8Array\n if (where.kind === 'address') bytes = await this.download(where.url)\n else {\n const path = resolve(this.own.appInstance.root, where.path)\n if (!existsSync(path) || !statSync(path).isFile())\n return refuse(\n 'list',\n `there is no file ${where.path}`,\n 'name a file in the app, or an https address',\n )\n bytes = readFileSync(path)\n }\n if (bytes.length > LIST_MAX_BYTES)\n return refuse(\n 'list',\n `${from} is larger than ${String(LIST_MAX_BYTES)} bytes, so it is not a list of plugins`,\n 'name the list itself',\n )\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } catch (cause) {\n return refuse(\n 'list',\n `${from} could not be read: ${reasonOf(cause)}`,\n 'check the address; nothing was pulled',\n )\n }\n }\n\n /**\n * 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\n * 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.\n */\n pulledDigest(name: string): string | undefined {\n return this.live.get(name) ?? this.recorded(name)?.digest\n }\n\n /** The plugins installed while the app runs, each pulled one with its source and author. */\n list(): SharedPluginInfo[] {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n const records = existsSync(file) ? pulledRecords(readFileSync(file, 'utf8')) : {}\n return this.own.extensions.list().map((info) => {\n const record = records[info.name]\n const author = record === undefined ? undefined : authorOf(record.source)\n const release = releaseOf(join(this.dir, info.name))\n return {\n ...info,\n ...(record === undefined ? {} : { pulledFrom: record.source }),\n ...(author === undefined ? {} : { author }),\n ...(release === undefined ? {} : { release }),\n }\n })\n }\n\n /**\n * 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\n * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.\n */\n remove(name: string): Promise<SharedRemoveResult> {\n return this.inTurn(() => this.removeNow(name))\n }\n\n private inTurn<T>(step: () => Promise<T>): Promise<T> {\n const run = this.queue.then(step)\n this.queue = run.catch(() => undefined)\n return run\n }\n\n /**\n * 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.\n */\n planPublish(name: string, options: PublishOptions = {}): Promise<PublishPlan | PublishRefused> {\n return this.inTurn(() => this.planNow(name, options))\n }\n\n /**\n * 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\n * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.\n */\n publish(\n name: string,\n confirmed: PublishPlan,\n options: PublishOptions = {},\n ): Promise<PublishResult> {\n return this.inTurn(async () => {\n const plan = await this.planNow(name, options)\n if ('ok' in plan) return plan\n if (!samePlan(plan, confirmed)) {\n return publishRefused(\n `this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`,\n 'look at the new plan and say yes again',\n )\n }\n const { home } = this.own.appInstance\n try {\n const shared = await sharePlugin(\n join(this.packages, name),\n {\n owner: plan.owner,\n repo: plan.repo,\n visibility: plan.visibility,\n kind: 'source-plugin',\n },\n { ...this.ports, store: new PluginStore(storeRootOf(home)) },\n )\n if (shared.status === 'refused')\n return publishRefused(shared.reason, 'fix what it names; nothing was sent')\n return {\n ok: true,\n url: shared.url,\n releaseUrl: shared.releaseUrl,\n version: shared.version,\n integrity: shared.integrity,\n digest: plan.digest,\n pullLine: plan.pullLine,\n }\n } catch (cause) {\n return publishRefused(\n reasonOf(cause),\n 'look at the repository; part of this publish may have been sent',\n )\n }\n })\n }\n\n /** 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. */\n private remember(name: string, record: PulledRecord | undefined): boolean {\n const { root } = this.own.appInstance\n const file = join(root, 'blend.yaml')\n if (!existsSync(file)) return false\n const text = readFileSync(file, 'utf8')\n const next = withPulledRecord(text, name, record)\n if (next !== text) {\n writeFileSync(`${file}.tmp`, next)\n renameSync(`${file}.tmp`, file)\n if (existsSync(join(root, LOCK_FILE))) writeLock(root)\n }\n return record === undefined || pulledRecords(next)[name] !== undefined\n }\n\n private async removeNow(name: string): Promise<SharedRemoveResult> {\n // Read before the removal, which forgets both the record and the live digest.\n const pulled = this.pulledDigest(name)\n const removed = await this.own.extensions.remove(name)\n if (!removed.ok) return removed\n const folder = join(this.dir, name)\n if (!existsSync(folder)) return { ok: true, name, folder: 'none' }\n if (pulled !== undefined && digestFolder(folder) === pulled) {\n rmSync(folder, { recursive: true, force: true })\n return { ok: true, name, folder: 'deleted' }\n }\n const why = pulled === undefined ? \"is this app's own plugin\" : 'was changed after the pull'\n return {\n ok: true,\n name,\n folder: 'kept',\n note: `plugins/${name} ${why}, so it stays and the app starts it again at its next start; delete the folder to drop it for good`,\n }\n }\n\n /** What `blend.yaml` remembers about one pulled plugin now. */\n private recorded(name: string): PulledRecord | undefined {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n return existsSync(file) ? pulledRecords(readFileSync(file, 'utf8'))[name] : undefined\n }\n\n /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */\n private get places(): NativePlaces {\n return { root: this.own.appInstance.root, home: this.own.appInstance.home }\n }\n\n /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */\n private keepNative(\n name: string,\n native: NativePackage | undefined,\n before: NativePackage | undefined,\n action: NativeAction | undefined,\n ): Pick<Extract<PullResult, { ok: true }>, 'native'> {\n if (\n before !== undefined &&\n (native === undefined ||\n before.version !== native.version ||\n before.package !== native.package)\n )\n this.dropNative(name)\n if (native === undefined || action === undefined) return {}\n this.natives.set(name, native)\n return {\n native: { package: native.package, version: native.version, size: native.size, action },\n }\n }\n\n /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */\n private dropNative(name: string): void {\n const native = this.natives.get(name)\n if (native === undefined) return\n this.natives.delete(name)\n const shared = [...this.natives.values()].some(\n (other) => other.package === native.package && other.version === native.version,\n )\n if (!shared) releaseNative(native, this.places)\n }\n\n /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */\n private async relinkNative(name: string): Promise<void> {\n let manifest: Record<string, unknown>\n try {\n manifest = JSON.parse(readFileSync(join(this.dir, name, 'package.json'), 'utf8')) as Record<\n string,\n unknown\n >\n } catch {\n return\n }\n const declared = nativesOf(manifest)\n const native = 'natives' in declared ? nativeFor(declared.natives) : undefined\n if (native === undefined) return\n try {\n await ensureNative(native, this.places, this.nativeWork)\n this.natives.set(name, native)\n } catch (cause) {\n console.warn(\n `plugin-share: ${name}'s ${native.package} was not installed again: ${reasonOf(cause)}`,\n )\n }\n }\n\n private async restore(): Promise<readonly RestoreOutcome[]> {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n if (!existsSync(file)) return []\n const outcomes: RestoreOutcome[] = []\n for (const [name, record] of Object.entries(pulledRecords(readFileSync(file, 'utf8')))) {\n if (existsSync(join(this.dir, name))) {\n await this.relinkNative(name)\n continue\n }\n const result = await this.pullNow(\n `${record.source}@sha256:${record.digest}`,\n record.integrity,\n )\n outcomes.push(\n result.ok\n ? { name, ok: true }\n : { name, ok: false, reason: result.reason, next: result.next },\n )\n if (!result.ok)\n console.warn(\n `plugin-share: ${name} was not fetched again: ${result.reason}. ${result.next}.`,\n )\n }\n return outcomes\n }\n\n private get packages(): string {\n return join(this.own.appInstance.home, 'plugin-packages')\n }\n\n private async planNow(\n name: string,\n options: PublishOptions,\n ): Promise<PublishPlan | PublishRefused> {\n const source = join(this.dir, name)\n if (!NAME.test(name) || !existsSync(source))\n return publishRefused(\n `this app has no plugin \"${name}\" in plugins/`,\n 'name a folder of plugins/',\n )\n try {\n const { host } = this.ports\n const owner = options.owner ?? host.login()\n const repo = name\n const description = `The ${name} Cordis plugin.`\n const license = options.license ?? DEFAULT_LICENSE\n if (!LICENSE_ID.test(license))\n return publishRefused(\n `\"${license}\" is not a license id`,\n 'write one such as MIT or Apache-2.0',\n )\n const release = { owner, repo, license }\n const existing = host.repository(owner, repo)\n let packaged = await packagePlugin(source, this.packages, name, description, { release })\n const released =\n existing !== undefined && host.releaseExists(owner, repo, `v${packaged.version}`)\n ? packaged.version\n : undefined\n if (released !== undefined)\n packaged = await packagePlugin(source, this.packages, name, description, {\n release,\n version: bumpVersion(released, 'patch'),\n })\n const secrets = findSecrets(\n readTarball(packFolder(packaged.dir).tarball).map((file) => ({\n path: file.path,\n text: Buffer.from(file.content).toString('utf8'),\n })),\n )\n if (secrets.length > 0) {\n return publishRefused(\n `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,\n \"take them out of the plugin and read them from the app's settings\",\n )\n }\n return {\n owner,\n repo,\n version: packaged.version,\n visibility: 'public',\n license,\n createsRepository: existing === undefined,\n ...(released === undefined ? {} : { released }),\n files: packaged.files,\n integrity: packaged.integrity,\n digest: packaged.digest,\n pullLine: pullLineOf(owner, repo, packaged.version, packaged.digest),\n }\n } catch (cause) {\n return publishRefused(reasonOf(cause), 'fix it, or sign in with gh; nothing was sent')\n }\n }\n\n private async pullNow(input: string, expectIntegrity?: string): Promise<PullResult> {\n const { home, root } = this.own.appInstance\n let read: ReturnType<typeof readSource>\n try {\n read = readSource(input, root)\n } catch (cause) {\n return refuse(\n 'source',\n reasonOf(cause),\n `write ${SOURCE_FORMS}, with @sha256:<digest> at the end to name the content`,\n )\n }\n mkdirSync(home, { recursive: true })\n const scratch = mkdtempSync(join(home, 'plugin-pull-'))\n try {\n let pulled: Awaited<ReturnType<typeof pullPlugin>>\n try {\n pulled = await pullPlugin(\n read.source,\n {\n store: new PluginStore(scratch),\n releases: this.releases,\n download: this.download,\n },\n expectIntegrity === undefined ? {} : { expectIntegrity },\n )\n } catch (cause) {\n return refuse(\n 'fetch',\n reasonOf(cause),\n 'check the source with the person who released it; nothing was installed',\n )\n }\n const files: PluginFile[] = readTarball(readFileSync(pulled.stored.path)).map(\n ({ path, content }) => ({ path, bytes: content, kind: 'file' }),\n )\n const refused = pullRefusal(pulled.manifest, files, {\n digest: read.digest,\n nameFits: (name) => NAME.test(name),\n hasService: (service) => this.own.get(service as never) !== undefined,\n })\n if (refused !== undefined) return refused\n const declared = nativesOf(pulled.manifest)\n return await this.install(\n pulled.stored.name,\n pulled.stored.version,\n pulled.stored.integrity,\n files,\n recordedSource(read.source, pulled.stored.version),\n 'natives' in declared ? nativeFor(declared.natives) : undefined,\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n }\n\n /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */\n private async install(\n name: string,\n version: string,\n integrity: string,\n files: readonly PluginFile[],\n source: string | undefined,\n native: NativePackage | undefined,\n ): Promise<PullResult> {\n const target = join(this.dir, name)\n const incoming = join(this.dir, `.pulling-${name}`)\n rmSync(incoming, { recursive: true, force: true })\n try {\n for (const file of files) {\n const path = join(incoming, ...file.path.split('/'))\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.bytes)\n }\n const digest = digestFolder(incoming)\n // The folder may be there already: the same bytes are already pulled, anything else is someone's work.\n const wrote = !existsSync(target)\n const before = this.recorded(name)\n const held = wrote ? undefined : digestFolder(target)\n if (held !== undefined && held !== digest) {\n const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`\n // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.\n const next =\n before !== undefined && held === before.digest\n ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`\n : `keep it, or move plugins/${name} out of plugins/ and pull again`\n return refuse(\n 'folder-exists',\n `plugins/${name} holds a different copy of this plugin, ${holder}`,\n next,\n )\n }\n const liveBefore = this.live.get(name)\n this.live.set(name, digest)\n if (wrote) renameSync(incoming, target)\n // Remembered as the folder appears, before it is installed, so whoever sees the folder can tell it is these released bytes (the frame then does\n // not load the app again for a plugin the app installs live); a pull that does not end running puts back what was remembered before.\n const remembered = source !== undefined && this.remember(name, { source, integrity, digest })\n // Installed before the plugin starts, so the plugin finds it; an install that does not end running takes back only what it added.\n let nativeAction: NativeAction | undefined\n const nativeBefore = this.natives.get(name)\n const undo = () => {\n if (native !== undefined && (nativeAction === 'downloaded' || nativeAction === 'linked'))\n releaseNative(native, this.places, nativeAction === 'linked')\n if (wrote) rmSync(target, { recursive: true, force: true })\n if (remembered) this.remember(name, before)\n if (liveBefore === undefined) this.live.delete(name)\n else this.live.set(name, liveBefore)\n }\n if (native !== undefined) {\n try {\n nativeAction = await ensureNative(native, this.places, this.nativeWork)\n } catch (cause) {\n undo()\n return refuse(\n 'native',\n `${native.package}@${native.version} (${Math.round(native.size / 1e6)} MB) could not be installed: ${reasonOf(cause)}`,\n 'check the internet connection and pull again; the plugin was not installed',\n )\n }\n }\n let result: Awaited<ReturnType<Context['extensions']['install']>>\n try {\n result = await this.own.extensions.install(target)\n } catch (cause) {\n undo()\n return refuse(\n 'install',\n reasonOf(cause),\n 'this app does not install plugins while it runs like this',\n )\n }\n if (!result.ok) {\n undo()\n return refuse('install', result.errors.join('; '), result.next)\n }\n if (result.state === 'pending') {\n await this.own.extensions.remove(name)\n undo()\n return missingServices(result.missing)\n }\n return {\n ok: true,\n name,\n version,\n integrity,\n digest,\n action: result.action,\n state: result.state,\n remembered,\n ...this.keepNative(name, native, nativeBefore, nativeAction),\n }\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n }\n}\n\nexport const pluginShare = {\n name: 'plugin-share',\n inject: ['extensions', 'appInstance'],\n apply(ctx: Context, config: PluginShareConfig) {\n // A pull runs a stranger's code and a publish leaves the machine: development only. The templates' src/app.ts leaves the row out in production; an\n // app whose src/app.ts is older than that line is covered here.\n if (process.env.NODE_ENV === 'production') return\n new PluginShare(ctx, config ?? {})\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,kBAAkB;;AAG/B,MAAa,mBAAmB;;AAMhC,MAAM,WAAW;AAmBjB,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,SAAS;AACf,MAAM,OAA0B;CAAC;CAAU;CAAS;AAAO;AAC3D,MAAM,OAA0B,CAAC,SAAS,KAAK;AAE/C,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGrE,SAAgB,UACd,UAC6E;CAC7E,MAAM,UAAU,SAAS;CACzB,IAAI,YAAY,KAAA,KAAc,SAAS,OAAO,KAAK,QAAQ,WAAW,KAAA,GACpE,OAAO,EAAE,SAAS,CAAC,EAAE;CACvB,IAAI,CAAC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../merge-edits.ts","../native.ts","../npm-login.ts","../publish.ts","../pull-check.ts","../pull-list.ts","../pulled-records.ts","../registry-source.ts","../index.ts"],"sourcesContent":["/**\n * A pulled plugin pulled again at a newer release, with the person's own edits in its folder. Three trees meet: `base` (the release they pulled), `mine` (the\n * folder now) and `theirs` (the new release). A file only one side changed takes that side's change; a file both changed is merged line by line, and the\n * merge is refused when the changes overlap. Pure over bytes, except the line merge, which is git's (`git merge-file`) and is passed in so a test needs no git.\n */\nimport { spawnSync } from 'node:child_process'\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\n/** A plugin's files by their `/` path. */\nexport type Tree = ReadonlyMap<string, Uint8Array>\n\n/** Merge one text file three ways: the merged bytes, or undefined when the two changes overlap. */\nexport type MergeFile = (\n base: Uint8Array,\n mine: Uint8Array,\n theirs: Uint8Array,\n) => Uint8Array | undefined\n\nexport interface MergedTrees {\n /** What the folder holds afterwards. */\n readonly files: ReadonlyMap<string, Uint8Array>\n /** The files that keep something of the person's own: their edit stands, or it was merged with the release's change. */\n readonly kept: readonly string[]\n /** The files whose changes overlap, or that one side changed and the other removed: nothing is written while there is one. */\n readonly conflicts: readonly string[]\n}\n\nconst same = (a: Uint8Array | undefined, b: Uint8Array | undefined): boolean =>\n a === undefined || b === undefined ? a === b : Buffer.from(a).equals(b)\n\n/** git's own three-way line merge. A binary file, a conflict, or no git on this computer is \"cannot merge\". */\nexport const gitMergeFile: MergeFile = (base, mine, theirs) => {\n if ([base, mine, theirs].some((bytes) => bytes.includes(0))) return undefined\n const dir = mkdtempSync(join(tmpdir(), 'plugin-merge-'))\n try {\n const [b, m, t] = ['base', 'mine', 'theirs'].map((name) => join(dir, name)) as [\n string,\n string,\n string,\n ]\n writeFileSync(b, base)\n writeFileSync(m, mine)\n writeFileSync(t, theirs)\n // `-p` prints the result; the status is the number of conflicts (0 = clean), negative on an error.\n const result = spawnSync('git', ['merge-file', '-p', m, b, t], { maxBuffer: 64 * 1024 * 1024 })\n return result.error === undefined && result.status === 0 ? result.stdout : undefined\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\n/** shortcut: a symlink is read as the file it points at and written back as a file; a plugin that is pulled holds none (portability refuses them). */\nexport function mergeTrees(\n base: Tree,\n mine: Tree,\n theirs: Tree,\n mergeFile: MergeFile = gitMergeFile,\n): MergedTrees {\n const files = new Map<string, Uint8Array>()\n const kept: string[] = []\n const conflicts: string[] = []\n const paths = [...new Set([...base.keys(), ...mine.keys(), ...theirs.keys()])].sort()\n for (const path of paths) {\n const [b, m, t] = [base.get(path), mine.get(path), theirs.get(path)]\n const put = (bytes: Uint8Array | undefined): void => {\n if (bytes !== undefined) files.set(path, bytes)\n }\n if (same(m, t)) put(m)\n else if (same(m, b)) put(t)\n else if (same(t, b)) {\n put(m)\n kept.push(path)\n } else if (b !== undefined && m !== undefined && t !== undefined) {\n const merged = mergeFile(b, m, t)\n if (merged === undefined) conflicts.push(path)\n else {\n files.set(path, merged)\n kept.push(path)\n }\n } else conflicts.push(path)\n }\n return { files, kept, conflicts }\n}\n","/**\n * 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\n * 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`).\n *\n * A plugin's package.json names them, one entry per OS and CPU, each pinned by npm's sha512:\n *\n * \"@acryldev/blends\": { \"native\": [\n * { \"package\": \"@deepseek-ai/libreoffice-kit-darwin-arm64\", \"version\": \"0.1.5\", \"os\": \"darwin\", \"cpu\": \"arm64\",\n * \"integrity\": \"sha512-...\", \"size\": 153171456 } ] }\n *\n * 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\n * 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\n * that needs it resolves it. Only a missing package or the empty placeholder (`@acryldev/absent`) is replaced; a real copy npm installed stays.\n * Removing the plugin takes the link and the download away; an app's start links again what an `npm install` unlinked.\n */\nimport { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n symlinkSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\n/** Where a native package is downloaded from: the npm registry, and nothing else. */\nexport const NATIVE_REGISTRY = 'https://registry.npmjs.org'\n\n/** The most a plugin's native packages may unpack to, all of its entries for one computer together. */\nexport const NATIVE_MAX_BYTES = 1_000_000_000\n\n/** The empty package the frame installs in place of an omitted one (frame/packages.json `omit.placeholder`). */\nexport const PLACEHOLDER = '@acryldev/absent'\n\n/** The file written last into an unpacked native package: without it the folder is an interrupted download. */\nconst COMPLETE = '.acrylblends-native-complete'\n\nexport type NativeOs = 'darwin' | 'linux' | 'win32'\nexport type NativeCpu = 'arm64' | 'x64'\n\nexport interface NativePackage {\n /** The npm package, as the package that needs it resolves it. */\n readonly package: string\n /** Its exact version. */\n readonly version: string\n readonly os: NativeOs\n /** Absent: any CPU of that OS (a WebAssembly build). */\n readonly cpu?: NativeCpu\n /** npm's `dist.integrity` of the tarball. */\n readonly integrity: string\n /** npm's `dist.unpackedSize`, in bytes: what a person is told before it is downloaded. */\n readonly size: number\n}\n\nconst NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u\nconst EXACT_VERSION = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u\nconst SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u\nconst OSES: readonly string[] = ['darwin', 'linux', 'win32']\nconst CPUS: readonly string[] = ['arm64', 'x64']\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */\nexport function nativesOf(\n manifest: Readonly<Record<string, unknown>>,\n): { readonly natives: readonly NativePackage[] } | { readonly error: string } {\n const section = manifest.acrylblends\n if (section === undefined || (isObject(section) && section.native === undefined))\n return { natives: [] }\n if (!isObject(section) || !Array.isArray(section.native))\n return { error: '\"acrylblends.native\" is not a list' }\n const natives: NativePackage[] = []\n for (const [index, entry] of section.native.entries()) {\n const at = `acrylblends.native[${index}]`\n if (!isObject(entry)) return { error: `${at} is not an object` }\n const { package: name, version, os, cpu, integrity, size } = entry\n if (typeof name !== 'string' || !NPM_NAME.test(name))\n return { error: `${at}.package is not an npm package name` }\n if (typeof version !== 'string' || !EXACT_VERSION.test(version))\n return { error: `${at}.version is not an exact version` }\n if (typeof os !== 'string' || !OSES.includes(os))\n return { error: `${at}.os is not one of ${OSES.join(', ')}` }\n if (cpu !== undefined && (typeof cpu !== 'string' || !CPUS.includes(cpu)))\n return { error: `${at}.cpu is not one of ${CPUS.join(', ')}` }\n if (typeof integrity !== 'string' || !SHA512.test(integrity))\n return { error: `${at}.integrity is not npm's sha512 of the tarball` }\n if (typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0)\n return { error: `${at}.size is not a number of bytes` }\n if (size > NATIVE_MAX_BYTES)\n return {\n error: `${at} unpacks to ${size} bytes, more than a plugin may bring (${NATIVE_MAX_BYTES})`,\n }\n natives.push({\n package: name,\n version,\n os: os as NativeOs,\n ...(cpu === undefined ? {} : { cpu: cpu as NativeCpu }),\n integrity,\n size,\n })\n }\n return { natives }\n}\n\n/** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */\nexport function nativeFor(\n natives: readonly NativePackage[],\n platform: string = process.platform,\n arch: string = process.arch,\n): NativePackage | undefined {\n return (\n natives.find((entry) => entry.os === platform && entry.cpu === arch) ??\n natives.find((entry) => entry.os === platform && entry.cpu === undefined)\n )\n}\n\n/** The tarball's address in the npm registry, the way npm names it. */\nexport function tarballUrl(native: Pick<NativePackage, 'package' | 'version'>): string {\n const base = native.package.slice(native.package.lastIndexOf('/') + 1)\n return `${NATIVE_REGISTRY}/${native.package}/-/${base}-${native.version}.tgz`\n}\n\n/** What a download and an unpack are, so a test can hand in local ones. */\nexport interface NativePorts {\n /** Write the file at `url` to `file`. */\n readonly download: (url: string, file: string) => Promise<void>\n /** Unpack the `.tgz` at `file` into `dir`, without the archive's top folder (npm's `package/`) and with the files' modes. */\n readonly unpack: (file: string, dir: string) => Promise<void>\n}\n\n/** 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. */\nexport function nativePorts(): NativePorts {\n return {\n async download(url, file) {\n if (!url.startsWith(`${NATIVE_REGISTRY}/`))\n throw new Error(`${url} is not in the npm registry`)\n const response = await fetch(url)\n if (!response.ok || response.body === null)\n throw new Error(`the npm registry answered ${response.status} for ${url}`)\n await pipeline(Readable.fromWeb(response.body as never), createWriteStream(file))\n },\n unpack: (file, dir) =>\n new Promise((done, fail) => {\n const tar = spawn('tar', ['-xzf', file, '-C', dir, '--strip-components=1'], {\n stdio: ['ignore', 'ignore', 'pipe'],\n windowsHide: true,\n })\n let error = ''\n tar.stderr.on('data', (chunk: Buffer) => {\n error += chunk.toString()\n })\n tar.once('error', fail)\n tar.once('exit', (code) =>\n code === 0 ? done() : fail(new Error(`tar could not unpack ${file}: ${error.trim()}`)),\n )\n }),\n }\n}\n\n/** Where the app keeps what it downloaded, and where it links it. */\nexport interface NativePlaces {\n /** The app's folder, whose `node_modules` the link goes into. */\n readonly root: string\n /** The app's home, which keeps the downloads. */\n readonly home: string\n}\n\n/** The folder a native package is unpacked into. */\nexport function nativeStore(\n home: string,\n native: Pick<NativePackage, 'package' | 'version'>,\n): string {\n return join(home, 'native', `${native.package.replace('/', '+')}@${native.version}`)\n}\n\nconst linkOf = (root: string, native: Pick<NativePackage, 'package'>) =>\n join(root, 'node_modules', ...native.package.split('/'))\n\n/** What is at the package's place in node_modules: our link, nothing, something we may replace, or a real package someone installed. */\nfunction placeState(link: string, store: string): 'ours' | 'missing' | 'replaceable' | 'foreign' {\n let stat: ReturnType<typeof lstatSync>\n try {\n stat = lstatSync(link)\n } catch {\n return 'missing'\n }\n if (stat.isSymbolicLink()) {\n let target: string\n try {\n target = realpathSync(link)\n } catch {\n return 'replaceable'\n }\n if (existsSync(store) && target === realpathSync(store)) return 'ours'\n // Another version this app downloaded (the plugin was updated): replaced, never mistaken for a copy npm installed.\n if (existsSync(dirname(store)) && dirname(target) === realpathSync(dirname(store)))\n return 'replaceable'\n }\n let name: unknown\n try {\n name = (JSON.parse(readFileSync(join(link, 'package.json'), 'utf8')) as { name?: unknown }).name\n } catch {\n return stat.isSymbolicLink() ? 'replaceable' : 'foreign'\n }\n return name === PLACEHOLDER ? 'replaceable' : 'foreign'\n}\n\nconst sha512Of = async (file: string): Promise<string> => {\n const hash = createHash('sha512')\n await pipeline(createReadStream(file), hash)\n return `sha512-${hash.digest('base64')}`\n}\n\n/** Download, check and unpack into the store; the store appears whole or not at all. */\nasync function fetchInto(native: NativePackage, store: string, ports: NativePorts): Promise<void> {\n mkdirSync(dirname(store), { recursive: true })\n const incoming = mkdtempSync(join(dirname(store), '.incoming-'))\n try {\n const file = join(incoming, 'package.tgz')\n await ports.download(tarballUrl(native), file)\n const integrity = await sha512Of(file)\n if (integrity !== native.integrity)\n throw new Error(\n `${native.package}@${native.version} from npm is not the file the plugin names (its sha512 differs)`,\n )\n const unpacked = join(incoming, 'package')\n mkdirSync(unpacked)\n await ports.unpack(file, unpacked)\n const manifest = JSON.parse(readFileSync(join(unpacked, 'package.json'), 'utf8')) as {\n name?: unknown\n version?: unknown\n }\n if (manifest.name !== native.package || manifest.version !== native.version)\n throw new Error(\n `the tarball holds ${String(manifest.name)}@${String(manifest.version)}, not ${native.package}@${native.version}`,\n )\n writeFileSync(join(unpacked, COMPLETE), '')\n rmSync(store, { recursive: true, force: true })\n renameSync(unpacked, store)\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n}\n\n/** What `ensureNative` did: downloaded it, only linked a download it had, found it linked, or left a real copy npm installed. */\nexport type NativeAction = 'downloaded' | 'linked' | 'unchanged' | 'present'\n\n/** 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. */\nexport async function ensureNative(\n native: NativePackage,\n places: NativePlaces,\n ports: NativePorts = nativePorts(),\n): Promise<NativeAction> {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n const state = placeState(link, store)\n if (state === 'foreign') return 'present'\n const complete = existsSync(join(store, COMPLETE))\n if (state === 'ours' && complete) return 'unchanged'\n if (!complete) await fetchInto(native, store, ports)\n rmSync(link, { recursive: true, force: true })\n mkdirSync(dirname(link), { recursive: true })\n // A junction on Windows: a directory symlink there needs a privilege a person may not have.\n symlinkSync(store, link, process.platform === 'win32' ? 'junction' : 'dir')\n return complete ? 'linked' : 'downloaded'\n}\n\n/** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */\nexport function releaseNative(\n native: Pick<NativePackage, 'package' | 'version'>,\n places: NativePlaces,\n keepDownload = false,\n): void {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n if (placeState(link, store) === 'ours') unlinkSync(link)\n if (!keepDownload) rmSync(store, { recursive: true, force: true })\n}\n","/**\n * The person's own npm, for a publish: who is signed in (`npm whoami`) and the publish itself, both through the `npm` on this computer and its configuration\n * (`.npmrc`). Nothing here reads or stores a token; a missing npm or login is reported with what to do.\n */\nimport { spawnSync } from 'node:child_process'\nimport { type NpmPublishPort, npmCli } from '@acryldev/plugin-hub-core'\n\n/** The registry's login and the publish, as the plan and the confirmed publish use them. */\nexport interface NpmPort extends NpmPublishPort {\n /** The account the person's npm is signed in as on `registry`. @throws naming `npm login` when it is not signed in. */\n login(registry: string): string\n}\n\nexport function npmWithLogin(): NpmPort {\n return {\n ...npmCli(),\n login(registry) {\n // On Windows npm is a .cmd file, which Node runs only through a shell; the arguments are ours, never the person's text.\n const result = spawnSync('npm', ['whoami', '--registry', registry], {\n encoding: 'utf8',\n shell: process.platform === 'win32',\n env: { ...process.env, npm_config_update_notifier: 'false' },\n })\n if (result.error !== undefined)\n throw new Error(\n 'npm is not available here: install Node.js (https://nodejs.org), which includes npm, and sign in with: npm login',\n )\n const account = (result.stdout ?? '').trim()\n if (result.status !== 0 || account === '') {\n const last =\n (result.stderr ?? '')\n .trim()\n .split('\\n')\n .filter((line) => !/^npm (notice|warn)/iu.test(line))\n .at(-1) ?? 'not signed in'\n throw new Error(\n `npm whoami failed: ${last} (sign in with: npm login --registry ${registry})`,\n )\n }\n return account\n },\n }\n}\n","/**\n * Publishing a plugin: what a person is asked to say yes to, and the comparison that makes the yes mean exactly that. Pure; the service does the I/O.\n */\nimport type { PublishGitPort, RepositoryHostPort } from '@acryldev/plugin-hub-core'\nimport type { NpmPort } from './npm-login.ts'\n\n/** Everything that leaves the machine, named before anything does. */\nexport interface PublishPlan {\n /** Where it goes: a GitHub release (absent) or an npm registry. For npm `owner` is the scope and `repo` the plugin's name. */\n readonly target?: 'npm'\n /** npm: the package's name (`@scope/name`) and the registry it is published to. */\n readonly package?: string\n readonly registry?: string\n readonly owner: string\n readonly repo: string\n readonly version: string\n readonly visibility: 'public'\n readonly license: string\n /** The repository does not exist yet: publishing creates it. */\n readonly createsRepository: boolean\n /** The version already released there; the plan then releases the next patch. */\n readonly released?: string\n readonly files: readonly string[]\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n /** What a friend runs to get exactly these bytes. */\n readonly pullLine: string\n}\n\nexport interface PublishRefused {\n readonly ok: false\n readonly reason: string\n readonly next: string\n}\n\nexport type PublishResult =\n | {\n readonly ok: true\n readonly url: string\n readonly releaseUrl: string\n readonly version: string\n readonly integrity: string\n readonly digest: string\n readonly pullLine: string\n }\n | PublishRefused\n\nexport interface PublishOptions {\n /** The account or organization; the signed-in one when absent. */\n readonly owner?: string\n /** The license the plugin is offered under, as an SPDX id; MIT when absent. The plan shows it before the person says yes. */\n readonly license?: string\n /** `npm`: publish to an npm registry with the person's own npm login instead of to GitHub. */\n readonly to?: 'npm'\n /** npm: the scope of the package; the account npm is signed in as when absent. */\n readonly scope?: string\n /** npm: the registry; the public one when absent. */\n readonly registry?: string\n}\n\n/** Where a publish goes through: the person's own `gh` and `git`. A test passes stand-ins, so no test publishes. */\nexport interface PublishPorts {\n readonly host: RepositoryHostPort\n readonly git: PublishGitPort\n /** The person's own npm (`npm whoami`, `npm publish`); the default is their installed npm. A test passes a stand-in. */\n readonly npm?: NpmPort\n}\n\n/** The line a friend copies: it names the bytes, so the check comes for free. */\nexport const pullLineOf = (owner: string, repo: string, version: string, digest: string): string =>\n `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`\n\n/** The line a friend copies for an npm package. */\nexport const npmPullLineOf = (name: string, version: string, digest: string): string =>\n `npm run acryl -- plugin pull npm:${name}@${version}@sha256:${digest}`\n\n/**\n * 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.\n * 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.\n */\nexport function samePlan(a: PublishPlan, b: PublishPlan): boolean {\n return (\n a.target === b.target &&\n a.package === b.package &&\n a.registry === b.registry &&\n a.owner === b.owner &&\n a.repo === b.repo &&\n a.version === b.version &&\n a.visibility === b.visibility &&\n a.license === b.license &&\n a.createsRepository === b.createsRepository &&\n a.integrity === b.integrity &&\n a.digest === b.digest &&\n a.pullLine === b.pullLine &&\n a.files.length === b.files.length &&\n a.files.every((file, index) => file === b.files[index])\n )\n}\n","/**\n * 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,\n * so a refusal has nothing to undo (Clean Architecture: policy free of I/O).\n */\nimport { digestFiles, type PluginFile, portabilityIssues } from '@acryldev/blends-core'\nimport { hostInjectFromSource } from '@acryldev/plugin-hub-core'\nimport { nativesOf } from './native.ts'\n\nexport type Refusal =\n | 'source'\n | 'fetch'\n | 'name'\n | 'digest'\n | 'portability'\n | 'dependencies'\n /** Its `acrylblends.native` list (native.ts) cannot be used. */\n | 'native'\n | 'entry'\n | 'inject'\n | 'missing-service'\n | 'folder-exists'\n | 'install'\n /** A list of sources that cannot be read, or holds a line that is not one source. */\n | 'list'\n\nexport interface PullRefused {\n readonly ok: false\n readonly refusal: Refusal\n readonly reason: string\n /** What the person can do about it. */\n readonly next: string\n}\n\nexport const refuse = (refusal: Refusal, reason: string, next: string): PullRefused => ({\n ok: false,\n refusal,\n reason,\n next,\n})\n\nconst SHA256 = /^[0-9a-f]{64}$/\nconst DIGEST_MARK = '@sha256:'\n\n/** The source a person wrote, split into where it comes from and the content digest it names. @throws when the digest is malformed. */\nexport function splitDigest(input: string): { readonly source: string; readonly digest?: string } {\n const at = input.lastIndexOf(DIGEST_MARK)\n if (at === -1) return { source: input }\n const digest = input.slice(at + DIGEST_MARK.length)\n if (!SHA256.test(digest))\n throw new Error(`\"${digest}\" is not a content digest: it has 64 lowercase hex characters`)\n return { source: input.slice(0, at), digest }\n}\n\n/** The entry files the extensions folder loads, in its order. */\nconst ENTRIES = ['index.ts', 'index.js', 'index.mjs']\n\nconst text = (file: PluginFile): string => Buffer.from(file.bytes).toString('utf8')\n\nexport interface PullContext {\n /** The content digest the source names. */\n readonly digest?: string | undefined\n /** Whether the extensions folder can hold a plugin of this name. */\n readonly nameFits: (name: string) => boolean\n /** Whether this app has the service right now. */\n readonly hasService: (name: string) => boolean\n}\n\n/** The first reason this package may not enter the app, or undefined. */\nexport function pullRefusal(\n manifest: Readonly<Record<string, unknown>>,\n files: readonly PluginFile[],\n context: PullContext,\n): PullRefused | undefined {\n const name = String(manifest.name)\n if (!context.nameFits(name)) {\n return refuse(\n 'name',\n `the package is called \"${name}\", which a folder in plugins/ cannot hold`,\n 'ask its author to release it under lowercase letters, digits and dashes',\n )\n }\n const digest = digestFiles(files)\n if (context.digest !== undefined && context.digest !== digest) {\n return refuse(\n 'digest',\n `${digest} is not the digest the source names (${context.digest}); these are different bytes`,\n 'ask the person who gave you the digest which release they meant',\n )\n }\n const issues = portabilityIssues(files)\n if (issues.length > 0) {\n return refuse(\n 'portability',\n issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; '),\n 'ask its author to fix this and release again, so it works on every OS',\n )\n }\n const dependencies = Object.keys(\n (manifest.dependencies as Record<string, unknown> | undefined) ?? {},\n )\n if (dependencies.length > 0) {\n return refuse(\n 'dependencies',\n `it needs ${dependencies.join(', ')} installed, and a pull installs nothing`,\n 'ask its author to bundle them or name them as peers',\n )\n }\n const native = nativesOf(manifest)\n if ('error' in native) {\n return refuse(\n 'native',\n native.error,\n 'ask its author to fix \"acrylblends.native\" in its package.json and release again',\n )\n }\n const entry = ENTRIES.flatMap((path) => files.filter((file) => file.path === path))[0]\n if (entry === undefined) {\n return refuse(\n 'entry',\n `it has none of ${ENTRIES.join(', ')} at its top level`,\n 'this package is not a plugin an app can load; ask its author',\n )\n }\n const inject = hostInjectFromSource(text(entry))\n if (inject !== undefined && 'error' in inject) {\n return refuse(\n 'inject',\n `${inject.error}. A pull reads what a plugin needs without running it`,\n 'ask its author to list the services as plain names',\n )\n }\n const missing = (inject?.names ?? []).filter((service) => !context.hasService(service))\n if (missing.length > 0) return missingServices(missing)\n return undefined\n}\n\nexport const missingServices = (missing: readonly string[]): PullRefused =>\n refuse(\n 'missing-service',\n `it needs ${missing.join(', ')}, which this app does not have`,\n 'add the plugin that provides it, then pull again',\n )\n","/**\n * 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\n * `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\n * 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.\n */\n\n/** A list is a few lines of text: anything larger is not a list of plugins. */\nexport const LIST_MAX_BYTES = 64 * 1024\n\n/** More sources than a group has people is a mistake, not a workshop. */\nexport const LIST_MAX_SOURCES = 100\n\n/** The command a person pastes from `plugin publish`: only its source is kept. */\nconst PULL_COMMAND = /^(?:npm run acryl --\\s+)?plugin pull\\s+/u\n\n/** A `#` at the start of a line or after a space begins a comment; a source never holds one there. */\nconst COMMENT = /(?:^|\\s)#.*$/u\n\nexport interface PullListLine {\n /** Its line in the list, from 1, so a problem is easy to find. */\n readonly line: number\n readonly source: string\n}\n\nexport interface ParsedPullList {\n /** The sources in their order, each once. */\n readonly sources: readonly PullListLine[]\n /** Lines that are not one source, each with what is wrong. */\n readonly problems: readonly string[]\n}\n\n/** The sources of a list, in order and without repeats, and the lines that are not a source. */\nexport function parsePullList(text: string): ParsedPullList {\n const sources: PullListLine[] = []\n const problems: string[] = []\n const seen = new Set<string>()\n text.split(/\\r?\\n/u).forEach((raw, index) => {\n const line = index + 1\n const value = raw.replace(COMMENT, '').trim().replace(PULL_COMMAND, '').trim()\n if (value === '') return\n if (/\\s/u.test(value)) {\n problems.push(\n `line ${String(line)} holds more than one word (\"${value}\"); write one source per line`,\n )\n return\n }\n if (seen.has(value)) return\n seen.add(value)\n sources.push({ line, source: value })\n })\n if (sources.length > LIST_MAX_SOURCES)\n problems.push(\n `the list has ${String(sources.length)} sources; a list holds at most ${String(LIST_MAX_SOURCES)}`,\n )\n return { sources, problems }\n}\n\n/** Where a list is read from: an https address, or a file (relative to the app folder). */\nexport type PullListLocation =\n | { readonly kind: 'address'; readonly url: string }\n | { readonly kind: 'file'; readonly path: string }\n\n/** @returns undefined for something that is neither (an http: address, a github: source): the caller names what a list may be. */\nexport function pullListLocation(from: string): PullListLocation | undefined {\n const value = from.trim()\n if (value === '') return undefined\n if (/^https:\\/\\//iu.test(value)) return { kind: 'address', url: value }\n // A drive letter (C:\\...) is a path; any other scheme is not a place a list is read from.\n if (/^[a-z][a-z0-9+.-]+:/iu.test(value) && !/^[a-z]:[\\\\/]/iu.test(value)) return undefined\n return { kind: 'file', path: value }\n}\n","/**\n * 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\n * 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\n * to text; comments and the person's formatting stay.\n */\nimport { isMap, isSeq, parseDocument } from 'yaml'\n\nexport const ROW = 'plugin-share'\n\nexport interface PulledRecord {\n /** `github:<owner>/<repo>@<version>` or an https address: something another machine can fetch. */\n readonly source: string\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n}\n\nconst isRecord = (value: unknown): value is PulledRecord => {\n const record = value as Partial<Record<keyof PulledRecord, unknown>> | null\n return (\n typeof record?.source === 'string' &&\n typeof record.integrity === 'string' &&\n typeof record.digest === 'string'\n )\n}\n\n/** The plugins this definition remembers pulling. */\nexport function pulledRecords(text: string): Readonly<Record<string, PulledRecord>> {\n const rows = (parseDocument(text).toJS() as { spec?: { rows?: unknown } } | null)?.spec?.rows\n if (!Array.isArray(rows)) return {}\n const pulled = (\n rows.find((row: { name?: unknown }) => row?.name === ROW) as\n | { config?: { pulled?: unknown } }\n | undefined\n )?.config?.pulled\n if (typeof pulled !== 'object' || pulled === null) return {}\n return Object.fromEntries(\n Object.entries(pulled).filter(([, record]) => isRecord(record)),\n ) as Record<string, PulledRecord>\n}\n\n/**\n * 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\n * composed without the row has nowhere to remember.\n */\nexport function withPulledRecord(\n text: string,\n name: string,\n record: PulledRecord | undefined,\n): string {\n const document = parseDocument(text)\n const rows = document.getIn(['spec', 'rows'])\n if (!isSeq(rows)) return text\n const row = rows.items.find((item) => isMap(item) && item.get('name') === ROW)\n if (!isMap(row)) return text\n if (record === undefined) {\n if (!row.hasIn(['config', 'pulled', name])) return text\n row.deleteIn(['config', 'pulled', name])\n const left = row.getIn(['config', 'pulled'])\n if (isMap(left) && left.items.length === 0) row.deleteIn(['config', 'pulled'])\n const config = row.get('config')\n if (isMap(config) && config.items.length === 0) row.delete('config')\n } else {\n row.setIn(['config'], row.get('config') ?? document.createNode({}))\n if (!row.hasIn(['config', 'pulled'])) row.setIn(['config', 'pulled'], document.createNode({}))\n row.setIn(['config', 'pulled', name], document.createNode(record))\n }\n return String(document)\n}\n","/**\n * `registry:<id>`: a plugin the public registry (cordisplugins.github.io) lists, pulled by the id it shows. The registry only points at a public GitHub\n * release, so the id is turned into the `github:<owner>/<repo>@<version>` source that release has, and the integrity the registry lists is the check the\n * download must pass: a release changed after the registry read it is refused. Pure; the caller fetches the index.\n */\n\nexport const REGISTRY_INDEX_URL = 'https://cordisplugins.github.io/registry/index.json'\n\n/** What a pull needs of one registry entry (the rest of the entry is for the page that shows it). */\nexport interface RegistryHit {\n /** `github:<owner>/<repo>@<version>`: what another machine fetches, and what the app records. */\n readonly source: string\n /** The sha512 the registry lists for the release file. */\n readonly integrity: string\n}\n\nexport type RegistryLookup =\n | { readonly ok: true; readonly hit: RegistryHit }\n | { readonly ok: false; readonly reason: string; readonly next: string }\n\nconst GITHUB_REPO =\n /^https:\\/\\/github\\.com\\/([A-Za-z0-9][A-Za-z0-9-]*)\\/([A-Za-z0-9][A-Za-z0-9._-]*?)(?:\\.git)?\\/?$/u\n\n/** Find `id` (or the package name, `@scope/name`) in the index text; its release as a source, or why there is none. */\nexport function lookUpRegistry(indexText: string, id: string): RegistryLookup {\n let entries: unknown\n try {\n entries = (JSON.parse(indexText) as { entries?: unknown }).entries\n } catch {\n entries = undefined\n }\n if (!Array.isArray(entries))\n return {\n ok: false,\n reason: 'the registry answered in a way this app does not understand',\n next: 'try again later, or pull github:<owner>/<repo> from the plugin page',\n }\n const wanted = id.trim().toLowerCase()\n const entry = entries.find(\n (item: { id?: unknown; name?: unknown }) =>\n typeof item?.id === 'string' &&\n (item.id.toLowerCase() === wanted ||\n (typeof item.name === 'string' && item.name.toLowerCase() === wanted)),\n ) as { repo?: unknown; version?: unknown; integrity?: unknown } | undefined\n if (entry === undefined)\n return {\n ok: false,\n reason: `the registry lists no plugin ${id}`,\n next: 'copy the id from https://cordisplugins.github.io, or pull github:<owner>/<repo>',\n }\n const repo = typeof entry.repo === 'string' ? GITHUB_REPO.exec(entry.repo) : null\n if (repo === null || typeof entry.version !== 'string' || typeof entry.integrity !== 'string')\n return {\n ok: false,\n reason: `the registry's entry for ${id} does not name a GitHub release this app can pull`,\n next: 'open its page on https://cordisplugins.github.io for how to install it',\n }\n return {\n ok: true,\n hit: { source: `github:${repo[1]}/${repo[2]}@${entry.version}`, integrity: entry.integrity },\n }\n}\n","/**\n * Sharing a plugin between people: `pull(source)` turns a release someone published into a running plugin in this app. It fetches without running\n * anything, decides from the package's files (`pull-check.ts`), and hands a folder to `extensions`, which owns the install and its rollback.\n * Design: docs/plans/plugin-share.md.\n */\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { findSecrets } from '@acryldev/app-persistence'\nimport { digestFolder, type PluginFile, pluginFiles } from '@acryldev/blends-core'\nimport { type ExtensionInfo, NAME } from '@acryldev/extensions'\nimport type {} from '@acryldev/instance'\nimport { LOCK_FILE, writeLock } from '@acryldev/manifest/lock'\nimport {\n bumpVersion,\n firstRegistryPort,\n gitCli,\n githubCli,\n githubReleasesOverHttps,\n httpsDownload,\n InvalidPluginSourceError,\n NPM_REGISTRY,\n npmRegistryOverHttps,\n npmRegistryViaCli,\n type PluginSource,\n PluginStore,\n PullError,\n packFolder,\n parsePluginSource,\n pullPlugin,\n type RegistryPort,\n type ReleasePort,\n readTarball,\n sharePlugin,\n storeRootOf,\n} from '@acryldev/plugin-hub-core'\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport { type MergedTrees, mergeTrees, type Tree } from './merge-edits.ts'\nimport {\n ensureNative,\n type NativeAction,\n type NativePackage,\n type NativePlaces,\n type NativePorts,\n nativeFor,\n nativePorts,\n nativesOf,\n releaseNative,\n} from './native.ts'\nimport { npmWithLogin } from './npm-login.ts'\nimport { packagePlugin } from './package.ts'\nimport {\n npmPullLineOf,\n type PublishOptions,\n type PublishPlan,\n type PublishPorts,\n type PublishRefused,\n type PublishResult,\n pullLineOf,\n samePlan,\n} from './publish.ts'\nimport {\n missingServices,\n type PullRefused,\n pullRefusal,\n refuse,\n splitDigest,\n} from './pull-check.ts'\nimport { LIST_MAX_BYTES, parsePullList, pullListLocation } from './pull-list.ts'\nimport { type PulledRecord, pulledRecords, withPulledRecord } from './pulled-records.ts'\nimport { lookUpRegistry, REGISTRY_INDEX_URL } from './registry-source.ts'\n\nexport type {\n PublishOptions,\n PublishPlan,\n PublishPorts,\n PublishRefused,\n PublishResult,\n} from './publish.ts'\n\n/** One remembered plugin the app fetched again at its start because its folder was gone. */\nexport type RestoreOutcome =\n | { readonly name: string; readonly ok: true }\n | { readonly name: string; readonly ok: false; readonly reason: string; readonly next: string }\n\nexport interface PluginShareConfig {\n /** Where pulled plugins go; must be an extensions source. Defaults to `<project>/plugins`. */\n dir?: string\n /** Where a `github:` source reads releases. Defaults to GitHub over HTTPS. */\n releases?: ReleasePort\n /** Where a publish goes. Defaults to the person's own `gh` and `git`. */\n publish?: PublishPorts\n /** How an https address is read: a release `.tgz` and a list of sources. Defaults to HTTPS with the hub's size and time limits. */\n download?: (url: string) => Promise<Uint8Array>\n /** Where `registry:<id>` reads the plugin registry's index. Defaults to cordisplugins.github.io. */\n registryIndex?: string\n /** Where an `npm:` source reads packages. Defaults to the public registry over HTTPS, then the person's own npm (a private scope or registry). */\n npm?: RegistryPort\n /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */\n native?: NativePorts\n}\n\nexport type PullResult =\n | {\n readonly ok: true\n readonly name: string\n readonly version: string\n /** The sha512 of the release's tarball, as the registry lists it. */\n readonly integrity: string\n /** The sha256 of the plugin's content: the same on every OS. A source can name it (`@sha256:<digest>`). */\n readonly digest: string\n readonly action: 'installed' | 'updated' | 'unchanged'\n readonly state: string\n /** Whether the app's `blend.yaml` and lock now name this source, so a copy of the app can fetch it. A local file names nothing to fetch. */\n readonly remembered: boolean\n /** The files of an older pulled copy that kept the person's own changes when this release updated it in place. */\n readonly kept?: readonly string[]\n /** The native package the plugin brought for this computer (native.ts), and what installing it did. */\n readonly native?: {\n readonly package: string\n readonly version: string\n readonly size: number\n readonly action: NativeAction\n }\n }\n | PullRefused\n\n/** One source of a list and what pulling it did. */\nexport interface PullListEntry {\n /** Its line in the list. */\n readonly line: number\n readonly source: string\n readonly result: PullResult\n}\n\n/** A list pulled: every source with its own result (some may be refused while the others install), or the list itself refused. */\nexport type PullListResult =\n | { readonly ok: true; readonly from: string; readonly entries: readonly PullListEntry[] }\n | PullRefused\n\n/** One plugin installed while the app runs, as a person reads the list: what it is and, for one pulled, where it came from and who released it. */\n/** What extensions says about an installed plugin (its state, the services a pending one waits for, ...), and where a pulled one came from. */\nexport interface SharedPluginInfo extends ExtensionInfo {\n /** The source it was pulled from (`github:<owner>/<repo>@<version>` or an address); absent for one made in this app or pulled from a local file. */\n readonly pulledFrom?: string\n /** Who released it: the account of a `github:` source or of a release address on github.com. */\n readonly author?: string\n /** The version its `package.json` names (`version` is the installed content's short digest); absent without one. */\n readonly release?: string\n}\n\n/** What removing a plugin did with its folder in `plugins/`. */\nexport type RemovedFolder =\n /** It held the release as pulled, so nothing of anyone's is lost: the pull line brings it back. */\n | 'deleted'\n /** It is this app's own work, or a pulled plugin changed after the pull: it stays, and the app starts it again at its next start. */\n | 'kept'\n | 'none'\n\nexport type SharedRemoveResult =\n | {\n readonly ok: true\n readonly name: string\n readonly folder: RemovedFolder\n readonly note?: string\n }\n | { readonly ok: false; readonly name: string; readonly errors: readonly string[] }\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n pluginShare: PluginShare\n }\n}\n\n/** The account that released a source: the owner of a `github:<owner>/<repo>@<version>` source or of a release address on github.com. */\nconst authorOf = (source: string): string | undefined =>\n (/^github:([^/]+)\\//u.exec(source) ?? /^https:\\/\\/github\\.com\\/([^/]+)\\//u.exec(source))?.[1]\n\n/** The version a plugin folder's `package.json` names, when it names a plain one. */\nfunction releaseOf(folder: string): string | undefined {\n try {\n const version = (\n JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')) as { version?: unknown }\n ).version\n return typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]+)?$/u.test(version)\n ? version\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** The license a new public plugin is offered under; the plan shows it before the person says yes. */\nconst DEFAULT_LICENSE = 'MIT'\nconst LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u\n/** An npm scope: what follows `@`. */\nconst NPM_SCOPE = /^[a-z0-9][a-z0-9._~-]*$/u\n\nconst publishRefused = (reason: string, next: string): PublishRefused => ({\n ok: false,\n reason,\n next,\n})\n\nconst SOURCE_FORMS =\n 'github:<owner>/<repo>[@<version>], npm:<package>[@<version>], registry:<id> or a .tgz path or address'\n\n/** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */\nfunction readSource(\n input: string,\n root: string,\n): { readonly source: PluginSource; readonly digest?: string } {\n const { source, digest } = splitDigest(input.trim())\n const isLocalTarball = /\\.(?:tgz|tar\\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source)\n const parsed = parsePluginSource(isLocalTarball ? resolve(root, source) : source)\n if (\n parsed.kind !== 'github' &&\n parsed.kind !== 'npm' &&\n parsed.kind !== 'tarball-file' &&\n parsed.kind !== 'tarball-url'\n ) {\n const named = parsed.kind === 'name' ? 'a bare name' : parsed.kind\n throw new InvalidPluginSourceError(\n input,\n `${named} sources are not offered here; pull ${SOURCE_FORMS}`,\n )\n }\n return { source: parsed, ...(digest === undefined ? {} : { digest }) }\n}\n\n/** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */\nfunction recordedSource(source: PluginSource, version: string): string | undefined {\n if (source.kind === 'github') return `github:${source.owner}/${source.repo}@${version}`\n if (source.kind === 'npm') return `npm:${source.name.full}@${version}`\n return source.kind === 'tarball-url' ? source.url : undefined\n}\n\n/** What two releases of one plugin share in a recorded source: `github:<owner>/<repo>` or `npm:<package>`, lower case. */\nconst repoOf = (source: string): string | undefined => {\n const github = /^(github:[^/@]+\\/[^/@]+)@/u.exec(source)?.[1]\n const npm = /^(npm:(?:@[^/@]+\\/)?[^/@]+)@/u.exec(source)?.[1]\n return (github ?? npm)?.toLowerCase()\n}\n\n/** A package's folder in `plugins/`: the name after its scope (`@ana/clock` is `clock`). */\nconst folderOf = (packageName: string): string =>\n packageName.includes('/') ? packageName.slice(packageName.lastIndexOf('/') + 1) : packageName\n\nconst treeOf = (files: readonly PluginFile[]): Tree =>\n new Map(files.map((file) => [file.path, file.bytes]))\n\n/** Make a plugin folder hold exactly `to`, having held `from`: files only `from` had go, every file of `to` is written. */\nfunction applyTree(folder: string, from: Tree, to: Tree): void {\n for (const path of from.keys())\n if (!to.has(path)) rmSync(join(folder, ...path.split('/')), { force: true })\n for (const [path, bytes] of to) {\n const file = join(folder, ...path.split('/'))\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, bytes)\n }\n}\n\nconst reasonOf = (cause: unknown): string => {\n if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason\n return cause instanceof Error ? cause.message : String(cause)\n}\n\nexport class PluginShare extends Service {\n /** What was fetched again at this start. */\n readonly restored: Promise<readonly RestoreOutcome[]>\n private readonly dir: string\n private readonly releases: ReleasePort\n private readonly download: (url: string) => Promise<Uint8Array>\n private readonly registryIndex: string\n private readonly npmRegistry: RegistryPort\n private readonly ports: PublishPorts\n /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */\n private queue: Promise<unknown> = Promise.resolve()\n /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */\n private readonly live = new Map<string, string>()\n private readonly nativeWork: NativePorts\n /** The native package each installed plugin brought for this computer: what its removal takes away. */\n private readonly natives = new Map<string, NativePackage>()\n\n /**\n * 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\n * 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.\n */\n private readonly own: Context\n\n constructor(ctx: Context, config: PluginShareConfig) {\n super(ctx, 'pluginShare')\n this.own = ctx\n this.dir = resolve(config.dir ?? join(ctx.appInstance.root, 'plugins'))\n this.releases = config.releases ?? githubReleasesOverHttps()\n this.download = config.download ?? httpsDownload()\n this.registryIndex = config.registryIndex ?? REGISTRY_INDEX_URL\n this.npmRegistry = config.npm ?? firstRegistryPort(npmRegistryOverHttps(), npmRegistryViaCli())\n this.nativeWork = config.native ?? nativePorts()\n this.ports = config.publish ?? { host: githubCli(), git: gitCli() }\n // Removing a plugin removes its record. Listened to here, not asked of each caller: every way of removing it goes through extensions.\n ctx.on('extensions/changed', (name, change) => {\n if (change !== 'removed') return\n this.live.delete(name)\n this.remember(name, undefined)\n this.dropNative(name)\n })\n // Not awaited by the app's start: a person offline still gets their app, and the warning says what is missing.\n this.restored = this.inTurn(() => this.restore())\n }\n\n /** 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. */\n pull(source: string): Promise<PullResult> {\n return this.inTurn(() => this.pullNow(source))\n }\n\n /**\n * 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\n * 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.\n * A list that cannot be read, or has a line that is not one source, pulls nothing.\n */\n async pullList(from: string): Promise<PullListResult> {\n const text = await this.readList(from)\n if (typeof text !== 'string') return text\n const { sources, problems } = parsePullList(text)\n if (problems.length > 0)\n return refuse('list', `${from}: ${problems.join('; ')}`, 'fix the list; nothing was pulled')\n if (sources.length === 0)\n return refuse(\n 'list',\n `${from} names no plugin`,\n 'write one source per line, e.g. github:someone/pomodoro@0.1.0',\n )\n const entries: PullListEntry[] = []\n for (const { line, source } of sources)\n entries.push({ line, source, result: await this.pull(source) })\n return { ok: true, from, entries }\n }\n\n /** The text of a list, or why it cannot be read. */\n private async readList(from: string): Promise<string | PullRefused> {\n const where = pullListLocation(from)\n if (where === undefined)\n return refuse(\n 'list',\n `\"${from}\" is not a list`,\n 'name a file in the app (e.g. group.txt) or an https address of one',\n )\n try {\n let bytes: Uint8Array\n if (where.kind === 'address') bytes = await this.download(where.url)\n else {\n const path = resolve(this.own.appInstance.root, where.path)\n if (!existsSync(path) || !statSync(path).isFile())\n return refuse(\n 'list',\n `there is no file ${where.path}`,\n 'name a file in the app, or an https address',\n )\n bytes = readFileSync(path)\n }\n if (bytes.length > LIST_MAX_BYTES)\n return refuse(\n 'list',\n `${from} is larger than ${String(LIST_MAX_BYTES)} bytes, so it is not a list of plugins`,\n 'name the list itself',\n )\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } catch (cause) {\n return refuse(\n 'list',\n `${from} could not be read: ${reasonOf(cause)}`,\n 'check the address; nothing was pulled',\n )\n }\n }\n\n /**\n * 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\n * 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.\n */\n pulledDigest(name: string): string | undefined {\n return this.live.get(name) ?? this.recorded(name)?.digest\n }\n\n /** The plugins installed while the app runs, each pulled one with its source and author. */\n list(): SharedPluginInfo[] {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n const records = existsSync(file) ? pulledRecords(readFileSync(file, 'utf8')) : {}\n return this.own.extensions.list().map((info) => {\n const record = records[info.name]\n const author = record === undefined ? undefined : authorOf(record.source)\n const release = releaseOf(join(this.dir, info.name))\n return {\n ...info,\n ...(record === undefined ? {} : { pulledFrom: record.source }),\n ...(author === undefined ? {} : { author }),\n ...(release === undefined ? {} : { release }),\n }\n })\n }\n\n /**\n * 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\n * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.\n */\n remove(name: string): Promise<SharedRemoveResult> {\n return this.inTurn(() => this.removeNow(name))\n }\n\n private inTurn<T>(step: () => Promise<T>): Promise<T> {\n const run = this.queue.then(step)\n this.queue = run.catch(() => undefined)\n return run\n }\n\n /**\n * 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.\n */\n planPublish(name: string, options: PublishOptions = {}): Promise<PublishPlan | PublishRefused> {\n return this.inTurn(() => this.planNow(name, options))\n }\n\n /**\n * 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\n * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.\n */\n publish(\n name: string,\n confirmed: PublishPlan,\n options: PublishOptions = {},\n ): Promise<PublishResult> {\n return this.inTurn(async () => {\n const plan = await this.planNow(name, options)\n if ('ok' in plan) return plan\n if (!samePlan(plan, confirmed)) {\n return publishRefused(\n `this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`,\n 'look at the new plan and say yes again',\n )\n }\n if (plan.target === 'npm') return this.publishNpm(name, plan)\n const { home } = this.own.appInstance\n try {\n const shared = await sharePlugin(\n join(this.packages, name),\n {\n owner: plan.owner,\n repo: plan.repo,\n visibility: plan.visibility,\n kind: 'source-plugin',\n },\n { ...this.ports, store: new PluginStore(storeRootOf(home)) },\n )\n if (shared.status === 'refused')\n return publishRefused(shared.reason, 'fix what it names; nothing was sent')\n return {\n ok: true,\n url: shared.url,\n releaseUrl: shared.releaseUrl,\n version: shared.version,\n integrity: shared.integrity,\n digest: plan.digest,\n pullLine: plan.pullLine,\n }\n } catch (cause) {\n return publishRefused(\n reasonOf(cause),\n 'look at the repository; part of this publish may have been sent',\n )\n }\n })\n }\n\n /** 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. */\n private remember(name: string, record: PulledRecord | undefined): boolean {\n const { root } = this.own.appInstance\n const file = join(root, 'blend.yaml')\n if (!existsSync(file)) return false\n const text = readFileSync(file, 'utf8')\n const next = withPulledRecord(text, name, record)\n if (next !== text) {\n writeFileSync(`${file}.tmp`, next)\n renameSync(`${file}.tmp`, file)\n if (existsSync(join(root, LOCK_FILE))) writeLock(root)\n }\n return record === undefined || pulledRecords(next)[name] !== undefined\n }\n\n private async removeNow(name: string): Promise<SharedRemoveResult> {\n // Read before the removal, which forgets both the record and the live digest.\n const pulled = this.pulledDigest(name)\n const removed = await this.own.extensions.remove(name)\n if (!removed.ok) return removed\n const folder = join(this.dir, name)\n if (!existsSync(folder)) return { ok: true, name, folder: 'none' }\n if (pulled !== undefined && digestFolder(folder) === pulled) {\n rmSync(folder, { recursive: true, force: true })\n return { ok: true, name, folder: 'deleted' }\n }\n const why = pulled === undefined ? \"is this app's own plugin\" : 'was changed after the pull'\n return {\n ok: true,\n name,\n folder: 'kept',\n note: `plugins/${name} ${why}, so it stays and the app starts it again at its next start; delete the folder to drop it for good`,\n }\n }\n\n /** What `blend.yaml` remembers about one pulled plugin now. */\n private recorded(name: string): PulledRecord | undefined {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n return existsSync(file) ? pulledRecords(readFileSync(file, 'utf8'))[name] : undefined\n }\n\n /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */\n private get places(): NativePlaces {\n return { root: this.own.appInstance.root, home: this.own.appInstance.home }\n }\n\n /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */\n private keepNative(\n name: string,\n native: NativePackage | undefined,\n before: NativePackage | undefined,\n action: NativeAction | undefined,\n ): Pick<Extract<PullResult, { ok: true }>, 'native'> {\n if (\n before !== undefined &&\n (native === undefined ||\n before.version !== native.version ||\n before.package !== native.package)\n )\n this.dropNative(name)\n if (native === undefined || action === undefined) return {}\n this.natives.set(name, native)\n return {\n native: { package: native.package, version: native.version, size: native.size, action },\n }\n }\n\n /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */\n private dropNative(name: string): void {\n const native = this.natives.get(name)\n if (native === undefined) return\n this.natives.delete(name)\n const shared = [...this.natives.values()].some(\n (other) => other.package === native.package && other.version === native.version,\n )\n if (!shared) releaseNative(native, this.places)\n }\n\n /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */\n private async relinkNative(name: string): Promise<void> {\n let manifest: Record<string, unknown>\n try {\n manifest = JSON.parse(readFileSync(join(this.dir, name, 'package.json'), 'utf8')) as Record<\n string,\n unknown\n >\n } catch {\n return\n }\n const declared = nativesOf(manifest)\n const native = 'natives' in declared ? nativeFor(declared.natives) : undefined\n if (native === undefined) return\n try {\n await ensureNative(native, this.places, this.nativeWork)\n this.natives.set(name, native)\n } catch (cause) {\n console.warn(\n `plugin-share: ${name}'s ${native.package} was not installed again: ${reasonOf(cause)}`,\n )\n }\n }\n\n private async restore(): Promise<readonly RestoreOutcome[]> {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n if (!existsSync(file)) return []\n const outcomes: RestoreOutcome[] = []\n for (const [name, record] of Object.entries(pulledRecords(readFileSync(file, 'utf8')))) {\n if (existsSync(join(this.dir, name))) {\n await this.relinkNative(name)\n continue\n }\n const result = await this.pullNow(\n `${record.source}@sha256:${record.digest}`,\n record.integrity,\n )\n outcomes.push(\n result.ok\n ? { name, ok: true }\n : { name, ok: false, reason: result.reason, next: result.next },\n )\n if (!result.ok)\n console.warn(\n `plugin-share: ${name} was not fetched again: ${result.reason}. ${result.next}.`,\n )\n }\n return outcomes\n }\n\n private get packages(): string {\n return join(this.own.appInstance.home, 'plugin-packages')\n }\n\n private async planNow(\n name: string,\n options: PublishOptions,\n ): Promise<PublishPlan | PublishRefused> {\n const source = join(this.dir, name)\n if (!NAME.test(name) || !existsSync(source))\n return publishRefused(\n `this app has no plugin \"${name}\" in plugins/`,\n 'name a folder of plugins/',\n )\n if (options.to === 'npm') return this.planNpm(name, source, options)\n try {\n const { host } = this.ports\n const owner = options.owner ?? host.login()\n const repo = name\n const description = `The ${name} Cordis plugin.`\n const license = options.license ?? DEFAULT_LICENSE\n if (!LICENSE_ID.test(license))\n return publishRefused(\n `\"${license}\" is not a license id`,\n 'write one such as MIT or Apache-2.0',\n )\n const release = { owner, repo, license }\n const existing = host.repository(owner, repo)\n let packaged = await packagePlugin(source, this.packages, name, description, { release })\n const released =\n existing !== undefined && host.releaseExists(owner, repo, `v${packaged.version}`)\n ? packaged.version\n : undefined\n if (released !== undefined)\n packaged = await packagePlugin(source, this.packages, name, description, {\n release,\n version: bumpVersion(released, 'patch'),\n })\n const secrets = findSecrets(\n readTarball(packFolder(packaged.dir).tarball).map((file) => ({\n path: file.path,\n text: Buffer.from(file.content).toString('utf8'),\n })),\n )\n if (secrets.length > 0) {\n return publishRefused(\n `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,\n \"take them out of the plugin and read them from the app's settings\",\n )\n }\n return {\n owner,\n repo,\n version: packaged.version,\n visibility: 'public',\n license,\n createsRepository: existing === undefined,\n ...(released === undefined ? {} : { released }),\n files: packaged.files,\n integrity: packaged.integrity,\n digest: packaged.digest,\n pullLine: pullLineOf(owner, repo, packaged.version, packaged.digest),\n }\n } catch (cause) {\n return publishRefused(reasonOf(cause), 'fix it, or sign in with gh; nothing was sent')\n }\n }\n\n /**\n * What publishing to npm would do, read without sending anything: the account is the person's own npm login (`npm whoami`), the package is\n * `@<scope>/<name>` (the scope defaults to that account), and a version npm already has makes the plan name the next patch, as a GitHub release does.\n */\n private async planNpm(\n name: string,\n source: string,\n options: PublishOptions,\n ): Promise<PublishPlan | PublishRefused> {\n const npm = this.ports.npm ?? npmWithLogin()\n const registry = options.registry ?? NPM_REGISTRY\n try {\n const account = npm.login(registry)\n const scope = (options.scope ?? account).replace(/^@/u, '').toLowerCase()\n if (!NPM_SCOPE.test(scope))\n return publishRefused(\n `\"${scope}\" is not an npm scope`,\n 'write letters, digits and dashes, for example --scope acme',\n )\n const license = options.license ?? DEFAULT_LICENSE\n if (!LICENSE_ID.test(license))\n return publishRefused(\n `\"${license}\" is not a license id`,\n 'write one such as MIT or Apache-2.0',\n )\n const packageName = `@${scope}/${name}`\n const pack = (version?: string) => this.packNpm(source, name, packageName, license, version)\n let packaged = await pack()\n const released = npm.hasVersion(packageName, packaged.version, registry)\n ? packaged.version\n : undefined\n if (released !== undefined) packaged = await pack(bumpVersion(released, 'patch'))\n const secrets = findSecrets(\n readTarball(packFolder(packaged.dir).tarball).map((file) => ({\n path: file.path,\n text: Buffer.from(file.content).toString('utf8'),\n })),\n )\n if (secrets.length > 0) {\n return publishRefused(\n `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,\n \"take them out of the plugin and read them from the app's settings\",\n )\n }\n return {\n target: 'npm',\n package: packageName,\n registry,\n owner: scope,\n repo: name,\n version: packaged.version,\n visibility: 'public',\n license,\n createsRepository: false,\n ...(released === undefined ? {} : { released }),\n files: packaged.files,\n integrity: packaged.integrity,\n digest: packaged.digest,\n pullLine: npmPullLineOf(packageName, packaged.version, packaged.digest),\n }\n } catch (cause) {\n return publishRefused(\n reasonOf(cause),\n 'fix it, or sign in with: npm login (--registry <address> for another registry); nothing was sent',\n )\n }\n }\n\n /** The plugin as the npm package `packageName`: a package of its own folder, the same bytes whenever it is made again for the same version. */\n private packNpm(\n source: string,\n name: string,\n packageName: string,\n license: string,\n version?: string,\n ) {\n return packagePlugin(source, this.packages, name, `The ${name} Cordis plugin.`, {\n release: { license },\n packageName,\n ...(version === undefined ? {} : { version }),\n })\n }\n\n /** The confirmed npm plan, published with the person's own npm: the package is made again, and only the bytes that were planned are sent. */\n private async publishNpm(name: string, plan: PublishPlan): Promise<PublishResult> {\n const registry = plan.registry ?? NPM_REGISTRY\n const packageName = plan.package ?? `@${plan.owner}/${plan.repo}`\n try {\n const packed = await this.packNpm(\n join(this.dir, name),\n name,\n packageName,\n plan.license,\n plan.version,\n )\n if (packed.integrity !== plan.integrity)\n return publishRefused(\n `the package made now is not the one that was planned (${packageName} v${plan.version}); nothing was sent`,\n 'look at the new plan and say yes again',\n )\n ;(this.ports.npm ?? npmWithLogin()).publish(packed.tarball, registry, 'public')\n const url =\n registry === NPM_REGISTRY\n ? `https://www.npmjs.com/package/${packageName}`\n : `${registry.replace(/\\/$/u, '')}/${packageName}`\n return {\n ok: true,\n url,\n releaseUrl: url,\n version: packed.version,\n integrity: packed.integrity,\n digest: plan.digest,\n pullLine: plan.pullLine,\n }\n } catch (cause) {\n return publishRefused(\n reasonOf(cause),\n 'look at the registry; part of this publish may have been sent',\n )\n }\n }\n\n /** A `registry:<id>` source turned into the release it lists, with the integrity the registry lists for it; any other source as it is. */\n private async resolveRegistry(\n input: string,\n expectIntegrity?: string,\n ): Promise<{ readonly input: string; readonly expectIntegrity?: string } | PullRefused> {\n const text = input.trim()\n if (!/^registry:/iu.test(text))\n return { input, ...(expectIntegrity === undefined ? {} : { expectIntegrity }) }\n // A digest written after the id (`registry:<id>@sha256:<digest>`) is not part of the id: it travels on to the release's source.\n let named: ReturnType<typeof splitDigest>\n try {\n named = splitDigest(text)\n } catch (cause) {\n return refuse(\n 'source',\n reasonOf(cause),\n 'write the 64 hex digits the plugin page shows after @sha256:',\n )\n }\n let index: string\n try {\n index = Buffer.from(await this.download(this.registryIndex)).toString('utf8')\n } catch (cause) {\n return refuse(\n 'fetch',\n `the registry could not be read: ${reasonOf(cause)}`,\n 'check the internet connection and pull again, or pull github:<owner>/<repo>',\n )\n }\n const found = lookUpRegistry(index, named.source.slice('registry:'.length))\n if (!found.ok) return refuse('source', found.reason, found.next)\n return {\n input:\n named.digest === undefined\n ? found.hit.source\n : `${found.hit.source}@sha256:${named.digest}`,\n expectIntegrity: expectIntegrity ?? found.hit.integrity,\n }\n }\n\n private async pullNow(input: string, expectIntegrity?: string): Promise<PullResult> {\n const { home, root } = this.own.appInstance\n const resolved = await this.resolveRegistry(input, expectIntegrity)\n if ('refusal' in resolved) return resolved\n input = resolved.input\n expectIntegrity = resolved.expectIntegrity\n let read: ReturnType<typeof readSource>\n try {\n read = readSource(input, root)\n } catch (cause) {\n return refuse(\n 'source',\n reasonOf(cause),\n `write ${SOURCE_FORMS}, with @sha256:<digest> at the end to name the content`,\n )\n }\n mkdirSync(home, { recursive: true })\n const scratch = mkdtempSync(join(home, 'plugin-pull-'))\n try {\n let pulled: Awaited<ReturnType<typeof pullPlugin>>\n try {\n pulled = await pullPlugin(\n read.source,\n {\n store: new PluginStore(scratch),\n releases: this.releases,\n registry: this.npmRegistry,\n download: this.download,\n },\n expectIntegrity === undefined ? {} : { expectIntegrity },\n )\n } catch (cause) {\n return refuse(\n 'fetch',\n reasonOf(cause),\n 'check the source with the person who released it; nothing was installed',\n )\n }\n // An npm package is `@scope/name` and lives in the folder `name`; a package from any other source must already be named for a folder.\n const folderIn = (packageName: string): string =>\n read.source.kind === 'npm' ? folderOf(packageName) : packageName\n const files: PluginFile[] = readTarball(readFileSync(pulled.stored.path)).map(\n ({ path, content }) => ({ path, bytes: content, kind: 'file' }),\n )\n const refused = pullRefusal(pulled.manifest, files, {\n digest: read.digest,\n nameFits: (name) => NAME.test(folderIn(name)),\n hasService: (service) => this.own.get(service as never) !== undefined,\n })\n if (refused !== undefined) return refused\n const declared = nativesOf(pulled.manifest)\n return await this.install(\n folderIn(pulled.stored.name),\n pulled.stored.version,\n pulled.stored.integrity,\n files,\n recordedSource(read.source, pulled.stored.version),\n 'natives' in declared ? nativeFor(declared.natives) : undefined,\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n }\n\n /**\n * What the folder holds once a newer release of its pulled plugin comes in, the person's own changes kept: the release they pulled is the base of a\n * three-way merge (fetched again from where it came from, checked against its recorded integrity, unless the folder is untouched and is the base).\n * Refused, and nothing written, when the release and the person changed the same lines.\n */\n private async planUpdate(\n name: string,\n before: PulledRecord,\n held: string,\n release: readonly PluginFile[],\n target: string,\n ): Promise<{ readonly mine: Tree; readonly merged: MergedTrees } | PullRefused> {\n const mine = treeOf(pluginFiles(target))\n let base = mine\n if (held !== before.digest) {\n const scratch = mkdtempSync(join(this.own.appInstance.home, 'plugin-base-'))\n try {\n const pulled = await pullPlugin(\n readSource(before.source, this.own.appInstance.root).source,\n {\n store: new PluginStore(scratch),\n releases: this.releases,\n registry: this.npmRegistry,\n download: this.download,\n },\n { expectIntegrity: before.integrity },\n )\n base = treeOf(\n readTarball(readFileSync(pulled.stored.path)).map(({ path, content }) => ({\n path,\n bytes: content,\n kind: 'file' as const,\n })),\n )\n } catch (cause) {\n return refuse(\n 'folder-exists',\n `plugins/${name} has changes of your own, and the release it was pulled from could not be fetched to keep them: ${reasonOf(cause)}`,\n `check the internet connection and pull again, or move plugins/${name} out of plugins/ and pull again`,\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n }\n const merged = mergeTrees(base, mine, treeOf(release))\n if (merged.conflicts.length > 0)\n return refuse(\n 'folder-exists',\n `plugins/${name} has changes of your own to ${merged.conflicts.join(', ')}, and the new release changes ${merged.conflicts.length === 1 ? 'it' : 'them'} too`,\n `plugins/${name} is untouched: move it out of plugins/ and pull again, then bring your changes back by hand`,\n )\n return { mine, merged }\n }\n\n /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */\n private async install(\n name: string,\n version: string,\n integrity: string,\n files: readonly PluginFile[],\n source: string | undefined,\n native: NativePackage | undefined,\n ): Promise<PullResult> {\n const target = join(this.dir, name)\n const incoming = join(this.dir, `.pulling-${name}`)\n rmSync(incoming, { recursive: true, force: true })\n try {\n for (const file of files) {\n const path = join(incoming, ...file.path.split('/'))\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.bytes)\n }\n const digest = digestFolder(incoming)\n // The folder may be there already: the same bytes are already pulled, anything else is someone's work.\n const wrote = !existsSync(target)\n const before = this.recorded(name)\n const held = wrote ? undefined : digestFolder(target)\n let update: { readonly mine: Tree; readonly merged: MergedTrees } | undefined\n if (held !== undefined && held !== digest) {\n // A newer release of the plugin pulled here updates it in place, the person's own changes kept; anything else in the folder is someone's work.\n const sameRepo =\n before !== undefined &&\n source !== undefined &&\n repoOf(before.source) !== undefined &&\n repoOf(before.source) === repoOf(source)\n if (before !== undefined && sameRepo && before.digest !== digest) {\n const planned = await this.planUpdate(name, before, held, files, target)\n if ('refusal' in planned) return planned\n update = planned\n } else {\n const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`\n // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.\n const next =\n before !== undefined && held === before.digest\n ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`\n : `keep it, or move plugins/${name} out of plugins/ and pull again`\n return refuse(\n 'folder-exists',\n `plugins/${name} holds a different copy of this plugin, ${holder}`,\n next,\n )\n }\n }\n const liveBefore = this.live.get(name)\n this.live.set(name, digest)\n if (wrote) renameSync(incoming, target)\n else if (update !== undefined) applyTree(target, update.mine, update.merged.files)\n // Remembered as the folder appears, before it is installed, so whoever sees the folder can tell it is these released bytes (the frame then does\n // not load the app again for a plugin the app installs live); a pull that does not end running puts back what was remembered before.\n const remembered = source !== undefined && this.remember(name, { source, integrity, digest })\n // Installed before the plugin starts, so the plugin finds it; an install that does not end running takes back only what it added.\n let nativeAction: NativeAction | undefined\n const nativeBefore = this.natives.get(name)\n const undo = () => {\n if (native !== undefined && (nativeAction === 'downloaded' || nativeAction === 'linked'))\n releaseNative(native, this.places, nativeAction === 'linked')\n if (wrote) rmSync(target, { recursive: true, force: true })\n else if (update !== undefined) applyTree(target, update.merged.files, update.mine)\n if (remembered) this.remember(name, before)\n if (liveBefore === undefined) this.live.delete(name)\n else this.live.set(name, liveBefore)\n }\n if (native !== undefined) {\n try {\n nativeAction = await ensureNative(native, this.places, this.nativeWork)\n } catch (cause) {\n undo()\n return refuse(\n 'native',\n `${native.package}@${native.version} (${Math.round(native.size / 1e6)} MB) could not be installed: ${reasonOf(cause)}`,\n 'check the internet connection and pull again; the plugin was not installed',\n )\n }\n }\n let result: Awaited<ReturnType<Context['extensions']['install']>>\n try {\n result = await this.own.extensions.install(target)\n } catch (cause) {\n undo()\n return refuse(\n 'install',\n reasonOf(cause),\n 'this app does not install plugins while it runs like this',\n )\n }\n if (!result.ok) {\n undo()\n return refuse('install', result.errors.join('; '), result.next)\n }\n if (result.state === 'pending') {\n await this.own.extensions.remove(name)\n undo()\n return missingServices(result.missing)\n }\n return {\n ok: true,\n name,\n version,\n integrity,\n digest,\n action: result.action,\n state: result.state,\n remembered,\n ...(update === undefined || update.merged.kept.length === 0\n ? {}\n : { kept: update.merged.kept }),\n ...this.keepNative(name, native, nativeBefore, nativeAction),\n }\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n }\n}\n\nexport const pluginShare = {\n name: 'plugin-share',\n inject: ['extensions', 'appInstance'],\n apply(ctx: Context, config: PluginShareConfig) {\n // A pull runs a stranger's code and a publish leaves the machine: development only. The templates' src/app.ts leaves the row out in production; an\n // app whose src/app.ts is older than that line is covered here.\n if (process.env.NODE_ENV === 'production') return\n new PluginShare(ctx, config ?? {})\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ,GAA2B,MACvC,MAAM,KAAA,KAAa,MAAM,KAAA,IAAY,MAAM,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC;;AAGxE,MAAa,gBAA2B,MAAM,MAAM,WAAW;CAC7D,IAAI;EAAC;EAAM;EAAM;CAAM,CAAC,CAAC,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,OAAO,KAAA;CACpE,MAAM,MAAM,YAAY,KAAK,OAAO,GAAG,eAAe,CAAC;CACvD,IAAI;EACF,MAAM,CAAC,GAAG,GAAG,KAAK;GAAC;GAAQ;GAAQ;EAAQ,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,IAAI,CAAC;EAK1E,cAAc,GAAG,IAAI;EACrB,cAAc,GAAG,IAAI;EACrB,cAAc,GAAG,MAAM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,OAAO,WAAW,OAAO,OAAO,KAAK,IAAI,GAAG,OAAO,IAAI;GAChE;GACA,IAAI,OAAO,UAAU,WAAW;IAC9B,MAAM,KAAK,IAAI,WAAW,OAAO,IAAI;IACrC,KAAK;IACL,OAAO,gBAAgB,OAAO,OAAO;GACvC;GACA,OAAO;IACL,IAAI;IACJ;IACA;IACA;IACA;IACA,QAAQ,OAAO;IACf,OAAO,OAAO;IACd;IACA,GAAI,WAAW,KAAA,KAAa,OAAO,OAAO,KAAK,WAAW,IACtD,CAAC,IACD,EAAE,MAAM,OAAO,OAAO,KAAK;IAC/B,GAAG,KAAK,WAAW,MAAM,QAAQ,cAAc,YAAY;GAC7D;EACF,UAAU;GACR,OAAO,UAAU;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EACnD;CACF;AACF;AAEA,MAAa,cAAc;CACzB,MAAM;CACN,QAAQ,CAAC,cAAc,aAAa;CACpC,MAAM,KAAc,QAA2B;EAG7C,IAAI,QAAQ,IAAI,aAAa,cAAc;EAC3C,IAAI,YAAY,KAAK,UAAU,CAAC,CAAC;CACnC;AACF"}
|
package/lib/package.js
CHANGED
|
@@ -15,10 +15,10 @@ function packageManifest(name, description, version = "0.1.0", release) {
|
|
|
15
15
|
description,
|
|
16
16
|
...release === void 0 ? {} : {
|
|
17
17
|
license: release.license,
|
|
18
|
-
repository: {
|
|
18
|
+
...release.owner === void 0 || release.repo === void 0 ? {} : { repository: {
|
|
19
19
|
type: "git",
|
|
20
20
|
url: `git+https://github.com/${release.owner}/${release.repo}.git`
|
|
21
|
-
}
|
|
21
|
+
} }
|
|
22
22
|
},
|
|
23
23
|
type: "module",
|
|
24
24
|
exports: {
|
|
@@ -100,7 +100,7 @@ async function packagePlugin(source, packages, name, description, options = {})
|
|
|
100
100
|
filter: (path) => !path.includes("node_modules")
|
|
101
101
|
});
|
|
102
102
|
try {
|
|
103
|
-
writeFileSync(join(target, "package.json"), `${JSON.stringify(packageManifest(name, description, version, options.release), null, 2)}\n`);
|
|
103
|
+
writeFileSync(join(target, "package.json"), `${JSON.stringify(packageManifest(options.packageName ?? name, description, version, options.release), null, 2)}\n`);
|
|
104
104
|
if (!existsSync(join(target, "README.md"))) writeFileSync(join(target, "README.md"), `# ${name}\n\n${description}\n\nA Cordis plugin. Once it is released, pull it into an ACRYLBLENDS app while that app runs (\`npm run dev\`): \`npm run acryl -- plugin pull github:<owner>/<repo>\`.\n`);
|
|
105
105
|
withLineFeeds(target);
|
|
106
106
|
const issues = portabilityIssues(pluginFiles(target));
|
package/lib/package.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../package.ts"],"sourcesContent":["/**\n * Turning a plugin folder into what other people's apps can pull: a package folder and its release tarball, with the same bytes on every OS. The\n * hub owns the tarball and the contract, blends-core what \"portable\" and \"digest\" mean; this module only decides what goes in.\n */\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { extname, join } from 'node:path'\nimport { digestFiles, pluginFiles, portabilityIssues } from '@acryldev/blends-core'\nimport { packFolder, readTarball, syncServiceContract } from '@acryldev/plugin-hub-core'\n\n/** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */\nexport function packageManifest(\n name: string,\n description: string,\n version = '0.1.0',\n release?: PackageRelease,\n): Record<string, unknown> {\n return {\n name,\n version,\n description,\n ...(release === undefined\n ? {}\n : {\n license: release.license,\n repository: {\n
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../package.ts"],"sourcesContent":["/**\n * Turning a plugin folder into what other people's apps can pull: a package folder and its release tarball, with the same bytes on every OS. The\n * hub owns the tarball and the contract, blends-core what \"portable\" and \"digest\" mean; this module only decides what goes in.\n */\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { extname, join } from 'node:path'\nimport { digestFiles, pluginFiles, portabilityIssues } from '@acryldev/blends-core'\nimport { packFolder, readTarball, syncServiceContract } from '@acryldev/plugin-hub-core'\n\n/** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */\nexport function packageManifest(\n name: string,\n description: string,\n version = '0.1.0',\n release?: PackageRelease,\n): Record<string, unknown> {\n return {\n name,\n version,\n description,\n ...(release === undefined\n ? {}\n : {\n license: release.license,\n // An npm package has no repository of its own to name.\n ...(release.owner === undefined || release.repo === undefined\n ? {}\n : {\n repository: {\n type: 'git',\n url: `git+https://github.com/${release.owner}/${release.repo}.git`,\n },\n }),\n }),\n type: 'module',\n exports: { '.': './index.ts', './package.json': './package.json' },\n // No `files` list: a plugin's plugin.json, data and .js files go with it, and the packer's own skips (node_modules, .git) apply.\n // ACRYL measured it: a host package listed under dependencies brings a second copy of the framework, and its services stop\n // matching after a restart. A peer names the version and installs nothing.\n peerDependencies: { '@deepseek-ai/cordis': '4.0.4' },\n keywords: ['cordis', 'cordis-plugin', 'acrylblends'],\n }\n}\n\n/** Where a package is going to be released: written in now, so what is planned is byte for byte what is released. */\nexport interface PackageRelease {\n /** The GitHub repository the package is released from; absent for npm. */\n readonly owner?: string\n readonly repo?: string\n readonly license: string\n}\n\nexport interface PackageOptions {\n /** This version, instead of the one already packaged. */\n readonly version?: string\n readonly release?: PackageRelease\n /** The name in the package's `package.json` when it is not the plugin's folder name (npm: `@scope/name`). */\n readonly packageName?: string\n}\n\nexport interface PackagedPlugin {\n readonly dir: string\n readonly version: string\n readonly files: readonly string[]\n /** The release file, next to the package folder. */\n readonly tarball: string\n /** The tarball's sha512, as the registry lists it. */\n readonly integrity: string\n /** The sha256 of the plugin's content, which a source can name (`@sha256:<digest>`). */\n readonly digest: string\n}\n\n/** Text whose line endings an editor or git on Windows may change: LF in the package, so those endings are not part of the plugin's identity. */\nconst TEXT = new Set([\n '.ts',\n '.mts',\n '.cts',\n '.tsx',\n '.js',\n '.mjs',\n '.cjs',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.css',\n '.html',\n '.yml',\n '.yaml',\n '.svg',\n])\n\nfunction withLineFeeds(dir: string): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) withLineFeeds(path)\n else if (entry.isFile() && TEXT.has(extname(entry.name).toLowerCase())) {\n const text = readFileSync(path, 'utf8')\n if (text.includes('\\r\\n')) writeFileSync(path, text.replaceAll('\\r\\n', '\\n'))\n }\n }\n}\n\n/** What the hub's share would otherwise add on the way out, changing the bytes after they were planned. */\nfunction markPublic(target: string): void {\n const file = join(target, 'package.json')\n const manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>\n writeFileSync(\n file,\n `${JSON.stringify({ ...manifest, acryl: { ...(manifest.acryl as object), visibility: 'public' } }, null, 2)}\\n`,\n )\n}\n\nfunction versionIn(target: string): string | undefined {\n try {\n const { version } = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')) as {\n version?: unknown\n }\n return typeof version === 'string' ? version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Package the plugin in `source` as `<packages>/<name>/` and `<packages>/<name>-<version>.tgz`. The person's folder is not touched. A version already\n * packaged stays: a release is made once, and a person bumps it deliberately.\n * @throws when the plugin would not work on every OS or its contract cannot be read; no package is left.\n */\nexport async function packagePlugin(\n source: string,\n packages: string,\n name: string,\n description: string,\n options: PackageOptions = {},\n): Promise<PackagedPlugin> {\n const target = join(packages, name)\n const version = options.version ?? versionIn(target)\n rmSync(target, { recursive: true, force: true })\n mkdirSync(packages, { recursive: true })\n cpSync(source, target, { recursive: true, filter: (path) => !path.includes('node_modules') })\n try {\n writeFileSync(\n join(target, 'package.json'),\n `${JSON.stringify(packageManifest(options.packageName ?? name, description, version, options.release), null, 2)}\\n`,\n )\n if (!existsSync(join(target, 'README.md'))) {\n writeFileSync(\n join(target, 'README.md'),\n `# ${name}\\n\\n${description}\\n\\nA Cordis plugin. Once it is released, pull it into an ACRYLBLENDS app while that app runs (\\`npm run dev\\`): \\`npm run acryl -- plugin pull github:<owner>/<repo>\\`.\\n`,\n )\n }\n withLineFeeds(target)\n const issues = portabilityIssues(pluginFiles(target))\n if (issues.length > 0)\n throw new Error(\n `it would not work on every OS: ${issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; ')}`,\n )\n // The contract other people's apps and the registry read: what the plugin needs and provides, from its code.\n const contract = await syncServiceContract(target)\n if (!contract.ok)\n throw new Error(`its service contract cannot be read: ${contract.errors.join('; ')}`)\n if (options.release !== undefined) markPublic(target)\n const packed = packFolder(target)\n const tarball = join(packages, packed.fileName)\n writeFileSync(tarball, packed.tarball)\n const digest = digestFiles(\n readTarball(packed.tarball).map(({ path, content }) => ({\n path,\n bytes: content,\n kind: 'file' as const,\n })),\n )\n return {\n dir: target,\n version: packed.version,\n files: packed.files,\n tarball,\n integrity: packed.integrity,\n digest,\n }\n } catch (cause) {\n rmSync(target, { recursive: true, force: true })\n throw cause\n }\n}\n"],"mappings":";;;;;;;;;;AAkBA,SAAgB,gBACd,MACA,aACA,UAAU,SACV,SACyB;CACzB,OAAO;EACL;EACA;EACA;EACA,GAAI,YAAY,KAAA,IACZ,CAAC,IACD;GACE,SAAS,QAAQ;GAEjB,GAAI,QAAQ,UAAU,KAAA,KAAa,QAAQ,SAAS,KAAA,IAChD,CAAC,IACD,EACE,YAAY;IACV,MAAM;IACN,KAAK,0BAA0B,QAAQ,MAAM,GAAG,QAAQ,KAAK;GAC/D,EACF;EACN;EACJ,MAAM;EACN,SAAS;GAAE,KAAK;GAAc,kBAAkB;EAAiB;EAIjE,kBAAkB,EAAE,uBAAuB,QAAQ;EACnD,UAAU;GAAC;GAAU;GAAiB;EAAa;CACrD;AACF;;AA+BA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,cAAc,KAAmB;CACxC,KAAK,MAAM,SAAS,YAAY,KAAK,EA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