@jxsuite/compiler 11.1.2 → 11.2.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.
@@ -21,7 +21,12 @@ import { readFileSync, readdirSync, statSync } from "node:fs";
21
21
  import { isJsonObject, isString } from "@jxsuite/schema/guards";
22
22
  import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
23
23
  import { errorMessage } from "@jxsuite/schema/parse";
24
- import { compareRoutes, fileToRoute as routeFromFileName } from "@jxsuite/site/routes";
24
+ import {
25
+ compareRoutes,
26
+ fileToRoute as routeFromFileName,
27
+ pageRelativePath,
28
+ routePriority,
29
+ } from "@jxsuite/site/routes";
25
30
  import { pageCount, pageSlice, pageUrl, pagedSource, pagination } from "@jxsuite/site/pagination";
26
31
  import type { PagePagination, PagedSource } from "@jxsuite/site/pagination";
27
32
  import { extname, join, relative, resolve } from "node:path";
@@ -32,6 +37,7 @@ import type {
32
37
  ResolvePathsContext,
33
38
  } from "@jxsuite/schema/format-registry";
34
39
  import type { JsonValue, JxDocument, JxPathsDef, ProjectConfig } from "@jxsuite/schema/types";
40
+ import type { BuildRequestCache } from "./build-time-request.ts";
35
41
  import { localeOfRoute } from "./i18n.ts";
36
42
  import type { ResolvedI18n } from "./i18n.ts";
37
43
  import type { ProjectSections } from "./project-sections.ts";
@@ -67,6 +73,11 @@ interface Route {
67
73
  export interface ExpandOptions {
68
74
  /** Collects one message per misconfigured route; without it the first one throws. */
69
75
  errors?: string[];
76
+ /**
77
+ * The build's `timing: "compiler"` `Request` fetches, shared with every other document the build
78
+ * resolves, so a paged list's request is sent once per build. Absent, each list fetches alone.
79
+ */
80
+ requestCache?: BuildRequestCache;
70
81
  }
71
82
 
72
83
  /**
@@ -199,7 +210,7 @@ async function declaredTranslationKey(
199
210
  *
200
211
  * @param {string} pagesDir - Absolute path to the pages/ directory
201
212
  * @param {FormatRegistry} [registry] - Format registry; its "page"-kind extensions are routable
202
- * @returns {Promise<Route[]>} Sorted route table (static routes first, then dynamic)
213
+ * @returns {Promise<Route[]>} Route table in match order (spec §4.4)
203
214
  */
204
215
  export async function discoverPages(pagesDir: string, registry?: FormatRegistry) {
205
216
  const routes: Route[] = [];
@@ -210,12 +221,84 @@ export async function discoverPages(pagesDir: string, registry?: FormatRegistry)
210
221
  ]);
211
222
  await walkDir(pagesDir, pagesDir, routes, pageExtensions, registry);
212
223
 
213
- // Static routes first, then dynamic, then catch-all (spec §4.4) — the shared ordering.
214
- routes.sort(compareRoutes);
224
+ // Segment-by-segment priority (spec §4.4), ties broken by file path so every host agrees.
225
+ routes.sort(
226
+ (a, b) =>
227
+ compareRoutes(a, b) ||
228
+ pageRelativePath(a.relativePath).localeCompare(pageRelativePath(b.relativePath)),
229
+ );
215
230
 
216
231
  return routes;
217
232
  }
218
233
 
