@hop-top/kit 0.5.0-alpha.12 → 0.5.0-alpha.14

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 (125) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +5 -5
  3. package/dist/bus-D2bAOPYz.d.ts +55 -0
  4. package/dist/bus.d.ts +1 -0
  5. package/dist/bus.js +13 -0
  6. package/dist/chunk-74E6RNOI.js +82 -0
  7. package/dist/chunk-B7XTFDBB.js +17 -0
  8. package/dist/chunk-CAONBSPO.js +497 -0
  9. package/dist/chunk-F7RSL4N4.js +88 -0
  10. package/dist/chunk-I6XDPSXQ.js +75 -0
  11. package/dist/chunk-IDM6YZXN.js +204 -0
  12. package/dist/{chunk-BXJ2J27B.js → chunk-IGKBRNEW.js} +10 -10
  13. package/dist/{chunk-VWGP4NVJ.js → chunk-MDVGMOZO.js} +45 -39
  14. package/dist/{chunk-4FMALWYB.js → chunk-MEF7W3MG.js} +45 -45
  15. package/dist/{chunk-VGOA5Y7S.js → chunk-Q547MHNB.js} +11 -11
  16. package/dist/{chunk-K7E34Q3A.js → chunk-TUU2BY5I.js} +136 -47
  17. package/dist/chunk-VKQCOVKI.js +880 -0
  18. package/dist/cli.js +3 -3
  19. package/dist/index-BqZ7WGQf.d.ts +731 -0
  20. package/dist/index.d.ts +8 -5
  21. package/dist/index.js +32 -18
  22. package/dist/{llm-DYuR7_uX.d.ts → llm-BazFKc_2.d.ts} +95 -9
  23. package/dist/{llm-anthropic-Cd_I2xXB.d.ts → llm-anthropic-BcAitoDV.d.ts} +1 -1
  24. package/dist/llm-anthropic.d.ts +2 -2
  25. package/dist/llm-anthropic.js +4 -4
  26. package/dist/{llm-openai-DyFrucmV.d.ts → llm-openai-CSDvuRH6.d.ts} +1 -1
  27. package/dist/llm-openai.d.ts +2 -2
  28. package/dist/llm-openai.js +4 -4
  29. package/dist/llm.d.ts +1 -1
  30. package/dist/llm.js +8 -2
  31. package/dist/{routellm-B0nv59mH.d.ts → routellm-B9UrONPr.d.ts} +1 -1
  32. package/dist/routellm.d.ts +2 -2
  33. package/dist/routellm.js +5 -5
  34. package/dist/upgrade/drivers/configfile.d.ts +45 -0
  35. package/dist/upgrade/drivers/configfile.js +78 -0
  36. package/dist/upgrade/drivers/fsdir.d.ts +61 -0
  37. package/dist/upgrade/drivers/fsdir.js +170 -0
  38. package/dist/upgrade/drivers/postgres.d.ts +121 -0
  39. package/dist/upgrade/drivers/postgres.js +195 -0
  40. package/dist/upgrade/drivers/sqlite.d.ts +101 -0
  41. package/dist/upgrade/drivers/sqlite.js +241 -0
  42. package/dist/upgrade/index.d.ts +2 -0
  43. package/dist/upgrade/index.js +73 -0
  44. package/dist/uri-IJ_AoY3d.d.ts +144 -0
  45. package/dist/uri.d.ts +1 -0
  46. package/dist/uri.js +37 -0
  47. package/dist/version-DEJ3pbiO.d.ts +10 -0
  48. package/dist/wizard-Bf_qHc31.d.ts +159 -0
  49. package/dist/wizard.d.ts +1 -0
  50. package/dist/wizard.js +39 -0
  51. package/package.json +76 -17
  52. package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
  53. package/skills/hop-top-kit-ts/SKILL.md +117 -0
  54. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
  55. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
  56. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
  57. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
  58. package/skills/hop-top-kit-ts/gym.json +5 -0
  59. package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
  60. package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
  61. package/skills/hop-top-kit-ts/references/coverage.md +56 -0
  62. package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
  63. package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
  64. package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
  65. package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
  66. package/src/index.test.ts +48 -2
  67. package/src/index.ts +6 -1
  68. package/src/llm-anthropic.conformance.test.ts +7 -0
  69. package/src/llm-boundkey.test.ts +260 -0
  70. package/src/llm-choice-hermetic.test.ts +1 -1
  71. package/src/llm-config.test.ts +2 -4
  72. package/src/llm-config.ts +5 -1
  73. package/src/llm-endpoint.ts +25 -5
  74. package/src/llm-keys.ts +47 -15
  75. package/src/llm-openai.test.ts +10 -4
  76. package/src/llm-openai.ts +7 -1
  77. package/src/llm-spec.test.ts +347 -0
  78. package/src/llm-spec.ts +80 -0
  79. package/src/llm-uri.ts +96 -12
  80. package/src/llm.test.ts +2 -2
  81. package/src/llm.ts +10 -0
  82. package/src/published-types.test.ts +8 -0
  83. package/src/serve.stopped-order.test.ts +156 -0
  84. package/src/upgrade/README.md +42 -0
  85. package/src/upgrade/backup.ts +174 -0
  86. package/src/upgrade/conformance.test.ts +310 -0
  87. package/src/upgrade/document.ts +229 -0
  88. package/src/upgrade/driver.ts +66 -0
  89. package/src/upgrade/drivers/README.md +47 -0
  90. package/src/upgrade/drivers/configfile.test.ts +112 -0
  91. package/src/upgrade/drivers/configfile.ts +107 -0
  92. package/src/upgrade/drivers/fsdir.test.ts +188 -0
  93. package/src/upgrade/drivers/fsdir.ts +216 -0
  94. package/src/upgrade/drivers/isolation.test.ts +18 -0
  95. package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
  96. package/src/upgrade/drivers/postgres.test.ts +272 -0
  97. package/src/upgrade/drivers/postgres.ts +284 -0
  98. package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
  99. package/src/upgrade/drivers/sqlite.ts +300 -0
  100. package/src/upgrade/drivers/version.ts +21 -0
  101. package/src/upgrade/errors.ts +117 -0
  102. package/src/upgrade/events.ts +117 -0
  103. package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
  104. package/src/{upgrade.ts → upgrade/index.ts} +20 -0
  105. package/src/upgrade/migration.ts +89 -0
  106. package/src/upgrade/migrator.test.ts +391 -0
  107. package/src/upgrade/migrator.ts +527 -0
  108. package/src/upgrade/options.ts +59 -0
  109. package/src/upgrade/semver.ts +90 -0
  110. package/test/llm/conformance-helpers.ts +3 -0
  111. package/test/skill-snippets.test.ts +60 -0
  112. package/test/upgrade/conformance-migrator.ts +439 -0
  113. package/test/upgrade/conformance-support.ts +44 -0
  114. package/test/upgrade/driver-support.ts +44 -0
  115. package/test/upgrade/pg-container.ts +64 -0
  116. package/test/upgrade/pg-race-worker.ts +48 -0
  117. package/test/upgrade/race-helper.ts +36 -0
  118. package/test/upgrade/sqlite-support.ts +41 -0
  119. package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
  120. package/vitest.config.ts +26 -0
  121. package/dist/chunk-X4E5QGEB.js +0 -171
  122. package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
  123. package/dist/upgrade.d.ts +0 -1
  124. package/dist/upgrade.js +0 -9
  125. package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
