@skillre/dsh-plugin-sticky-wall 0.8.0 → 0.9.1

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/lib/index.js CHANGED
@@ -8,10 +8,12 @@
8
8
  * stopping or updating the row releases all three with no residue.
9
9
  */
10
10
  import { homedir } from 'node:os';
11
+ import { dirname, join } from 'node:path';
12
+ import { z } from 'zod';
11
13
  import { Config, resolveConfig, resolveNotesDir } from './config.js';
12
14
  import { StickyWallStore } from './store.js';
13
15
  import { createExecuteRoute } from './transport.js';
14
- import { LEGACY_DOMAIN_NAME, LEGACY_DOMAIN_VERSION, LIMITS } from './types.js';
16
+ import { COLORS, LEGACY_DOMAIN_NAME, LEGACY_DOMAIN_VERSION, LIMITS, WIDTHS } from './types.js';
15
17
  export { Config, StickyWallStore };
16
18
  export const name = 'skillre-sticky-wall';
17
19
  /**
@@ -30,6 +32,44 @@ export const inject = ['connection'];
30
32
  function service(ctx, key) {
31
33
  return ctx.get(key);
32
34
  }
35
+ /**
36
+ * The record schema the legacy domain validates every stored note against.
37
+ *
38
+ * This MUST be a real schema. `storageDomain` runs
39
+ * `tableSpec.valueSchema.parse(raw)` on every record while opening the domain,
40
+ * so declaring the table as a bare `{}` makes `valueSchema` undefined, throws on
41
+ * the first record, and — because the spec asks for `invalidRecords:
42
+ * 'backup-and-skip'` — makes the backend move EVERY note aside as
43
+ * `<id>.json.bak.<stamp>` and treat it as absent. That is exactly what shipped
44
+ * in 0.8.0: the migration reported zero notes, seeded a welcome note, and the
45
+ * user's wall appeared empty while the data sat renamed on disk.
46
+ *
47
+ * It is deliberately permissive (`passthrough`, every field optional) because
48
+ * its job is to LOAD a retired format, not to police it: a record missing a
49
+ * field must still migrate with a sane default rather than be quarantined.
50
+ */
51
+ const LegacyNoteSchema = z
52
+ .object({
53
+ id: z.string().min(1),
54
+ title: z.string().optional(),
55
+ body: z.string().optional(),
56
+ tags: z.array(z.string()).optional(),
57
+ color: z.string().optional(),
58
+ pinned: z.boolean().optional(),
59
+ archived: z.boolean().optional(),
60
+ createdAt: z.string().optional(),
61
+ updatedAt: z.string().optional(),
62
+ layout: z
63
+ .object({
64
+ x: z.number(),
65
+ y: z.number(),
66
+ rotate: z.number(),
67
+ width: z.string(),
68
+ })
69
+ .nullable()
70
+ .optional(),
71
+ })
72
+ .passthrough();
33
73
  /**
34
74
  * Drain a 0.7.x install's storage-domain notes so they can be migrated.
35
75
  *
@@ -44,14 +84,42 @@ async function readLegacyNotes(facility) {
44
84
  name: LEGACY_DOMAIN_NAME,
45
85
  version: LEGACY_DOMAIN_VERSION,
46
86
  layout: 'per-record',
87
+ // `backup-and-skip` is kept: it is the only accepted value, and with a real
88
+ // schema it now means what it was meant to mean — one genuinely corrupt
89
+ // record is set aside instead of sinking the whole migration.
47
90
  invalidRecords: 'backup-and-skip',
48
- tables: { notes: {} },
91
+ tables: { notes: { valueSchema: LegacyNoteSchema } },
49
92
  });
50
93
  try {
51
94
  const notes = [];
52
- for (const [, value] of domain.table('notes').entries()) {
53
- if (value !== null && typeof value === 'object' && 'id' in value)
54
- notes.push(value);
95
+ for (const [key, value] of domain.table('notes').entries()) {
96
+ const record = value;
97
+ if (record === null || typeof record !== 'object')
98
+ continue;
99
+ const stamp = new Date().toISOString();
100
+ notes.push({
101
+ // The storage key IS the note id; trust it over a disagreeing field so a
102
+ // half-written record still migrates under the identity the wall stored.
103
+ id: typeof record.id === 'string' && record.id !== '' ? record.id : key,
104
+ title: typeof record.title === 'string' ? record.title : '',
105
+ body: typeof record.body === 'string' ? record.body : '',
106
+ tags: Array.isArray(record.tags) ? record.tags.map(String) : [],
107
+ color: COLORS.includes(String(record.color)) ? record.color : 'yellow',
108
+ pinned: record.pinned === true,
109
+ archived: record.archived === true,
110
+ createdAt: typeof record.createdAt === 'string' ? record.createdAt : stamp,
111
+ updatedAt: typeof record.updatedAt === 'string' ? record.updatedAt : stamp,
112
+ layout: record.layout === null || record.layout === undefined
113
+ ? null
114
+ : {
115
+ x: Number(record.layout.x) || 0,
116
+ y: Number(record.layout.y) || 0,
117
+ rotate: Number(record.layout.rotate) || 0,
118
+ width: WIDTHS.includes(String(record.layout.width))
119
+ ? record.layout.width
120
+ : 'md',
121
+ },
122
+ });
55
123
  }
56
124
  return notes;
57
125
  }
@@ -59,6 +127,17 @@ async function readLegacyNotes(facility) {
59
127
  await domain.close();
60
128
  }
61
129
  }
130
+ /**
131
+ * The directory a 0.7.x install's storage domain wrote its records into.
132
+ *
133
+ * It sits beside the notes directory, under the same DSH home, so it is derived
134
+ * rather than configured: `storages/<domain name>/notes`. The recovery path uses
135
+ * it to find the `<id>.json.bak.<stamp>` files a broken 0.8.0 run left behind.
136
+ */
137
+ function legacyNotesDirOf(notesDir) {
138
+ const home = dirname(dirname(notesDir));
139
+ return join(home, 'storages', LEGACY_DOMAIN_NAME, 'notes');
140
+ }
62
141
  /** Model-facing text for one tool result; short, deterministic and readable. */
