@agimon-ai/po-build 0.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +96 -0
  3. package/dist/_virtual/_rolldown/runtime.cjs +1 -0
  4. package/dist/browserFile.cjs +1 -0
  5. package/dist/browserFile.d.mts +2 -0
  6. package/dist/browserFile.mjs +1 -0
  7. package/dist/constants/contributions.cjs +2 -0
  8. package/dist/constants/contributions.cjs.map +1 -0
  9. package/dist/constants/contributions.mjs +2 -0
  10. package/dist/constants/contributions.mjs.map +1 -0
  11. package/dist/constants/layout.cjs +2 -0
  12. package/dist/constants/layout.cjs.map +1 -0
  13. package/dist/constants/layout.d.mts +56 -0
  14. package/dist/constants/layout.d.mts.map +1 -0
  15. package/dist/constants/layout.mjs +2 -0
  16. package/dist/constants/layout.mjs.map +1 -0
  17. package/dist/index.cjs +1 -0
  18. package/dist/index.d.mts +17 -0
  19. package/dist/index.mjs +1 -0
  20. package/dist/services/browserFile/index.cjs +2 -0
  21. package/dist/services/browserFile/index.cjs.map +1 -0
  22. package/dist/services/browserFile/index.d.mts +22 -0
  23. package/dist/services/browserFile/index.d.mts.map +1 -0
  24. package/dist/services/browserFile/index.mjs +2 -0
  25. package/dist/services/browserFile/index.mjs.map +1 -0
  26. package/dist/services/filename/index.cjs +2 -0
  27. package/dist/services/filename/index.cjs.map +1 -0
  28. package/dist/services/filename/index.d.mts +29 -0
  29. package/dist/services/filename/index.d.mts.map +1 -0
  30. package/dist/services/filename/index.mjs +2 -0
  31. package/dist/services/filename/index.mjs.map +1 -0
  32. package/dist/services/generate/index.cjs +3 -0
  33. package/dist/services/generate/index.cjs.map +1 -0
  34. package/dist/services/generate/index.d.mts +15 -0
  35. package/dist/services/generate/index.d.mts.map +1 -0
  36. package/dist/services/generate/index.mjs +3 -0
  37. package/dist/services/generate/index.mjs.map +1 -0
  38. package/dist/services/generate/type.d.mts +28 -0
  39. package/dist/services/generate/type.d.mts.map +1 -0
  40. package/dist/services/identity/index.cjs +2 -0
  41. package/dist/services/identity/index.cjs.map +1 -0
  42. package/dist/services/identity/index.mjs +2 -0
  43. package/dist/services/identity/index.mjs.map +1 -0
  44. package/dist/services/renderClient/index.cjs +3 -0
  45. package/dist/services/renderClient/index.cjs.map +1 -0
  46. package/dist/services/renderClient/index.mjs +3 -0
  47. package/dist/services/renderClient/index.mjs.map +1 -0
  48. package/dist/services/renderEntry/index.cjs +7 -0
  49. package/dist/services/renderEntry/index.cjs.map +1 -0
  50. package/dist/services/renderEntry/index.d.mts +18 -0
  51. package/dist/services/renderEntry/index.d.mts.map +1 -0
  52. package/dist/services/renderEntry/index.mjs +7 -0
  53. package/dist/services/renderEntry/index.mjs.map +1 -0
  54. package/dist/services/renderEntry/type.d.mts +16 -0
  55. package/dist/services/renderEntry/type.d.mts.map +1 -0
  56. package/dist/services/renderMcpWidgets/index.cjs +3 -0
  57. package/dist/services/renderMcpWidgets/index.cjs.map +1 -0
  58. package/dist/services/renderMcpWidgets/index.mjs +3 -0
  59. package/dist/services/renderMcpWidgets/index.mjs.map +1 -0
  60. package/dist/services/resolveTarget/index.cjs +2 -0
  61. package/dist/services/resolveTarget/index.cjs.map +1 -0
  62. package/dist/services/resolveTarget/index.d.mts +18 -0
  63. package/dist/services/resolveTarget/index.d.mts.map +1 -0
  64. package/dist/services/resolveTarget/index.mjs +2 -0
  65. package/dist/services/resolveTarget/index.mjs.map +1 -0
  66. package/dist/services/resolveTarget/type.d.mts +30 -0
  67. package/dist/services/resolveTarget/type.d.mts.map +1 -0
  68. package/dist/services/scan/index.cjs +2 -0
  69. package/dist/services/scan/index.cjs.map +1 -0
  70. package/dist/services/scan/index.d.mts +8 -0
  71. package/dist/services/scan/index.d.mts.map +1 -0
  72. package/dist/services/scan/index.mjs +2 -0
  73. package/dist/services/scan/index.mjs.map +1 -0
  74. package/dist/services/scan/type.d.mts +25 -0
  75. package/dist/services/scan/type.d.mts.map +1 -0
  76. package/dist/services/segments/index.cjs +2 -0
  77. package/dist/services/segments/index.cjs.map +1 -0
  78. package/dist/services/segments/index.d.mts +26 -0
  79. package/dist/services/segments/index.d.mts.map +1 -0
  80. package/dist/services/segments/index.mjs +2 -0
  81. package/dist/services/segments/index.mjs.map +1 -0
  82. package/dist/services/syncManifest/index.cjs +2 -0
  83. package/dist/services/syncManifest/index.cjs.map +1 -0
  84. package/dist/services/syncManifest/index.d.mts +21 -0
  85. package/dist/services/syncManifest/index.d.mts.map +1 -0
  86. package/dist/services/syncManifest/index.mjs +2 -0
  87. package/dist/services/syncManifest/index.mjs.map +1 -0
  88. package/dist/services/syncManifest/type.d.mts +15 -0
  89. package/dist/services/syncManifest/type.d.mts.map +1 -0
  90. package/dist/services/tsdownPreset/index.cjs +2 -0
  91. package/dist/services/tsdownPreset/index.cjs.map +1 -0
  92. package/dist/services/tsdownPreset/index.d.mts +89 -0
  93. package/dist/services/tsdownPreset/index.d.mts.map +1 -0
  94. package/dist/services/tsdownPreset/index.mjs +2 -0
  95. package/dist/services/tsdownPreset/index.mjs.map +1 -0
  96. package/dist/services/unistylesBabel/index.cjs +2 -0
  97. package/dist/services/unistylesBabel/index.cjs.map +1 -0
  98. package/dist/services/unistylesBabel/index.d.mts +17 -0
  99. package/dist/services/unistylesBabel/index.d.mts.map +1 -0
  100. package/dist/services/unistylesBabel/index.mjs +2 -0
  101. package/dist/services/unistylesBabel/index.mjs.map +1 -0
  102. package/dist/services/unistylesBabel/type.d.mts +13 -0
  103. package/dist/services/unistylesBabel/type.d.mts.map +1 -0
  104. package/dist/services/writeGenerated/index.cjs +2 -0
  105. package/dist/services/writeGenerated/index.cjs.map +1 -0
  106. package/dist/services/writeGenerated/index.d.mts +23 -0
  107. package/dist/services/writeGenerated/index.d.mts.map +1 -0
  108. package/dist/services/writeGenerated/index.mjs +2 -0
  109. package/dist/services/writeGenerated/index.mjs.map +1 -0
  110. package/dist/tsdown.cjs +1 -0
  111. package/dist/tsdown.d.mts +3 -0
  112. package/dist/tsdown.mjs +1 -0
  113. package/dist/types/extensionGraph.d.mts +75 -0
  114. package/dist/types/extensionGraph.d.mts.map +1 -0
  115. package/package.json +72 -0
