docattest 0.0.0-stage → 0.1.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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/dist/agents/claude.json +30 -0
  4. package/dist/agents/cursor.json +19 -0
  5. package/dist/agents/gemini.json +27 -0
  6. package/dist/agents/index.json +3 -0
  7. package/dist/api/adapter.d.ts +231 -0
  8. package/dist/api/adapter.js +2 -0
  9. package/dist/api/attestation.d.ts +76 -0
  10. package/dist/api/attestation.js +2 -0
  11. package/dist/api/audit.d.ts +56 -0
  12. package/dist/api/audit.js +2 -0
  13. package/dist/api/config.d.ts +44 -0
  14. package/dist/api/config.js +2 -0
  15. package/dist/api/constants.d.ts +35 -0
  16. package/dist/api/constants.js +56 -0
  17. package/dist/api/errors.d.ts +15 -0
  18. package/dist/api/errors.js +22 -0
  19. package/dist/api/impact.d.ts +49 -0
  20. package/dist/api/impact.js +2 -0
  21. package/dist/api/project.d.ts +64 -0
  22. package/dist/api/project.js +2 -0
  23. package/dist/api/report.d.ts +107 -0
  24. package/dist/api/report.js +2 -0
  25. package/dist/client/answers.d.ts +17 -0
  26. package/dist/client/answers.js +23 -0
  27. package/dist/client/core.d.ts +18 -0
  28. package/dist/client/core.js +58 -0
  29. package/dist/client/place.d.ts +14 -0
  30. package/dist/client/place.js +37 -0
  31. package/dist/client/project.d.ts +3 -0
  32. package/dist/client/project.js +98 -0
  33. package/dist/client/workspace.d.ts +12 -0
  34. package/dist/client/workspace.js +72 -0
  35. package/dist/compare-strings.d.ts +2 -0
  36. package/dist/compare-strings.js +5 -0
  37. package/dist/core-binary/locate.js +113 -0
  38. package/dist/core-binary/package.js +70 -0
  39. package/dist/core.json +4 -0
  40. package/dist/files/disk.d.ts +4 -0
  41. package/dist/files/disk.js +67 -0
  42. package/dist/files/glob.d.ts +10 -0
  43. package/dist/files/glob.js +21 -0
  44. package/dist/files/ignored.d.ts +14 -0
  45. package/dist/files/ignored.js +14 -0
  46. package/dist/files/memory.d.ts +5 -0
  47. package/dist/files/memory.js +26 -0
  48. package/dist/files/source.d.ts +22 -0
  49. package/dist/files/source.js +17 -0
  50. package/dist/index.d.ts +10 -0
  51. package/dist/index.js +6 -0
  52. package/dist/json.d.ts +16 -0
  53. package/dist/json.js +43 -0
  54. package/dist/language/cache.js +18 -0
  55. package/dist/language/citations/listing.js +64 -0
  56. package/dist/language/citations/match.js +14 -0
  57. package/dist/language/citations/tests-in-file.js +101 -0
  58. package/dist/language/compiler.js +73 -0
  59. package/dist/language/description.js +24 -0
  60. package/dist/language/impact/affected.js +50 -0
  61. package/dist/language/impact/fingerprint.js +123 -0
  62. package/dist/language/impact/graph.js +72 -0
  63. package/dist/language/impact/lookup.js +100 -0
  64. package/dist/language/impact/program.js +87 -0
  65. package/dist/language/impact/renames.js +57 -0
  66. package/dist/language/impact/revision.js +62 -0
  67. package/dist/language/impact/units.js +80 -0
  68. package/dist/language/index.js +10 -0
  69. package/dist/language/inventory/observables.js +56 -0
  70. package/dist/language/inventory/plan.js +72 -0
  71. package/dist/language/inventory/probe.js +150 -0
  72. package/dist/language/languages.js +43 -0
  73. package/dist/language/node/dependency.js +34 -0
  74. package/dist/language/node/exports-map.js +92 -0
  75. package/dist/language/program/exports.js +29 -0
  76. package/dist/language/program/file-names.js +13 -0
  77. package/dist/language/program/globals.js +38 -0
  78. package/dist/language/program/host.js +91 -0
  79. package/dist/language/program/options.js +48 -0
  80. package/dist/language/program/program.js +41 -0
  81. package/dist/language/run/attempt.js +100 -0
  82. package/dist/language/run/facts.js +109 -0
  83. package/dist/language/run/host.js +73 -0
  84. package/dist/language/run/jobs.js +37 -0
  85. package/dist/language/run/pool.js +75 -0
  86. package/dist/language/run/protocol.js +37 -0
  87. package/dist/language/run/result.js +18 -0
  88. package/dist/language/run/runner.js +115 -0
  89. package/dist/language/run/sourcemap.js +43 -0
  90. package/dist/language/run/spawn.js +40 -0
  91. package/dist/language/run/transpile.js +50 -0
  92. package/dist/language/session.js +42 -0
  93. package/dist/language/surfaces/packages.js +71 -0
  94. package/dist/language/surfaces/resolve.js +48 -0
  95. package/dist/language/surfaces/specs.js +32 -0
  96. package/dist/language/surfaces/stale.js +23 -0
  97. package/dist/language/symbols.js +95 -0
  98. package/dist/language/syntax/doc-comments.js +90 -0
  99. package/dist/language/syntax/doc-prose.js +23 -0
  100. package/dist/language/syntax/expression.js +52 -0
  101. package/dist/language/syntax/imports.js +83 -0
  102. package/dist/language/syntax/lexical.js +41 -0
  103. package/dist/language/syntax/parse.js +11 -0
  104. package/dist/language/syntax/prose.js +11 -0
  105. package/dist/language/syntax/setup-module.js +88 -0
  106. package/dist/language/ts.cjs +9 -0
  107. package/dist/language/worker/cases.js +73 -0
  108. package/dist/language/worker/compile.js +15 -0
  109. package/dist/language/worker/console.js +10 -0
  110. package/dist/language/worker/context.js +16 -0
  111. package/dist/language/worker/describe.js +107 -0
  112. package/dist/language/worker/example.js +27 -0
  113. package/dist/language/worker/facts.js +69 -0
  114. package/dist/language/worker/host-client.js +55 -0
  115. package/dist/language/worker/main.js +71 -0
  116. package/dist/language/worker/network.js +35 -0
  117. package/dist/language/worker/observe.js +39 -0
  118. package/dist/language/worker/registry.js +78 -0
  119. package/dist/language/worker/setup-facts.js +50 -0
  120. package/dist/language/worker/strays.js +37 -0
  121. package/dist/launcher/main.js +38 -0
  122. package/dist/platforms.json +40 -0
  123. package/dist/protocol/context.js +48 -0
  124. package/dist/protocol/main.js +22 -0
  125. package/dist/protocol/methods.js +178 -0
  126. package/dist/protocol/output.js +40 -0
  127. package/dist/protocol/overlay.js +31 -0
  128. package/dist/protocol/serve.js +24 -0
  129. package/dist/protocol/server.js +108 -0
  130. package/dist/protocol/wire.js +117 -0
  131. package/dist/schema/agent.json +162 -0
  132. package/dist/schema/attestations.json +307 -0
  133. package/dist/schema/kit.json +190 -0
  134. package/dist/schema/language.json +162 -0
  135. package/dist/schema/messages.json +68 -0
  136. package/dist/schema/methods.json +412 -0
  137. package/dist/schema/project.json +113 -0
  138. package/dist/schema/results.json +249 -0
  139. package/package.json +73 -4
