@acryldev/blends 1.7.17 → 1.7.18

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/dist/index.js CHANGED
@@ -95,7 +95,7 @@ var packages = {
95
95
  "path": "../plugins/versions"
96
96
  },
97
97
  "@acryldev/blends-frame": {
98
- "version": "0.2.10",
98
+ "version": "0.2.11",
99
99
  "path": "../plugins/blends-frame"
100
100
  }
101
101
  };
@@ -54,6 +54,7 @@ They are enabled as they are built.
54
54
  | Look up a call | [API](api/index.md), [Routing](api/routing.md), [Context](api/context.md), [Request](api/request.md), [API summary](api/summary.md) |
55
55
  | Understand the design | [Concepts](concepts/motivation.md) |
56
56
  | Copy a pattern | [Guides](guides/best-practices.md), [Validation](guides/validation.md), [Testing](guides/testing.md), [Data, migrations and choosing a store](guides/data.md), [Forms, sessions and a database](guides/forms-and-sessions.md), [Client components without a bundler](guides/client-modules.md), [Bring your own tool](guides/bring-your-own-tool.md) |
57
+ | Share a plugin with other people: publish, pull from GitHub or the registry, update | [Share a plugin](guides/share-plugins.md) |
57
58
  | Run the 90-minute workshop | [Workshop](workshop/README.md), and the room around it in [Facilitator notes](workshop/facilitator.md) |
58
59
  | Use Acryl inside a Cordis app | [Acryl in a Cordis app](cordis/acryl-in-a-cordis-app.md), [Plugin lifecycle](cordis/plugin-lifecycle.md), [Mounting](cordis/mounting.md) |
59
60
  | Move from the 0.3 router calls | [Migration from 0.3](cordis/migration-from-0-3.md) |
