@duffcloudservices/cms 0.13.9 → 0.13.11

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/README.md CHANGED
@@ -319,6 +319,10 @@ dcsContentPlugin({
319
319
  })
320
320
  ```
321
321
 
322
+ On production builds the plugin also injects the AI-assistant loader, a small inline `<script data-dcs-agent-loader>` in `<head>`. By default it asks the page's own host for `/api/v1/agent/config` first, then falls back to the platform route `/api/v1/sites/<slug>/agent/config`.
323
+
324
+ Some sites have a production host with no `/api` route, such as a site served from its SWA default hostname. For those, set `agent_config_origin: platform` in `.dcs/site.yaml`. The loader then makes one request to the platform route and never probes the page host, so no 404 appears in the visitor's console (C-1941). The served tag carries `data-dcs-agent-config-origin="platform"`. If the key is absent or set to `same-origin`, the loader is unchanged. Any other value is ignored with one build-time warning.
325
+
322
326
  ### dcsSeoPlugin
323
327
 
324
328
  Injects `.dcs/seo.yaml` at build time and, opt-in, emits per-route static SEO.
@@ -721,7 +721,20 @@ interface DcsAgentWidgetLoaderOptions {
721
721
  apiBaseUrl?: string;
722
722
  /** Full URL of the CDN widget bundle. */
723
723
  cdnScriptUrl?: string;
724
+ /**
725
+ * Where the loader asks for the agent config (C-1941). `'same-origin'`
726
+ * (default, unchanged) probes the page host's slug-free `/api/v1/agent/config`
727
+ * first, then falls back to the platform slug route. `'platform'` goes
728
+ * straight to the platform slug route and never probes the page host. Use it
729
+ * for a site whose production host has no `/api` route, such as an SWA
730
+ * default hostname. There the same-origin probe always 404s and leaves an
731
+ * uncatchable console line on every page load.
732
+ */
733
+ configOrigin?: AgentConfigOrigin;
724
734
  }
735
+ /** The values `.dcs/site.yaml` `agent_config_origin` accepts (C-1941). */
736
+ declare const AGENT_CONFIG_ORIGINS: readonly ["same-origin", "platform"];
737
+ type AgentConfigOrigin = (typeof AGENT_CONFIG_ORIGINS)[number];
725
738
  /**
726
739
  * Builds the inline loader script body. Slug + URLs are HTML-safe-encoded (see
727
740
  * encodeForInlineScript) so no value can break out of the string literal OR the
@@ -736,6 +749,13 @@ declare function buildAgentWidgetLoaderScript(options: DcsAgentWidgetLoaderOptio
736
749
  * builds).
737
750
  */
738
751
  declare function readSiteSlug(projectRoot: string): string | null;
752
+ /**
753
+ * Reads `agent_config_origin` from `.dcs/site.yaml` (C-1941). If the key is
754
+ * absent it returns null, and the loader keeps its same-origin-first default. A
755
+ * value outside AGENT_CONFIG_ORIGINS is ignored with ONE build-time
756
+ * console.warn. It never fails the build and never changes the served loader.
757
+ */
758
+ declare function readAgentConfigOrigin(projectRoot: string): AgentConfigOrigin | null;
739
759
  interface DcsAgentWidgetTagOptions {
740
760
  /** Vite project root used to resolve the site slug. */
741
761
  projectRoot: string;
@@ -750,4 +770,4 @@ interface DcsAgentWidgetTagOptions {
750
770
  */
751
771
  declare function dcsAgentWidgetLoaderTag(options: DcsAgentWidgetTagOptions): HtmlTagDescriptor | null;
752
772
 
753
- export { DCS_MOTION_TOKENS_CSS, DEFAULT_AGENT_API_BASE_URL, DEFAULT_AGENT_WIDGET_SCRIPT_URL, type DcsAgentWidgetLoaderOptions, type DcsAgentWidgetTagOptions, type DcsCdnBuildEndOptions, type DcsCdnImagePluginOptions, type DcsContentPluginOptions, type DcsEditorPluginOptions, type DcsPreviewPluginOptions, type DcsResponsiveImageLintOptions, type DcsSeoPluginOptions, NoindexOrphanError, type ResponsiveImageLintReport, type ResponsiveImageViolation, buildAgentWidgetLoaderScript, chainBuildEnd, collectNoindexMatchKeys, dcsAgentWidgetLoaderTag, dcsCdnBuildEnd, dcsCdnImagePlugin, dcsContentPlugin, dcsEditorPlugin, dcsMotionTokensStyleTag, dcsPreviewPlugin, dcsResponsiveImageLint, dcsSeoPlugin, emitSiteFiles, emitStaticSeoHtml, findFullSizeCdnImages, findOrphanNoindexEntries, isFullSizeCdnUrl, readSiteSlug, responsiveImagePlugin };
773
+ export { AGENT_CONFIG_ORIGINS, type AgentConfigOrigin, DCS_MOTION_TOKENS_CSS, DEFAULT_AGENT_API_BASE_URL, DEFAULT_AGENT_WIDGET_SCRIPT_URL, type DcsAgentWidgetLoaderOptions, type DcsAgentWidgetTagOptions, type DcsCdnBuildEndOptions, type DcsCdnImagePluginOptions, type DcsContentPluginOptions, type DcsEditorPluginOptions, type DcsPreviewPluginOptions, type DcsResponsiveImageLintOptions, type DcsSeoPluginOptions, NoindexOrphanError, type ResponsiveImageLintReport, type ResponsiveImageViolation, buildAgentWidgetLoaderScript, chainBuildEnd, collectNoindexMatchKeys, dcsAgentWidgetLoaderTag, dcsCdnBuildEnd, dcsCdnImagePlugin, dcsContentPlugin, dcsEditorPlugin, dcsMotionTokensStyleTag, dcsPreviewPlugin, dcsResponsiveImageLint, dcsSeoPlugin, emitSiteFiles, emitStaticSeoHtml, findFullSizeCdnImages, findOrphanNoindexEntries, isFullSizeCdnUrl, readAgentConfigOrigin, readSiteSlug, responsiveImagePlugin };
@@ -79,16 +79,23 @@ var config = {
79
79
  // src/plugins/agentWidget.ts
80
80
  var DEFAULT_AGENT_API_BASE_URL = config.agentApiBaseUrl;
81
81
  var DEFAULT_AGENT_WIDGET_SCRIPT_URL = config.agentWidgetScriptUrl;
82
+ var AGENT_CONFIG_ORIGINS = ["same-origin", "platform"];
82
83
  var trimTrailingSlash = (value) => value.replace(/\/+$/, "");
83
84
  var encodeForInlineScript = (value) => JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
84
85
  function buildAgentWidgetLoaderScript(options) {
85
86
  const slug = encodeForInlineScript(options.siteSlug);
86
87
  const api = encodeForInlineScript(trimTrailingSlash(options.apiBaseUrl || DEFAULT_AGENT_API_BASE_URL));
87
88
  const cdn = encodeForInlineScript(options.cdnScriptUrl || DEFAULT_AGENT_WIDGET_SCRIPT_URL);
88
- return "(function(){try{if(window.__DCS_AGENT_LOADER__)return;window.__DCS_AGENT_LOADER__=1;try{if(window.self!==window.top)return;}catch(e){return;}if(/[?&]dcs-hide-widget(?:[=&]|$)/.test(location.search))return;var S=" + slug + ",A=" + api + ",C=" + cdn + ';var go=function(){try{var p=function(u){return fetch(u,{headers:{Accept:"application/json"}}).then(function(r){if(!r||(r.headers.get("content-type")||"").indexOf("json")===-1)return null;return r.ok?r.json()["catch"](function(){return null;}):0;})["catch"](function(){return null;});};p("/api/v1/agent/config").then(function(c){return c===null?p(A+"/api/v1/sites/"+encodeURIComponent(S)+"/agent/config"):c;}).then(function(c){if(!c||!c.enabled)return;window.__DCS_AGENT_BOOTSTRAP__={siteSlug:S,apiBaseUrl:A,config:c};var s=document.createElement("script");s.src=C;s.async=true;s.setAttribute("data-dcs-agent-slug",S);(document.head||document.documentElement).appendChild(s);}).catch(function(){});}catch(e){}};if("requestIdleCallback"in window){requestIdleCallback(go,{timeout:4000});}else{setTimeout(go,1200);}}catch(e){}})();';
89
+ const platformProbe = 'p(A+"/api/v1/sites/"+encodeURIComponent(S)+"/agent/config")';
90
+ const configChain = options.configOrigin === "platform" ? platformProbe : 'p("/api/v1/agent/config").then(function(c){return c===null?' + platformProbe + ":c;})";
91
+ return "(function(){try{if(window.__DCS_AGENT_LOADER__)return;window.__DCS_AGENT_LOADER__=1;try{if(window.self!==window.top)return;}catch(e){return;}if(/[?&]dcs-hide-widget(?:[=&]|$)/.test(location.search))return;var S=" + slug + ",A=" + api + ",C=" + cdn + ';var go=function(){try{var p=function(u){return fetch(u,{headers:{Accept:"application/json"}}).then(function(r){if(!r||(r.headers.get("content-type")||"").indexOf("json")===-1)return null;return r.ok?r.json()["catch"](function(){return null;}):0;})["catch"](function(){return null;});};' + // C-1941: configOrigin 'platform' drops the same-origin arm entirely.
92
+ configChain + '.then(function(c){if(!c||!c.enabled)return;window.__DCS_AGENT_BOOTSTRAP__={siteSlug:S,apiBaseUrl:A,config:c};var s=document.createElement("script");s.src=C;s.async=true;s.setAttribute("data-dcs-agent-slug",S);(document.head||document.documentElement).appendChild(s);}).catch(function(){});}catch(e){}};if("requestIdleCallback"in window){requestIdleCallback(go,{timeout:4000});}else{setTimeout(go,1200);}}catch(e){}})();';
89
93
  }
90
94
  var SITE_YAML_CANDIDATES = [".dcs/site.yaml", "../.dcs/site.yaml"];
91
95
  function readSiteSlug(projectRoot) {
96
+ return readSiteYaml(projectRoot)?.slug ?? null;
97
+ }
98
+ function readSiteYaml(projectRoot) {
92
99
  const candidates = [
93
100
  ...SITE_YAML_CANDIDATES.map((rel) => path5.resolve(projectRoot, rel)),
94
101
  path5.resolve(process.cwd(), ".dcs/site.yaml")
@@ -98,22 +105,38 @@ function readSiteSlug(projectRoot) {
98
105
  if (!fs5.existsSync(candidate)) continue;
99
106
  const parsed = yaml4.load(fs5.readFileSync(candidate, "utf8"));
100
107
  const slug = parsed && typeof parsed.site_slug === "string" ? parsed.site_slug.trim() : "";
101
- if (slug) return slug;
108
+ if (parsed && slug) return { slug, fields: parsed };
102
109
  } catch {
103
110
  }
104
111
  }
105
112
  return null;
106
113
  }
114
+ function readAgentConfigOrigin(projectRoot) {
115
+ const raw = readSiteYaml(projectRoot)?.fields.agent_config_origin;
116
+ if (raw === void 0 || raw === null) return null;
117
+ const value = typeof raw === "string" ? raw.trim() : raw;
118
+ if (typeof value === "string" && AGENT_CONFIG_ORIGINS.includes(value)) {
119
+ return value;
120
+ }
121
+ console.warn(
122
+ `[dcs-agent-widget] ignoring .dcs/site.yaml agent_config_origin=${JSON.stringify(raw)}; expected one of ${AGENT_CONFIG_ORIGINS.join(", ")}. The loader keeps the same-origin-first probe.`
123
+ );
124
+ return null;
125
+ }
107
126
  function dcsAgentWidgetLoaderTag(options) {
108
127
  const siteSlug = readSiteSlug(options.projectRoot);
109
128
  if (!siteSlug) return null;
129
+ const configOrigin = readAgentConfigOrigin(options.projectRoot);
110
130
  return {
111
131
  tag: "script",
112
- attrs: { "data-dcs-agent-loader": "" },
132
+ // The config-origin attribute only marks the served HTML, so audits and live
133
+ // proofs can read it. The behaviour itself is baked into the loader body.
134
+ attrs: configOrigin === "platform" ? { "data-dcs-agent-loader": "", "data-dcs-agent-config-origin": "platform" } : { "data-dcs-agent-loader": "" },
113
135
  children: buildAgentWidgetLoaderScript({
114
136
  siteSlug,
115
137
  apiBaseUrl: options.apiBaseUrl,
116
- cdnScriptUrl: options.cdnScriptUrl
138
+ cdnScriptUrl: options.cdnScriptUrl,
139
+ configOrigin: configOrigin ?? void 0
117
140
  }),
118
141
  injectTo: "head"
119
142
  };
@@ -285,6 +308,7 @@ function prerenderNavigationUrl(origin, routePath) {
285
308
  url.searchParams.set("dcs-no-telemetry", "");
286
309
  return url.toString();
287
310
  }
311
+ var BLOCKED_LOG_CAP = 1e3;
288
312
  var CONTENT_TYPES = {
289
313
  ".html": "text/html; charset=utf-8",
290
314
  ".js": "text/javascript; charset=utf-8",
@@ -306,10 +330,29 @@ var CONTENT_TYPES = {
306
330
  ".map": "application/json; charset=utf-8"
307
331
  };
308
332
  async function startStaticServer(outDir) {
333
+ let origin = "";
334
+ const blocked = [];
335
+ const refuse = (entry) => {
336
+ if (blocked.length < BLOCKED_LOG_CAP) blocked.push(entry);
337
+ };
309
338
  const server = http.createServer((req, res) => {
339
+ let url;
340
+ try {
341
+ url = new URL(req.url ?? "/", origin);
342
+ } catch {
343
+ res.writeHead(400, { Connection: "close" });
344
+ res.end();
345
+ return;
346
+ }
347
+ if (url.origin !== origin) {
348
+ refuse(`${req.method ?? "GET"} ${url.host}${url.pathname}`);
349
+ res.writeHead(403, { Connection: "close" });
350
+ res.end();
351
+ return;
352
+ }
310
353
  let pathname = "/";
311
354
  try {
312
- pathname = decodeURIComponent(new URL(req.url ?? "/", "http://127.0.0.1").pathname);
355
+ pathname = decodeURIComponent(url.pathname);
313
356
  } catch {
314
357
  pathname = "/";
315
358
  }
@@ -343,13 +386,19 @@ async function startStaticServer(outDir) {
343
386
  res.end(buf);
344
387
  });
345
388
  });
389
+ server.on("connect", (req, socket) => {
390
+ refuse(`CONNECT ${req.url ?? ""}`);
391
+ socket.destroy();
392
+ });
346
393
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
347
394
  const addr = server.address();
348
- const origin = `http://127.0.0.1:${addr.port}`;
395
+ origin = `http://127.0.0.1:${addr.port}`;
349
396
  return {
350
397
  origin,
398
+ blocked,
351
399
  close: () => new Promise((resolve) => {
352
400
  server.close(() => resolve());
401
+ server.closeAllConnections();
353
402
  })
354
403
  };
