@surfaces-ui/dev-server 0.0.0-stage → 0.3.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.
package/dist/server.js ADDED
@@ -0,0 +1,272 @@
1
+ import http from "node:http";
2
+ import { create } from "@bufbuild/protobuf";
3
+ import { Code, ConnectError } from "@connectrpc/connect";
4
+ import { connectNodeAdapter } from "@connectrpc/connect-node";
5
+ import { ModelChoiceError, combinePipelines, SemanticModelError, StaleSemanticModelError, StaleSurfaceError, semanticDatasetProblems, semanticModelDataProblems, } from "@surfaces-ui/data";
6
+ import { createDiscovery } from "@surfaces-ui/discovery";
7
+ import { createEngineServices, toConnectError } from "@surfaces-ui/engine-service";
8
+ import { createPipelines } from "@surfaces-ui/pipelines";
9
+ import { agentEvent, describesAgents } from "@surfaces-ui/agent";
10
+ import { AgentService, ContextService, DescribeAgentsResponseSchema, DiscoveryService, FormService, IngestService, ListPipelineVersionsResponseSchema, ModelService, PipelineService, SemanticService, ViewService } from "@surfaces-ui/proto";
11
+ /** Answers every turn by saying no agent is set up, so a chat explains itself instead of failing with a protocol error. */
12
+ const noAgent = {
13
+ async *send() {
14
+ yield agentEvent.error("UNAVAILABLE", "No agent is set up on this server. Give surfaces.config.ts an agent (for example anthropicAgent from @surfaces-ui/agent-anthropic) and restart the server.");
15
+ yield agentEvent.done("", "no agent");
16
+ },
17
+ };
18
+ /**
19
+ * Serves any AgentBackend as `AgentService` on a Connect router: one `Send`
20
+ * streams one turn. Mount it in your own Connect server, or pass `agent` to
21
+ * `createSurfacesServer`. Who the person is comes from the request
22
+ * (`decided_by`, `actor`); check it against your own session before acting.
23
+ */
24
+ export function agentRoutes(agent) {
25
+ return (router) => {
26
+ router.service(AgentService, {
27
+ async *send(request, context) {
28
+ yield* agent.send(request, { signal: context.signal });
29
+ },
30
+ // What a chat may offer: agents, models, skills and connectors. An agent that says nothing offers no choices.
31
+ async describeAgents() {
32
+ return describesAgents(agent) ? await agent.describeAgents() : create(DescribeAgentsResponseSchema, {});
33
+ },
34
+ });
35
+ };
36
+ }
37
+ const LOCALHOST = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
38
+ export async function createSurfacesServer(options) {
39
+ const services = await createEngineServices(options);
40
+ const sources = new Map(options.sources.map((s) => [s.id, s]));
41
+ let server;
42
+ const dataRoutes = services.routes;
43
+ // Discovery reads the catalog through the same services, in process.
44
+ const dataSource = services.dataSource;
45
+ const discovery = options.discovery === false ? undefined : createDiscovery({ ...options.discovery, dataSource });
46
+ // Discovery messages are written for people (not found, needs a name), so they are passed on.
47
+ const found = async (run) => {
48
+ try {
49
+ return await run();
50
+ }
51
+ catch (error) {
52
+ throw error instanceof ConnectError ? error : new ConnectError(error instanceof Error ? error.message : String(error), Code.InvalidArgument);
53
+ }
54
+ };
55
+ const finished = () => {
56
+ services.clearResults();
57
+ discovery?.refresh();
58
+ };
59
+ const reference = (options.pipelines && options.pipelines.length > 0) || options.savedPipelines
60
+ ? await createPipelines({
61
+ pipelines: options.pipelines ?? [],
62
+ engineOf: (id) => sources.get(id)?.engine,
63
+ ...(options.pipelineRuns ? { runs: options.pipelineRuns } : {}),
64
+ ...(options.savedPipelines ? { saved: options.savedPipelines } : {}),
65
+ // A run changes tables, so kept results and the search index over them are out of date.
66
+ onFinished: finished,
67
+ })
68
+ : undefined;
69
+ const backends = [...(reference ? [reference] : []), ...(options.externalPipelines?.({ onFinished: finished }) ?? [])];
70
+ const pipelines = backends.length > 0 ? combinePipelines(backends) : undefined;
71
+ const agent = typeof options.agent === "function" ? options.agent(dataSource, { semantics: options.semantics, ...(pipelines ? { pipelines } : {}) }) : (options.agent ?? noAgent);
72
+ const guarded = async (run) => {
73
+ try {
74
+ return await run();
75
+ }
76
+ catch (error) {
77
+ throw toConnectError(error);
78
+ }
79
+ };
80
+ const { forms, library, models } = options;
81
+ // Every save is checked against the data, whatever store holds the models.
82
+ const semantics = options.semantics && {
83
+ ...options.semantics,
84
+ async saveSemanticModel(request, callOptions) {
85
+ const problems = request.model ? await semanticModelDataProblems(request.model, services.dataSource, callOptions) : [];
86
+ // A model on a pipeline dataset must read that dataset, on its source.
87
+ const ref = request.model?.dataset;
88
+ if (ref?.pipelineId && request.model) {
89
+ const pipeline = pipelines ? await pipelines.getPipeline({ id: ref.pipelineId }, callOptions).then((r) => r.pipeline, () => undefined) : undefined;
90
+ problems.push(...semanticDatasetProblems(request.model, pipeline, { key: false }));
91
+ }
92
+ if (problems.length > 0)
93
+ throw new SemanticModelError(problems);
94
+ return options.semantics.saveSemanticModel(request, callOptions);
95
+ },
96
+ };
97
+ const modelled = async (run) => {
98
+ try {
99
+ return await run();
100
+ }
101
+ catch (error) {
102
+ if (error instanceof StaleSemanticModelError)
103
+ throw new ConnectError(error.message, Code.Aborted);
104
+ if (error instanceof SemanticModelError)
105
+ throw new ConnectError(error.message, Code.InvalidArgument);
106
+ if (error instanceof Error && /^(No semantic model|Version \d+ of)/.test(error.message))
107
+ throw new ConnectError(error.message, Code.NotFound);
108
+ return found(() => Promise.reject(error));
109
+ }
110
+ };
111
+ const saved = async (run) => {
112
+ try {
113
+ return await run();
114
+ }
115
+ catch (error) {
116
+ if (error instanceof StaleSurfaceError)
117
+ throw new ConnectError(error.message, Code.Aborted);
118
+ if (error instanceof Error && /^(No saved surface|Version \d+ of)/.test(error.message))
119
+ throw new ConnectError(error.message, Code.NotFound);
120
+ return found(() => Promise.reject(error));
121
+ }
122
+ };
123
+ const unbuilt = () => Promise.reject(new ConnectError("Apps are not built yet; use the surface calls.", Code.Unimplemented));
124
+ const allRoutes = (router) => {
125
+ dataRoutes(router);
126
+ agentRoutes(agent)(router);
127
+ if (forms) {
128
+ router.service(FormService, {
129
+ listForms: (r) => found(() => forms.listForms(r)),
130
+ getForm: (r) => found(() => forms.getForm(r)),
131
+ submit: (r) => found(() => forms.submit(r)),
132
+ listSubmissions: (r) => found(() => forms.listSubmissions(r)),
133
+ });
134
+ }
135
+ if (models) {
136
+ const chosen = async (run) => {
137
+ try {
138
+ return await run();
139
+ }
140
+ catch (error) {
141
+ if (error instanceof ModelChoiceError)
142
+ throw new ConnectError(error.message, Code.InvalidArgument);
143
+ return found(() => Promise.reject(error));
144
+ }
145
+ };
146
+ router.service(ModelService, {
147
+ listModelBackends: (r) => chosen(() => models.listModelBackends(r)),
148
+ setModel: (r) => chosen(() => models.setModel(r)),
149
+ });
150
+ }
151
+ if (library) {
152
+ router.service(ViewService, {
153
+ listSurfaces: (r) => saved(() => library.listSurfaces(r)),
154
+ getSurface: (r) => saved(() => library.getSurface(r)),
155
+ saveSurface: (r) => saved(() => library.saveSurface(r)),
156
+ deleteSurface: (r) => saved(() => library.deleteSurface(r)),
157
+ listSurfaceVersions: (r) => saved(() => library.listSurfaceVersions(r)),
158
+ listApps: unbuilt,
159
+ getApp: unbuilt,
160
+ saveApp: unbuilt,
161
+ deleteApp: unbuilt,
162
+ listAppVersions: unbuilt,
163
+ createSnapshot: unbuilt,
164
+ getSnapshot: unbuilt,
165
+ });
166
+ }
167
+ if (semantics) {
168
+ router.service(SemanticService, {
169
+ listSemanticModels: (r) => modelled(() => semantics.listSemanticModels(r)),
170
+ getSemanticModel: (r) => modelled(() => semantics.getSemanticModel(r)),
171
+ saveSemanticModel: (r) => modelled(() => semantics.saveSemanticModel(r)),
172
+ deleteSemanticModel: (r) => modelled(() => semantics.deleteSemanticModel(r)),
173
+ listSemanticModelVersions: (r) => modelled(() => semantics.listSemanticModelVersions(r)),
174
+ });
175
+ }
176
+ if (pipelines) {
177
+ router.service(PipelineService, {
178
+ listPipelines: (r) => found(() => pipelines.listPipelines(r)),
179
+ getPipeline: (r) => found(() => pipelines.getPipeline(r)),
180
+ listRuns: (r) => found(() => pipelines.listRuns(r)),
181
+ getRun: (r) => found(() => pipelines.getRun(r)),
182
+ startRun: (r) => found(() => pipelines.startRun(r)),
183
+ cancelRun: (r) => found(() => pipelines.cancelRun(r)),
184
+ savePipeline: (r) => pipelines.savePipeline
185
+ ? found(async () => {
186
+ try {
187
+ return await pipelines.savePipeline(r);
188
+ }
189
+ catch (error) {
190
+ if (error instanceof Error && /changed since/.test(error.message))
191
+ throw new ConnectError(error.message, Code.Aborted);
192
+ throw error;
193
+ }
194
+ })
195
+ : Promise.reject(new ConnectError("Pipelines on this server cannot be changed. Set savedPipelines in surfaces.config.ts to allow approved saves.", Code.FailedPrecondition)),
196
+ listPipelineVersions: (r) => found(() => pipelines.listPipelineVersions?.(r) ?? Promise.resolve(create(ListPipelineVersionsResponseSchema, {}))),
197
+ });
198
+ router.service(IngestService, { inspectFiles: (r) => guarded(() => pipelines.inspectFiles(r)) });
199
+ }
200
+ if (!discovery)
201
+ return;
202
+ router.service(DiscoveryService, {
203
+ search: (r) => found(() => discovery.search(r)),
204
+ getObject: (r) => found(() => discovery.getObject(r)),
205
+ getRelated: (r) => found(() => discovery.getRelated(r)),
206
+ describe: (r, context) => found(() => discovery.describe(r, { signal: context.signal })),
207
+ saveDescription: (r) => found(() => discovery.saveDescription(r)),
208
+ setCertification: (r) => found(() => discovery.setCertification(r)),
209
+ async *ask(r, context) {
210
+ try {
211
+ yield* discovery.ask(r, { signal: context.signal });
212
+ }
213
+ catch (error) {
214
+ throw error instanceof ConnectError ? error : new ConnectError(error instanceof Error ? error.message : String(error), Code.InvalidArgument);
215
+ }
216
+ },
217
+ });
218
+ router.service(ContextService, {
219
+ listContextPacks: (r) => found(() => discovery.listContextPacks(r)),
220
+ getContextPack: (r) => found(() => discovery.getContextPack(r)),
221
+ saveContextPack: (r) => found(() => discovery.saveContextPack(r)),
222
+ deleteContextPack: (r) => found(() => discovery.deleteContextPack(r)),
223
+ renderContextPack: (r) => found(() => discovery.renderContextPack(r)),
224
+ });
225
+ };
226
+ const allowed = options.allowedOrigins ?? [LOCALHOST];
227
+ const originAllowed = (origin) => allowed.some((rule) => (typeof rule === "string" ? rule === origin : rule.test(origin)));
228
+ return {
229
+ dataSource,
230
+ discovery,
231
+ pipelines,
232
+ forms,
233
+ library,
234
+ semantics,
235
+ models,
236
+ routes: allRoutes,
237
+ listen(port = 5220, host = "127.0.0.1") {
238
+ const handler = connectNodeAdapter({ routes: allRoutes });
239
+ server = http.createServer((req, res) => {
240
+ const origin = req.headers.origin;
241
+ if (origin && originAllowed(origin)) {
242
+ res.setHeader("Access-Control-Allow-Origin", origin);
243
+ res.setHeader("Vary", "Origin");
244
+ res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
245
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Connect-Protocol-Version, Connect-Timeout-Ms, Connect-Accept-Encoding, Connect-Content-Encoding, X-User-Agent");
246
+ res.setHeader("Access-Control-Max-Age", "7200");
247
+ }
248
+ if (req.method === "OPTIONS") {
249
+ res.writeHead(origin && originAllowed(origin) ? 204 : 403).end();
250
+ return;
251
+ }
252
+ handler(req, res);
253
+ });
254
+ return new Promise((resolve, reject) => {
255
+ server.once("error", reject);
256
+ server.listen(port, host, () => {
257
+ const address = server.address();
258
+ resolve({ url: `http://${host}:${address.port}`, port: address.port });
259
+ });
260
+ });
261
+ },
262
+ async close() {
263
+ await services.close();
264
+ if (server) {
265
+ server.closeAllConnections();
266
+ await new Promise((resolve) => server.close(() => resolve()));
267
+ }
268
+ await Promise.all([...sources.values()].map((s) => s.engine.close().catch(() => { })));
269
+ },
270
+ };
271
+ }
272
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,IAAI,EAAE,YAAY,EAAsB,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAIL,gBAAgB,EAGhB,gBAAgB,EAChB,kBAAkB,EAElB,uBAAuB,EACvB,iBAAiB,EAEjB,u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AC,GAAG,EAAE,CAAC;oBACjE,OAAO;gBACT,CAAC;gBACD,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YACpB,CAAC,CAAC,CAAC;YACH,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACrC,MAAO,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;gBAC9B,MAAO,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE;oBAC9B,MAAM,OAAO,GAAG,MAAO,CAAC,OAAO,EAAiB,CAAC;oBACjD,OAAO,CAAC,EAAE,GAAG,EAAE,UAAU,IAAI,IAAI,OAAO,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;gBACzE,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;YACvB,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,CAAC,mBAAmB,EAAE,CAAC;gBAC7B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YACvE,CAAC;YACD,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACxF,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import http from \"node:http\";\nimport { create } from \"@bufbuild/protobuf\";\nimport type { AddressInfo } from \"node:net\";\nimport { Code, ConnectError, type ConnectRouter } from \"@connectrpc/connect\";\nimport { connectNodeAdapter } from \"@connectrpc/connect-node\";\nimport {\n type DataSource,\n type Discovery,\n type Forms,\n ModelChoiceError,\n type ModelSettings,\n type Pipelines,\n combinePipelines,\n SemanticModelError,\n type Semantics,\n StaleSemanticModelError,\n StaleSurfaceError,\n type SurfaceLibrary,\n semanticDatasetProblems,\n semanticModelDataProblems,\n} from \"@surfaces-ui/data\";\nimport { type DiscoveryOptions, createDiscovery } from \"@surfaces-ui/discovery\";\nimport { type EngineServicesOptions, createEngineServices, toConnectError } from \"@surfaces-ui/engine-service\";\nimport { type PipelineDefinition, type PipelineStore, type RunStore, createPipelines } from \"@surfaces-ui/pipelines\";\nimport { type AgentBackend, agentEvent, describesAgents } from \"@surfaces-ui/agent\";\nimport { AgentService, ContextService, DescribeAgentsResponseSchema, DiscoveryService, FormService, IngestService, ListPipelineVersionsResponseSchema, ModelService, PipelineService, SemanticService, ViewService } from \"@surfaces-ui/proto\";\n\nexport type { ServerSource, StoredResultsOptions } from \"@surfaces-ui/engine-service\";\n\nexport interface SurfacesServerOptions extends EngineServicesOptions {\n /**\n * Discovery settings: sources whose data values may be shown or shared, an\n * embedder for semantic search, a language model, and where packs are kept.\n * Pass `false` to leave the discovery services out.\n */\n discovery?: Omit<DiscoveryOptions, \"dataSource\"> | false;\n /**\n * Pipelines this server can run. Their SQL is set here, on the server; a\n * client can only choose which to run. Omit to leave the pipeline services out.\n */\n pipelines?: PipelineDefinition[];\n /**\n * Pipeline backends built by another tool, served beside the pipelines\n * above: `dbtPipelines` from `@surfaces-ui/pipelines-dbt` for a dbt project.\n * `onFinished` is for a run they start, which changes tables.\n */\n externalPipelines?(hooks: { onFinished(): void }): Pipelines[];\n /** Where pipeline runs are kept, so history outlives a restart. Omit to keep them in memory. */\n pipelineRuns?: RunStore;\n /**\n * Allows `SavePipeline`: a pipeline a person approved is checked (its\n * version, the digest of what they approved, read-only queries and a dry\n * run) and kept here. Pipelines in `pipelines` cannot be changed this way.\n * Omit to keep pipelines fixed.\n */\n savedPipelines?: PipelineStore;\n /**\n * Forms people can submit. The backend defines each form's fields; a client\n * sends a form id and values, which are checked before anything is kept.\n * Omit to leave the form service out.\n */\n forms?: Forms;\n /** Where saved surfaces (pages, charts, forms, explorers) are kept. Omit to leave the surface calls out. */\n library?: SurfaceLibrary;\n /**\n * Where semantic models are kept, served as `SemanticService`. Every save\n * is checked against the data first: the model's query must run through\n * this server's read-only sources and return the columns its fields name.\n * Omit to leave it out.\n */\n semantics?: Semantics;\n /**\n * Which model each agent backend uses, served as `ModelService` so a page\n * can show and change it. It carries no key. Omit to leave it out.\n */\n models?: ModelSettings;\n /**\n * An agent to serve as `AgentService`, so a browser chat reaches it with\n * `connectAgent` from `@surfaces-ui/client-connect`. The agent runs here, with\n * its model key in this server's environment. Omit to leave it out.\n * Pass a function to build the agent from this server's own data source,\n * for tools that list tables or run queries.\n */\n agent?: AgentBackend | ((dataSource: DataSource, services: AgentServices) => AgentBackend);\n /** Origins allowed to call from a browser. Defaults to any localhost origin. */\n allowedOrigins?: (string | RegExp)[];\n}\n\n/** What a server gives an agent it builds, besides its data: give them to `dataTools`. */\nexport interface AgentServices {\n /** The server's semantic models, for `list_semantic_models` and `describe_semantic_model`. */\n semantics?: Semantics;\n /** The server's pipelines, for `pipelineTools` from `@surfaces-ui/agent`. */\n pipelines?: Pipelines;\n}\n\n/** Answers every turn by saying no agent is set up, so a chat explains itself instead of failing with a protocol error. */\nconst noAgent: AgentBackend = {\n async *send() {\n yield agentEvent.error(\"UNAVAILABLE\", \"No agent is set up on this server. Give surfaces.config.ts an agent (for example anthropicAgent from @surfaces-ui/agent-anthropic) and restart the server.\");\n yield agentEvent.done(\"\", \"no agent\");\n },\n};\n\n/**\n * Serves any AgentBackend as `AgentService` on a Connect router: one `Send`\n * streams one turn. Mount it in your own Connect server, or pass `agent` to\n * `createSurfacesServer`. Who the person is comes from the request\n * (`decided_by`, `actor`); check it against your own session before acting.\n */\nexport function agentRoutes(agent: AgentBackend): (router: ConnectRouter) => void {\n return (router) => {\n router.service(AgentService, {\n async *send(request, context) {\n yield* agent.send(request, { signal: context.signal });\n },\n // What a chat may offer: agents, models, skills and connectors. An agent that says nothing offers no choices.\n async describeAgents() {\n return describesAgents(agent) ? await agent.describeAgents() : create(DescribeAgentsResponseSchema, {});\n },\n });\n };\n}\n\nexport interface SurfacesServer {\n /** The server's sources as an in-process DataSource (no HTTP), for embedding in other servers. */\n dataSource: DataSource;\n /** The discovery backend, when enabled. */\n discovery: (Discovery & { warm(): Promise<{ objects: number }> }) | undefined;\n /** The pipeline backend, when pipelines are configured. */\n pipelines: Pipelines | undefined;\n forms: Forms | undefined;\n library: SurfaceLibrary | undefined;\n semantics: Semantics | undefined;\n models: ModelSettings | undefined;\n /** Registers the services on a Connect router, to mount in an existing server. */\n routes(router: ConnectRouter): void;\n /** Starts an HTTP server. Port 0 picks a free port. */\n listen(port?: number, host?: string): Promise<{ url: string; port: number }>;\n close(): Promise<void>;\n}\n\nconst LOCALHOST = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/;\n\nexport async function createSurfacesServer(options: SurfacesServerOptions): Promise<SurfacesServer> {\n const services = await createEngineServices(options);\n const sources = new Map(options.sources.map((s) => [s.id, s]));\n let server: http.Server | undefined;\n\n const dataRoutes = services.routes;\n // Discovery reads the catalog through the same services, in process.\n const dataSource = services.dataSource;\n const discovery = options.discovery === false ? undefined : createDiscovery({ ...options.discovery, dataSource });\n // Discovery messages are written for people (not found, needs a name), so they are passed on.\n const found = async <T>(run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n throw error instanceof ConnectError ? error : new ConnectError(error instanceof Error ? error.message : String(error), Code.InvalidArgument);\n }\n };\n const finished = () => {\n services.clearResults();\n discovery?.refresh();\n };\n const reference =\n (options.pipelines && options.pipelines.length > 0) || options.savedPipelines\n ? await createPipelines({\n pipelines: options.pipelines ?? [],\n engineOf: (id) => sources.get(id)?.engine,\n ...(options.pipelineRuns ? { runs: options.pipelineRuns } : {}),\n ...(options.savedPipelines ? { saved: options.savedPipelines } : {}),\n // A run changes tables, so kept results and the search index over them are out of date.\n onFinished: finished,\n })\n : undefined;\n const backends = [...(reference ? [reference] : []), ...(options.externalPipelines?.({ onFinished: finished }) ?? [])];\n const pipelines = backends.length > 0 ? combinePipelines(backends) : undefined;\n const agent = typeof options.agent === \"function\" ? options.agent(dataSource, { semantics: options.semantics, ...(pipelines ? { pipelines } : {}) }) : (options.agent ?? noAgent);\n const guarded = async <T>(run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n throw toConnectError(error);\n }\n };\n const { forms, library, models } = options;\n // Every save is checked against the data, whatever store holds the models.\n const semantics: Semantics | undefined = options.semantics && {\n ...options.semantics,\n async saveSemanticModel(request, callOptions) {\n const problems = request.model ? await semanticModelDataProblems(request.model, services.dataSource, callOptions) : [];\n // A model on a pipeline dataset must read that dataset, on its source.\n const ref = request.model?.dataset;\n if (ref?.pipelineId && request.model) {\n const pipeline = pipelines ? await pipelines.getPipeline({ id: ref.pipelineId }, callOptions).then((r) => r.pipeline, () => undefined) : undefined;\n problems.push(...semanticDatasetProblems(request.model, pipeline, { key: false }));\n }\n if (problems.length > 0) throw new SemanticModelError(problems);\n return options.semantics!.saveSemanticModel(request, callOptions);\n },\n };\n const modelled = async <T>(run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (error instanceof StaleSemanticModelError) throw new ConnectError(error.message, Code.Aborted);\n if (error instanceof SemanticModelError) throw new ConnectError(error.message, Code.InvalidArgument);\n if (error instanceof Error && /^(No semantic model|Version \\d+ of)/.test(error.message)) throw new ConnectError(error.message, Code.NotFound);\n return found(() => Promise.reject(error));\n }\n };\n const saved = async <T>(run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (error instanceof StaleSurfaceError) throw new ConnectError(error.message, Code.Aborted);\n if (error instanceof Error && /^(No saved surface|Version \\d+ of)/.test(error.message)) throw new ConnectError(error.message, Code.NotFound);\n return found(() => Promise.reject(error));\n }\n };\n const unbuilt = () => Promise.reject(new ConnectError(\"Apps are not built yet; use the surface calls.\", Code.Unimplemented));\n const allRoutes = (router: ConnectRouter) => {\n dataRoutes(router);\n agentRoutes(agent)(router);\n if (forms) {\n router.service(FormService, {\n listForms: (r) => found(() => forms.listForms(r)),\n getForm: (r) => found(() => forms.getForm(r)),\n submit: (r) => found(() => forms.submit(r)),\n listSubmissions: (r) => found(() => forms.listSubmissions(r)),\n });\n }\n if (models) {\n const chosen = async <T>(run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (error instanceof ModelChoiceError) throw new ConnectError(error.message, Code.InvalidArgument);\n return found(() => Promise.reject(error));\n }\n };\n router.service(ModelService, {\n listModelBackends: (r) => chosen(() => models.listModelBackends(r)),\n setModel: (r) => chosen(() => models.setModel(r)),\n });\n }\n if (library) {\n router.service(ViewService, {\n listSurfaces: (r) => saved(() => library.listSurfaces(r)),\n getSurface: (r) => saved(() => library.getSurface(r)),\n saveSurface: (r) => saved(() => library.saveSurface(r)),\n deleteSurface: (r) => saved(() => library.deleteSurface(r)),\n listSurfaceVersions: (r) => saved(() => library.listSurfaceVersions(r)),\n listApps: unbuilt,\n getApp: unbuilt,\n saveApp: unbuilt,\n deleteApp: unbuilt,\n listAppVersions: unbuilt,\n createSnapshot: unbuilt,\n getSnapshot: unbuilt,\n });\n }\n if (semantics) {\n router.service(SemanticService, {\n listSemanticModels: (r) => modelled(() => semantics.listSemanticModels(r)),\n getSemanticModel: (r) => modelled(() => semantics.getSemanticModel(r)),\n saveSemanticModel: (r) => modelled(() => semantics.saveSemanticModel(r)),\n deleteSemanticModel: (r) => modelled(() => semantics.deleteSemanticModel(r)),\n listSemanticModelVersions: (r) => modelled(() => semantics.listSemanticModelVersions(r)),\n });\n }\n if (pipelines) {\n router.service(PipelineService, {\n listPipelines: (r) => found(() => pipelines.listPipelines(r)),\n getPipeline: (r) => found(() => pipelines.getPipeline(r)),\n listRuns: (r) => found(() => pipelines.listRuns(r)),\n getRun: (r) => found(() => pipelines.getRun(r)),\n startRun: (r) => found(() => pipelines.startRun(r)),\n cancelRun: (r) => found(() => pipelines.cancelRun(r)),\n savePipeline: (r) =>\n pipelines.savePipeline\n ? found(async () => {\n try {\n return await pipelines.savePipeline!(r);\n } catch (error) {\n if (error instanceof Error && /changed since/.test(error.message)) throw new ConnectError(error.message, Code.Aborted);\n throw error;\n }\n })\n : Promise.reject(new ConnectError(\"Pipelines on this server cannot be changed. Set savedPipelines in surfaces.config.ts to allow approved saves.\", Code.FailedPrecondition)),\n listPipelineVersions: (r) => found(() => pipelines.listPipelineVersions?.(r) ?? Promise.resolve(create(ListPipelineVersionsResponseSchema, {}))),\n });\n router.service(IngestService, { inspectFiles: (r) => guarded(() => pipelines.inspectFiles(r)) });\n }\n if (!discovery) return;\n router.service(DiscoveryService, {\n search: (r) => found(() => discovery.search(r)),\n getObject: (r) => found(() => discovery.getObject(r)),\n getRelated: (r) => found(() => discovery.getRelated(r)),\n describe: (r, context) => found(() => discovery.describe(r, { signal: context.signal })),\n saveDescription: (r) => found(() => discovery.saveDescription(r)),\n setCertification: (r) => found(() => discovery.setCertification(r)),\n async *ask(r, context) {\n try {\n yield* discovery.ask(r, { signal: context.signal });\n } catch (error) {\n throw error instanceof ConnectError ? error : new ConnectError(error instanceof Error ? error.message : String(error), Code.InvalidArgument);\n }\n },\n });\n router.service(ContextService, {\n listContextPacks: (r) => found(() => discovery.listContextPacks(r)),\n getContextPack: (r) => found(() => discovery.getContextPack(r)),\n saveContextPack: (r) => found(() => discovery.saveContextPack(r)),\n deleteContextPack: (r) => found(() => discovery.deleteContextPack(r)),\n renderContextPack: (r) => found(() => discovery.renderContextPack(r)),\n });\n };\n\n const allowed = options.allowedOrigins ?? [LOCALHOST];\n const originAllowed = (origin: string) => allowed.some((rule) => (typeof rule === \"string\" ? rule === origin : rule.test(origin)));\n\n return {\n dataSource,\n discovery,\n pipelines,\n forms,\n library,\n semantics,\n models,\n routes: allRoutes,\n listen(port = 5220, host = \"127.0.0.1\") {\n const handler = connectNodeAdapter({ routes: allRoutes });\n server = http.createServer((req, res) => {\n const origin = req.headers.origin;\n if (origin && originAllowed(origin)) {\n res.setHeader(\"Access-Control-Allow-Origin\", origin);\n res.setHeader(\"Vary\", \"Origin\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\");\n res.setHeader(\n \"Access-Control-Allow-Headers\",\n \"Content-Type, Connect-Protocol-Version, Connect-Timeout-Ms, Connect-Accept-Encoding, Connect-Content-Encoding, X-User-Agent\",\n );\n res.setHeader(\"Access-Control-Max-Age\", \"7200\");\n }\n if (req.method === \"OPTIONS\") {\n res.writeHead(origin && originAllowed(origin) ? 204 : 403).end();\n return;\n }\n handler(req, res);\n });\n return new Promise((resolve, reject) => {\n server!.once(\"error\", reject);\n server!.listen(port, host, () => {\n const address = server!.address() as AddressInfo;\n resolve({ url: `http://${host}:${address.port}`, port: address.port });\n });\n });\n },\n async close() {\n await services.close();\n if (server) {\n server.closeAllConnections();\n await new Promise<void>((resolve) => server!.close(() => resolve()));\n }\n await Promise.all([...sources.values()].map((s) => s.engine.close().catch(() => {})));\n },\n };\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { DiscoveryStore } from "@surfaces-ui/discovery";
2
+ /**
3
+ * Keeps context packs, accepted descriptions and certifications as JSON files in a folder,
4
+ * one file per pack, so they can be reviewed and committed like any other
5
+ * project file.
6
+ */
7
+ export declare function fileDiscoveryStore(dir: string): DiscoveryStore;
package/dist/store.js ADDED
@@ -0,0 +1,88 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fromJson, toJson } from "@bufbuild/protobuf";
4
+ import { ContextPackSchema } from "@surfaces-ui/proto";
5
+ /**
6
+ * Keeps context packs, accepted descriptions and certifications as JSON files in a folder,
7
+ * one file per pack, so they can be reviewed and committed like any other
8
+ * project file.
9
+ */
10
+ export function fileDiscoveryStore(dir) {
11
+ const packsDir = path.join(dir, "context");
12
+ const descriptionsFile = path.join(dir, "descriptions.json");
13
+ // Pack IDs become file names; anything else is refused so an ID cannot escape the folder.
14
+ const fileOf = (id) => {
15
+ if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(id))
16
+ throw new Error("Invalid context pack ID.");
17
+ return path.join(packsDir, `${id}.json`);
18
+ };
19
+ const read = (file) => {
20
+ try {
21
+ return fromJson(ContextPackSchema, JSON.parse(fs.readFileSync(file, "utf8")));
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ };
27
+ const certificationsFile = path.join(dir, "certifications.json");
28
+ const certifications = () => {
29
+ try {
30
+ return JSON.parse(fs.readFileSync(certificationsFile, "utf8"));
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ };
36
+ const descriptions = () => {
37
+ try {
38
+ return JSON.parse(fs.readFileSync(descriptionsFile, "utf8"));
39
+ }
40
+ catch {
41
+ return {};
42
+ }
43
+ };
44
+ return {
45
+ async listPacks() {
46
+ if (!fs.existsSync(packsDir))
47
+ return [];
48
+ return fs
49
+ .readdirSync(packsDir)
50
+ .filter((f) => f.endsWith(".json"))
51
+ .map((f) => read(path.join(packsDir, f)))
52
+ .filter((p) => p !== undefined);
53
+ },
54
+ async getPack(id) {
55
+ return read(fileOf(id));
56
+ },
57
+ async savePack(pack) {
58
+ fs.mkdirSync(packsDir, { recursive: true });
59
+ fs.writeFileSync(fileOf(pack.id), `${JSON.stringify(toJson(ContextPackSchema, pack), null, 2)}\n`);
60
+ },
61
+ async deletePack(id) {
62
+ fs.rmSync(fileOf(id), { force: true });
63
+ },
64
+ async getDescriptions() {
65
+ return descriptions();
66
+ },
67
+ async setDescription(key, value) {
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ // Keys use a NUL separator internally; store them readably.
70
+ const all = descriptions();
71
+ all[key] = value;
72
+ fs.writeFileSync(descriptionsFile, `${JSON.stringify(all, null, 2)}\n`);
73
+ },
74
+ async getCertifications() {
75
+ return certifications();
76
+ },
77
+ async setCertification(key, value) {
78
+ fs.mkdirSync(dir, { recursive: true });
79
+ const all = certifications();
80
+ if (value)
81
+ all[key] = value;
82
+ else
83
+ delete all[key];
84
+ fs.writeFileSync(certificationsFile, `${JSON.stringify(all, null, 2)}\n`);
85
+ },
86
+ };
87
+ }
88
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAoB,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEzE;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAC3C,MAAM,gBAAgB,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAC;IAC7D,0FAA0F;IAC1F,MAAM,MAAM,GAAG,CAAC,EAAU,EAAE,EAAE;QAC5B,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,EAAE,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;QACvF,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,CAAC,IAAY,EAA2B,EAAE;QACrD,IAAI,CAAC;YACH,OAAO,QAAQ,CAAC,iBAAiB,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;QAChF,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IAC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AAE,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5E,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fromJson, toJson } from \"@bufbuild/protobuf\";\nimport type { DiscoveryStore, StoredCertification, StoredDescription } from \"@surfaces-ui/discovery\";\nimport { type ContextPack, ContextPackSchema } from \"@surfaces-ui/proto\";\n\n/**\n * Keeps context packs, accepted descriptions and certifications as JSON files in a folder,\n * one file per pack, so they can be reviewed and committed like any other\n * project file.\n */\nexport function fileDiscoveryStore(dir: string): DiscoveryStore {\n const packsDir = path.join(dir, \"context\");\n const descriptionsFile = path.join(dir, \"descriptions.json\");\n // Pack IDs become file names; anything else is refused so an ID cannot escape the folder.\n const fileOf = (id: string) => {\n if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(id)) throw new Error(\"Invalid context pack ID.\");\n return path.join(packsDir, `${id}.json`);\n };\n const read = (file: string): ContextPack | undefined => {\n try {\n return fromJson(ContextPackSchema, JSON.parse(fs.readFileSync(file, \"utf8\")));\n } catch {\n return undefined;\n }\n };\n const certificationsFile = path.join(dir, \"certifications.json\");\n const certifications = (): Record<string, StoredCertification> => {\n try {\n return JSON.parse(fs.readFileSync(certificationsFile, \"utf8\")) as Record<string, StoredCertification>;\n } catch {\n return {};\n }\n };\n const descriptions = (): Record<string, StoredDescription> => {\n try {\n return JSON.parse(fs.readFileSync(descriptionsFile, \"utf8\")) as Record<string, StoredDescription>;\n } catch {\n return {};\n }\n };\n return {\n async listPacks() {\n if (!fs.existsSync(packsDir)) return [];\n return fs\n .readdirSync(packsDir)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => read(path.join(packsDir, f)))\n .filter((p): p is ContextPack => p !== undefined);\n },\n async getPack(id) {\n return read(fileOf(id));\n },\n async savePack(pack) {\n fs.mkdirSync(packsDir, { recursive: true });\n fs.writeFileSync(fileOf(pack.id), `${JSON.stringify(toJson(ContextPackSchema, pack), null, 2)}\\n`);\n },\n async deletePack(id) {\n fs.rmSync(fileOf(id), { force: true });\n },\n async getDescriptions() {\n return descriptions();\n },\n async setDescription(key, value) {\n fs.mkdirSync(dir, { recursive: true });\n // Keys use a NUL separator internally; store them readably.\n const all = descriptions();\n all[key] = value;\n fs.writeFileSync(descriptionsFile, `${JSON.stringify(all, null, 2)}\\n`);\n },\n async getCertifications() {\n return certifications();\n },\n async setCertification(key, value) {\n fs.mkdirSync(dir, { recursive: true });\n const all = certifications();\n if (value) all[key] = value;\n else delete all[key];\n fs.writeFileSync(certificationsFile, `${JSON.stringify(all, null, 2)}\\n`);\n },\n };\n}\n"]}
@@ -0,0 +1,34 @@
1
+ import { type FormSpec, type Forms, type StateStorage, type MemorySemanticsOptions, type Semantics, type SurfaceLibrary } from "@surfaces-ui/data";
2
+ import type { PipelineStore, RunStore } from "@surfaces-ui/pipelines";
3
+ /**
4
+ * Keeps saved surfaces as one JSON file each in a folder, every version in
5
+ * the file, so they can be reviewed and committed like other project files.
6
+ */
7
+ export declare function fileLibraryStorage(dir: string, idPattern?: RegExp): StateStorage;
8
+ export declare function fileSurfaceLibrary(dir: string): SurfaceLibrary;
9
+ /**
10
+ * Semantic models as one JSON file each in a folder (`<name>.json`, every
11
+ * kept version in it, in the contract's JSON form), so a project's models
12
+ * are reviewed and committed like its other files.
13
+ */
14
+ export declare function fileSemantics(dir: string, options?: Omit<MemorySemanticsOptions, "storage">): Semantics;
15
+ /** A form as `surfaces.config.ts` declares it. */
16
+ export type FormConfig = FormSpec;
17
+ /**
18
+ * Forms whose submissions are appended to one JSON-lines file per form in a
19
+ * folder. Values are checked against the form's fields before anything is
20
+ * written; nothing a client sends chooses the file.
21
+ */
22
+ export declare function fileForms(dir: string, forms: FormConfig[]): Forms;
23
+ /**
24
+ * Pipelines a person approved, as one JSON file each in a folder
25
+ * (`<id>.json`, every version in it), so they are reviewed and committed like
26
+ * other project files. Only the runner writes here, after its checks.
27
+ */
28
+ export declare function filePipelineStore(dir: string): PipelineStore;
29
+ /**
30
+ * Runs kept as one JSON file per pipeline in a folder, newest first and at
31
+ * most `limit` of them, so history outlives a restart. A run is written as it
32
+ * changes; the last write wins, so one server should own a folder.
33
+ */
34
+ export declare function fileRunStore(dir: string, limit?: number): RunStore;