@dooc-dev/dooc 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,6 @@
1
1
  {
2
+ "Site title": "Site title",
3
+ "Edit site title": "Edit site title",
2
4
  "Editor font": "Editor font",
3
5
  "Viewer font": "Viewer font",
4
6
  "Default font": "Default font",
@@ -1,4 +1,6 @@
1
1
  {
2
+ "Site title": "サイト名",
3
+ "Edit site title": "サイト名を編集",
2
4
  "Editor font": "エディターのフォント",
3
5
  "Viewer font": "ビューアーのフォント",
4
6
  "Default font": "標準フォント",
@@ -1,4 +1,6 @@
1
1
  {
2
+ "Site title": "站点名称",
3
+ "Edit site title": "编辑站点名称",
2
4
  "Editor font": "编辑器字体",
3
5
  "Viewer font": "查看器字体",
4
6
  "Default font": "默认字体",
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { escapeHtml } from "../core/html.js";
2
3
  import { isPluginError, PluginError } from "../plugins/oauth.js";
3
4
  import { createPluginRuntime } from "../plugins/runtime.js";
4
5
  import { isLocalToolRequest } from "./editor-tools.js";
@@ -95,7 +96,11 @@ export const createPluginHandler = (plugins, presentation = { mocks: {} }, crede
95
96
  tickets.set(ticket, { plugin, origin, expires: Date.now() + 10 * 60 * 1000 });
96
97
  return `${origin}/api/plugins/login/${plugin}?ticket=${ticket}`;
97
98
  };
98
- const authorizationUrl = (session, plugin, host) => {
99
+ const authorizationUrl = async (session, plugin, host) => {
100
+ if (config.plugins.find((item) => item.id === plugin)?.oauth.deviceAuthorizationUrl) {
101
+ const state = await runtime.connectDevice(session, plugin);
102
+ return `http://${host}/api/plugins/device/${plugin}?state=${state}`;
103
+ }
99
104
  const authorization = new URL(runtime.connect(session, plugin, `http://${host}/api/plugins/callback/${plugin}`));
100
105
  const mock = origins.get(authorization.origin);
101
106
  return mock
@@ -184,10 +189,48 @@ export const createPluginHandler = (plugins, presentation = { mocks: {} }, crede
184
189
  tickets.delete(key);
185
190
  if (!runtime.hasSession(session))
186
191
  createSession();
187
- res.writeHead(303, { location: authorizationUrl(session, ticket.plugin, host) });
192
+ res.writeHead(303, {
193
+ location: await authorizationUrl(session, ticket.plugin, host),
194
+ });
188
195
  res.end();
189
196
  return true;
190
197
  }
198
+ const device = /^\/api\/plugins\/device\/([a-z][a-z0-9-]{0,63})$/.exec(url.pathname);
199
+ if (req.method === "GET" && device?.[1]) {
200
+ if (url.searchParams.getAll("state").length !== 1)
201
+ throw new PluginError(400, "Invalid device authorization");
202
+ const pending = await runtime.pollDevice(session, device[1], url.searchParams.get("state") ?? "");
203
+ if (req.headers.accept === "application/json") {
204
+ send(200, pending ?? { connected: true });
205
+ return true;
206
+ }
207
+ const nonce = randomBytes(16).toString("hex");
208
+ res.setHeader("content-security-policy", `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`);
209
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
210
+ const name = escapeHtml(config.plugins.find((item) => item.id === device[1])?.name ?? device[1]);
211
+ res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Connect ${name}</title>
212
+ <style>html{color-scheme:light dark}body{max-width:32rem;margin:4rem auto;padding:0 1.5rem;font:16px/1.6 system-ui}input{font:1.5rem monospace;max-width:100%;box-sizing:border-box;padding:.5rem}a{color:LinkText}:focus-visible{outline:2px solid LinkText;outline-offset:3px}</style>
213
+ <main><h1>Connect ${name}</h1>${pending ? `<section id="instructions"><p>Enter this code on ${name} to authorize dooc.</p><p><label>Verification code<br><input readonly value="${escapeHtml(pending.userCode)}"></label></p><p><a href="${escapeHtml(pending.verificationUri)}" target="_blank" rel="noopener noreferrer">Continue to ${name}</a></p><noscript><p>After approving, <a href="">check the connection</a>.</p></noscript></section>` : ""}
214
+ <p id="status" role="status">${pending ? "Waiting for authorization…" : "Connected. You can close this tab and return to dooc."}</p></main>
215
+ ${pending
216
+ ? `<script nonce="${nonce}">
217
+ const status = document.getElementById("status");
218
+ async function poll() {
219
+ try {
220
+ const response = await fetch(location.href, {headers:{accept:"application/json"}});
221
+ const data = await response.json();
222
+ if (!response.ok) throw new Error(data.error || "Sign-in failed. Return to dooc and try again.");
223
+ if (data.connected) {
224
+ document.getElementById("instructions").hidden = true;
225
+ status.textContent = "Connected. You can close this tab and return to dooc.";
226
+ } else setTimeout(poll, data.retryAfter * 1000);
227
+ } catch (error) { status.textContent = error.message; }
228
+ }
229
+ setTimeout(poll, ${pending.retryAfter * 1000});
230
+ </script>`
231
+ : ""}</html>`);
232
+ return true;
233
+ }
191
234
  const callback = /^\/api\/plugins\/callback\/([a-z][a-z0-9-]{0,63})$/.exec(url.pathname);
192
235
  if (req.method === "GET" && callback?.[1]) {
193
236
  let cancelled = false;
@@ -231,7 +274,7 @@ export const createPluginHandler = (plugins, presentation = { mocks: {} }, crede
231
274
  (credentials || input.action === "connect" || input.action === "status"))
232
275
  createSession();
233
276
  if (input.action === "connect") {
234
- send(200, { url: authorizationUrl(session, input.plugin, host) });
277
+ send(200, { url: await authorizationUrl(session, input.plugin, host) });
235
278
  }
236
279
  else if (input.action === "status") {
237
280
  send(200, { user: runtime.status(session, input.plugin) ?? null });
@@ -1,4 +1,4 @@
1
- import { filesSnapshot, updateFiles, uploadFile } from "../compiler/files.js";
1
+ import { completeFilePaths, filesSnapshot, updateFiles, uploadFile } from "../compiler/files.js";
2
2
  import { loadProjectFonts } from "../compiler/fonts.js";
3
3
  import { textfilePath, writeTextfile } from "../compiler/textfile.js";
4
4
  import { defaultFilePath, docIconFile, MAX_FILE_UPLOAD_BYTES, parseFileLayout, docFile as sourceDocFile, suggestDocFileName, } from "../core/files.js";
@@ -68,6 +68,7 @@ import { mountPanelResize, mountToolsResize } from "./resize.js";
68
68
  import { resourceIndex, resourceLibraryHtml, resourceTabs } from "./resource-library.js";
69
69
  import { mountSearch, SEARCH_LABELS, searchIndex, searchSections } from "./search.js";
70
70
  import { siteIconResponse } from "./site-icon.js";
71
+ import { siteTitleResponse } from "./site-title.js";
71
72
  import { previewTextfiles, textfileResponse } from "./textfile.js";
72
73
  import { mountThemePickers } from "./theme-picker.js";
73
74
  import { readWorkspaceSource } from "./workspace.js";
@@ -1182,6 +1183,9 @@ body.extensions-over #nav-extensions, body.extensions-over .extensions-dropzone
1182
1183
  const EDIT_CSS = `
1183
1184
  body.git-diff-hidden .cm-lineNumbers :is(.cm-git-added, .cm-git-modified, .cm-git-deleted-start, .cm-git-deleted-end) { box-shadow: none; }
1184
1185
  body.git-diff-hidden .cm-line:is(.cm-git-added, .cm-git-modified, .cm-git-deleted-start, .cm-git-deleted-end) { background-color: transparent; }
1186
+ #site-title[role="button"] { cursor: text; position: relative; }
1187
+ #site-title:focus-visible { outline: 1px solid var(--c-line); }
1188
+ #site-title .nav-rename-form { inset: 0; padding: 0; }
1185
1189
  #site-icon-slot input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
1186
1190
  #site-icon-slot:hover, #site-icon-slot:focus-within, #sidebar-head.over #site-icon-slot { background: var(--c-line); border-radius: 3px; }
1187
1191
  #site-icon-slot:focus-within, #sidebar-head.over #site-icon-slot { outline: 1px solid var(--c-fg-muted); outline-offset: 2px; }
@@ -1856,7 +1860,7 @@ ${opts.publish ? `<meta name="referrer" content="no-referrer"><meta http-equiv="
1856
1860
  <title>${escapeHtml(pageTitle(mode, opts.title, site.title))}</title>
1857
1861
  <script>try{const t=localStorage.getItem("docs-preview:theme");if(t)document.documentElement.dataset.theme=t;const e=localStorage.getItem("docs-editor:theme");if(e)document.documentElement.dataset.editorTheme=e}catch{}</script>
1858
1862
  <style>${fontCss(Boolean(opts.publish))}${CSS}${mode === "edit" ? EDIT_CSS : ""}</style></head>
1859
- <body${mode === "edit" ? ' class="edit"' : ""}><nav id="sidebar"><div id="sidebar-resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="sidebar" aria-label="Resize sidebar" data-i18n-aria-label="Resize sidebar" title="Resize sidebar" data-i18n-title="Resize sidebar"></div><div id="sidebar-head">${siteIcon}<div id="site-title" class="site-title" title="${siteTitle}">${siteTitle}</div><button id="sidebar-toggle" type="button" aria-controls="sidebar-content" aria-expanded="true" title="Close sidebar" data-i18n-title="Close sidebar">${SIDEBAR_ICON}</button></div><div id="sidebar-content"><div id="nav-groups">${nav}</div><div id="nav-status" role="status" aria-live="polite"></div></div></nav>${main}${opts.aside ?? ""}
1863
+ <body${mode === "edit" ? ' class="edit"' : ""}><nav id="sidebar"><div id="sidebar-resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="sidebar" aria-label="Resize sidebar" data-i18n-aria-label="Resize sidebar" title="Resize sidebar" data-i18n-title="Resize sidebar"></div><div id="sidebar-head">${siteIcon}<div id="site-title" class="site-title" title="${siteTitle}"${mode === "edit" ? ` data-title="${escapeHtml(site.title ?? "")}" tabindex="0" role="button" aria-label="Edit site title" data-i18n-aria-label="Edit site title"` : ""}>${siteTitle}</div><button id="sidebar-toggle" type="button" aria-controls="sidebar-content" aria-expanded="true" title="Close sidebar" data-i18n-title="Close sidebar">${SIDEBAR_ICON}</button></div><div id="sidebar-content"><div id="nav-groups">${nav}</div><div id="nav-status" role="status" aria-live="polite"></div></div></nav>${main}${opts.aside ?? ""}
1860
1864
  ${bootScripts}${graphScript}
1861
1865
  <script id="code-grammars" type="application/json">${JSON.stringify(site.codeGrammars ?? []).replace(/</g, "\\u003c")}</script>
1862
1866
  ${opts.publish ? `<script>${inlineScript(opts.publish.codeJs)}</script>` : '<script src="/assets/code.js" defer></script>'}
@@ -1944,6 +1948,7 @@ ${mode === "edit"
1944
1948
  // re-fetch the nav regardless of the outcome (= the display is always a copy of
1945
1949
  // dooc.yaml; no rollback logic).
1946
1950
  // The root placeholder and row buttons open the create form.
1951
+ const t = (key) => window.__docsTranslate?.(key) ?? key;
1947
1952
  const status = document.getElementById("nav-status");
1948
1953
  const setStatus = (message, error) => {
1949
1954
  if (!status) return;
@@ -1956,7 +1961,13 @@ ${mode === "edit"
1956
1961
  const id = (cur && cur.closest(".nav-item").dataset.docId) || "";
1957
1962
  const rp = location.pathname.startsWith("/_statics") ? location.pathname.slice(1) : ["/_git", "/_extensions"].includes(location.pathname) ? location.pathname.slice(1) : location.pathname.startsWith("/_files") ? location.pathname.slice(8).replace(/^\\/|\\/$/g, "") : null;
1958
1963
  const res = await localeFetch("/api/nav?current=" + encodeURIComponent(id) + (rp == null ? "" : "&res=" + encodeURIComponent(rp)));
1959
- if (res.ok) document.getElementById("nav-groups").innerHTML = (await res.json()).html;
1964
+ if (res.ok) {
1965
+ const data = await res.json();
1966
+ document.getElementById("nav-groups").innerHTML = data.html;
1967
+ const label = document.getElementById("site-title");
1968
+ if (!label.querySelector("form")) label.textContent = label.title = data.siteTitle || "dooc";
1969
+ label.dataset.title = data.siteTitle || "";
1970
+ }
1960
1971
  if (window.__docsNavRestore) window.__docsNavRestore();
1961
1972
  document.dispatchEvent(new Event("docs:ui-refresh"));
1962
1973
  };
@@ -1983,17 +1994,85 @@ ${mode === "edit"
1983
1994
  event.preventDefault();
1984
1995
  docAction(button.closest(".nav-item"), button.dataset.docAction);
1985
1996
  });
1997
+ const editSiteTitle = (label) => {
1998
+ if (document.querySelector(".nav-rename-form")) return;
1999
+ const original = label.textContent;
2000
+ const baseTitle = label.dataset.title || null;
2001
+ const form = document.createElement("form");
2002
+ form.className = "nav-rename-form";
2003
+ form.title = t("Enter to save / Esc to cancel");
2004
+ const input = document.createElement("input");
2005
+ input.name = "title";
2006
+ input.value = original;
2007
+ input.required = true;
2008
+ input.maxLength = 256;
2009
+ input.setAttribute("aria-label", t("Site title"));
2010
+ form.append(input);
2011
+ label.replaceChildren(form);
2012
+ input.select();
2013
+ let busy = false;
2014
+ let closed = false;
2015
+ const close = () => {
2016
+ if (closed) return;
2017
+ closed = true;
2018
+ form.remove();
2019
+ label.textContent = original;
2020
+ void refresh();
2021
+ };
2022
+ form.addEventListener("focusout", (event) => {
2023
+ if (!busy && !form.contains(event.relatedTarget)) close();
2024
+ });
2025
+ form.addEventListener("keydown", (event) => {
2026
+ if (event.isComposing) return;
2027
+ if (event.key === "Escape" && !busy) {
2028
+ event.preventDefault();
2029
+ close();
2030
+ label.focus();
2031
+ } else if (event.key === "Enter") {
2032
+ event.preventDefault();
2033
+ form.requestSubmit();
2034
+ }
2035
+ });
2036
+ form.addEventListener("submit", async (event) => {
2037
+ event.preventDefault();
2038
+ if (busy || closed || !input.value.trim()) return;
2039
+ busy = true;
2040
+ input.readOnly = true;
2041
+ try {
2042
+ const result = await post("/api/site-title", { title: input.value, baseTitle });
2043
+ closed = true;
2044
+ form.remove();
2045
+ label.textContent = label.title = result.title;
2046
+ label.dataset.title = result.title;
2047
+ await refresh();
2048
+ label.focus();
2049
+ setStatus("", false);
2050
+ } catch (error) {
2051
+ setStatus(error.message, true);
2052
+ input.focus();
2053
+ } finally {
2054
+ busy = false;
2055
+ input.readOnly = false;
2056
+ }
2057
+ });
2058
+ };
1986
2059
  const editLabel = (event) => {
1987
2060
  if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
1988
2061
  const target = event.target instanceof Element ? event.target : null;
1989
2062
  if (!target || target.closest("button, input, form, .nav-doc-icon")) return;
2063
+ const label = target.closest("#site-title");
2064
+ if (label) {
2065
+ event.preventDefault();
2066
+ editSiteTitle(label);
2067
+ return;
2068
+ }
1990
2069
  const row = target.closest("#nav-groups [data-doc-id] > .nav-row");
1991
2070
  if (!row) return;
1992
2071
  event.preventDefault();
1993
2072
  docAction(row.closest("[data-doc-id]"), "rename");
1994
2073
  };
1995
2074
  document.addEventListener("dblclick", editLabel);
1996
- document.addEventListener("keydown", (event) => { if (event.key === "F2") editLabel(event); });
2075
+ document.addEventListener("keydown", (event) => { if (event.key === "F2" || (event.key === "Enter" && event.target.id === "site-title")) editLabel(event); });
1997
2076
  const setIcon = async (slot, file) => {
1998
2077
  if (file && !/\\.svg$/i.test(file.name) && file.type !== "image/svg+xml") {
1999
2078
  setStatus("Icon must be svg", true);
@@ -2961,11 +3040,13 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
2961
3040
  const input = await readJson(req, Math.ceil((MAX_FILE_UPLOAD_BYTES * 4) / 3) + 16_384);
2962
3041
  if (!input)
2963
3042
  throw new Error("Invalid file request");
2964
- const result = input.action === "read"
2965
- ? filesSnapshot(root)
2966
- : input.action === "upload"
2967
- ? uploadFile(root, input)
2968
- : updateFiles(root, input);
3043
+ const result = input.action === "complete"
3044
+ ? completeFilePaths(root, input.prefix)
3045
+ : input.action === "read"
3046
+ ? filesSnapshot(root)
3047
+ : input.action === "upload"
3048
+ ? uploadFile(root, input)
3049
+ : updateFiles(root, input);
2969
3050
  sendJson(res, 200, result);
2970
3051
  }
2971
3052
  catch (error) {
@@ -3125,14 +3206,17 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3125
3206
  await handleIcon(req, res);
3126
3207
  return;
3127
3208
  }
3128
- if (path === "/api/site-icon") {
3209
+ if (path === "/api/site-icon" || path === "/api/site-title") {
3129
3210
  if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3130
3211
  sendJson(res, 403, {
3131
- error: "Site icons require a same-origin local editor request",
3212
+ error: "Site settings require a same-origin local editor request",
3132
3213
  });
3133
3214
  return;
3134
3215
  }
3135
- const result = siteIconResponse(root, await readJson(req));
3216
+ const input = await readJson(req);
3217
+ const result = path === "/api/site-title"
3218
+ ? siteTitleResponse(root, input)
3219
+ : siteIconResponse(root, input);
3136
3220
  sendJson(res, result.status, result.body);
3137
3221
  return;
3138
3222
  }
@@ -0,0 +1,13 @@
1
+ export declare const siteTitleResponse: (root: string, input: Record<string, unknown> | undefined) => {
2
+ status: number;
3
+ body: {
4
+ error: string;
5
+ title?: undefined;
6
+ };
7
+ } | {
8
+ status: number;
9
+ body: {
10
+ title: string;
11
+ error?: undefined;
12
+ };
13
+ };
@@ -0,0 +1,37 @@
1
+ import { Document, isSeq, parseDocument } from "yaml";
2
+ import { parseManifestText } from "../compiler/manifest.js";
3
+ import { readTextfile, writeTextfile } from "../compiler/textfile.js";
4
+ import { MANIFEST_FILE } from "../core/content-metadata.js";
5
+ export const siteTitleResponse = (root, input) => {
6
+ if (typeof input?.title !== "string" ||
7
+ !input.title.trim() ||
8
+ input.title.length > 256 ||
9
+ [...input.title].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) ||
10
+ (input.baseTitle !== null && typeof input.baseTitle !== "string"))
11
+ return { status: 400, body: { error: "Enter a site title (1–256 characters)" } };
12
+ try {
13
+ const raw = readTextfile(root, MANIFEST_FILE);
14
+ const manifest = parseManifestText(raw);
15
+ if (manifest.errors.length)
16
+ return { status: 409, body: { error: manifest.errors.join("\n") } };
17
+ if ((manifest.title ?? null) !== input.baseTitle)
18
+ return { status: 409, body: { error: "Site title changed externally. Try again." } };
19
+ const parsed = parseDocument(raw);
20
+ const document = isSeq(parsed.contents) || parsed.contents == null
21
+ ? new Document({ docs: parsed.toJS() ?? [] })
22
+ : parsed;
23
+ if (document !== parsed)
24
+ document.commentBefore = parsed.commentBefore;
25
+ const title = input.title.trim();
26
+ document.set("title", title);
27
+ if (!writeTextfile(root, MANIFEST_FILE, document.toString(), raw))
28
+ return { status: 409, body: { error: "Manifest changed externally. Try again." } };
29
+ return { status: 200, body: { title } };
30
+ }
31
+ catch (error) {
32
+ return {
33
+ status: 400,
34
+ body: { error: error instanceof Error ? error.message : String(error) },
35
+ };
36
+ }
37
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dooc-dev/dooc",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "View and edit source files with dooc.yaml configuration, and share them as source ZIPs or standalone HTML.",
5
5
  "type": "module",
6
6
  "files": [