@@ -0,0 +1,2 @@
1
+ function e(e){return e.replace(/([a-z0-9])([A-Z])/gu,`$1-$2`).toLowerCase().replaceAll(`-`,`_`)}function t(e){return e.replace(/([a-z0-9])([A-Z])/gu,`$1-$2`).toLowerCase()}function n(e){return Object.entries(e).map(([e,t])=>Array.isArray(t)?`${e}: [${t.map(e=>`'${e}'`).join(`, `)}]`:`${e}: '${t}'`).join(`, `)}export{n as renderIdentity,t as toKebab,e as toSnake};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["toSnake","name","toKebab","renderIdentity","identity","key","value","item"],"sources":["../../../src/services/identity/index.ts"],"sourcesContent":["/**\n * What a path knows about a contribution's identity.\n *\n * The generator supplies these and the authored file is spread over the top,\n * so a file that states its own name or id always wins. That is what lets the\n * filename be the identity without taking the choice away.\n */\n\n/** `write-plan` and `writePlan` both become `write_plan`. */\nexport function toSnake(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/gu, '$1-$2')\n .toLowerCase()\n .replaceAll('-', '_');\n}\n\n/** `PlanPanel` becomes `plan-panel`; an already-kebab name is unchanged. */\nexport function toKebab(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();\n}\n\n/** One derived field and the literal it holds. */\nexport type Identity = Readonly<Record<string, string | readonly string[]>>;\n\n/** Renders an identity as object-literal members, ready to precede a spread. */\nexport function renderIdentity(identity: Identity): string {\n return Object.entries(identity)\n .map(([key, value]) =>\n Array.isArray(value)\n ? `${key}: [${value.map((item) => `'${item}'`).join(', ')}]`\n : `${key}: '${value as string}'`,\n )\n .join(', ');\n}\n"],"mappings":"AASA,SAAgBA,EAAQ,EAAsB,CAC5C,OAAOC,EACJ,QAAQ,sBAAuB,OAAO,CAAC,CACvC,YAAY,CAAC,CACb,WAAW,IAAK,GAAG,CACxB,CAGA,SAAgBC,EAAQ,EAAsB,CAC5C,OAAOD,EAAK,QAAQ,sBAAuB,OAAO,CAAC,CAAC,YAAY,CAClE,CAMA,SAAgBE,EAAe,EAA4B,CACzD,OAAO,OAAO,QAAQC,CAAQ,CAAC,CAC5B,KAAK,CAACC,EAAKC,KACV,MAAM,QAAQA,CAAK,EACf,GAAGD,EAAI,KAAKC,EAAM,IAAK,GAAS,IAAIC,EAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,GACxD,GAAGF,EAAI,KAAKC,EAAgB,EAClC,CAAC,CACA,KAAK,IAAI,CACd"}
@@ -0,0 +1,3 @@
1
+ require("../../constants/layout.cjs");const e=require("../identity/index.cjs");let t=require("node:path");const n=[`global`,`workspace`,`session`];function r(t,n){if(!n)return`api`;let r=e.toKebab(t).split(`-`).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``);return/^[A-Za-z_]/u.test(r)?r:`api${r}`}function i(e){let t=e.route[0];if(t!==void 0&&`literal`in t)return t.literal}function a(e){let t=/* @__PURE__ */ new Map;for(let n of e.entries){if(n.side!==`backend`||n.surface!==`api`||n.role!==`contribution`)continue;let e=i(n);if(e===void 0)continue;let r=t.get(e)??/* @__PURE__ */ new Set;r.add(n.scope),t.set(e,r)}let a=[...t.keys()].sort();return a.map(e=>{let i=t.get(e),o=n.findIndex(e=>i.has(e));return{basePath:e,scopes:n.slice(o),identifier:r(e,a.length>1)}})}function o(e){let n=t.posix.relative(e,`src/types/apiRoutes`);return n.startsWith(`.`)?n:`./${n}`}function s(e){let t=e.scopes.map(e=>`'${e}'`).join(`, `),n=e.identifier===`api`?``:` for the ${e.basePath} mount`;return[`/** Scopes the tree mounts '${e.basePath}' at${n}. */`,`export const ${e.identifier}Scopes = [${t}] as const;`,``,`export const ${e.identifier} = createApiClient(routes, {`,` scopes: ${e.identifier}Scopes,`,` basePath: '${e.basePath}',`,` transport: (input, init) => sealedTransport.fetch(input, init),`,` sessionAddress: sessionApiAddress,`,`});`,``]}function c(e,t){let n=a(e);if(n.length!==0)return`${[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';`,`import { sealedTransport } from '@agimon-ai/po-web-security/browser';`,``,`import routes from '${o(t.entryDir??`generated`)}';`,``,...n.flatMap(e=>s(e))].join(`
2
+ `).replace(/\n+$/u,``)}\n`}exports.renderApiClient=c;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["toKebab","posix","require_index","node_path","SCOPE_ORDER","identifierFor","multiple","camel","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","entryDir","renderMount","scopes","mount","suffix","renderApiClient","mounts","options"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\nfunction renderMount(mount: ClientMount): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ' transport: (input, init) => sealedTransport.fetch(input, init),',\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n"],"mappings":"0GAsBA,MAGMI,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAASC,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAACC,EAAU,MAAO,MACtB,IAAMC,EAAQP,EAAAA,QAAQQ,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,OAAQ,GAASC,EAAK,OAAS,CAAC,CAAC,CACjC,KAAK,EAAM,IAAWC,IAAU,EAAID,EAAOA,EAAK,EAAE,EAAE,YAAY,EAAIA,EAAK,MAAM,CAAC,CAAE,CAAC,CACnF,KAAK,EAAE,EACV,MAAO,cAAc,KAAKF,CAAK,EAAIA,EAAQ,MAAMA,GACnD,CAUA,SAASI,EAAc,E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A,EAAM,WAAW,SAC9B,gBAAgBA,EAAM,SAAS,IAC/B,oEACA,uCACA,MACA,EACF,CACF,CAQA,SAAgBE,EAAgB,EAAuB,EAA4C,CACjG,IAAMC,EAAShB,EAASE,CAAK,EAC7B,GAAIc,EAAO,SAAW,EAWtB,MAAO,GAAG,CARR,4DACA,+EACA,wEACA,GACA,uBAAuBR,EAAgBS,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAGD,EAAO,QAAS,GAAUL,EAAYE,CAAK,CAAC,CAEnC,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD"}
@@ -0,0 +1,3 @@
1
+ import"../../constants/layout.mjs";import{toKebab as e}from"../identity/index.mjs";import{posix as t}from"node:path";const n=[`global`,`workspace`,`session`];function r(t,n){if(!n)return`api`;let r=e(t).split(`-`).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``);return/^[A-Za-z_]/u.test(r)?r:`api${r}`}function i(e){let t=e.route[0];if(t!==void 0&&`literal`in t)return t.literal}function a(e){let t=/* @__PURE__ */ new Map;for(let n of e.entries){if(n.side!==`backend`||n.surface!==`api`||n.role!==`contribution`)continue;let e=i(n);if(e===void 0)continue;let r=t.get(e)??/* @__PURE__ */ new Set;r.add(n.scope),t.set(e,r)}let a=[...t.keys()].sort();return a.map(e=>{let i=t.get(e),o=n.findIndex(e=>i.has(e));return{basePath:e,scopes:n.slice(o),identifier:r(e,a.length>1)}})}function o(e){let n=t.relative(e,`src/types/apiRoutes`);return n.startsWith(`.`)?n:`./${n}`}function s(e){let t=e.scopes.map(e=>`'${e}'`).join(`, `),n=e.identifier===`api`?``:` for the ${e.basePath} mount`;return[`/** Scopes the tree mounts '${e.basePath}' at${n}. */`,`export const ${e.identifier}Scopes = [${t}] as const;`,``,`export const ${e.identifier} = createApiClient(routes, {`,` scopes: ${e.identifier}Scopes,`,` basePath: '${e.basePath}',`,` transport: (input, init) => sealedTransport.fetch(input, init),`,` sessionAddress: sessionApiAddress,`,`});`,``]}function c(e,t){let n=a(e);if(n.length!==0)return`${[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';`,`import { sealedTransport } from '@agimon-ai/po-web-security/browser';`,``,`import routes from '${o(t.entryDir??`generated`)}';`,``,...n.flatMap(e=>s(e))].join(`
2
+ `).replace(/\n+$/u,``)}\n`}export{c as renderApiClient};
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["SCOPE_ORDER","identifierFor","multiple","camel","toKebab","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","posix","entryDir","renderMount","scopes","mount","suffix","renderApiClient","mounts","options"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\nfunction renderMount(mount: ClientMount): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ' transport: (input, init) => sealedTransport.fetch(input, init),',\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n"],"mappings":"qHAsBA,MAGMA,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAASC,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAACC,EAAU,MAAO,MACtB,IAAMC,EAAQC,EAAQC,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,OAAQ,GAASC,EAAK,OAAS,CAAC,CAAC,CACjC,KAAK,EAAM,IAAWC,IAAU,EAAID,EAAOA,EAAK,EAAE,EAAE,YAAY,EAAIA,EAAK,MAAM,CAAC,CAAE,CAAC,CACnF,KAAK,EAAE,EACV,MAAO,cAAc,KAAKH,CAAK,EAAIA,EAAQ,MAAMA,GACnD,CAUA,SAASK,EAAc,EAA2C,CAChE,IAAMC,EAAQC,EAAM,MAAM,GAC1B,G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ACA,uCACA,MACA,EACF,CACF,CAQA,SAAgBE,EAAgB,EAAuB,EAA4C,CACjG,IAAMC,EAASjB,EAASE,CAAK,EAC7B,GAAIe,EAAO,SAAW,EAWtB,MAAO,GAAG,CARR,4DACA,+EACA,wEACA,GACA,uBAAuBT,EAAgBU,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAGD,EAAO,QAAS,GAAUL,EAAYE,CAAK,CAAC,CAEnC,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD"}
@@ -0,0 +1,7 @@
1
+ const e=require("../resolveTarget/index.cjs"),t=require("../identity/index.cjs");let n=require("node:path");const r=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,i=[`fileLinks`,`repositorySettingsPanel`,`start`],a={server:[`channels`],web:[],native:[],mcp:[]},o=[`services`],s=[`global`,`workspace`,`session`],c={server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function l(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
2
+ `)}function u(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
3
+ `)}function d(){return[`/* v8 ignore next -- generated normalization branch */`,`const defined = <T>(values: readonly (T | undefined)[]): T[] =>`,` values.filter((value): value is T => value !== undefined);`].join(`
4
+ `)}const f=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
5
+ `);function p(e,n){return n===void 0?{id:t.toKebab(e)}:{slot:n,id:t.toKebab(e)}}const m={tool:e=>({name:t.toSnake(e)}),command:e=>({name:t.toKebab(e)}),channel:e=>({frameType:t.toSnake(e)}),hook:e=>({event:t.toSnake(e)}),mode:e=>({name:t.toKebab(e)})},h={tool:e=>({tools:[t.toSnake(e)]}),channel:e=>({channel:t.toSnake(e)}),slot:(e,n)=>({slot:`${n.pluginId}.${t.toKebab(e)}`}),command:e=>({id:t.toKebab(e)}),tab:e=>({id:t.toKebab(e)}),template:e=>({id:t.toKebab(e)}),dock:e=>({id:t.toKebab(e)}),setting:e=>({id:t.toKebab(e)}),action:e=>({id:t.toKebab(e)}),mode:e=>({name:t.toKebab(e)}),"activity-group":e=>({name:t.toKebab(e)}),"selection-axis":e=>({name:t.toKebab(e)}),leader:(e,n)=>({id:`${n.pluginId}.${t.toKebab(e)}`})};function g(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e.isFrontendTarget(n)?a===`fill`?p(i.name,i.target):h[a]?.(i.name,r):m[a]?.(i.name)}function _(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function v(e,t){return _([e.entry.surface??`extra`,e.entry.name],t)}function y(e,t){let r=e.replace(/\.[^.]+$/u,``),i=n.posix.relative(t,r);return i.startsWith(`.`)?i:`./${i}`}function b(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function x(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=v(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:g(r,e.target,t),mcpWidget:a}})}const S={global:0,workspace:1,session:2};function C(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function w(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function T(e,t,n){let r=n;for(let n of e)S[n.entry.scope]<=S[t]&&(r=n.context);return r}function E(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function D(n,r,i){if(o.includes(n.contribution.field))return`${n.identifier}(${r})`;let s=e.isFrontendTarget(i)?n.identifier:`at(${n.identifier}, ${r})`,c=a[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return s;if(n.identity===void 0)return c?n.identifier:s;let l=t.renderIdentity(n.identity);if(c)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${s})`;return n.mcpWidget===void 0?u:`withWidget(${b(n.mcpWidget)}, ${u})`}function O(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function k(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${c[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function A(e,t,n,r){let a=/* @__PURE__ */ new Map;for(let t of e){let e=a.get(t.contribution.field);e===void 0?a.set(t.contribution.field,[t]):e.push(t)}let o=[];for(let e of[...a.keys()].sort()){let s=a.get(e);if(i.includes(e)){let i=s[0];if(i){let a=D(i,n(i),r);o.push(`${t}${k(e,`${e}: ${a},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${b(e.mcpWidget)}, tool))`}`:D(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;o.push(`${t}${k(e,`${e}: ${l},`,r)}`)}return o}function j(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): DoomServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function M(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${y(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`)]}function N(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
+ `)}function P(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(l()),e.some(e=>e.includes(`many(`))&&t.push(u()),e.some(e=>e.includes(`defined(`))&&t.push(d()),e.some(e=>e.includes(`via(`))&&t.push(f),t.length>0?[...t,``]:[]}function F(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function I(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${F(n)} => ({`,...i,`${r}}),`]:[`${a}${F([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function L(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function R(e,t){let n=x(e,t),i=E(e.escapeHatches),a=C(e.roots),o=[],c=!1;for(let[e,t]of s.entries()){let r=n.filter(t=>s.indexOf(t.contribution.entry.scope)<=e),l=i.filter(t=>s.indexOf(t.entry.scope)<=e),u=a.filter(t=>s.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...j(A(r,` `,e=>T(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...l.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(c=!0);let p=I(w(u,`context`,f),L(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return N([r,O(o),...a.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...c?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...M(n,i,a,t.entryDir),``,...P(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...a.length?[` providerOverrides: composeServerProviderOverrides(${a.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function z(e,t){let n=x(e,t),i=A(n,` `,()=>`context`,`mcp`);return N([r,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...M(n,[],[],t.entryDir),``,...P(i),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const B={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function V(e,t,n){let i=B[n],a=x(e,t),o=E(e.escapeHatches),l=[];for(let e of s){let t=a.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),i=[...A(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];i.length!==0&&l.push(` ${e}: {`,...i,` },`)}let u=l.some(e=>e.includes(`get `))?`${i.define}, type ${c[n]}`:i.define;return N([r,`import { ${u} } from '${i.module}';`,``,...M(a,o,[],t.entryDir),``,...P(l),`export const ${i.exportName} = ${i.define}({`,` id: '${t.pluginId}',`,...l,`});`,``])}function H(e,t){return V(e,t,`web`)}function U(e,t){return V(e,t,`native`)}exports.renderMcpEntry=z,exports.renderNativeEntry=U,exports.renderServerEntry=R,exports.renderWebEntry=H;
7
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["toKebab","toSnake","isFrontendTarget","posix","renderIdentity","require_index","require_index$1","node_path","HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","name","BACKEND_IDENTITY","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => DoomHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'DoomServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'DoomMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type DoomServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): DoomServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies DoomMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"4GAQA,MAAMQ,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,0BACR,IAAK,yBAGL,OAAQ,yBACR,IAAK,sBACP,EAOA,SAASC,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAASC,GAAuB,CAC9B,MAAO,CACL,6DACA,kGACA,kGACA,iEACA,IACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAASC,GAA0B,CACjC,MAAO,CACL,yDACA,kEACA,8DACF,CAAC,CAAC,KAAK;CAAI,CACb,CAgBA,MAAMC,EAAkB,CACtB,2EACA,mFACF,CAAC,CAAC,KAAK;CAAI,EAWX,SAASC,EAAa,EAAc,EAAsC,CAExE,OADIC,IAAW,IAAA,GAAkB,CAAE,GAAInB,EAAAA,QAAQoB,CAAI,CAAE,EAC9C,CAAE,KAAMD,EAAQ,GAAInB,EAAAA,QAAQoB,CAAI,CAAE,CAC3C,CAGA,MAAMC,EAAyE,CAC7E,KAAO,IAAU,CAAE,KAAMpB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M,OAAO,IACnD,UAAU7F,EAAQ,SAAS,IAC3B,GAAGiD,EACH,MACA,EACF,CAAC,CACH,CAGA,SAAgB8C,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBtE,EAAYtB,EAAS,KAAK,CACvD,CAGA,SAAgBgG,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBtE,EAAYtB,EAAS,QAAQ,CAC1D"}
@@ -0,0 +1,18 @@
1
+ import { TargetResolution } from "../resolveTarget/type.mjs";
2
+ import { RenderOptions } from "./type.mjs";
3
+ //#region src/services/renderEntry/index.d.ts
4
+ /**
5
+ * The headless entry, one declaration per scope.
6
+ *
7
+ * Contributions cascade downward here because the server does not do it
8
+ * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the
9
+ * scopes above it. Emitting the repetition is what lets an author declare a
10
+ * channel once and have it mount at all three scopes.
11
+ */
12
+ export declare function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string;
13
+ /** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */
14
+ export declare function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string;
15
+ /** The native app entry, built from `.native` files only. */
16
+ export declare function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string;
17
+ //#endregion
18
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/renderEntry/index.ts"],"mappings":";;;;;;;;;;;wBAifgB,kBAAkB,YAAY,kBAAkB,SAAS;;wBA4IzD,eAAe,YAAY,kBAAkB,SAAS;;wBAKtD,kBAAkB,YAAY,kBAAkB,SAAS"}
@@ -0,0 +1,7 @@
1
+ import{isFrontendTarget as e}from"../resolveTarget/index.mjs";import{renderIdentity as t,toKebab as n,toSnake as r}from"../identity/index.mjs";import{posix as i}from"node:path";const a=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,o=[`fileLinks`,`repositorySettingsPanel`,`start`],s={server:[`channels`],web:[],native:[],mcp:[]},c=[`services`],l=[`global`,`workspace`,`session`],u={server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function d(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
2
+ `)}function f(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
3
+ `)}function p(){return[`/* v8 ignore next -- generated normalization branch */`,`const defined = <T>(values: readonly (T | undefined)[]): T[] =>`,` values.filter((value): value is T => value !== undefined);`].join(`
4
+ `)}const m=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
5
+ `);function h(e,t){return t===void 0?{id:n(e)}:{slot:t,id:n(e)}}const g={tool:e=>({name:r(e)}),command:e=>({name:n(e)}),channel:e=>({frameType:r(e)}),hook:e=>({event:r(e)}),mode:e=>({name:n(e)})},_={tool:e=>({tools:[r(e)]}),channel:e=>({channel:r(e)}),slot:(e,t)=>({slot:`${t.pluginId}.${n(e)}`}),command:e=>({id:n(e)}),tab:e=>({id:n(e)}),template:e=>({id:n(e)}),dock:e=>({id:n(e)}),setting:e=>({id:n(e)}),action:e=>({id:n(e)}),mode:e=>({name:n(e)}),"activity-group":e=>({name:n(e)}),"selection-axis":e=>({name:n(e)}),leader:(e,t)=>({id:`${t.pluginId}.${n(e)}`})};function v(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e(n)?a===`fill`?h(i.name,i.target):_[a]?.(i.name,r):g[a]?.(i.name)}function y(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function b(e,t){return y([e.entry.surface??`extra`,e.entry.name],t)}function x(e,t){let n=e.replace(/\.[^.]+$/u,``),r=i.relative(t,n);return r.startsWith(`.`)?r:`./${r}`}function S(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function C(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=b(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:v(r,e.target,t),mcpWidget:a}})}const w={global:0,workspace:1,session:2};function T(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function E(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function D(e,t,n){let r=n;for(let n of e)w[n.entry.scope]<=w[t]&&(r=n.context);return r}function O(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function k(n,r,i){if(c.includes(n.contribution.field))return`${n.identifier}(${r})`;let a=e(i)?n.identifier:`at(${n.identifier}, ${r})`,o=s[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return a;if(n.identity===void 0)return o?n.identifier:a;let l=t(n.identity);if(o)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${a})`;return n.mcpWidget===void 0?u:`withWidget(${S(n.mcpWidget)}, ${u})`}function A(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function j(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${u[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function M(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.contribution.field);e===void 0?i.set(t.contribution.field,[t]):e.push(t)}let a=[];for(let e of[...i.keys()].sort()){let s=i.get(e);if(o.includes(e)){let i=s[0];if(i){let o=k(i,n(i),r);a.push(`${t}${j(e,`${e}: ${o},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${S(e.mcpWidget)}, tool))`}`:k(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;a.push(`${t}${j(e,`${e}: ${l},`,r)}`)}return a}function N(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): DoomServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function P(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${x(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`)]}function F(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
+ `)}function I(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(d()),e.some(e=>e.includes(`many(`))&&t.push(f()),e.some(e=>e.includes(`defined(`))&&t.push(p()),e.some(e=>e.includes(`via(`))&&t.push(m),t.length>0?[...t,``]:[]}function L(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function R(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${L(n)} => ({`,...i,`${r}}),`]:[`${a}${L([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function z(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function B(e,t){let n=C(e,t),r=O(e.escapeHatches),i=T(e.roots),o=[],s=!1;for(let[e,t]of l.entries()){let a=n.filter(t=>l.indexOf(t.contribution.entry.scope)<=e),c=r.filter(t=>l.indexOf(t.entry.scope)<=e),u=i.filter(t=>l.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...N(M(a,` `,e=>D(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...c.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(s=!0);let p=R(E(u,`context`,f),z(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return F([a,A(o),...i.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...s?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...P(n,r,i,t.entryDir),``,...I(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...i.length?[` providerOverrides: composeServerProviderOverrides(${i.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function V(e,t){let n=C(e,t),r=M(n,` `,()=>`context`,`mcp`);return F([a,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...P(n,[],[],t.entryDir),``,...I(r),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const H={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function U(e,t,n){let r=H[n],i=C(e,t),o=O(e.escapeHatches),s=[];for(let e of l){let t=i.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),a=[...M(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];a.length!==0&&s.push(` ${e}: {`,...a,` },`)}let c=s.some(e=>e.includes(`get `))?`${r.define}, type ${u[n]}`:r.define;return F([a,`import { ${c} } from '${r.module}';`,``,...P(i,o,[],t.entryDir),``,...I(s),`export const ${r.exportName} = ${r.define}({`,` id: '${t.pluginId}',`,...s,`});`,``])}function W(e,t){return U(e,t,`web`)}function G(e,t){return U(e,t,`native`)}export{V as renderMcpEntry,G as renderNativeEntry,B as renderServerEntry,W as renderWebEntry};
7
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","toKebab","name","BACKEND_IDENTITY","toSnake","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","isFrontendTarget","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","posix","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","renderIdentity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => DoomHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'DoomServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'DoomMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type DoomServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): DoomServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies DoomMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"iLAQA,MAAMA,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,0BACR,IAAK,yBAGL,OAAQ,yBACR,IAAK,sBACP,EAOA,SAASC,GAAmB,CAC1B,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K,SAAS,MAAM,CAAC,EACrD,GAAG0D,EAAM,OAAO,SAAS5G,EAAmBM,KAC5CsG,EAAM,OACV,OAAOrB,EAAQ,CACb5F,EACA,YAAYkH,EAAM,WAAWD,EAAM,OAAO,IAC1C,GACA,GAAG1B,EAAWZ,EAAUe,EAAS,CAAC,EAAGzE,EAAQ,QAAQ,EACrD,GACA,GAAG6E,EAAYzB,CAAM,EACrB,gBAAgB4C,EAAM,WAAW,KAAKA,EAAM,OAAO,IACnD,UAAUhG,EAAQ,SAAS,IAC3B,GAAGoD,EACH,MACA,EACF,CAAC,CACH,CAGA,SAAgB8C,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBvE,EAAYxB,EAAS,KAAK,CACvD,CAGA,SAAgBmG,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBvE,EAAYxB,EAAS,QAAQ,CAC1D"}
@@ -0,0 +1,16 @@
1
+ //#region src/services/renderEntry/type.d.ts
2
+ /** What the renderers need beyond the resolved contributions themselves. */
3
+ export interface RenderOptions {
4
+ /** The package's npm name, used as the extension and facet name. */
5
+ readonly packageName: string;
6
+ /** The cockpit plugin id. */
7
+ readonly pluginId: string;
8
+ /** Routing root, package-relative. */
9
+ readonly root: string;
10
+ /** Where the generated entry is written, package-relative, so its imports can be made relative to it. */
11
+ readonly entryDir: string;
12
+ /** Backend declaration path to its package-owned browser widget key. */
13
+ readonly mcpWidgets?: Readonly<Record<string, string>>;
14
+ }
15
+ //#endregion
16
+ //# sourceMappingURL=type.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.mts","names":[],"sources":["../../../src/services/renderEntry/type.ts"],"mappings":";;iBACiB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA,aAAa,SAAS"}
@@ -0,0 +1,3 @@
1
+ const e=require("../identity/index.cjs");let t=require("node:path");function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e.toSnake(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e.toSnake(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.posix.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {`,...s,`};`,``].join(`
2
+ `)}}exports.renderMcpWidgets=n;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["toSnake","posix","require_index","node_path","renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","key","packageName","tools","candidate","relative","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"oEAMA,SAAgBI,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IAAMC,EAAuC,CAAC,EACxCC,EAAoB,CAAC,EACrBC,EAAoB,CAAC,EACrBC,kBAAQ,IAAI,IACZC,EAAUC,EAAM,QACnB,OAAQ,GAAUC,EAAM,OAAS,YAAcA,EAAM,WAAa,OAASA,EAAM,UAAY,MAAM,CAAC,CACpG,MAAM,EAAM,IAAUC,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC5D,IAAK,GAAM,CAACC,EAAOH,KAAUF,EAAQ,QAAQ,EAAG,CAC9C,IAAMM,EAAOf,EAAAA,QAAQW,EAAM,IAAI,EACzBK,EAAM,GAAGC,EAAY,GAAGF,IAC9B,GAAIP,EAAM,IAAIQ,CAAG,EAAG,MAAU,MAAM,yBAAyBA,EAAI,EAAE,EACnE,IAAME,EAAQR,EAAM,QAAQ,OACzB,GACCS,EAAU,OAAS,WACnBA,EAAU,WAAa,OACvBA,EAAU,UAAY,QACtBnB,EAAAA,QAAQmB,EAAU,IAAI,IAAMJ,GAC5B,KAAK,UAAUI,EAAU,KAAK,IAAM,KAAK,UAAUR,EAAM,KAAK,CAClE,EACA,GAAIO,EAAM,SAAW,EACnB,MAAU,MAAM,eAAeP,EAAM,KAAK,kDAAkD,EAC9FH,EAAM,IAAIQ,CAAG,EACb,EAAaE,EAAM,EAAE,CAAE,MAAQF,EAC/B,IAAMI,EAAWnB,EAAAA,MAAM,SAASoB,EAAUV,EAAM,KAAK,QAAQ,YAAa,EAAE,CAAC,EAC7EL,EAAQ,KACN,gBAAgBQ,EAAM,QAAQ,KAAK,UAAUM,EAAS,WAAW,GAAG,EAAIA,EAAW,KAAKA,GAAU,EAAE,EACtG,EACAb,EAAQ,KAAK,KAAK,KAAK,UAAUS,CAAG,EAAE,UAAUF,EAAM,EAAE,CAC1D,CACA,MAAO,CACL,eACA,MAAO,CAAC,GAAGN,CAAK,EAChB,OACEC,EAAQ,SAAW,EACf,IAAA,GACA,CACE,4DACA,8CACA,0EACA,GAAGH,EACH,GACA,wFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
@@ -0,0 +1,3 @@
1
+ import{toSnake as e}from"../identity/index.mjs";import{posix as t}from"node:path";function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {`,...s,`};`,``].join(`
2
+ `)}}export{n as renderMcpWidgets};
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","toSnake","key","packageName","tools","candidate","relative","posix","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"kFAMA,SAAgBA,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IAAMC,EAAuC,CAAC,EACxCC,EAAoB,CAAC,EACrBC,EAAoB,CAAC,EACrBC,kBAAQ,IAAI,IACZC,EAAUC,EAAM,QACnB,OAAQ,GAAUC,EAAM,OAAS,YAAcA,EAAM,WAAa,OAASA,EAAM,UAAY,MAAM,CAAC,CACpG,MAAM,EAAM,IAAUC,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC5D,IAAK,GAAM,CAACC,EAAOH,KAAUF,EAAQ,QAAQ,EAAG,CAC9C,IAAMM,EAAOC,EAAQL,EAAM,IAAI,EACzBM,EAAM,GAAGC,EAAY,GAAGH,IAC9B,GAAIP,EAAM,IAAIS,CAAG,EAAG,MAAU,MAAM,yBAAyBA,EAAI,EAAE,EACnE,IAAME,EAAQT,EAAM,QAAQ,OACzB,GACCU,EAAU,OAAS,WACnBA,EAAU,WAAa,OACvBA,EAAU,UAAY,QACtBJ,EAAQI,EAAU,IAAI,IAAML,GAC5B,KAAK,UAAUK,EAAU,KAAK,IAAM,KAAK,UAAUT,EAAM,KAAK,CAClE,EACA,GAAIQ,EAAM,SAAW,EACnB,MAAU,MAAM,eAAeR,EAAM,KAAK,kDAAkD,EAC9FH,EAAM,IAAIS,CAAG,EACb,EAAaE,EAAM,EAAE,CAAE,MAAQF,EAC/B,IAAMI,EAAWC,EAAM,SAASC,EAAUZ,EAAM,KAAK,QAAQ,YAAa,EAAE,CAAC,EAC7EL,EAAQ,KACN,gBAAgBQ,EAAM,QAAQ,KAAK,UAAUO,EAAS,WAAW,GAAG,EAAIA,EAAW,KAAKA,GAAU,EAAE,EACtG,EACAd,EAAQ,KAAK,KAAK,KAAK,UAAUU,CAAG,EAAE,UAAUH,EAAM,EAAE,CAC1D,CACA,MAAO,CACL,eACA,MAAO,CAAC,GAAGN,CAAK,EAChB,OACEC,EAAQ,SAAW,EACf,IAAA,GACA,CACE,4DACA,8CACA,0EACA,GAAGH,EACH,GACA,wFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
@@ -0,0 +1,2 @@
1
+ require("../../constants/layout.cjs");const e=require("../../constants/contributions.cjs"),t={global:0,workspace:1,session:2};function n(e){return e===`web`||e===`native`}function r(e,t){return n(t)?e.side===`frontend`:e.side===`backend`}function i(e,t){return t===`mcp`||t===`native`?e.platform===t:e.platform===void 0||e.platform===t}const a={server:{backend:e.SERVER_FIELDS,frontend:{}},web:{backend:{},frontend:e.WEB_FIELDS},native:{backend:{},frontend:e.NATIVE_FIELDS},mcp:{backend:e.MCP_FIELDS,frontend:{}}};function o(e){let t=e.gates.map(e=>`${e.kind}:${e.id}`).join(`/`),n=e.route.map(e=>`literal`in e?e.literal:`[${e.param.name}]`).join(`/`);return[e.side,e.scope,t,e.surface??``,n,e.name,e.target??``].join(`|`)}function s(e,t,n){return n===void 0?t:e[n]??t}function c(t,r){let i=t.surface;if(i===void 0)return;let o=a[r][t.side][i];if(o!==void 0&&o!==``&&!(n(r)&&i===`lifecycle`&&t.name!==`start`))return n(r)&&i===`setting`?s(e.SETTING_FIELDS,o,t.target):r===`web`&&i===`action`?s(e.ACTION_FIELDS,o,t.target):o}function l(e,n){let a=[],s=[],l=[],u=/* @__PURE__ */ new Map;for(let t of e.entries){if(!r(t,n)||!i(t,n))continue;if(t.role===`escape-hatch`){s.push(t);continue}if(t.role===`root`){if(t.side===`frontend`){a.push({path:t.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}l.push(t);continue}let e=o(t),c=u.get(e);if(c===void 0){u.set(e,t);continue}if(c.platform===t.platform){a.push({path:t.file,message:`duplicates ${c.file} for ${n}; the first one wins`});continue}t.platform!==void 0&&u.set(e,t)}let d=[];for(let e of u.values()){let t=c(e,n);t!==void 0&&d.push({entry:e,field:t})}return{target:n,contributions:d,escapeHatches:s,roots:l.sort((e,n)=>t[e.scope]-t[n.scope]),notices:a}}exports.isFrontendTarget=n,exports.resolveTarget=l;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["SERVER_FIELDS","WEB_FIELDS","NATIVE_FIELDS","MCP_FIELDS","SETTING_FIELDS","ACTION_FIELDS","require_contributions","SCOPE_DEPTH","isFrontendTarget","target","drawsFrom","entry","servesPlatform","FIELDS_OF","logicalKey","gates","gate","route","segment","variantField","entryTarget","fallback","table","fieldFor","surface","declared","resolveTarget","notices","escapeHatches","roots","winners","graph","key","held","contributions","field","left","right"],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n MCP_FIELDS,\n NATIVE_FIELDS,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport { NATIVE_PLATFORM } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionNotice, ExtensionSide } from '../../types/extensionGraph';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from './type';\n\n/** Nesting order, so roots compose outermost first. */\nconst SCOPE_DEPTH: Readonly<Record<string, number>> = { global: 0, workspace: 1, session: 2 };\n\n/** Whether a host draws presentation: the cockpit and the native app do, the server and MCP hosts run logic. */\nexport function isFrontendTarget(target: BuildTarget): target is FrontendTarget {\n return target === 'web' || target === NATIVE_PLATFORM;\n}\n\n/** Which side a host reads. */\nfunction drawsFrom(entry: ExtensionEntry, target: BuildTarget): boolean {\n return isFrontendTarget(target) ? entry.side === 'frontend' : entry.side === 'backend';\n}\n\n/**\n * Whether a file's platform suffix lets it reach a host.\n *\n * MCP and native take only files that name them: an unsuffixed backend file may\n * touch the whole server, and an unsuffixed frontend file may touch the DOM.\n * The server and the cockpit still accept an unsuffixed sibling as a fallback.\n */\nfunction servesPlatform(entry: ExtensionEntry, target: BuildTarget): boolean {\n if (target === 'mcp' || target === NATIVE_PLATFORM) return entry.platform === target;\n return entry.platform === undefined || entry.platform === target;\n}\n\nconst FIELDS_OF: Readonly<Record<BuildTarget, Readonly<Record<ExtensionSide, Readonly<Record<string, string>>>>>> = {\n server: { backend: SERVER_FIELDS, frontend: {} },\n web: { backend: {}, frontend: WEB_FIELDS },\n native: { backend: {}, frontend: NATIVE_FIELDS },\n mcp: { backend: MCP_FIELDS, frontend: {} },\n};\n\n/** Everything but the platform: two files sharing this are the same contribution. */\nfunction logicalKey(entry: ExtensionEntry): string {\n const gates = entry.gates.map((gate) => `${gate.kind}:${gate.id}`).join('/');\n const route = entry.route\n .map((segment) => ('literal' in segment ? segment.literal : `[${segment.param.name}]`))\n .join('/');\n // The side is part of it, so a tool's logic and its cockpit renderer never\n // look like one contribution overriding the other.\n return [entry.side, entry.scope, gates, entry.surface ?? '', route, entry.name, entry.target ?? ''].join('|');\n}\n\n/** Resolves the field for a surface whose filename target picks between two shapes. */\nfunction variantField(\n table: Readonly<Record<string, string>>,\n fallback: string,\n entryTarget: string | undefined,\n): string {\n if (entryTarget === undefined) return fallback;\n return table[entryTarget] ?? fallback;\n}\n\nfunction fieldFor(entry: ExtensionEntry, target: BuildTarget): string | undefined {\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n const declared = FIELDS_OF[target][entry.side][surface];\n if (declared === undefined || declared === NOT_A_CONTRIBUTION) return undefined;\n\n if (isFrontendTarget(target) && surface === 'lifecycle' && entry.name !== 'start') return undefined;\n if (isFrontendTarget(target) && surface === 'setting') return variantField(SETTING_FIELDS, declared, entry.target);\n if (target === 'web' && surface === 'action') return variantField(ACTION_FIELDS, declared, entry.target);\n return declared;\n}\n\n/**\n * Picks the winning file per logical contribution for one host.\n *\n * Metro and Expo semantics: a file naming this platform replaces a sibling\n * that names none, and a file naming none serves the server or the cockpit\n * when it has no more specific sibling. The scan reports the unnamed one, so\n * this is a fallback rather than a supported way to author. MCP and native\n * have no fallback at all: they read only the files that name them. Two files\n * naming the same platform for the same contribution is an authoring mistake,\n * so the first wins and the second becomes a notice rather than silently\n * disappearing.\n */\nexport function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution {\n const notices: ExtensionNotice[] = [];\n const escapeHatches: ExtensionEntry[] = [];\n const roots: ExtensionEntry[] = [];\n const winners = new Map<string, ExtensionEntry>();\n\n for (const entry of graph.entries) {\n if (!drawsFrom(entry, target)) continue;\n if (!servesPlatform(entry, target)) continue;\n if (entry.role === 'escape-hatch') {\n escapeHatches.push(entry);\n continue;\n }\n\n if (entry.role === 'root') {\n // Backend only. A root is constructed from a mount context, and the\n // cockpit has none: it builds its plugin definition as data and starts\n // it separately, so there is nothing for a frontend root to receive.\n if (entry.side === 'frontend') {\n notices.push({ path: entry.file, message: 'a scope root is a backend file; the cockpit has no mount context' });\n continue;\n }\n roots.push(entry);\n continue;\n }\n\n const key = logicalKey(entry);\n const held = winners.get(key);\n if (held === undefined) {\n winners.set(key, entry);\n continue;\n }\n if (held.platform === entry.platform) {\n notices.push({ path: entry.file, message: `duplicates ${held.file} for ${target}; the first one wins` });\n continue;\n }\n // A platform file always beats the unsuffixed sibling it overrides.\n if (entry.platform !== undefined) winners.set(key, entry);\n }\n\n const contributions: ResolvedContribution[] = [];\n for (const entry of winners.values()) {\n const field = fieldFor(entry, target);\n if (field === undefined) continue;\n contributions.push({ entry, field });\n }\n\n return {\n target,\n contributions,\n escapeHatches,\n roots: roots.sort((left, right) => SCOPE_DEPTH[left.scope] - SCOPE_DEPTH[right.scope]),\n notices,\n };\n}\n"],"mappings":"2FAcMO,EAAgD,CAAE,OAAQ,EAAG,UAAW,EAAG,QAAS,CAAE,EAG5F,SAAgBC,EAAiB,EAA+C,CAC9E,OAAOC,IAAW,OAASA,IAAA,QAC7B,CAGA,SAASC,EAAU,EAAuB,EAA8B,CACtE,OAAOF,EAAiBC,CAAM,EAAIE,EAAM,OAAS,WAAaA,EAAM,OAAS,SAC/E,CASA,SAASC,EAAe,EAAuB,EAA8B,CAE3E,OADIH,IAAW,OAASA,IAAA,SAAmCE,EAAM,WAAaF,EACvEE,EAAM,WAAa,IAAA,IAAaA,EAAM,WAAaF,CAC5D,CAEA,MAAMI,EAA8G,CAClH,OAAQ,CAAE,QAASb,EAAAA,cAAe,SAAU,CAAC,CAAE,EAC/C,IAAK,CAAE,QAAS,CAAC,EAAG,SAAUC,EAAAA,UAAW,EACzC,OAAQ,CAAE,QAAS,CAAC,EAAG,SAAUC,EAAAA,aAAc,EAC/C,IAAK,CAAE,QAASC,EAAAA,WAAY,SAAU,CAAC,CAAE,CAC3C,EAGA,SAASW,EAAW,EAA+B,CACjD,IAAMC,EAAQJ,EAAM,MAAM,IAAK,GAAS,GAAGK,EAAK,KAAK,GAAGA,EAAK,IAAI,CAAC,CAAC,KAAK,GAAG,EACrEC,EAAQN,EAAM,MACjB,IAAK,GAAa,YAAaO,EAAUA,EAAQ,QAAU,IAAIA,EAAQ,MAAM,KAAK,EAAG,CAAC,CACtF,KAAK,GAAG,EAGX,MAAO,CAACP,EAAM,KAAMA,EAAM,MAAOI,EAAOJ,EAAM,SAAW,GAAIM,EAAON,EAAM,KAAMA,EAAM,QAAU,EAAE,CAAC,CAAC,KAAK,GAAG,CAC9G,CAGA,SAASQ,EACP,EACA,EACA,EACQ,CAER,O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,cAAcsB,EAAK,KAAK,OAAOxB,EAAO,qBAAsB,CAAC,EACvG,QACF,CAEIE,EAAM,WAAa,IAAA,IAAWmB,EAAQ,IAAIE,EAAKrB,CAAK,CAC1D,CAEA,IAAMuB,EAAwC,CAAC,EAC/C,IAAK,IAAMvB,KAASmB,EAAQ,OAAO,EAAG,CACpC,IAAMK,EAAQZ,EAASZ,EAAOF,CAAM,EAChC0B,IAAU,IAAA,IACdD,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,gBACA,gBACA,MAAOL,EAAM,MAAM,EAAM,IAAUtB,EAAY6B,EAAK,OAAS7B,EAAY8B,EAAM,MAAM,EACrF,SACF,CACF"}
@@ -0,0 +1,18 @@
1
+ import { ExtensionGraph } from "../../types/extensionGraph.mjs";
2
+ import { BuildTarget, TargetResolution } from "./type.mjs";
3
+ //#region src/services/resolveTarget/index.d.ts
4
+ /**
5
+ * Picks the winning file per logical contribution for one host.
6
+ *
7
+ * Metro and Expo semantics: a file naming this platform replaces a sibling
8
+ * that names none, and a file naming none serves the server or the cockpit
9
+ * when it has no more specific sibling. The scan reports the unnamed one, so
10
+ * this is a fallback rather than a supported way to author. MCP and native
11
+ * have no fallback at all: they read only the files that name them. Two files
12
+ * naming the same platform for the same contribution is an authoring mistake,
13
+ * so the first wins and the second becomes a notice rather than silently
14
+ * disappearing.
15
+ */
16
+ export declare function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution;
17
+ //#endregion
18
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/resolveTarget/index.ts"],"mappings":";;;;;;;;;;;;;;;wBA2FgB,cAAc,OAAO,gBAAgB,QAAQ,cAAc"}
@@ -0,0 +1,2 @@
1
+ import"../../constants/layout.mjs";import{ACTION_FIELDS as e,MCP_FIELDS as t,NATIVE_FIELDS as n,SERVER_FIELDS as r,SETTING_FIELDS as i,WEB_FIELDS as a}from"../../constants/contributions.mjs";const o={global:0,workspace:1,session:2};function s(e){return e===`web`||e===`native`}function c(e,t){return s(t)?e.side===`frontend`:e.side===`backend`}function l(e,t){return t===`mcp`||t===`native`?e.platform===t:e.platform===void 0||e.platform===t}const u={server:{backend:r,frontend:{}},web:{backend:{},frontend:a},native:{backend:{},frontend:n},mcp:{backend:t,frontend:{}}};function d(e){let t=e.gates.map(e=>`${e.kind}:${e.id}`).join(`/`),n=e.route.map(e=>`literal`in e?e.literal:`[${e.param.name}]`).join(`/`);return[e.side,e.scope,t,e.surface??``,n,e.name,e.target??``].join(`|`)}function f(e,t,n){return n===void 0?t:e[n]??t}function p(t,n){let r=t.surface;if(r===void 0)return;let a=u[n][t.side][r];if(a!==void 0&&a!==``&&!(s(n)&&r===`lifecycle`&&t.name!==`start`))return s(n)&&r===`setting`?f(i,a,t.target):n===`web`&&r===`action`?f(e,a,t.target):a}function m(e,t){let n=[],r=[],i=[],a=/* @__PURE__ */ new Map;for(let o of e.entries){if(!c(o,t)||!l(o,t))continue;if(o.role===`escape-hatch`){r.push(o);continue}if(o.role===`root`){if(o.side===`frontend`){n.push({path:o.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}i.push(o);continue}let e=d(o),s=a.get(e);if(s===void 0){a.set(e,o);continue}if(s.platform===o.platform){n.push({path:o.file,message:`duplicates ${s.file} for ${t}; the first one wins`});continue}o.platform!==void 0&&a.set(e,o)}let s=[];for(let e of a.values()){let n=p(e,t);n!==void 0&&s.push({entry:e,field:n})}return{target:t,contributions:s,escapeHatches:r,roots:i.sort((e,t)=>o[e.scope]-o[t.scope]),notices:n}}export{s as isFrontendTarget,m as resolveTarget};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["SCOPE_DEPTH","isFrontendTarget","target","drawsFrom","entry","servesPlatform","FIELDS_OF","SERVER_FIELDS","WEB_FIELDS","NATIVE_FIELDS","MCP_FIELDS","logicalKey","gates","gate","route","segment","variantField","entryTarget","fallback","table","fieldFor","surface","declared","SETTING_FIELDS","ACTION_FIELDS","resolveTarget","notices","escapeHatches","roots","winners","graph","key","held","contributions","field","left","right"],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n MCP_FIELDS,\n NATIVE_FIELDS,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport { NATIVE_PLATFORM } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionNotice, ExtensionSide } from '../../types/extensionGraph';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from './type';\n\n/** Nesting order, so roots compose outermost first. */\nconst SCOPE_DEPTH: Readonly<Record<string, number>> = { global: 0, workspace: 1, session: 2 };\n\n/** Whether a host draws presentation: the cockpit and the native app do, the server and MCP hosts run logic. */\nexport function isFrontendTarget(target: BuildTarget): target is FrontendTarget {\n return target === 'web' || target === NATIVE_PLATFORM;\n}\n\n/** Which side a host reads. */\nfunction drawsFrom(entry: ExtensionEntry, target: BuildTarget): boolean {\n return isFrontendTarget(target) ? entry.side === 'frontend' : entry.side === 'backend';\n}\n\n/**\n * Whether a file's platform suffix lets it reach a host.\n *\n * MCP and native take only files that name them: an unsuffixed backend file may\n * touch the whole server, and an unsuffixed frontend file may touch the DOM.\n * The server and the cockpit still accept an unsuffixed sibling as a fallback.\n */\nfunction servesPlatform(entry: ExtensionEntry, target: BuildTarget): boolean {\n if (target === 'mcp' || target === NATIVE_PLATFORM) return entry.platform === target;\n return entry.platform === undefined || entry.platform === target;\n}\n\nconst FIELDS_OF: Readonly<Record<BuildTarget, Readonly<Record<ExtensionSide, Readonly<Record<string, string>>>>>> = {\n server: { backend: SERVER_FIELDS, frontend: {} },\n web: { backend: {}, frontend: WEB_FIELDS },\n native: { backend: {}, frontend: NATIVE_FIELDS },\n mcp: { backend: MCP_FIELDS, frontend: {} },\n};\n\n/** Everything but the platform: two files sharing this are the same contribution. */\nfunction logicalKey(entry: ExtensionEntry): string {\n const gates = entry.gates.map((gate) => `${gate.kind}:${gate.id}`).join('/');\n const route = entry.route\n .map((segment) => ('literal' in segment ? segment.literal : `[${segment.param.name}]`))\n .join('/');\n // The side is part of it, so a tool's logic and its cockpit renderer never\n // look like one contribution overriding the other.\n return [entry.side, entry.scope, gates, entry.surface ?? '', route, entry.name, entry.target ?? ''].join('|');\n}\n\n/** Resolves the field for a surface whose filename target picks between two shapes. */\nfunction variantField(\n table: Readonly<Record<string, string>>,\n fallback: string,\n entryTarget: string | undefined,\n): string {\n if (entryTarget === undefined) return fallback;\n return table[entryTarget] ?? fallback;\n}\n\nfunction fieldFor(entry: ExtensionEntry, target: BuildTarget): string | undefined {\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n const declared = FIELDS_OF[target][entry.side][surface];\n if (declared === undefined || declared === NOT_A_CONTRIBUTION) return undefined;\n\n if (isFrontendTarget(target) && surface === 'lifecycle' && entry.name !== 'start') return undefined;\n if (isFrontendTarget(target) && surface === 'setting') return variantField(SETTING_FIELDS, declared, entry.target);\n if (target === 'web' && surface === 'action') return variantField(ACTION_FIELDS, declared, entry.target);\n return declared;\n}\n\n/**\n * Picks the winning file per logical contribution for one host.\n *\n * Metro and Expo semantics: a file naming this platform replaces a sibling\n * that names none, and a file naming none serves the server or the cockpit\n * when it has no more specific sibling. The scan reports the unnamed one, so\n * this is a fallback rather than a supported way to author. MCP and native\n * have no fallback at all: they read only the files that name them. Two files\n * naming the same platform for the same contribution is an authoring mistake,\n * so the first wins and the second becomes a notice rather than silently\n * disappearing.\n */\nexport function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution {\n const notices: ExtensionNotice[] = [];\n const escapeHatches: ExtensionEntry[] = [];\n const roots: ExtensionEntry[] = [];\n const winners = new Map<string, ExtensionEntry>();\n\n for (const entry of graph.entries) {\n if (!drawsFrom(entry, target)) continue;\n if (!servesPlatform(entry, target)) continue;\n if (entry.role === 'escape-hatch') {\n escapeHatches.push(entry);\n continue;\n }\n\n if (entry.role === 'root') {\n // Backend only. A root is constructed from a mount context, and the\n // cockpit has none: it builds its plugin definition as data and starts\n // it separately, so there is nothing for a frontend root to receive.\n if (entry.side === 'frontend') {\n notices.push({ path: entry.file, message: 'a scope root is a backend file; the cockpit has no mount context' });\n continue;\n }\n roots.push(entry);\n continue;\n }\n\n const key = logicalKey(entry);\n const held = winners.get(key);\n if (held === undefined) {\n winners.set(key, entry);\n continue;\n }\n if (held.platform === entry.platform) {\n notices.push({ path: entry.file, message: `duplicates ${held.file} for ${target}; the first one wins` });\n continue;\n }\n // A platform file always beats the unsuffixed sibling it overrides.\n if (entry.platform !== undefined) winners.set(key, entry);\n }\n\n const contributions: ResolvedContribution[] = [];\n for (const entry of winners.values()) {\n const field = fieldFor(entry, target);\n if (field === undefined) continue;\n contributions.push({ entry, field });\n }\n\n return {\n target,\n contributions,\n escapeHatches,\n roots: roots.sort((left, right) => SCOPE_DEPTH[left.scope] - SCOPE_DEPTH[right.scope]),\n notices,\n };\n}\n"],"mappings":"+LAcA,MAAMA,EAAgD,CAAE,OAAQ,EAAG,UAAW,EAAG,QAAS,CAAE,EAG5F,SAAgBC,EAAiB,EAA+C,CAC9E,OAAOC,IAAW,OAASA,IAAA,QAC7B,CAGA,SAASC,EAAU,EAAuB,EAA8B,CACtE,OAAOF,EAAiBC,CAAM,EAAIE,EAAM,OAAS,WAAaA,EAAM,OAAS,SAC/E,CASA,SAASC,EAAe,EAAuB,EAA8B,CAE3E,OADIH,IAAW,OAASA,IAAA,SAAmCE,EAAM,WAAaF,EACvEE,EAAM,WAAa,IAAA,IAAaA,EAAM,WAAaF,CAC5D,CAEA,MAAMI,EAA8G,CAClH,OAAQ,CAAE,QAASC,EAAe,SAAU,CAAC,CAAE,EAC/C,IAAK,CAAE,QAAS,CAAC,EAAG,SAAUC,CAAW,EACzC,OAAQ,CAAE,QAAS,CAAC,EAAG,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AG,SACpC,GAAIE,EAAM,OAAS,eAAgB,CACjCuB,EAAc,KAAKvB,CAAK,EACxB,QACF,CAEA,GAAIA,EAAM,OAAS,OAAQ,CAIzB,GAAIA,EAAM,OAAS,WAAY,CAC7BsB,EAAQ,KAAK,CAAE,KAAMtB,EAAM,KAAM,QAAS,kEAAmE,CAAC,EAC9G,QACF,CACAwB,EAAM,KAAKxB,CAAK,EAChB,QACF,CAEA,IAAM2B,EAAMpB,EAAWP,CAAK,EACtB4B,EAAOH,EAAQ,IAAIE,CAAG,EAC5B,GAAIC,IAAS,IAAA,GAAW,CACtBH,EAAQ,IAAIE,EAAK3B,CAAK,EACtB,QACF,CACA,GAAI4B,EAAK,WAAa5B,EAAM,SAAU,CACpCsB,EAAQ,KAAK,CAAE,KAAMtB,EAAM,KAAM,QAAS,cAAc4B,EAAK,KAAK,OAAO9B,EAAO,qBAAsB,CAAC,EACvG,QACF,CAEIE,EAAM,WAAa,IAAA,IAAWyB,EAAQ,IAAIE,EAAK3B,CAAK,CAC1D,CAEA,IAAM6B,EAAwC,CAAC,EAC/C,IAAK,IAAM7B,KAASyB,EAAQ,OAAO,EAAG,CACpC,IAAMK,EAAQd,EAAShB,EAAOF,CAAM,EAChCgC,IAAU,IAAA,IACdD,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,gBACA,gBACA,MAAOL,EAAM,MAAM,EAAM,IAAU5B,EAAYmC,EAAK,OAASnC,EAAYoC,EAAM,MAAM,EACrF,SACF,CACF"}
@@ -0,0 +1,30 @@
1
+ import { ExtensionEntry, ExtensionNotice } from "../../types/extensionGraph.mjs";
2
+ //#region src/services/resolveTarget/type.d.ts
3
+ /** The hosts an entry can be generated for. */
4
+ export type BuildTarget = 'server' | 'web' | 'native' | 'mcp';
5
+ /** The hosts that draw presentation from the `(frontend)` side. */
6
+ export type FrontendTarget = Extract<BuildTarget, 'web' | 'native'>;
7
+ /** One file and the host contribution array it belongs in. */
8
+ export interface ResolvedContribution {
9
+ /** The winning file for this logical contribution on this host. */
10
+ readonly entry: ExtensionEntry;
11
+ /** The host contribution array this belongs in. */
12
+ readonly field: string;
13
+ }
14
+ /** Everything one host needs generated, plus anything skipped on the way. */
15
+ export interface TargetResolution {
16
+ readonly target: BuildTarget;
17
+ readonly contributions: readonly ResolvedContribution[];
18
+ /** Escape-hatch files whose raw contributions are merged in wholesale. */
19
+ readonly escapeHatches: readonly ExtensionEntry[];
20
+ /**
21
+ * Scope constructors, outermost first.
22
+ *
23
+ * Each one runs before the contributions beneath it and its value joins
24
+ * their mount context, so the order is the nesting order and nothing else.
25
+ */
26
+ readonly roots: readonly ExtensionEntry[];
27
+ readonly notices: readonly ExtensionNotice[];
28
+ }
29
+ //#endregion
30
+ //# sourceMappingURL=type.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.mts","names":[],"sources":["../../../src/services/resolveTarget/type.ts"],"mappings":";;;YAGY;;YAGA,iBAAiB,QAAQ;;iBAGpB;;WAEN,OAAO;;WAEP;;;iBAIM;WACN,QAAQ;WACR,wBAAwB;;WAExB,wBAAwB;;;;;;;WAOxB,gBAAgB;WAChB,kBAAkB"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../segments/index.cjs"),r=require("../filename/index.cjs");let i=require("node:fs");i=e.__toESM(i,1);let a=require("node:path");a=e.__toESM(a,1);const o={scope:`global`,side:void 0,gates:[],surface:void 0,route:[],pendingGate:void 0};function s(e){return e===`backend`?t.BACKEND_SURFACES:t.FRONTEND_SURFACES}function c(e,n){return(e===`backend`?n.platforms?.backend:n.platforms?.frontend)??(e===`backend`?t.BACKEND_PLATFORMS:t.FRONTEND_PLATFORMS)}function l(e,t){let n=s(t);if(n.includes(e))return;let r=e.endsWith(`s`)?e.slice(0,-1):`${e}s`;return n.includes(r)?r:void 0}function u(e){return/export\s+default\s+defineRoutedContribution\s*\([\s\S]*,\s*\{\s*cardinality\s*:\s*['"](optional|many|collection)['"]/u.exec(e)?.[1]}function d(e,n){return(n===void 0?[t.DEFAULT_ROUTING_ROOT,t.ROUTING_ROOT_ALIAS]:[n]).find(t=>i.default.existsSync(a.default.join(e,t)))}const f=`the .cli platform is retired: Po has no terminal host, so move this file to .server or delete it`;function p(e){let p=d(e.packageDir,e.root);if(p===void 0)return{root:e.root??`src/extensions`,entries:[],notices:[]};let m=e.sides?.backend??`backend`,h=e.sides?.frontend??`frontend`,g=e.generatedEntries??t.GENERATED_ENTRY_NAMES,_=[],v=[],y=(e,t)=>void v.push({path:e,message:t}),b=(t,n,r)=>{n.platform===void 0&&y(t,`names no platform; add one of ${c(r,e).join(`, `)} before .${n.extension} (without one the host is inferred from the side rather than declared)`)},x=(t,n)=>{let r=a.default.join(e.packageDir,t),o=i.default.readdirSync(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name));for(let e of o){let r=`${t}/${e.name}`;e.isDirectory()?S(r,e.name,n):e.isFile()&&C(r,e.name,n)}},S=(e,r,i)=>{let a=n.classifySegment(r);if(a.kind===`private`)return;if(a.kind===`group`)return i.side===void 0&&a.name===m?x(e,{...i,side:`backend`}):i.side===void 0&&a.name===h?x(e,{...i,side:`frontend`}):x(e,i);if(a.kind===`dynamic`)return i.surface!==void 0&&t.ROUTED_SURFACES.includes(i.surface)?x(e,{...i,route:[...i.route,{param:a.param}]}):y(e,`a dynamic segment is only meaningful inside a routed surface such as api/`);if(i.pendingGate!==void 0){let t={kind:i.pendingGate,id:a.name};return x(e,{...i,gates:[...i.gates,t],pendingGate:void 0})}if(i.surface!==void 0)return t.ROUTED_SURFACES.includes(i.surface)?x(e,{...i,route:[...i.route,{literal:a.name}]}):y(e,`${i.surface}/ takes files directly; put helpers in a _private folder`);if(i.side===void 0)return a.name===`workspaces`&&i.scope===`global`?x(e,{...i,scope:`workspace`}):a.name===`sessions`&&i.scope===`workspace`?x(e,{...i,scope:`session`}):y(e,`expected a scope segment or a side group, such as (${m})`);if(t.GATE_SEGMENTS.includes(a.name))return x(e,{...i,pendingGate:a.name});if(s(i.side).includes(a.name))return x(e,{...i,surface:a.name});let o=l(a.name,i.side);return y(e,o===void 0?`'${a.name}' is not a ${i.side} surface`:`'${a.name}' is not a surface, did you mean '${o}'`)},C=(n,o,s)=>{if(s.side===void 0){let e=o.slice(0,o.lastIndexOf(`.`));return s.scope===`global`&&g.includes(e)||s.scope===`global`||r.parseFilename(o,[])===void 0?void 0:y(n,`a contribution needs a side group and a surface folder`)}let l=c(s.side,e),d=r.parseFilename(o,[...l,`mcp`,`cli`]);if(d===void 0)return;if(d.platform===`cli`)return y(n,f);if(d.platform===`mcp`&&(s.scope!==`session`||(s.side===`frontend`?s.surface!==`tool`||!o.endsWith(`.mcp.tsx`):s.surface!==`tool`&&s.surface!==`skill`&&s.surface!==`resource`)))return y(n,`MCP declarations belong in a session backend tool/, skill/, resource/, or frontend tool/*.mcp.tsx surface`);let p=u(i.default.readFileSync(a.default.join(e.packageDir,n),`utf8`));if(s.surface===void 0){let e=s.gates[s.gates.length-1];if(e!==void 0&&d.name===e.kind){b(n,d,s.side),_.push({file:n,scope:s.scope,side:s.side,gates:s.gates.slice(0,-1),surface:e.kind,route:[],name:e.id,target:d.target,platform:d.platform,...p?{cardinality:p}:{},role:`contribution`});return}if(d.name===`root`&&e===void 0){b(n,d,s.side),_.push({file:n,scope:s.scope,side:s.side,gates:[],surface:void 0,route:[],name:d.name,target:d.target,platform:d.platform,role:`root`});return}return y(n,e===void 0?`only ${t.ROOT_FILE_NAME}.* is read at a side root; move each contribution into its named surface folder`:`inside ${e.kind}/${e.id}/ a contribution needs a surface folder, or name the file ${e.kind}.* to declare the gate`)}t.ROUTED_SURFACES.includes(s.surface)&&d.name!==`route`||(b(n,d,s.side),_.push({file:n,scope:s.scope,side:s.side,gates:s.gates,surface:s.surface,route:s.route,name:d.name,target:d.target,platform:d.platform,...p?{cardinality:p}:{},role:`contribution`}))};return x(p,o),{root:p,entries:_,notices:v}}exports.RETIRED_PLATFORM_NOTICE=f,exports.resolveRoutingRoot=d,exports.scanExtensions=p;
2
+ //# sourceMappingURL=index.cjs.map