63
142
  function renderWall(value) {
64
143
  const data = (value ?? {});
@@ -271,6 +350,10 @@ export function apply(ctx, rawConfig = {}) {
271
350
  maxNotes: config.maxNotes,
272
351
  seedWelcomeNote: config.seedWelcomeNote,
273
352
  readLegacy: facility?.open === undefined ? undefined : () => readLegacyNotes(facility),
353
+ // Where a broken 0.8.0 run quarantined the legacy records, so the corrected
354
+ // migration can recover them from `.bak` files instead of reporting an
355
+ // already-migrated wall and leaving the user's notes stranded.
356
+ legacyNotesDir: facility?.open === undefined ? undefined : legacyNotesDirOf(notesDir),
274
357
  log: (message) => ctx.logger?.warn?.(`sticky-wall: ${message}`),
275
358
  });
276
359
  ready.catch((error) => {
package/lib/migrate.d.ts CHANGED
@@ -42,6 +42,15 @@ export interface MigrateOptions {
42
42
  readLegacy: () => Promise<Note[]>;
43
43
  /** Clock for the marker's `at` field. */
44
44
  now?: (() => Date) | undefined;
45
+ /**
46
+ * Where the legacy records live on disk, when the caller knows.
47
+ *
48
+ * Only used to recover a wall that 0.8.0 left looking empty: that build
49
+ * quarantined every record as `<id>.json.bak.<stamp>` in this directory, so
50
+ * the files are the only remaining copy. Omit it and that recovery cannot run
51
+ * — which is correct for a caller that has no legacy medium at all.
52
+ */
53
+ legacyNotesDir?: string | undefined;
45
54
  }
46
55
  /**
47
56
  * Move the legacy notes into `notesDir`, or explain why there was nothing to do.
package/lib/migrate.js CHANGED
@@ -20,7 +20,7 @@
20
20
  import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
21
21
  import { dirname, join, resolve } from 'node:path';
22
22
  import { fileNameOf, idOfFile, isNoteId, parseNoteFile, serializeNoteFile } from './frontmatter.js';
23
- import { LEGACY_DOMAIN_NAME, LIMITS, MIGRATION_MARKER } from './types.js';
23
+ import { COLORS, LEGACY_DOMAIN_NAME, LIMITS, MIGRATION_MARKER, WIDTHS } from './types.js';
24
24
  /** The staging directory the migration writes into before publishing. */
25
25
  function stagingDirOf(notesDir) {
26
26
  return `${notesDir}.migrating`;
@@ -42,6 +42,157 @@ async function isAlreadyPresent(notesDir) {
42
42
  }
43
43
  return entries.some((name) => name === MIGRATION_MARKER || idOfFile(name) !== null);
44
44
  }
45
+ /**
46
+ * The marker value written by 0.8.0's BUGGY migration, if this note is it.
47
+ *
48
+ * 0.8.0 read zero legacy notes (its table spec had no `valueSchema`, so the
49
+ * domain quarantined every record) and then seeded the welcome note into an
50
+ * "empty" wall. A user who ran that build therefore has a notes directory that
51
+ * looks already-migrated and holds one seeded welcome note — and the corrected
52
+ * migration would refuse to run, leaving their real notes stranded in `.bak`
53
+ * files forever.
54
+ *
55
+ * The seeded note is identifiable: it is the welcome note, AND the only file in
56
+ * the directory. Both conditions are required. A user who genuinely has one note
57
+ * they wrote themselves must never have it confused with the seed.
58
+ */
59
+ const SEEDED_WELCOME_BODY = '随手记下一闪而过的灵感,或一件临时的工作。';
60
+ /** True when the directory holds nothing but 0.8.0's auto-seeded welcome note. */
61
+ async function isBuggyEmptyWall(notesDir) {
62
+ let entries;
63
+ try {
64
+ entries = await readdir(notesDir);
65
+ }
66
+ catch (error) {
67
+ const code = error.code;
68
+ if (code === 'ENOENT' || code === 'ENOTDIR')
69
+ return false;
70
+ throw error;
71
+ }
72
+ const files = entries.filter((name) => idOfFile(name) !== null);
73
+ if (files.length !== 1)
74
+ return false;
75
+ const only = files[0] ?? '';
76
+ if (idOfFile(only) !== 'welcome')
77
+ return false;
78
+ try {
79
+ const text = await readFile(join(notesDir, only), 'utf8');
80
+ return text.includes(SEEDED_WELCOME_BODY);
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /**
87
+ * Recover a wall that 0.8.0 left looking empty.
88
+ *
89
+ * The broken build quarantined every legacy record as `<id>.json.bak.<stamp>`
90
+ * and seeded a welcome note beside them. This reads the quarantined records
91
+ * straight from disk, writes each as a real `.md` next to the seeded note, and
92
+ * removes the seeded note afterwards so the user's own `welcome` note (if the
93
+ * 0.7.x wall had one) is the one that survives.
94
+ *
95
+ * It only ever ADDS notes and removes a note it identified as the seed: an
96
+ * existing `.md` is never overwritten, so a user who wrote something after
97
+ * upgrading keeps it.
98
+ */
99
+ async function recoverFromBuggyWall(notesDir, options) {
100
+ const legacyDir = options.legacyNotesDir;
101
+ if (legacyDir === undefined)
102
+ return { migrated: false, reason: 'already-present' };
103
+ let entries;
104
+ try {
105
+ entries = await readdir(legacyDir);
106
+ }
107
+ catch {
108
+ return { migrated: false, reason: 'already-present' };
109
+ }
110
+ // Prefer the newest quarantine stamp per note: a second boot of the broken
111
+ // build overwrites the earlier backup, and the newer bytes are the real ones.
112
+ const newest = new Map();
113
+ for (const name of entries) {
114
+ const match = name.match(/^(.*)\.json\.bak\.(\d+)$/);
115
+ if (match === null)
116
+ continue;
117
+ const id = match[1] ?? '';
118
+ if (!isNoteId(id))
119
+ continue;
120
+ const stamp = match[2] ?? '';
121
+ const previous = newest.get(id);
122
+ // The stamp is a zero-padded `YYYYMMDDHHmm`, so a lexical compare orders it.
123
+ if (previous === undefined || stamp >= previous.stamp)
124
+ newest.set(id, { file: name, stamp });
125
+ }
126
+ if (newest.size === 0)
127
+ return { migrated: false, reason: 'already-present' };
128
+ let written = 0;
129
+ for (const [id, { file }] of newest) {
130
+ const target = join(notesDir, fileNameOf(id));
131
+ // Never overwrite a note the user already has on the wall.
132
+ const exists = await stat(target).then(() => true, () => false);
133
+ if (exists)
134
+ continue;
135
+ try {
136
+ const envelope = JSON.parse(await readFile(join(legacyDir, file), 'utf8'));
137
+ const record = envelope.record;
138
+ if (record === null || typeof record !== 'object')
139
+ continue;
140
+ const note = normalizeLegacyRecord(record, id);
141
+ await writeFile(target, serializeNoteFile(note), 'utf8');
142
+ written += 1;
143
+ }
144
+ catch {
145
+ // A record that cannot be read stays quarantined on disk; one bad file
146
+ // must not stop the rest from coming back.
147
+ }
148
+ }
149
+ // The seeded welcome note is only removed when the user's own notes came back,
150
+ // so a failed recovery cannot leave them looking at an empty wall.
151
+ if (written > 0)
152
+ await rm(join(notesDir, fileNameOf('welcome')), { force: true });
153
+ return written === 0
154
+ ? { migrated: false, reason: 'already-present' }
155
+ : { migrated: true, reason: 'recovered-from-broken-migration', count: written };
156
+ }
157
+ /**
158
+ * Coerce one quarantined legacy record into a note this build can write.
159
+ *
160
+ * The backup files are raw storage envelopes left by a retired format, so every
161
+ * field is treated as untrusted: a missing or wrongly-typed value takes the same
162
+ * default a fresh note would use rather than aborting the recovery.
163
+ */
164
+ function normalizeLegacyRecord(record, id) {
165
+ const stamp = new Date().toISOString();
166
+ const text = (value, fallback) => (typeof value === 'string' ? value : fallback);
167
+ const colour = text(record['color'], 'yellow');
168
+ const rawLayout = record['layout'];
169
+ let layout = null;
170
+ if (rawLayout !== null && typeof rawLayout === 'object') {
171
+ const box = rawLayout;
172
+ const width = text(box['width'], 'md');
173
+ layout = {
174
+ x: Number(box['x']) || 0,
175
+ y: Number(box['y']) || 0,
176
+ rotate: Number(box['rotate']) || 0,
177
+ width: WIDTHS.includes(width) ? width : 'md',
178
+ };
179
+ }
180
+ const tags = Array.isArray(record['tags'])
181
+ ? record['tags'].map((tag) => String(tag).trim().toLowerCase()).filter((tag) => tag !== '').slice(0, LIMITS.tags)
182
+ : [];
183
+ return {
184
+ id,
185
+ title: text(record['title'], '').slice(0, LIMITS.title),
186
+ body: text(record['body'], ''),
187
+ tags,
188
+ color: COLORS.includes(colour) ? colour : 'yellow',
189
+ pinned: record['pinned'] === true,
190
+ archived: record['archived'] === true,
191
+ createdAt: text(record['createdAt'], stamp),
192
+ updatedAt: text(record['updatedAt'], stamp),
193
+ layout,
194
+ };
195
+ }
45
196
  /** Two timestamps name the same instant, tolerating format-only differences. */
46
197
  function sameInstant(left, right) {
47
198
  if (left === right)
@@ -86,8 +237,15 @@ export async function migrateNotes(options) {
86
237
  const staging = stagingDirOf(notesDir);
87
238
  let renamed = false;
88
239
  try {
89
- if (await isAlreadyPresent(notesDir))
90
- return { migrated: false, reason: 'already-present' };
240
+ if (await isAlreadyPresent(notesDir)) {
241
+ // A directory produced by 0.8.0's broken migration also counts as
242
+ // "present", but it is a false empty wall: recover from it instead of
243
+ // leaving the user's real notes quarantined in `.bak` files.
244
+ if (!(await isBuggyEmptyWall(notesDir)))
245
+ return { migrated: false, reason: 'already-present' };
246
+ const recovered = await recoverFromBuggyWall(notesDir, options);
247
+ return recovered;
248
+ }
91
249
  const legacy = await options.readLegacy();
92
250
  if (legacy.length === 0)
93
251
  return { migrated: false, reason: 'no-legacy' };
package/lib/store.d.ts CHANGED
@@ -70,6 +70,13 @@ export interface StoreOptions {
70
70
  * and nothing else — which is what the tests and any non-DSH caller want.
71
71
  */
72
72
  readLegacy?: (() => Promise<Note[]>) | undefined;
73
+ /**
74
+ * Where a broken 0.8.0 run quarantined the legacy records.
75
+ *
76
+ * Passed through to the migration so it can recover a wall that build left
77
+ * looking empty. Omit it when the caller has no legacy medium at all.
78
+ */
79
+ legacyNotesDir?: string | undefined;
73
80
  /** Injectable clock; tests use a stepping clock so timestamps are distinct. */
74
81
  now?: (() => Date) | undefined;
75
82
  /** Sink for non-fatal problems (an oversized or unreadable note file). */
package/lib/store.js CHANGED
@@ -205,6 +205,7 @@ export class StickyWallStore {
205
205
  const result = await migrateNotes({
206
206
  notesDir: store.notesDir,
207
207
  readLegacy: options.readLegacy,
208
+ ...(options.legacyNotesDir === undefined ? {} : { legacyNotesDir: options.legacyNotesDir }),
208
209
  ...(options.now === undefined ? {} : { now: options.now }),
209
210
  });
210
211
  if (!result.migrated && result.reason === 'failed') {
@@ -374,7 +375,14 @@ export class StickyWallStore {
374
375
  return;
375
376
  const stamp = this.now().toISOString();
376
377
  const note = {
377
- id: 'welcome',
378
+ // A RANDOM id, not the literal `welcome`.
379
+ //
380
+ // The seeded note used to be written as `welcome.md`, which is a legal id
381
+ // a 0.7.x wall could already own (the old seed used exactly that name). A
382
+ // migration that recovered such a note and then let the seed run would
383
+ // OVERWRITE the user's real note — which is precisely what happened during
384
+ // the 0.8.0 incident's second restart. A fresh UUID can never collide.
385
+ id: globalThis.crypto.randomUUID(),
378
386
  title: '便签墙',
379
387
  body: '随手记下一闪而过的灵感,或一件临时的工作。点右下角的 + 新建一张便签;按 ⌘/Ctrl + Enter 保存。',
380
388
  tags: ['开始'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillre/dsh-plugin-sticky-wall",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "便签墙:DSH 侧栏的自由画布便签板,可拖动摆放、一键整理,正文按 Markdown 渲染",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",