@@ -0,0 +1,117 @@
1
+ # Share a plugin: publish it, pull it, update it
2
+
3
+ A plugin is a folder in `plugins/`. Another person's app takes it from a GitHub release, from the public plugin registry, or from a list your group
4
+ keeps. Every command below was run, as two people with their own apps and their own home folders (Ana publishes, Ben pulls), against a real GitHub
5
+ organization. They run in the app's folder, with the app running (`npm run dev`, or the desktop app): a pull installs into the running app.
6
+
7
+ You need `gh` signed in (`gh auth login`) to publish, and nothing to pull a public plugin.
8
+
9
+ ## 1. Make the plugin
10
+
11
+ `plugins/hello-ana/package.json` (the name and a version; the folder name is the plugin's name):
12
+
13
+ ```json
14
+ { "name": "hello-ana", "version": "0.1.0", "description": "A greeting.", "type": "module", "main": "index.ts" }
15
+ ```
16
+
17
+ `plugins/hello-ana/index.ts`:
18
+
19
+ ```ts
20
+ import type { Context } from '@deepseek-ai/cordis'
21
+ import { Acryl } from 'acrylblends'
22
+
23
+ export const name = 'hello-ana'
24
+ export const inject = ['router']
25
+
26
+ export function apply(ctx: Context): void {
27
+ ctx.router.route('/hello-ana', new Acryl().get('/', (c) => c.json({ text: 'hello from Ana, v0.1.0' })))
28
+ }
29
+ ```
30
+
31
+ Saving the folder starts the plugin in the running app: in the frame it answers at `/app/hello-ana` (under `npm start` at `/hello-ana`). A syntax error
32
+ leaves the previous version running and says so in the log.
33
+
34
+ ## 2. Publish it
35
+
36
+ ```sh
37
+ npm run acryl -- plugin publish hello-ana --owner <your GitHub account or organization>
38
+ ```
39
+
40
+ It prints the plan and sends nothing: the repository (new or not), the version, the license (`--license <id>`, MIT by default), the files, and that the
41
+ repository gets the topic `cordis-plugin`, which is how the public registry finds it. Only a person's `yes` at the terminal publishes; an agent gets the
42
+ plan and cannot answer. It ends with the line to give a friend:
43
+
44
+ ```
45
+ npm run acryl -- plugin pull github:<owner>/hello-ana@0.1.0@sha256:<digest>
46
+ ```
47
+
48
+ The same in the app: Settings > Plugins > My plugins > **Share...** on the plugin, then one of **Save here** (this computer only), **Share privately**,
49
+ **Share publicly**, **Publish to npm** or **List in the registry**. It shows the plan and asks again before it sends anything; the account field is empty for your own account.
50
+
51
+ | Target | How | Result |
52
+ | --- | --- | --- |
53
+ | GitHub | `plugin publish`, or Share publicly / Share privately | a repository and a release holding exactly the plugin's files, and the pull line |
54
+ | The public registry | `plugin publish` (always public), or **List in the registry** | the repository has the topic `cordis-plugin`; cordisplugins.github.io lists it at its next sync (hourly) |
55
+ | npm | `plugin publish <name> --to npm` | the package `@<scope>/<name>` on the npm registry (see below) |
56
+
57
+ A plugin that holds a secret is refused, naming the file.
58
+
59
+ ### To npm
60
+
61
+ ```sh
62
+ npm run acryl -- plugin publish hello-ana --to npm # as @<the account npm is signed in as>/hello-ana
63
+ npm run acryl -- plugin publish hello-ana --to npm --scope acme # as @acme/hello-ana
64
+ npm run acryl -- plugin publish hello-ana --to npm --registry https://npm.example.com/ # another registry
65
+ ```
66
+
67
+ It uses **your own** npm login and nothing else: it asks `npm whoami`, and when you are not signed in the plan is refused with `npm login`. The plan shows
68
+ the package, the registry, the version and the license before the `yes`; a version npm already has makes it the next patch. The package is public, named
69
+ `@scope/name` (the plugin's folder name is `name`). The same is the **Publish to npm** button of Share... (the account field is the scope; blank is your npm login's account). To try it without publishing, run the same command with `npm_config_dry_run=true` in the environment of
70
+ the running app: npm then stops before sending the package.
71
+
72
+ ## 3. Pull it
73
+
74
+ ```sh
75
+ npm run acryl -- plugin pull github:<owner>/hello-ana # the latest release
76
+ npm run acryl -- plugin pull github:<owner>/hello-ana@0.1.0 # one version
77
+ npm run acryl -- plugin pull github:<owner>/hello-ana@0.1.0@sha256:<digest> # exactly these bytes (the line the publisher gave)
78
+ npm run acryl -- plugin pull registry:hello-ana # the registry's id, checked against the integrity the registry lists
79
+ npm run acryl -- plugin pull npm:@acme/hello-ana # from npm: the latest version, or @0.1.1, and @sha256:<digest> to name the bytes
80
+ ```
81
+
82
+ An npm package `@acme/hello-ana` is installed in the folder `plugins/hello-ana`; the checksum npm lists for the version must match the bytes that arrive. A
83
+ public package needs no login; a private scope or registry is read through your own npm configuration.
84
+
85
+ In the app: Settings > Plugins > **Registry**, search, **Add to my app** (it says it runs someone else's code and asks first); or **Add by address** for
86
+ a `github:` line from a colleague. The plugin is live at once; `blend.yaml` records where it came from, so a copy of the app fetches the same bytes.
87
+
88
+ A group's plugins in one command: put one source per line in a file (`#` starts a comment), then `npm run acryl -- plugin pull --from group.txt`. Each
89
+ line is pulled on its own; a refused one is named with its reason while the others run.
90
+
91
+ ```sh
92
+ npm run acryl -- plugin list # what is installed, where each pulled one came from and who released it
93
+ npm run acryl -- plugin remove hello-ana
94
+ ```
95
+
96
+ ## 4. Update it, and keep your own edits
97
+
98
+ Ana changes the plugin and runs the same `plugin publish` again: the version that is already released is not released twice, so the plan names the next
99
+ patch (0.1.1) and says so. Ben runs the same pull line he used before:
100
+
101
+ ```sh
102
+ npm run acryl -- plugin pull github:<owner>/hello-ana@0.1.1
103
+ ```
104
+
105
+ In the app, Settings > Plugins > Registry shows **Update to v0.1.1** instead of "Added" when the registry lists a newer release than the one pulled; it asks first and does the same as the command.
106
+
107
+ - A folder Ben never touched is replaced by the new release, live.
108
+ - A folder Ben changed is merged: the release he pulled is fetched again as the common ancestor, a file only he changed keeps his change, a file of his own stays, and
109
+ a file both changed is merged line by line. The answer names the files that kept something of his (`kept`).
110
+ - When Ben and the release changed the same lines, nothing is written: the pull is refused naming the file, and his folder is exactly as it was. Move the folder
111
+ out of `plugins/`, pull again, and bring his change back by hand.
112
+ - A plugin another account released under the same name is never merged: it is refused naming where the copy in the app came from.
113
+
114
+ ## Try it without touching your own account
115
+
116
+ Use a throwaway GitHub organization and a second app with its own home folder, so the two people never share files. Publishing as the organization needs
117
+ `gh` signed in as one of its members: `--owner <organization>`.
@@ -141,9 +141,16 @@ type PullListView = {
141
141
  interface PublishOptionsView {
142
142
  readonly owner?: string;
143
143
  readonly license?: string;
144
+ /** `npm`: publish to an npm registry with the person's own npm login. */
145
+ readonly to?: 'npm';
146
+ readonly scope?: string;
147
+ readonly registry?: string;
144
148
  }
145
149
  /** A plan as the door shows it. The service owns it; the door passes it back unchanged. */
146
150
  interface PublishPlanView {
151
+ readonly target?: 'npm';
152
+ readonly package?: string;
153
+ readonly registry?: string;
147
154
  readonly owner: string;
148
155
  readonly repo: string;
149
156
  readonly version: string;
@@ -519,7 +519,7 @@ const VERB_SPECS = {
519
519
  }
520
520
  },
521
521
  "plugin-publish": {
522
- usage: "plugin publish <name> [--owner <account>] [--license <id>]: show what publishing this plugin would send; in a person's own terminal, ask them",
522
+ usage: "plugin publish <name> [--owner <account>] [--license <id>] [--to npm [--scope <scope>] [--registry <address>]]: show what publishing this plugin would send; in a person's own terminal, ask them",
523
523
  description: "Show what publishing a plugin would send: the account, repository, version, license, files and the line a friend pulls it with. Sends nothing. Only a person can say yes, in their own terminal or with Share in the frame; tell them the plan and how.",
524
524
  arguments: {
525
525
  type: "object",
@@ -535,6 +535,19 @@ const VERB_SPECS = {
535
535
  license: {
536
536
  type: "string",
537
537
  description: "an SPDX license id; MIT when absent"
538
+ },
539
+ to: {
540
+ type: "string",
541
+ enum: ["npm"],
542
+ description: "npm: publish to an npm registry with the person's own npm login instead of GitHub"
543
+ },
544
+ scope: {
545
+ type: "string",
546
+ description: "with to npm: the package scope; the npm login's account when absent"
547
+ },
548
+ registry: {
549
+ type: "string",
550
+ description: "with to npm: the registry address; the public one when absent"
538
551
  }
539
552
  },
540
553
  required: ["name"],
@@ -698,8 +711,9 @@ var DoorError = class extends Error {
698
711
  /** What a plan says, for a person deciding. */
699
712
  function renderPublishPlan(plan) {
700
713
  return [
701
- `Publish to ${plan.owner}/${plan.repo}${plan.createsRepository ? " (a new repository)" : ""}, ${plan.visibility}, version ${plan.version}, license ${plan.license}.`,
714
+ plan.target === "npm" ? `Publish to npm as ${plan.package ?? plan.repo} (registry ${plan.registry ?? "https://registry.npmjs.org/"}, signed in as the account of your own npm login), ${plan.visibility}, version ${plan.version}, license ${plan.license}.` : `Publish to ${plan.owner}/${plan.repo}${plan.createsRepository ? " (a new repository)" : ""}, ${plan.visibility}, version ${plan.version}, license ${plan.license}.`,
702
715
  `Files: ${plan.files.join(", ")}.`,
716
+ ...plan.target === "npm" ? [] : [`The repository gets the topic cordis-plugin, so the public plugin registry (cordisplugins.github.io) lists it within about an hour.`],
703
717
  `A friend gets exactly these bytes with: ${plan.pullLine}`
704
718
  ].join("\n");
705
719
  }
@@ -1025,11 +1039,14 @@ var Door = class {
1025
1039
  }
1026
1040
  /** Only a plan: no argument of any verb can publish, so an agent never says yes for a person. */
1027
1041
  async planPublish(input) {
1028
- const { name, owner, license } = input;
1042
+ const { name, owner, license, to, scope, registry } = input;
1029
1043
  if (typeof name !== "string" || name === "") throw new DoorError("invalid", "plugin publish needs a plugin name, e.g. plugin publish pomodoro");
1030
1044
  const value = await this.share().planPublish(name, {
1031
1045
  ...typeof owner === "string" && owner !== "" ? { owner } : {},
1032
- ...typeof license === "string" && license !== "" ? { license } : {}
1046
+ ...typeof license === "string" && license !== "" ? { license } : {},
1047
+ ...to === "npm" ? { to } : {},
1048
+ ...typeof scope === "string" && scope !== "" ? { scope } : {},
1049
+ ...typeof registry === "string" && registry !== "" ? { registry } : {}
1033
1050
  });
1034
1051
  if ("ok" in value) throw new DoorError("refused", `${value.reason}. ${value.next}.`);
1035
1052
  return {
@@ -1045,7 +1062,7 @@ var Door = class {
1045
1062
  tool: "plugin-publish",
1046
1063
  target: {
1047
1064
  role: "plugin",
1048
- name: `${confirmed.owner}/${confirmed.repo}@${confirmed.version}`
1065
+ name: `${confirmed.package ?? `${confirmed.owner}/${confirmed.repo}`}@${confirmed.version}`
1049
1066
  },
1050
1067
  outcome: value.ok ? "ok" : "refused",
1051
1068
  approval: "token"
@@ -1418,7 +1435,7 @@ function operatorRoutes(prefix, secret, door, reportError) {
1418
1435
  }
1419
1436
  }).post(`${prefix}/publish-confirmed`, operatorOnly(secret), jsonBody, async (c) => {
1420
1437
  const body = await readJson(c);
1421
- const { name, confirm, owner, license } = body === INVALID_JSON || typeof body !== "object" || body === null ? {} : body;
1438
+ const { name, confirm, owner, license, to, scope, registry } = body === INVALID_JSON || typeof body !== "object" || body === null ? {} : body;
1422
1439
  if (typeof name !== "string" || typeof confirm !== "object" || confirm === null) return c.json({
1423
1440
  ok: false,
1424
1441
  code: "invalid",
@@ -1427,7 +1444,10 @@ function operatorRoutes(prefix, secret, door, reportError) {
1427
1444
  try {
1428
1445
  const value = await door.publishConfirmed(name, confirm, {
1429
1446
  ...typeof owner === "string" ? { owner } : {},
1430
- ...typeof license === "string" ? { license } : {}
1447
+ ...typeof license === "string" ? { license } : {},
1448
+ ...to === "npm" ? { to } : {},
1449
+ ...typeof scope === "string" ? { scope } : {},
1450
+ ...typeof registry === "string" ? { registry } : {}
1431
1451
  });
1432
1452
  return c.json({
1433
1453
  ok: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acryldev/blends",
3
- "version": "1.7.17",
3
+ "version": "1.7.18",
4
4
  "description": "The Acryl web framework (import { Acryl } from \"acrylblends\") and the acrylblends command that scaffolds Cordis apps.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acryldev/door",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "The door of an ACRYL framework app, one Cordis plugin: an agent working in the app folder looks at the running page (snapshots with refs), acts on it (click, type, select, press, scroll, wait) and installs plugins live, through .acryl/bin/acryl; loopback only, with a per-run secret in .acryl/door.json, an audit log, and an in-page indicator with a kill switch",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,7 +17,7 @@ import { fileURLToPath } from 'node:url'
17
17
  import { readDoorFile, STATE_DIR, DOOR_FILE } from '../host/door-file.ts'
18
18
 
19
19
  const ACT_OPS = new Set(['click', 'type', 'select', 'press', 'scroll', 'wait', 'reload', 'navigate'])
20
- const VALUED = new Set(['--dir', '--owner', '--license', '--ref', '--text', '--option', '--key', '--direction', '--amount', '--cursor', '--max-nodes', '--role', '--name', '--timeout-ms', '--id', '--width', '--height', '--window', '--tool', '--args', '--path', '--from'])
20
+ const VALUED = new Set(['--dir', '--owner', '--license', '--to', '--scope', '--registry', '--ref', '--text', '--option', '--key', '--direction', '--amount', '--cursor', '--max-nodes', '--role', '--name', '--timeout-ms', '--id', '--width', '--height', '--window', '--tool', '--args', '--path', '--from'])
21
21
  const FLAGS = new Set(['--json', '--submit', '--no-clear', '--gone', '--force', '--help'])
22
22
 
23
23
  export class UsageError extends Error {}
@@ -44,7 +44,7 @@ const USAGE = `usage: acryl <verb> [options] [--json] [--dir <app folder>]
44
44
  act wait (--text <t> | --role <role> [--name <n>]) [--gone] [--timeout-ms <ms>]
45
45
  (look and every act take --window <n>: the desktop window whose page it is for; window list prints the numbers)
46
46
  frame [open|close|toggle left|right | settings [<section>] | build | preview] (the ACRYL frame around the app; alone, what is open)
47
- plugin list | plugin add <folder> | plugin pull <source> | plugin publish <name> [--owner <account>] [--license <id>] | plugin remove <name> | plugin reload
47
+ plugin list | plugin add <folder> | plugin pull <source> | plugin publish <name> [--owner <account>] [--license <id>] [--to npm [--scope <scope>] [--registry <address>]] | plugin remove <name> | plugin reload
48
48
  window list | window open [--path <p>] | window focus --id <n> | window close --id <n> [--force]
49
49
  window resize --id <n> --width <px> --height <px>
50
50
  menu list | menu click --path "File>New Note" [--force]
@@ -160,7 +160,11 @@ export function parseInvocation(argv: readonly string[], env: NodeJS.ProcessEnv
160
160
  if (third === undefined) throw new UsageError('plugin publish needs a plugin name, e.g. plugin publish pomodoro')
161
161
  const owner = values.get('--owner')
162
162
  const license = values.get('--license')
163
- return make('plugin-publish', { name: third, ...(owner === undefined ? {} : { owner }), ...(license === undefined ? {} : { license }) })
163
+ const to = values.get('--to')
164
+ if (to !== undefined && to !== 'npm') throw new UsageError('plugin publish --to takes npm (GitHub is the default), e.g. plugin publish pomodoro --to npm')
165
+ const scope = values.get('--scope')
166
+ const registry = values.get('--registry')
167
+ return make('plugin-publish', { name: third, ...(owner === undefined ? {} : { owner }), ...(license === undefined ? {} : { license }), ...(to === undefined ? {} : { to }), ...(scope === undefined ? {} : { scope }), ...(registry === undefined ? {} : { registry }) })
164
168
  }
165
169
  if (second === 'remove') { if (third === undefined) throw new UsageError('plugin remove needs a plugin name'); return make('plugin-remove', { name: third }) }
166
170
  throw new UsageError(`plugin needs list, add, pull, publish, remove or reload\n${USAGE}`)
@@ -285,6 +289,8 @@ const isPlan = (value: unknown): value is PlanAsked =>
285
289
 
286
290
  /** What the prompt names. */
287
291
  interface PlanAsked {
292
+ /** npm: the package it publishes. */
293
+ readonly package?: string
288
294
  readonly owner: string
289
295
  readonly repo: string
290
296
  readonly version: string
@@ -300,9 +306,9 @@ async function confirmPublish(
300
306
  url: string,
301
307
  headers: Record<string, string>,
302
308
  ): Promise<number> {
303
- const yes = await io.ask?.(`Publish ${plan.owner}/${plan.repo} v${plan.version} under ${plan.license}? Type yes to send it: `)
309
+ const yes = await io.ask?.(`Publish ${plan.package ?? `${plan.owner}/${plan.repo}`} v${plan.version} under ${plan.license}? Type yes to send it: `)
304
310
  if (yes !== true) { io.out('Nothing was sent.\n'); return 0 }
305
- const response = await request(url, { method: 'POST', headers, body: JSON.stringify({ name: invocation.args.name, owner: invocation.args.owner, license: invocation.args.license, confirm: plan }) })
311
+ const response = await request(url, { method: 'POST', headers, body: JSON.stringify({ name: invocation.args.name, owner: invocation.args.owner, license: invocation.args.license, to: invocation.args.to, scope: invocation.args.scope, registry: invocation.args.registry, confirm: plan }) })
306
312
  const body = await response.json().catch(() => undefined) as { ok?: boolean; message?: string; value?: { ok?: boolean; releaseUrl?: string; pullLine?: string; reason?: string; next?: string } } | undefined
307
313
  const result = body?.value
308
314
  if (body?.ok !== true || result?.ok !== true) {
@@ -60,10 +60,17 @@ export type PullListView =
60
60
  export interface PublishOptionsView {
61
61
  readonly owner?: string
62
62
  readonly license?: string
63
+ /** `npm`: publish to an npm registry with the person's own npm login. */
64
+ readonly to?: 'npm'
65
+ readonly scope?: string
66
+ readonly registry?: string
63
67
  }
64
68
 
65
69
  /** A plan as the door shows it. The service owns it; the door passes it back unchanged. */
66
70
  export interface PublishPlanView {
71
+ readonly target?: 'npm'
72
+ readonly package?: string
73
+ readonly registry?: string
67
74
  readonly owner: string
68
75
  readonly repo: string
69
76
  readonly version: string
@@ -77,9 +84,19 @@ export interface PublishPlanView {
77
84
 
78
85
  /** What a plan says, for a person deciding. */
79
86
  export function renderPublishPlan(plan: PublishPlanView): string {
87
+ const where =
88
+ plan.target === 'npm'
89
+ ? `Publish to npm as ${plan.package ?? plan.repo} (registry ${plan.registry ?? 'https://registry.npmjs.org/'}, signed in as the account of your own npm login), ${plan.visibility}, version ${plan.version}, license ${plan.license}.`
90
+ : `Publish to ${plan.owner}/${plan.repo}${plan.createsRepository ? ' (a new repository)' : ''}, ${plan.visibility}, version ${plan.version}, license ${plan.license}.`
80
91
  return [
81
- `Publish to ${plan.owner}/${plan.repo}${plan.createsRepository ? ' (a new repository)' : ''}, ${plan.visibility}, version ${plan.version}, license ${plan.license}.`,
92
+ where,
82
93
  `Files: ${plan.files.join(', ')}.`,
94
+ // A public repository carries the topic the plugin registry (cordisplugins.github.io) lists by: said before the yes, not found out after.
95
+ ...(plan.target === 'npm'
96
+ ? []
97
+ : [
98
+ `The repository gets the topic cordis-plugin, so the public plugin registry (cordisplugins.github.io) lists it within about an hour.`,
99
+ ]),
83
100
  `A friend gets exactly these bytes with: ${plan.pullLine}`,
84
101
  ].join('\n')
85
102
  }
@@ -407,11 +424,14 @@ export class Door {
407
424
 
408
425
  /** Only a plan: no argument of any verb can publish, so an agent never says yes for a person. */
409
426
  private async planPublish(input: Record<string, unknown>): Promise<VerbAnswer> {
410
- const { name, owner, license } = input
427
+ const { name, owner, license, to, scope, registry } = input
411
428
  if (typeof name !== 'string' || name === '') throw new DoorError('invalid', 'plugin publish needs a plugin name, e.g. plugin publish pomodoro')
412
429
  const value = await this.share().planPublish(name, {
413
430
  ...(typeof owner === 'string' && owner !== '' ? { owner } : {}),
414
431
  ...(typeof license === 'string' && license !== '' ? { license } : {}),
432
+ ...(to === 'npm' ? { to } : {}),
433
+ ...(typeof scope === 'string' && scope !== '' ? { scope } : {}),
434
+ ...(typeof registry === 'string' && registry !== '' ? { registry } : {}),
415
435
  })
416
436
  if ('ok' in value) throw new DoorError('refused', `${value.reason}. ${value.next}.`)
417
437
  return { value, text: `${renderPublishPlan(value)}\nNothing was sent. Only a person can say yes: they run \`npm run acryl -- plugin publish ${name}\` in their own terminal, or press Share in the frame. \`--license <id>\` changes the license before the yes.` }
@@ -420,7 +440,7 @@ export class Door {
420
440
  /** The person's yes, from their own terminal. Not a verb: MCP and the chat do not have it. */
421
441
  async publishConfirmed(name: string, confirmed: PublishPlanView, options: PublishOptionsView): Promise<unknown> {
422
442
  const value = await this.share().publish(name, confirmed, options)
423
- this.deps.audit.record({ at: new Date().toISOString(), tool: 'plugin-publish', target: { role: 'plugin', name: `${confirmed.owner}/${confirmed.repo}@${confirmed.version}` }, outcome: value.ok ? 'ok' : 'refused', approval: 'token' })
443
+ this.deps.audit.record({ at: new Date().toISOString(), tool: 'plugin-publish', target: { role: 'plugin', name: `${confirmed.package ?? `${confirmed.owner}/${confirmed.repo}`}@${confirmed.version}` }, outcome: value.ok ? 'ok' : 'refused', approval: 'token' })
424
444
  return value
425
445
  }
426
446
 
@@ -39,7 +39,7 @@ export function operatorRoutes(prefix: string, secret: string, door: Door, repor
39
39
  // secret could still reach it: the door keeps honest agents from publishing by accident, the person's account is the real boundary.
40
40
  .post(`${prefix}/publish-confirmed`, operatorOnly(secret), jsonBody, async (c) => {
41
41
  const body = await readJson(c)
42
- const { name, confirm, owner, license } = (body === INVALID_JSON || typeof body !== 'object' || body === null ? {} : body) as { name?: unknown; confirm?: unknown; owner?: unknown; license?: unknown }
42
+ const { name, confirm, owner, license, to, scope, registry } = (body === INVALID_JSON || typeof body !== 'object' || body === null ? {} : body) as { name?: unknown; confirm?: unknown; owner?: unknown; license?: unknown; to?: unknown; scope?: unknown; registry?: unknown }
43
43
  if (typeof name !== 'string' || typeof confirm !== 'object' || confirm === null) {
44
44
  return c.json({ ok: false, code: 'invalid', message: 'the body is { name, confirm }' } satisfies CallResponse, 400)
45
45
  }
@@ -47,6 +47,9 @@ export function operatorRoutes(prefix: string, secret: string, door: Door, repor
47
47
  const value = await door.publishConfirmed(name, confirm as PublishPlanView, {
48
48
  ...(typeof owner === 'string' ? { owner } : {}),
49
49
  ...(typeof license === 'string' ? { license } : {}),
50
+ ...(to === 'npm' ? { to } : {}),
51
+ ...(typeof scope === 'string' ? { scope } : {}),
52
+ ...(typeof registry === 'string' ? { registry } : {}),
50
53
  })
51
54
  return c.json({ ok: true, value, text: JSON.stringify(value, null, 2) } satisfies CallResponse)
52
55
  } catch (cause) {
@@ -105,9 +105,9 @@ export const VERB_SPECS: Readonly<Record<Verb, VerbSpec>> = {
105
105
  arguments: { type: 'object', properties: { source: { type: 'string', description: 'github:<owner>/<repo>[@<version>][@sha256:<digest>], or a .tgz path or https address' }, from: { type: 'string', description: 'instead of source: a list of sources, a file in the app (e.g. group.txt) or an https address' } }, additionalProperties: false },
106
106
  },
107
107
  'plugin-publish': {
108
- usage: 'plugin publish <name> [--owner <account>] [--license <id>]: show what publishing this plugin would send; in a person\'s own terminal, ask them',
108
+ usage: 'plugin publish <name> [--owner <account>] [--license <id>] [--to npm [--scope <scope>] [--registry <address>]]: show what publishing this plugin would send; in a person\'s own terminal, ask them',
109
109
  description: 'Show what publishing a plugin would send: the account, repository, version, license, files and the line a friend pulls it with. Sends nothing. Only a person can say yes, in their own terminal or with Share in the frame; tell them the plan and how.',
110
- arguments: { type: 'object', properties: { name: { type: 'string', description: 'a plugin of plugins/' }, owner: { type: 'string', description: 'the GitHub account or organization; the signed-in one when absent' }, license: { type: 'string', description: 'an SPDX license id; MIT when absent' } }, required: ['name'], additionalProperties: false },
110
+ arguments: { type: 'object', properties: { name: { type: 'string', description: 'a plugin of plugins/' }, owner: { type: 'string', description: 'the GitHub account or organization; the signed-in one when absent' }, license: { type: 'string', description: 'an SPDX license id; MIT when absent' }, to: { type: 'string', enum: ['npm'], description: 'npm: publish to an npm registry with the person\'s own npm login instead of GitHub' }, scope: { type: 'string', description: 'with to npm: the package scope; the npm login\'s account when absent' }, registry: { type: 'string', description: 'with to npm: the registry address; the public one when absent' } }, required: ['name'], additionalProperties: false },
111
111
  },
112
112
  'plugin-remove': {
113
113
  usage: 'plugin remove <name>: stop and remove an installed plugin',
@@ -214,8 +214,15 @@ export function validate(document: unknown, known?: Iterable<string>): Diagnosti
214
214
  metadata.visibility !== 'public'
215
215
  )
216
216
  add('schema-error', 'metadata.visibility', "must be 'private' or 'public'")
217
- if (metadata.from !== undefined && (typeof metadata.from !== 'string' || metadata.from.trim() === ''))
218
- add('schema-error', 'metadata.from', "must name a source such as 'acrylblends.notes#0.3.1' or 'github:ana/notes#v0.2.0'")
217
+ if (
218
+ metadata.from !== undefined &&
219
+ (typeof metadata.from !== 'string' || metadata.from.trim() === '')
220
+ )
221
+ add(
222
+ 'schema-error',
223
+ 'metadata.from',
224
+ "must name a source such as 'acrylblends.notes#0.3.1' or 'github:ana/notes#v0.2.0'",
225
+ )
219
226
  }
220
227
 
221
228
  const spec = document.spec
@@ -8,8 +8,14 @@ Share plugins between people. Pull a plugin someone released into your running a
8
8
  npm run acryl -- plugin pull github:<owner>/<repo>@<version>
9
9
  ```
10
10
 
11
+ `registry:<id>` pulls what the public plugin registry (cordisplugins.github.io) lists under that id, checked against the integrity it lists.
12
+
11
13
  The line someone gives you after publishing also carries `@sha256:<digest>`. Then a release with different bytes is refused, with exit 1, and nothing changes.
12
14
 
15
+ A newer release of a plugin you already pulled updates it in place. A folder you never touched is replaced. A folder you changed is merged three ways
16
+ (the release you pulled, your folder, the new release; `merge-edits.ts`): a file only you changed keeps your change, a file both changed is merged line by
17
+ line with git, and when the same lines changed nothing is written and the pull is refused naming the file. The answer lists the files that kept your changes (`kept`).
18
+
13
19
  The app must be running (`npm run dev`), because the pull installs into it live. A stopped app never installs offline: the line exits 3 and asks you to start the app and run the same line again.
14
20
 
15
21
  The app remembers where each pulled plugin came from, in the `plugin-share` row of `blend.yaml`. A copy of the app fetches the same bytes at its next start.
@@ -15,29 +15,35 @@ import {
15
15
  } from 'node:fs'
16
16
  import { dirname, join, resolve } from 'node:path'
17
17
  import { findSecrets } from '@acryldev/app-persistence'
18
- import { digestFolder, type PluginFile } from '@acryldev/blends-core'
18
+ import { digestFolder, type PluginFile, pluginFiles } from '@acryldev/blends-core'
19
19
  import { type ExtensionInfo, NAME } from '@acryldev/extensions'
20
20
  import type {} from '@acryldev/instance'
21
21
  import { LOCK_FILE, writeLock } from '@acryldev/manifest/lock'
22
22
  import {
23
23
  bumpVersion,
24
+ firstRegistryPort,
24
25
  gitCli,
25
26
  githubCli,
26
27
  githubReleasesOverHttps,
27
28
  httpsDownload,
28
29
  InvalidPluginSourceError,
30
+ NPM_REGISTRY,
31
+ npmRegistryOverHttps,
32
+ npmRegistryViaCli,
29
33
  type PluginSource,
30
34
  PluginStore,
31
35
  PullError,
32
36
  packFolder,
33
37
  parsePluginSource,
34
38
  pullPlugin,
39
+ type RegistryPort,
35
40
  type ReleasePort,
36
41
  readTarball,
37
42
  sharePlugin,
38
43
  storeRootOf,
39
44
  } from '@acryldev/plugin-hub-core'
40
45
  import { type Context, Service } from '@deepseek-ai/cordis'
46
+ import { type MergedTrees, mergeTrees, type Tree } from './merge-edits.ts'
41
47
  import {
42
48
  ensureNative,
43
49
  type NativeAction,
@@ -49,8 +55,10 @@ import {
49
55
  nativesOf,
50
56
  releaseNative,
51
57
  } from './native.ts'
58
+ import { npmWithLogin } from './npm-login.ts'
52
59
  import { packagePlugin } from './package.ts'
53
60
  import {
61
+ npmPullLineOf,
54
62
  type PublishOptions,
55
63
  type PublishPlan,
56
64
  type PublishPorts,
@@ -68,6 +76,7 @@ import {
68
76
  } from './pull-check.ts'
69
77
  import { LIST_MAX_BYTES, parsePullList, pullListLocation } from './pull-list.ts'
70
78
  import { type PulledRecord, pulledRecords, withPulledRecord } from './pulled-records.ts'
79
+ import { lookUpRegistry, REGISTRY_INDEX_URL } from './registry-source.ts'
71
80
 
72
81
  export type {
73
82
  PublishOptions,
@@ -91,6 +100,10 @@ export interface PluginShareConfig {
91
100
  publish?: PublishPorts
92
101
  /** 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. */
93
102
  download?: (url: string) => Promise<Uint8Array>
103
+ /** Where `registry:<id>` reads the plugin registry's index. Defaults to cordisplugins.github.io. */
104
+ registryIndex?: string
105
+ /** Where an `npm:` source reads packages. Defaults to the public registry over HTTPS, then the person's own npm (a private scope or registry). */
106
+ npm?: RegistryPort
94
107
  /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */
95
108
  native?: NativePorts
96
109
  }
@@ -108,6 +121,8 @@ export type PullResult =
108
121
  readonly state: string
109
122
  /** 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. */
110
123
  readonly remembered: boolean
124
+ /** The files of an older pulled copy that kept the person's own changes when this release updated it in place. */
125
+ readonly kept?: readonly string[]
111
126
  /** The native package the plugin brought for this computer (native.ts), and what installing it did. */
112
127
  readonly native?: {
113
128
  readonly package: string
@@ -186,6 +201,8 @@ function releaseOf(folder: string): string | undefined {
186
201
  /** The license a new public plugin is offered under; the plan shows it before the person says yes. */
187
202
  const DEFAULT_LICENSE = 'MIT'
188
203
  const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u
204
+ /** An npm scope: what follows `@`. */
205
+ const NPM_SCOPE = /^[a-z0-9][a-z0-9._~-]*$/u
189
206
 
190
207
  const publishRefused = (reason: string, next: string): PublishRefused => ({
191
208
  ok: false,
@@ -193,7 +210,8 @@ const publishRefused = (reason: string, next: string): PublishRefused => ({
193
210
  next,
194
211
  })
195
212
 
196
- const SOURCE_FORMS = 'github:<owner>/<repo>[@<version>] or a .tgz path or address'
213
+ const SOURCE_FORMS =
214
+ 'github:<owner>/<repo>[@<version>], npm:<package>[@<version>], registry:<id> or a .tgz path or address'
197
215
 
198
216
  /** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */
199
217
  function readSource(
@@ -203,7 +221,12 @@ function readSource(
203
221
  const { source, digest } = splitDigest(input.trim())
204
222
  const isLocalTarball = /\.(?:tgz|tar\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source)
205
223
  const parsed = parsePluginSource(isLocalTarball ? resolve(root, source) : source)
206
- if (parsed.kind !== 'github' && parsed.kind !== 'tarball-file' && parsed.kind !== 'tarball-url') {
224
+ if (
225
+ parsed.kind !== 'github' &&
226
+ parsed.kind !== 'npm' &&
227
+ parsed.kind !== 'tarball-file' &&
228
+ parsed.kind !== 'tarball-url'
229
+ ) {
207
230
  const named = parsed.kind === 'name' ? 'a bare name' : parsed.kind
208
231
  throw new InvalidPluginSourceError(
209
232
  input,
@@ -216,9 +239,35 @@ function readSource(
216
239
  /** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */
217
240
  function recordedSource(source: PluginSource, version: string): string | undefined {
218
241
  if (source.kind === 'github') return `github:${source.owner}/${source.repo}@${version}`
242
+ if (source.kind === 'npm') return `npm:${source.name.full}@${version}`
219
243
  return source.kind === 'tarball-url' ? source.url : undefined
220
244
  }
221
245
 
246
+ /** What two releases of one plugin share in a recorded source: `github:<owner>/<repo>` or `npm:<package>`, lower case. */
247
+ const repoOf = (source: string): string | undefined => {
248
+ const github = /^(github:[^/@]+\/[^/@]+)@/u.exec(source)?.[1]
249
+ const npm = /^(npm:(?:@[^/@]+\/)?[^/@]+)@/u.exec(source)?.[1]
250
+ return (github ?? npm)?.toLowerCase()
251
+ }
252
+
253
+ /** A package's folder in `plugins/`: the name after its scope (`@ana/clock` is `clock`). */
254
+ const folderOf = (packageName: string): string =>
255
+ packageName.includes('/') ? packageName.slice(packageName.lastIndexOf('/') + 1) : packageName
256
+
257
+ const treeOf = (files: readonly PluginFile[]): Tree =>
258
+ new Map(files.map((file) => [file.path, file.bytes]))
259
+
260
+ /** Make a plugin folder hold exactly `to`, having held `from`: files only `from` had go, every file of `to` is written. */
261
+ function applyTree(folder: string, from: Tree, to: Tree): void {
262
+ for (const path of from.keys())
263
+ if (!to.has(path)) rmSync(join(folder, ...path.split('/')), { force: true })
264
+ for (const [path, bytes] of to) {
265
+ const file = join(folder, ...path.split('/'))
266
+ mkdirSync(dirname(file), { recursive: true })
267
+ writeFileSync(file, bytes)
268
+ }
269
+ }
270
+
222
271
  const reasonOf = (cause: unknown): string => {
223
272
  if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason
224
273
  return cause instanceof Error ? cause.message : String(cause)
@@ -230,6 +279,8 @@ export class PluginShare extends Service {
230
279
  private readonly dir: string
231
280
  private readonly releases: ReleasePort
232
281
  private readonly download: (url: string) => Promise<Uint8Array>
282
+ private readonly registryIndex: string
283
+ private readonly npmRegistry: RegistryPort
233
284
  private readonly ports: PublishPorts
234
285
  /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */
235
286
  private queue: Promise<unknown> = Promise.resolve()
@@ -251,6 +302,8 @@ export class PluginShare extends Service {
251
302
  this.dir = resolve(config.dir ?? join(ctx.appInstance.root, 'plugins'))
252
303
  this.releases = config.releases ?? githubReleasesOverHttps()
253
304
  this.download = config.download ?? httpsDownload()
305
+ this.registryIndex = config.registryIndex ?? REGISTRY_INDEX_URL
306
+ this.npmRegistry = config.npm ?? firstRegistryPort(npmRegistryOverHttps(), npmRegistryViaCli())
254
307
  this.nativeWork = config.native ?? nativePorts()
255
308
  this.ports = config.publish ?? { host: githubCli(), git: gitCli() }
256
309
  // Removing a plugin removes its record. Listened to here, not asked of each caller: every way of removing it goes through extensions.
@@ -394,6 +447,7 @@ export class PluginShare extends Service {
394
447
  'look at the new plan and say yes again',
395
448
  )
396
449
  }
450
+ if (plan.target === 'npm') return this.publishNpm(name, plan)
397
451
  const { home } = this.own.appInstance
398
452
  try {
399
453
  const shared = await sharePlugin(
@@ -568,6 +622,7 @@ export class PluginShare extends Service {
568
622
  `this app has no plugin "${name}" in plugins/`,
569
623
  'name a folder of plugins/',
570
624
  )
625
+ if (options.to === 'npm') return this.planNpm(name, source, options)
571
626
  try {
572
627
  const { host } = this.ports
573
628
  const owner = options.owner ?? host.login()
@@ -621,8 +676,174 @@ export class PluginShare extends Service {
621
676
  }
622
677
  }
623
678
 
679
+ /**
680
+ * What publishing to npm would do, read without sending anything: the account is the person's own npm login (`npm whoami`), the package is
681
+ * `@<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.
682
+ */
683
+ private async planNpm(
684
+ name: string,
685
+ source: string,
686
+ options: PublishOptions,
687
+ ): Promise<PublishPlan | PublishRefused> {
688
+ const npm = this.ports.npm ?? npmWithLogin()
689
+ const registry = options.registry ?? NPM_REGISTRY
690
+ try {
691
+ const account = npm.login(registry)
692
+ const scope = (options.scope ?? account).replace(/^@/u, '').toLowerCase()
693
+ if (!NPM_SCOPE.test(scope))
694
+ return publishRefused(
695
+ `"${scope}" is not an npm scope`,
696
+ 'write letters, digits and dashes, for example --scope acme',
697
+ )
698
+ const license = options.license ?? DEFAULT_LICENSE
699
+ if (!LICENSE_ID.test(license))
700
+ return publishRefused(
701
+ `"${license}" is not a license id`,
702
+ 'write one such as MIT or Apache-2.0',
703
+ )
704
+ const packageName = `@${scope}/${name}`
705
+ const pack = (version?: string) => this.packNpm(source, name, packageName, license, version)
706
+ let packaged = await pack()
707
+ const released = npm.hasVersion(packageName, packaged.version, registry)
708
+ ? packaged.version
709
+ : undefined
710
+ if (released !== undefined) packaged = await pack(bumpVersion(released, 'patch'))
711
+ const secrets = findSecrets(
712
+ readTarball(packFolder(packaged.dir).tarball).map((file) => ({
713
+ path: file.path,
714
+ text: Buffer.from(file.content).toString('utf8'),
715
+ })),
716
+ )
717
+ if (secrets.length > 0) {
718
+ return publishRefused(
719
+ `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,
720
+ "take them out of the plugin and read them from the app's settings",
721
+ )
722
+ }
723
+ return {
724
+ target: 'npm',
725
+ package: packageName,
726
+ registry,
727
+ owner: scope,
728
+ repo: name,
729
+ version: packaged.version,
730
+ visibility: 'public',
731
+ license,
732
+ createsRepository: false,
733
+ ...(released === undefined ? {} : { released }),
734
+ files: packaged.files,
735
+ integrity: packaged.integrity,
736
+ digest: packaged.digest,
737
+ pullLine: npmPullLineOf(packageName, packaged.version, packaged.digest),
738
+ }
739
+ } catch (cause) {
740
+ return publishRefused(
741
+ reasonOf(cause),
742
+ 'fix it, or sign in with: npm login (--registry <address> for another registry); nothing was sent',
743
+ )
744
+ }
745
+ }
746
+
747
+ /** 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. */
748
+ private packNpm(
749
+ source: string,
750
+ name: string,
751
+ packageName: string,
752
+ license: string,
753
+ version?: string,
754
+ ) {
755
+ return packagePlugin(source, this.packages, name, `The ${name} Cordis plugin.`, {
756
+ release: { license },
757
+ packageName,
758
+ ...(version === undefined ? {} : { version }),
759
+ })
760
+ }
761
+
762
+ /** 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. */
763
+ private async publishNpm(name: string, plan: PublishPlan): Promise<PublishResult> {
764
+ const registry = plan.registry ?? NPM_REGISTRY
765
+ const packageName = plan.package ?? `@${plan.owner}/${plan.repo}`
766
+ try {
767
+ const packed = await this.packNpm(
768
+ join(this.dir, name),
769
+ name,
770
+ packageName,
771
+ plan.license,
772
+ plan.version,
773
+ )
774
+ if (packed.integrity !== plan.integrity)
775
+ return publishRefused(
776
+ `the package made now is not the one that was planned (${packageName} v${plan.version}); nothing was sent`,
777
+ 'look at the new plan and say yes again',
778
+ )
779
+ ;(this.ports.npm ?? npmWithLogin()).publish(packed.tarball, registry, 'public')
780
+ const url =
781
+ registry === NPM_REGISTRY
782
+ ? `https://www.npmjs.com/package/${packageName}`
783
+ : `${registry.replace(/\/$/u, '')}/${packageName}`
784
+ return {
785
+ ok: true,
786
+ url,
787
+ releaseUrl: url,
788
+ version: packed.version,
789
+ integrity: packed.integrity,
790
+ digest: plan.digest,
791
+ pullLine: plan.pullLine,
792
+ }
793
+ } catch (cause) {
794
+ return publishRefused(
795
+ reasonOf(cause),
796
+ 'look at the registry; part of this publish may have been sent',
797
+ )
798
+ }
799
+ }
800
+
801
+ /** A `registry:<id>` source turned into the release it lists, with the integrity the registry lists for it; any other source as it is. */
802
+ private async resolveRegistry(
803
+ input: string,
804
+ expectIntegrity?: string,
805
+ ): Promise<{ readonly input: string; readonly expectIntegrity?: string } | PullRefused> {
806
+ const text = input.trim()
807
+ if (!/^registry:/iu.test(text))
808
+ return { input, ...(expectIntegrity === undefined ? {} : { expectIntegrity }) }
809
+ // A digest written after the id (`registry:<id>@sha256:<digest>`) is not part of the id: it travels on to the release's source.
810
+ let named: ReturnType<typeof splitDigest>
811
+ try {
812
+ named = splitDigest(text)
813
+ } catch (cause) {
814
+ return refuse(
815
+ 'source',
816
+ reasonOf(cause),
817
+ 'write the 64 hex digits the plugin page shows after @sha256:',
818
+ )
819
+ }
820
+ let index: string
821
+ try {
822
+ index = Buffer.from(await this.download(this.registryIndex)).toString('utf8')
823
+ } catch (cause) {
824
+ return refuse(
825
+ 'fetch',
826
+ `the registry could not be read: ${reasonOf(cause)}`,
827
+ 'check the internet connection and pull again, or pull github:<owner>/<repo>',
828
+ )
829
+ }
830
+ const found = lookUpRegistry(index, named.source.slice('registry:'.length))
831
+ if (!found.ok) return refuse('source', found.reason, found.next)
832
+ return {
833
+ input:
834
+ named.digest === undefined
835
+ ? found.hit.source
836
+ : `${found.hit.source}@sha256:${named.digest}`,
837
+ expectIntegrity: expectIntegrity ?? found.hit.integrity,
838
+ }
839
+ }
840
+
624
841
  private async pullNow(input: string, expectIntegrity?: string): Promise<PullResult> {
625
842
  const { home, root } = this.own.appInstance
843
+ const resolved = await this.resolveRegistry(input, expectIntegrity)
844
+ if ('refusal' in resolved) return resolved
845
+ input = resolved.input
846
+ expectIntegrity = resolved.expectIntegrity
626
847
  let read: ReturnType<typeof readSource>
627
848
  try {
628
849
  read = readSource(input, root)
@@ -643,6 +864,7 @@ export class PluginShare extends Service {
643
864
  {
644
865
  store: new PluginStore(scratch),
645
866
  releases: this.releases,
867
+ registry: this.npmRegistry,
646
868
  download: this.download,
647
869
  },
648
870
  expectIntegrity === undefined ? {} : { expectIntegrity },
@@ -654,18 +876,21 @@ export class PluginShare extends Service {
654
876
  'check the source with the person who released it; nothing was installed',
655
877
  )
656
878
  }
879
+ // 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.
880
+ const folderIn = (packageName: string): string =>
881
+ read.source.kind === 'npm' ? folderOf(packageName) : packageName
657
882
  const files: PluginFile[] = readTarball(readFileSync(pulled.stored.path)).map(
658
883
  ({ path, content }) => ({ path, bytes: content, kind: 'file' }),
659
884
  )
660
885
  const refused = pullRefusal(pulled.manifest, files, {
661
886
  digest: read.digest,
662
- nameFits: (name) => NAME.test(name),
887
+ nameFits: (name) => NAME.test(folderIn(name)),
663
888
  hasService: (service) => this.own.get(service as never) !== undefined,
664
889
  })
665
890
  if (refused !== undefined) return refused
666
891
  const declared = nativesOf(pulled.manifest)
667
892
  return await this.install(
668
- pulled.stored.name,
893
+ folderIn(pulled.stored.name),
669
894
  pulled.stored.version,
670
895
  pulled.stored.integrity,
671
896
  files,
@@ -677,6 +902,60 @@ export class PluginShare extends Service {
677
902
  }
678
903
  }
679
904
 
905
+ /**
906
+ * 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
907
+ * three-way merge (fetched again from where it came from, checked against its recorded integrity, unless the folder is untouched and is the base).
908
+ * Refused, and nothing written, when the release and the person changed the same lines.
909
+ */
910
+ private async planUpdate(
911
+ name: string,
912
+ before: PulledRecord,
913
+ held: string,
914
+ release: readonly PluginFile[],
915
+ target: string,
916
+ ): Promise<{ readonly mine: Tree; readonly merged: MergedTrees } | PullRefused> {
917
+ const mine = treeOf(pluginFiles(target))
918
+ let base = mine
919
+ if (held !== before.digest) {
920
+ const scratch = mkdtempSync(join(this.own.appInstance.home, 'plugin-base-'))
921
+ try {
922
+ const pulled = await pullPlugin(
923
+ readSource(before.source, this.own.appInstance.root).source,
924
+ {
925
+ store: new PluginStore(scratch),
926
+ releases: this.releases,
927
+ registry: this.npmRegistry,
928
+ download: this.download,
929
+ },
930
+ { expectIntegrity: before.integrity },
931
+ )
932
+ base = treeOf(
933
+ readTarball(readFileSync(pulled.stored.path)).map(({ path, content }) => ({
934
+ path,
935
+ bytes: content,
936
+ kind: 'file' as const,
937
+ })),
938
+ )
939
+ } catch (cause) {
940
+ return refuse(
941
+ 'folder-exists',
942
+ `plugins/${name} has changes of your own, and the release it was pulled from could not be fetched to keep them: ${reasonOf(cause)}`,
943
+ `check the internet connection and pull again, or move plugins/${name} out of plugins/ and pull again`,
944
+ )
945
+ } finally {
946
+ rmSync(scratch, { recursive: true, force: true })
947
+ }
948
+ }
949
+ const merged = mergeTrees(base, mine, treeOf(release))
950
+ if (merged.conflicts.length > 0)
951
+ return refuse(
952
+ 'folder-exists',
953
+ `plugins/${name} has changes of your own to ${merged.conflicts.join(', ')}, and the new release changes ${merged.conflicts.length === 1 ? 'it' : 'them'} too`,
954
+ `plugins/${name} is untouched: move it out of plugins/ and pull again, then bring your changes back by hand`,
955
+ )
956
+ return { mine, merged }
957
+ }
958
+
680
959
  /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */
681
960
  private async install(
682
961
  name: string,
@@ -700,22 +979,36 @@ export class PluginShare extends Service {
700
979
  const wrote = !existsSync(target)
701
980
  const before = this.recorded(name)
702
981
  const held = wrote ? undefined : digestFolder(target)
982
+ let update: { readonly mine: Tree; readonly merged: MergedTrees } | undefined
703
983
  if (held !== undefined && held !== digest) {
704
- const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`
705
- // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.
706
- const next =
707
- before !== undefined && held === before.digest
708
- ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`
709
- : `keep it, or move plugins/${name} out of plugins/ and pull again`
710
- return refuse(
711
- 'folder-exists',
712
- `plugins/${name} holds a different copy of this plugin, ${holder}`,
713
- next,
714
- )
984
+ // 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.
985
+ const sameRepo =
986
+ before !== undefined &&
987
+ source !== undefined &&
988
+ repoOf(before.source) !== undefined &&
989
+ repoOf(before.source) === repoOf(source)
990
+ if (before !== undefined && sameRepo && before.digest !== digest) {
991
+ const planned = await this.planUpdate(name, before, held, files, target)
992
+ if ('refusal' in planned) return planned
993
+ update = planned
994
+ } else {
995
+ const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`
996
+ // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.
997
+ const next =
998
+ before !== undefined && held === before.digest
999
+ ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`
1000
+ : `keep it, or move plugins/${name} out of plugins/ and pull again`
1001
+ return refuse(
1002
+ 'folder-exists',
1003
+ `plugins/${name} holds a different copy of this plugin, ${holder}`,
1004
+ next,
1005
+ )
1006
+ }
715
1007
  }
716
1008
  const liveBefore = this.live.get(name)
717
1009
  this.live.set(name, digest)
718
1010
  if (wrote) renameSync(incoming, target)
1011
+ else if (update !== undefined) applyTree(target, update.mine, update.merged.files)
719
1012
  // 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
720
1013
  // 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.
721
1014
  const remembered = source !== undefined && this.remember(name, { source, integrity, digest })
@@ -726,6 +1019,7 @@ export class PluginShare extends Service {
726
1019
  if (native !== undefined && (nativeAction === 'downloaded' || nativeAction === 'linked'))
727
1020
  releaseNative(native, this.places, nativeAction === 'linked')
728
1021
  if (wrote) rmSync(target, { recursive: true, force: true })
1022
+ else if (update !== undefined) applyTree(target, update.merged.files, update.mine)
729
1023
  if (remembered) this.remember(name, before)
730
1024
  if (liveBefore === undefined) this.live.delete(name)
731
1025
  else this.live.set(name, liveBefore)
@@ -771,6 +1065,9 @@ export class PluginShare extends Service {
771
1065
  action: result.action,
772
1066
  state: result.state,
773
1067
  remembered,
1068
+ ...(update === undefined || update.merged.kept.length === 0
1069
+ ? {}
1070
+ : { kept: update.merged.kept }),
774
1071
  ...this.keepNative(name, native, nativeBefore, nativeAction),
775
1072
  }
776
1073
  } finally {
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 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
3
+ * 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
4
+ * 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.
5
+ */
6
+ import { spawnSync } from 'node:child_process'
7
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+
11
+ /** A plugin's files by their `/` path. */
12
+ export type Tree = ReadonlyMap<string, Uint8Array>
13
+
14
+ /** Merge one text file three ways: the merged bytes, or undefined when the two changes overlap. */
15
+ export type MergeFile = (
16
+ base: Uint8Array,
17
+ mine: Uint8Array,
18
+ theirs: Uint8Array,
19
+ ) => Uint8Array | undefined
20
+
21
+ export interface MergedTrees {
22
+ /** What the folder holds afterwards. */
23
+ readonly files: ReadonlyMap<string, Uint8Array>
24
+ /** The files that keep something of the person's own: their edit stands, or it was merged with the release's change. */
25
+ readonly kept: readonly string[]
26
+ /** The files whose changes overlap, or that one side changed and the other removed: nothing is written while there is one. */
27
+ readonly conflicts: readonly string[]
28
+ }
29
+
30
+ const same = (a: Uint8Array | undefined, b: Uint8Array | undefined): boolean =>
31
+ a === undefined || b === undefined ? a === b : Buffer.from(a).equals(b)
32
+
33
+ /** git's own three-way line merge. A binary file, a conflict, or no git on this computer is "cannot merge". */
34
+ export const gitMergeFile: MergeFile = (base, mine, theirs) => {
35
+ if ([base, mine, theirs].some((bytes) => bytes.includes(0))) return undefined
36
+ const dir = mkdtempSync(join(tmpdir(), 'plugin-merge-'))
37
+ try {
38
+ const [b, m, t] = ['base', 'mine', 'theirs'].map((name) => join(dir, name)) as [
39
+ string,
40
+ string,
41
+ string,
42
+ ]
43
+ writeFileSync(b, base)
44
+ writeFileSync(m, mine)
45
+ writeFileSync(t, theirs)
46
+ // `-p` prints the result; the status is the number of conflicts (0 = clean), negative on an error.
47
+ const result = spawnSync('git', ['merge-file', '-p', m, b, t], { maxBuffer: 64 * 1024 * 1024 })
48
+ return result.error === undefined && result.status === 0 ? result.stdout : undefined
49
+ } finally {
50
+ rmSync(dir, { recursive: true, force: true })
51
+ }
52
+ }
53
+
54
+ /** 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). */
55
+ export function mergeTrees(
56
+ base: Tree,
57
+ mine: Tree,
58
+ theirs: Tree,
59
+ mergeFile: MergeFile = gitMergeFile,
60
+ ): MergedTrees {
61
+ const files = new Map<string, Uint8Array>()
62
+ const kept: string[] = []
63
+ const conflicts: string[] = []
64
+ const paths = [...new Set([...base.keys(), ...mine.keys(), ...theirs.keys()])].sort()
65
+ for (const path of paths) {
66
+ const [b, m, t] = [base.get(path), mine.get(path), theirs.get(path)]
67
+ const put = (bytes: Uint8Array | undefined): void => {
68
+ if (bytes !== undefined) files.set(path, bytes)
69
+ }
70
+ if (same(m, t)) put(m)
71
+ else if (same(m, b)) put(t)
72
+ else if (same(t, b)) {
73
+ put(m)
74
+ kept.push(path)
75
+ } else if (b !== undefined && m !== undefined && t !== undefined) {
76
+ const merged = mergeFile(b, m, t)
77
+ if (merged === undefined) conflicts.push(path)
78
+ else {
79
+ files.set(path, merged)
80
+ kept.push(path)
81
+ }
82
+ } else conflicts.push(path)
83
+ }
84
+ return { files, kept, conflicts }
85
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 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
3
+ * (`.npmrc`). Nothing here reads or stores a token; a missing npm or login is reported with what to do.
4
+ */
5
+ import { spawnSync } from 'node:child_process'
6
+ import { type NpmPublishPort, npmCli } from '@acryldev/plugin-hub-core'
7
+
8
+ /** The registry's login and the publish, as the plan and the confirmed publish use them. */
9
+ export interface NpmPort extends NpmPublishPort {
10
+ /** The account the person's npm is signed in as on `registry`. @throws naming `npm login` when it is not signed in. */
11
+ login(registry: string): string
12
+ }
13
+
14
+ export function npmWithLogin(): NpmPort {
15
+ return {
16
+ ...npmCli(),
17
+ login(registry) {
18
+ // On Windows npm is a .cmd file, which Node runs only through a shell; the arguments are ours, never the person's text.
19
+ const result = spawnSync('npm', ['whoami', '--registry', registry], {
20
+ encoding: 'utf8',
21
+ shell: process.platform === 'win32',
22
+ env: { ...process.env, npm_config_update_notifier: 'false' },
23
+ })
24
+ if (result.error !== undefined)
25
+ throw new Error(
26
+ 'npm is not available here: install Node.js (https://nodejs.org), which includes npm, and sign in with: npm login',
27
+ )
28
+ const account = (result.stdout ?? '').trim()
29
+ if (result.status !== 0 || account === '') {
30
+ const last =
31
+ (result.stderr ?? '')
32
+ .trim()
33
+ .split('\n')
34
+ .filter((line) => !/^npm (notice|warn)/iu.test(line))
35
+ .at(-1) ?? 'not signed in'
36
+ throw new Error(
37
+ `npm whoami failed: ${last} (sign in with: npm login --registry ${registry})`,
38
+ )
39
+ }
40
+ return account
41
+ },
42
+ }
43
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acryldev/plugin-share",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Share plugins between people. Pull one someone released into the running app: fetched without running anything, checked by digest and for every OS, then installed live. Publish one, only as a plan a person confirmed.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,10 +30,15 @@ export function packageManifest(
30
30
  ? {}
31
31
  : {
32
32
  license: release.license,
33
- repository: {
34
- type: 'git',
35
- url: `git+https://github.com/${release.owner}/${release.repo}.git`,
36
- },
33
+ // An npm package has no repository of its own to name.
34
+ ...(release.owner === undefined || release.repo === undefined
35
+ ? {}
36
+ : {
37
+ repository: {
38
+ type: 'git',
39
+ url: `git+https://github.com/${release.owner}/${release.repo}.git`,
40
+ },
41
+ }),
37
42
  }),
38
43
  type: 'module',
39
44
  exports: { '.': './index.ts', './package.json': './package.json' },
@@ -47,8 +52,9 @@ export function packageManifest(
47
52
 
48
53
  /** Where a package is going to be released: written in now, so what is planned is byte for byte what is released. */
49
54
  export interface PackageRelease {
50
- readonly owner: string
51
- readonly repo: string
55
+ /** The GitHub repository the package is released from; absent for npm. */
56
+ readonly owner?: string
57
+ readonly repo?: string
52
58
  readonly license: string
53
59
  }
54
60
 
@@ -56,6 +62,8 @@ export interface PackageOptions {
56
62
  /** This version, instead of the one already packaged. */
57
63
  readonly version?: string
58
64
  readonly release?: PackageRelease
65
+ /** The name in the package's `package.json` when it is not the plugin's folder name (npm: `@scope/name`). */
66
+ readonly packageName?: string
59
67
  }
60
68
 
61
69
  export interface PackagedPlugin {
@@ -142,7 +150,7 @@ export async function packagePlugin(
142
150
  try {
143
151
  writeFileSync(
144
152
  join(target, 'package.json'),
145
- `${JSON.stringify(packageManifest(name, description, version, options.release), null, 2)}\n`,
153
+ `${JSON.stringify(packageManifest(options.packageName ?? name, description, version, options.release), null, 2)}\n`,
146
154
  )
147
155
  if (!existsSync(join(target, 'README.md'))) {
148
156
  writeFileSync(
@@ -2,9 +2,15 @@
2
2
  * 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.
3
3
  */
4
4
  import type { PublishGitPort, RepositoryHostPort } from '@acryldev/plugin-hub-core'
5
+ import type { NpmPort } from './npm-login.ts'
5
6
 
6
7
  /** Everything that leaves the machine, named before anything does. */
7
8
  export interface PublishPlan {
9
+ /** Where it goes: a GitHub release (absent) or an npm registry. For npm `owner` is the scope and `repo` the plugin's name. */
10
+ readonly target?: 'npm'
11
+ /** npm: the package's name (`@scope/name`) and the registry it is published to. */
12
+ readonly package?: string
13
+ readonly registry?: string
8
14
  readonly owner: string
9
15
  readonly repo: string
10
16
  readonly version: string
@@ -46,24 +52,39 @@ export interface PublishOptions {
46
52
  readonly owner?: string
47
53
  /** The license the plugin is offered under, as an SPDX id; MIT when absent. The plan shows it before the person says yes. */
48
54
  readonly license?: string
55
+ /** `npm`: publish to an npm registry with the person's own npm login instead of to GitHub. */
56
+ readonly to?: 'npm'
57
+ /** npm: the scope of the package; the account npm is signed in as when absent. */
58
+ readonly scope?: string
59
+ /** npm: the registry; the public one when absent. */
60
+ readonly registry?: string
49
61
  }
50
62
 
51
63
  /** Where a publish goes through: the person's own `gh` and `git`. A test passes stand-ins, so no test publishes. */
52
64
  export interface PublishPorts {
53
65
  readonly host: RepositoryHostPort
54
66
  readonly git: PublishGitPort
67
+ /** The person's own npm (`npm whoami`, `npm publish`); the default is their installed npm. A test passes a stand-in. */
68
+ readonly npm?: NpmPort
55
69
  }
56
70
 
57
71
  /** The line a friend copies: it names the bytes, so the check comes for free. */
58
72
  export const pullLineOf = (owner: string, repo: string, version: string, digest: string): string =>
59
73
  `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`
60
74
 
75
+ /** The line a friend copies for an npm package. */
76
+ export const npmPullLineOf = (name: string, version: string, digest: string): string =>
77
+ `npm run acryl -- plugin pull npm:${name}@${version}@sha256:${digest}`
78
+
61
79
  /**
62
80
  * 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.
63
81
  * 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.
64
82
  */
65
83
  export function samePlan(a: PublishPlan, b: PublishPlan): boolean {
66
84
  return (
85
+ a.target === b.target &&
86
+ a.package === b.package &&
87
+ a.registry === b.registry &&
67
88
  a.owner === b.owner &&
68
89
  a.repo === b.repo &&
69
90
  a.version === b.version &&
@@ -0,0 +1,62 @@
1
+ /**
2
+ * `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
3
+ * 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
4
+ * download must pass: a release changed after the registry read it is refused. Pure; the caller fetches the index.
5
+ */
6
+
7
+ export const REGISTRY_INDEX_URL = 'https://cordisplugins.github.io/registry/index.json'
8
+
9
+ /** What a pull needs of one registry entry (the rest of the entry is for the page that shows it). */
10
+ export interface RegistryHit {
11
+ /** `github:<owner>/<repo>@<version>`: what another machine fetches, and what the app records. */
12
+ readonly source: string
13
+ /** The sha512 the registry lists for the release file. */
14
+ readonly integrity: string
15
+ }
16
+
17
+ export type RegistryLookup =
18
+ | { readonly ok: true; readonly hit: RegistryHit }
19
+ | { readonly ok: false; readonly reason: string; readonly next: string }
20
+
21
+ const GITHUB_REPO =
22
+ /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*?)(?:\.git)?\/?$/u
23
+
24
+ /** Find `id` (or the package name, `@scope/name`) in the index text; its release as a source, or why there is none. */
25
+ export function lookUpRegistry(indexText: string, id: string): RegistryLookup {
26
+ let entries: unknown
27
+ try {
28
+ entries = (JSON.parse(indexText) as { entries?: unknown }).entries
29
+ } catch {
30
+ entries = undefined
31
+ }
32
+ if (!Array.isArray(entries))
33
+ return {
34
+ ok: false,
35
+ reason: 'the registry answered in a way this app does not understand',
36
+ next: 'try again later, or pull github:<owner>/<repo> from the plugin page',
37
+ }
38
+ const wanted = id.trim().toLowerCase()
39
+ const entry = entries.find(
40
+ (item: { id?: unknown; name?: unknown }) =>
41
+ typeof item?.id === 'string' &&
42
+ (item.id.toLowerCase() === wanted ||
43
+ (typeof item.name === 'string' && item.name.toLowerCase() === wanted)),
44
+ ) as { repo?: unknown; version?: unknown; integrity?: unknown } | undefined
45
+ if (entry === undefined)
46
+ return {
47
+ ok: false,
48
+ reason: `the registry lists no plugin ${id}`,
49
+ next: 'copy the id from https://cordisplugins.github.io, or pull github:<owner>/<repo>',
50
+ }
51
+ const repo = typeof entry.repo === 'string' ? GITHUB_REPO.exec(entry.repo) : null
52
+ if (repo === null || typeof entry.version !== 'string' || typeof entry.integrity !== 'string')
53
+ return {
54
+ ok: false,
55
+ reason: `the registry's entry for ${id} does not name a GitHub release this app can pull`,
56
+ next: 'open its page on https://cordisplugins.github.io for how to install it',
57
+ }
58
+ return {
59
+ ok: true,
60
+ hit: { source: `github:${repo[1]}/${repo[2]}@${entry.version}`, integrity: entry.integrity },
61
+ }
62
+ }