@abraca/junis 2.87.0 → 2.90.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 (109) hide show
  1. package/dist/module.d.mts +43 -4
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +121 -6
  4. package/dist/runtime/assets/css/jun.css +2 -2
  5. package/dist/runtime/components/JunDocSurface.d.vue.ts +20 -2
  6. package/dist/runtime/components/JunDocSurface.vue +27 -2
  7. package/dist/runtime/components/JunDocSurface.vue.d.ts +20 -2
  8. package/dist/runtime/components/JunHead.vue +16 -4
  9. package/dist/runtime/components/JunNavDock.d.vue.ts +15 -0
  10. package/dist/runtime/components/JunNavDock.vue +94 -0
  11. package/dist/runtime/components/JunNavDock.vue.d.ts +15 -0
  12. package/dist/runtime/components/JunNavMenu.client.d.vue.ts +15 -0
  13. package/dist/runtime/components/JunNavMenu.client.vue +501 -0
  14. package/dist/runtime/components/JunNavMenu.client.vue.d.ts +15 -0
  15. package/dist/runtime/components/JunNavPreview.d.vue.ts +17 -0
  16. package/dist/runtime/components/JunNavPreview.vue +169 -0
  17. package/dist/runtime/components/JunNavPreview.vue.d.ts +17 -0
  18. package/dist/runtime/components/JunNavigation.d.vue.ts +4 -11
  19. package/dist/runtime/components/JunNavigation.vue +813 -138
  20. package/dist/runtime/components/JunNavigation.vue.d.ts +4 -11
  21. package/dist/runtime/components/JunNoteLinks.vue +1 -1
  22. package/dist/runtime/components/JunOfflinePanel.client.d.vue.ts +3 -0
  23. package/dist/runtime/components/JunOfflinePanel.client.vue +293 -0
  24. package/dist/runtime/components/JunOfflinePanel.client.vue.d.ts +3 -0
  25. package/dist/runtime/components/JunPageHero.vue +3 -3
  26. package/dist/runtime/components/JunSectionBar.d.vue.ts +41 -0
  27. package/dist/runtime/components/JunSectionBar.vue +144 -0
  28. package/dist/runtime/components/JunSectionBar.vue.d.ts +41 -0
  29. package/dist/runtime/components/renderers/JunConfigRenderer.vue +618 -6
  30. package/dist/runtime/components/renderers/JunEntryRenderer.vue +48 -0
  31. package/dist/runtime/composables/useJunCommands.d.ts +1 -1
  32. package/dist/runtime/composables/useJunCommands.js +14 -1
  33. package/dist/runtime/composables/useJunCreatePage.js +7 -1
  34. package/dist/runtime/composables/useJunDocPage.d.ts +28 -0
  35. package/dist/runtime/composables/useJunDocPage.js +111 -20
  36. package/dist/runtime/composables/useJunGarden.d.ts +1 -1
  37. package/dist/runtime/composables/useJunGarden.js +3 -2
  38. package/dist/runtime/composables/useJunGestures.d.ts +53 -0
  39. package/dist/runtime/composables/useJunGestures.js +89 -0
  40. package/dist/runtime/composables/useJunMenuState.d.ts +4 -0
  41. package/dist/runtime/composables/useJunMenuState.js +5 -0
  42. package/dist/runtime/composables/useJunNavItems.d.ts +50 -0
  43. package/dist/runtime/composables/useJunNavItems.js +188 -0
  44. package/dist/runtime/composables/useJunNavSettings.d.ts +58 -1
  45. package/dist/runtime/composables/useJunNavSettings.js +110 -8
  46. package/dist/runtime/composables/useJunOffline.d.ts +109 -0
  47. package/dist/runtime/composables/useJunOffline.js +294 -0
  48. package/dist/runtime/composables/useJunOptions.d.ts +1 -0
  49. package/dist/runtime/composables/useJunSettings.d.ts +1 -1
  50. package/dist/runtime/composables/useJunSettings.js +2 -0
  51. package/dist/runtime/composables/useJunSiblings.d.ts +30 -0
  52. package/dist/runtime/composables/useJunSiblings.js +38 -0
  53. package/dist/runtime/composables/useJunSiteConfig.d.ts +70 -3
  54. package/dist/runtime/composables/useJunTheme.js +4 -1
  55. package/dist/runtime/composables/useJunViewingAccent.js +10 -0
  56. package/dist/runtime/layouts/jun.vue +32 -2
  57. package/dist/runtime/pages/doc.vue +2 -0
  58. package/dist/runtime/pages/index.vue +2 -0
  59. package/dist/runtime/server/api/health.get.d.ts +15 -0
  60. package/dist/runtime/server/api/health.get.js +7 -2
  61. package/dist/runtime/server/api/links.get.js +27 -3
  62. package/dist/runtime/server/api/offline.get.d.ts +10 -0
  63. package/dist/runtime/server/api/offline.get.js +13 -0
  64. package/dist/runtime/server/api/resolve/[...slug].get.d.ts +20 -0
  65. package/dist/runtime/server/api/resolve/[...slug].get.js +31 -0
  66. package/dist/runtime/server/api/search.get.d.ts +1 -1
  67. package/dist/runtime/server/api/search.get.js +42 -39
  68. package/dist/runtime/server/api/tree.get.js +3 -1
  69. package/dist/runtime/server/janitor/junJanitorChores.d.ts +14 -7
  70. package/dist/runtime/server/janitor/junJanitorChores.js +21 -3
  71. package/dist/runtime/server/janitor/junJanitorMachine.js +36 -4
  72. package/dist/runtime/server/janitor/junJanitorPerform.d.ts +15 -1
  73. package/dist/runtime/server/janitor/junJanitorPerform.js +13 -5
  74. package/dist/runtime/server/janitor/junJanitorYText.d.ts +40 -3
  75. package/dist/runtime/server/janitor/junJanitorYText.js +60 -14
  76. package/dist/runtime/server/plugins/jun-compress.d.ts +2 -0
  77. package/dist/runtime/server/plugins/jun-compress.js +76 -0
  78. package/dist/runtime/server/plugins/jun-janitor.js +132 -81
  79. package/dist/runtime/server/routes/jun-card.png.get.d.ts +2 -0
  80. package/dist/runtime/server/routes/jun-card.png.get.js +40 -0
  81. package/dist/runtime/server/routes/jun-sw.js.get.js +66 -13
  82. package/dist/runtime/server/routes/sitemap.xml.get.js +5 -18
  83. package/dist/runtime/server/utils/junCard.d.ts +39 -0
  84. package/dist/runtime/server/utils/junCard.js +159 -0
  85. package/dist/runtime/server/utils/junIcon.d.ts +27 -2
  86. package/dist/runtime/server/utils/junIcon.js +5 -5
  87. package/dist/runtime/server/utils/junJanitorStatus.d.ts +59 -0
  88. package/dist/runtime/server/utils/junJanitorStatus.js +27 -0
  89. package/dist/runtime/server/utils/junPages.d.ts +51 -0
  90. package/dist/runtime/server/utils/junPages.js +70 -0
  91. package/dist/runtime/types.d.ts +295 -0
  92. package/dist/runtime/utils/junAdopt.d.ts +43 -0
  93. package/dist/runtime/utils/junAdopt.js +7 -0
  94. package/dist/runtime/utils/junGesture.d.ts +84 -0
  95. package/dist/runtime/utils/junGesture.js +40 -0
  96. package/dist/runtime/utils/junLetters.d.ts +86 -0
  97. package/dist/runtime/utils/junLetters.js +173 -0
  98. package/dist/runtime/utils/junNavValue.d.ts +56 -0
  99. package/dist/runtime/utils/junNavValue.js +36 -0
  100. package/dist/runtime/utils/junOffline.d.ts +138 -0
  101. package/dist/runtime/utils/junOffline.js +73 -0
  102. package/dist/runtime/utils/junSearchRank.d.ts +79 -0
  103. package/dist/runtime/utils/junSearchRank.js +73 -0
  104. package/dist/runtime/utils/junSocial.d.ts +59 -0
  105. package/dist/runtime/utils/junSocial.js +56 -0
  106. package/dist/runtime/utils/junViewSpecs.d.ts +39 -1
  107. package/dist/runtime/utils/junViewSpecs.js +92 -1
  108. package/dist/types.d.mts +1 -1
  109. package/package.json +13 -9