355
404
  }
@@ -379,29 +428,29 @@ async function createPlaywrightRenderer(options) {
379
428
  console.warn("[dcs-seo] body-prerender: playwright has no chromium export; skipping.");
380
429
  return null;
381
430
  }
431
+ const server = await startStaticServer(outDir);
382
432
  let browser;
383
433
  try {
384
- browser = await chromium.launch({ headless: true });
434
+ browser = await chromium.launch({ headless: true, proxy: { server: server.origin } });
385
435
  } catch (err) {
436
+ await server.close().catch(() => {
437
+ });
386
438
  console.warn(
387
439
  "[dcs-seo] body-prerender: failed to launch Chromium (run `npx playwright install chromium`); skipping body prerender:",
388
440
  err instanceof Error ? err.message : err
389
441
  );
390
442
  return null;
391
443
  }
392
- let staticServer;
393
444
  let context;
394
445
  try {
395
- staticServer = await startStaticServer(outDir);
396
446
  context = await browser.newContext({ reducedMotion: "reduce" });
397
447
  } catch (err) {
398
- await staticServer?.close().catch(() => {
399
- });
400
448
  await browser.close().catch(() => {
401
449
  });
450
+ await server.close().catch(() => {
451
+ });
402
452
  throw err;
403
453
  }
