@hadoku/service-kernel 0.1.5 → 0.1.7

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.
@@ -22,13 +22,8 @@ export interface ReleaseOrdering {
22
22
  }
23
23
  /** The newest release notes in `dir`, by `ordering`, or null when there are none. */
24
24
  export declare function latestRelease(dir: string, ordering: ReleaseOrdering): Promise<ReleaseNotes | null>;
25
- /**
26
- * How many releases, newest first, a boot re-sends as edits. ArchiveBot keeps a post's record for 7
27
- * days and refuses an edit it has no record of, so older notes cannot be changed this way anyway.
28
- */
29
- export declare const EDITABLE_RELEASES = 3;
30
- /** The newest `count` release notes in `dir`, newest first, by `ordering`. */
31
- export declare function recentReleases(dir: string, ordering: ReleaseOrdering, count?: number): Promise<ReleaseNotes[]>;
25
+ /** Every release's notes in `dir`, newest first, by `ordering`. */
26
+ export declare function allReleases(dir: string, ordering: ReleaseOrdering): Promise<ReleaseNotes[]>;
32
27
  /** The `# ` heading is the title; everything after it is the body. */
33
28
  export declare function parseNotes(version: string, text: string): ReleaseNotes;
34
29
  /**
@@ -43,13 +38,29 @@ export declare function splitBody(body: string, max?: number): string[];
43
38
  * the gap: those go. Other blank lines, block starts and anything inside a code fence stay.
44
39
  */
45
40
  export declare function forDiscord(body: string): string;
41
+ /** Who a text credits: every `@name` in it, each once (case-insensitive), in the order it first names them. */
42
+ export declare function creditsIn(text: string): string[];
43
+ /** A credited name as the post shows it: bold, italic and underlined, its own markup characters escaped. */
44
+ export declare function creditMark(name: string): string;
45
+ /** Notes text with every `@name` credit shown as `creditMark(name)`: nobody is pinged. */
46
+ export declare function showCredits(text: string): string;
47
+ export declare function releaseEmbeds(notes: ReleaseNotes, appUrl: string): Embed[];
48
+ export interface CreditCount {
49
+ name: string;
50
+ count: number;
51
+ }
46
52
  /**
47
- * Who a release thanks: every `@name` in its notes, the hadoku name of whoever reported a bug the
48
- * release fixes (docs/RELEASE.md § "Attribution"), each once, in the order the notes first name them.
49
- * A sentence's closing full stop is not part of a name.
53
+ * How many things each person is credited with across `releases`: one per line of notes (a
54
+ * bullet) that names them, however often it does. Most credits first, then by name. Two spellings
55
+ * of one name differing only in case are one person, shown as first seen.
50
56
  */