234
+ /** Two pages that generate one concrete URL, and which of them builds it. */
235
+ export interface RouteCollision {
236
+ url: string;
237
+ kind: "outranked" | "tie" | "repeat";
238
+ /** Page path (`pages/…`) of the route that builds the URL. */
239
+ kept: string;
240
+ /** Page path (`pages/…`) of the route that does not. */
241
+ dropped: string;
242
+ message: string;
243
+ }
244
+
245
+ /** The routes {@link resolveRouteCollisions} keeps, and one collision per route it drops. */
246
+ export interface RouteResolution {
247
+ routes: Route[];
248
+ collisions: RouteCollision[];
249
+ }
250
+
251
+ /** The page path of a route, as authors write it. */
252
+ function pagePath(route: Route): string {
253
+ return `pages/${pageRelativePath(route.relativePath)}`;
254
+ }
255
+
256
+ /**
257
+ * Leave one route per concrete URL (spec §4.4, "Two pages, one URL").
258
+ *
259
+ * Precondition: `routes` is {@link expandDynamicRoutes}' output, which keeps {@link discoverPages}'
260
+ * order with each template's expansions contiguous, so the first route for a URL is the one with
261
+ * priority. A trailing slash is not significant, so a catch-all expanded with an empty rest meets
262
+ * the index page.
263
+ *
264
+ * @param {Route[]} routes - Expanded routes, in priority order
265
+ * @returns {{ routes: Route[]; collisions: RouteCollision[] }} The routes kept, and one collision
266
+ * per route dropped
267
+ */
268
+ export function resolveRouteCollisions(routes: Route[]): RouteResolution {
269
+ const seen = new Map<string, Route>();
270
+ const kept: Route[] = [];
271
+ const collisions: RouteCollision[] = [];
272
+ for (const route of routes) {
273
+ const url =
274
+ route.urlPattern.length > 1 ? route.urlPattern.replace(/\/+$/, "") : route.urlPattern;
275
+ const first = seen.get(url);
276
+ if (first === undefined) {
277
+ seen.set(url, route);
278
+ kept.push(route);
279
+ continue;
280
+ }
281
+ const keptPath = pagePath(first);
282
+ const droppedPath = pagePath(route);
283
+ let kind: RouteCollision["kind"] = "outranked";
284
+ let message = `${keptPath} and ${droppedPath} both generate ${url}. ${keptPath} is the more specific route, so it builds ${url} and ${droppedPath} does not.`;
285
+ if (first.sourcePath === route.sourcePath) {
286
+ kind = "repeat";
287
+ message = `The $paths of ${keptPath} yields ${url} more than once; it is built once.`;
288
+ } else if (
289
+ routePriority(
290
+ routeFromFileName(first.relativePath),
291
+ routeFromFileName(route.relativePath),
292
+ ) === 0
293
+ ) {
294
+ kind = "tie";
295
+ message = `${keptPath} and ${droppedPath} both generate ${url}, and neither route is more specific than the other. Rename or remove one of them.`;
296
+ }
297
+ collisions.push({ dropped: droppedPath, kept: keptPath, kind, message, url });
298
+ }
299
+ return { collisions, routes: kept };
300
+ }
301
+
219
302
  /**
220
303
  * Recursively walk the pages directory tree.
221
304
  *
@@ -436,6 +519,7 @@ export async function expandDynamicRoutes(
436
519
  projectRoot,
437
520
  registry,
438
521
  report,
522
+ requestCache: options.requestCache,
439
523
  sections,
440
524
  });
441
525
  expanded.push(...pages);
@@ -509,6 +593,7 @@ interface PagedContext {
509
593
  projectRoot: string;
510
594
  registry: ExtensionRegistry | undefined;
511
595
  report: (route: Route, message: string) => void;
596
+ requestCache: BuildRequestCache | undefined;
512
597
  sections: ProjectSections;
513
598
  }
514
599
 
@@ -662,6 +747,7 @@ async function resolvePagedEntry(
662
747
  await resolvePrototypes(mini, pageRoute, ctx.projectRoot, {
663
748
  ...(ctx.projectConfig && { config: ctx.projectConfig }),
664
749
  ...(ctx.registry && { registry: ctx.registry }),
750
+ ...(ctx.requestCache && { requestCache: ctx.requestCache }),
665
751
  sections: ctx.sections,
666
752
  });
667
753
  /* SAFETY: a resolved class entry is the JSON its `resolve()` answered with, and an unresolved
@@ -12,14 +12,18 @@ import { createServer } from "node:http";
12
12
  import type { Server } from "node:http";
13
13
  import { existsSync, readFileSync, statSync } from "node:fs";
14
14
  import { extname, join, normalize, resolve, sep } from "node:path";
15
- import { MEDIA_TYPE_BY_EXTENSION } from "@jxsuite/schema/media-type";
15
+ import { mediaTypeForPath } from "@jxsuite/schema/media-type";
16
+ import type { DeclaredMediaTypes } from "@jxsuite/schema/media-type";
17
+ import { parseProjectSource } from "@jxsuite/schema/project-file";
18
+ import { projectFileStamp } from "@jxsuite/schema/project-file/node";
19
+ import { buildProjectExtensionRegistry } from "./format-host.ts";
16
20
 
17
21
  /*
18
- * The extensions this server can be asked for. `MEDIA_TYPE_BY_EXTENSION` is spread in **last** so
19
- * the registered spellings win: `.md` carries the `variant` that says which markdown it is, and
20
- * `.yaml`/`.yml` are `application/yaml` rather than an `application/octet-stream` download prompt.
21
- * Everything else is this table's own, because a shared table for `image/png` would be a second
22
- * source of truth for something no standard is ambiguous about.
22
+ * The extensions this server can be asked for. `mediaTypeForPath` answers first (an enabled
23
+ * format's declaration, then the core table's registered spellings: `.md` with the `variant` that
24
+ * says which markdown it is, `.yaml`/`.yml` as `application/yaml`), so this table never repeats
25
+ * them. Everything here is this table's own, because a shared table for `image/png` would be a
26
+ * second source of truth for something no standard is ambiguous about.
23
27
  */