package/src/llm-uri.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { URI } from "./llm";
9
- import { redactURI } from "./llm-endpoint";
9
+ import { credentialParam, redactURI } from "./llm-endpoint";
10
10
  import { LLMError } from "./llm-error";
11
11
  import { goQuote } from "./llm-quote";
12
12
 
@@ -18,13 +18,24 @@ import { goQuote } from "./llm-quote";
18
18
  * `ollama://[::1]:11434/llama3`) when it splits as `host:port` with a
19
19
  * non-empty port; otherwise the whole path is the model
20
20
  * (`openrouter://openai/gpt-4.1-nano`). The query splits on `&`, each
21
- * pair on its first `=`, and is not percent-decoded; a param without
22
- * `=` is `""`, one with an empty name is dropped. `params` is absent
23
- * when none is left.
21
+ * pair on its first `=`; a param without `=` is `""`, one with an
22
+ * empty name is dropped. `params` is absent when none is left.
23
+ *
24
+ * The model and each param name and value are percent-decoded after
25
+ * the URI is split, so an escaped `?`, `&` or `#` is part of the text,
26
+ * never a separator: `x%3Fbase_url%3Dhttps%3A%2F%2Fevil` is a model of
27
+ * that literal text and sets no `base_url`. Only `%XX` is decoded; `+`
28
+ * stays `+`, so a key holding one survives. A malformed escape (or one
29
+ * that does not decode to UTF-8) is an error, as is a `base_url` or
30
+ * credential param (`api_key`, `token`, ...) named twice, whichever
31
+ * value would win; other params are last-wins. Build a URI from parts
32
+ * with {@link specURI}, never by concatenation: a raw `?` or `&` in a
33
+ * part still splits.
24
34
  *
