@cubicecho/discovery-core 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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/dist/client/fetch-json.d.ts +23 -0
  4. package/dist/client/fetch-json.js +75 -0
  5. package/dist/core/defaults.d.ts +27 -0
  6. package/dist/core/defaults.js +15 -0
  7. package/dist/core/errors.d.ts +30 -0
  8. package/dist/core/errors.js +37 -0
  9. package/dist/core/host-slug.d.ts +11 -0
  10. package/dist/core/host-slug.js +22 -0
  11. package/dist/core/parse.d.ts +13 -0
  12. package/dist/core/parse.js +22 -0
  13. package/dist/core/spec-version.d.ts +12 -0
  14. package/dist/core/spec-version.js +22 -0
  15. package/dist/index.d.ts +18 -0
  16. package/dist/index.js +18 -0
  17. package/dist/mdns/advertise-service.d.ts +51 -0
  18. package/dist/mdns/advertise-service.js +72 -0
  19. package/dist/mdns/advertiser.d.ts +47 -0
  20. package/dist/mdns/advertiser.js +50 -0
  21. package/dist/mdns/browse.d.ts +91 -0
  22. package/dist/mdns/browse.js +64 -0
  23. package/dist/mdns/entry-tracker.d.ts +76 -0
  24. package/dist/mdns/entry-tracker.js +89 -0
  25. package/dist/mdns/load-bonjour.d.ts +15 -0
  26. package/dist/mdns/load-bonjour.js +20 -0
  27. package/dist/mdns/report-error.d.ts +10 -0
  28. package/dist/mdns/report-error.js +18 -0
  29. package/dist/mdns/responder.d.ts +60 -0
  30. package/dist/mdns/responder.js +182 -0
  31. package/dist/mdns/txt.d.ts +40 -0
  32. package/dist/mdns/txt.js +53 -0
  33. package/dist/mdns/watch-entries.d.ts +38 -0
  34. package/dist/mdns/watch-entries.js +43 -0
  35. package/dist/mdns.d.ts +13 -0
  36. package/dist/mdns.js +13 -0
  37. package/dist/serve/document-response.d.ts +31 -0
  38. package/dist/serve/document-response.js +74 -0
  39. package/dist/serve/node-handler.d.ts +53 -0
  40. package/dist/serve/node-handler.js +63 -0
  41. package/dist/serve/request-origin.d.ts +16 -0
  42. package/dist/serve/request-origin.js +23 -0
  43. package/llms.txt +74 -0
  44. package/package.json +75 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Benjamin Van Treese
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @cubicecho/discovery-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared core of the cubicecho discovery packages. Apps don't install this directly: they use
4
+ [`@cubicecho/mcp-discovery`](https://github.com/cubicecho/mcp-discovery) to be found as an MCP server, or
5
+ [`@cubicecho/graphql-mdns-discovery`](https://github.com/cubicecho/graphql-mdns-discovery) to be found as a
6
+ GraphQL API. Both libraries are built on this one, so an app that uses them together gets one mDNS
7
+ responder and middleware that don't overlap.
8
+
9
+ ```bash
10
+ npm install @cubicecho/discovery-core zod
11
+ npm install bonjour-service # only for ./mdns
12
+ ```
13
+
14
+ ## What is here
15
+
16
+ | Export | Parts |
17
+ | --- | --- |
18
+ | `.` | `documentResponse` / `writeDocument` / `documentHandler` (open CORS, `Cache-Control`, ETag, `304`, `HEAD`, `OPTIONS`, `405`), `answeringMiddleware`, `requestOrigin`, `fetchJson` (timeout and size cap), `DiscoveryError` and its subclasses, `parseDocument`, `specVersionSchema`, `hostSlug`, the defaults |
19
+ | `./mdns` | `advertiseService`, `createAdvertiser`, `watchServices` / `findServices`, `toFoundHost`, `createEntryTracker`, `watchEntries`, TXT helpers, `acquireResponder` |
20
+
21
+ ## One responder per process
22
+
23
+ Every advertisement and browse goes through `acquireResponder()`, a reference-counted bonjour-service
24
+ instance kept on `globalThis`. Two copies of this package in one `node_modules` still share it. The last
25
+ release closes the socket.
26
+
27
+ That fixes a real conflict. bonjour-service unregisters a stopped service's records by name, so stopping
28
+ one service removes the host's `A`/`AAAA` records and the `_services._dns-sd._udp` pointer that every other
29
+ service on the host also uses. It also sends goodbyes for them, so peers drop the address of a service
30
+ that is still up. After a stop, the shared responder registers the remaining services' records again and
31
+ announces the ones the stopped service shared with them. RFC 6762 §10.1 has a cache keep a goodbye'd
32
+ record for one second, so the announcement arrives before any peer drops the address.
33
+ `tests/mdns/network.test.ts` shows the failure without the fix.
34
+
35
+ ## Rules for a package built on this
36
+
37
+ - Use your own DNS-SD service type (`mcp`, `graphql`) and your own TXT layout, versioned by `txtvers`.
38
+ - Serve your own well-known path, and answer only that path: wrap the handler in `answeringMiddleware`
39
+ so a request you don't own goes to `next()`.
40
+ - Give your exports names of their own (`advertiseGraphql`, not `advertise`), so an app can import two
41
+ discovery packages without aliasing. Re-export the shared classes from here, so `instanceof` works
42
+ across packages.
43
+ - Keep `zod` and `bonjour-service` as peer dependencies with the ranges used here (`>=4.1`, `>=1.4`), so
44
+ an app installs one copy of each.
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Fetching a discovery document from a host nobody has vetted: bounded in time and size.
3
+ */
4
+ import { type FetchSettings } from '../core/defaults.ts';
5
+ /** What every document fetch accepts besides its settings. */
6
+ export interface FetchOptions {
7
+ /** Abandons the fetch; combined with the timeout. */
8
+ signal?: AbortSignal;
9
+ /** The fetch to use, for a proxy-aware one or a test double. */
10
+ fetch?: typeof globalThis.fetch;
11
+ }
12
+ /**
13
+ * Fetches a URL and parses its body as JSON, bounded in time and size.
14
+ *
15
+ * @param url - What to fetch.
16
+ * @param accept - The media type to ask for.
17
+ * @param [overrides] - Fetch settings to change.
18
+ * @param [options] - Abort signal and fetch implementation.
19
+ * @returns The parsed JSON, not yet validated.
20
+ * @throws {@link DocumentFetchError} On a network failure, timeout, error status or oversized body.
21
+ * @throws {@link InvalidDocumentError} If the body is not JSON.
22
+ */
23
+ export declare function fetchJson(url: string, accept: string, overrides?: Partial<FetchSettings>, options?: FetchOptions): Promise<unknown>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Fetching a discovery document from a host nobody has vetted: bounded in time and size.
3
+ */
4
+ import { FETCH_DEFAULTS } from '../core/defaults.js';
5
+ import { DocumentFetchError, InvalidDocumentError } from '../core/errors.js';
6
+ /**
7
+ * Reads a response body, stopping once it passes the size cap.
8
+ *
9
+ * @param response - A response whose body has not been read.
10
+ * @param url - What was fetched, for the error.
11
+ * @param maxBytes - The largest body accepted.
12
+ * @returns The body as text.
13
+ * @throws {@link DocumentFetchError} If the body is larger than `maxBytes`.
14
+ */
15
+ async function readBoundedText(response, url, maxBytes) {
16
+ const tooLarge = () => new DocumentFetchError(`${url} is larger than ${maxBytes} bytes; raise maxDocumentBytes to accept it`, url, response.status);
17
+ const declaredBytes = Number(response.headers.get('content-length') ?? 0);
18
+ if (declaredBytes > maxBytes) {
19
+ await response.body?.cancel();
20
+ throw tooLarge();
21
+ }
22
+ if (!response.body) {
23
+ return '';
24
+ }
25
+ const chunks = [];
26
+ let totalBytes = 0;
27
+ for await (const chunk of response.body) {
28
+ totalBytes += chunk.byteLength;
29
+ if (totalBytes > maxBytes) {
30
+ throw tooLarge();
31
+ }
32
+ chunks.push(chunk);
33
+ }
34
+ return Buffer.concat(chunks).toString('utf8');
35
+ }
36
+ /**
37
+ * Fetches a URL and parses its body as JSON, bounded in time and size.
38
+ *
39
+ * @param url - What to fetch.
40
+ * @param accept - The media type to ask for.
41
+ * @param [overrides] - Fetch settings to change.
42
+ * @param [options] - Abort signal and fetch implementation.
43
+ * @returns The parsed JSON, not yet validated.
44
+ * @throws {@link DocumentFetchError} On a network failure, timeout, error status or oversized body.
45
+ * @throws {@link InvalidDocumentError} If the body is not JSON.
46
+ */
47
+ export async function fetchJson(url, accept, overrides = {}, options = {}) {
48
+ const { timeoutMs, maxDocumentBytes } = { ...FETCH_DEFAULTS, ...overrides };
49
+ const fetchImpl = options.fetch ?? globalThis.fetch;
50
+ const timeout = AbortSignal.timeout(timeoutMs);
51
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
52
+ let text;
53
+ try {
54
+ const response = await fetchImpl(url, { headers: { Accept: accept }, signal });
55
+ if (response.ok === false) {
56
+ await response.body?.cancel();
57
+ throw new DocumentFetchError(`${url} answered ${response.status} ${response.statusText}`.trim(), url, response.status);
58
+ }
59
+ text = await readBoundedText(response, url, maxDocumentBytes);
60
+ }
61
+ catch (cause) {
62
+ if (cause instanceof DocumentFetchError) {
63
+ throw cause;
64
+ }
65
+ const timedOut = timeout.aborted;
66
+ const reason = timedOut ? `timed out after ${timeoutMs} ms` : 'could not be fetched';
67
+ throw new DocumentFetchError(`${url} ${reason}`, url, null, { cause });
68
+ }
69
+ try {
70
+ return JSON.parse(text);
71
+ }
72
+ catch (cause) {
73
+ throw new InvalidDocumentError(`${url} did not return JSON`, url, { cause });
74
+ }
75
+ }
@@ -0,0 +1,27 @@
1
+ /** How discovery documents are served. */
2
+ export interface ServeSettings {
3
+ /** How long a client may reuse a document before asking again, in seconds. */
4
+ maxAgeSeconds: number;
5
+ }
6
+ /** The serving defaults; the max age is the one the MCP Server Card spec recommends. */
7
+ export declare const SERVE_DEFAULTS: Readonly<ServeSettings>;
8
+ /** How discovery documents are fetched. */
9
+ export interface FetchSettings {
10
+ /** How long one document fetch may take, headers and body together, in ms. */
11
+ timeoutMs: number;
12
+ /** The largest document accepted, in bytes. */
13
+ maxDocumentBytes: number;
14
+ }
15
+ /** The fetching defaults. */
16
+ export declare const FETCH_DEFAULTS: Readonly<FetchSettings>;
17
+ /** How mDNS advertising and browsing behave. */
18
+ export interface MdnsSettings {
19
+ /** How long a timed browse listens before answering, in ms. */
20
+ browseMs: number;
21
+ /** How long an advertisement waits for its announcement to go out before giving up, in ms. */
22
+ announceTimeoutMs: number;
23
+ /** How often an entry watch re-reads every known host's document, to catch entries added or removed, in ms. */
24
+ refreshMs: number;
25
+ }
26
+ /** The mDNS defaults; probing alone takes about 750 ms. */
27
+ export declare const MDNS_DEFAULTS: Readonly<MdnsSettings>;
@@ -0,0 +1,15 @@
1
+ /** The serving defaults; the max age is the one the MCP Server Card spec recommends. */
2
+ export const SERVE_DEFAULTS = Object.freeze({
3
+ maxAgeSeconds: 3600,
4
+ });
5
+ /** The fetching defaults. */
6
+ export const FETCH_DEFAULTS = Object.freeze({
7
+ timeoutMs: 5000,
8
+ maxDocumentBytes: 1_048_576,
9
+ });
10
+ /** The mDNS defaults; probing alone takes about 750 ms. */
11
+ export const MDNS_DEFAULTS = Object.freeze({
12
+ browseMs: 3000,
13
+ announceTimeoutMs: 5000,
14
+ refreshMs: 300_000,
15
+ });
@@ -0,0 +1,30 @@
1
+ /** Any failure to read a discovery document; discovery functions report these per entry. */
2
+ export declare class DiscoveryError extends Error {
3
+ /** Where the document was read from: a URL, or a label for an inline one. */
4
+ readonly source: string;
5
+ /**
6
+ * Builds the error.
7
+ *
8
+ * @param message - What went wrong and what to check.
9
+ * @param source - Where the document was read from.
10
+ * @param [options] - Carries the underlying `cause`.
11
+ */
12
+ constructor(message: string, source: string, options?: ErrorOptions);
13
+ }
14
+ /** A document could not be fetched: network failure, timeout, an error status or an oversized body. */
15
+ export declare class DocumentFetchError extends DiscoveryError {
16
+ /** The HTTP status, or null when no response arrived. */
17
+ readonly status: number | null;
18
+ /**
19
+ * Builds the error.
20
+ *
21
+ * @param message - What went wrong and what to check.
22
+ * @param source - The URL that was fetched.
23
+ * @param status - The HTTP status, or null when no response arrived.
24
+ * @param [options] - Carries the underlying `cause`.
25
+ */
26
+ constructor(message: string, source: string, status: number | null, options?: ErrorOptions);
27
+ }
28
+ /** A document arrived but is not valid JSON, or does not match its schema. */
29
+ export declare class InvalidDocumentError extends DiscoveryError {
30
+ }
@@ -0,0 +1,37 @@
1
+ /** Any failure to read a discovery document; discovery functions report these per entry. */
2
+ export class DiscoveryError extends Error {
3
+ /** Where the document was read from: a URL, or a label for an inline one. */
4
+ source;
5
+ /**
6
+ * Builds the error.
7
+ *
8
+ * @param message - What went wrong and what to check.
9
+ * @param source - Where the document was read from.
10
+ * @param [options] - Carries the underlying `cause`.
11
+ */
12
+ constructor(message, source, options) {
13
+ super(message, options);
14
+ this.name = new.target.name;
15
+ this.source = source;
16
+ }
17
+ }
18
+ /** A document could not be fetched: network failure, timeout, an error status or an oversized body. */
19
+ export class DocumentFetchError extends DiscoveryError {
20
+ /** The HTTP status, or null when no response arrived. */
21
+ status;
22
+ /**
23
+ * Builds the error.
24
+ *
25
+ * @param message - What went wrong and what to check.
26
+ * @param source - The URL that was fetched.
27
+ * @param status - The HTTP status, or null when no response arrived.
28
+ * @param [options] - Carries the underlying `cause`.
29
+ */
30
+ constructor(message, source, status, options) {
31
+ super(message, source, options);
32
+ this.status = status;
33
+ }
34
+ }
35
+ /** A document arrived but is not valid JSON, or does not match its schema. */
36
+ export class InvalidDocumentError extends DiscoveryError {
37
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Turning a machine's hostname into the part of a discovery name that tells two hosts apart.
3
+ */
4
+ /**
5
+ * A hostname's first label as a slug: lowercase letters, digits and dashes, as a reverse-DNS name's namespace allows.
6
+ *
7
+ * @param hostname - E.g. `NAS`, `my_box.lan`; usually `os.hostname()`.
8
+ * @param [fallback] - Answered when nothing usable is left, e.g. `router`.
9
+ * @returns E.g. `nas`, `my-box`; at most 63 characters, with no leading or trailing dash.
10
+ */
11
+ export declare function hostSlug(hostname: string, fallback?: string): string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Turning a machine's hostname into the part of a discovery name that tells two hosts apart.
3
+ */
4
+ /** The longest DNS label, in characters; a slug is one label. */
5
+ const DNS_LABEL_MAX_LENGTH = 63;
6
+ /** What `hostSlug` answers when a hostname has nothing usable in it. */
7
+ const DEFAULT_FALLBACK = 'host';
8
+ /**
9
+ * A hostname's first label as a slug: lowercase letters, digits and dashes, as a reverse-DNS name's namespace allows.
10
+ *
11
+ * @param hostname - E.g. `NAS`, `my_box.lan`; usually `os.hostname()`.
12
+ * @param [fallback] - Answered when nothing usable is left, e.g. `router`.
13
+ * @returns E.g. `nas`, `my-box`; at most 63 characters, with no leading or trailing dash.
14
+ */
15
+ export function hostSlug(hostname, fallback = DEFAULT_FALLBACK) {
16
+ const [label = ''] = hostname.toLowerCase().split('.');
17
+ const slug = label
18
+ .replace(/[^a-z0-9-]+/g, '-')
19
+ .slice(0, DNS_LABEL_MAX_LENGTH)
20
+ .replace(/^-+|-+$/g, '');
21
+ return slug === '' ? fallback : slug;
22
+ }
@@ -0,0 +1,13 @@
1
+ import { type z } from 'zod';
2
+ /**
3
+ * Validates a document against its schema.
4
+ *
5
+ * @typeParam S - The schema; the result is its output type.
6
+ * @param schema - What the document must match.
7
+ * @param value - The parsed JSON.
8
+ * @param kind - What the document is, for the message (`Server Card`, `AI Catalog`).
9
+ * @param source - Where it came from, for the message.
10
+ * @returns The validated document.
11
+ * @throws {@link InvalidDocumentError} If the document does not match, listing each issue.
12
+ */
13
+ export declare function parseDocument<S extends z.ZodType>(schema: S, value: unknown, kind: string, source: string): z.output<S>;
@@ -0,0 +1,22 @@
1
+ import { prettifyError } from 'zod';
2
+ import { InvalidDocumentError } from './errors.js';
3
+ /**
4
+ * Validates a document against its schema.
5
+ *
6
+ * @typeParam S - The schema; the result is its output type.
7
+ * @param schema - What the document must match.
8
+ * @param value - The parsed JSON.
9
+ * @param kind - What the document is, for the message (`Server Card`, `AI Catalog`).
10
+ * @param source - Where it came from, for the message.
11
+ * @returns The validated document.
12
+ * @throws {@link InvalidDocumentError} If the document does not match, listing each issue.
13
+ */
14
+ export function parseDocument(schema, value, kind, source) {
15
+ const result = schema.safeParse(value);
16
+ if (result.success) {
17
+ return result.data;
18
+ }
19
+ throw new InvalidDocumentError(`${source} is not a valid ${kind}:\n${prettifyError(result.error)}`, source, {
20
+ cause: result.error,
21
+ });
22
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The `Major.Minor` version a discovery document carries, and the rule for reading one: any minor of the
3
+ * supported major is accepted, and a higher major is refused with a message that says so.
4
+ */
5
+ import { z } from 'zod';
6
+ /**
7
+ * A schema for a document's `specVersion` that accepts any minor of one major.
8
+ *
9
+ * @param supportedMajor - The major version the reader understands, e.g. `1`.
10
+ * @returns The schema.
11
+ */
12
+ export declare function specVersionSchema(supportedMajor: number): z.ZodString;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The `Major.Minor` version a discovery document carries, and the rule for reading one: any minor of the
3
+ * supported major is accepted, and a higher major is refused with a message that says so.
4
+ */
5
+ import { z } from 'zod';
6
+ /** `Major.Minor`, both non-negative integers. */
7
+ const SPEC_VERSION_PATTERN = /^(\d+)\.(\d+)$/;
8
+ /**
9
+ * A schema for a document's `specVersion` that accepts any minor of one major.
10
+ *
11
+ * @param supportedMajor - The major version the reader understands, e.g. `1`.
12
+ * @returns The schema.
13
+ */
14
+ export function specVersionSchema(supportedMajor) {
15
+ return z
16
+ .string()
17
+ .regex(SPEC_VERSION_PATTERN, 'Must be Major.Minor, e.g. 1.0')
18
+ .refine((specVersion) => {
19
+ const [, major] = SPEC_VERSION_PATTERN.exec(specVersion) ?? [];
20
+ return Number(major) === supportedMajor;
21
+ }, `Only specVersion ${supportedMajor}.x is supported`);
22
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The parts every cubicecho discovery package shares.
3
+ *
4
+ * Serving a public discovery document (open CORS, a cache lifetime, an ETag and `304`), fetching one from a
5
+ * host nobody vetted (bounded in time and size), the errors both report, and the reading rules for a
6
+ * document's `specVersion`. mDNS advertising and browsing, on one responder per process, is the separate
7
+ * `@cubicecho/discovery-core/mdns` export. Apps use `@cubicecho/mcp-discovery` or
8
+ * `@cubicecho/graphql-mdns-discovery`; this package is what they are built on.
9
+ */
10
+ export { type FetchOptions, fetchJson } from './client/fetch-json.ts';
11
+ export { FETCH_DEFAULTS, type FetchSettings, MDNS_DEFAULTS, type MdnsSettings, SERVE_DEFAULTS, type ServeSettings, } from './core/defaults.ts';
12
+ export { DiscoveryError, DocumentFetchError, InvalidDocumentError } from './core/errors.ts';
13
+ export { hostSlug } from './core/host-slug.ts';
14
+ export { parseDocument } from './core/parse.ts';
15
+ export { specVersionSchema } from './core/spec-version.ts';
16
+ export { type DocumentRequest, type DocumentResponse, documentResponse } from './serve/document-response.ts';
17
+ export { answeringMiddleware, type DocumentHandler, type DocumentMiddleware, type DocumentSource, documentHandler, requestPath, writeDocument, } from './serve/node-handler.ts';
18
+ export { requestOrigin } from './serve/request-origin.ts';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The parts every cubicecho discovery package shares.
3
+ *
4
+ * Serving a public discovery document (open CORS, a cache lifetime, an ETag and `304`), fetching one from a
5
+ * host nobody vetted (bounded in time and size), the errors both report, and the reading rules for a
6
+ * document's `specVersion`. mDNS advertising and browsing, on one responder per process, is the separate
7
+ * `@cubicecho/discovery-core/mdns` export. Apps use `@cubicecho/mcp-discovery` or
8
+ * `@cubicecho/graphql-mdns-discovery`; this package is what they are built on.
9
+ */
10
+ export { fetchJson } from './client/fetch-json.js';
11
+ export { FETCH_DEFAULTS, MDNS_DEFAULTS, SERVE_DEFAULTS, } from './core/defaults.js';
12
+ export { DiscoveryError, DocumentFetchError, InvalidDocumentError } from './core/errors.js';
13
+ export { hostSlug } from './core/host-slug.js';
14
+ export { parseDocument } from './core/parse.js';
15
+ export { specVersionSchema } from './core/spec-version.js';
16
+ export { documentResponse } from './serve/document-response.js';
17
+ export { answeringMiddleware, documentHandler, requestPath, writeDocument, } from './serve/node-handler.js';
18
+ export { requestOrigin } from './serve/request-origin.js';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Advertising one DNS-SD service on the local network, on the process's shared responder.
3
+ */
4
+ import { type MdnsSettings } from '../core/defaults.ts';
5
+ /** The announcement did not go out in time, most often because the name is already in use on the network. */
6
+ export declare class AdvertiseError extends Error {
7
+ /** The instance name that was being advertised. */
8
+ readonly serviceName: string;
9
+ /**
10
+ * Builds the error.
11
+ *
12
+ * @param message - What went wrong and what to check.
13
+ * @param serviceName - The instance name that was being advertised.
14
+ * @param [options] - Carries the underlying `cause`.
15
+ */
16
+ constructor(message: string, serviceName: string, options?: ErrorOptions);
17
+ }
18
+ /** One service to advertise. */
19
+ export interface ServiceAnnouncement {
20
+ /** The DNS-SD service type without underscores or protocol, e.g. `mcp` for `_mcp._tcp`. */
21
+ type: string;
22
+ /** The instance name people see when browsing. Unique on the network for this type. */
23
+ name: string;
24
+ /** The port the service listens on. */
25
+ port: number;
26
+ /** The TXT record. */
27
+ txt: Record<string, string>;
28
+ /** The mDNS hostname to advertise; the machine's own name plus `.local` when unset. */
29
+ host?: string;
30
+ /** Told about socket errors after the announcement; they are emitted as process warnings when unset. */
31
+ onError?: (error: Error) => void;
32
+ }
33
+ /** A running advertisement. */
34
+ export interface Advertisement {
35
+ /** Sends goodbye packets for this service, and closes the socket if nothing else in the process uses it. */
36
+ stop: () => Promise<void>;
37
+ }
38
+ /**
39
+ * Advertises a DNS-SD service, resolving once the announcement has gone out.
40
+ *
41
+ * @param announcement - The type, instance name, port and TXT record.
42
+ * @param [overrides] - mDNS settings to change.
43
+ * @returns The advertisement, to stop on shutdown.
44
+ * @throws {@link AdvertiseError} If the announcement does not go out in time or the socket fails first.
45
+ * @throws If bonjour-service is not installed.
46
+ *
47
+ * @remarks
48
+ * Every advertisement in a process shares one responder, so advertising several types from one app (an MCP
49
+ * endpoint and a GraphQL API, say) opens one socket, and stopping one leaves the others resolvable.
50
+ */
51
+ export declare function advertiseService(announcement: ServiceAnnouncement, overrides?: Partial<MdnsSettings>): Promise<Advertisement>;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Advertising one DNS-SD service on the local network, on the process's shared responder.
3
+ */
4
+ import { hostname } from 'node:os';
5
+ import { MDNS_DEFAULTS } from '../core/defaults.js';
6
+ import { errorReporter } from './report-error.js';
7
+ import { acquireResponder } from './responder.js';
8
+ /** The domain every mDNS hostname lives under. */
9
+ const MDNS_DOMAIN = '.local';
10
+ /** The announcement did not go out in time, most often because the name is already in use on the network. */
11
+ export class AdvertiseError extends Error {
12
+ /** The instance name that was being advertised. */
13
+ serviceName;
14
+ /**
15
+ * Builds the error.
16
+ *
17
+ * @param message - What went wrong and what to check.
18
+ * @param serviceName - The instance name that was being advertised.
19
+ * @param [options] - Carries the underlying `cause`.
20
+ */
21
+ constructor(message, serviceName, options) {
22
+ super(message, options);
23
+ this.name = 'AdvertiseError';
24
+ this.serviceName = serviceName;
25
+ }
26
+ }
27
+ /**
28
+ * Advertises a DNS-SD service, resolving once the announcement has gone out.
29
+ *
30
+ * @param announcement - The type, instance name, port and TXT record.
31
+ * @param [overrides] - mDNS settings to change.
32
+ * @returns The advertisement, to stop on shutdown.
33
+ * @throws {@link AdvertiseError} If the announcement does not go out in time or the socket fails first.
34
+ * @throws If bonjour-service is not installed.
35
+ *
36
+ * @remarks
37
+ * Every advertisement in a process shares one responder, so advertising several types from one app (an MCP
38
+ * endpoint and a GraphQL API, say) opens one socket, and stopping one leaves the others resolvable.
39
+ */
40
+ export async function advertiseService(announcement, overrides = {}) {
41
+ const { announceTimeoutMs } = { ...MDNS_DEFAULTS, ...overrides };
42
+ const { type, name, port, txt, host = `${hostname()}${MDNS_DOMAIN}` } = announcement;
43
+ let rejectStart = () => undefined;
44
+ let isUp = false;
45
+ const reportLater = errorReporter(announcement.onError);
46
+ const lease = await acquireResponder((error) => {
47
+ if (isUp === false) {
48
+ rejectStart(error);
49
+ return;
50
+ }
51
+ reportLater(error);
52
+ });
53
+ const service = lease.publish({ name, type, port, txt, host });
54
+ try {
55
+ await new Promise((resolve, reject) => {
56
+ rejectStart = (cause) => reject(new AdvertiseError(`Advertising "${name}" failed: ${cause.message}`, name, { cause }));
57
+ const timer = setTimeout(() => {
58
+ reject(new AdvertiseError(`"${name}" was not announced within ${announceTimeoutMs} ms; the name may already be in use on the network`, name));
59
+ }, announceTimeoutMs);
60
+ service.once('up', () => {
61
+ clearTimeout(timer);
62
+ isUp = true;
63
+ resolve();
64
+ });
65
+ });
66
+ }
67
+ catch (error) {
68
+ await lease.release();
69
+ throw error;
70
+ }
71
+ return { stop: () => lease.release() };
72
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Keeping an mDNS announcement in step with a setting that can change while the process runs.
3
+ */
4
+ import type { Advertisement } from './advertise-service.ts';
5
+ /** What every advertiser's options carry, whatever the service type. */
6
+ export interface AdvertiserOptions {
7
+ /** The instance name, for the log. */
8
+ name: string;
9
+ /** The port, for the log. */
10
+ port: number;
11
+ /** Told about socket errors after the announcement. */
12
+ onError?: (error: Error) => void;
13
+ }
14
+ /**
15
+ * What the advertiser needs from its host.
16
+ *
17
+ * @typeParam O - What `start` takes.
18
+ */
19
+ export interface AdvertiserDeps<O extends AdvertiserOptions> {
20
+ /** Whether the host should be announced; read on every `sync`, so it can follow a live setting. */
21
+ isWanted: () => boolean;
22
+ /** What to announce; read when an announcement starts, so a changed port or path takes effect on the next one. */
23
+ options: () => O;
24
+ /** Told when the announcement starts or stops, and why one could not start. */
25
+ log: (message: string) => void;
26
+ /** Starts an announcement, e.g. a package's own `advertise`. */
27
+ start: (options: O) => Promise<Advertisement>;
28
+ }
29
+ /** Keeps the announcement in step with `isWanted()`. */
30
+ export interface Advertiser {
31
+ /** Starts or stops the announcement to match `isWanted()` as it is when this call runs. */
32
+ sync: () => Promise<void>;
33
+ /** Stops the announcement, if any; call on shutdown so browsers drop the host at once. */
34
+ close: () => Promise<void>;
35
+ }
36
+ /**
37
+ * An advertiser that announces nothing until the first `sync`.
38
+ *
39
+ * @typeParam O - What `start` takes.
40
+ * @param deps - The setting, what to announce, the log and the announcer.
41
+ * @returns The advertiser.
42
+ *
43
+ * @remarks
44
+ * Calls run one after another, so a quick on-off-on never runs two announcements. One that fails (the name is
45
+ * taken, multicast is blocked) is logged and the host carries on; the next `sync` tries again.
46
+ */
47
+ export declare function createAdvertiser<O extends AdvertiserOptions>(deps: AdvertiserDeps<O>): Advertiser;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Keeping an mDNS announcement in step with a setting that can change while the process runs.
3
+ */
4
+ /**
5
+ * An advertiser that announces nothing until the first `sync`.
6
+ *
7
+ * @typeParam O - What `start` takes.
8
+ * @param deps - The setting, what to announce, the log and the announcer.
9
+ * @returns The advertiser.
10
+ *
11
+ * @remarks
12
+ * Calls run one after another, so a quick on-off-on never runs two announcements. One that fails (the name is
13
+ * taken, multicast is blocked) is logged and the host carries on; the next `sync` tries again.
14
+ */
15
+ export function createAdvertiser(deps) {
16
+ let current = null;
17
+ let queue = Promise.resolve();
18
+ const stop = async () => {
19
+ if (!current) {
20
+ return;
21
+ }
22
+ const stopping = current;
23
+ current = null;
24
+ await stopping.stop();
25
+ deps.log('LAN discovery: stopped advertising');
26
+ };
27
+ const apply = async () => {
28
+ const isWanted = deps.isWanted();
29
+ if (isWanted === false) {
30
+ await stop();
31
+ return;
32
+ }
33
+ if (current) {
34
+ return;
35
+ }
36
+ const options = deps.options();
37
+ try {
38
+ current = await deps.start({ onError: (error) => deps.log(`LAN discovery: ${error.message}`), ...options });
39
+ deps.log(`LAN discovery: advertising "${options.name}" on port ${options.port}`);
40
+ }
41
+ catch (error) {
42
+ deps.log(`LAN discovery: could not advertise: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ };
45
+ const enqueue = (step) => {
46
+ queue = queue.then(step, step);
47
+ return queue;
48
+ };
49
+ return { sync: () => enqueue(apply), close: () => enqueue(stop) };
50
+ }