24
28
  const MIME_TYPES = new Map(
25
29
  Object.entries({
@@ -38,7 +42,6 @@ const MIME_TYPES = new Map(
38
42
  ".webp": "image/webp",
39
43
  ".woff2": "font/woff2",
40
44
  ".xml": "application/xml; charset=utf-8",
41
- ...MEDIA_TYPE_BY_EXTENSION,
42
45
  }),
43
46
  );
44
47
 
@@ -68,23 +71,49 @@ export function resolvePreviewFile(distDir: string, pathname: string): string |
68
71
  return existsSync(index) ? index : null;
69
72
  }
70
73
 
74
+ /**
75
+ * The project's enabled formats, built once for the server's lifetime (`dist/` is fixed output, so
76
+ * a changed `extensions` list needs a rebuild anyway). Null with no project file, and null with one
77
+ * warning when the registry cannot build: a preview that refuses to start over a broken extension
78
+ * helps nobody.
79
+ */
80
+ async function previewFormats(projectRoot: string): Promise<DeclaredMediaTypes | null> {
81
+ const stamp = projectFileStamp(projectRoot);
82
+ if (!stamp) {
83
+ return null;
84
+ }
85
+ try {
86
+ const config = parseProjectSource(readFileSync(stamp.path, "utf8"), stamp.path);
87
+ const registry = await buildProjectExtensionRegistry(projectRoot, config);
88
+ return registry.formats;
89
+ } catch (error) {
90
+ const reason = error instanceof Error ? error.message : String(error);
91
+ console.warn(`jx preview: ${reason}; files are typed by the core table`);
92
+ return null;
93
+ }
94
+ }
95
+
71
96
  /**
72
97
  * Start the preview server on the given port (0 picks a free port).
73
98
  *
74
99
  * @param {string} distDir - Absolute path to the built dist directory
75
100
  * @param {number} port - Port to listen on
101
+ * @param {string} [projectRoot] - The project, whose enabled formats type the files they claim
76
102
  * @returns {Server} The listening node:http server
77
103
  */