25
35
  * Throws an {@link LLMError} (`empty URI`, `missing scheme in URI
26
- * "..."`, `empty scheme in URI "..."`) quoting `raw` with its
27
- * credentials masked by {@link redactURI}.
36
+ * "..."`, `empty scheme in URI "..."`, `malformed percent-escape in
37
+ * URI "..."`, `duplicate "name" param in URI "..."`) quoting `raw` with
38
+ * its credentials masked by {@link redactURI}.
28
39
  */
29
40
  export function parseURI(raw: string): URI {
30
41
  if (raw === "") throw new LLMError("empty URI");
@@ -37,7 +48,7 @@ export function parseURI(raw: string): URI {
37
48
  let params: Record<string, string> | undefined;
38
49
  const q = rest.indexOf("?");
39
50
  if (q >= 0) {
40
- params = parseQuery(rest.slice(q + 1));
51
+ params = parseQuery(rest.slice(q + 1), raw);
41
52
  rest = rest.slice(0, q);
42
53
  }
43
54
 
@@ -52,26 +63,99 @@ export function parseURI(raw: string): URI {
52
63
  }
53
64
  }
54
65
 
55
- const uri: URI = { scheme, model };
66
+ // Split first, decode after: an escaped separator stays text.
67
+ const decoded = percentDecode(model);
68
+ if (decoded === undefined) throw malformed(raw);
69
+ const uri: URI = { scheme, model: decoded };
56
70
  if (host !== "") uri.host = host;
57
71
  if (params && Object.keys(params).length > 0) uri.params = params;
58
72
  return uri;
59
73
  }
60
74
 
61
- function parseQuery(qs: string): Record<string, string> | undefined {
75
+ function parseQuery(qs: string, raw: string): Record<string, string> | undefined {
62
76
  if (qs === "") return undefined;
63
77
  const m: Record<string, string> = {};
64
78
  for (const pair of qs.split("&")) {
65
79
  const eq = pair.indexOf("=");
66
- const k = eq < 0 ? pair : pair.slice(0, eq);
67
- const v = eq < 0 ? "" : pair.slice(eq + 1);
68
- if (k === "") continue;
80
+ const rk = eq < 0 ? pair : pair.slice(0, eq);
81
+ const rv = eq < 0 ? "" : pair.slice(eq + 1);
82
+ if (rk === "") continue;
83
+ const k = percentDecode(rk);
84
+ const v = percentDecode(rv);
85
+ if (k === undefined || v === undefined) throw malformed(raw);
86
+ // Which of two security params wins must never depend on what a
87
+ // caller appended.
88
+ if (Object.prototype.hasOwnProperty.call(m, k) && (k === "base_url" || credentialParam(k))) {
89
+ throw new LLMError(`duplicate ${goQuote(k)} param in URI ${goQuote(redactURI(raw))}`);
90
+ }
69
91
  // An own property even for "__proto__": never the prototype.
70
92
  Object.defineProperty(m, k, { value: v, enumerable: true, writable: true, configurable: true });
71
93
  }
72
94
  return m;
73
95
  }
74
96
 
97
+ function malformed(raw: string): LLMError {
98
+ return new LLMError(`malformed percent-escape in URI ${goQuote(redactURI(raw))}`);
99
+ }
100
+
101
+ /**
102
+ * Percent-decodes `s`: `%XX` only, `+` stays `+`. Undefined for an
103
+ * escape that is not two hex digits or whose bytes are not UTF-8.
104
+ *
105
+ * @internal
106
+ */
107
+ export function percentDecode(s: string): string | undefined {
108
+ if (!s.includes("%")) return s;
109
+ if (/%(?![0-9A-Fa-f]{2})/.test(s)) return undefined;
110
+ try {
111
+ return s.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => decodeURIComponent(run));
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ }
116
+
117
+ const UNRESERVED = /[A-Za-z0-9\-._~]/;
118
+ const enc = new TextEncoder();
119
+
120
+ /**
121
+ * Percent-escapes everything but unreserved characters and those in
122
+ * `keep`, as UTF-8.
123
+ *
124
+ * @internal
125
+ */
126
+ export function escapeExcept(s: string, keep: string): string {
127
+ let out = "";
128
+ for (const ch of s) {
129
+ if (UNRESERVED.test(ch) || (ch.length === 1 && keep.includes(ch))) {
130
+ out += ch;
131
+ continue;
132
+ }
133
+ for (const b of enc.encode(ch)) out += `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
134
+ }
135
+ return out;
136
+ }
137
+
138
+ /**
139
+ * Escapes a param name or value as {@link parseURI} decodes it: `&`,
140
+ * `#`, `%`, `+` and `=` are escaped, `:` `/` `@` kept for readability.
141
+ *
142
+ * @internal
143
+ */
144
+ export function escapeParam(s: string): string {
145
+ return escapeExcept(s, ":/@");
146
+ }
147
+
148
+ /**
149
+ * Escapes a model: everything but unreserved characters, `/` and `@`,
150
+ * so `:` cannot pass for a host:port and `?`, `&`, `#` and `%` stay
151
+ * text.
152
+ *
153
+ * @internal
154
+ */
155
+ export function escapeModel(s: string): string {
156
+ return escapeExcept(s, "/@");
157
+ }
158
+
75
159
  /** Go `net.SplitHostPort`: undefined where Go returns an error. */
