@livespace/plugin-studio 0.0.0-stage → 0.1.0

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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -2
  3. package/dist/auth.js +220 -0
  4. package/dist/cli.js +67 -0
  5. package/dist/keys.js +42 -0
  6. package/dist/manifest.js +16 -0
  7. package/dist/page/domain/connection.js +2 -0
  8. package/dist/page/domain/display.js +38 -0
  9. package/dist/page/domain/draft.js +80 -0
  10. package/dist/page/domain/failures-store.js +41 -0
  11. package/dist/page/domain/failures.js +75 -0
  12. package/dist/page/domain/layout-store.js +119 -0
  13. package/dist/page/domain/log-store.js +37 -0
  14. package/dist/page/domain/navigation-store.js +16 -0
  15. package/dist/page/domain/plugin-data.js +70 -0
  16. package/dist/page/domain/plugin-store.js +257 -0
  17. package/dist/page/domain/probe-store.js +100 -0
  18. package/dist/page/domain/profile-session.js +115 -0
  19. package/dist/page/domain/profile-store.js +21 -0
  20. package/dist/page/domain/samples.js +221 -0
  21. package/dist/page/domain/secrets-store.js +159 -0
  22. package/dist/page/domain/secrets.js +135 -0
  23. package/dist/page/domain/settings-data.js +64 -0
  24. package/dist/page/domain/settings-session.js +206 -0
  25. package/dist/page/domain/settings-store.js +62 -0
  26. package/dist/page/domain/slot-store.js +50 -0
  27. package/dist/page/domain/studio.js +121 -0
  28. package/dist/page/domain/surface-store.js +71 -0
  29. package/dist/page/domain/toasts-store.js +60 -0
  30. package/dist/page/domain/view-data.js +122 -0
  31. package/dist/page/domain/view-store.js +132 -0
  32. package/dist/page/host.css +907 -0
  33. package/dist/page/index.html +31 -0
  34. package/dist/page/main.js +31 -0
  35. package/dist/page/plugin-studio-logo.svg +4 -0
  36. package/dist/page/reload.svg +1 -0
  37. package/dist/page/transport/browser-storage.js +41 -0
  38. package/dist/page/transport/embed.js +142 -0
  39. package/dist/page/transport/plugin-keys.js +68 -0
  40. package/dist/page/transport/studio-api.js +74 -0
  41. package/dist/page/ui/app.js +61 -0
  42. package/dist/page/ui/boot.js +44 -0
  43. package/dist/page/ui/brand.js +3 -0
  44. package/dist/page/ui/context.js +11 -0
  45. package/dist/page/ui/json-field.js +19 -0
  46. package/dist/page/ui/json-tokens.js +40 -0
  47. package/dist/page/ui/json-view.js +11 -0
  48. package/dist/page/ui/memo.js +23 -0
  49. package/dist/page/ui/messages.js +34 -0
  50. package/dist/page/ui/page-switcher.js +11 -0
  51. package/dist/page/ui/plugin-frame.js +43 -0
  52. package/dist/page/ui/profile-page.js +13 -0
  53. package/dist/page/ui/resize-handle.js +63 -0
  54. package/dist/page/ui/root.js +9 -0
  55. package/dist/page/ui/section.js +19 -0
  56. package/dist/page/ui/settings/config-form.js +59 -0
  57. package/dist/page/ui/settings/secret-field.js +22 -0
  58. package/dist/page/ui/settings/settings-page.js +60 -0
  59. package/dist/page/ui/sidebar/custom-settings-section.js +10 -0
  60. package/dist/page/ui/sidebar/failures-section.js +27 -0
  61. package/dist/page/ui/sidebar/installation-section.js +30 -0
  62. package/dist/page/ui/sidebar/metadata-section.js +9 -0
  63. package/dist/page/ui/sidebar/plugin-section.js +18 -0
  64. package/dist/page/ui/sidebar/preferences-section.js +16 -0
  65. package/dist/page/ui/sidebar/record-section.js +17 -0
  66. package/dist/page/ui/sidebar/viewer-section.js +8 -0
  67. package/dist/page/ui/sidebar-group.js +4 -0
  68. package/dist/page/ui/splash.js +6 -0
  69. package/dist/page/ui/status.js +10 -0
  70. package/dist/page/ui/surface.js +23 -0
  71. package/dist/page/ui/theme.js +13 -0
  72. package/dist/page/ui/toasts.js +31 -0
  73. package/dist/page/ui/top-bar.js +37 -0
  74. package/dist/server.js +519 -0
  75. package/dist/start.js +108 -0
  76. package/package.json +55 -5
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The failure switches: what the studio answers when the plugin asks for API credentials or a
3
+ * plugin token, and how the dev account's exchange refuses, so a plugin and its backend can be
4
+ * tried against each failure Livespace can give. No DOM here.
5
+ */
6
+ const CREDENTIAL_CODES = [
7
+ "bad_request",
8
+ "unauthenticated",
9
+ "forbidden",
10
+ "not_found",
11
+ "conflict",
12
+ "server_error",
13
+ ];
14
+ export const NO_ANSWER = "no-answer";
15
+ export const CREDENTIALS_CHOICES = [
16
+ ...CREDENTIAL_CODES.map((code) => ({
17
+ value: code,
18
+ label: `Refuse: ${code}`,
19
+ })),
20
+ { value: NO_ANSWER, label: "No answer (the SDK times out)" },
21
+ ];
22
+ export const TOKEN = "token";
23
+ export const EVERY_OTHER_EXPIRED = "every-other-expired";
24
+ export const TOKEN_CHOICES = [
25
+ { value: TOKEN, label: "A token for the viewer" },
26
+ {
27
+ value: EVERY_OTHER_EXPIRED,
28
+ label: "Every other token already expired (exercises the retry after a 401)",
29
+ },
30
+ ...[...CREDENTIAL_CODES, "not_purchased"].map((code) => ({
31
+ value: code,
32
+ label: `Refuse: ${code}`,
33
+ })),
34
+ { value: NO_ANSWER, label: "No answer (the SDK times out)" },
35
+ ];
36
+ export const ACCEPT = "accept";
37
+ export const EXCHANGE_CHOICES = [
38
+ { value: ACCEPT, label: "Exchange it" },
39
+ { value: "not_installed", label: "Refuse: not_installed" },
40
+ { value: "not_purchased", label: "Refuse: not_purchased" },
41
+ { value: "user_not_allowed", label: "Refuse: user_not_allowed" },
42
+ { value: "invalid_client", label: "Refuse: invalid_client" },
43
+ ];
44
+ /** There's no real account behind the studio, so API credentials are always refused. */
45
+ export const DEFAULT_FAILURES = {
46
+ credentials: "unauthenticated",
47
+ token: TOKEN,
48
+ exchange: ACCEPT,
49
+ };
50
+ /** The answer to `request-api-credentials`, or `null` for none at all. */
51
+ export function credentialsAnswer(requestId, choice) {
52
+ if (choice === NO_ANSWER) {
53
+ return null;
54
+ }
55
+ const error = CREDENTIAL_CODES.includes(choice)
56
+ ? choice
57
+ : "unauthenticated";
58
+ return { requestId, error };
59
+ }
60
+ /**
61
+ * What to do with `request-session-token`. "Every other" alternates, starting expired: the SDK
62
+ * keeps a token for its lifetime and asks again after a 401, so the retry gets a good one.
63
+ */
64
+ export function tokenPlan(choice, lastWasExpired) {
65
+ if (choice === TOKEN) {
66
+ return { kind: "token", expired: false };
67
+ }
68
+ if (choice === EVERY_OTHER_EXPIRED) {
69
+ return { kind: "token", expired: !lastWasExpired };
70
+ }
71
+ if (choice === NO_ANSWER) {
72
+ return { kind: "none" };
73
+ }
74
+ return { kind: "error", code: choice };
75
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The page's frame: how wide the sidebar and the messages pane are, whether the messages pane is
3
+ * shown, and which sidebar sections are open. Remembered in this browser.
4
+ *
5
+ * Widths are kept as asked for and fitted to the window when read, so a narrower window squeezes
6
+ * the panes without forgetting what they were.
7
+ */
8
+ import { batch, computed, effect, signal, } from "@preact/signals";
9
+ export const MIN_SIDEBAR_PX = 240;
10
+ export const DEFAULT_SIDEBAR_PX = 320;
11
+ export const MIN_MESSAGES_PX = 240;
12
+ export const DEFAULT_MESSAGES_PX = 360;
13
+ /** The least the main area keeps: a 420 px column and its padding. */
14
+ export const MIN_MAIN_PX = 480;
15
+ /** Each resize handle's width. */
16
+ export const HANDLE_PX = 6;
17
+ /** How far an arrow key moves a handle. */
18
+ export const KEY_STEP_PX = 16;
19
+ export const DEFAULT_LAYOUT = {
20
+ sidebarWidth: DEFAULT_SIDEBAR_PX,
21
+ messages: true,
22
+ messagesWidth: DEFAULT_MESSAGES_PX,
23
+ sections: {},
24
+ };
25
+ /** `value` within [min, max]; when there's no room for both, the minimum wins. */
26
+ const clamp = (value, min, max) => Math.max(min, Math.min(value, max));
27
+ const finiteOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
28
+ export class LayoutStore {
29
+ storage;
30
+ viewportWidth;
31
+ #sidebarWidth;
32
+ #messagesShown;
33
+ #messagesWidth;
34
+ #sections;
35
+ #stopSaving;
36
+ /** The sidebar's width, fitted to the window. */
37
+ sidebarWidth;
38
+ /** The messages pane's width, fitted to the window and the sidebar. */
39
+ messagesWidth;
40
+ /** How much of the window's right edge the messages pane covers: 0 when hidden. */
41
+ messagesOffset;
42
+ constructor(storage,
43
+ /** The window's width, kept current by the page. */
44
+ viewportWidth) {
45
+ this.storage = storage;
46
+ this.viewportWidth = viewportWidth;
47
+ const saved = storage.read(DEFAULT_LAYOUT);
48
+ this.#sidebarWidth = signal(finiteOr(saved.sidebarWidth, DEFAULT_SIDEBAR_PX));
49
+ this.#messagesShown = signal(saved.messages !== false);
50
+ this.#messagesWidth = signal(finiteOr(saved.messagesWidth, DEFAULT_MESSAGES_PX));
51
+ this.#sections = signal(saved.sections && typeof saved.sections === "object"
52
+ ? { ...saved.sections }
53
+ : {});
54
+ this.sidebarWidth = computed(() => clamp(this.#sidebarWidth.value, MIN_SIDEBAR_PX, this.#maxSidebar()));
55
+ this.messagesWidth = computed(() => clamp(this.#messagesWidth.value, MIN_MESSAGES_PX, this.#maxMessages()));
56
+ this.messagesOffset = computed(() => this.#messagesShown.value ? this.messagesWidth.value + HANDLE_PX : 0);
57
+ // Saves what was asked for, not what the window allows.
58
+ this.#stopSaving = effect(() => {
59
+ this.storage.write({
60
+ sidebarWidth: this.#sidebarWidth.value,
61
+ messages: this.#messagesShown.value,
62
+ messagesWidth: this.#messagesWidth.value,
63
+ sections: this.#sections.value,
64
+ });
65
+ });
66
+ }
67
+ get messagesShown() {
68
+ return this.#messagesShown;
69
+ }
70
+ get sections() {
71
+ return this.#sections;
72
+ }
73
+ /** The widest the sidebar may be: half the window, and room left for the rest. */
74
+ #maxSidebar() {
75
+ const width = this.viewportWidth.value;
76
+ const messages = this.#messagesShown.value
77
+ ? this.#messagesWidth.value + HANDLE_PX
78
+ : 0;
79
+ return Math.min(width * 0.5, width - messages - HANDLE_PX - MIN_MAIN_PX);
80
+ }
81
+ #maxMessages() {
82
+ const width = this.viewportWidth.value;
83
+ return Math.min(width * 0.6, width - this.sidebarWidth.value - 2 * HANDLE_PX - MIN_MAIN_PX);
84
+ }
85
+ /** Resizes the sidebar; a drag past the limits stops at them. */
86
+ resizeSidebar = (width) => {
87
+ this.#sidebarWidth.value = clamp(width, MIN_SIDEBAR_PX, this.#maxSidebar());
88
+ };
89
+ resizeMessages = (width) => {
90
+ this.#messagesWidth.value = clamp(width, MIN_MESSAGES_PX, this.#maxMessages());
91
+ };
92
+ /** One arrow-key step: `1` widens, `-1` narrows. */
93
+ stepSidebar = (direction) => {
94
+ this.resizeSidebar(this.sidebarWidth.value + direction * KEY_STEP_PX);
95
+ };
96
+ stepMessages = (direction) => {
97
+ this.resizeMessages(this.messagesWidth.value + direction * KEY_STEP_PX);
98
+ };
99
+ toggleMessages = () => {
100
+ batch(() => {
101
+ // What the pane was squeezed to stays its width when it comes back.
102
+ this.#messagesWidth.value = this.messagesWidth.value;
103
+ this.#messagesShown.value = !this.#messagesShown.value;
104
+ });
105
+ };
106
+ /** Whether a section is open: as it was left, else `initially`. */
107
+ isOpen(name, initially) {
108
+ return this.#sections.value[name] ?? initially;
109
+ }
110
+ setOpen = (name, open) => {
111
+ if (this.#sections.value[name] === open) {
112
+ return;
113
+ }
114
+ this.#sections.value = { ...this.#sections.value, [name]: open };
115
+ };
116
+ dispose() {
117
+ this.#stopSaving();
118
+ }
119
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The message log: every message between the studio and the plugin, both ways, and the studio's
3
+ * own notes. Oldest first; the oldest go once there are too many to keep.
4
+ */
5
+ import { signal } from "@preact/signals";
6
+ /** Enough for a long session; past it, the oldest go. */
7
+ export const MAX_ENTRIES = 2000;
8
+ export class LogStore {
9
+ now;
10
+ #entries = signal([]);
11
+ #nextId = 1;
12
+ constructor(now = Date.now) {
13
+ this.now = now;
14
+ }
15
+ get entries() {
16
+ return this.#entries;
17
+ }
18
+ /** Adds an entry. An arrow, as the plugin channel and old page code call it bare. */
19
+ append = (direction, type, payload, source) => {
20
+ const entry = {
21
+ id: this.#nextId++,
22
+ at: this.now(),
23
+ direction,
24
+ type,
25
+ ...(payload === undefined ? {} : { payload }),
26
+ ...(source === undefined ? {} : { source }),
27
+ };
28
+ const entries = this.#entries.value;
29
+ this.#entries.value =
30
+ entries.length < MAX_ENTRIES
31
+ ? [...entries, entry]
32
+ : [...entries.slice(entries.length - MAX_ENTRIES + 1), entry];
33
+ };
34
+ clear = () => {
35
+ this.#entries.value = [];
36
+ };
37
+ }
@@ -0,0 +1,16 @@
1
+ /** Which page is shown: the profile, or the settings screen. It follows the address's hash. */
2
+ import { signal } from "@preact/signals";
3
+ export const pageFor = (hash) => hash === "#settings" ? "settings" : "profile";
4
+ export class NavigationStore {
5
+ #page;
6
+ constructor(hash) {
7
+ this.#page = signal(pageFor(hash));
8
+ }
9
+ get page() {
10
+ return this.#page;
11
+ }
12
+ /** The hash changed: the page follows. */
13
+ follow = (hash) => {
14
+ this.#page.value = pageFor(hash);
15
+ };
16
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The Plugin section's logic: the address checked as Livespace checks one, a pasted catalog
3
+ * manifest read for what the studio needs from it, and the env values a backend sets. No DOM.
4
+ */
5
+ import { RECORD_CHOICES } from "./view-data.js";
6
+ /** Why an address can't be embedded, or undefined when it can (as the server checks it too). */
7
+ export function urlProblem(text, devOrigin) {
8
+ let url;
9
+ try {
10
+ url = new URL(text.trim());
11
+ }
12
+ catch {
13
+ return "That isn't an address: http://… or https://…";
14
+ }
15
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
16
+ return "The address must start with http:// or https://.";
17
+ }
18
+ if (url.origin === devOrigin) {
19
+ return "That's the studio's own origin. Livespace refuses a plugin on its own origin.";
20
+ }
21
+ return undefined;
22
+ }
23
+ /** A catalog manifest, written as JSON, read for its id and where it may go. */
24
+ export function readManifest(text) {
25
+ let value;
26
+ try {
27
+ value = JSON.parse(text);
28
+ }
29
+ catch (error) {
30
+ return { ok: false, reason: error.message };
31
+ }
32
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
33
+ return { ok: false, reason: "A manifest is a JSON object." };
34
+ }
35
+ const manifest = value;
36
+ const id = manifest.id;
37
+ const types = manifest.allowedObjectTypes;
38
+ return {
39
+ ok: true,
40
+ manifest,
41
+ clientId: typeof id === "string" && id !== "" ? `plugin:${id}` : undefined,
42
+ objectTypes: Array.isArray(types)
43
+ ? types.filter((type) => typeof type === "string")
44
+ : null,
45
+ };
46
+ }
47
+ /**
48
+ * The record choices a catalog plugin can be shown with: the types its manifest lists, or every
49
+ * type and no record when it lists none (`null`, anywhere). A plugin added by URL gets them all.
50
+ */
51
+ export function recordChoicesFor(objectTypes) {
52
+ if (objectTypes === null) {
53
+ return RECORD_CHOICES;
54
+ }
55
+ return RECORD_CHOICES.filter((choice) => choice.value !== "none" && objectTypes.includes(choice.value));
56
+ }
57
+ /** The first choice a list allows, when the current one isn't among them. */
58
+ export function allowedChoice(current, choices) {
59
+ return choices.some((choice) => choice.value === current)
60
+ ? current
61
+ : (choices[0]?.value ?? "none");
62
+ }
63
+ /** What a backend's environment needs to trust the dev account. */
64
+ export function backendEnv(devOrigin, clientId) {
65
+ return [
66
+ `LIVESPACE_KEYS_URL=${devOrigin}/core/api/auth/jwks`,
67
+ `LIVESPACE_AUTH_URL=${devOrigin}`,
68
+ `PLUGIN_CLIENT_ID=${clientId}`,
69
+ ].join("\n");
70
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * What the studio says the plugin is: its address, its client id, how accounts add it (which
3
+ * decides where its keys are), and its catalog manifest. The server holds it, for the tokens and
4
+ * the exchange. The address is also kept in this browser. Also what the plugin last declared about
5
+ * where it fits, its metadata, until it's embedded afresh.
6
+ */
7
+ import { batch, computed, signal, } from "@preact/signals";
8
+ import { Refused, } from "../transport/studio-api.js";
9
+ import { timers, Draft } from "./draft.js";
10
+ import { backendEnv, readManifest, recordChoicesFor, urlProblem, } from "./plugin-data.js";
11
+ export const NO_ADDRESS = { pluginUrl: null, cliUrl: null };
12
+ /** Until the server answers, a plugin with no address. */
13
+ const UNKNOWN = {
14
+ pluginUrl: null,
15
+ clientId: "",
16
+ distribution: "url",
17
+ manifest: null,
18
+ };
19
+ export class PluginStore {
20
+ deps;
21
+ #state = signal(UNKNOWN);
22
+ #addressProblem = signal(undefined);
23
+ #clientIdProblem = signal(undefined);
24
+ #manifestNote = signal(undefined);
25
+ #reloads = signal(0);
26
+ #metadata = signal(null);
27
+ /** The client id as typed, sent once typing pauses. */
28
+ clientIdDraft;
29
+ /** The catalog manifest as typed; one that reads as JSON is sent. */
30
+ manifestDraft;
31
+ pluginUrl;
32
+ /** The plugin's origin, which its messages must come from. */
33
+ pluginOrigin;
34
+ clientId;
35
+ distribution;
36
+ /** A catalog plugin's manifest, read; `undefined` for one added by URL, or no manifest. */
37
+ catalogManifest;
38
+ /** `plugin:<id>` from a catalog manifest, when it differs from the client id. */
39
+ suggestedClientId;
40
+ /**
41
+ * Where it can be installed, as how accounts add it decides: by URL, where the plugin declares
42
+ * (`supportedContextTypes`); from the catalog, where its manifest says (`allowedObjectTypes`).
43
+ * Every type and the apps menu when nothing says otherwise.
44
+ */
45
+ recordChoices;
46
+ /** What a backend's environment needs, to trust the dev account. */
47
+ env;
48
+ constructor(deps) {
49
+ this.deps = deps;
50
+ const scheduler = deps.scheduler ?? timers;
51
+ this.pluginUrl = computed(() => this.#state.value.pluginUrl);
52
+ this.pluginOrigin = computed(() => {
53
+ const url = this.pluginUrl.value;
54
+ return url === null ? null : new URL(url).origin;
55
+ });
56
+ this.clientId = computed(() => this.#state.value.clientId);
57
+ this.distribution = computed(() => this.#state.value.distribution);
58
+ this.catalogManifest = computed(() => {
59
+ const { distribution, manifest } = this.#state.value;
60
+ return distribution === "catalog" && manifest !== null
61
+ ? readManifest(JSON.stringify(manifest))
62
+ : undefined;
63
+ });
64
+ this.suggestedClientId = computed(() => {
65
+ const read = this.catalogManifest.value;
66
+ const suggested = read?.ok ? read.clientId : undefined;
67
+ return suggested === this.clientId.value ? undefined : suggested;
68
+ });
69
+ this.recordChoices = computed(() => {
70
+ if (this.distribution.value === "catalog") {
71
+ const read = this.catalogManifest.value;
72
+ return recordChoicesFor(read?.ok ? read.objectTypes : null);
73
+ }
74
+ return recordChoicesFor(this.#metadata.value?.supportedContextTypes ?? null);
75
+ });
76
+ this.env = computed(() => backendEnv(deps.studioOrigin, this.clientId.value));
77
+ this.clientIdDraft = new Draft("", (text) => ({ ok: true, value: text }), "", {
78
+ later: (run, ms) => scheduler.later(() => {
79
+ run();
80
+ void this.#sendClientId();
81
+ }, ms),
82
+ cancel: scheduler.cancel,
83
+ });
84
+ this.manifestDraft = new Draft("", (text) => {
85
+ if (text.trim() === "") {
86
+ return { ok: true, value: null };
87
+ }
88
+ const read = readManifest(text);
89
+ return read.ok ? { ok: true, value: read.manifest } : read;
90
+ }, null, {
91
+ later: (run, ms) => scheduler.later(() => {
92
+ run();
93
+ void this.#sendManifest();
94
+ }, ms),
95
+ cancel: scheduler.cancel,
96
+ });
97
+ }
98
+ /** Bumped for a fresh embed of the same address: the pages are keyed by it. */
99
+ get reloads() {
100
+ return this.#reloads;
101
+ }
102
+ /** Whether `text` is the address embedded now, so embedding it means a reload. */
103
+ isCurrent(text) {
104
+ return text.trim() === this.pluginUrl.value;
105
+ }
106
+ /** Embeds the plugin afresh at the same address: a new iframe, a new handshake. */
107
+ reload = () => {
108
+ batch(() => {
109
+ this.#addressProblem.value = undefined;
110
+ this.#metadata.value = null;
111
+ this.#reloads.value++;
112
+ });
113
+ };
114
+ /**
115
+ * What the plugin last declared about where it fits, already through `sanitizePluginMetadata`;
116
+ * `null` until it's heard, and again once the plugin is embedded afresh.
117
+ */
118
+ get metadata() {
119
+ return this.#metadata;
120
+ }
121
+ hearMetadata = (metadata) => {
122
+ this.#metadata.value = metadata;
123
+ };
124
+ get addressProblem() {
125
+ return this.#addressProblem;
126
+ }
127
+ get clientIdProblem() {
128
+ return this.#clientIdProblem;
129
+ }
130
+ /** What happened to the manifest last: loaded, cleared, or why it wasn't used. */
131
+ get manifestNote() {
132
+ return this.#manifestNote;
133
+ }
134
+ /**
135
+ * Reads the server's state, then the address saved here: it's embedded again unless the
136
+ * studio was started with a different one.
137
+ */
138
+ async load() {
139
+ this.#adopt(await this.deps.api.plugin());
140
+ const startedWith = this.pluginUrl.value;
141
+ const saved = this.deps.storage.read(NO_ADDRESS);
142
+ if (saved.cliUrl !== startedWith) {
143
+ this.deps.storage.write({
144
+ cliUrl: startedWith,
145
+ pluginUrl: startedWith ?? saved.pluginUrl,
146
+ });
147
+ }
148
+ const wanted = this.deps.storage.read(NO_ADDRESS).pluginUrl;
149
+ if (wanted !== null && wanted !== startedWith) {
150
+ if ((await this.setAddress(wanted)) !== undefined) {
151
+ this.#addressProblem.value = undefined;
152
+ this.#saveAddress(startedWith);
153
+ }
154
+ }
155
+ }
156
+ /** Embeds another page; why it can't be, otherwise. */
157
+ setAddress = async (text) => {
158
+ const problem = urlProblem(text, this.deps.studioOrigin) ??
159
+ (await this.#change({ pluginUrl: text.trim() }));
160
+ this.#addressProblem.value = problem;
161
+ if (problem === undefined) {
162
+ this.#saveAddress(this.pluginUrl.value);
163
+ }
164
+ return problem;
165
+ };
166
+ clearAddressProblem = () => {
167
+ this.#addressProblem.value = undefined;
168
+ };
169
+ adoptClientId = async (clientId) => {
170
+ this.clientIdDraft.set(clientId);
171
+ await this.#sendClientId();
172
+ };
173
+ setDistribution = async (distribution) => {
174
+ if (distribution === this.distribution.value) {
175
+ return;
176
+ }
177
+ await this.#change({ distribution });
178
+ this.deps.log("note", `Distribution: ${distribution === "url" ? "added by URL" : "catalog"}`);
179
+ };
180
+ /** Loads the project's `plugin-manifest.json` into the editor, and sends it. */
181
+ loadProjectManifest = async () => {
182
+ const manifest = await this.deps.api.projectManifest();
183
+ if (manifest === null) {
184
+ this.#manifestNote.value =
185
+ "The project has no plugin-manifest.json: `npx @livespace/plugin-cli manifest init` makes one.";
186
+ return;
187
+ }
188
+ this.manifestDraft.set(JSON.stringify(manifest, null, 2));
189
+ await this.#change({ manifest });
190
+ this.#manifestNote.value = "Loaded from plugin-manifest.json.";
191
+ };
192
+ async #sendClientId() {
193
+ const clientId = this.clientIdDraft.committed.value;
194
+ if (clientId === this.clientId.value) {
195
+ this.#clientIdProblem.value = undefined;
196
+ return;
197
+ }
198
+ const problem = await this.#change({ clientId });
199
+ this.#clientIdProblem.value = problem;
200
+ if (problem === undefined) {
201
+ this.deps.log("note", `Client id: ${clientId}`);
202
+ }
203
+ }
204
+ async #sendManifest() {
205
+ const parsed = this.manifestDraft.parsed.value;
206
+ if (!parsed.ok) {
207
+ this.#manifestNote.value = undefined;
208
+ return;
209
+ }
210
+ await this.#change({ manifest: parsed.value });
211
+ this.#manifestNote.value =
212
+ parsed.value === null ? "No manifest: no keys." : undefined;
213
+ }
214
+ /** Sends a change; the server's refusal comes back as text. */
215
+ async #change(changes) {
216
+ try {
217
+ this.#adopt(await this.deps.api.changePlugin(changes));
218
+ return undefined;
219
+ }
220
+ catch (error) {
221
+ if (error instanceof Refused) {
222
+ return error.message;
223
+ }
224
+ throw error;
225
+ }
226
+ }
227
+ #adopt(state) {
228
+ batch(() => {
229
+ const before = this.#state.value;
230
+ this.#state.value = state;
231
+ // Another plugin, or another build of it, declares afresh.
232
+ if (before.pluginUrl !== state.pluginUrl) {
233
+ this.#metadata.value = null;
234
+ }
235
+ // The editors follow the server, unless they're what changed it.
236
+ if (this.clientIdDraft.committed.value !== state.clientId) {
237
+ this.clientIdDraft.set(state.clientId);
238
+ }
239
+ if (before.manifest !== state.manifest && state.manifest !== null) {
240
+ const read = this.manifestDraft.parsed.value;
241
+ const same = read.ok &&
242
+ JSON.stringify(read.value) === JSON.stringify(state.manifest);
243
+ if (!same) {
244
+ this.manifestDraft.set(JSON.stringify(state.manifest, null, 2));
245
+ }
246
+ }
247
+ });
248
+ }
249
+ #saveAddress(pluginUrl) {
250
+ const saved = this.deps.storage.read(NO_ADDRESS);
251
+ this.deps.storage.write({ ...saved, pluginUrl });
252
+ }
253
+ dispose() {
254
+ this.clientIdDraft.dispose();
255
+ this.manifestDraft.dispose();
256
+ }
257
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The config probe: a hidden embed in config mode, as the plugins-2 settings screen makes one, which
3
+ * asks the plugin for its form and hears what it declares about itself. It runs whenever a plugin
4
+ * is embedded, on either page, so what the plugin declares is known from the start: the studio's
5
+ * stand-in for what Livespace learnt when the plugin was installed. One per embed of an address.
6
+ */
7
+ import { MSG_CONFIG_FORM, MSG_PLUGIN_METADATA, isSecretField, isValueField, sanitizeConfigForm, sanitizePluginMetadata, } from "@livespace/plugin-sdk";
8
+ import { batch, computed, effect, signal, } from "@preact/signals";
9
+ import { Embed } from "../transport/embed.js";
10
+ import { CONFIG_FORM_TIMEOUT_MS } from "./settings-data.js";
11
+ export class ProbeStore {
12
+ deps;
13
+ #form = signal(null);
14
+ #unusable = signal(false);
15
+ #timedOut = signal(false);
16
+ formStatus;
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ this.formStatus = computed(() => {
20
+ if (this.#unusable.value) {
21
+ return { kind: "unusable" };
22
+ }
23
+ const form = this.#form.value;
24
+ if (form === null) {
25
+ return this.#timedOut.value ? { kind: "timedOut" } : { kind: "asking" };
26
+ }
27
+ return form.fields.some((field) => isValueField(field) || isSecretField(field))
28
+ ? { kind: "ready" }
29
+ : { kind: "empty" };
30
+ });
31
+ }
32
+ /** The plugin's form, already through `sanitizeConfigForm`; `null` until it answers. */
33
+ get form() {
34
+ return this.#form;
35
+ }
36
+ /**
37
+ * A new embed of the probe: asked afresh, so what the last one said goes. Zero size and
38
+ * transparent in the page, never `display: none`, which may never load.
39
+ */
40
+ connect = (post) => {
41
+ batch(() => {
42
+ this.#form.value = null;
43
+ this.#unusable.value = false;
44
+ this.#timedOut.value = false;
45
+ });
46
+ const { log, view, scheduler } = this.deps;
47
+ const timer = scheduler.later(() => {
48
+ if (this.#form.peek() === null) {
49
+ this.#timedOut.value = true;
50
+ }
51
+ }, CONFIG_FORM_TIMEOUT_MS);
52
+ const embed = new Embed({
53
+ post,
54
+ state: () => ({
55
+ mode: "config",
56
+ preferences: view.preferences.value,
57
+ context: { user: null },
58
+ config: null,
59
+ fullscreen: false,
60
+ }),
61
+ log: (direction, type, payload) => log.append(direction, type, payload, "probe"),
62
+ });
63
+ // The preferences reach it as they change, as on the settings screen.
64
+ const stop = effect(() => {
65
+ view.preferences.value;
66
+ embed.update();
67
+ });
68
+ return {
69
+ receive: (data) => {
70
+ embed.receive(data);
71
+ const { type, payload } = (data ?? {});
72
+ this.#hear(type, payload);
73
+ },
74
+ loaded: () => embed.loaded(),
75
+ dispose: () => {
76
+ stop();
77
+ scheduler.cancel(timer);
78
+ embed.dispose();
79
+ },
80
+ };
81
+ };
82
+ #hear(type, payload) {
83
+ if (type === MSG_CONFIG_FORM) {
84
+ const form = sanitizeConfigForm(payload, { secrets: true });
85
+ batch(() => {
86
+ this.#unusable.value = form === null;
87
+ if (form !== null) {
88
+ this.#form.value = form;
89
+ }
90
+ });
91
+ }
92
+ else if (type === MSG_PLUGIN_METADATA) {
93
+ const { metadata, dropped } = sanitizePluginMetadata(payload);
94
+ if (dropped.length > 0) {
95
+ this.deps.log.append("note", `metadata: dropped ${dropped.join(", ")}, as Livespace would`, undefined, "probe");
96
+ }
97
+ this.deps.metadata.hearMetadata(metadata);
98
+ }
99
+ }
100
+ }