78
- export function startPreviewServer(distDir: string, port: number): Server {
104
+ export function startPreviewServer(distDir: string, port: number, projectRoot?: string): Server {
79
105
  const dist = resolve(distDir);
80
- const server = createServer((req, res) => {
106
+ const formats = projectRoot === undefined ? Promise.resolve(null) : previewFormats(projectRoot);
107
+ const server = createServer(async (req, res) => {
81
108
  const url = new URL(req.url ?? "/", "http://localhost");
82
109
  const filePath = resolvePreviewFile(dist, decodeURIComponent(url.pathname));
83
110
 
84
111
  if (filePath) {
85
112
  res.writeHead(200, {
86
113
  "Content-Type":
87
- MIME_TYPES.get(extname(filePath).toLowerCase()) ?? "application/octet-stream",
114
+ mediaTypeForPath(filePath, await formats) ??
115
+ MIME_TYPES.get(extname(filePath).toLowerCase()) ??
116
+ "application/octet-stream",
88
117
  });
89
118
  res.end(readFileSync(filePath));
90
119
  return;
@@ -4,11 +4,14 @@
4
4
  * Loads every extension-contributed project.json section through the owning class's `projectData`
5
5
  * capability and returns the results keyed by section key. Hosts thread the record through the
6
6
  * build (route expansion, prototype resolution) without knowing any section's shape.
7
+ *
8
+ * @docs extending/extensions/project-sections
7
9
  */
8
10
 
9
11
  import { createNodeFormatIO } from "./format-host.ts";
12
+ import { isNonNullObject } from "@jxsuite/schema/guards";
10
13
  import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
11
- import type { ProjectSectionData } from "@jxsuite/schema/format-registry";
14
+ import type { FormatEntry, ProjectSectionData } from "@jxsuite/schema/format-registry";
12
15
  import type { ProjectConfig } from "@jxsuite/schema/types";
13
16
 
14
17
  /* One section's `projectData` result. The host never reads inside it: it hands it to classes as
@@ -19,12 +22,41 @@ export type { ProjectSectionData } from "@jxsuite/schema/format-registry";
19
22
  /** Every loaded project section, keyed by its section key (`content`, `auth`, ...). */
20
23
  export type ProjectSections = Record<string, ProjectSectionData>;
21
24
 
25
+ /**
26
+ * Whether a section owner contributes to the build or the dev server (specs/extensions.md §8.4).
27
+ *
28
+ * A class that owns no project section is always active. A section owner is inactive when its value
29
+ * is absent, `null`, or an object or array with no own keys, and active for any other value. One
30
+ * test decides `emit`, `assets`, `head`, server-mount activation and section-owner push steps in
31
+ * every host. Section loading is deliberately not gated by it.
32
+ *
33
+ * @param {Pick<FormatEntry, "project">} entry - The class entry
34
+ * @param {ProjectConfig | undefined} projectConfig - The project config
35
+ * @returns {boolean} Whether the entry's contributions apply
36
+ */
37
+ export function sectionOwnerActive(
38
+ entry: Pick<FormatEntry, "project">,
39
+ projectConfig: ProjectConfig | undefined,
40
+ ): boolean {
41
+ if (entry.project == null) {
42
+ return true;
43
+ }
44
+ const value: unknown = projectConfig?.[entry.project.key];
45
+ if (value === undefined || value === null) {
46
+ return false;
47
+ }
48
+ return isNonNullObject(value) ? Object.keys(value).length > 0 : true;
49
+ }
50
+
22
51
  /**
23
52
  * Load all extension-contributed project sections.
24
53
  *
25
54
  * A section is loaded only when its key is present in the project config: `projectData` on an
26
55
  * absent section would only manufacture empty data (the parser's returns an empty Map), so skipping
27
- * keeps `_project` free of keys the author never declared — and is the cheaper rule.
56
+ * keeps `_project` free of keys the author never declared — and is the cheaper rule. Loading is not
57
+ * gated by {@link sectionOwnerActive} (specs/extensions.md §8.4): it contributes no file, route or
58
+ * head entry, and the owner's `resolvePaths` reads the loaded value unguarded, so an empty section
59
+ * must still load.
28
60
  *
29
61
  * @param {string} projectRoot - Absolute path to the project root
30
62
  * @param {ProjectConfig | undefined} projectConfig - Already-loaded project config
@@ -20,13 +20,16 @@ import { isJsonObject, isPrototypeDef, isString } from "@jxsuite/schema/guards";
20
20
  import { errorMessage } from "@jxsuite/schema/parse";
21
21
  import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
22
22
  import type {
23
+ JsonValue,
23
24
  JxDocument,
24
25
  JxMutableNode,
25
26
  JxPrototypeDef,
26
27
  JxStateDefinition,
27
28
  ProjectConfig,
28
29
  } from "@jxsuite/schema/types";
29
- import { externalClassConfig, isExternalClassDef } from "../shared.ts";
30
+ import { buildInitialScope, externalClassConfig, isExternalClassDef } from "../shared.ts";
31
+ import { fetchAtBuildTime } from "./build-time-request.ts";
32
+ import type { BuildRequestCache } from "./build-time-request.ts";
30
33
  import { instantiateAndResolve, loadClass, locateClass } from "./external-class.ts";
31
34
  import type { ClassRoute, ExternalClassConfig } from "./external-class.ts";
32
35
  import type { ProjectSections } from "./project-sections.ts";
@@ -49,6 +52,11 @@ interface PrototypeProjectContext {
49
52
  * for one has to stay a state entry; a page's is baked into its markup and then stripped.
50
53
  */
51
54
  asInitialValues?: boolean;
55
+ /**
56
+ * Shares each distinct `timing: "compiler"` `Request` fetch between the pages of one build, so a
57
+ * request a layout names is sent once. Absent, every entry is fetched on its own.
58
+ */
59
+ requestCache?: BuildRequestCache;
52
60
  }
53
61
 
54
62
  /**
@@ -57,11 +65,14 @@ interface PrototypeProjectContext {
57
65
  * A client- or server-timed entry stays for its own pipeline, unless its registry class has a
58
66
  * `lower` capability, which compiles it away here into a core-shape def (specs/extensions.md §8.3).
59
67
  * Every other entry that names an external class (`timing: "compiler"`, or no `timing`) is located,
60
- * loaded, constructed and replaced with its value (`external-class.ts`).
68
+ * loaded, constructed and replaced with its value (`external-class.ts`). A `timing: "compiler"`
69
+ * `Request` is fetched once, after the classes, and replaced with its JSON response
70
+ * (`build-time-request.ts`). Any other built-in at compiler timing has no build-time value, so it
71
+ * is refused.
61
72
  *
62
- * Nothing is swallowed: a `lower` that throws, a compiler-timed entry that names no class, and a
63
- * class that cannot be located, loaded or resolved are each collected, and one error naming every
64
- * such entry is thrown after the rest have been tried.
73
+ * Nothing is swallowed: a `lower` that throws, a compiler-timed entry that names no class or has no
74
+ * build-time value, and a class or request that cannot be located, loaded, fetched or resolved are
75
+ * each collected, and one error naming every such entry is thrown after the rest have been tried.
65
76
  *
66
77
  * @param {JxMutableNode | JxDocument} doc - The document (mutated in place)
67
78
  * @param {ClassRoute} route - Route info
@@ -92,14 +103,40 @@ export async function resolvePrototypes(
92
103
  registry: projectContext.registry,
93
104
  };
94
105
 
106
+ /** The `timing: "compiler"` `Request` entries, fetched once every class has resolved. */
107
+ const requests: [string, JxPrototypeDef][] = [];
108
+ /** Writes one resolved value as its entry's state, in the shape the caller asked for. */
109
+ const assign = (key: string, def: JxPrototypeDef, value: JsonValue): void => {
110
+ if (projectContext.asInitialValues) {
111
+ state[key] = { default: value ?? null };
112
+ } else {
113
+ // Preserve timing metadata on the resolved value so compilePage() can strip it
114
+ if (def.timing && isJsonObject(value)) {
115
+ value.timing = def.timing;
116
+ }
117
+ state[key] = value;
118
+ }
119
+ replaced[key] = state[key];
120
+ };
121
+
95
122
  for (const [key, def] of Object.entries(state)) {
96
123
  if (!isPrototypeDef(def)) {
97
124
  continue;
98
125
  }
126
+ const label = `"${key}" ($prototype "${def.$prototype}")`;
127
+ /* A built-in at compiler timing has a build-time value only when it is a `Request`. Any other
128
+ one is refused, because the page it would bake is the one the build reports as built. */
129
+ if (isBuiltInAtCompilerTiming(def)) {
130
+ if (def.$prototype === "Request") {
131
+ requests.push([key, def]);
132
+ } else {
133
+ failures.push(`${label}: has no build-time value; remove "timing" or use "client"`);
134
+ }
135
+ continue;
136
+ }
99
137
  if (SKIP_PROTOTYPES.has(def.$prototype)) {
100
138
  continue;
101
139
  }
102
- const label = `"${key}" ($prototype "${def.$prototype}")`;
103
140
  // Only resolve timing: "compiler" (or unset timing with a class mapping). Timing: "server"
104
141
  // And timing: "client" stay for their pipelines — but a registry class with a `lower`
105
142
  // Capability compiles away here into a core-shape def (specs/extensions.md §8.3): dynamic
@@ -139,9 +176,10 @@ export async function resolvePrototypes(
139
176
  try {
140
177
  const located = locateClass(def, lookup);
141
178
  if (located === undefined) {
142
- // A built-in at compiler timing, and an unset-timing name nothing maps, are not this
143
- // Resolver's: the first belongs to its own target, the second may only ever run interpreted.
144
- if (def.timing === "compiler" && isExternalClassDef(def)) {
179
+ /* A built-in that maps to no class belongs to its own target, or to the interpreter. An
180
+ external class that maps to none fails the build, whatever its timing: no target would
181
+ construct it, so the page would be bound to nothing while the build reports success. */
182
+ if (isExternalClassDef(def)) {
145
183
  failures.push(
146
184
  `${label} names no class: give it a $src or an imports entry, or enable the ` +
147
185
  `extension that provides "${def.$prototype}"`,
@@ -154,22 +192,31 @@ export async function resolvePrototypes(
154
192
  Ctor,
155
193
  buildConfig(def, route, projectRoot, state, projectContext),
156
194
  );
157
- if (projectContext.asInitialValues) {
158
- state[key] = { default: value ?? null };
159
- } else {
160
- // Preserve timing metadata on the resolved value so compilePage() can strip it
161
- if (def.timing && isJsonObject(value)) {
162
- value.timing = def.timing;
163
- }
164
- state[key] = value;
165
- }
166
- replaced[key] = state[key];
195
+ assign(key, def, value);
167
196
  } catch (error) {
168
197
  const hint = def.timing ? "" : ' (set "timing": "client" if it must run in the browser)';
169
198
  failures.push(`${label}: ${errorMessage(error)}${hint}`);
170
199
  }
171
200
  }
172
201
 
202
+ if (requests.length > 0) {
203
+ /* One scope over the state as the classes left it: a `url` may read `$site`, `$page`, constants
204
+ and resolved values, and a runtime-only entry (another `Request`) fails as unresolvable. */
205
+ const scope = buildInitialScope(state);
206
+ await Promise.all(
207
+ requests.map(async ([key, def]) => {
208
+ try {
209
+ const value = await fetchAtBuildTime(def, scope, {
210
+ cache: projectContext.requestCache,
211
+ });
212
+ assign(key, def, value);
213
+ } catch (error) {
214
+ failures.push(`"${key}" ($prototype "Request"): ${errorMessage(error)}`);
215
+ }
216
+ }),
217
+ );
218
+ }
219
+
173
220
  if (failures.length > 0) {
174
221
  throw new Error(
175
222
  failures.length === 1
@@ -180,6 +227,14 @@ export async function resolvePrototypes(
180
227
  return replaced;
181
228
  }
182
229
 
230
+ /**
231
+ * Whether an entry is a built-in at `timing: "compiler"`. Such an entry has a build-time value only
232
+ * when it is a `Request`, which is fetched; any other is refused.
233
+ */
234
+ function isBuiltInAtCompilerTiming(def: JxPrototypeDef): boolean {
235
+ return def.timing === "compiler" && !isExternalClassDef(def);
236
+ }
237
+
183
238
  /**
184
239
  * The config a class is constructed with during the build: the entry's own keys minus the reserved
185
240
  * ones (spec.md §12.3), plus what only the build host knows.
@@ -59,6 +59,10 @@ export async function composeEntryDocuments(projectRoot: string) {
59
59
  project: ext.schemas.project && fragmentRef(projectRoot, ext, ext.schemas.project),
60
60
  })),
61
61
  loadJson: restrictedSchemaLoader(root),
62
+ // The field union refuses a pointer into any other section (specs/extensions.md §9).
63
+ referenceableSections: registry
64
+ .referenceableSections()
65
+ .flatMap((entry) => (entry.project ? [entry.project.key] : [])),
62
66
  });
63
67
 
64
68
  return { documentSchema, projectSchema };
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Section-push: the one loop that composes section owners' `deploySchema` steps for a schema push
3
+ * (specs/extensions.md §11.1, §12). Both hosts call it: `jx db push` (`db-push.ts`) with each
4
+ * provider's own class, and the dev server's studio push (`@jxsuite/server`) with the `local:`
5
+ * stand-ins its mounts receive. The host stays extension-agnostic: registry dispatch only, no
6
+ * extension import and no section-name literal.
7
+ */
8
+
9
+ import { errorMessage } from "@jxsuite/schema/parse";
10
+ import { sectionOwnerActive } from "./project-sections.ts";
11
+ import { isString } from "@jxsuite/schema/guards";
12
+ import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
13
+ import type {
14
+ ImplementationExport,
15
+ SectionDeployOptions,
16
+ SectionPushStep,
17
+ } from "@jxsuite/schema/format-registry";
18
+ import type { ProjectConfig } from "@jxsuite/schema/types";
19
+
20
+ export type { SectionPushStep } from "@jxsuite/schema/format-registry";
21
+
22
+ /** What one section owner contributed to a push. */
23
+ export interface SectionPushResult {
24
+ /** The section key the owner contributes under. */
25
+ section: string;
26
+ steps: SectionPushStep[];
27
+ warnings: string[];
28
+ /** True when the steps were executed (never on a dry run or after an error). */
29
+ applied: boolean;
30
+ /** The owner's thrown message, when its `deploySchema` (or a connector import) failed. */
31
+ error?: string;
32
+ }
33
+
34
+ /** The connector implementation classes a push hands section owners, keyed by provider id. */
35
+ type ConnectorClasses = Record<string, ImplementationExport | null | undefined>;
36
+
37
+ /**
38
+ * Resolve connector implementation classes keyed by provider id. With `standins`, a connector
39
+ * declaring `local: "<provider>"` is served by the registry's class for that provider instead of
40
+ * its own (specs/extensions.md §12); without, each provider is its own class, as the generated
41
+ * worker builds the map.
42
+ *
43
+ * Each provider is its implementation module's export (specs/extensions.md §6.1): this host only
44
+ * routes it. A module exporting no such export yields a nullish entry, which the receiving mount or
45
+ * section owner reports as an unavailable provider.
46
+ *
47
+ * @param {ExtensionRegistry} registry
48
+ * @param {{ standins: boolean }} options
49
+ * @returns {Promise<ConnectorClasses>}
50
+ */
51
+ export async function resolveConnectorClasses(
52
+ registry: ExtensionRegistry,
53
+ options: { standins: boolean },
54
+ ): Promise<ConnectorClasses> {
55
+ const entries = registry.connectors();
56
+ const out: ConnectorClasses = {};
57
+ for (const entry of entries) {
58
+ const provider = String(entry.connector!.provider);
59
+ const { local } = entry.connector!;
60
+ const target =
61
+ options.standins && isString(local)
62
+ ? (entries.find((e) => e.connector!.provider === local) ?? entry)
63
+ : entry;
64
+ out[provider] = await target.implementationExport();
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Run every section owner's `deploySchema` (any non-connector project contribution declaring the
71
+ * capability), in contribution order. A section absent or null in the project contributes nothing;
72
+ * a step with no kind takes the section key; an owner that throws is reported on its result.
73
+ *
74
+ * @param {ExtensionRegistry} registry
75
+ * @param {ProjectConfig} config
76
+ * @param {object} options - `standins` picks the connector classes handed to the owners
77
+ * @returns {Promise<SectionPushResult[]>}
78
+ */
79
+ export async function pushSectionOwners(
80
+ registry: ExtensionRegistry,
81
+ config: ProjectConfig,
82
+ options: {
83
+ env: SectionDeployOptions["env"];
84
+ dryRun: boolean;
85
+ connection?: string | undefined;
86
+ standins: boolean;
87
+ },
88
+ ): Promise<SectionPushResult[]> {
89
+ const { dryRun, env, standins } = options;
90
+ const owners = registry
91
+ .projectContributions()
92
+ .filter((entry) => entry.connector === null && entry.capabilities.deploySchema);
93
+
94
+ // Resolved lazily and once, so a project without a section owner imports no connector code.
95
+ let connectorsPromise: Promise<ConnectorClasses> | undefined;
96
+ const results: SectionPushResult[] = [];
97
+ for (const entry of owners) {
98
+ const { key } = entry.project!;
99
+ const section = config[key];
100
+ if (section === undefined || section === null || !sectionOwnerActive(entry, config)) {
101
+ continue;
102
+ }
103
+ try {
104
+ connectorsPromise ??= resolveConnectorClasses(registry, { standins });
105
+ const connectors = await connectorsPromise;
106
+ const deployOptions: SectionDeployOptions = { connectors, dryRun, env };
107
+ if (options.connection !== undefined) {
108
+ deployOptions.connection = options.connection;
109
+ }
110
+ const result = await entry.call("deploySchema", section, config, deployOptions);
111
+ const steps = result.steps.map((step) => {
112
+ step.kind ||= key;
113
+ return step;
114
+ });
115
+ results.push({
116
+ applied: !dryRun,
117
+ section: key,
118
+ steps,
119
+ warnings: result.warnings,
120
+ });
121
+ } catch (error) {
122
+ results.push({
123
+ applied: false,
124
+ error: errorMessage(error),
125
+ section: key,
126
+ steps: [],
127
+ warnings: [],
128
+ });
129
+ }
130
+ }
131
+ return results;
132
+ }