@@ -0,0 +1,48 @@
1
+ import { diskFiles } from '../files/disk.js';
2
+ import { memoryFiles } from '../files/memory.js';
3
+ import { overlay } from './overlay.js';
4
+ import { isObject } from '../json.js';
5
+ import { Params, ProtocolError } from './wire.js';
6
+ /**
7
+ * The adapter context `open` describes. With `files` the project lives in memory and `root`
8
+ * is not read; without, it is the directory at `root`, less what the language ignores.
9
+ */
10
+ export function contextOf(params, ignored) {
11
+ const files = params.has('files')
12
+ ? memoryFiles(params.textMap('files'))
13
+ : diskFiles(params.string('root'), ignored);
14
+ const snapshots = new Params('open: snapshots', params.has('snapshots') ? params.object('snapshots') : {});
15
+ return {
16
+ files,
17
+ surfaces: params.list('surfaces').map(surfaceOf),
18
+ setup: params.optionalString('setup'),
19
+ timeoutMs: params.number('timeoutMs'),
20
+ workers: params.number('workers'),
21
+ network: params.boolean('network'),
22
+ snapshots: {
23
+ dir: snapshots.optionalString('dir'),
24
+ data: new Map(Object.entries(snapshots.has('data') ? snapshots.object('data') : {})),
25
+ },
26
+ manifests: new Map(Object.entries(params.has('manifests') ? params.object('manifests') : {})),
27
+ examples: params.has('examples') ? params.attestations('examples', 'example') : [],
28
+ };
29
+ }
30
+ // A surface as the config states it: `{ name, entry }`, the entry a string or `{ import, path }`.
31
+ function surfaceOf(value) {
32
+ const { name, entry } = isObject(value) ? value : {};
33
+ const both = isObject(entry) && typeof entry.import === 'string' && typeof entry.path === 'string';
34
+ if (typeof name !== 'string' || !(typeof entry === 'string' || both)) {
35
+ throw new ProtocolError('open: each of "surfaces" must have a "name" and an "entry"');
36
+ }
37
+ return { name, entry };
38
+ }
39
+ /**
40
+ * The change `affected` describes: the project as it is now, with each path in `base`
41
+ * replaced by its base contents (null: it did not exist then).
42
+ */
43
+ export function changeOf(files, params) {
44
+ const base = params.textOrNullMap('base');
45
+ const read = (file) => base[file] ?? undefined;
46
+ return { base: overlay(files, Object.keys(base), read), changed: params.strings('changed') };
47
+ }
48
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ // docattest-adapter-typescript: the TypeScript adapter behind the protocol in PROTOCOL.md.
3
+ //
4
+ // Attested code may print, on any thread and by any means, down to writing descriptor 1
5
+ // directly. So the server runs as a child whose descriptor 1 is this process's stderr, and
6
+ // whose descriptor 3 is this process's stdout: only the server's responses reach the core.
7
+ // Stdin is handed over as it is; nothing flows through this process.
8
+ import { spawn } from 'node:child_process';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { PROTOCOL_FD_FLAG } from './output.js';
11
+ const server = fileURLToPath(new URL('./serve.js', import.meta.url));
12
+ const args = [...process.execArgv, server, PROTOCOL_FD_FLAG];
13
+ const child = spawn(process.execPath, args, { stdio: [0, 2, 2, 1] });
14
+ for (const signal of ['SIGINT', 'SIGTERM']) {
15
+ process.on(signal, () => child.kill(signal));
16
+ }
17
+ child.on('error', (err) => {
18
+ process.stderr.write(`docattest-adapter-typescript: ${err.message}\n`);
19
+ process.exit(1);
20
+ });
21
+ child.on('exit', (code) => process.exit(code ?? 1));
22
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,178 @@
1
+ import { InternalError, UserError } from '../api/errors.js';
2
+ import { sourceFileMatcher } from '../files/glob.js';
3
+ import { ignoreRule } from '../files/ignored.js';
4
+ import { isObject } from '../json.js';
5
+ import { changeOf, contextOf } from './context.js';
6
+ import { Params, PROTOCOL_VERSION, ProtocolError } from './wire.js';
7
+ /** The optional protocol methods (PROTOCOL.md §3): this adapter implements every one. */
8
+ const CAPABILITIES = ['tests', 'observables', 'affected'];
9
+ /** The methods that need the whole language: its compiler, its runtime. */
10
+ const HEAVY = ['docComments', 'open'];
11
+ /**
12
+ * The protocol's methods over one language plugin and the one session `open` creates. Each
13
+ * handler runs synchronously up to its first await, in the order requests arrive, so `open`
14
+ * has taken effect before the next line is read.
15
+ *
16
+ * It starts with the language's description only, which is enough for `hello` and for the
17
+ * questions about text; the server hands it the whole language (`use`) before it calls a
18
+ * method that `needs` it.
19
+ */
20
+ export class Methods {
21
+ description;
22
+ info;
23
+ greeted = false;
24
+ language;
25
+ opened;
26
+ closing;
27
+ inFlight = new Set();
28
+ isSource;
29
+ /** Whether the last `hello` said that more requests will follow. */
30
+ warm = false;
31
+ constructor(description, info) {
32
+ this.description = description;
33
+ this.info = info;
34
+ this.isSource = sourceFileMatcher(description.sourceFiles);
35
+ }
36
+ /** Whether `method` cannot be called before the whole language is handed over. */
37
+ needs(method) {
38
+ return this.greeted && !this.language && HEAVY.includes(method);
39
+ }
40
+ /** Hand over the whole language. */
41
+ use(language) {
42
+ this.language = language;
43
+ }
44
+ /** Call one method; throws for an unknown method or one out of order. */
45
+ call(method, params) {
46
+ const { description } = this;
47
+ const lifecycle = new Map([
48
+ ['hello', (p) => this.hello(p)],
49
+ ['docComments', (p) => this.docComments(p)],
50
+ ['assertions', (p) => description.assertions(examplesOf(p))],
51
+ ['docProse', (p) => description.docProse(sourcesOf('docProse', p))],
52
+ ['mentions', (p) => description.mentions(p.strings('spans'), p.strings('symbols'))],
53
+ ['expressions', (p) => description.expressions(p.strings('expressions'))],
54
+ ['open', (p) => this.open(p)],
55
+ ['close', () => this.close()],
56
+ ]);
57
+ const handler = lifecycle.get(method) ?? this.sessionMethod(method);
58
+ if (!handler)
59
+ throw new ProtocolError(`unknown method "${method}"`);
60
+ if (!this.greeted && method !== 'hello') {
61
+ throw new ProtocolError(`"${method}" before "hello": hello is always first`);
62
+ }
63
+ return handler(params);
64
+ }
65
+ /** Close the session if one is open and not yet closed. */
66
+ async shutdown() {
67
+ if (this.opened && !this.closing)
68
+ this.closing = this.opened.session.close();
69
+ await this.closing;
70
+ }
71
+ /**
72
+ * `close`: release the session's workers once every request already sent has its answer,
73
+ * so a `close` that overtakes them never cuts them short. Later session methods are errors.
74
+ */
75
+ async close() {
76
+ const { session } = this.current('close');
77
+ this.closing = Promise.allSettled([...this.inFlight]).then(() => session.close());
78
+ await this.closing;
79
+ return {};
80
+ }
81
+ hello(params) {
82
+ const protocol = params.number('protocol');
83
+ if (protocol !== PROTOCOL_VERSION) {
84
+ throw new UserError(`the ${this.info.name} adapter speaks protocol ${PROTOCOL_VERSION}, not ${protocol}`);
85
+ }
86
+ this.greeted = true;
87
+ this.warm = params.has('warm') && params.boolean('warm');
88
+ return {
89
+ protocol: PROTOCOL_VERSION,
90
+ adapter: { name: this.info.name, version: this.info.version },
91
+ blockLanguages: [...this.description.blockLanguages],
92
+ sourceFiles: {
93
+ include: [...this.description.sourceFiles.include],
94
+ exclude: [...this.description.sourceFiles.exclude],
95
+ },
96
+ ignoredNames: [...this.description.ignoredNames],
97
+ capabilities: [...CAPABILITIES],
98
+ vocabulary: { ...this.description.vocabulary },
99
+ };
100
+ }
101
+ whole(method) {
102
+ if (this.language)
103
+ return this.language;
104
+ throw new InternalError(`"${method}" was called before the language loaded`);
105
+ }
106
+ docComments(params) {
107
+ const language = this.whole('docComments');
108
+ return sourcesOf('docComments', params).flatMap(({ page, text }) => this.isSource(page) ? language.docComments(page, text) : []);
109
+ }
110
+ open(params) {
111
+ if (this.opened)
112
+ throw new ProtocolError('"open" was already called: one session per process');
113
+ const context = contextOf(params, ignoreRule(this.description));
114
+ this.opened = { session: this.whole('open').createSession(context), files: context.files };
115
+ return {};
116
+ }
117
+ sessionMethod(method) {
118
+ const handler = SESSION_METHODS.get(method);
119
+ if (!handler)
120
+ return undefined;
121
+ return (params) => {
122
+ const answer = Promise.resolve(handler(this.current(method), params));
123
+ this.inFlight.add(answer);
124
+ void answer.finally(() => this.inFlight.delete(answer)).catch(() => undefined);
125
+ return answer;
126
+ };
127
+ }
128
+ current(method) {
129
+ if (!this.opened)
130
+ throw new ProtocolError(`"${method}" before "open"`);
131
+ if (this.closing)
132
+ throw new ProtocolError(`"${method}" after "close"`);
133
+ return this.opened;
134
+ }
135
+ }
136
+ const SESSION_METHODS = new Map([
137
+ ['compile', ({ session }, p) => session.compile(p.attestations('examples', 'example'))],
138
+ [
139
+ 'evaluate',
140
+ async ({ session }, p) => Object.fromEntries(await session.evaluate(p.attestations('facts', 'fact'))),
141
+ ],
142
+ [
143
+ 'run',
144
+ ({ session }, p) => session.run(p.attestations('examples', 'example'), p.attestations('cases', 'cases')),
145
+ ],
146
+ ['symbols', ({ session }, p) => symbolsById(session, p.attestations('attestations'))],
147
+ ['exports', async ({ session }, p) => (await session.exports(p.string('surface'))) ?? null],
148
+ ['describeSurfaces', async ({ session }) => Object.fromEntries(await session.describeSurfaces())],
149
+ ['tests', ({ session }, p) => session.tests(p.string('file'))],
150
+ ['observables', ({ session }, p) => session.observables(p.string('surface'))],
151
+ ['affected', ({ session, files }, p) => session.affected(changeOf(files, p))],
152
+ ['inCode', ({ session }, p) => session.inCode(p.strings('names'), p.strings('files'))],
153
+ ]);
154
+ /** `files`: source files as `{ page, text }`. */
155
+ function sourcesOf(method, params) {
156
+ return params.list('files').map((file) => {
157
+ const { page, text } = isObject(file) ? file : {};
158
+ if (typeof page !== 'string' || typeof text !== 'string') {
159
+ throw new ProtocolError(`${method}: each of "files" must have a "page" and a "text"`);
160
+ }
161
+ return { page, text };
162
+ });
163
+ }
164
+ /** `examples`: example code as `{ lang, code }`. */
165
+ function examplesOf(params) {
166
+ return params.list('examples').map((example) => {
167
+ const { lang, code } = isObject(example) ? example : {};
168
+ if (typeof lang !== 'string' || typeof code !== 'string') {
169
+ throw new ProtocolError('assertions: each of "examples" must have a "lang" and a "code"');
170
+ }
171
+ return { lang, code };
172
+ });
173
+ }
174
+ async function symbolsById(session, all) {
175
+ const refs = await Promise.all(all.map(async (a) => [a.id, await session.symbols(a)]));
176
+ return Object.fromEntries(refs);
177
+ }
178
+ //# sourceMappingURL=methods.js.map
@@ -0,0 +1,40 @@
1
+ import { createWriteStream, fstatSync } from 'node:fs';
2
+ import { Socket } from 'node:net';
3
+ import { isatty, WriteStream } from 'node:tty';
4
+ /** The descriptor the server writes responses to; the launcher maps it to its own stdout. */
5
+ const PROTOCOL_FD = 3;
6
+ /** The argument by which the launcher tells the server that descriptor is its to write. */
7
+ export const PROTOCOL_FD_FLAG = `--protocol-fd=${PROTOCOL_FD}`;
8
+ /**
9
+ * Responses go to a descriptor nothing else in the process knows about. The server's own
10
+ * stdout (descriptor 1, which attested code on any thread can reach with
11
+ * `fs.writeSync(1, …)`) is the launcher's stderr, so no output but a response can ever
12
+ * reach the core's end of the pipe.
13
+ */
14
+ export function protocolOutput(argv) {
15
+ // Without the launcher, descriptor 3 is whatever Node itself opened first.
16
+ if (!argv.includes(PROTOCOL_FD_FLAG)) {
17
+ throw new Error('the adapter server writes responses to a descriptor its launcher opens: ' +
18
+ 'start it with docattest-adapter-typescript (dist/protocol/main.js)');
19
+ }
20
+ const stream = writable(PROTOCOL_FD);
21
+ return {
22
+ line: (text) => {
23
+ stream.write(`${text}\n`);
24
+ },
25
+ end: () => new Promise((resolve) => {
26
+ stream.end(resolve);
27
+ }),
28
+ };
29
+ }
30
+ // The same choice Node makes for process.stdout: a terminal, a pipe or socket, or anything
31
+ // else (a file, or a device such as /dev/null), which is written like a file.
32
+ function writable(fd) {
33
+ if (isatty(fd))
34
+ return new WriteStream(fd);
35
+ const stat = fstatSync(fd);
36
+ if (stat.isFIFO() || stat.isSocket())
37
+ return new Socket({ fd, readable: false, writable: true });
38
+ return createWriteStream('', { fd });
39
+ }
40
+ //# sourceMappingURL=output.js.map
@@ -0,0 +1,31 @@
1
+ import { normalise, relativeTo } from '../files/source.js';
2
+ /**
3
+ * The project as it was at the base: changed files come from `read` (undefined when they
4
+ * did not exist), every other file from the working tree. Nothing can be written to it.
5
+ */
6
+ export function overlay(files, changed, read) {
7
+ const isChanged = new Set(changed);
8
+ const readRel = (file) => {
9
+ const rel = normalise(file);
10
+ return isChanged.has(rel) ? read(rel) : files.read(rel);
11
+ };
12
+ const readAbsolute = (abs) => {
13
+ const rel = relativeTo(files.root, abs);
14
+ return rel === undefined ? files.readAbsolute(abs) : readRel(rel);
15
+ };
16
+ const listed = () => {
17
+ const kept = files.list().filter((f) => !isChanged.has(f));
18
+ return [...kept, ...changed.filter((f) => read(f) !== undefined)].sort();
19
+ };
20
+ const source = {
21
+ root: files.root,
22
+ memory: files.memory,
23
+ list: listed,
24
+ read: readRel,
25
+ exists: (file) => readRel(file) !== undefined,
26
+ readAbsolute,
27
+ existsAbsolute: (abs) => readAbsolute(abs) !== undefined,
28
+ };
29
+ return source;
30
+ }
31
+ //# sourceMappingURL=overlay.js.map
@@ -0,0 +1,24 @@
1
+ // The adapter server proper, started by main.ts with its stdout on the launcher's stderr
2
+ // and the launcher's stdout on descriptor 3. Nothing but responses is written there.
3
+ import { readFileSync } from 'node:fs';
4
+ import { enableCompileCache } from 'node:module';
5
+ import { protocolOutput } from './output.js';
6
+ // The compiler is megabytes of JavaScript, loaded by every adapter process: Node's own cache
7
+ // of compiled code (in the temporary directory, or NODE_COMPILE_CACHE) saves most of that.
8
+ enableCompileCache();
9
+ const output = protocolOutput(process.argv.slice(2));
10
+ const { serve } = await import('./server.js');
11
+ // The description loads at once; the compiler only when a request needs it.
12
+ const { description } = await import('../language/description.js');
13
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
14
+ await serve({
15
+ input: process.stdin,
16
+ write: output.line,
17
+ description,
18
+ load: async () => (await import('../language/index.js')).typescript,
19
+ info: { name: 'typescript', version: pkg.version },
20
+ });
21
+ // Exit once the last line is out: attested code may have left handles behind.
22
+ await output.end();
23
+ process.exit(0);
24
+ //# sourceMappingURL=serve.js.map
@@ -0,0 +1,108 @@
1
+ import { Methods } from './methods.js';
2
+ import { idOf, parseRequest, Params, wireError } from './wire.js';
3
+ /**
4
+ * Serve the adapter protocol until the input ends. Each request starts as soon as its line
5
+ * arrives and is answered when it finishes, in whatever order that is. At end of input the
6
+ * server waits for requests in flight, closes the session and resolves.
7
+ *
8
+ * `hello` is answered from the description alone. The whole language is loaded when a
9
+ * request needs it, or right after a `hello` that said more will follow (`warm`); requests
10
+ * that arrive meanwhile wait their turn, so they still start in the order they were sent.
11
+ */
12
+ export async function serve(options) {
13
+ const { input, write, description, load, info } = options;
14
+ const methods = new Methods(description, info);
15
+ const inFlight = new Set();
16
+ let loading;
17
+ const loaded = () => (loading ??= load().then((language) => {
18
+ methods.use(language);
19
+ }));
20
+ const start = inTurn(methods, loaded);
21
+ const accept = (line) => {
22
+ if (!line.trim())
23
+ return;
24
+ const done = start(line)
25
+ .then(answered)
26
+ .then((response) => {
27
+ write(encode(response));
28
+ // The answer to `hello` is out: now is the time to get ready for what follows it.
29
+ if (methods.warm && !loading)
30
+ void loaded().catch(() => undefined);
31
+ });
32
+ inFlight.add(done);
33
+ void done.finally(() => inFlight.delete(done));
34
+ };
35
+ await readLines(input, accept);
36
+ while (inFlight.size)
37
+ await Promise.all(inFlight);
38
+ try {
39
+ await methods.shutdown();
40
+ }
41
+ catch (err) {
42
+ process.stderr.write(`${wireError(err).message}\n`);
43
+ }
44
+ }
45
+ /**
46
+ * Start requests one after another, in arrival order: each handler is called once the one
47
+ * before it has been, and once the language is there if it needs it. The answers are not
48
+ * waited for, so requests still overlap.
49
+ */
50
+ function inTurn(methods, loaded) {
51
+ let turn = Promise.resolve();
52
+ return (line) => {
53
+ const started = turn.then(async () => {
54
+ let id = null;
55
+ try {
56
+ const request = parseRequest(line);
57
+ id = request.id;
58
+ if (methods.needs(request.method))
59
+ await loaded();
60
+ const params = new Params(request.method, request.params);
61
+ return { id, answer: Promise.resolve(methods.call(request.method, params)) };
62
+ }
63
+ catch (err) {
64
+ return { id: id ?? idOf(err), answer: Promise.reject(toError(err)) };
65
+ }
66
+ });
67
+ turn = started;
68
+ return started;
69
+ };
70
+ }
71
+ async function answered({ id, answer }) {
72
+ try {
73
+ return { id, result: await answer };
74
+ }
75
+ catch (err) {
76
+ return { id, error: wireError(err) };
77
+ }
78
+ }
79
+ const toError = (err) => (err instanceof Error ? err : new Error(String(err)));
80
+ // A result that cannot be serialised is the adapter's bug, reported against its request.
81
+ function encode(response) {
82
+ try {
83
+ return JSON.stringify(response);
84
+ }
85
+ catch (err) {
86
+ return JSON.stringify({ id: response.id, error: wireError(err) });
87
+ }
88
+ }
89
+ /** Call `accept` with every newline-terminated line, and with a final unterminated one. */
90
+ async function readLines(input, accept) {
91
+ input.setEncoding('utf8');
92
+ // Only new text is scanned, so a long line arriving in many chunks costs linear time.
93
+ let parts = [];
94
+ for await (const chunk of input) {
95
+ const text = String(chunk);
96
+ let start = 0;
97
+ for (let end = text.indexOf('\n'); end !== -1; end = text.indexOf('\n', start)) {
98
+ accept(parts.join('') + text.slice(start, end));
99
+ parts = [];
100
+ start = end + 1;
101
+ }
102
+ if (start < text.length)
103
+ parts.push(text.slice(start));
104
+ }
105
+ if (parts.length)
106
+ accept(parts.join(''));
107
+ }
108
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,117 @@
1
+ import { UserError } from '../api/errors.js';
2
+ import { isObject, isStringArray } from '../json.js';
3
+ /** The protocol version this adapter speaks. */
4
+ export const PROTOCOL_VERSION = 1;
5
+ /**
6
+ * The core broke the protocol: a malformed line, an unknown method, a method out of order or
7
+ * params of the wrong shape. Reported as `internal`, since it is a bug in the core, but
8
+ * without a stack: the message says everything.
9
+ */
10
+ export class ProtocolError extends Error {
11
+ name = 'ProtocolError';
12
+ }
13
+ /** The error payload for anything a handler threw. */
14
+ export function wireError(err) {
15
+ if (err instanceof UserError)
16
+ return { kind: 'user', message: err.message };
17
+ if (err instanceof ProtocolError)
18
+ return { kind: 'internal', message: err.message };
19
+ const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
20
+ return { kind: 'internal', message };
21
+ }
22
+ /** Parse one request line; a line without a readable id throws with `id` attached. */
23
+ export function parseRequest(line) {
24
+ let value;
25
+ try {
26
+ value = JSON.parse(line);
27
+ }
28
+ catch {
29
+ throw new ProtocolError(`a request line is not JSON: ${preview(line)}`);
30
+ }
31
+ if (!isObject(value))
32
+ throw new ProtocolError(`a request is not an object: ${preview(line)}`);
33
+ const { id, method, params = {} } = value;
34
+ if (typeof id !== 'number' && typeof id !== 'string') {
35
+ throw new ProtocolError(`a request has no "id" (a number or a string): ${preview(line)}`);
36
+ }
37
+ if (typeof method !== 'string') {
38
+ throw Object.assign(new ProtocolError(`request ${id} has no "method"`), { id });
39
+ }
40
+ if (!isObject(params)) {
41
+ throw Object.assign(new ProtocolError(`request ${id}: "params" is not an object`), { id });
42
+ }
43
+ return { id, method, params };
44
+ }
45
+ /** The id a failed parse carried, when it got that far. */
46
+ export function idOf(err) {
47
+ const id = isObject(err) ? err.id : undefined;
48
+ return typeof id === 'number' || typeof id === 'string' ? id : null;
49
+ }
50
+ const preview = (line) => (line.length > 80 ? `${line.slice(0, 80)}…` : line);
51
+ /** Typed reads of request params; a missing or mistyped field is a protocol error. */
52
+ export class Params {
53
+ method;
54
+ params;
55
+ constructor(method, params) {
56
+ this.method = method;
57
+ this.params = params;
58
+ }
59
+ fail(name, what) {
60
+ throw new ProtocolError(`${this.method}: "${name}" must be ${what}`);
61
+ }
62
+ list(name) {
63
+ const value = this.params[name];
64
+ return Array.isArray(value) ? value : this.fail(name, 'an array');
65
+ }
66
+ attestations(name, kind) {
67
+ const items = this.list(name);
68
+ const fits = (a) => isObject(a) &&
69
+ typeof a.id === 'string' &&
70
+ typeof a.page === 'string' &&
71
+ typeof a.line === 'number' &&
72
+ (kind === undefined ? typeof a.kind === 'string' : a.kind === kind);
73
+ const what = kind === undefined ? 'attestations' : `${kind} attestations`;
74
+ return items.every(fits) ? items : this.fail(name, `a list of ${what}`);
75
+ }
76
+ strings(name) {
77
+ const value = this.params[name];
78
+ return isStringArray(value) ? value : this.fail(name, 'an array of strings');
79
+ }
80
+ string(name) {
81
+ const value = this.params[name];
82
+ return typeof value === 'string' ? value : this.fail(name, 'a string');
83
+ }
84
+ optionalString(name) {
85
+ return this.params[name] === undefined ? undefined : this.string(name);
86
+ }
87
+ number(name) {
88
+ const value = this.params[name];
89
+ return typeof value === 'number' ? value : this.fail(name, 'a number');
90
+ }
91
+ boolean(name) {
92
+ const value = this.params[name];
93
+ return typeof value === 'boolean' ? value : this.fail(name, 'a boolean');
94
+ }
95
+ object(name) {
96
+ const value = this.params[name];
97
+ return isObject(value) ? value : this.fail(name, 'an object');
98
+ }
99
+ has(name) {
100
+ return this.params[name] !== undefined;
101
+ }
102
+ /** An object whose values are all strings. */
103
+ textMap(name) {
104
+ const value = this.object(name);
105
+ const ok = Object.values(value).every((v) => typeof v === 'string');
106
+ return ok ? value : this.fail(name, 'a map of strings');
107
+ }
108
+ /** An object whose values are strings or null. */
109
+ textOrNullMap(name) {
110
+ const value = this.object(name);
111
+ const ok = Object.values(value).every((v) => typeof v === 'string' || v === null);
112
+ return ok
113
+ ? value
114
+ : this.fail(name, 'a map of strings or null');
115
+ }
116
+ }
117
+ //# sourceMappingURL=wire.js.map