51
- export declare function mentionsIn(body: string): string[];
52
- export declare function releaseEmbeds(notes: ReleaseNotes, appUrl: string): Embed[];
57
+ export declare function creditCounts(releases: readonly ReleaseNotes[]): CreditCount[];
58
+ export declare const CREDITS_TITLE = "Credits & attribution";
59
+ /**
60
+ * The credits post's text: everyone the notes credit, most first, with their count, then the people
61
+ * `earlier` names (credited before there were release notes). Null when it would name nobody.
62
+ */
63
+ export declare function creditsBody(releases: readonly ReleaseNotes[], earlier: readonly string[]): string | null;
53
64
  export interface AnnounceOptions {
54
65
  /** This app's id: the idempotency key and `source` field are `<service>-release-<version>` / `service`. */
55
66
  service: string;
@@ -59,6 +70,11 @@ export interface AnnounceOptions {
59
70
  secret: string;
60
71
  /** The secret's env var name, used only in the "no secret" skip log line. */
61
72
  secretEnvName: string;
73
+ /**
74
+ * A file whose `@name`s are the people credited before there were release notes, listed after
75
+ * the counts in the credits post. Absent or missing file: nobody.
76
+ */
77
+ earlierCreditsFile?: string;
62
78
  archivebotUrl: string;
63
79
  appUrl: string;
64
80
  log: JsonLog;
@@ -66,9 +82,10 @@ export interface AnnounceOptions {
66
82
  now?: () => Date;
67
83
  }
68
84
  /**
69
- * Post the current release's notes, then re-send the newest few as edits, so a corrected notes file
70
- * (a credit added to a bullet, a typo) changes its post at the next boot. ArchiveBot edits only a post
71
- * whose shown text differs and never posts from an edit. Resolves on every outcome; the outcome is
72
- * logged, never thrown.
85
+ * At boot, in this order: delete the credits post of every older release (404, none on record, is
86
+ * the usual answer); post the current release's notes; re-send every release's notes as edits, so a
87
+ * corrected notes file (a credit added, a typo) changes its post; then post the current release's
88
+ * credits, or edit them when already posted. ArchiveBot edits only a post whose shown text differs
89
+ * and never posts from an edit. Resolves on every outcome; each is logged, never thrown.
73
90
  */
74
91
  export declare function announceRelease(options: AnnounceOptions): Promise<void>;
@@ -6,9 +6,14 @@
6
6
  * idempotency key `<service>-release-<version>` is deduped by ArchiveBot for 7 days, so a restart
7
7
  * posts nothing new.
8
8
  *
9
- * A bug's reporter is named in its bullet as `@name` (their hadoku name; docs/RELEASE.md § "Attribution").
10
- * Those names ride as `mentions`, and ArchiveBot turns each `@name` in the notes into the person's
11
- * Discord mention, inline where the bullet credits them. No separate thank-you line.
9
+ * Whoever a bullet credits is named in it as `@name` (docs/RELEASE.md § "Attribution"). The post
10
+ * shows each as ***__name__*** (bold, italic, underlined) and pings nobody: the operator, 2026-11-09,
11
+ * "we should not do discord @ mentions anymore".
12
+ *
13
+ * Under the newest notes stands one credits post, "Credits & attribution": everyone the notes have
14
+ * ever credited, most credits first, and the people the app's earlier-credits file names, who helped
15
+ * before there were release notes. Each release deletes the previous release's credits post and
16
+ * posts its own after its notes, so the credits are always the newest post.
12
17
  *
13
18
  * `secret` is the app's webhook secret (empty = skip, never an error); a failed post never blocks
14
19
  * boot, and the next boot retries it.
@@ -32,14 +37,9 @@ export async function latestRelease(dir, ordering) {
32
37
  return null;
33
38
  return parseNotes(newest.slice(0, -'.md'.length), await readFile(join(dir, newest), 'utf8'));
34
39
  }
35
- /**
36
- * How many releases, newest first, a boot re-sends as edits. ArchiveBot keeps a post's record for 7
37
- * days and refuses an edit it has no record of, so older notes cannot be changed this way anyway.
38
- */
39
- export const EDITABLE_RELEASES = 3;
40
- /** The newest `count` release notes in `dir`, newest first, by `ordering`. */
41
- export async function recentReleases(dir, ordering, count = EDITABLE_RELEASES) {
42
- const names = ordering.newestFirst(await readdir(dir)).slice(0, count);
40
+ /** Every release's notes in `dir`, newest first, by `ordering`. */
41
+ export async function allReleases(dir, ordering) {
42
+ const names = ordering.newestFirst(await readdir(dir));
43
43
  return Promise.all(names.map(async (name) => parseNotes(name.slice(0, -'.md'.length), await readFile(join(dir, name), 'utf8'))));
44
44
  }
45
45
  /** The `# ` heading is the title; everything after it is the body. */
@@ -116,39 +116,86 @@ export function forDiscord(body) {
116
116
  const heading = (line) => line !== undefined && line.trimStart().startsWith('#');
117
117
  return out.filter((line, i) => line.trim() !== '' || !(heading(out[i - 1]) || heading(out[i + 1]))).join('\n');
118
118
  }
119
- /**
120
- * Who a release thanks: every `@name` in its notes, the hadoku name of whoever reported a bug the
121
- * release fixes (docs/RELEASE.md § "Attribution"), each once, in the order the notes first name them.
122
- * A sentence's closing full stop is not part of a name.
123
- */
124
- export function mentionsIn(body) {
119
+ /** A credit in notes text: `@name`, not inside a word, a path or an address; a closing full stop is not part of it. */
120
+ const CREDIT = /(?<![\w@/])@([A-Za-z0-9_.-]*[A-Za-z0-9_])/g;
121
+ /** Who a text credits: every `@name` in it, each once (case-insensitive), in the order it first names them. */
122
+ export function creditsIn(text) {
125
123
  const names = new Map();
126
- for (const match of body.matchAll(/(?<![\w@/])@([A-Za-z0-9_.-]+)/g)) {
127
- const name = match[1].replace(/[.-]+$/, '');
128
- if (name !== '' && !names.has(name.toLowerCase()))
129
- names.set(name.toLowerCase(), name);
124
+ for (const match of text.matchAll(CREDIT)) {
125
+ if (!names.has(match[1].toLowerCase()))
126
+ names.set(match[1].toLowerCase(), match[1]);
130
127
  }
131
128
  return [...names.values()];
132
129
  }
130
+ /** A credited name as the post shows it: bold, italic and underlined, its own markup characters escaped. */
131
+ export function creditMark(name) {
132
+ return `***__${name.replace(/[\\*_~`|]/g, (c) => `\\${c}`)}__***`;
133
+ }
134
+ /** Notes text with every `@name` credit shown as `creditMark(name)`: nobody is pinged. */
135
+ export function showCredits(text) {
136
+ return text.replace(CREDIT, (_, name) => creditMark(name));
137
+ }
133
138
  export function releaseEmbeds(notes, appUrl) {
134
- return splitBody(forDiscord(notes.body)).map((description, i) => ({
139
+ return splitBody(showCredits(forDiscord(notes.body))).map((description, i) => ({
135
140
  ...(i === 0 ? { title: notes.title } : {}),
136
141
  description,
137
142
  url: appUrl,
138
143
  color: 0x2f855a,
139
144
  }));
140
145
  }
141
- /** The signed ArchiveBot request for one release's notes: its idempotency key is the release's own. */
146
+ /**
147
+ * How many things each person is credited with across `releases`: one per line of notes (a
148
+ * bullet) that names them, however often it does. Most credits first, then by name. Two spellings
149
+ * of one name differing only in case are one person, shown as first seen.
150
+ */
151
+ export function creditCounts(releases) {
152
+ const counts = new Map();
153
+ for (const notes of releases) {
154
+ for (const line of forDiscord(notes.body).split('\n')) {
155
+ for (const name of creditsIn(line)) {
156
+ const key = name.toLowerCase();
157
+ const entry = counts.get(key) ?? { name, count: 0 };
158
+ entry.count += 1;
159
+ counts.set(key, entry);
160
+ }
161
+ }
162
+ }
163
+ return [...counts.values()].sort((a, b) => b.count - a.count || a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
164
+ }
165
+ export const CREDITS_TITLE = 'Credits & attribution';
166
+ /**
167
+ * The credits post's text: everyone the notes credit, most first, with their count, then the people
168
+ * `earlier` names (credited before there were release notes). Null when it would name nobody.
169
+ */
170
+ export function creditsBody(releases, earlier) {
171
+ const counts = creditCounts(releases);
172
+ if (counts.length === 0 && earlier.length === 0)
173
+ return null;
174
+ const sections = [];
175
+ if (counts.length > 0) {
176
+ sections.push(['## In the release notes', ...counts.map((c, i) => `${i + 1}. ${creditMark(c.name)} — ${c.count}`)].join('\n'));
177
+ }
178
+ if (earlier.length > 0)
179
+ sections.push(['## Before the release notes', earlier.map(creditMark).join(', ')].join('\n'));
180
+ return sections.join('\n');
181
+ }
182
+ /**
183
+ * The signed ArchiveBot request for one release's notes: its idempotency key is the release's own,
184
+ * its record is kept for good (`retain`), and an edit with no record finds the post by its title's
185
+ * version (`find`), so a release of any age can still be corrected.
186
+ */
142
187
  function notesPayload(service, notes, appUrl, now) {
143
- const mentions = mentionsIn(notes.body);
188
+ const titlePrefix = notes.title.startsWith(`${notes.version} `) ? `${notes.version} ` : notes.title;
144
189
  return JSON.stringify({
145
190
  idempotencyKey: `${service}-release-${notes.version}`,
146
191
  timestamp: now.getTime(),
147
192
  source: service,
148
- ...(mentions.length === 0 ? {} : { mentions }),
193
+ retain: true,
194
+ find: { titlePrefix },
149
195
  embeds: releaseEmbeds(notes, appUrl),
150
196
  });
151
197
  }
198
+ const creditsKey = (service, version) => `${service}-credits-${version}`;
152
199
  async function postSigned(options, path, body) {
153
200
  const signature = createHmac('sha256', options.secret).update(body).digest('hex');
154
201
  return (options.fetch ?? fetch)(`${options.archivebotUrl}${path}`, {
@@ -158,11 +205,30 @@ async function postSigned(options, path, body) {
158
205
  signal: AbortSignal.timeout(10_000),
159
206
  });
160
207
  }
208
+ /** POST `body` to ArchiveBot's `path`: the status, the raw reply, and a 2xx reply parsed (`{}` otherwise). */
209
+ async function call(options, path, body) {
210
+ const res = await postSigned(options, path, body);
211
+ const raw = await res.text();
212
+ return { status: res.status, ok: res.ok, raw, answer: res.ok ? JSON.parse(raw) : {} };
213
+ }
214
+ async function readEarlierCredits(file) {
215
+ if (file === undefined)
216
+ return [];
217
+ try {
218
+ return creditsIn(await readFile(file, 'utf8'));
219
+ }
220
+ catch (err) {
221
+ if (err.code === 'ENOENT')
222
+ return [];
223
+ throw err;
224
+ }
225
+ }
161
226
  /**
162
- * Post the current release's notes, then re-send the newest few as edits, so a corrected notes file
163
- * (a credit added to a bullet, a typo) changes its post at the next boot. ArchiveBot edits only a post
164
- * whose shown text differs and never posts from an edit. Resolves on every outcome; the outcome is
165
- * logged, never thrown.
227
+ * At boot, in this order: delete the credits post of every older release (404, none on record, is
228
+ * the usual answer); post the current release's notes; re-send every release's notes as edits, so a
229
+ * corrected notes file (a credit added, a typo) changes its post; then post the current release's
230
+ * credits, or edit them when already posted. ArchiveBot edits only a post whose shown text differs
231
+ * and never posts from an edit. Resolves on every outcome; each is logged, never thrown.
166
232
  */
167
233
  export async function announceRelease(options) {
168
234
  const { log, service, ordering } = options;
@@ -171,62 +237,86 @@ export async function announceRelease(options) {
171
237
  return;
172
238
  }
173
239
  const now = () => (options.now ?? (() => new Date()))();
240
+ let releases;
174
241
  try {
175
- const notes = await latestRelease(options.releasesDir, ordering);
176
- if (notes === null) {
177
- log({ event: 'release-announce', outcome: 'skipped', reason: `no release notes in ${options.releasesDir}` });
178
- return;
179
- }
180
- const res = await postSigned(options, '/api/messages/send', notesPayload(service, notes, options.appUrl, now()));
181
- const reply = await res.text();
182
- if (!res.ok) {
183
- log({ event: 'release-announce', outcome: 'failed', version: notes.version, status: res.status, reply: reply.slice(0, 500) });
184
- return;
185
- }
186
- const answer = JSON.parse(reply);
187
- log({
188
- event: 'release-announce',
189
- outcome: answer.deduped === true ? 'already-posted' : 'posted',
190
- version: notes.version,
191
- // A name ArchiveBot could not match to anyone is posted as plain text: say so, so it can be fixed.
192
- ...(answer.unresolved !== undefined && answer.unresolved.length > 0 ? { unresolved: answer.unresolved } : {}),
193
- });
242
+ releases = await allReleases(options.releasesDir, ordering);
194
243
  }
195
244
  catch (err) {
196
245
  log({ event: 'release-announce', outcome: 'failed', error: err instanceof Error ? err.message : String(err) });
197
246
  return;
198
247
  }
199
- let recent;
248
+ const notes = releases[0];
249
+ if (notes === undefined) {
250
+ log({ event: 'release-announce', outcome: 'skipped', reason: `no release notes in ${options.releasesDir}` });
251
+ return;
252
+ }
253
+ for (const older of releases.slice(1)) {
254
+ try {
255
+ const res = await call(options, '/api/messages/delete', JSON.stringify({ idempotencyKey: creditsKey(service, older.version), timestamp: now().getTime(), source: service }));
256
+ if (res.status === 404)
257
+ continue;
258
+ log({ event: 'release-credits', outcome: res.ok ? 'deleted' : 'failed', version: older.version, ...(res.ok ? {} : { status: res.status, reply: res.raw.slice(0, 500) }) });
259
+ }
260
+ catch (err) {
261
+ log({ event: 'release-credits', outcome: 'failed', version: older.version, error: err instanceof Error ? err.message : String(err) });
262
+ }
263
+ }
200
264
  try {
201
- recent = await recentReleases(options.releasesDir, ordering);
265
+ const res = await call(options, '/api/messages/send', notesPayload(service, notes, options.appUrl, now()));
266
+ if (!res.ok) {
267
+ log({ event: 'release-announce', outcome: 'failed', version: notes.version, status: res.status, reply: res.raw.slice(0, 500) });
268
+ return;
269
+ }
270
+ log({ event: 'release-announce', outcome: res.answer.deduped === true ? 'already-posted' : 'posted', version: notes.version });
202
271
  }
203
272
  catch (err) {
204
- log({ event: 'release-edit', outcome: 'failed', error: err instanceof Error ? err.message : String(err) });
273
+ log({ event: 'release-announce', outcome: 'failed', version: notes.version, error: err instanceof Error ? err.message : String(err) });
205
274
  return;
206
275
  }
207
- for (const notes of recent) {
276
+ for (const release of releases) {
208
277
  try {
209
- const res = await postSigned(options, '/api/messages/edit', notesPayload(service, notes, options.appUrl, now()));
210
- const reply = await res.text();
211
- // 404: ArchiveBot holds no post for it (older than its 7-day record): nothing to change.
278
+ const res = await call(options, '/api/messages/edit', notesPayload(service, release, options.appUrl, now()));
279
+ // 404: no post for it, on record or in the channel's history: nothing to change.
212
280
  if (res.status === 404)
213
281
  continue;
214
282
  if (!res.ok) {
215
- log({ event: 'release-edit', outcome: 'failed', version: notes.version, status: res.status, reply: reply.slice(0, 500) });
283
+ log({ event: 'release-edit', outcome: 'failed', version: release.version, status: res.status, reply: res.raw.slice(0, 500) });
216
284
  continue;
217
285
  }
218
- const answer = JSON.parse(reply);
219
- if (answer.edited !== true)
220
- continue;
221
- log({
222
- event: 'release-edit',
223
- outcome: 'edited',
224
- version: notes.version,
225
- ...(answer.unresolved !== undefined && answer.unresolved.length > 0 ? { unresolved: answer.unresolved } : {}),
226
- });
286
+ if (res.answer.edited === true)
287
+ log({ event: 'release-edit', outcome: 'edited', version: release.version });
227
288
  }
228
289
  catch (err) {
229
- log({ event: 'release-edit', outcome: 'failed', version: notes.version, error: err instanceof Error ? err.message : String(err) });
290
+ log({ event: 'release-edit', outcome: 'failed', version: release.version, error: err instanceof Error ? err.message : String(err) });
230
291
  }
231
292
  }
293
+ try {
294
+ const body = creditsBody(releases, await readEarlierCredits(options.earlierCreditsFile));
295
+ if (body === null)
296
+ return;
297
+ const payload = (at) => JSON.stringify({
298
+ idempotencyKey: creditsKey(service, notes.version),
299
+ timestamp: at.getTime(),
300
+ source: service,
301
+ retain: true,
302
+ embeds: splitBody(body).map((description, i) => ({ ...(i === 0 ? { title: CREDITS_TITLE } : {}), description, url: options.appUrl, color: 0x2f855a })),
303
+ });
304
+ const sent = await call(options, '/api/messages/send', payload(now()));
305
+ if (!sent.ok) {
306
+ log({ event: 'release-credits', outcome: 'failed', version: notes.version, status: sent.status, reply: sent.raw.slice(0, 500) });
307
+ return;
308
+ }
309
+ if (sent.answer.deduped !== true) {
310
+ log({ event: 'release-credits', outcome: 'posted', version: notes.version });
311
+ return;
312
+ }
313
+ const edited = await call(options, '/api/messages/edit', payload(now()));
314
+ if (!edited.ok)
315
+ log({ event: 'release-credits', outcome: 'failed', version: notes.version, status: edited.status, reply: edited.raw.slice(0, 500) });
316
+ else if (edited.answer.edited === true)
317
+ log({ event: 'release-credits', outcome: 'edited', version: notes.version });
318
+ }
319
+ catch (err) {
320
+ log({ event: 'release-credits', outcome: 'failed', version: notes.version, error: err instanceof Error ? err.message : String(err) });
321
+ }
232
322
  }
@@ -1,4 +1,4 @@
1
1
  export { busyHandler, isLocalProbe, type BusyReport, type BusyRun } from './busy.js';
2
2
  export { bootClock } from './bootClock.js';
3
3
  export { closeConnections, sendThenFlush, type Closable, type Flushable } from './flush-sockets.js';
4
- export { announceRelease, EDITABLE_RELEASES, forDiscord, latestRelease, mentionsIn, parseNotes, recentReleases, releaseEmbeds, splitBody, type AnnounceOptions, type Embed, type ReleaseNotes, type ReleaseOrdering, } from './announce.js';
4
+ export { allReleases, announceRelease, creditCounts, creditMark, creditsBody, creditsIn, CREDITS_TITLE, forDiscord, latestRelease, parseNotes, releaseEmbeds, showCredits, splitBody, type AnnounceOptions, type CreditCount, type Embed, type ReleaseNotes, type ReleaseOrdering, } from './announce.js';
@@ -1,4 +1,4 @@
1
1
  export { busyHandler, isLocalProbe } from "./busy.js";
2
2
  export { bootClock } from "./bootClock.js";
3
3
  export { closeConnections, sendThenFlush } from "./flush-sockets.js";
4
- export { announceRelease, EDITABLE_RELEASES, forDiscord, latestRelease, mentionsIn, parseNotes, recentReleases, releaseEmbeds, splitBody, } from "./announce.js";
4
+ export { allReleases, announceRelease, creditCounts, creditMark, creditsBody, creditsIn, CREDITS_TITLE, forDiscord, latestRelease, parseNotes, releaseEmbeds, showCredits, splitBody, } from "./announce.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/service-kernel",
3
- "version": "0.1.5",
4
- "gitHead": "84616ba324f2080db27dea12049f4cfa4121e3d1",
3
+ "version": "0.1.7",
4
+ "gitHead": "6e5c08714648a3a0cb50946f8194f656d998beb0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any game keeps: edge auth and the tier gate, base path and bundle check, health and the busy probe, lifecycle, the JSON logger, the state directory, telemetry and capacity, per-caller limits, the browser relays, the erase registry, and createGameServer, which boots a game from its config and plugins. Knows no game; the app binds its service id, prefix and env names. MIT; imports only node built-ins, express, socket.io and @wolffm/*.",
@@ -56,8 +56,8 @@
56
56
  }
57
57
  },
58
58
  "dependencies": {
59
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.66",
60
- "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.66",
59
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.68",
60
+ "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.68",
61
61
  "express": "^5.1.0",
62
62
  "socket.io": "^4.8.3"
63
63
  },