@@ -170,23 +170,69 @@ export function junLastParagraph(fragment) {
170
170
  fragment.push([para]);
171
171
  return text;
172
172
  }
173
- export function junSplitParagraph(fragment, bodyIndex) {
174
- let offset = 0;
175
- let insertAt = fragment.length;
176
- for (let i = 0; i < fragment.length; i++) {
177
- const child = fragment.get(i);
178
- if (!isElement(child) || isSchemaNode(child)) continue;
179
- const len = elementTextLength(child);
180
- if (offset + len >= bodyIndex) {
181
- insertAt = i + 1;
182
- break;
173
+ export function junBlockNames(fragment) {
174
+ return junBlocks(fragment).map((b) => b.nodeName);
175
+ }
176
+ function moveTextPrefix(src, dest, count) {
177
+ if (count <= 0) return 0;
178
+ const delta = src.toDelta();
179
+ const prefix = [];
180
+ let taken = 0;
181
+ for (const op of delta) {
182
+ if (taken >= count) break;
183
+ if (typeof op.insert === "string") {
184
+ const slice = op.insert.slice(0, count - taken);
185
+ if (!slice) continue;
186
+ prefix.push({ insert: slice, ...op.attributes ? { attributes: op.attributes } : {} });
187
+ taken += slice.length;
188
+ } else if (op.insert !== void 0) {
189
+ const value = op.insert;
190
+ prefix.push({
191
+ insert: typeof value?.clone === "function" ? value.clone() : op.insert,
192
+ ...op.attributes ? { attributes: op.attributes } : {}
193
+ });
194
+ taken += 1;
183
195
  }
184
- offset += len;
185
196
  }
186
- const para = new Y.XmlElement("paragraph");
197
+ if (!taken) return 0;
198
+ dest.applyDelta(prefix);
199
+ src.delete(0, taken);
200
+ return taken;
201
+ }
202
+ export function junSplitParagraph(fragment, bodyIndex, headNodeName, tailNodeName) {
203
+ const blocks = junBlocks(fragment);
204
+ const target = blocks.find((b) => bodyIndex >= b.bodyStart && bodyIndex <= b.bodyStart + b.text.length) ?? blocks[blocks.length - 1];
205
+ if (!target) {
206
+ const head2 = new Y.XmlElement(headNodeName ?? "paragraph");
207
+ head2.insert(0, [new Y.XmlText()]);
208
+ const tail = new Y.XmlElement("paragraph");
209
+ const text2 = new Y.XmlText();
210
+ tail.insert(0, [text2]);
211
+ fragment.push([head2, tail]);
212
+ return text2;
213
+ }
214
+ const local = Math.max(0, Math.min(bodyIndex - target.bodyStart, target.text.length));
215
+ const head = new Y.XmlElement(headNodeName ?? target.nodeName);
216
+ const headText = new Y.XmlText();
217
+ head.insert(0, [headText]);
218
+ const first = target.el.get(0);
219
+ if (local > 0 && isText(first)) moveTextPrefix(first, headText, local);
220
+ fragment.insert(target.childIndex, [head]);
221
+ const tailIndex = target.childIndex + 1;
222
+ if (tailNodeName && tailNodeName !== target.nodeName && elementTextLength(target.el) === 0 && target.el.length <= 1) {
223
+ const tail = new Y.XmlElement(tailNodeName);
224
+ const text2 = new Y.XmlText();
225
+ tail.insert(0, [text2]);
226
+ fragment.delete(tailIndex, 1);
227
+ fragment.insert(tailIndex, [tail]);
228
+ return text2;
229
+ }
230
+ for (let i = 0; i < target.el.length; i++) {
231
+ const child = target.el.get(i);
232
+ if (isText(child)) return child;
233
+ }
187
234
  const text = new Y.XmlText();
188
- para.insert(0, [text]);
189
- fragment.insert(insertAt, [para]);
235
+ target.el.insert(0, [text]);
190
236
  return text;
191
237
  }
192
238
  export function junDeleteRange(fragment, at, count) {
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,76 @@
1
+ import { defineNitroPlugin } from "nitropack/runtime";
2
+ import { promisify } from "node:util";
3
+ import { brotliCompress, constants, gzip } from "node:zlib";
4
+ const brotli = promisify(brotliCompress);
5
+ const gzipAsync = promisify(gzip);
6
+ const MIN_BYTES = 1024;
7
+ function isCompressible(type) {
8
+ if (!type) return false;
9
+ const value = type.toLowerCase();
10
+ return value.startsWith("text/") || value.includes("json") || value.includes("javascript") || value.includes("xml") || value.includes("+html") || value.includes("manifest");
11
+ }
12
+ function pickEncoding(accept) {
13
+ if (!accept) return null;
14
+ const value = accept.toLowerCase();
15
+ if (value.includes("br")) return "br";
16
+ if (value.includes("gzip")) return "gzip";
17
+ return null;
18
+ }
19
+ function isPlainData(body) {
20
+ if (typeof body !== "object" || body === null) return false;
21
+ if (Buffer.isBuffer(body)) return false;
22
+ if (body instanceof Error) return false;
23
+ const candidate = body;
24
+ if (typeof candidate.arrayBuffer === "function") return false;
25
+ if (typeof candidate.pipe === "function" || typeof candidate.pipeTo === "function") return false;
26
+ if (typeof candidate.end === "function") return false;
27
+ if (candidate.buffer !== void 0) return false;
28
+ if (Symbol.asyncIterator in candidate) return false;
29
+ return true;
30
+ }
31
+ export default defineNitroPlugin((nitroApp) => {
32
+ nitroApp.hooks.hook("beforeResponse", async (event, response) => {
33
+ const body = response?.body;
34
+ const res = event.node.res;
35
+ if (res.headersSent) return;
36
+ if (res.getHeader("content-encoding")) return;
37
+ let raw;
38
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
39
+ if (!isCompressible(String(res.getHeader("content-type") ?? ""))) return;
40
+ raw = Buffer.isBuffer(body) ? body : Buffer.from(body, "utf8");
41
+ } else if (isPlainData(body)) {
42
+ const existing = String(res.getHeader("content-type") ?? "");
43
+ if (existing && !isCompressible(existing)) return;
44
+ try {
45
+ raw = Buffer.from(JSON.stringify(body), "utf8");
46
+ } catch {
47
+ return;
48
+ }
49
+ if (!existing) res.setHeader("content-type", "application/json;charset=utf-8");
50
+ } else {
51
+ return;
52
+ }
53
+ if (raw.byteLength < MIN_BYTES) return;
54
+ const encoding = pickEncoding(event.node.req.headers["accept-encoding"]);
55
+ if (!encoding) return;
56
+ try {
57
+ const packed = encoding === "br" ? await brotli(raw, {
58
+ // Quality 4 — this is on the request's critical path. See the
59
+ // header: 11 is a build-time setting and costs tens of ms here.
60
+ params: {
61
+ [constants.BROTLI_PARAM_QUALITY]: 4,
62
+ [constants.BROTLI_PARAM_SIZE_HINT]: raw.byteLength
63
+ }
64
+ }) : await gzipAsync(raw, { level: 6 });
65
+ if (packed.byteLength >= raw.byteLength) return;
66
+ res.setHeader("content-encoding", encoding);
67
+ res.setHeader("content-length", packed.byteLength);
68
+ const vary = String(res.getHeader("vary") ?? "");
69
+ if (!vary.toLowerCase().includes("accept-encoding")) {
70
+ res.setHeader("vary", vary ? `${vary}, Accept-Encoding` : "Accept-Encoding");
71
+ }
72
+ response.body = packed;
73
+ } catch {
74
+ }
75
+ });
76
+ });
@@ -8,16 +8,34 @@ import {
8
8
  plain
9
9
  } from "../janitor/junJanitorStore.js";
10
10
  import { junSiteConfigMeta, junSlugMap } from "../utils/junCache.js";
11
+ import { junJanitorNote, junJanitorPhase } from "../utils/junJanitorStatus.js";
11
12
  import { junSeedExpected, junSeedSettled, junWaitForSeed } from "../utils/junSeedGate.js";
12
13
  const BOOT_DELAY_MS = 2e4;
13
14
  const SEED_WAIT_MS = 18e4;
15
+ const RETRY_DELAYS_MS = [3e4, 6e4, 12e4, 3e5];
14
16
  export default defineNitroPlugin((nitroApp) => {
15
17
  const runtime = useRuntimeConfig();
16
18
  const jun = runtime.public.jun;
17
19
  const options = runtime.jun?.janitor;
18
- if (!jun?.features?.janitor || !options?.enabled) return;
20
+ if (!jun?.features?.janitor || !options?.enabled) {
21
+ junJanitorPhase("absent", !jun?.features?.janitor ? "jun.features.janitor is off in this BUILD \u2014 a runtime env var cannot turn it on" : "jun.janitor.enabled is false in this build");
22
+ return;
23
+ }
24
+ junJanitorPhase("waiting", "in this build \u2014 waiting for the service runners to boot");
25
+ const settings = options;
19
26
  const log = (message) => console.log(`[jun:janitor] ${message}`);
20
27
  nitroApp.hooks.hook("abracadabra:before-runners", () => {
28
+ junJanitorPhase("waiting", "the service runners are booting \u2014 registering");
29
+ try {
30
+ register();
31
+ } catch (error) {
32
+ const message = error?.message ?? String(error);
33
+ junJanitorNote({ lastError: message });
34
+ junJanitorPhase("absent", `the runner could not be registered: ${message}`);
35
+ log(`could not register the runner: ${message}`);
36
+ }
37
+ });
38
+ function register() {
21
39
  registerServerPlugin({
22
40
  name: "jun:janitor",
23
41
  serverRunners: [
@@ -26,31 +44,48 @@ export default defineNitroPlugin((nitroApp) => {
26
44
  start(ctx) {
27
45
  let stopped = false;
28
46
  let shutdown = null;
29
- const boot = setTimeout(() => {
30
- void (async () => {
31
- try {
32
- if (junSeedExpected() && !junSeedSettled()) {
33
- log('waiting for the seeder to finish before deciding what "clean" means');
34
- const settled = await junWaitForSeed(SEED_WAIT_MS);
35
- log(settled ? "seed finished \u2014 reading the site" : `seed still running after ${Math.round(SEED_WAIT_MS / 1e3)}s \u2014 starting anyway`);
36
- }
37
- shutdown = await hire(ctx, options, log);
38
- } catch (error) {
39
- log(`could not start: ${error?.message ?? error}`);
47
+ let timer = null;
48
+ let failures = 0;
49
+ junJanitorNote({ mode: settings.mode ?? "observe" });
50
+ junJanitorPhase("waiting", `registered \u2014 first attempt in ${Math.round(BOOT_DELAY_MS / 1e3)}s`);
51
+ const attempt = async () => {
52
+ if (stopped) return;
53
+ junJanitorNote({ attempts: failures + 1 });
54
+ try {
55
+ if (junSeedExpected() && !junSeedSettled()) {
56
+ junJanitorPhase("waiting", "waiting for the seeder to settle");
57
+ log('waiting for the seeder to finish before deciding what "clean" means');
58
+ const settled = await junWaitForSeed(SEED_WAIT_MS);
59
+ log(settled ? "seed finished \u2014 reading the site" : `seed still running after ${Math.round(SEED_WAIT_MS / 1e3)}s \u2014 starting anyway`);
40
60
  }
41
- if (stopped && shutdown) await shutdown();
42
- })();
43
- }, BOOT_DELAY_MS);
61
+ if (stopped) return;
62
+ junJanitorPhase("connecting", "authenticating and syncing the root document");
63
+ shutdown = await hire(ctx, settings, log);
64
+ if (!stopped) junJanitorPhase("on-duty", `on duty \u2014 mode: ${settings.mode ?? "observe"}`);
65
+ } catch (error) {
66
+ const message = error?.message ?? String(error);
67
+ const delay = RETRY_DELAYS_MS[Math.min(failures, RETRY_DELAYS_MS.length - 1)];
68
+ failures++;
69
+ junJanitorNote({ lastError: message });
70
+ junJanitorPhase("retrying", `could not start (${message}) \u2014 attempt ${failures + 1} in ${Math.round(delay / 1e3)}s`);
71
+ log(`could not start: ${message} \u2014 trying again in ${Math.round(delay / 1e3)}s`);
72
+ if (!stopped) timer = setTimeout(() => void attempt(), delay);
73
+ return;
74
+ }
75
+ if (stopped && shutdown) await shutdown();
76
+ };
77
+ timer = setTimeout(() => void attempt(), BOOT_DELAY_MS);
44
78
  return () => {
45
79
  stopped = true;
46
- clearTimeout(boot);
80
+ if (timer) clearTimeout(timer);
81
+ junJanitorPhase("off-duty", "the runner was shut down");
47
82
  void shutdown?.();
48
83
  };
49
84
  }
50
85
  }
51
86
  ]
52
87
  });
53
- });
88
+ }
54
89
  });
55
90
  async function hire(ctx, options, log) {
56
91
  const runtime = useRuntimeConfig();
@@ -71,74 +106,90 @@ async function hire(ctx, options, log) {
71
106
  log: (message) => log(message.replace("[jun:janitor] ", ""))
72
107
  });
73
108
  await actor.connect();
74
- const tree = createJunTreeWriter({
75
- rootDocId: ctx.rootDocId,
76
- sharedRoot: ctx.rootDoc,
77
- client: actor.httpClient ?? ctx.client,
78
- log
79
- });
80
- let baselineHandle = null;
81
- let baselineFailed = false;
82
- const baseline = async () => {
83
- if (baselineHandle || baselineFailed) return baselineHandle;
84
- if (options.baseline === "off") return null;
85
- try {
86
- const docId = await ensureBaselineDoc(ctx, actor, tree, log);
87
- if (!docId) {
109
+ junJanitorNote({ publicKey: actor.identityKey });
110
+ try {
111
+ return await hired();
112
+ } catch (error) {
113
+ await actor.destroy().catch(() => {
114
+ });
115
+ throw error;
116
+ }
117
+ async function hired() {
118
+ const tree = createJunTreeWriter({
119
+ rootDocId: ctx.rootDocId,
120
+ sharedRoot: ctx.rootDoc,
121
+ client: actor.httpClient ?? ctx.client,
122
+ log
123
+ });
124
+ let baselineHandle = null;
125
+ let baselineFailed = false;
126
+ const baseline = async () => {
127
+ if (baselineHandle || baselineFailed) return baselineHandle;
128
+ if (options.baseline === "off") {
129
+ junJanitorNote({ hasBaseline: false });
130
+ return null;
131
+ }
132
+ try {
133
+ const docId = await ensureBaselineDoc(ctx, actor, tree, log);
134
+ if (!docId) {
135
+ baselineFailed = true;
136
+ junJanitorNote({ hasBaseline: false });
137
+ return null;
138
+ }
139
+ baselineHandle = await junOpenBaseline(docId, actor.httpClient ?? ctx.client);
140
+ junJanitorNote({ hasBaseline: true });
141
+ return baselineHandle;
142
+ } catch (error) {
88
143
  baselineFailed = true;
144
+ junJanitorNote({ hasBaseline: false });
145
+ log(`baseline document unavailable: ${error?.message ?? error}`);
89
146
  return null;
90
147
  }
91
- baselineHandle = await junOpenBaseline(docId, actor.httpClient ?? ctx.client);
92
- return baselineHandle;
93
- } catch (error) {
94
- baselineFailed = true;
95
- log(`baseline document unavailable: ${error?.message ?? error}`);
96
- return null;
97
- }
98
- };
99
- const machine = createJunJanitorMachine(
100
- {
101
- mode: options.mode ?? "observe",
102
- baselineMode: options.baseline ?? "after-seed",
103
- name: options.name ?? "janitor",
104
- rootDocId: ctx.rootDocId,
105
- shiftHours: options.shiftHours ?? [0, 24],
106
- budget: {
107
- choresPerHour: options.budget?.choresPerHour ?? 40,
108
- linesPerHour: options.budget?.linesPerHour ?? 20,
109
- maxDocRemovalRatio: options.budget?.maxDocRemovalRatio ?? 0.5,
110
- choresPerShift: options.budget?.choresPerShift ?? 12
111
- },
112
- // The baseline document is the janitor's own notebook. Reverting it would
113
- // be a snake eating its tail, and it is hidden from every reader anyway.
114
- ignoreDocIds: [...options.ignoreDocIds ?? []],
115
- motor: options.tuning?.motor,
116
- patrol: options.tuning?.patrol,
117
- chores: options.tuning?.chores,
118
- voice: options.tuning?.voice,
119
- phrases: options.phrases
120
- },
121
- {
122
- actor,
123
- tree,
124
- baseline,
125
- slugFor: async (docId) => {
126
- const slugs = await junSlugMap();
127
- const slug = slugs[docId];
128
- return slug ? `/${slug}` : null;
148
+ };
149
+ const machine = createJunJanitorMachine(
150
+ {
151
+ mode: options.mode ?? "observe",
152
+ baselineMode: options.baseline ?? "after-seed",
153
+ name: options.name ?? "janitor",
154
+ rootDocId: ctx.rootDocId,
155
+ shiftHours: options.shiftHours ?? [0, 24],
156
+ budget: {
157
+ choresPerHour: options.budget?.choresPerHour ?? 40,
158
+ linesPerHour: options.budget?.linesPerHour ?? 20,
159
+ maxDocRemovalRatio: options.budget?.maxDocRemovalRatio ?? 0.5,
160
+ choresPerShift: options.budget?.choresPerShift ?? 12
161
+ },
162
+ // The baseline document is the janitor's own notebook. Reverting it would
163
+ // be a snake eating its tail, and it is hidden from every reader anyway.
164
+ ignoreDocIds: [...options.ignoreDocIds ?? []],
165
+ motor: options.tuning?.motor,
166
+ patrol: options.tuning?.patrol,
167
+ chores: options.tuning?.chores,
168
+ voice: options.tuning?.voice,
169
+ phrases: options.phrases
129
170
  },
130
- siteConfig: () => junSiteConfigMeta(),
131
- log
132
- }
133
- );
134
- machine.start();
135
- log(`on duty \u2014 mode: ${options.mode ?? "observe"}`);
136
- return async () => {
137
- await machine.stop();
138
- await actor.destroy();
139
- if (baselineHandle) await junCloseBaseline(baselineHandle);
140
- log("off duty");
141
- };
171
+ {
172
+ actor,
173
+ tree,
174
+ baseline,
175
+ slugFor: async (docId) => {
176
+ const slugs = await junSlugMap();
177
+ const slug = slugs[docId];
178
+ return slug ? `/${slug}` : null;
179
+ },
180
+ siteConfig: () => junSiteConfigMeta(),
181
+ log
182
+ }
183
+ );
184
+ machine.start();
185
+ log(`on duty \u2014 mode: ${options.mode ?? "observe"}`);
186
+ return async () => {
187
+ await machine.stop();
188
+ await actor.destroy();
189
+ if (baselineHandle) await junCloseBaseline(baselineHandle);
190
+ log("off duty");
191
+ };
192
+ }
142
193
  }
143
194
  async function ensureBaselineDoc(ctx, actor, tree, log) {
144
195
  const map = actor.tree;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<Uint8Array<ArrayBuffer>>>;
2
+ export default _default;
@@ -0,0 +1,40 @@
1
+ import { defineEventHandler, getQuery, setResponseHeader } from "h3";
2
+ import { junBrandIdentity } from "../utils/junBrand.js";
3
+ import { junRenderCard } from "../utils/junCard.js";
4
+ import { junDocTree } from "../utils/junCache.js";
5
+ import { isJunOwnerOnlyDoc } from "../utils/junVisibility.js";
6
+ import { useRuntimeConfig } from "nitropack/runtime";
7
+ function kindOf(type, opts) {
8
+ if (!type) return void 0;
9
+ const label = opts?.typeLabels?.[type];
10
+ if (label) return label;
11
+ return Object.entries(opts?.typeIds ?? {}).find(([, id]) => id === type)?.[0];
12
+ }
13
+ export default defineEventHandler(async (event) => {
14
+ const docId = String(getQuery(event).d ?? "");
15
+ const identity = await junBrandIdentity();
16
+ const opts = useRuntimeConfig().public.jun;
17
+ let title = "";
18
+ let kind;
19
+ let excerpt;
20
+ if (docId) {
21
+ const tree = await junDocTree().catch(() => ({}));
22
+ const entry = tree[docId];
23
+ if (entry && !entry.trashed && !isJunOwnerOnlyDoc(entry)) {
24
+ title = entry.label ?? "";
25
+ kind = kindOf(entry.type, opts);
26
+ const meta = entry.meta ?? {};
27
+ const summary = meta.excerpt ?? meta.description;
28
+ if (typeof summary === "string") excerpt = summary;
29
+ }
30
+ }
31
+ const png = await junRenderCard({
32
+ identity,
33
+ title: title || identity.name,
34
+ kind,
35
+ excerpt
36
+ });
37
+ setResponseHeader(event, "content-type", "image/png");
38
+ setResponseHeader(event, "cache-control", "public, max-age=31536000, immutable");
39
+ return new Uint8Array(png);
40
+ });
@@ -1,10 +1,12 @@
1
1
  import { defineEventHandler, setResponseHeader } from "h3";
2
2
  import { useRuntimeConfig } from "nitropack/runtime";
3
+ import { junOfflineCacheName, JUN_OFFLINE_MODE_URL } from "../../utils/junOffline.js";
3
4
  export default defineEventHandler((event) => {
4
5
  const config = useRuntimeConfig();
5
6
  const jun = config.public.jun;
6
7
  const build = config.app?.buildId ?? "dev";
7
8
  const apiBase = jun?.apiBase ?? "/api/_jun";
9
+ const cache = junOfflineCacheName(build);
8
10
  setResponseHeader(event, "content-type", "text/javascript; charset=utf-8");
9
11
  setResponseHeader(event, "service-worker-allowed", "/");
10
12
  setResponseHeader(event, "cache-control", "no-cache");
@@ -25,8 +27,30 @@ self.addEventListener('activate', (event) => {
25
27
  `;
26
28
  }
27
29
  return `/* @abraca/junis service worker \u2014 generated, do not edit */
28
- const CACHE = 'jun-${build}'
30
+ const CACHE = ${JSON.stringify(cache)}
29
31
  const API_BASE = ${JSON.stringify(apiBase)}
32
+ const MODE_URL = ${JSON.stringify(JUN_OFFLINE_MODE_URL)}
33
+
34
+ /**
35
+ * How much of the site this visitor keeps: 'off' | 'visited' | 'site'.
36
+ *
37
+ * Read from the CACHE, not from localStorage, which does not exist in a worker
38
+ * \u2014 and a worker restarts independently of the tab that configured it, so a
39
+ * value held only in memory is a setting that lasts until the browser feels
40
+ * like evicting this thread. Memoised, and dropped when the page says so.
41
+ */
42
+ let modePromise = null
43
+
44
+ function readMode() {
45
+ if (!modePromise) {
46
+ modePromise = caches.open(CACHE)
47
+ .then(c => c.match(MODE_URL))
48
+ .then(hit => (hit ? hit.json() : null))
49
+ .then(body => (body && body.mode) || 'visited')
50
+ .catch(() => 'visited')
51
+ }
52
+ return modePromise
53
+ }
30
54
 
31
55
  /** Immutable by construction: content-hashed, or fingerprinted in ?v=. */
32
56
  function isImmutable(url) {
@@ -41,7 +65,6 @@ function isImmutable(url) {
41
65
  function isPassThrough(url) {
42
66
  return url.pathname.startsWith(API_BASE)
43
67
  || url.pathname.startsWith('/api/')
44
- || url.pathname.startsWith('/uploads/')
45
68
  || url.pathname === '/manifest.webmanifest'
46
69
  || url.pathname === '/feed.xml'
47
70
  || url.pathname === '/feed.json'
@@ -49,8 +72,8 @@ function isPassThrough(url) {
49
72
  }
50
73
 
51
74
  self.addEventListener('install', () => {
52
- // No precache \u2014 see the header. Take over immediately so a deploy does not
53
- // wait for every tab to close.
75
+ // No precache \u2014 a copy is something a visitor ASKS for. Take over
76
+ // immediately so a deploy does not wait for every tab to close.
54
77
  self.skipWaiting()
55
78
  })
56
79
 
@@ -64,15 +87,18 @@ self.addEventListener('activate', (event) => {
64
87
 
65
88
  self.addEventListener('message', (event) => {
66
89
  if (event.data === 'jun:skip-waiting') self.skipWaiting()
90
+ // The page changed the mode, or emptied the cache. Either way this worker's
91
+ // memoised answer is stale and re-reading it costs one cache match.
92
+ if (event.data === 'jun:mode-changed') modePromise = null
67
93
  })
68
94
 
69
- async function networkFirst(request) {
95
+ async function networkFirst(request, keep) {
70
96
  const cache = await caches.open(CACHE)
71
97
  try {
72
98
  const response = await fetch(request)
73
99
  // Only a real, complete answer is worth keeping. An opaque or errored
74
100
  // response cached here would be served back as the offline page.
75
- if (response && response.ok && response.type === 'basic') {
101
+ if (keep && response && response.ok && response.type === 'basic') {
76
102
  cache.put(request, response.clone())
77
103
  }
78
104
  return response
@@ -100,6 +126,27 @@ async function cacheFirst(request) {
100
126
  return response
101
127
  }
102
128
 
129
+ /**
130
+ * An upload is served from a saved copy and NEVER added to one by browsing.
131
+ *
132
+ * Images are the heavy half \u2014 the one part of a site whose size is a property
133
+ * of its content rather than of its page count \u2014 so filling the cache with
134
+ * them as a reader scrolls is exactly the silent download this whole surface
135
+ * exists to prevent. If a copy holds this image, offline shows it; otherwise
136
+ * offline shows a broken image, which is what it honestly is.
137
+ */
138
+ async function cachedOnlyFallback(request) {
139
+ try {
140
+ return await fetch(request)
141
+ }
142
+ catch (err) {
143
+ const cache = await caches.open(CACHE)
144
+ const hit = await cache.match(request)
145
+ if (hit) return hit
146
+ throw err
147
+ }
148
+ }
149
+
103
150
  self.addEventListener('fetch', (event) => {
104
151
  const request = event.request
105
152
  if (request.method !== 'GET') return
@@ -113,14 +160,20 @@ self.addEventListener('fetch', (event) => {
113
160
  if (url.origin !== self.location.origin) return
114
161
  if (isPassThrough(url)) return
115
162
 
116
- if (isImmutable(url)) {
117
- event.respondWith(cacheFirst(request))
118
- return
119
- }
163
+ const isNav = request.mode === 'navigate'
164
+ const isUpload = url.pathname.startsWith('/uploads/')
165
+ if (!isNav && !isUpload && !isImmutable(url)) return
120
166
 
121
- if (request.mode === 'navigate') {
122
- event.respondWith(networkFirst(request))
123
- }
167
+ event.respondWith((async () => {
168
+ const mode = await readMode()
169
+ // 'off' is a visitor who would rather no storage were used, and it has to
170
+ // mean that on the way IN as well as on the way out \u2014 a worker that keeps
171
+ // filling a cache it refuses to read is the worst of both.
172
+ if (mode === 'off') return fetch(request)
173
+ if (isUpload) return cachedOnlyFallback(request)
174
+ if (isImmutable(url)) return cacheFirst(request)
175
+ return networkFirst(request, true)
176
+ })())
124
177
  })
125
178
  `;
126
179
  });
@@ -1,29 +1,16 @@
1
1
  import { defineEventHandler, setResponseHeader } from "h3";
2
- import { junDocTree, junRootDocId, junSlugMap } from "../utils/junCache.js";
2
+ import { junPublicPages } from "../utils/junPages.js";
3
3
  import { junSiteUrl } from "../utils/junFeed.js";
4
- import { isJunOwnerOnlyDoc } from "../utils/junVisibility.js";
5
4
  export default defineEventHandler(async (event) => {
6
5
  const site = junSiteUrl();
7
- const rootDocId = junRootDocId();
8
- const [tree, idToSlug] = await Promise.all([junDocTree(), junSlugMap()]);
9
- const urls = Object.entries(idToSlug).filter(([id]) => {
10
- if (id === rootDocId) return false;
11
- const e = tree[id];
12
- if (!e || e.trashed) return false;
13
- if (isJunOwnerOnlyDoc(e)) return false;
14
- if (e.meta?.draft === true) return false;
15
- if (e.meta?.signerId) return false;
16
- if ((e.type ?? "").endsWith("-redirect")) return false;
17
- if (e.meta?.paneDoc || e.meta?.paneWidget) return false;
18
- if (e.meta?.t != null) return false;
19
- return true;
20
- }).map(([, slug]) => `${site}/${slug}`);
6
+ const pages = await junPublicPages();
21
7
  setResponseHeader(event, "content-type", "application/xml; charset=utf-8");
22
8
  return [
23
9
  '<?xml version="1.0" encoding="UTF-8"?>',
24
10
  '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
25
- ` <url><loc>${site}/</loc></url>`,
26
- ...urls.map((u) => ` <url><loc>${u}</loc></url>`),
11
+ // `/` is `junPublicPages`'s first entry, so the root is emitted once,
12
+ // by the same loop as everything else.
13
+ ...pages.map((p) => ` <url><loc>${site}${p.path === "/" ? "/" : p.path}</loc></url>`),
27
14
  "</urlset>"
28
15
  ].join("\n");
29
16
  });