404
- const server = staticServer;
405
454
  const renderer = {
406
455
  async renderRoute(routePath) {
407
456
  const page = await context.newPage();
@@ -464,6 +513,7 @@ async function createPlaywrightRenderer(options) {
464
513
  let teardown = null;
465
514
  return {
466
515
  renderer,
516
+ blockedRequests: () => server.blocked.slice(),
467
517
  close() {
468
518
  teardown ??= (async () => {
469
519
  try {
@@ -1929,6 +1979,6 @@ function chainBuildEnd(...hooks) {
1929
1979
  };
1930
1980
  }
1931
1981
 
1932
- export { DCS_MOTION_TOKENS_CSS, DEFAULT_AGENT_API_BASE_URL, DEFAULT_AGENT_WIDGET_SCRIPT_URL, NoindexOrphanError, buildAgentWidgetLoaderScript, chainBuildEnd, collectNoindexMatchKeys, dcsAgentWidgetLoaderTag, dcsCdnBuildEnd, dcsCdnImagePlugin, dcsContentPlugin, dcsEditorPlugin, dcsMotionTokensStyleTag, dcsPreviewPlugin, dcsResponsiveImageLint, dcsSeoPlugin, emitSiteFiles, emitStaticSeoHtml, findFullSizeCdnImages, findOrphanNoindexEntries, isFullSizeCdnUrl, readSiteSlug, responsiveImagePlugin };
1982
+ export { AGENT_CONFIG_ORIGINS, DCS_MOTION_TOKENS_CSS, DEFAULT_AGENT_API_BASE_URL, DEFAULT_AGENT_WIDGET_SCRIPT_URL, NoindexOrphanError, buildAgentWidgetLoaderScript, chainBuildEnd, collectNoindexMatchKeys, dcsAgentWidgetLoaderTag, dcsCdnBuildEnd, dcsCdnImagePlugin, dcsContentPlugin, dcsEditorPlugin, dcsMotionTokensStyleTag, dcsPreviewPlugin, dcsResponsiveImageLint, dcsSeoPlugin, emitSiteFiles, emitStaticSeoHtml, findFullSizeCdnImages, findOrphanNoindexEntries, isFullSizeCdnUrl, readAgentConfigOrigin, readSiteSlug, responsiveImagePlugin };
1933
1983
  //# sourceMappingURL=index.js.map
1934
1984
  //# sourceMappingURL=index.js.map