@agimon-ai/po-build 0.0.0-alpha.2 → 0.0.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +149 -22
- package/dist/browserFile.mjs +1 -1
- package/dist/constants/contributions.cjs +1 -1
- package/dist/constants/contributions.cjs.map +1 -1
- package/dist/constants/contributions.mjs +1 -1
- package/dist/constants/contributions.mjs.map +1 -1
- package/dist/constants/layout.cjs +1 -1
- package/dist/constants/layout.cjs.map +1 -1
- package/dist/constants/layout.d.mts +2 -0
- package/dist/constants/layout.d.mts.map +1 -1
- package/dist/constants/layout.mjs +1 -1
- package/dist/constants/layout.mjs.map +1 -1
- package/dist/services/generate/index.cjs.map +1 -1
- package/dist/services/generate/index.mjs.map +1 -1
- package/dist/services/renderClient/index.cjs.map +1 -1
- package/dist/services/renderClient/index.mjs.map +1 -1
- package/dist/services/renderEntry/index.cjs +3 -3
- package/dist/services/renderEntry/index.cjs.map +1 -1
- package/dist/services/renderEntry/index.d.mts +10 -4
- package/dist/services/renderEntry/index.d.mts.map +1 -1
- package/dist/services/renderEntry/index.mjs +3 -3
- package/dist/services/renderEntry/index.mjs.map +1 -1
- package/dist/services/renderEntry/type.d.mts +1 -1
- package/dist/services/renderMcpWidgets/index.cjs +1 -1
- package/dist/services/renderMcpWidgets/index.cjs.map +1 -1
- package/dist/services/renderMcpWidgets/index.mjs +1 -1
- package/dist/services/renderMcpWidgets/index.mjs.map +1 -1
- package/dist/services/resolveTarget/index.cjs +1 -1
- package/dist/services/resolveTarget/index.cjs.map +1 -1
- package/dist/services/resolveTarget/index.mjs +1 -1
- package/dist/services/resolveTarget/index.mjs.map +1 -1
- package/dist/services/resolveTarget/type.d.mts +2 -0
- package/dist/services/resolveTarget/type.d.mts.map +1 -1
- package/dist/services/serverContracts/index.cjs +3 -0
- package/dist/services/serverContracts/index.cjs.map +1 -0
- package/dist/services/serverContracts/index.mjs +3 -0
- package/dist/services/serverContracts/index.mjs.map +1 -0
- package/dist/services/serverContracts/type.d.mts +8 -0
- package/dist/services/serverContracts/type.d.mts.map +1 -0
- package/dist/services/syncManifest/index.cjs +1 -1
- package/dist/services/syncManifest/index.cjs.map +1 -1
- package/dist/services/syncManifest/index.d.mts.map +1 -1
- package/dist/services/syncManifest/index.mjs +1 -1
- package/dist/services/syncManifest/index.mjs.map +1 -1
- package/dist/services/syncManifest/type.d.mts +3 -0
- package/dist/services/syncManifest/type.d.mts.map +1 -1
- package/dist/services/tsdownPreset/index.cjs +1 -1
- package/dist/services/tsdownPreset/index.cjs.map +1 -1
- package/dist/services/tsdownPreset/index.d.mts +9 -1
- package/dist/services/tsdownPreset/index.d.mts.map +1 -1
- package/dist/services/tsdownPreset/index.mjs +1 -1
- package/dist/services/tsdownPreset/index.mjs.map +1 -1
- package/dist/tsdown.cjs +1 -1
- package/dist/tsdown.d.mts +2 -2
- package/dist/tsdown.mjs +1 -1
- package/package.json +6 -6
|
@@ -1 +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,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,GAAIC,EAAQC,CAAI,CAAE,EAC9C,CAAE,KAAMF,EAAQ,GAAIC,EAAQC,CAAI,CAAE,CAC3C,CAGA,MAAMC,EAAyE,CAC7E,KAAO,IAAU,C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,OAAOJ,EAAoBvE,EAAYxB,EAAS,QAAQ,CAC1D"}
|
|
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","servedFrom","declared","binding","field","unlessHosted","served","rendered","hosted","shadowKey","gates","gate","segment","renderIdentity","withoutShadowed","nearest","bindings","hatchBindings","contractBindings","member","contextExpression","resolved","isFactory","identity","value","serverImport","scopes","defer","bodyFor","grouped","held","members","contextOf","indent","servedOf","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","contracts","c","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","injects","usesRoots","visible","here","innermost","hatch","factory","provides","contract","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 plugin's array holds `() => PoHubChannel`, 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: 'PoServerSessionPlugin',\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: 'PoMcpSessionPlugin',\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. Each goes through the host's\n * `scopeRoot`, so a root an outer level already built is reused, not rebuilt.\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(\n `const ${root.declaration} = await ${base}.scopeRoot('${root.entry.scope}', ${root.identifier}, ${enclosing});`,\n );\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\n/**\n * The outer scope that already serves a cascaded contribution, when one can.\n *\n * Only a scope-wide registration is served from outside. A channel reaches\n * every session beneath the level that mounted it, and an API or method bound\n * to an outer root is mounted where that root lives. Root-free APIs and\n * methods still cascade, because each level mounts them under its own path,\n * and session registrations such as tools exist only on a session's agent.\n */\nfunction servedFrom(\n binding: Binding,\n roots: readonly RootBinding[],\n scope: ExtensionScope,\n): ExtensionScope | undefined {\n const declared = binding.contribution.entry.scope;\n if (DEPTH[declared] >= DEPTH[scope]) return undefined;\n const { field } = binding.contribution;\n if (field === 'channels') return declared;\n const rootBound = roots.some((root) => DEPTH[root.entry.scope] <= DEPTH[declared]);\n return rootBound && (field === 'api' || field === 'methods') ? declared : undefined;\n}\n\n/**\n * Drops a member while the outer level `served` runs the package and serves it there.\n *\n * A single member leaves a hole for `defined` to remove rather than spreading a\n * conditional array, because TypeScript gives a spread no contextual type and\n * the identity helper's T would widen to unknown.\n */\nfunction unlessHosted(rendered: string, served: ExtensionScope | undefined): string {\n if (served === undefined) return rendered;\n const hosted = `context.hosted('${served}')`;\n if (rendered.startsWith('...')) return `...(${hosted} ? [] : ${rendered.slice('...'.length)})`;\n return `${hosted} ? undefined : ${rendered}`;\n}\n\n/**\n * What makes two routed contributions the same one: its gates, its field, and the identity the host\n * reads, which for an API is its route path. Hooks have none, because two handlers of one event both run.\n */\nfunction shadowKey(binding: Binding): string | undefined {\n const { entry, field } = binding.contribution;\n if (field === 'hooks') return undefined;\n const gates = entry.gates.map((gate) => `${gate.kind}:${gate.id}`).join('/');\n if (field === 'api') {\n const route = entry.route.map((segment) => ('literal' in segment ? segment.literal : `[${segment.param.name}]`));\n return `${gates}|api|${route.join('/')}`;\n }\n return binding.identity === undefined ? undefined : `${gates}|${field}|${renderIdentity(binding.identity)}`;\n}\n\n/**\n * Leaves out a contribution cascaded from an outer level when a level nearer this one declares the\n * same contribution again, as the cockpit replaces a parent's contribution when its key matches. Both\n * would otherwise claim one name, and the host keeps whichever registered first.\n */\nfunction withoutShadowed(bindings: readonly Binding[]): Binding[] {\n const nearest = new Map<string, number>();\n for (const binding of bindings) {\n const key = shadowKey(binding);\n if (key !== undefined) nearest.set(key, Math.max(nearest.get(key) ?? -1, DEPTH[binding.contribution.entry.scope]));\n }\n return bindings.filter((binding) => {\n const key = shadowKey(binding);\n return key === undefined || nearest.get(key) === DEPTH[binding.contribution.entry.scope];\n });\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/** Each `contract/` file under an identifier of its own. */\nfunction contractBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n const taken = new Set<string>();\n return entries.map((entry) => ({ identifier: uniqueIdentifier(['contract', entry.name], taken), 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 PoServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverPlugin';`;\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 servedOf: (binding: Binding) => ExtensionScope | undefined = () => undefined,\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 unlessHosted(\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 servedOf(entry),\n ),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const holes = members.some(\n (entry) =>\n entry.contribution.entry.cardinality === 'optional' ||\n (entry.contribution.entry.cardinality !== 'many' && servedOf(entry) !== undefined),\n );\n const rendered = holes ? `defined(${entries})` : 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(): PoServerSessionPlugin['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 contracts: readonly { identifier: string; entry: ExtensionEntry }[] = [],\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...contracts.map((c) => `import ${c.identifier} from '${specifierFor(c.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) => /\\bcontext[.,)]/u.test(line)) ? '(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 each level reads exactly one\n * `plugin[host.scope]` and nothing from the scopes above it. Emitting the\n * repetition is what lets an author declare a channel once and have it reach\n * every session, whether or not an outer level runs the package. When one does,\n * the host says so through `context.hosted`, and the inner level leaves to it\n * the roots, channels and root-bound registrations it already serves.\n *\n * `provides` lists each level's `contract/` files, and `injects` what the roots\n * a level builds or reuses ask for, so the host can make the level wait for\n * them and the build can write both into the manifest.\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 const contracts = contractBindings(resolution.contracts);\n\n const scopes: string[] = [];\n const injects: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = withoutShadowed(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 names every root that encloses it. The host hands back the\n // one an outer level already built, and builds it here when none did.\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(\n visible,\n ' ',\n (b) => contextForScope(roots, b.contribution.entry.scope, 'context'),\n 'server',\n (b) => servedFrom(b, roots, scope),\n ),\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) {\n usesRoots = true;\n injects.push(`${scope}: [${roots.map((root) => root.identifier).join(', ')}]`);\n }\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n const provides = SCOPE_ORDER.flatMap((scope) => {\n const declared = contracts.filter((contract) => contract.entry.scope === scope);\n return declared.length === 0\n ? []\n : [` ${scope}: [${declared.map((contract) => contract.identifier).join(', ')}],`];\n });\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir, contracts),\n '',\n ...resolverFor(scopes),\n 'export const serverPlugin = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...(provides.length > 0 ? [' provides: {', ...provides, ' },'] : []),\n ...(injects.length > 0 ? [` injects: composeRootInjects({ ${injects.join(', ')} }),`] : []),\n ...scopes,\n '});',\n '',\n 'export default serverPlugin;',\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 PoMcpSessionPlugin } 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 PoMcpSessionPlugin,',\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,0B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AAQ,GAAM8B,EAAE,aAAa,MAAM,QAAU9C,CAAK,EACrEgE,EAAOjB,EAAQ,OAAQ,GAAMC,EAAE,MAAM,QAAUhD,CAAK,EACpDJ,EAAO,CACX,GAAGgC,EAAQmC,EAAS,WAAc,YAAa9G,CAAM,EAGrD,GAAG+G,EAAK,IAAK,GAAU,UAAUE,EAAM,WAAW,EAAE,CACtD,EACItE,EAAK,SAAW,GACpB8B,EAAO,KAAK,KAAK1B,EAAM,KAAM,GAAGJ,EAAM,MAAM,CAC9C,CAEA,IAAM8E,EAAQhD,EAAO,KAAM,GAAS7B,EAAK,SAAS,MAAM,CAAC,EACrD,GAAG4E,EAAM,OAAO,SAAS9H,EAAmBM,KAC5CwH,EAAM,OACV,OAAOxB,EAAQ,CACb3G,EACA,YAAYoI,EAAM,WAAWD,EAAM,OAAO,IAC1C,GACA,GAAG/B,EAAW1B,EAAU+B,EAAS,CAAC,EAAGxF,EAAQ,QAAQ,EACrD,GACA,GAAG4F,EAAYzB,CAAM,EACrB,gBAAgB+C,EAAM,WAAW,KAAKA,EAAM,OAAO,IACnD,UAAUlH,EAAQ,SAAS,IAC3B,GAAGmE,EACH,MACA,EACF,CAAC,CACH,CAGA,SAAgBiD,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBzF,EAAYxB,EAAS,KAAK,CACvD,CAGA,SAAgBqH,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBzF,EAAYxB,EAAS,QAAQ,CAC1D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/services/renderEntry/type.d.ts
|
|
2
2
|
/** What the renderers need beyond the resolved contributions themselves. */
|
|
3
3
|
export interface RenderOptions {
|
|
4
|
-
/** The package's npm name, used as the extension and
|
|
4
|
+
/** The package's npm name, used as the extension and server plugin name. */
|
|
5
5
|
readonly packageName: string;
|
|
6
6
|
/** The cockpit plugin id. */
|
|
7
7
|
readonly pluginId: string;
|
|
@@ -1,3 +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 {
|
|
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 { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {`,...s,`};`,``].join(`
|
|
2
2
|
`)}}exports.renderMcpWidgets=n;
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +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 {
|
|
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 { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {',\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,wEACA,GAAGH,EACH,GACA,sFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
|
|
@@ -1,3 +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 {
|
|
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 { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {`,...s,`};`,``].join(`
|
|
2
2
|
`)}}export{n as renderMcpWidgets};
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +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 {
|
|
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 { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {',\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,wEACA,GAAGH,EACH,GACA,sFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
|
|
@@ -1,2 +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):r===`native`&&i===`action`?t.target===void 0?void 0:e.NATIVE_ACTION_FIELDS[t.target]:o}function l(n,a){let s=[],l=[],u=[],d=/* @__PURE__ */ new Map;for(let e of n.entries){if(!r(e,a)||!i(e,a))continue;if(e.role===`escape-hatch`){l.push(e);continue}if(e.role===`root`){if(e.side===`frontend`){s.push({path:e.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}u.push(e);continue}let t=o(e),n=
|
|
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):r===`native`&&i===`action`?t.target===void 0?void 0:e.NATIVE_ACTION_FIELDS[t.target]:o}function l(n,a){let s=[],l=[],u=[],d=[],f=/* @__PURE__ */ new Map;for(let e of n.entries){if(!r(e,a)||!i(e,a))continue;if(e.role===`escape-hatch`){l.push(e);continue}if(e.role===`root`){if(e.side===`frontend`){s.push({path:e.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}u.push(e);continue}if(e.surface===`contract`){if(e.gates.length>0){s.push({path:e.file,message:`a contract belongs to its level and cannot sit under a gate`});continue}d.push(e);continue}let t=o(e),n=f.get(t);n===void 0?f.set(t,e):n.platform===e.platform?s.push({path:e.file,message:`duplicates ${n.file} for ${a}; the first one wins`}):e.platform!==void 0&&f.set(t,e)}let p=[];for(let t of f.values()){let n=c(t,a);n===void 0?a===`native`&&t.surface!==void 0&&e.NATIVE_FIELDS[t.surface]!==``&&s.push({path:t.file,message:`${t.surface}/${t.name} is not supported by the native host`}):p.push({entry:t,field:n})}return{target:a,contributions:p,escapeHatches:l,roots:u.sort((e,n)=>t[e.scope]-t[n.scope]),contracts:d.sort((e,t)=>e.file.localeCompare(t.file)),notices:s}}exports.isFrontendTarget=n,exports.resolveTarget=l;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["SERVER_FIELDS","WEB_FIELDS","NATIVE_FIELDS","MCP_FIELDS","SETTING_FIELDS","ACTION_FIELDS","NATIVE_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_ACTION_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 // No fallback shape: an unnamed or context action is reported, never routed.\n if (target === NATIVE_PLATFORM && surface === 'action') {\n return entry.target === undefined ? undefined : NATIVE_ACTION_FIELDS[entry.target];\n }\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) {\n if (\n target === NATIVE_PLATFORM &&\n entry.surface !== undefined &&\n NATIVE_FIELDS[entry.surface] !== NOT_A_CONTRIBUTION\n ) {\n notices.push({\n path: entry.file,\n message: `${entry.surface}/${entry.name} is not supported by the native host`,\n });\n }\n continue;\n }\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":"2FAeMQ,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,QAASd,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,SAASY,EAAW,EAA+B,CACjD,IAAMC,EAAQJ,EAAM,MAAM,IAAK,GAAS,GAAGK,EAAK,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S","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","contracts","winners","graph","key","held","contributions","field","left","right"],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n MCP_FIELDS,\n NATIVE_ACTION_FIELDS,\n NATIVE_FIELDS,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport { CONTRACT_SURFACE, 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 // No fallback shape: an unnamed or context action is reported, never routed.\n if (target === NATIVE_PLATFORM && surface === 'action') {\n return entry.target === undefined ? undefined : NATIVE_ACTION_FIELDS[entry.target];\n }\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 contracts: 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 if (entry.surface === CONTRACT_SURFACE) {\n // What a level provides is fixed for the package, so no mode can switch a contract off.\n if (entry.gates.length > 0) {\n notices.push({ path: entry.file, message: 'a contract belongs to its level and cannot sit under a gate' });\n continue;\n }\n contracts.push(entry);\n continue;\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) {\n if (\n target === NATIVE_PLATFORM &&\n entry.surface !== undefined &&\n NATIVE_FIELDS[entry.surface] !== NOT_A_CONTRIBUTION\n ) {\n notices.push({\n path: entry.file,\n message: `${entry.surface}/${entry.name} is not supported by the native host`,\n });\n }\n continue;\n }\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 contrac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uB,EAAOH,EAAQ,IAAIE,CAAG,EACxBC,IAAS,IAAA,GACXH,EAAQ,IAAIE,EAAKtB,CAAK,EAGpBuB,EAAK,WAAavB,EAAM,SAC1BgB,EAAQ,KAAK,CAAE,KAAMhB,EAAM,KAAM,QAAS,cAAcuB,EAAK,KAAK,OAAOzB,EAAO,qBAAsB,CAAC,EAIrGE,EAAM,WAAa,IAAA,IAAWoB,EAAQ,IAAIE,EAAKtB,CAAK,CAC1D,CAEA,IAAMwB,EAAwC,CAAC,EAC/C,IAAK,IAAMxB,KAASoB,EAAQ,OAAO,EAAG,CACpC,IAAMK,EAAQb,EAASZ,EAAOF,CAAM,EAChC2B,IAAU,IAAA,GAEV3B,IAAA,UACAE,EAAM,UAAY,IAAA,IAClBV,EAAAA,cAAcU,EAAM,WAAA,IAEpBgB,EAAQ,KAAK,CACX,KAAMhB,EAAM,KACZ,QAAS,GAAGA,EAAM,QAAQ,GAAGA,EAAM,KAAK,qCAC1C,CAAC,EAILwB,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,gBACA,gBACA,MAAON,EAAM,MAAM,EAAM,IAAUtB,EAAY8B,EAAK,OAAS9B,EAAY+B,EAAM,MAAM,EACrF,UAAWR,EAAU,MAAM,EAAM,IAAUO,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC9E,SACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../../constants/layout.mjs";import{ACTION_FIELDS as e,MCP_FIELDS as t,NATIVE_ACTION_FIELDS as n,NATIVE_FIELDS as r,SERVER_FIELDS as i,SETTING_FIELDS as a,WEB_FIELDS as o}from"../../constants/contributions.mjs";const s={global:0,workspace:1,session:2};function c(e){return e===`web`||e===`native`}function l(e,t){return c(t)?e.side===`frontend`:e.side===`backend`}function u(e,t){return t===`mcp`||t===`native`?e.platform===t:e.platform===void 0||e.platform===t}const d={server:{backend:i,frontend:{}},web:{backend:{},frontend:o},native:{backend:{},frontend:r},mcp:{backend:t,frontend:{}}};function f(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 p(e,t,n){return n===void 0?t:e[n]??t}function m(t,r){let i=t.surface;if(i===void 0)return;let o=d[r][t.side][i];if(o!==void 0&&o!==``&&!(c(r)&&i===`lifecycle`&&t.name!==`start`))return c(r)&&i===`setting`?p(a,o,t.target):r===`web`&&i===`action`?p(e,o,t.target):r===`native`&&i===`action`?t.target===void 0?void 0:n[t.target]:o}function h(e,t){let n=[],i=[],a=[],o=/* @__PURE__ */ new Map;for(let r of e.entries){if(!l(r,t)||!u(r,t))continue;if(r.role===`escape-hatch`){i.push(r);continue}if(r.role===`root`){if(r.side===`frontend`){n.push({path:r.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}a.push(r);continue}let e=f(r),s=
|
|
1
|
+
import"../../constants/layout.mjs";import{ACTION_FIELDS as e,MCP_FIELDS as t,NATIVE_ACTION_FIELDS as n,NATIVE_FIELDS as r,SERVER_FIELDS as i,SETTING_FIELDS as a,WEB_FIELDS as o}from"../../constants/contributions.mjs";const s={global:0,workspace:1,session:2};function c(e){return e===`web`||e===`native`}function l(e,t){return c(t)?e.side===`frontend`:e.side===`backend`}function u(e,t){return t===`mcp`||t===`native`?e.platform===t:e.platform===void 0||e.platform===t}const d={server:{backend:i,frontend:{}},web:{backend:{},frontend:o},native:{backend:{},frontend:r},mcp:{backend:t,frontend:{}}};function f(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 p(e,t,n){return n===void 0?t:e[n]??t}function m(t,r){let i=t.surface;if(i===void 0)return;let o=d[r][t.side][i];if(o!==void 0&&o!==``&&!(c(r)&&i===`lifecycle`&&t.name!==`start`))return c(r)&&i===`setting`?p(a,o,t.target):r===`web`&&i===`action`?p(e,o,t.target):r===`native`&&i===`action`?t.target===void 0?void 0:n[t.target]:o}function h(e,t){let n=[],i=[],a=[],o=[],c=/* @__PURE__ */ new Map;for(let r of e.entries){if(!l(r,t)||!u(r,t))continue;if(r.role===`escape-hatch`){i.push(r);continue}if(r.role===`root`){if(r.side===`frontend`){n.push({path:r.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}a.push(r);continue}if(r.surface===`contract`){if(r.gates.length>0){n.push({path:r.file,message:`a contract belongs to its level and cannot sit under a gate`});continue}o.push(r);continue}let e=f(r),s=c.get(e);s===void 0?c.set(e,r):s.platform===r.platform?n.push({path:r.file,message:`duplicates ${s.file} for ${t}; the first one wins`}):r.platform!==void 0&&c.set(e,r)}let d=[];for(let e of c.values()){let i=m(e,t);i===void 0?t===`native`&&e.surface!==void 0&&r[e.surface]!==``&&n.push({path:e.file,message:`${e.surface}/${e.name} is not supported by the native host`}):d.push({entry:e,field:i})}return{target:t,contributions:d,escapeHatches:i,roots:a.sort((e,t)=>s[e.scope]-s[t.scope]),contracts:o.sort((e,t)=>e.file.localeCompare(t.file)),notices:n}}export{c as isFrontendTarget,h as resolveTarget};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +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","NATIVE_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_ACTION_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 // No fallback shape: an unnamed or context action is reported, never routed.\n if (target === NATIVE_PLATFORM && surface === 'action') {\n return entry.target === undefined ? undefined : NATIVE_ACTION_FIELDS[entry.target];\n }\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) {\n if (\n target === NATIVE_PLATFORM &&\n entry.surface !== undefined &&\n NATIVE_FIELDS[entry.surface] !== NOT_A_CONTRIBUTION\n ) {\n notices.push({\n path: entry.file,\n message: `${entry.surface}/${entry.name} is not supported by the native host`,\n });\n }\n continue;\n }\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":"yNAeA,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,IA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EAAM,MAAM,EAAM,IAAU7B,EAAYoC,EAAK,OAASpC,EAAYqC,EAAM,MAAM,EACrF,SACF,CACF"}
|
|
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","NATIVE_ACTION_FIELDS","resolveTarget","notices","escapeHatches","roots","contracts","winners","graph","key","held","contributions","field","left","right"],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n MCP_FIELDS,\n NATIVE_ACTION_FIELDS,\n NATIVE_FIELDS,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport { CONTRACT_SURFACE, 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 // No fallback shape: an unnamed or context action is reported, never routed.\n if (target === NATIVE_PLATFORM && surface === 'action') {\n return entry.target === undefined ? undefined : NATIVE_ACTION_FIELDS[entry.target];\n }\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 contracts: 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 if (entry.surface === CONTRACT_SURFACE) {\n // What a level provides is fixed for the package, so no mode can switch a contract off.\n if (entry.gates.length > 0) {\n notices.push({ path: entry.file, message: 'a contract belongs to its level and cannot sit under a gate' });\n continue;\n }\n contracts.push(entry);\n continue;\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) {\n if (\n target === NATIVE_PLATFORM &&\n entry.surface !== undefined &&\n NATIVE_FIELDS[entry.surface] !== NOT_A_CONTRIBUTION\n ) {\n notices.push({\n path: entry.file,\n message: `${entry.surface}/${entry.name} is not supported by the native host`,\n });\n }\n continue;\n }\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 contracts: contracts.sort((left, right) => left.file.localeCompare(right.file)),\n notices,\n };\n}\n"],"mappings":"yNAeA,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,SAAUC,CAAc,EAC/C,IAAK,CAAE,QAASC,EAAY,SAAU,CAAC,CAAE,CAC3C,EAGA,SAASC,EAAW,EAA+B,CACjD,IAAMC,EAAQR,EAAM,MAAM,IAAK,GAAS,GAAGS,EAAK,KAAK,GAAGA,EAAK,IAAI,CAAC,CAAC,KAAK,GAAG,EACrEC,EAAQV,EAAM,MACjB,IAAK,GAAa,YAAaW,EAAUA,EAAQ,QAAU,IAAIA,EAAQ,MAAM,KAAK,EAAG,CAAC,CACtF,KAAK,GAAG,EAGX,MAAO,CAACX,EAAM,KAAMA,EAAM,MAAOQ,EAAOR,EAAM,SAAW,GAAIU,EAAOV,EAAM,KAAMA,EAAM,QA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M,MAAM,OAAS,EAAG,CAC1BuB,EAAQ,KAAK,CAAE,KAAMvB,EAAM,KAAM,QAAS,6DAA8D,CAAC,EACzG,QACF,CACA0B,EAAU,KAAK1B,CAAK,EACpB,QACF,CACA,IAAM6B,EAAMtB,EAAWP,CAAK,EACtB8B,EAAOH,EAAQ,IAAIE,CAAG,EACxBC,IAAS,IAAA,GACXH,EAAQ,IAAIE,EAAK7B,CAAK,EAGpB8B,EAAK,WAAa9B,EAAM,SAC1BuB,EAAQ,KAAK,CAAE,KAAMvB,EAAM,KAAM,QAAS,cAAc8B,EAAK,KAAK,OAAOhC,EAAO,qBAAsB,CAAC,EAIrGE,EAAM,WAAa,IAAA,IAAW2B,EAAQ,IAAIE,EAAK7B,CAAK,CAC1D,CAEA,IAAM+B,EAAwC,CAAC,EAC/C,IAAK,IAAM/B,KAAS2B,EAAQ,OAAO,EAAG,CACpC,IAAMK,EAAQhB,EAAShB,EAAOF,CAAM,EAChCkC,IAAU,IAAA,GAEVlC,IAAA,UACAE,EAAM,UAAY,IAAA,IAClBK,EAAcL,EAAM,WAAA,IAEpBuB,EAAQ,KAAK,CACX,KAAMvB,EAAM,KACZ,QAAS,GAAGA,EAAM,QAAQ,GAAGA,EAAM,KAAK,qCAC1C,CAAC,EAIL+B,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,gBACA,gBACA,MAAON,EAAM,MAAM,EAAM,IAAU7B,EAAYqC,EAAK,OAASrC,EAAYsC,EAAM,MAAM,EACrF,UAAWR,EAAU,MAAM,EAAM,IAAUO,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC9E,SACF,CACF"}
|
|
@@ -24,6 +24,8 @@ export interface TargetResolution {
|
|
|
24
24
|
* their mount context, so the order is the nesting order and nothing else.
|
|
25
25
|
*/
|
|
26
26
|
readonly roots: readonly ExtensionEntry[];
|
|
27
|
+
/** Service contracts each level provides, one per `contract/` file. Server only. */
|
|
28
|
+
readonly contracts: readonly ExtensionEntry[];
|
|
27
29
|
readonly notices: readonly ExtensionNotice[];
|
|
28
30
|
}
|
|
29
31
|
//#endregion
|
|
@@ -1 +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;
|
|
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;;WAEhB,oBAAoB;WACpB,kBAAkB"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:child_process"),r=require("node:url");const i=(0,require("node:util").promisify)(n.execFile),a=`\0po-server-contracts\0`,o=[`const names = (table) => Object.fromEntries(Object.entries(table ?? {})`,` .map(([level, contracts]) => [level, contracts.map((contract) => contract.name)])`,` .filter(([, list]) => list.length > 0));`,`try {`,` const plugin = (await import(process.argv[1])).default ?? {};`,` const result = JSON.stringify({ provides: names(plugin.provides), injects: names(plugin.injects) });`,` process.stdout.write(${JSON.stringify(a)} + result, () => process.exit(0));`,`} catch (error) {`," process.stderr.write(error instanceof Error ? `${error.name}: ${error.message}` : String(error));",` process.exit(1);`,`}`].join(`
|
|
2
|
+
`);function s(e){return((typeof e==`object`&&e&&`stderr`in e&&typeof e.stderr==`string`?e.stderr.trim():``)||(e instanceof Error?e.message:String(e))).slice(0,1e3)}async function c(e,n){let c=t.default.join(e,n),l;try{({stdout:l}=await i(process.execPath,[`--input-type=module`,`-e`,o,(0,r.pathToFileURL)(c).href],{cwd:e,timeout:1e4,maxBuffer:1048576}))}catch(e){throw Error(`Could not read the service contracts of ${c}: ${s(e)}`,{cause:e})}let u=l.lastIndexOf(a);if(u<0)throw Error(`Reading the service contracts of ${c} printed no result.`);return JSON.parse(l.slice(u+21))}exports.readServerContracts=c;
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["promisify","execFile","path","pathToFileURL","require_runtime","node_path","node_child_process","node_url","execute","RESULT_MARKER","CONTRACTS_PRINTER","problemOf","error","readServerContracts","built","packageDir","dist","stdout","marker"],"sources":["../../../src/services/serverContracts/index.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { promisify } from 'node:util';\n\nimport type { ServerContractNames } from './type';\n\nconst execute = promisify(execFile);\n\n/** How long importing a built server entry may take before the build gives up on it. */\nconst READ_TIMEOUT_MS = 10_000;\nconst READ_MAX_BUFFER = 1024 * 1024;\n\n/** Precedes the JSON, so anything a module prints while it loads cannot be read as the answer. */\nconst RESULT_MARKER = '\\u0000po-server-contracts\\u0000';\n\n/**\n * Imports one built server entry and prints the names of the contracts its plugin provides and\n * injects at each level. It exits once the result is flushed, because a module that leaves a handle\n * open would otherwise keep the child alive until the timeout.\n */\nconst CONTRACTS_PRINTER = [\n 'const names = (table) => Object.fromEntries(Object.entries(table ?? {})',\n ' .map(([level, contracts]) => [level, contracts.map((contract) => contract.name)])',\n ' .filter(([, list]) => list.length > 0));',\n 'try {',\n ' const plugin = (await import(process.argv[1])).default ?? {};',\n ' const result = JSON.stringify({ provides: names(plugin.provides), injects: names(plugin.injects) });',\n ` process.stdout.write(${JSON.stringify(RESULT_MARKER)} + result, () => process.exit(0));`,\n '} catch (error) {',\n ' process.stderr.write(error instanceof Error ? `${error.name}: ${error.message}` : String(error));',\n ' process.exit(1);',\n '}',\n].join('\\n');\n\nfunction problemOf(error: unknown): string {\n const stderr =\n error !== null && typeof error === 'object' && 'stderr' in error && typeof error.stderr === 'string'\n ? error.stderr.trim()\n : '';\n return (stderr || (error instanceof Error ? error.message : String(error))).slice(0, 1000);\n}\n\n/**\n * The contract names a built server entry declares, read by importing it in a bounded child process.\n *\n * The plugin is the one source of truth: a contract a root injects may come from another package,\n * and only the loaded value names it exactly. The child keeps the entry's module graph, its timers\n * and its failures out of the build. A failure throws, so a manifest never claims less than the\n * code it describes.\n */\nexport async function readServerContracts(packageDir: string, dist: string): Promise<ServerContractNames> {\n const built = path.join(packageDir, dist);\n let stdout: string;\n try {\n ({ stdout } = await execute(\n process.execPath,\n ['--input-type=module', '-e', CONTRACTS_PRINTER, pathToFileURL(built).href],\n { cwd: packageDir, timeout: READ_TIMEOUT_MS, maxBuffer: READ_MAX_BUFFER },\n ));\n } catch (error) {\n throw new Error(`Could not read the service contracts of ${built}: ${problemOf(error)}`, { cause: error });\n }\n const marker = stdout.lastIndexOf(RESULT_MARKER);\n if (marker < 0) throw new Error(`Reading the service contracts of ${built} printed no result.`);\n return JSON.parse(stdout.slice(marker + RESULT_MARKER.length)) as ServerContractNames;\n}\n"],"mappings":"8JAOA,MAAMQ,GAAA,qBAAUR,CAAAA,CAAAA,UAAAA,CAAUC,EAAAA,QAAQ,EAO5BQ,EAAgB,0BAOhBC,EAAoB,CACxB,0EACA,sFACA,6CACA,QACA,kEACA,yGACA,0BAA0B,KAAK,UAAUD,CAAa,EAAE,oCACxD,oBACA,sGACA,qBACA,GACF,CAAC,CAAC,KAAK;CAAI,EAEX,SAASE,EAAU,EAAwB,CAKzC,QAHoB,OAAOC,GAAU,UAAnCA,GAA+C,WAAYA,GAAS,OAAOA,EAAM,QAAW,SACxFA,EAAM,OAAO,KAAK,EAClB,MACaA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAAA,CAAI,MAAM,EAAG,GAAI,CAC3F,CAUA,eAAsBC,EAAoB,EAAoB,EAA4C,CACxG,IAAMC,EAAQZ,EAAAA,QAAK,KAAKa,EAAYC,CAAI,EACpCC,EACJ,GAAI,EACD,WAAa,MAAMT,EAClB,QAAQ,SACR,CAAC,sBAAuB,KAAME,GAAmBP,EAAAA,EAAAA,cAAAA,CAAcW,CAAK,CAAC,CAAC,IAAI,EAC1E,CAAE,IAAKC,EAAY,QAAS,IAAiB,UAAW,OAAgB,CAC1E,EACF,OAASH,EAAO,CACd,MAAU,MAAM,2CAA2CE,EAAM,IAAIH,EAAUC,CAAK,IAAK,CAAE,MAAOA,CAAM,CAAC,CAC3G,CACA,IAAMM,EAASD,EAAO,YAAYR,CAAa,EAC/C,GAAIS,EAAS,EAAG,MAAU,MAAM,oCAAoCJ,EAAM,oBAAoB,EAC9F,OAAO,KAAK,MAAMG,EAAO,MAAMC,EAAS,EAAoB,CAAC,CAC/D"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import e from"node:path";import{execFile as t}from"node:child_process";import{pathToFileURL as n}from"node:url";import{promisify as r}from"node:util";const i=r(t),a=`\0po-server-contracts\0`,o=[`const names = (table) => Object.fromEntries(Object.entries(table ?? {})`,` .map(([level, contracts]) => [level, contracts.map((contract) => contract.name)])`,` .filter(([, list]) => list.length > 0));`,`try {`,` const plugin = (await import(process.argv[1])).default ?? {};`,` const result = JSON.stringify({ provides: names(plugin.provides), injects: names(plugin.injects) });`,` process.stdout.write(${JSON.stringify(a)} + result, () => process.exit(0));`,`} catch (error) {`," process.stderr.write(error instanceof Error ? `${error.name}: ${error.message}` : String(error));",` process.exit(1);`,`}`].join(`
|
|
2
|
+
`);function s(e){return((typeof e==`object`&&e&&`stderr`in e&&typeof e.stderr==`string`?e.stderr.trim():``)||(e instanceof Error?e.message:String(e))).slice(0,1e3)}async function c(t,r){let c=e.join(t,r),l;try{({stdout:l}=await i(process.execPath,[`--input-type=module`,`-e`,o,n(c).href],{cwd:t,timeout:1e4,maxBuffer:1048576}))}catch(e){throw Error(`Could not read the service contracts of ${c}: ${s(e)}`,{cause:e})}let u=l.lastIndexOf(a);if(u<0)throw Error(`Reading the service contracts of ${c} printed no result.`);return JSON.parse(l.slice(u+21))}export{c as readServerContracts};
|
|
3
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["path","execute","promisify","execFile","RESULT_MARKER","CONTRACTS_PRINTER","problemOf","error","readServerContracts","built","packageDir","dist","stdout","pathToFileURL","marker"],"sources":["../../../src/services/serverContracts/index.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { promisify } from 'node:util';\n\nimport type { ServerContractNames } from './type';\n\nconst execute = promisify(execFile);\n\n/** How long importing a built server entry may take before the build gives up on it. */\nconst READ_TIMEOUT_MS = 10_000;\nconst READ_MAX_BUFFER = 1024 * 1024;\n\n/** Precedes the JSON, so anything a module prints while it loads cannot be read as the answer. */\nconst RESULT_MARKER = '\\u0000po-server-contracts\\u0000';\n\n/**\n * Imports one built server entry and prints the names of the contracts its plugin provides and\n * injects at each level. It exits once the result is flushed, because a module that leaves a handle\n * open would otherwise keep the child alive until the timeout.\n */\nconst CONTRACTS_PRINTER = [\n 'const names = (table) => Object.fromEntries(Object.entries(table ?? {})',\n ' .map(([level, contracts]) => [level, contracts.map((contract) => contract.name)])',\n ' .filter(([, list]) => list.length > 0));',\n 'try {',\n ' const plugin = (await import(process.argv[1])).default ?? {};',\n ' const result = JSON.stringify({ provides: names(plugin.provides), injects: names(plugin.injects) });',\n ` process.stdout.write(${JSON.stringify(RESULT_MARKER)} + result, () => process.exit(0));`,\n '} catch (error) {',\n ' process.stderr.write(error instanceof Error ? `${error.name}: ${error.message}` : String(error));',\n ' process.exit(1);',\n '}',\n].join('\\n');\n\nfunction problemOf(error: unknown): string {\n const stderr =\n error !== null && typeof error === 'object' && 'stderr' in error && typeof error.stderr === 'string'\n ? error.stderr.trim()\n : '';\n return (stderr || (error instanceof Error ? error.message : String(error))).slice(0, 1000);\n}\n\n/**\n * The contract names a built server entry declares, read by importing it in a bounded child process.\n *\n * The plugin is the one source of truth: a contract a root injects may come from another package,\n * and only the loaded value names it exactly. The child keeps the entry's module graph, its timers\n * and its failures out of the build. A failure throws, so a manifest never claims less than the\n * code it describes.\n */\nexport async function readServerContracts(packageDir: string, dist: string): Promise<ServerContractNames> {\n const built = path.join(packageDir, dist);\n let stdout: string;\n try {\n ({ stdout } = await execute(\n process.execPath,\n ['--input-type=module', '-e', CONTRACTS_PRINTER, pathToFileURL(built).href],\n { cwd: packageDir, timeout: READ_TIMEOUT_MS, maxBuffer: READ_MAX_BUFFER },\n ));\n } catch (error) {\n throw new Error(`Could not read the service contracts of ${built}: ${problemOf(error)}`, { cause: error });\n }\n const marker = stdout.lastIndexOf(RESULT_MARKER);\n if (marker < 0) throw new Error(`Reading the service contracts of ${built} printed no result.`);\n return JSON.parse(stdout.slice(marker + RESULT_MARKER.length)) as ServerContractNames;\n}\n"],"mappings":"sJAOA,MAAMC,EAAUC,EAAUC,CAAQ,EAO5BC,EAAgB,0BAOhBC,EAAoB,CACxB,0EACA,sFACA,6CACA,QACA,kEACA,yGACA,0BAA0B,KAAK,UAAUD,CAAa,EAAE,oCACxD,oBACA,sGACA,qBACA,GACF,CAAC,CAAC,KAAK;CAAI,EAEX,SAASE,EAAU,EAAwB,CAKzC,QAHoB,OAAOC,GAAU,UAAnCA,GAA+C,WAAYA,GAAS,OAAOA,EAAM,QAAW,SACxFA,EAAM,OAAO,KAAK,EAClB,MACaA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAAA,CAAI,MAAM,EAAG,GAAI,CAC3F,CAUA,eAAsBC,EAAoB,EAAoB,EAA4C,CACxG,IAAMC,EAAQT,EAAK,KAAKU,EAAYC,CAAI,EACpCC,EACJ,GAAI,EACD,WAAa,MAAMX,EAClB,QAAQ,SACR,CAAC,sBAAuB,KAAMI,EAAmBQ,EAAcJ,CAAK,CAAC,CAAC,IAAI,EAC1E,CAAE,IAAKC,EAAY,QAAS,IAAiB,UAAW,OAAgB,CAC1E,EACF,OAASH,EAAO,CACd,MAAU,MAAM,2CAA2CE,EAAM,IAAIH,EAAUC,CAAK,IAAK,CAAE,MAAOA,CAAM,CAAC,CAC3G,CACA,IAAMO,EAASF,EAAO,YAAYR,CAAa,EAC/C,GAAIU,EAAS,EAAG,MAAU,MAAM,oCAAoCL,EAAM,oBAAoB,EAC9F,OAAO,KAAK,MAAMG,EAAO,MAAME,EAAS,EAAoB,CAAC,CAC/D"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/services/serverContracts/type.d.ts
|
|
2
|
+
/** The service contract names a server plugin provides and injects, keyed by level, as the manifest lists them. */
|
|
3
|
+
export interface ServerContractNames {
|
|
4
|
+
readonly provides: Readonly<Record<string, readonly string[]>>;
|
|
5
|
+
readonly injects: Readonly<Record<string, readonly string[]>>;
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//# sourceMappingURL=type.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.mts","names":[],"sources":["../../../src/services/serverContracts/type.ts"],"mappings":";;iBACiB;WACN,UAAU,SAAS;WACnB,SAAS,SAAS"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../identity/index.cjs");let r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=[`global`,`workspace`,`session`],o=`apiContracts`,s=`src/exports/${o}.ts`,c=`./extensions/web`,l=`./dist/extensions/web.mjs`,u=`./extensions/native`,d=`./dist/extensions/native.mjs`,f=`./${t.GENERATED_DIR}/mcp.ts`;function p(e){let t=e.entries.filter(e=>e.side===`backend`);if(t.length===0)return[];let n=Math.min(...t.map(e=>a.indexOf(e.scope)));return a.slice(n)}function m(e,t){return e.entries.filter(e=>e.side===`frontend`&&e.platform===`native`==(t===`native`))}function h(e){let t=new Set(e.map(e=>e.scope));return a.filter(e=>t.has(e))}function g(e){return[...new Set(e.filter(e=>e.surface===`channel`).map(e=>n.toSnake(e.name)))].sort()}function _(e,t){let n={};for(let[a,o]of Object.entries(t)){if(a===`./package.json`||typeof o!=`object`||!o){n[a]=o;continue}let t=o,s=t.import??t.default,c=s?.endsWith(`.mjs`)===!0?`${s.slice(0,-4)}.d.mts`:void 0;n[a]=t.types===void 0&&c!==void 0&&r.default.existsSync(i.default.join(e,c))?{types:c,...t}:t}return n}function v(e){let{packageDir:n,graph:a,targets:f,pluginId:v}=e,y={...e.manifest};if(y.exports!==void 0&&typeof y.exports==`object`){let e=_(n,y.exports);delete e[`./extensions/pi`],f.includes(`web`)?e[c]={import:l}:delete e[c],f.includes(`native`)?e[u]={import:d}:delete e[u],y.exports=Object.fromEntries(Object.entries(e).sort(([e],[t])=>e===`./package.json`?1:t===`./package.json`?-1:e.localeCompare(t)))}if(delete y.pi,f.includes(`server`)){let
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../identity/index.cjs");let r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=[`global`,`workspace`,`session`],o=`apiContracts`,s=`src/exports/${o}.ts`,c=`./extensions/web`,l=`./dist/extensions/web.mjs`,u=`./extensions/native`,d=`./dist/extensions/native.mjs`,f=`./${t.GENERATED_DIR}/mcp.ts`;function p(e){let t=e.entries.filter(e=>e.side===`backend`);if(t.length===0)return[];let n=Math.min(...t.map(e=>a.indexOf(e.scope)));return a.slice(n)}function m(e,t){return e.entries.filter(e=>e.side===`frontend`&&e.platform===`native`==(t===`native`))}function h(e){let t=new Set(e.map(e=>e.scope));return a.filter(e=>t.has(e))}function g(e){return[...new Set(e.filter(e=>e.surface===`channel`).map(e=>n.toSnake(e.name)))].sort()}function _(e,t){let n={};for(let[a,o]of Object.entries(t)){if(a===`./package.json`||typeof o!=`object`||!o){n[a]=o;continue}let t=o,s=t.import??t.default,c=s?.endsWith(`.mjs`)===!0?`${s.slice(0,-4)}.d.mts`:void 0;n[a]=t.types===void 0&&c!==void 0&&r.default.existsSync(i.default.join(e,c))?{types:c,...t}:t}return n}function v(e){let{packageDir:n,graph:a,targets:f,pluginId:v}=e,y={...e.manifest};if(y.exports!==void 0&&typeof y.exports==`object`){let e=_(n,y.exports);delete e[`./extensions/pi`],f.includes(`web`)?e[c]={import:l}:delete e[c],f.includes(`native`)?e[u]={import:d}:delete e[u],y.exports=Object.fromEntries(Object.entries(e).sort(([e],[t])=>e===`./package.json`?1:t===`./package.json`?-1:e.localeCompare(t)))}if(delete y.pi,f.includes(`server`)){let c=r.default.existsSync(i.default.join(n,s))?{contracts:{entry:`./${s}`,dist:`./dist/${o}.mjs`}}:{},l=e.serverContracts?.provides??{},u=e.serverContracts?.injects??{};y.poServer={entry:`./${t.GENERATED_DIR}/server.ts`,dist:t.SERVER_DIST,scopes:p(a),...c,...Object.keys(l).length>0?{provides:l}:{},...Object.keys(u).length>0?{injects:u}:{}}}else delete y.poServer;if(f.includes(`web`)){let e=m(a,`web`);y.poWeb={pluginId:v,channels:g(e),client:l,scopes:h(e)}}else delete y.poWeb;if(f.includes(`native`)){let e=m(a,`native`);y.poNative={pluginId:v,channels:g(e),client:d,scopes:h(e)}}else delete y.poNative;return y}function y(e,n,r=[]){let i={...e};return n?i.poMcp={entry:f,dist:`./dist/extensions/mcp.mjs`,scopes:[`session`],...r.length===0?{}:{ui:{entry:`./${t.GENERATED_DIR}/mcp-ui.ts`,dist:`./dist/extensions/mcp-ui.mjs`,widgets:r}}}:delete i.poMcp,i}function b(e){let t=i.default.join(e.packageDir,`package.json`),n=`${JSON.stringify(v(e),null,2)}\n`;return r.default.readFileSync(t,`utf8`)!==n&&(r.default.writeFileSync(t,n),!0)}function x(e,t,n=[]){let a=i.default.join(e,`package.json`),o=JSON.parse(r.default.readFileSync(a,`utf8`)),s=`${JSON.stringify(y(o,t,n),null,2)}\n`;return r.default.readFileSync(a,`utf8`)!==s&&(r.default.writeFileSync(a,s),!0)}exports.syncManifest=v,exports.syncMcpManifest=y,exports.writeManifest=b,exports.writeMcpManifest=x;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|