@cubicecho/graphql-mdns-discovery 0.0.0-stage → 1.0.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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The GraphQL services document: what a host lists at `/.well-known/graphql-services.json`.
3
+ *
4
+ * There is no standard for advertising a GraphQL API, so the layout is this package's, versioned by
5
+ * `specVersion`. It follows the same rules as an MCP Server Card: it is public, it never carries credentials,
6
+ * it declares headers a client must supply without their values, and readers keep fields they don't know.
7
+ */
8
+ import { InvalidDocumentError, parseDocument, specVersionSchema } from '@cubicecho/discovery-core';
9
+ import { z } from 'zod';
10
+ /** The `specVersion` this package writes. */
11
+ export const GRAPHQL_SERVICES_SPEC_VERSION = '1.0';
12
+ /** The `specVersion` major this package reads; any minor is accepted. */
13
+ const SUPPORTED_MAJOR = 1;
14
+ /** The shortest and longest service name. */
15
+ const NAME_MIN_LENGTH = 3;
16
+ const NAME_MAX_LENGTH = 200;
17
+ /** The longest title. */
18
+ const TITLE_MAX_LENGTH = 100;
19
+ /** The longest description. */
20
+ const DESCRIPTION_MAX_LENGTH = 500;
21
+ /** Reverse-DNS with one slash, as an MCP Server Card name: `io.github.cubicecho.ethos.nas/api`. */
22
+ const NAME_PATTERN = /^[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+$/;
23
+ /** An absolute http(s) or ws(s) URL, or a path on the document's host. */
24
+ const URL_PATTERN = /^(?:(?:https?|wss?):\/\/|\/(?!\/))/;
25
+ /** What a document's kind is called in messages. */
26
+ const DOCUMENT_KIND = 'GraphQL services document';
27
+ /** What one service's kind is called in messages. */
28
+ const SERVICE_KIND = 'GraphQL service';
29
+ /** The HTTP methods a GraphQL endpoint can take queries on. */
30
+ export const GraphqlMethod = { Post: 'POST', Get: 'GET' };
31
+ /** The subscription transports a service can offer. */
32
+ export const SubscriptionProtocol = { GraphqlWs: 'graphql-ws', GraphqlSse: 'graphql-sse' };
33
+ /** A URL in the document: absolute, or a path that resolves against the document's URL. */
34
+ const urlSchema = z.string().regex(URL_PATTERN, 'Must be an http(s) or ws(s) URL, or a path starting with one "/"');
35
+ /** A header a client sends with every request; the value is never in the document. */
36
+ export const graphqlHeaderSchema = z.looseObject({
37
+ name: z.string().min(1),
38
+ description: z.string().optional(),
39
+ /** The client must supply it, e.g. `Authorization`. */
40
+ isRequired: z.boolean().optional(),
41
+ /** Its value is a secret, so a client should store it as one. */
42
+ isSecret: z.boolean().optional(),
43
+ });
44
+ /** Where queries and mutations go. */
45
+ export const graphqlEndpointSchema = z.looseObject({
46
+ url: urlSchema,
47
+ /** The methods it takes queries on; POST when unstated. */
48
+ methods: z.array(z.enum(GraphqlMethod)).optional(),
49
+ });
50
+ /** Where subscriptions go, and over which protocol. */
51
+ export const graphqlSubscriptionsSchema = z.looseObject({
52
+ url: urlSchema,
53
+ protocol: z.enum(SubscriptionProtocol),
54
+ });
55
+ /** One GraphQL API a host serves. */
56
+ export const graphqlServiceSchema = z.looseObject({
57
+ /** Unique on the network: reverse-DNS with the host's slug, e.g. `io.github.cubicecho.ethos.nas/api`. */
58
+ name: z
59
+ .string()
60
+ .min(NAME_MIN_LENGTH)
61
+ .max(NAME_MAX_LENGTH)
62
+ .regex(NAME_PATTERN, 'Must be reverse-DNS with one slash, e.g. com.example/api'),
63
+ title: z.string().max(TITLE_MAX_LENGTH).optional(),
64
+ description: z.string().max(DESCRIPTION_MAX_LENGTH).optional(),
65
+ version: z.string().min(1).optional(),
66
+ endpoint: graphqlEndpointSchema,
67
+ subscriptions: graphqlSubscriptionsSchema.optional(),
68
+ headers: z.array(graphqlHeaderSchema).optional(),
69
+ /** Whether the endpoint answers introspection queries. */
70
+ introspection: z.boolean().optional(),
71
+ /** Where the schema can be downloaded as SDL. */
72
+ schemaUrl: urlSchema.optional(),
73
+ /** Anything else, under reverse-DNS keys, e.g. `{"io.github.cubicecho.symphony/role": "unified"}`. */
74
+ _meta: z.record(z.string(), z.unknown()).optional(),
75
+ });
76
+ /** A service whose endpoint may still be left out. */
77
+ const graphqlServiceDraftSchema = graphqlServiceSchema.partial({ endpoint: true });
78
+ /**
79
+ * The envelope of a GraphQL services document.
80
+ *
81
+ * @remarks
82
+ * Its services are read one by one (`parseGraphqlService`), so one bad entry doesn't hide the rest.
83
+ */
84
+ export const graphqlServicesDocumentSchema = z.looseObject({
85
+ specVersion: specVersionSchema(SUPPORTED_MAJOR),
86
+ services: z.array(z.unknown()),
87
+ });
88
+ /**
89
+ * Validates one service from a document.
90
+ *
91
+ * @param value - The parsed JSON.
92
+ * @param source - Where it came from, for the message.
93
+ * @returns The service.
94
+ * @throws {@link InvalidDocumentError} If it does not match, listing each issue.
95
+ */
96
+ export function parseGraphqlService(value, source) {
97
+ return parseDocument(graphqlServiceSchema, value, SERVICE_KIND, source);
98
+ }
99
+ /**
100
+ * Validates a document's envelope, leaving its services to be read one by one.
101
+ *
102
+ * @param value - The parsed JSON.
103
+ * @param source - Where it came from, for the message.
104
+ * @returns The envelope.
105
+ * @throws {@link InvalidDocumentError} If it is not a 1.x document.
106
+ */
107
+ export function parseGraphqlServicesEnvelope(value, source) {
108
+ return parseDocument(graphqlServicesDocumentSchema, value, DOCUMENT_KIND, source);
109
+ }
110
+ /**
111
+ * Validates a whole document, every service included.
112
+ *
113
+ * @param value - The parsed JSON.
114
+ * @param source - Where it came from, for the message.
115
+ * @returns The document.
116
+ * @throws {@link InvalidDocumentError} If the envelope or any service does not match.
117
+ */
118
+ export function parseGraphqlServicesDocument(value, source) {
119
+ const envelope = parseGraphqlServicesEnvelope(value, source);
120
+ const services = envelope.services.map((service, index) => parseGraphqlService(service, `${source} services[${index}]`));
121
+ return { ...envelope, services };
122
+ }
123
+ /**
124
+ * Builds one service, validating it.
125
+ *
126
+ * @param fields - The service.
127
+ * @returns The service.
128
+ * @throws {@link InvalidDocumentError} If it is not valid, so a bad service fails where it is built.
129
+ */
130
+ export function createGraphqlService(fields) {
131
+ return parseGraphqlService(fields, SERVICE_KIND);
132
+ }
133
+ /**
134
+ * Builds a GraphQL services document, adding its `specVersion` and validating the result.
135
+ *
136
+ * @param services - The services the host lists.
137
+ * @returns The document.
138
+ * @throws {@link InvalidDocumentError} If a service is not valid.
139
+ */
140
+ export function createGraphqlServicesDocument(services) {
141
+ return parseGraphqlServicesDocument({ specVersion: GRAPHQL_SERVICES_SPEC_VERSION, services }, DOCUMENT_KIND);
142
+ }
143
+ /**
144
+ * Resolves a URL from a document against the document's own URL.
145
+ *
146
+ * @param url - A URL or path from the document.
147
+ * @param base - The document's URL.
148
+ * @returns The absolute URL.
149
+ * @throws {@link InvalidDocumentError} If it doesn't resolve.
150
+ */
151
+ function resolveUrl(url, base) {
152
+ try {
153
+ return new URL(url, base).href;
154
+ }
155
+ catch (cause) {
156
+ throw new InvalidDocumentError(`${base} lists a URL that does not resolve: ${url}`, base, { cause });
157
+ }
158
+ }
159
+ /**
160
+ * How to connect to a service, with every URL made absolute.
161
+ *
162
+ * @param service - A validated service.
163
+ * @param documentUrl - Where the document was read from; relative URLs resolve against it.
164
+ * @returns The connection.
165
+ * @throws {@link InvalidDocumentError} If a URL does not resolve.
166
+ */
167
+ export function graphqlServiceConnection(service, documentUrl) {
168
+ const { subscriptions } = service;
169
+ return {
170
+ url: resolveUrl(service.endpoint.url, documentUrl),
171
+ subscriptions: subscriptions
172
+ ? { url: resolveUrl(subscriptions.url, documentUrl), protocol: subscriptions.protocol }
173
+ : null,
174
+ schemaUrl: service.schemaUrl === undefined ? null : resolveUrl(service.schemaUrl, documentUrl),
175
+ requiredHeaders: (service.headers ?? [])
176
+ .filter((header) => header.isRequired === true)
177
+ .map((header) => header.name),
178
+ };
179
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Advertise and discover GraphQL APIs.
3
+ *
4
+ * A host lists its GraphQL APIs in a public document at `/.well-known/graphql-services.json`, giving each
5
+ * one's endpoint, subscription transport, SDL location and the headers a client must supply (never their
6
+ * values). This package builds, validates and serves that document, and on the client side reads it, bounded
7
+ * in time and size, with each entry checked on its own. LAN advertising and browsing as `_graphql._tcp` is the
8
+ * separate `@cubicecho/graphql-mdns-discovery/mdns` export.
9
+ *
10
+ * It is built on `@cubicecho/discovery-core`, as `@cubicecho/mcp-discovery` is, so an app can use both: they
11
+ * serve different paths, advertise different service types, share one mDNS responder, and export different
12
+ * names. The shared errors and defaults are re-exported here.
13
+ */
14
+ export { DiscoveryError, DocumentFetchError, FETCH_DEFAULTS, type FetchOptions, type FetchSettings, hostSlug, InvalidDocumentError, SERVE_DEFAULTS, type ServeSettings, } from '@cubicecho/discovery-core';
15
+ export { type DiscoveredGraphqlService, discoverGraphql, discoverGraphqlDocument, fetchGraphqlServicesDocument, type GraphqlDiscovery, type GraphqlDiscoveryFailure, } from './client/discover.ts';
16
+ export { DEFAULT_GRAPHQL_PATH, GRAPHQL_SERVICES_MEDIA_TYPE, GRAPHQL_SERVICES_WELL_KNOWN_PATH } from './core/consts.ts';
17
+ export { createGraphqlService, createGraphqlServicesDocument, GRAPHQL_SERVICES_SPEC_VERSION, type GraphqlEndpoint, type GraphqlHeader, GraphqlMethod, type GraphqlService, type GraphqlServiceConnection, type GraphqlServiceDraft, type GraphqlServiceFields, type GraphqlServicesDocument, type GraphqlServicesEnvelope, type GraphqlSubscriptions, graphqlEndpointSchema, graphqlHeaderSchema, graphqlServiceConnection, graphqlServiceSchema, graphqlServicesDocumentSchema, graphqlSubscriptionsSchema, parseGraphqlService, parseGraphqlServicesDocument, parseGraphqlServicesEnvelope, SubscriptionProtocol, } from './document/graphql-services.ts';
18
+ export { type AdvertisedGraphqlApi, type GraphqlApiSource, type GraphqlServiceContext, graphqlDiscoveryMiddleware, graphqlServicesHandler, } from './serve/graphql-discovery-middleware.ts';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Advertise and discover GraphQL APIs.
3
+ *
4
+ * A host lists its GraphQL APIs in a public document at `/.well-known/graphql-services.json`, giving each
5
+ * one's endpoint, subscription transport, SDL location and the headers a client must supply (never their
6
+ * values). This package builds, validates and serves that document, and on the client side reads it, bounded
7
+ * in time and size, with each entry checked on its own. LAN advertising and browsing as `_graphql._tcp` is the
8
+ * separate `@cubicecho/graphql-mdns-discovery/mdns` export.
9
+ *
10
+ * It is built on `@cubicecho/discovery-core`, as `@cubicecho/mcp-discovery` is, so an app can use both: they
11
+ * serve different paths, advertise different service types, share one mDNS responder, and export different
12
+ * names. The shared errors and defaults are re-exported here.
13
+ */
14
+ export { DiscoveryError, DocumentFetchError, FETCH_DEFAULTS, hostSlug, InvalidDocumentError, SERVE_DEFAULTS, } from '@cubicecho/discovery-core';
15
+ export { discoverGraphql, discoverGraphqlDocument, fetchGraphqlServicesDocument, } from './client/discover.js';
16
+ export { DEFAULT_GRAPHQL_PATH, GRAPHQL_SERVICES_MEDIA_TYPE, GRAPHQL_SERVICES_WELL_KNOWN_PATH } from './core/consts.js';
17
+ export { createGraphqlService, createGraphqlServicesDocument, GRAPHQL_SERVICES_SPEC_VERSION, GraphqlMethod, graphqlEndpointSchema, graphqlHeaderSchema, graphqlServiceConnection, graphqlServiceSchema, graphqlServicesDocumentSchema, graphqlSubscriptionsSchema, parseGraphqlService, parseGraphqlServicesDocument, parseGraphqlServicesEnvelope, SubscriptionProtocol, } from './document/graphql-services.js';
18
+ export { graphqlDiscoveryMiddleware, graphqlServicesHandler, } from './serve/graphql-discovery-middleware.js';
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Advertising a GraphQL host on the local network as a `_graphql._tcp` service.
3
+ */
4
+ import type { MdnsSettings } from '@cubicecho/discovery-core';
5
+ import { type Advertisement, type Advertiser, type AdvertiserDeps } from '@cubicecho/discovery-core/mdns';
6
+ /** What to advertise. */
7
+ export interface AdvertiseGraphqlOptions {
8
+ /** The instance name people see when browsing, e.g. `Ethos on nas`. Unique on the network for `_graphql._tcp`. */
9
+ name: string;
10
+ /** The HTTP port the host listens on. */
11
+ port: number;
12
+ /**
13
+ * Path of the main GraphQL endpoint.
14
+ *
15
+ * @defaultValue `DEFAULT_GRAPHQL_PATH`
16
+ */
17
+ path?: string;
18
+ /**
19
+ * Path of the host's GraphQL services document.
20
+ *
21
+ * @defaultValue `GRAPHQL_SERVICES_WELL_KNOWN_PATH`
22
+ */
23
+ documentPath?: string;
24
+ /** The host speaks HTTPS. */
25
+ tls?: boolean;
26
+ /** The mDNS hostname to advertise; the machine's own name plus `.local` when unset. */
27
+ host?: string;
28
+ /** Told about socket errors after the announcement; they are emitted as process warnings when unset. */
29
+ onError?: (error: Error) => void;
30
+ }
31
+ /**
32
+ * Advertises a GraphQL host as `_graphql._tcp`, resolving once the announcement has gone out.
33
+ *
34
+ * @param options - The instance name, port and paths.
35
+ * @param [overrides] - mDNS settings to change.
36
+ * @returns The advertisement, to stop on shutdown.
37
+ * @throws {@link AdvertiseError} If the announcement does not go out in time or the socket fails first.
38
+ * @throws If bonjour-service is not installed.
39
+ *
40
+ * @remarks
41
+ * It shares the process's one mDNS responder with mcp-discovery's `advertise`, so an app can announce its MCP
42
+ * endpoint and its GraphQL API together, even under the same instance name, and stop either one alone.
43
+ */
44
+ export declare function advertiseGraphql(options: AdvertiseGraphqlOptions, overrides?: Partial<MdnsSettings>): Promise<Advertisement>;
45
+ /** What a GraphQL advertiser needs from its host; `start` is `advertiseGraphql` unless replaced. */
46
+ export interface GraphqlAdvertiserDeps extends Omit<AdvertiserDeps<AdvertiseGraphqlOptions>, 'start'> {
47
+ /**
48
+ * Starts an announcement; replaced in tests.
49
+ *
50
+ * @defaultValue `advertiseGraphql`
51
+ */
52
+ start?: (options: AdvertiseGraphqlOptions) => Promise<Advertisement>;
53
+ }
54
+ /**
55
+ * A GraphQL advertiser that follows a setting which can change while the process runs; announces nothing until the first `sync`.
56
+ *
57
+ * @param deps - The setting, what to announce, the log and optionally the announcer.
58
+ * @returns The advertiser: call `sync()` after each change and `close()` on shutdown.
59
+ */
60
+ export declare function createGraphqlAdvertiser(deps: GraphqlAdvertiserDeps): Advertiser;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Advertising a GraphQL host on the local network as a `_graphql._tcp` service.
3
+ */
4
+ import { advertiseService, createAdvertiser, } from '@cubicecho/discovery-core/mdns';
5
+ import { DEFAULT_GRAPHQL_PATH, GRAPHQL_SERVICES_WELL_KNOWN_PATH } from '../core/consts.js';
6
+ import { buildGraphqlTxtRecord, GRAPHQL_SERVICE_TYPE } from './txt-record.js';
7
+ /**
8
+ * Advertises a GraphQL host as `_graphql._tcp`, resolving once the announcement has gone out.
9
+ *
10
+ * @param options - The instance name, port and paths.
11
+ * @param [overrides] - mDNS settings to change.
12
+ * @returns The advertisement, to stop on shutdown.
13
+ * @throws {@link AdvertiseError} If the announcement does not go out in time or the socket fails first.
14
+ * @throws If bonjour-service is not installed.
15
+ *
16
+ * @remarks
17
+ * It shares the process's one mDNS responder with mcp-discovery's `advertise`, so an app can announce its MCP
18
+ * endpoint and its GraphQL API together, even under the same instance name, and stop either one alone.
19
+ */
20
+ export function advertiseGraphql(options, overrides = {}) {
21
+ const { name, port, path = DEFAULT_GRAPHQL_PATH, documentPath = GRAPHQL_SERVICES_WELL_KNOWN_PATH, tls = false, } = options;
22
+ const txt = buildGraphqlTxtRecord({ path, documentPath, tls });
23
+ return advertiseService({ type: GRAPHQL_SERVICE_TYPE, name, port, txt, host: options.host, onError: options.onError }, overrides);
24
+ }
25
+ /**
26
+ * A GraphQL advertiser that follows a setting which can change while the process runs; announces nothing until the first `sync`.
27
+ *
28
+ * @param deps - The setting, what to announce, the log and optionally the announcer.
29
+ * @returns The advertiser: call `sync()` after each change and `close()` on shutdown.
30
+ */
31
+ export function createGraphqlAdvertiser(deps) {
32
+ return createAdvertiser({ ...deps, start: deps.start ?? ((options) => advertiseGraphql(options)) });
33
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Finding GraphQL hosts on the local network, by browsing for `_graphql._tcp` services.
3
+ */
4
+ import type { MdnsSettings } from '@cubicecho/discovery-core';
5
+ import { type FoundHost, type FoundService, type ServiceBrowse, type ServiceWatch, type ServiceWatchHandlers } from '@cubicecho/discovery-core/mdns';
6
+ import { type GraphqlTxtRecord } from './txt-record.ts';
7
+ /** A GraphQL host found on the network, with the URLs to reach it. */
8
+ export interface GraphqlHost extends FoundHost<GraphqlTxtRecord> {
9
+ /** The main GraphQL endpoint. */
10
+ endpointUrl: string;
11
+ /** The services document, for `discoverGraphqlDocument`. */
12
+ documentUrl: string;
13
+ }
14
+ /**
15
+ * Turns a found `_graphql._tcp` service into the URLs a client needs.
16
+ *
17
+ * @param service - A service from a bonjour-service browser.
18
+ * @returns The host.
19
+ */
20
+ export declare function toGraphqlHost(service: FoundService): GraphqlHost;
21
+ /** What to browse for: `_graphql._tcp`, read as GraphQL hosts. */
22
+ export declare const GRAPHQL_BROWSE: Readonly<ServiceBrowse<GraphqlHost>>;
23
+ /**
24
+ * Browses for GraphQL hosts until stopped, reporting each as it comes and goes.
25
+ *
26
+ * @param handlers - Called as hosts appear and disappear.
27
+ * @returns The watch, to stop when done.
28
+ * @throws If bonjour-service is not installed.
29
+ */
30
+ export declare function watchGraphqlHosts(handlers: ServiceWatchHandlers<GraphqlHost>): Promise<ServiceWatch<GraphqlHost>>;
31
+ /**
32
+ * Listens for GraphQL hosts for a while, then lists what answered.
33
+ *
34
+ * @param [overrides] - mDNS settings to change; `browseMs` is how long to listen.
35
+ * @returns The hosts, one per advertised instance.
36
+ * @throws If bonjour-service is not installed.
37
+ */
38
+ export declare function findGraphqlHosts(overrides?: Partial<MdnsSettings>): Promise<GraphqlHost[]>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Finding GraphQL hosts on the local network, by browsing for `_graphql._tcp` services.
3
+ */
4
+ import { findServices, toFoundHost, watchServices, } from '@cubicecho/discovery-core/mdns';
5
+ import { GRAPHQL_SERVICE_TYPE, parseGraphqlTxtRecord } from './txt-record.js';
6
+ /**
7
+ * Turns a found `_graphql._tcp` service into the URLs a client needs.
8
+ *
9
+ * @param service - A service from a bonjour-service browser.
10
+ * @returns The host.
11
+ */
12
+ export function toGraphqlHost(service) {
13
+ const found = toFoundHost(service, parseGraphqlTxtRecord);
14
+ return {
15
+ ...found,
16
+ endpointUrl: new URL(found.txt.path, found.origin).href,
17
+ documentUrl: new URL(found.txt.documentPath, found.origin).href,
18
+ };
19
+ }
20
+ /** What to browse for: `_graphql._tcp`, read as GraphQL hosts. */
21
+ export const GRAPHQL_BROWSE = Object.freeze({
22
+ type: GRAPHQL_SERVICE_TYPE,
23
+ toHost: toGraphqlHost,
24
+ });
25
+ /**
26
+ * Browses for GraphQL hosts until stopped, reporting each as it comes and goes.
27
+ *
28
+ * @param handlers - Called as hosts appear and disappear.
29
+ * @returns The watch, to stop when done.
30
+ * @throws If bonjour-service is not installed.
31
+ */
32
+ export function watchGraphqlHosts(handlers) {
33
+ return watchServices(GRAPHQL_BROWSE, handlers);
34
+ }
35
+ /**
36
+ * Listens for GraphQL hosts for a while, then lists what answered.
37
+ *
38
+ * @param [overrides] - mDNS settings to change; `browseMs` is how long to listen.
39
+ * @returns The hosts, one per advertised instance.
40
+ * @throws If bonjour-service is not installed.
41
+ */
42
+ export function findGraphqlHosts(overrides = {}) {
43
+ return findServices(GRAPHQL_BROWSE, overrides);
44
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The TXT record a `_graphql._tcp` service carries: where on the host the GraphQL endpoint and the services
3
+ * document are.
4
+ *
5
+ * There is no standard for this; the layout is this package's, versioned by `txtvers`. A record from someone
6
+ * else's `_graphql._tcp` service still parses, with defaults for whatever it leaves out.
7
+ */
8
+ /** The DNS-SD service type, which bonjour-service turns into `_graphql._tcp`. Never `mcp`, so the two don't mix. */
9
+ export declare const GRAPHQL_SERVICE_TYPE = "graphql";
10
+ /** Where on an advertised host its GraphQL endpoint and document are. */
11
+ export interface GraphqlTxtRecord {
12
+ /** Path of the main GraphQL endpoint. */
13
+ path: string;
14
+ /** Path of the host's GraphQL services document. */
15
+ documentPath: string;
16
+ /** The host speaks HTTPS. */
17
+ tls: boolean;
18
+ }
19
+ /**
20
+ * The TXT record for an advertised GraphQL host.
21
+ *
22
+ * @param record - Where the endpoint and document are.
23
+ * @returns Key-value pairs for bonjour-service's `txt`.
24
+ * @throws If a path is not absolute, since a client would resolve it against the wrong place.
25
+ */
26
+ export declare function buildGraphqlTxtRecord(record: GraphqlTxtRecord): Record<string, string>;
27
+ /**
28
+ * Reads a `_graphql._tcp` TXT record from the network, falling back to defaults for missing or unsafe values.
29
+ *
30
+ * @param txt - The decoded record, or undefined when the service had none.
31
+ * @returns Where the endpoint and document are; `/graphql` and the well-known document when unstated.
32
+ */
33
+ export declare function parseGraphqlTxtRecord(txt: Readonly<Record<string, unknown>> | undefined): GraphqlTxtRecord;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The TXT record a `_graphql._tcp` service carries: where on the host the GraphQL endpoint and the services
3
+ * document are.
4
+ *
5
+ * There is no standard for this; the layout is this package's, versioned by `txtvers`. A record from someone
6
+ * else's `_graphql._tcp` service still parses, with defaults for whatever it leaves out.
7
+ */
8
+ import { assertLocalPaths, FLAG_ON, readTxtFlag, readTxtPath, TXT_TLS_KEY, TXT_VERSION_KEY, } from '@cubicecho/discovery-core/mdns';
9
+ import { DEFAULT_GRAPHQL_PATH, GRAPHQL_SERVICES_WELL_KNOWN_PATH } from '../core/consts.js';
10
+ /** The DNS-SD service type, which bonjour-service turns into `_graphql._tcp`. Never `mcp`, so the two don't mix. */
11
+ export const GRAPHQL_SERVICE_TYPE = 'graphql';
12
+ /** The TXT layout version this package writes. */
13
+ const TXT_VERSION = '1';
14
+ /** The keys of the TXT record. */
15
+ const TxtKey = { Version: TXT_VERSION_KEY, Path: 'path', Document: 'doc', Tls: TXT_TLS_KEY };
16
+ /**
17
+ * The TXT record for an advertised GraphQL host.
18
+ *
19
+ * @param record - Where the endpoint and document are.
20
+ * @returns Key-value pairs for bonjour-service's `txt`.
21
+ * @throws If a path is not absolute, since a client would resolve it against the wrong place.
22
+ */
23
+ export function buildGraphqlTxtRecord(record) {
24
+ assertLocalPaths([record.path, record.documentPath]);
25
+ const txt = {
26
+ [TxtKey.Version]: TXT_VERSION,
27
+ [TxtKey.Path]: record.path,
28
+ [TxtKey.Document]: record.documentPath,
29
+ };
30
+ if (record.tls) {
31
+ txt[TxtKey.Tls] = FLAG_ON;
32
+ }
33
+ return txt;
34
+ }
35
+ /**
36
+ * Reads a `_graphql._tcp` TXT record from the network, falling back to defaults for missing or unsafe values.
37
+ *
38
+ * @param txt - The decoded record, or undefined when the service had none.
39
+ * @returns Where the endpoint and document are; `/graphql` and the well-known document when unstated.
40
+ */
41
+ export function parseGraphqlTxtRecord(txt) {
42
+ return {
43
+ path: readTxtPath(txt, TxtKey.Path, DEFAULT_GRAPHQL_PATH),
44
+ documentPath: readTxtPath(txt, TxtKey.Document, GRAPHQL_SERVICES_WELL_KNOWN_PATH),
45
+ tls: readTxtFlag(txt, TxtKey.Tls),
46
+ };
47
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Watching the local network for GraphQL APIs: mDNS finds the hosts, and their services documents say what
3
+ * they serve.
4
+ */
5
+ import type { FetchSettings, MdnsSettings } from '@cubicecho/discovery-core';
6
+ import { type EntrySource, type EntryTracker, type EntryWatchHandlers } from '@cubicecho/discovery-core/mdns';
7
+ import { type GraphqlDiscovery } from '../client/discover.ts';
8
+ import type { GraphqlService, GraphqlServiceConnection } from '../document/graphql-services.ts';
9
+ import { type GraphqlHost } from './browse.ts';
10
+ /** A GraphQL API found on the network. */
11
+ export interface LanGraphqlService {
12
+ /** Unique on the network: the host's instance name and the service's name, `<instance>/<service name>`. */
13
+ key: string;
14
+ host: GraphqlHost;
15
+ service: GraphqlService;
16
+ /** How to reach it, with absolute URLs. */
17
+ connection: GraphqlServiceConnection;
18
+ }
19
+ /** What a GraphQL service watch tells its caller. */
20
+ export type GraphqlServiceWatchHandlers = EntryWatchHandlers<LanGraphqlService>;
21
+ /** Reads the document at a URL; `discoverGraphqlDocument` with the caller's fetch settings. */
22
+ export type GraphqlDocumentReader = (documentUrl: string) => Promise<GraphqlDiscovery>;
23
+ /** A running GraphQL service watch. */
24
+ export interface GraphqlServiceWatch {
25
+ /** The services currently known. */
26
+ services: () => LanGraphqlService[];
27
+ /** Re-reads every known host's document now, instead of waiting for the next refresh. */
28
+ refresh: () => Promise<void>;
29
+ /** Stops browsing and refreshing. */
30
+ stop: () => Promise<void>;
31
+ }
32
+ /**
33
+ * How the entry tracker reads a GraphQL host: its document's services, keyed `<instance>/<service name>`.
34
+ *
35
+ * @param readDocument - Reads a host's document.
36
+ * @returns The source.
37
+ */
38
+ export declare function graphqlServiceSource(readDocument: GraphqlDocumentReader): EntrySource<GraphqlHost, LanGraphqlService>;
39
+ /**
40
+ * A tracker that reports GraphQL services through `handlers`, for driving it from something other than mDNS.
41
+ *
42
+ * @param handlers - Told about services coming, changing and going, and about errors.
43
+ * @param readDocument - Reads a host's document.
44
+ * @returns The tracker.
45
+ */
46
+ export declare function createGraphqlServiceTracker(handlers: GraphqlServiceWatchHandlers, readDocument: GraphqlDocumentReader): EntryTracker<GraphqlHost, LanGraphqlService>;
47
+ /**
48
+ * Watches the network for GraphQL APIs, reporting each as it appears, changes and goes.
49
+ *
50
+ * @param handlers - Told about services and errors.
51
+ * @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read.
52
+ * @param [fetchOverrides] - Fetch settings for the documents.
53
+ * @returns The watch, to stop when done.
54
+ * @throws If bonjour-service is not installed.
55
+ *
56
+ * @remarks
57
+ * Anything on the LAN can advertise, and a document is unauthenticated: decide what to connect to by policy,
58
+ * not by a name alone. A process that also advertises sees itself; skip its own instance name.
59
+ */
60
+ export declare function watchGraphqlServices(handlers: GraphqlServiceWatchHandlers, overrides?: Partial<MdnsSettings>, fetchOverrides?: Partial<FetchSettings>): Promise<GraphqlServiceWatch>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Watching the local network for GraphQL APIs: mDNS finds the hosts, and their services documents say what
3
+ * they serve.
4
+ */
5
+ import { createEntryTracker, watchEntries, } from '@cubicecho/discovery-core/mdns';
6
+ import { discoverGraphqlDocument } from '../client/discover.js';
7
+ import { GRAPHQL_BROWSE } from './browse.js';
8
+ /**
9
+ * How the entry tracker reads a GraphQL host: its document's services, keyed `<instance>/<service name>`.
10
+ *
11
+ * @param readDocument - Reads a host's document.
12
+ * @returns The source.
13
+ */
14
+ export function graphqlServiceSource(readDocument) {
15
+ return {
16
+ readHost: async (host) => {
17
+ const discovery = await readDocument(host.documentUrl);
18
+ return {
19
+ entries: discovery.services.map(({ service, connection }) => ({
20
+ key: `${host.name}/${service.name}`,
21
+ host,
22
+ service,
23
+ connection,
24
+ })),
25
+ failures: discovery.failures.map((failure) => failure.error),
26
+ };
27
+ },
28
+ keyOf: (entry) => entry.key,
29
+ fingerprint: (entry) => JSON.stringify([entry.service, entry.connection, entry.host.origin]),
30
+ };
31
+ }
32
+ /**
33
+ * A tracker that reports GraphQL services through `handlers`, for driving it from something other than mDNS.
34
+ *
35
+ * @param handlers - Told about services coming, changing and going, and about errors.
36
+ * @param readDocument - Reads a host's document.
37
+ * @returns The tracker.
38
+ */
39
+ export function createGraphqlServiceTracker(handlers, readDocument) {
40
+ return createEntryTracker(handlers, graphqlServiceSource(readDocument));
41
+ }
42
+ /**
43
+ * Watches the network for GraphQL APIs, reporting each as it appears, changes and goes.
44
+ *
45
+ * @param handlers - Told about services and errors.
46
+ * @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read.
47
+ * @param [fetchOverrides] - Fetch settings for the documents.
48
+ * @returns The watch, to stop when done.
49
+ * @throws If bonjour-service is not installed.
50
+ *
51
+ * @remarks
52
+ * Anything on the LAN can advertise, and a document is unauthenticated: decide what to connect to by policy,
53
+ * not by a name alone. A process that also advertises sees itself; skip its own instance name.
54
+ */
55
+ export async function watchGraphqlServices(handlers, overrides = {}, fetchOverrides = {}) {
56
+ const source = graphqlServiceSource((documentUrl) => discoverGraphqlDocument(documentUrl, fetchOverrides));
57
+ const { entries, ...watch } = await watchEntries(GRAPHQL_BROWSE, source, handlers, overrides);
58
+ return { ...watch, services: entries };
59
+ }
package/dist/mdns.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * LAN advertising and browsing for GraphQL hosts over mDNS / DNS-SD, as `_graphql._tcp` services.
3
+ *
4
+ * A separate entry point, `@cubicecho/graphql-mdns-discovery/mdns`, because it needs the optional peer
5
+ * dependency bonjour-service. mDNS only says where a host is; its services document, read with
6
+ * `discoverGraphqlDocument`, says what it serves. Every advertisement and browse shares the process's one
7
+ * responder with mcp-discovery and anything else built on `@cubicecho/discovery-core`.
8
+ */
9
+ export { MDNS_DEFAULTS, type MdnsSettings } from '@cubicecho/discovery-core';
10
+ export { AdvertiseError, type Advertisement, type Advertiser, type FoundService, type ServiceWatch, type ServiceWatchHandlers, } from '@cubicecho/discovery-core/mdns';
11
+ export { type AdvertiseGraphqlOptions, advertiseGraphql, createGraphqlAdvertiser, type GraphqlAdvertiserDeps, } from './mdns/advertise.ts';
12
+ export { findGraphqlHosts, GRAPHQL_BROWSE, type GraphqlHost, toGraphqlHost, watchGraphqlHosts, } from './mdns/browse.ts';
13
+ export { buildGraphqlTxtRecord, GRAPHQL_SERVICE_TYPE, type GraphqlTxtRecord, parseGraphqlTxtRecord, } from './mdns/txt-record.ts';
14
+ export { createGraphqlServiceTracker, type GraphqlDocumentReader, type GraphqlServiceWatch, type GraphqlServiceWatchHandlers, graphqlServiceSource, type LanGraphqlService, watchGraphqlServices, } from './mdns/watch-services.ts';
package/dist/mdns.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * LAN advertising and browsing for GraphQL hosts over mDNS / DNS-SD, as `_graphql._tcp` services.
3
+ *
4
+ * A separate entry point, `@cubicecho/graphql-mdns-discovery/mdns`, because it needs the optional peer
5
+ * dependency bonjour-service. mDNS only says where a host is; its services document, read with
6
+ * `discoverGraphqlDocument`, says what it serves. Every advertisement and browse shares the process's one
7
+ * responder with mcp-discovery and anything else built on `@cubicecho/discovery-core`.
8
+ */
9
+ export { MDNS_DEFAULTS } from '@cubicecho/discovery-core';
10
+ export { AdvertiseError, } from '@cubicecho/discovery-core/mdns';
11
+ export { advertiseGraphql, createGraphqlAdvertiser, } from './mdns/advertise.js';
12
+ export { findGraphqlHosts, GRAPHQL_BROWSE, toGraphqlHost, watchGraphqlHosts, } from './mdns/browse.js';
13
+ export { buildGraphqlTxtRecord, GRAPHQL_SERVICE_TYPE, parseGraphqlTxtRecord, } from './mdns/txt-record.js';
14
+ export { createGraphqlServiceTracker, graphqlServiceSource, watchGraphqlServices, } from './mdns/watch-services.js';