76
160
  function splitHostPort(hp: string): [string, string] | undefined {
77
161
  const i = hp.lastIndexOf(":");
package/src/llm.test.ts CHANGED
@@ -110,9 +110,9 @@ describe("parseURI", () => {
110
110
  expect(() => parseURI("")).toThrow("empty URI");
111
111
  });
112
112
 
113
- it("keeps param values as written: no percent-decoding", () => {
113
+ it("percent-decodes param values", () => {
114
114
  const uri = parseURI("openai://gpt-4?base_url=https%3A%2F%2Fx.test&flag");
115
- expect(uri.params).toEqual({ base_url: "https%3A%2F%2Fx.test", flag: "" });
115
+ expect(uri.params).toEqual({ base_url: "https://x.test", flag: "" });
116
116
  });
117
117
 
118
118
  it("takes an IPv6 host form", () => {
package/src/llm.ts CHANGED
@@ -57,6 +57,7 @@ import {
57
57
  } from "./llm-endpoint";
58
58
  import { loadConfig, type LoadOptions } from "./llm-config";
59
59
  import { parseURI } from "./llm-uri";
60
+ import { specURI, type Spec } from "./llm-spec";
60
61
  export {
61
62
  checkKeyEndpoint,
62
63
  credentialsTrusted,
@@ -65,6 +66,7 @@ export {
65
66
  } from "./llm-endpoint";
66
67
  export { loadConfig, parseURI, type LoadOptions };
67
68
  export { applyAPIKey } from "./llm-keys";
69
+ export { loadConfigSpec, specURI, type Spec } from "./llm-spec";
68
70
  export {
69
71
  requestStartedPayload,
70
72
  responseReceivedPayload,
@@ -757,6 +759,14 @@ export function resolve(uriStr: string, opts: LoadOptions = {}): Provider {
757
759
  return factory(cfg);
758
760
  }
759
761
 
762
+ /**
763
+ * {@link resolve} for a {@link Spec}: the Spec's parts are escaped
764
+ * into the URI, so no part can add a param of its own.
765
+ */
766
+ export function resolveSpec(s: Spec, opts: LoadOptions = {}): Provider {
767
+ return resolve(specURI(s), opts);
768
+ }
769
+
760
770
  /** Clear the registry (for tests). */
761
771
  export function clearRegistry(): void {
762
772
  registry.clear();
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { afterAll, beforeAll, describe, expect, it } from 'vitest';
17
17
  import { execFileSync } from 'node:child_process';
18
+ import { createRequire } from 'node:module';
18
19
  import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
19
20
  import * as path from 'node:path';
20
21
  import * as ts from 'typescript';
@@ -109,6 +110,13 @@ describe('published declarations', () => {
109
110
 
110
111
  afterAll(() => { rmSync(stageDir, { recursive: true, force: true }); });
111
112
 
113
+ // Runtime resolution through the package `exports` map, outside any test alias.
114
+ it.each(Object.keys(pkg.exports))('%s resolves and loads from the built package', (key) => {
115
+ const req = createRequire(files[1]);
116
+ const spec = key === '.' ? pkg.name : `${pkg.name}/${key.slice(2)}`;
117
+ expect(typeof req(spec)).toBe('object');
118
+ });
119
+
112
120
  it.each(Object.entries(modes).map(([name, m]) => [name, m.skipLibCheck] as const))(
113
121
  'type-check clean (moduleResolution %s, skipLibCheck %s)', (mode) => {
114
122
  const program = ts.createProgram(files, {
@@ -0,0 +1,156 @@
1
+ /**
2
+ * `stopped` is a service's Stop returning, so on a canceled run the
3
+ * events follow reverse start order however the cancellation and the
4
+ * Start returns interleave with the supervisor's wait.
5
+ */
6
+
7
+ import { describe, expect, it } from 'vitest';
8
+
9
+ import {
10
+ ServiceRegistry,
11
+ Supervisor,
12
+ type EventPayload,
13
+ type Publisher,
14
+ type Service,
15
+ type ServiceConfig,
16
+ } from './serve.js';
17
+
18
+ const enabled = (...names: string[]): Record<string, ServiceConfig> =>
19
+ Object.fromEntries(names.map((n) => [n, { enabled: true }]));
20
+
21
+ const sleep = (ms: number): Promise<void> =>
22
+ new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); });
23
+
24
+ const onAbort = (signal: AbortSignal): Promise<void> =>
25
+ new Promise((r) => {
26
+ if (signal.aborted) { r(); return; }
27
+ signal.addEventListener('abort', () => r(), { once: true });
28
+ });
29
+
30
+ /** Start returns as soon as the run is canceled. */
31
+ function onCancel(name: string, readyAfterMs = 0): Service {
32
+ return {
33
+ name,
34
+ async start(signal, ready) {
35
+ if (readyAfterMs > 0) await sleep(readyAfterMs);
36
+ ready();
37
+ await onAbort(signal);
38
+ },
39
+ ready: () => true,
40
+ async stop() { /* nothing to release */ },
41
+ };
42
+ }
43
+
44
+ /** Start returns only once its Stop was called: the listener shape. */
45
+ function untilStop(name: string, readyAfterMs = 0): Service {
46
+ let release!: () => void;
47
+ const released = new Promise<void>((r) => { release = r; });
48
+ return {
49
+ name,
50
+ async start(_signal, ready) {
51
+ if (readyAfterMs > 0) await sleep(readyAfterMs);
52
+ ready();
53
+ await released;
54
+ },
55
+ ready: () => true,
56
+ async stop() { release(); },
57
+ };
58
+ }
59
+
60
+ type Recorded = { topic: string; payload: EventPayload };
61
+
62
+ function recorder(
63
+ hook?: (e: Recorded) => void,
64
+ ): Publisher & { events: Recorded[]; stopped: () => string[] } {
65
+ const events: Recorded[] = [];
66
+ return {
67
+ events,
68
+ publish(e) {
69
+ const rec = { topic: e.topic, payload: e.payload };
70
+ events.push(rec);
71
+ hook?.(rec);
72
+ },
73
+ stopped: () => events
74
+ .filter((e) => e.topic === 'kit.serve.service.stopped')
75
+ .map((e) => e.payload.service as string),
76
+ };
77
+ }
78
+
79
+ const NAMES = ['alpha', 'beta', 'gamma', 'delta'];
80
+ const REVERSE = ['delta', 'gamma', 'beta', 'alpha'];
81
+
82
+ describe('serve stopped order on a canceled run', () => {
83
+ it('cancel at the aggregate-ready publish keeps reverse order', async () => {
84
+ for (let i = 0; i < 50; i++) {
85
+ const ac = new AbortController();
86
+ const pub = recorder((e) => {
87
+ if (e.topic === 'kit.serve.supervisor.ready_reported') ac.abort();
88
+ });
89
+ const sup = new Supervisor(
90
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta')),
91
+ { publisher: pub },
92
+ );
93
+ const res = await sup.run(ac.signal, NAMES, enabled(...NAMES));
94
+ expect(res.error).toBeUndefined();
95
+ expect(pub.stopped()).toEqual(REVERSE);
96
+ }
97
+ });
98
+
99
+ it('cancel while the last service is still starting keeps reverse order', async () => {
100
+ for (let i = 0; i < 20; i++) {
101
+ const ac = new AbortController();
102
+ const pub = recorder((e) => {
103
+ if (e.topic === 'kit.serve.service.ready_reported' && e.payload.service === 'gamma') {
104
+ ac.abort();
105
+ }
106
+ });
107
+ const sup = new Supervisor(
108
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta', 20)),
109
+ { publisher: pub },
110
+ );
111
+ const res = await sup.run(ac.signal, NAMES, enabled(...NAMES));
112
+ expect(res.error).toBeUndefined();
113
+ expect(pub.stopped()).toEqual(REVERSE);
114
+ }
115
+ });
116
+
117
+ it('cancel after steady state keeps reverse order', async () => {
118
+ for (let i = 0; i < 50; i++) {
119
+ const ac = new AbortController();
120
+ const pub = recorder();
121
+ const sup = new Supervisor(
122
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta')),
123
+ { publisher: pub },
124
+ );
125
+ const run = sup.run(ac.signal, NAMES, enabled(...NAMES));
126
+ await sleep(5);
127
+ ac.abort();
128
+ await run;
129
+ expect(pub.stopped()).toEqual(REVERSE);
130
+ }
131
+ });
132
+
133
+ it('an early self-exit still reports stopped once, at exit time', async () => {
134
+ const quitter: Service = {
135
+ name: 'quitter',
136
+ async start(_signal, ready) { ready(); await sleep(10); },
137
+ ready: () => true,
138
+ async stop() { /* nothing to release */ },
139
+ };
140
+ const ac = new AbortController();
141
+ const pub = recorder();
142
+ const sup = new Supervisor(registryOf(onCancel('steady'), quitter), { publisher: pub });
143
+ const run = sup.run(ac.signal, ['steady', 'quitter'], enabled('steady', 'quitter'));
144
+ for (let i = 0; i < 200 && !pub.stopped().includes('quitter'); i++) await sleep(5);
145
+ expect(pub.stopped()).toEqual(['quitter']);
146
+ ac.abort();
147
+ await run;
148
+ expect(pub.stopped()).toEqual(['quitter', 'steady']);
149
+ });
150
+ });
151
+
152
+ function registryOf(...svcs: Service[]): ServiceRegistry {
153
+ const r = new ServiceRegistry();
154
+ for (const s of svcs) r.register(s);
155
+ return r;
156
+ }
@@ -0,0 +1,42 @@
1
+ # upgrade
2
+
3
+ ## What it answers
4
+
5
+ How a TypeScript tool checks for a newer release, orders migration versions leniently, registers versioned schema migrations and migrates one JSON document by its own version field, and runs migrations across schema drivers with backup, lock, baseline and rollback (`Migrator`). Same semantics as Go `core/upgrade`. Drivers for config files, directories, SQLite and Postgres live in [`drivers/`](drivers/README.md), one subpath import each; write others against `SchemaDriver`. Wrong module for self-update (download, replace): Go only.
6
+
7
+ ## Use it when
8
+
9
+ - announce a newer release: `createChecker({ name, currentVersion, owner, repo })`, then `notifyIfAvailable(process.stderr)`
10
+ - order or select migrations: `compareVersions('v1.9.0', '1.10.0')`, `new Registry().pending(schema, from, to)`
11
+ - migrate a JSON document: `migrateDocument(text, steps, { latest: 3 })`
12
+ - migrate stores: `new Migrator(tool, version, opts)`, `addDriver(d)`, `await run(signal?)`, `status()`, `rollbackLatest()`
13
+ - share one Postgres database across installs: `await openPostgresDriver({ db: pool, connect: () => pool.connect(), table, name })`
14
+
15
+ ## Quick start
16
+
17
+ ```ts
18
+ import { migrateDocument, type DocStep } from '@hop-top/kit/upgrade';
19
+
20
+ const steps: DocStep[] = [
21
+ { from: 1, to: 2, apply: (d) => ({ ...d, title: d.name }), note: 'add title' },
22
+ ];
23
+ const { doc, report } = migrateDocument('{"version":1,"name":"x"}', steps);
24
+ ```
25
+
26
+ ## Contract
27
+
28
+ - Versions: a leading `v` and `+build` are dropped; missing or non-numeric parts are 0; a release sorts above its pre-releases. Not the strict `semver` package.
29
+ - Documents: the chain follows versions, not step order; newer, versionless or gapped documents fail with a `DocError` whose `kind` says why; the input is never modified; a current document comes back byte for byte.
30
+ - Migrator: per schema, lock, read version, baseline, backup, each `up` then `verify` then the version record, rollback, prune, unlock. A failed `up` is an applied step that cannot be downed: with a backup the run restores it at once (no `down` runs, reverted `restore`); without one (server database, `SqliteDriver` with `db`) it ends not restored, so keep an `up` atomic there. `down` serves a failed `verify`, record or final verify. `run` and `status` return Promises; `signal` aborts between steps (`context canceled`).
31
+ - Drivers: `SchemaDriver` methods may be sync or async. Optional `lock(signal)` returns an unlock; `storesVersion: true` means the driver owns its version, else the Migrator writes `<data dir>/<schema>/version`. Backups: `<data dir>/backups/<schema>/pre-<v>/` plus `pre-<v>.version`.
32
+ - Errors: a driver throws `BackupUnsupportedError` when it cannot back up or restore; `isBackupUnsupported`, `isNotRestored`, `isVerifyError`, `isCanceled` walk the run error's `cause` chain. Events go to any `{ publish(event) }` (a kit `Bus`).
33
+ - Postgres: the table is `<table>(schema_name, version)`; the lock is a session advisory lock on `kit-upgrade:<table>:<name>` (same key as Go, so Go and TypeScript Migrators exclude each other) taken on a dedicated `connect()` client by polling `pg_try_advisory_lock` about every 50ms, so an aborted wait rejects with `abortError(signal)` and holds nothing. Unlock runs `pg_advisory_unlock` on that client, then releases it; if that fails the client is destroyed (`release(true)`). `db.options.max === 1` is refused at lock time: the lock holds one connection. No transaction-mode pooler. No backup: a failed run is `NotRestoredError`; keep an `up` atomic. `pg` is the caller's, kit imports none.
34
+ - Parity: [`contracts/upgrade-v1`](../../../../contracts/upgrade-v1/README.md) `versions.json`, `document.json` and `migrator.json`, replayed by [`conformance.test.ts`](conformance.test.ts).
35
+
36
+ ## Neighbours
37
+
38
+ - Go reference: [`go/core/upgrade`](../../../../go/core/upgrade/README.md); Rust port: [`sdk/rs/src/upgrade`](../../../rs/src/upgrade/README.md)
39
+
40
+ ## See also
41
+
42
+ - [`docs/adopters/reference/ts-api-reference.md`](../../../../docs/adopters/reference/ts-api-reference.md)
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Backup bookkeeping and the version file, ported from Go
3
+ * `core/upgrade/backup.go`. The layout is Go's, so two ports see the same
4
+ * directory under the same data dir:
5
+ *
6
+ * <data dir>/<schema>/version the version file
7
+ * <data dir>/backups/<schema>/pre-<v>/ a backup, filled by the driver
8
+ * <data dir>/backups/<schema>/pre-<v>.version the version the run started at
9
+ *
10
+ * The Migrator writes the version file (for drivers without
11
+ * `storesVersion`) and the `.version` sidecar; drivers fill the backup
12
+ * directory and read the version file back with {@link readVersionFile}.
13
+ */
14
+
15
+ import { promises as fs } from 'node:fs';
16
+ import * as path from 'node:path';
17
+
18
+ import { dataDir as xdgDataDir } from '../xdg';
19
+ import { NotRestoredError, BackupUnsupportedError } from './errors';
20
+ import { compareSemver, parseSemver, trimV } from './semver';
21
+
22
+ export const DEFAULT_RETENTION = 5;
23
+
24
+ /** Suffix of the file beside a backup directory: `pre-<v>.version`. */
25
+ const PRE_RUN_SUFFIX = '.version';
26
+
27
+ /** The default data dir of a tool: `<xdg data dir>/hop/<tool>`. */
28
+ export function defaultDataDir(tool: string): string {
29
+ return xdgDataDir(path.join('hop', tool));
30
+ }
31
+
32
+ /**
33
+ * Reads `<dataDir>/<schema>/version`, trimmed. Resolves `""` when the file
34
+ * does not exist. For drivers that read what the Migrator recorded.
35
+ */
36
+ export async function readVersionFile(dataDir: string, schema: string): Promise<string> {
37
+ try {
38
+ return (await fs.readFile(path.join(dataDir, schema, 'version'), 'utf8')).trim();
39
+ } catch (e) {
40
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return '';
41
+ throw e;
42
+ }
43
+ }
44
+
45
+ /** Writes `<dataDir>/<schema>/version`, creating the directory. */
46
+ export async function writeVersionFile(dataDir: string, schema: string, version: string): Promise<void> {
47
+ const dir = path.join(dataDir, schema);
48
+ try {
49
+ await fs.mkdir(dir, { recursive: true, mode: 0o750 });
50
+ } catch (e) {
51
+ throw new Error(`create version dir: ${(e as Error).message}`, { cause: e });
52
+ }
53
+ try {
54
+ await fs.writeFile(path.join(dir, 'version'), version, { mode: 0o600 });
55
+ } catch (e) {
56
+ throw new Error(`write version file: ${(e as Error).message}`, { cause: e });
57
+ }
58
+ }
59
+
60
+ /** The versioned `pre-` directories of a schema, newest semver first. */
61
+ async function backupDirs(schemaDir: string): Promise<{ name: string; v: ReturnType<typeof parseSemver> }[]> {
62
+ const entries = await fs.readdir(schemaDir, { withFileTypes: true });
63
+ const dirs: { name: string; v: ReturnType<typeof parseSemver> }[] = [];
64
+ for (const e of entries) {
65
+ if (!e.isDirectory() || !e.name.startsWith('pre-')) continue;
66
+ dirs.push({ name: e.name, v: parseSemver(trimV(e.name.slice('pre-'.length))) });
67
+ }
68
+ return dirs.sort((a, b) => compareSemver(b.v, a.v));
69
+ }
70
+
71
+ const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
72
+
73
+ /** Backup lifecycle of one schema. */
74
+ export class BackupStore {
75
+ private readonly retention: number;
76
+
77
+ constructor(
78
+ private readonly schema: string,
79
+ private readonly base: string,
80
+ retention: number,
81
+ ) {
82
+ this.retention = retention <= 0 ? DEFAULT_RETENTION : retention;
83
+ }
84
+
85
+ private get schemaDir(): string {
86
+ return path.join(this.base, 'backups', this.schema);
87
+ }
88
+
89
+ /** Creates and returns the directory of the backup taken before `version`. */
90
+ async backupDir(version: string): Promise<string> {
91
+ const dir = path.join(this.schemaDir, 'pre-' + version);
92
+ try {
93
+ await fs.mkdir(dir, { recursive: true, mode: 0o750 });
94
+ } catch (e) {
95
+ throw new Error(`create backup dir: ${(e as Error).message}`, { cause: e });
96
+ }
97
+ return dir;
98
+ }
99
+
100
+ async hasBackup(version: string): Promise<boolean> {
101
+ try {
102
+ await fs.stat(path.join(this.schemaDir, 'pre-' + version));
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /** Removes a backup directory (after an unsupported backup). */
110
+ async discard(backupPath: string): Promise<void> {
111
+ await fs.rm(backupPath, { recursive: true, force: true });
112
+ }
113
+
114
+ /** Saves, beside the backup, the version the run started at ("" is an empty file). */
115
+ async savePreRun(backupPath: string, version: string): Promise<void> {
116
+ try {
117
+ await fs.writeFile(backupPath + PRE_RUN_SUFFIX, version, { mode: 0o600 });
118
+ } catch (e) {
119
+ throw new Error(`write pre-run version: ${(e as Error).message}`, { cause: e });
120
+ }
121
+ }
122
+
123
+ /** The version saved beside `backupPath`; `recorded` is false for a backup taken before it was saved. */
124
+ async readPreRun(backupPath: string): Promise<{ version: string; recorded: boolean }> {
125
+ try {
126
+ const data = await fs.readFile(backupPath + PRE_RUN_SUFFIX, 'utf8');
127
+ return { version: data.trim(), recorded: true };
128
+ } catch (e) {
129
+ if (isMissing(e)) return { version: '', recorded: false };
130
+ throw new Error(`read pre-run version: ${(e as Error).message}`, { cause: e });
131
+ }
132
+ }
133
+
134
+ /** The most recent backup directory by semver. */
135
+ async latestBackup(): Promise<string> {
136
+ let dirs: Awaited<ReturnType<typeof backupDirs>>;
137
+ try {
138
+ dirs = await backupDirs(this.schemaDir);
139
+ } catch (e) {
140
+ if (isMissing(e)) throw this.noBackups();
141
+ throw new Error(`read backup dir: ${(e as Error).message}`, { cause: e });
142
+ }
143
+ if (dirs.length === 0) throw this.noBackups();
144
+ return path.join(this.schemaDir, dirs[0].name);
145
+ }
146
+
147
+ /** No backup at all: not restored, with unsupported as its cause. */
148
+ private noBackups(): NotRestoredError {
149
+ return new NotRestoredError('no backups found for ' + this.schema, {
150
+ cause: new BackupUnsupportedError(),
151
+ });
152
+ }
153
+
154
+ /** Keeps the `retention` most recent backups by semver, removing the rest and their sidecars. */
155
+ async prune(): Promise<void> {
156
+ let dirs: Awaited<ReturnType<typeof backupDirs>>;
157
+ try {
158
+ dirs = await backupDirs(this.schemaDir);
159
+ } catch (e) {
160
+ if (isMissing(e)) return;
161
+ throw new Error(`read backup dir: ${(e as Error).message}`, { cause: e });
162
+ }
163
+ // Oldest first, like Go: the first failure stops the prune.
164
+ for (const d of dirs.slice(this.retention).reverse()) {
165
+ const p = path.join(this.schemaDir, d.name);
166
+ try {
167
+ await fs.rm(p, { recursive: true, force: true });
168
+ await fs.rm(p + PRE_RUN_SUFFIX, { force: true });
169
+ } catch (e) {
170
+ throw new Error(`prune backup ${d.name}: ${(e as Error).message}`, { cause: e });
171
+ }
172
+ }
173
+ }
174
+ }