@aglyn/aglyn 1.15.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/buy-now-pay-later.d.ts +45 -0
  3. package/src/lib/app-utils/buy-now-pay-later.js +68 -0
  4. package/src/lib/app-utils/buy-now-pay-later.js.map +1 -0
  5. package/src/lib/app-utils/contexts.d.ts +1 -0
  6. package/src/lib/app-utils/contexts.js +1 -0
  7. package/src/lib/app-utils/contexts.js.map +1 -1
  8. package/src/lib/app-utils/docs-help-sections.generated.js +2 -0
  9. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  10. package/src/lib/app-utils/docs-help.generated.d.ts +3 -3
  11. package/src/lib/app-utils/docs-help.generated.js +9 -0
  12. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  13. package/src/lib/app-utils/docs-index.generated.js +4 -4
  14. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  15. package/src/lib/app-utils/plan-entitlements.d.ts +127 -75
  16. package/src/lib/app-utils/plan-entitlements.js +120 -77
  17. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  18. package/src/lib/app-utils/plugin-bundle-checks.d.ts +14 -2
  19. package/src/lib/app-utils/plugin-bundle-checks.js +82 -7
  20. package/src/lib/app-utils/plugin-bundle-checks.js.map +1 -1
  21. package/src/lib/app-utils/plugin-connection-editor.d.ts +48 -0
  22. package/src/lib/app-utils/plugin-connection-editor.js +46 -0
  23. package/src/lib/app-utils/plugin-connection-editor.js.map +1 -0
  24. package/src/lib/app-utils/plugin-connection-record.d.ts +42 -0
  25. package/src/lib/app-utils/plugin-connection-record.js +48 -0
  26. package/src/lib/app-utils/plugin-connection-record.js.map +1 -0
  27. package/src/lib/app-utils/plugin-connection-records-context.d.ts +23 -0
  28. package/src/lib/app-utils/plugin-connection-records-context.js +29 -0
  29. package/src/lib/app-utils/plugin-connection-records-context.js.map +1 -0
  30. package/src/lib/app-utils/plugin-connection-records.d.ts +42 -0
  31. package/src/lib/app-utils/plugin-connection-records.js +56 -0
  32. package/src/lib/app-utils/plugin-connection-records.js.map +1 -0
  33. package/src/lib/app-utils/plugin-connections.d.ts +320 -0
  34. package/src/lib/app-utils/plugin-connections.js +895 -0
  35. package/src/lib/app-utils/plugin-connections.js.map +1 -0
  36. package/src/lib/app-utils/plugin-elements.d.ts +104 -0
  37. package/src/lib/app-utils/plugin-elements.js +128 -0
  38. package/src/lib/app-utils/plugin-elements.js.map +1 -0
  39. package/src/lib/app-utils/plugin-manifest.d.ts +20 -75
  40. package/src/lib/app-utils/plugin-manifest.js +65 -100
  41. package/src/lib/app-utils/plugin-manifest.js.map +1 -1
  42. package/src/lib/app-utils/realm-elements-context.d.ts +16 -0
  43. package/src/lib/app-utils/realm-elements-context.js +16 -0
  44. package/src/lib/app-utils/realm-elements-context.js.map +1 -1
  45. package/src/lib/app-utils/realm-host-surface.generated.js +1 -0
  46. package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
  47. package/src/lib/app-utils/release-flags.d.ts +1 -1
  48. package/src/lib/app-utils/release-flags.js +11 -0
  49. package/src/lib/app-utils/release-flags.js.map +1 -1
  50. package/src/lib/app-utils/server.d.ts +1 -0
  51. package/src/lib/app-utils/server.js +2 -0
  52. package/src/lib/app-utils/server.js.map +1 -1
  53. package/src/lib/plugin-manager/feature-plugins.d.ts +25 -0
  54. package/src/lib/plugin-manager/feature-plugins.js +10 -0
  55. package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
  56. package/src/lib/plugin-manager/first-party-plugins.generated.js +11 -0
  57. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  58. package/src/lib/plugin-manager/index.d.ts +1 -0
  59. package/src/lib/plugin-manager/index.js +1 -0
  60. package/src/lib/plugin-manager/index.js.map +1 -1
  61. package/src/lib/plugin-manager/plugin-artifact-inventory.d.ts +5 -0
  62. package/src/lib/plugin-manager/plugin-artifact-inventory.js.map +1 -1
  63. package/src/lib/plugin-manager/plugin-site-csp.d.ts +36 -0
  64. package/src/lib/plugin-manager/plugin-site-csp.js +50 -1
  65. package/src/lib/plugin-manager/plugin-site-csp.js.map +1 -1
  66. package/src/lib/plugin-manager/realm-host-aglyn.generated.js +61 -59
  67. package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
  68. package/src/lib/plugin-manager/site-page-enricher-services.d.ts +35 -0
  69. package/src/lib/plugin-manager/site-page-enricher-services.js +35 -0
  70. package/src/lib/plugin-manager/site-page-enricher-services.js.map +1 -0
  71. package/src/lib/plugin-manager/site-page-hooks.js +16 -3
  72. package/src/lib/plugin-manager/site-page-hooks.js.map +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/plugin-connections.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * DECLARED CONNECTIONS: THE MANIFEST'S `connections` BLOCK (AGL-4193).\n *\n * A marketplace plugin's code runs in a sandbox, never on the platform's\n * servers, so it cannot hold an OAuth grant, refresh it, or call a provider's\n * API on a schedule. A connection is the plugin DECLARING all of that as data\n * instead: which provider to send the site owner to, which hosts the platform\n * may call with the grant, how the owner picks what to connect (an account,\n * then one of its locations), and how a scheduled fetch maps the provider's\n * answer into a small, typed, public record the plugin's element then reads.\n * The platform runs the OAuth dance with the publisher's own OAuth app, keeps\n * the tokens sealed, and makes every request itself. Third-party code never\n * sees a token.\n *\n * Everything here is publisher-authored data that the platform turns into\n * outbound requests carrying a customer's token, so it is bounded hard:\n *\n * - every URL is https, with no credentials, query or fragment where none\n * belongs, and never an IP literal or `localhost`;\n * - every request a template describes must land on a host the connection\n * lists in `apiHosts`, checked again after the template is filled in;\n * - a wildcard host covers exactly ONE label (`*.example.com`);\n * - every list, string, page count and record has a ceiling.\n *\n * Pure: no Node, no Firestore, no React. The manifest validator, the bundle\n * checker (and the local CLI built from it), the connect routes and the sync\n * all read this one module, so a declaration cannot pass one and fail another.\n */\n\nimport type { HostVariable, HostVariableType } from './variables'\n\n/** A request method a template may use. */\nexport type PluginConnectionMethod = 'GET' | 'POST'\n\n/** How the platform authenticates the publisher's OAuth app at the token endpoint. */\nexport type PluginConnectionTokenAuthMethod = 'body' | 'basic'\n\n/** Cursor pagination: the answer names the next page's cursor, a query parameter carries it back. */\nexport interface PluginConnectionPagination {\n /** Dot path, in the answer, to the next page's cursor (`nextPageToken`). */\n cursorPath: string\n /** The query parameter the cursor is sent back in (`pageToken`). */\n cursorParam: string\n /** Pages fetched at most, 1 to {@link PLUGIN_CONNECTION_MAX_PAGES}. */\n maxPages: number\n}\n\n/**\n * One request the platform makes with a connection's token.\n *\n * `url`, every `query` value and every string `body` value may carry\n * `{{resource.<id>}}`, filled with the id the site owner chose for that\n * resource. Placeholders may appear in the path and the query only, never in\n * the scheme or the host, and the filled-in URL is checked against\n * `apiHosts` again before anything is sent.\n */\nexport interface PluginConnectionRequest {\n method: PluginConnectionMethod\n url: string\n query?: Record<string, string>\n /** A flat JSON body, POST only. */\n body?: Record<string, string | number | boolean>\n /** Dot path to the array of items in the answer. */\n itemsPath?: string\n pagination?: PluginConnectionPagination\n}\n\n/**\n * Something the site owner picks after connecting: an account, a location.\n * Resources are ordered, and a later one's request may name an earlier one's\n * choice (`{{resource.accounts}}`), which is how a picker chains.\n */\nexport interface PluginConnectionResource {\n /** Identifier, unique within the connection (`accounts`). */\n id: string\n /** What one of them is called in the picker (`Account`). */\n label: string\n /** The list request. `itemsPath` is required. */\n request: PluginConnectionRequest & { itemsPath: string }\n /** Dot path, in each item, to its id (`name`). */\n idPath: string\n /** Dot path, in each item, to what the picker shows (`accountName`). */\n labelPath: string\n /** Items listed at most, across every page. */\n maxItems: number\n}\n\n/** The type a record field is coerced to. */\nexport type PluginConnectionFieldType = 'string' | 'number' | 'boolean' | 'datetime' | 'url'\n\n/** One field of the public record, read from an answer by path. */\nexport interface PluginConnectionRecordField {\n type: PluginConnectionFieldType\n /** Dot path to the value: in the request's answer, or in an item. */\n path: string\n /** Required for `string` and `url`: the value is cut to this many characters. */\n maxLength?: number\n /**\n * Values to translate before coercion (`{ \"FIVE\": 5 }`). A value not in\n * the map is dropped, so a provider adding a value cannot leak it raw.\n */\n map?: Record<string, string | number | boolean>\n}\n\n/** A summary field of the record: which sync request it reads from, and where. */\nexport interface PluginConnectionSummaryField extends PluginConnectionRecordField {\n /** The sync request id whose answer holds it. */\n request: string\n}\n\n/** The record's list: one entry per item of a sync request's answer. */\nexport interface PluginConnectionRecordItems {\n /** The sync request whose `itemsPath` items become entries. */\n request: string\n /** Entries kept at most. */\n maxItems: number\n /** Fields of each entry, read relative to the item. */\n fields: Record<string, PluginConnectionRecordField>\n}\n\n/**\n * The PUBLIC record a sync writes for a site: what the plugin's element reads.\n * Public by design, so nothing in it may be secret, and it is typed and\n * bounded so the record can never grow past what was declared.\n */\nexport interface PluginConnectionRecordSchema {\n fields?: Record<string, PluginConnectionSummaryField>\n items?: PluginConnectionRecordItems\n}\n\n/** A sync request: a request with an id the record schema names it by. */\nexport interface PluginConnectionSyncRequest extends PluginConnectionRequest {\n id: string\n}\n\n/** The scheduled fetch the platform runs for every connected site. */\nexport interface PluginConnectionSync {\n /** Hours between runs, at least {@link PLUGIN_CONNECTION_MIN_INTERVAL_HOURS}. */\n intervalHours: number\n requests: PluginConnectionSyncRequest[]\n record: PluginConnectionRecordSchema\n}\n\n/** One declared connection. */\nexport interface PluginConnectionDeclaration {\n /** Identifier, unique within the manifest; persisted, never renamed. */\n id: string\n /** The provider's id (`google`); a label for people and logs, never a code path. */\n provider: string\n /** What the console calls it (`Google Business Profile`). */\n label: string\n description?: string\n authorizationUrl: string\n tokenUrl: string\n /** Where a grant is revoked on disconnect, when the provider has one. */\n revocationUrl?: string\n scopes: string[]\n /** How scopes are joined in the authorization request; a space by default. */\n scopeSeparator?: ' ' | ','\n /** Extra authorization parameters (`access_type=offline`). Reserved names are refused. */\n authParams?: Record<string, string>\n /** `body` (client_secret_post, the default) or `basic` (client_secret_basic). */\n tokenAuthMethod?: PluginConnectionTokenAuthMethod\n /** The hosts the platform may call with this connection's token. */\n apiHosts: string[]\n resources?: PluginConnectionResource[]\n sync?: PluginConnectionSync\n}\n\n/* ------------------------------------------------------------------ */\n/* Bounds */\n/* ------------------------------------------------------------------ */\n\nexport const PLUGIN_CONNECTION_MAX = 4\nexport const PLUGIN_CONNECTION_ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/\nexport const PLUGIN_CONNECTION_MAX_SCOPES = 20\nexport const PLUGIN_CONNECTION_MAX_API_HOSTS = 10\nexport const PLUGIN_CONNECTION_MAX_AUTH_PARAMS = 10\nexport const PLUGIN_CONNECTION_MAX_RESOURCES = 3\nexport const PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS = 200\nexport const PLUGIN_CONNECTION_MAX_SYNC_REQUESTS = 3\nexport const PLUGIN_CONNECTION_MAX_PAGES = 10\nexport const PLUGIN_CONNECTION_MIN_INTERVAL_HOURS = 1\nexport const PLUGIN_CONNECTION_MAX_INTERVAL_HOURS = 168\nexport const PLUGIN_CONNECTION_MAX_RECORD_FIELDS = 20\nexport const PLUGIN_CONNECTION_MAX_RECORD_ITEMS = 100\nexport const PLUGIN_CONNECTION_MAX_STRING_LENGTH = 5000\nexport const PLUGIN_CONNECTION_MAX_URL_LENGTH = 2048\nexport const PLUGIN_CONNECTION_MAX_MAP_ENTRIES = 32\n/** The whole block, serialized: a ceiling on everything the lists above multiply to. */\nexport const PLUGIN_CONNECTION_MAX_DECLARATION_CHARS = 32_000\n/**\n * `capabilities.imageHosts`, at most (AGL-4195). Each one widens the `img-src`\n * of every site that installs the plugin, so the list is kept short.\n */\nexport const PLUGIN_MAX_IMAGE_HOSTS = 5\n\nconst TEXT_MAX = 300\nconst LABEL_MAX = 80\nconst IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]{0,31}$/\nconst PATH_SEGMENT = /^[A-Za-z0-9_$-]{1,64}$/\nconst PATH_MAX_SEGMENTS = 8\nconst SCOPE = /^[!#-[\\]-~]{1,200}$/\nconst PARAM_NAME = /^[A-Za-z0-9_.-]{1,40}$/\nconst PARAM_VALUE_MAX = 200\nconst TEMPLATE_VALUE_MAX = 500\nconst BODY_MAX_KEYS = 20\nconst QUERY_MAX_KEYS = 10\nconst HOST_LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/\nconst PLACEHOLDER = /\\{\\{\\s*([^{}]*?)\\s*\\}\\}/g\nconst RESOURCE_PLACEHOLDER = /^resource\\.([A-Za-z][A-Za-z0-9_]{0,31})$/\nconst FIELD_TYPES: readonly PluginConnectionFieldType[] = ['string', 'number', 'boolean', 'datetime', 'url']\n\n/**\n * Authorization parameters the platform sets itself. A declaration naming one\n * would replace the platform's own client id, redirect, state or scope.\n */\nexport const PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS: readonly string[] = [\n 'client_id',\n 'client_secret',\n 'redirect_uri',\n 'response_type',\n 'state',\n 'scope',\n 'code',\n 'code_challenge',\n 'code_challenge_method',\n 'nonce',\n]\n\n/* ------------------------------------------------------------------ */\n/* Hosts and URLs */\n/* ------------------------------------------------------------------ */\n\nconst isIpLiteral = (hostname: string): boolean =>\n /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(':') || hostname.startsWith('[')\n\n/**\n * Whether `hostname` is a usable public hostname: lowercase labels, at least two\n * of them, no IP literal, no `localhost`.\n */\nfunction isPublicHostname(hostname: string): boolean {\n if (!hostname || hostname.length > 253 || isIpLiteral(hostname)) return false\n const labels = hostname.split('.')\n if (labels.length < 2) return false\n if (labels.some((label) => !HOST_LABEL.test(label))) return false\n const tld = labels[labels.length - 1]\n if (/^\\d+$/.test(tld)) return false\n return !(hostname === 'localhost' || hostname.endsWith('.localhost') || tld === 'local' || tld === 'internal')\n}\n\n/**\n * A host pattern: an exact public hostname (`api.example.com`), or one whose\n * first label is a lone `*` over at least two more labels (`*.example.com`).\n * Anything wider — `*.com`, `*.*.example.com`, `*api.example.com` — is refused.\n */\nexport function isPluginConnectionHostPattern(value: unknown): value is string {\n if (typeof value !== 'string') return false\n if (value !== value.toLowerCase()) return false\n if (value.startsWith('*.')) {\n const rest = value.slice(2)\n return !rest.includes('*') && isPublicHostname(rest) && rest.split('.').length >= 2\n }\n return !value.includes('*') && isPublicHostname(value)\n}\n\n/** Whether `hostname` is covered by `pattern` (exact, or a one-label wildcard). */\nexport function pluginConnectionHostMatches(pattern: string, hostname: string): boolean {\n const candidate = hostname.toLowerCase()\n if (!pattern.startsWith('*.')) return candidate === pattern\n const rest = pattern.slice(1) // `.example.com`\n if (!candidate.endsWith(rest)) return false\n const label = candidate.slice(0, candidate.length - rest.length)\n return HOST_LABEL.test(label)\n}\n\n/** Whether a URL may be called with a connection's token: https, on a listed host, no credentials. */\nexport function isPluginConnectionUrlAllowed(url: string, apiHosts: readonly string[]): boolean {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return false\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.port) return false\n if (parsed.hash) return false\n return apiHosts.some((pattern) => pluginConnectionHostMatches(pattern, parsed.hostname))\n}\n\n/** An OAuth endpoint: https, a public host, no credentials, port, query or fragment. */\nfunction endpointError(value: unknown, name: string): string | null {\n if (typeof value !== 'string' || !value || value.length > PLUGIN_CONNECTION_MAX_URL_LENGTH) {\n return `${name} must be an https URL`\n }\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n return `${name} must be an https URL`\n }\n if (parsed.protocol !== 'https:') return `${name} must be an https URL`\n if (parsed.username || parsed.password || parsed.port) return `${name} must not carry credentials or a port`\n if (parsed.search || parsed.hash || value.includes('?') || value.includes('#')) {\n return `${name} must not carry a query or fragment (declare authorization parameters in authParams)`\n }\n if (!isPublicHostname(parsed.hostname)) return `${name} must name a public host`\n if (value.includes('{{')) return `${name} must not carry placeholders`\n return null\n}\n\n/** The host of an endpoint URL already validated, for the bundle checker. */\nexport function pluginConnectionEndpointHosts(connection: PluginConnectionDeclaration): string[] {\n const hosts = new Set<string>()\n for (const url of [connection.authorizationUrl, connection.tokenUrl, connection.revocationUrl]) {\n if (!url) continue\n try {\n hosts.add(new URL(url).hostname)\n } catch {\n // Validated already; nothing to add.\n }\n }\n return [...hosts]\n}\n\n/* ------------------------------------------------------------------ */\n/* Paths and templates */\n/* ------------------------------------------------------------------ */\n\n/** Whether `value` is a dot path of plain segments (`reviewer.displayName`, `items.0.id`). */\nexport function isPluginConnectionPath(value: unknown): value is string {\n if (typeof value !== 'string' || !value) return false\n const segments = value.split('.')\n return segments.length <= PATH_MAX_SEGMENTS && segments.every((segment) => PATH_SEGMENT.test(segment))\n}\n\n/**\n * Reads a dot path out of a parsed JSON answer. Own properties only, so a\n * path can never reach `__proto__` or anything else an object inherits.\n */\nexport function readPluginConnectionPath(source: unknown, path: string): unknown {\n let current: unknown = source\n for (const segment of path.split('.')) {\n if (current === null || current === undefined) return undefined\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) return undefined\n current = current[Number(segment)]\n continue\n }\n if (typeof current !== 'object') return undefined\n if (!Object.prototype.hasOwnProperty.call(current, segment)) return undefined\n current = (current as Record<string, unknown>)[segment]\n }\n return current\n}\n\n/** The resource ids a template string names, or an error for any other placeholder. */\nfunction templateRefs(value: string): { refs: string[] } | { error: string } {\n const refs: string[] = []\n for (const match of value.matchAll(PLACEHOLDER)) {\n const inner = match[1] ?? ''\n const resource = RESOURCE_PLACEHOLDER.exec(inner)\n if (!resource) return { error: `unknown placeholder \"{{${inner}}}\" (only {{resource.<id>}} is filled in)` }\n refs.push(resource[1])\n }\n // A brace left over is a placeholder that did not parse.\n const stripped = value.replace(PLACEHOLDER, '')\n if (stripped.includes('{{') || stripped.includes('}}')) return { error: 'a placeholder is not closed' }\n return { refs }\n}\n\n/**\n * A choice a site owner made, safe to put in a URL path or query: printable,\n * no `..`, nothing that could end the path or start a query, fragment,\n * credential or percent-escape.\n */\nexport function isPluginConnectionChoiceId(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n /^[A-Za-z0-9._~:/-]{1,256}$/.test(value) &&\n !value.split('/').some((segment) => segment === '..' || segment === '.') &&\n !value.startsWith('/') &&\n !value.includes('//')\n )\n}\n\n/** A filled-in request, ready to send. */\nexport interface PluginConnectionPreparedRequest {\n method: PluginConnectionMethod\n url: string\n body?: string\n}\n\nexport type PluginConnectionTemplateResult =\n | { ok: true; request: PluginConnectionPreparedRequest }\n | { ok: false; error: string }\n\n/**\n * Fills a request template with the site's choices and the page cursor, and\n * refuses a result that would leave `apiHosts`. The ONE way a template becomes\n * a request: the connect routes' resource picker and the scheduled sync both\n * call it, so the host check cannot be skipped by either.\n */\nexport function preparePluginConnectionRequest(\n request: PluginConnectionRequest,\n options: {\n apiHosts: readonly string[]\n choices: Readonly<Record<string, string>>\n cursor?: string | null\n },\n): PluginConnectionTemplateResult {\n const fill = (value: string): string | null => {\n let missing = false\n const out = value.replace(PLACEHOLDER, (_whole, inner: string) => {\n const resource = RESOURCE_PLACEHOLDER.exec(String(inner).trim())\n const choice = resource ? options.choices[resource[1]] : undefined\n if (!isPluginConnectionChoiceId(choice)) {\n missing = true\n return ''\n }\n return choice\n })\n return missing ? null : out\n }\n const url = fill(request.url)\n if (url === null) return { ok: false, error: 'a choice this request needs has not been made' }\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return { ok: false, error: 'the request URL is not valid' }\n }\n for (const [key, value] of Object.entries(request.query ?? {})) {\n const filled = fill(value)\n if (filled === null) return { ok: false, error: 'a choice this request needs has not been made' }\n parsed.searchParams.set(key, filled)\n }\n if (options.cursor && request.pagination) {\n parsed.searchParams.set(request.pagination.cursorParam, options.cursor)\n }\n const finalUrl = parsed.toString()\n if (!isPluginConnectionUrlAllowed(finalUrl, options.apiHosts)) {\n return { ok: false, error: 'the request would leave the connection’s declared hosts' }\n }\n if (request.method === 'GET' || !request.body) {\n return { ok: true, request: { method: request.method, url: finalUrl } }\n }\n const body: Record<string, string | number | boolean> = {}\n for (const [key, value] of Object.entries(request.body)) {\n if (typeof value !== 'string') {\n body[key] = value\n continue\n }\n const filled = fill(value)\n if (filled === null) return { ok: false, error: 'a choice this request needs has not been made' }\n body[key] = filled\n }\n return { ok: true, request: { method: request.method, url: finalUrl, body: JSON.stringify(body) } }\n}\n\n/* ------------------------------------------------------------------ */\n/* Validation */\n/* ------------------------------------------------------------------ */\n\ntype Verdict<T> = { ok: true; value: T } | { ok: false; error: string }\n\nconst fail = (error: string): { ok: false; error: string } => ({ ok: false, error })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst boundedText = (value: unknown, max: number): string | null =>\n typeof value === 'string' && value.trim() && value.trim().length <= max ? value.trim() : null\n\nconst intIn = (value: unknown, min: number, max: number): number | null =>\n typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max ? value : null\n\n/** The host part of a template URL, before any placeholder could appear. */\nfunction templateUrlError(url: unknown, apiHosts: readonly string[], where: string): string | null {\n if (typeof url !== 'string' || !url || url.length > PLUGIN_CONNECTION_MAX_URL_LENGTH) {\n return `${where}: url must be an https URL`\n }\n const authorityEnd = url.indexOf('/', 'https://'.length)\n const head = authorityEnd === -1 ? url : url.slice(0, authorityEnd)\n if (!url.startsWith('https://')) return `${where}: url must be an https URL`\n if (head.includes('{{') || head.includes('@')) return `${where}: url must name its host literally`\n if (url.includes('#')) return `${where}: url must not carry a fragment`\n // Placeholders replaced with a harmless id to judge the URL's shape.\n const probe = url.replace(PLACEHOLDER, 'x')\n if (!isPluginConnectionUrlAllowed(probe, apiHosts)) {\n return `${where}: url must be on one of the connection's apiHosts`\n }\n return null\n}\n\nfunction validatePagination(raw: unknown, where: string): Verdict<PluginConnectionPagination | undefined> {\n if (raw === undefined) return { ok: true, value: undefined }\n if (!isRecord(raw)) return fail(`${where}: pagination must be an object`)\n if (!isPluginConnectionPath(raw['cursorPath'])) return fail(`${where}: pagination.cursorPath must be a dot path`)\n if (typeof raw['cursorParam'] !== 'string' || !PARAM_NAME.test(raw['cursorParam'])) {\n return fail(`${where}: pagination.cursorParam must be a query parameter name`)\n }\n const maxPages = intIn(raw['maxPages'], 1, PLUGIN_CONNECTION_MAX_PAGES)\n if (maxPages === null) {\n return fail(`${where}: pagination.maxPages must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_PAGES}`)\n }\n return {\n ok: true,\n value: { cursorPath: raw['cursorPath'], cursorParam: raw['cursorParam'], maxPages },\n }\n}\n\nfunction validateRequest(\n raw: unknown,\n where: string,\n context: { apiHosts: readonly string[]; resourceIds: readonly string[]; requireItems: boolean },\n): Verdict<PluginConnectionRequest> {\n if (!isRecord(raw)) return fail(`${where} must be an object`)\n const method = raw['method'] ?? 'GET'\n if (method !== 'GET' && method !== 'POST') return fail(`${where}: method must be GET or POST`)\n const urlError = templateUrlError(raw['url'], context.apiHosts, where)\n if (urlError) return fail(urlError)\n const url = raw['url'] as string\n const refs: string[] = []\n const collect = (value: string, label: string): string | null => {\n if (value.length > TEMPLATE_VALUE_MAX && label !== 'url') return `${where}: ${label} is too long`\n const parsed = templateRefs(value)\n if ('error' in parsed) return `${where}: ${label} has an ${parsed.error}`\n refs.push(...parsed.refs)\n return null\n }\n const urlRefs = collect(url, 'url')\n if (urlRefs) return fail(urlRefs)\n\n let query: Record<string, string> | undefined\n if (raw['query'] !== undefined) {\n if (!isRecord(raw['query'])) return fail(`${where}: query must be an object of strings`)\n const entries = Object.entries(raw['query'])\n if (entries.length > QUERY_MAX_KEYS) return fail(`${where}: query names too many parameters`)\n query = {}\n for (const [key, value] of entries) {\n if (!PARAM_NAME.test(key) || typeof value !== 'string') {\n return fail(`${where}: query must be an object of strings`)\n }\n const error = collect(value, `query.${key}`)\n if (error) return fail(error)\n query[key] = value\n }\n }\n\n let body: Record<string, string | number | boolean> | undefined\n if (raw['body'] !== undefined) {\n if (method !== 'POST') return fail(`${where}: only a POST request has a body`)\n if (!isRecord(raw['body'])) return fail(`${where}: body must be a flat object`)\n const entries = Object.entries(raw['body'])\n if (entries.length > BODY_MAX_KEYS) return fail(`${where}: body has too many fields`)\n body = {}\n for (const [key, value] of entries) {\n if (!PARAM_NAME.test(key)) return fail(`${where}: body field \"${key}\" is not a plain name`)\n if (typeof value === 'string') {\n const error = collect(value, `body.${key}`)\n if (error) return fail(error)\n body[key] = value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n body[key] = value\n } else if (typeof value === 'boolean') {\n body[key] = value\n } else {\n return fail(`${where}: body must be a flat object of strings, numbers and booleans`)\n }\n }\n }\n\n for (const ref of refs) {\n if (!context.resourceIds.includes(ref)) {\n return fail(`${where}: {{resource.${ref}}} names no resource declared before it`)\n }\n }\n\n let itemsPath: string | undefined\n if (raw['itemsPath'] !== undefined) {\n if (!isPluginConnectionPath(raw['itemsPath'])) return fail(`${where}: itemsPath must be a dot path`)\n itemsPath = raw['itemsPath']\n } else if (context.requireItems) {\n return fail(`${where}: itemsPath is required`)\n }\n const pagination = validatePagination(raw['pagination'], where)\n if (pagination.ok === false) return pagination\n if (pagination.value && !itemsPath) return fail(`${where}: a paginated request needs an itemsPath`)\n\n return {\n ok: true,\n value: {\n method,\n url,\n ...(query && Object.keys(query).length ? { query } : {}),\n ...(body ? { body } : {}),\n ...(itemsPath ? { itemsPath } : {}),\n ...(pagination.value ? { pagination: pagination.value } : {}),\n },\n }\n}\n\nfunction validateField(\n raw: unknown,\n where: string,\n): Verdict<PluginConnectionRecordField> {\n if (!isRecord(raw)) return fail(`${where} must be an object`)\n const type = raw['type']\n if (!FIELD_TYPES.includes(type as PluginConnectionFieldType)) {\n return fail(`${where}: type must be one of ${FIELD_TYPES.join(', ')}`)\n }\n if (!isPluginConnectionPath(raw['path'])) return fail(`${where}: path must be a dot path`)\n const field: PluginConnectionRecordField = { type: type as PluginConnectionFieldType, path: raw['path'] }\n if (type === 'string' || type === 'url') {\n const ceiling = type === 'url' ? PLUGIN_CONNECTION_MAX_URL_LENGTH : PLUGIN_CONNECTION_MAX_STRING_LENGTH\n const maxLength = intIn(raw['maxLength'], 1, ceiling)\n if (maxLength === null) return fail(`${where}: maxLength is required, a whole number from 1 to ${ceiling}`)\n field.maxLength = maxLength\n } else if (raw['maxLength'] !== undefined) {\n return fail(`${where}: only a string or url field has a maxLength`)\n }\n if (raw['map'] !== undefined) {\n if (!isRecord(raw['map'])) return fail(`${where}: map must be an object`)\n const entries = Object.entries(raw['map'])\n if (!entries.length || entries.length > PLUGIN_CONNECTION_MAX_MAP_ENTRIES) {\n return fail(`${where}: map must have 1 to ${PLUGIN_CONNECTION_MAX_MAP_ENTRIES} entries`)\n }\n const map: Record<string, string | number | boolean> = {}\n for (const [key, value] of entries) {\n if (key.length > 100) return fail(`${where}: a map key is too long`)\n if (typeof value === 'string' && value.length <= 200) map[key] = value\n else if (typeof value === 'number' && Number.isFinite(value)) map[key] = value\n else if (typeof value === 'boolean') map[key] = value\n else return fail(`${where}: map values must be short strings, numbers or booleans`)\n }\n field.map = map\n }\n return { ok: true, value: field }\n}\n\nfunction validateFieldSet<T>(\n raw: unknown,\n where: string,\n each: (value: unknown, at: string) => Verdict<T>,\n required: boolean,\n): Verdict<Record<string, T> | undefined> {\n if (raw === undefined) return required ? fail(`${where} is required`) : { ok: true, value: undefined }\n if (!isRecord(raw)) return fail(`${where} must be an object`)\n const entries = Object.entries(raw)\n if ((required && !entries.length) || entries.length > PLUGIN_CONNECTION_MAX_RECORD_FIELDS) {\n return fail(`${where} must name 1 to ${PLUGIN_CONNECTION_MAX_RECORD_FIELDS} fields`)\n }\n const out: Record<string, T> = {}\n for (const [name, value] of entries) {\n if (!IDENTIFIER.test(name)) return fail(`${where}: \"${name}\" is not a plain field name`)\n const verdict = each(value, `${where}.${name}`)\n if (verdict.ok === false) return verdict\n out[name] = verdict.value\n }\n return { ok: true, value: out }\n}\n\nfunction validateSync(\n raw: unknown,\n where: string,\n context: { apiHosts: readonly string[]; resourceIds: readonly string[] },\n): Verdict<PluginConnectionSync | undefined> {\n if (raw === undefined) return { ok: true, value: undefined }\n if (!isRecord(raw)) return fail(`${where} must be an object`)\n const intervalHours = intIn(raw['intervalHours'], PLUGIN_CONNECTION_MIN_INTERVAL_HOURS, PLUGIN_CONNECTION_MAX_INTERVAL_HOURS)\n if (intervalHours === null) {\n return fail(\n `${where}: intervalHours must be a whole number from ${PLUGIN_CONNECTION_MIN_INTERVAL_HOURS} to ${PLUGIN_CONNECTION_MAX_INTERVAL_HOURS}`,\n )\n }\n const requestsRaw = raw['requests']\n if (!Array.isArray(requestsRaw) || !requestsRaw.length || requestsRaw.length > PLUGIN_CONNECTION_MAX_SYNC_REQUESTS) {\n return fail(`${where}: requests must list 1 to ${PLUGIN_CONNECTION_MAX_SYNC_REQUESTS} requests`)\n }\n const requests: PluginConnectionSyncRequest[] = []\n for (const [index, entry] of requestsRaw.entries()) {\n const at = `${where}.requests[${index}]`\n if (!isRecord(entry) || typeof entry['id'] !== 'string' || !IDENTIFIER.test(entry['id'])) {\n return fail(`${at}: id must be a plain identifier`)\n }\n if (requests.some((request) => request.id === entry['id'])) return fail(`${at}: id \"${entry['id']}\" is used twice`)\n const verdict = validateRequest(entry, at, { ...context, requireItems: false })\n if (verdict.ok === false) return verdict\n requests.push({ id: entry['id'], ...verdict.value })\n }\n const recordRaw = raw['record']\n if (!isRecord(recordRaw)) return fail(`${where}: record must be an object`)\n const requestIds = requests.map((request) => request.id)\n const fields = validateFieldSet<PluginConnectionSummaryField>(\n recordRaw['fields'],\n `${where}.record.fields`,\n (value, at) => {\n if (!isRecord(value) || typeof value['request'] !== 'string' || !requestIds.includes(value['request'])) {\n return fail(`${at}: request must name one of the sync requests`)\n }\n const field = validateField(value, at)\n if (field.ok === false) return field\n return { ok: true, value: { request: value['request'], ...field.value } }\n },\n false,\n )\n if (fields.ok === false) return fields\n let items: PluginConnectionRecordItems | undefined\n if (recordRaw['items'] !== undefined) {\n const itemsRaw = recordRaw['items']\n const at = `${where}.record.items`\n if (!isRecord(itemsRaw)) return fail(`${at} must be an object`)\n const source = requests.find((request) => request.id === itemsRaw['request'])\n if (!source) return fail(`${at}: request must name one of the sync requests`)\n if (!source.itemsPath) return fail(`${at}: request \"${source.id}\" declares no itemsPath`)\n const maxItems = intIn(itemsRaw['maxItems'], 1, PLUGIN_CONNECTION_MAX_RECORD_ITEMS)\n if (maxItems === null) return fail(`${at}: maxItems must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_RECORD_ITEMS}`)\n const itemFields = validateFieldSet(itemsRaw['fields'], `${at}.fields`, validateField, true)\n if (itemFields.ok === false) return itemFields\n items = { request: source.id, maxItems, fields: itemFields.value ?? {} }\n }\n if (!fields.value && !items) return fail(`${where}: record must declare fields, items or both`)\n return {\n ok: true,\n value: {\n intervalHours,\n requests,\n record: { ...(fields.value ? { fields: fields.value } : {}), ...(items ? { items } : {}) },\n },\n }\n}\n\n/** Validates one connection. */\nexport function validatePluginConnection(raw: unknown, where = 'connection'): Verdict<PluginConnectionDeclaration> {\n if (!isRecord(raw)) return fail(`${where} must be an object`)\n const id = raw['id']\n if (typeof id !== 'string' || !PLUGIN_CONNECTION_ID_PATTERN.test(id)) {\n return fail(`${where}: id must be lowercase letters, digits and dashes (2 to 32)`)\n }\n const at = `connection \"${id}\"`\n const provider = raw['provider']\n if (typeof provider !== 'string' || !PLUGIN_CONNECTION_ID_PATTERN.test(provider)) {\n return fail(`${at}: provider must be lowercase letters, digits and dashes (2 to 32)`)\n }\n const label = boundedText(raw['label'], LABEL_MAX)\n if (!label) return fail(`${at}: label is required (at most ${LABEL_MAX} characters)`)\n let description: string | undefined\n if (raw['description'] !== undefined) {\n const text = boundedText(raw['description'], TEXT_MAX)\n if (!text) return fail(`${at}: description must be at most ${TEXT_MAX} characters`)\n description = text\n }\n for (const name of ['authorizationUrl', 'tokenUrl'] as const) {\n const error = endpointError(raw[name], name)\n if (error) return fail(`${at}: ${error}`)\n }\n if (raw['revocationUrl'] !== undefined) {\n const error = endpointError(raw['revocationUrl'], 'revocationUrl')\n if (error) return fail(`${at}: ${error}`)\n }\n const scopesRaw = raw['scopes']\n if (!Array.isArray(scopesRaw) || !scopesRaw.length || scopesRaw.length > PLUGIN_CONNECTION_MAX_SCOPES) {\n return fail(`${at}: scopes must list 1 to ${PLUGIN_CONNECTION_MAX_SCOPES} scopes`)\n }\n if (scopesRaw.some((scope) => typeof scope !== 'string' || !SCOPE.test(scope) || scope.includes(','))) {\n return fail(`${at}: a scope must be printable, with no spaces or commas`)\n }\n const scopeSeparator = raw['scopeSeparator']\n if (scopeSeparator !== undefined && scopeSeparator !== ' ' && scopeSeparator !== ',') {\n return fail(`${at}: scopeSeparator must be a space or a comma`)\n }\n let authParams: Record<string, string> | undefined\n if (raw['authParams'] !== undefined) {\n if (!isRecord(raw['authParams'])) return fail(`${at}: authParams must be an object of strings`)\n const entries = Object.entries(raw['authParams'])\n if (entries.length > PLUGIN_CONNECTION_MAX_AUTH_PARAMS) return fail(`${at}: authParams names too many parameters`)\n authParams = {}\n for (const [key, value] of entries) {\n if (!PARAM_NAME.test(key) || typeof value !== 'string' || value.length > PARAM_VALUE_MAX) {\n return fail(`${at}: authParams must be an object of short strings`)\n }\n if (PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS.includes(key.toLowerCase())) {\n return fail(`${at}: authParams may not set \"${key}\", which the platform sets itself`)\n }\n authParams[key] = value\n }\n }\n const tokenAuthMethod = raw['tokenAuthMethod']\n if (tokenAuthMethod !== undefined && tokenAuthMethod !== 'body' && tokenAuthMethod !== 'basic') {\n return fail(`${at}: tokenAuthMethod must be \"body\" or \"basic\"`)\n }\n const apiHostsRaw = raw['apiHosts']\n if (!Array.isArray(apiHostsRaw) || !apiHostsRaw.length || apiHostsRaw.length > PLUGIN_CONNECTION_MAX_API_HOSTS) {\n return fail(`${at}: apiHosts must list 1 to ${PLUGIN_CONNECTION_MAX_API_HOSTS} hosts`)\n }\n for (const pattern of apiHostsRaw) {\n if (!isPluginConnectionHostPattern(pattern)) {\n return fail(\n `${at}: api host \"${String(pattern)}\" must be a lowercase public hostname, or *.<domain> with one wildcard label`,\n )\n }\n }\n const apiHosts = [...new Set(apiHostsRaw as string[])]\n\n const resources: PluginConnectionResource[] = []\n if (raw['resources'] !== undefined) {\n const list = raw['resources']\n if (!Array.isArray(list) || list.length > PLUGIN_CONNECTION_MAX_RESOURCES) {\n return fail(`${at}: resources must list at most ${PLUGIN_CONNECTION_MAX_RESOURCES} resources`)\n }\n for (const [index, entry] of list.entries()) {\n const where2 = `${at} resources[${index}]`\n if (!isRecord(entry) || typeof entry['id'] !== 'string' || !IDENTIFIER.test(entry['id'])) {\n return fail(`${where2}: id must be a plain identifier`)\n }\n const resourceId = entry['id']\n if (resources.some((resource) => resource.id === resourceId)) return fail(`${where2}: id \"${resourceId}\" is used twice`)\n const resourceLabel = boundedText(entry['label'], LABEL_MAX)\n if (!resourceLabel) return fail(`${where2}: label is required (at most ${LABEL_MAX} characters)`)\n const request = validateRequest(entry['request'], `${where2}.request`, {\n apiHosts,\n resourceIds: resources.map((resource) => resource.id),\n requireItems: true,\n })\n if (request.ok === false) return request\n if (!isPluginConnectionPath(entry['idPath'])) return fail(`${where2}: idPath must be a dot path`)\n if (!isPluginConnectionPath(entry['labelPath'])) return fail(`${where2}: labelPath must be a dot path`)\n const maxItems =\n entry['maxItems'] === undefined ? 100 : intIn(entry['maxItems'], 1, PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS)\n if (maxItems === null) {\n return fail(`${where2}: maxItems must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS}`)\n }\n resources.push({\n id: resourceId,\n label: resourceLabel,\n request: request.value as PluginConnectionResource['request'],\n idPath: entry['idPath'],\n labelPath: entry['labelPath'],\n maxItems,\n })\n }\n }\n\n const sync = validateSync(raw['sync'], `${at} sync`, {\n apiHosts,\n resourceIds: resources.map((resource) => resource.id),\n })\n if (sync.ok === false) return sync\n\n return {\n ok: true,\n value: {\n id,\n provider,\n label,\n ...(description ? { description } : {}),\n authorizationUrl: raw['authorizationUrl'] as string,\n tokenUrl: raw['tokenUrl'] as string,\n ...(raw['revocationUrl'] !== undefined ? { revocationUrl: raw['revocationUrl'] as string } : {}),\n scopes: [...new Set(scopesRaw as string[])],\n ...(scopeSeparator ? { scopeSeparator: scopeSeparator as ' ' | ',' } : {}),\n ...(authParams && Object.keys(authParams).length ? { authParams } : {}),\n ...(tokenAuthMethod ? { tokenAuthMethod: tokenAuthMethod as PluginConnectionTokenAuthMethod } : {}),\n apiHosts,\n ...(resources.length ? { resources } : {}),\n ...(sync.value ? { sync: sync.value } : {}),\n },\n }\n}\n\n/**\n * Validates a manifest's whole `connections` block. Refused whole when any\n * entry is malformed — unlike an element, a connection dropped on the way in\n * is an OAuth flow and a sync that silently do not exist.\n */\nexport function validatePluginConnections(raw: unknown): Verdict<PluginConnectionDeclaration[]> {\n if (raw === undefined || raw === null) return { ok: true, value: [] }\n if (!Array.isArray(raw)) return fail('connections must be a list')\n if (raw.length > PLUGIN_CONNECTION_MAX) return fail(`At most ${PLUGIN_CONNECTION_MAX} connections may be declared`)\n let serialized: string\n try {\n serialized = JSON.stringify(raw)\n } catch {\n return fail('connections must be plain JSON')\n }\n if (serialized.length > PLUGIN_CONNECTION_MAX_DECLARATION_CHARS) {\n return fail(`connections must serialize to at most ${PLUGIN_CONNECTION_MAX_DECLARATION_CHARS} characters`)\n }\n const out: PluginConnectionDeclaration[] = []\n for (const [index, entry] of raw.entries()) {\n const verdict = validatePluginConnection(entry, `connections[${index}]`)\n if (verdict.ok === false) return verdict\n if (out.some((connection) => connection.id === verdict.value.id)) {\n return fail(`connection id \"${verdict.value.id}\" is declared twice`)\n }\n out.push(verdict.value)\n }\n return { ok: true, value: out }\n}\n\n/**\n * Validates `capabilities.imageHosts`: the hosts a plugin's element may show\n * images from on a published site. The tenant admits each, as an `https://`\n * source, to the `img-src` of the sites that install the plugin (AGL-4195),\n * so the rule is strict: a bare lowercase public hostname, or `*.` over one\n * label of a domain (never `*.com`), no scheme (so never `data:` or `http:`),\n * no port, no path, at most {@link PLUGIN_MAX_IMAGE_HOSTS}. Same host rule as\n * `apiHosts`.\n */\nexport function validatePluginImageHosts(raw: unknown): Verdict<string[]> {\n if (raw === undefined) return { ok: true, value: [] }\n if (!Array.isArray(raw) || raw.length > PLUGIN_MAX_IMAGE_HOSTS) {\n return fail(`imageHosts must list at most ${PLUGIN_MAX_IMAGE_HOSTS} hosts`)\n }\n for (const pattern of raw) {\n if (!isPluginConnectionHostPattern(pattern)) {\n return fail(`Image host \"${String(pattern)}\" must be a lowercase public hostname, or *.<domain> with one wildcard label`)\n }\n }\n return { ok: true, value: [...new Set(raw as string[])] }\n}\n\n/** The connection a manifest declares under `connectionId`, re-validated, or `null`. */\nexport function findPluginConnection(\n manifest: { connections?: unknown } | null | undefined,\n connectionId: string,\n): PluginConnectionDeclaration | null {\n const verdict = validatePluginConnections(manifest?.connections)\n if (verdict.ok === false) return null\n return verdict.value.find((connection) => connection.id === connectionId) ?? null\n}\n\n/**\n * The authorization address the site owner is sent to: the declared\n * endpoint with the platform's own client id, redirect, state and scope, and\n * the declaration's extra parameters, which may not override any of those.\n */\nexport function pluginConnectionAuthorizeUrl(\n connection: PluginConnectionDeclaration,\n options: { clientId: string; redirectUri: string; state: string },\n): string {\n const url = new URL(connection.authorizationUrl)\n for (const [key, value] of Object.entries(connection.authParams ?? {})) {\n if (PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS.includes(key.toLowerCase())) continue\n url.searchParams.set(key, value)\n }\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('client_id', options.clientId)\n url.searchParams.set('redirect_uri', options.redirectUri)\n url.searchParams.set('scope', connection.scopes.join(connection.scopeSeparator ?? ' '))\n url.searchParams.set('state', options.state)\n return url.toString()\n}\n\n/* ------------------------------------------------------------------ */\n/* Site variables from a record (AGL-4195) */\n/* ------------------------------------------------------------------ */\n\n/** The longest id a `{{var:…}}` token carries (`binding-tokens.ts`). */\nconst VARIABLE_ID_MAX = 64\nconst VARIABLE_ID_REF = /^[A-Za-z0-9_-]{1,64}$/\n\n/**\n * The `{{var:…}}` id a record's SUMMARY field resolves under on a site:\n * `{listingId}__{connectionId}-{field}`, e.g. `Kq3…__reviews-rating`.\n *\n * Chosen so it can never be a site's own variable and can never be two\n * fields at once:\n *\n * - a site's own variables carry Firestore auto ids (letters and digits),\n * and this id always holds `__` and `-`;\n * - a field name never holds `-` (`[A-Za-z][A-Za-z0-9_]*`), so the field is\n * what follows the LAST `-`; a connection id never holds `_`, so the\n * connection is what follows the last `__` before it, and the listing is\n * the rest. Two different triples therefore never spell the same id.\n *\n * `null` when the id would not fit a token (64 characters): such a field\n * has no variable, rather than one that no token could name.\n */\nexport function pluginConnectionVariableId(\n listingId: string,\n connectionId: string,\n field: string,\n): string | null {\n if (!PLUGIN_CONNECTION_ID_PATTERN.test(connectionId) || !IDENTIFIER.test(field)) return null\n const id = `${listingId}__${connectionId}-${field}`\n return id.length <= VARIABLE_ID_MAX && VARIABLE_ID_REF.test(id) ? id : null\n}\n\n/** How a record value of each declared type is held as a site variable. */\nconst VARIABLE_TYPE_OF: Readonly<Record<PluginConnectionFieldType, HostVariableType>> = {\n string: 'text',\n url: 'text',\n number: 'number',\n boolean: 'boolean',\n datetime: 'date',\n}\n\n/**\n * The site variables one connection's record gives a site: one per declared\n * SUMMARY field (`sync.record.fields`) holding a value, under\n * {@link pluginConnectionVariableId}. A field the record does not hold, or\n * holds as a value of another type than declared, has no variable, so its\n * token renders empty as any unknown variable does. Items never become\n * variables: a list has no single value to print.\n *\n * Each variable's `name` is its id. Names are what a function's expressions\n * read, and an id with `-` in it is not a name an expression can spell, so\n * these never shadow one of the site's own variables in a function.\n */\nexport function pluginConnectionRecordVariables(\n listingId: string,\n connection: Pick<PluginConnectionDeclaration, 'id' | 'sync'>,\n fields: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, HostVariable> {\n const out: Record<string, HostVariable> = {}\n const declared = connection.sync?.record.fields ?? {}\n for (const [field, declaration] of Object.entries(declared)) {\n const value = fields?.[field]\n const id = pluginConnectionVariableId(listingId, connection.id, field)\n if (!id || value === null || value === undefined) continue\n const type = VARIABLE_TYPE_OF[declaration.type]\n let stored: string | null = null\n if (declaration.type === 'number' && typeof value === 'number' && Number.isFinite(value)) {\n stored = String(value)\n } else if (declaration.type === 'boolean' && typeof value === 'boolean') {\n stored = value ? 'true' : 'false'\n } else if (declaration.type === 'datetime' && typeof value === 'number' && Number.isFinite(value)) {\n const date = new Date(value)\n stored = Number.isNaN(date.getTime()) ? null : date.toISOString()\n } else if ((declaration.type === 'string' || declaration.type === 'url') && typeof value === 'string') {\n stored = value\n }\n if (stored === null) continue\n out[id] = { name: id, type, value: stored }\n }\n return out\n}\n"],"names":["PLUGIN_CONNECTION_MAX","PLUGIN_CONNECTION_ID_PATTERN","PLUGIN_CONNECTION_MAX_SCOPES","PLUGIN_CONNECTION_MAX_API_HOSTS","PLUGIN_CONNECTION_MAX_AUTH_PARAMS","PLUGIN_CONNECTION_MAX_RESOURCES","PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS","PLUGIN_CONNECTION_MAX_SYNC_REQUESTS","PLUGIN_CONNECTION_MAX_PAGES","PLUGIN_CONNECTION_MIN_INTERVAL_HOURS","PLUGIN_CONNECTION_MAX_INTERVAL_HOURS","PLUGIN_CONNECTION_MAX_RECORD_FIELDS","PLUGIN_CONNECTION_MAX_RECORD_ITEMS","PLUGIN_CONNECTION_MAX_STRING_LENGTH","PLUGIN_CONNECTION_MAX_URL_LENGTH","PLUGIN_CONNECTION_MAX_MAP_ENTRIES","PLUGIN_CONNECTION_MAX_DECLARATION_CHARS","PLUGIN_MAX_IMAGE_HOSTS","TEXT_MAX","LABEL_MAX","IDENTIFIER","PATH_SEGMENT","PATH_MAX_SEGMENTS","SCOPE","PARAM_NAME","PARAM_VALUE_MAX","TEMPLATE_VALUE_MAX","BODY_MAX_KEYS","QUERY_MAX_KEYS","HOST_LABEL","PLACEHOLDER","RESOURCE_PLACEHOLDER","FIELD_TYPES","PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS","isIpLiteral","hostname","test","includes","startsWith","isPublicHostname","length","labels","split","some","label","tld","endsWith","isPluginConnectionHostPattern","value","toLowerCase","rest","slice","pluginConnectionHostMatches","pattern","candidate","isPluginConnectionUrlAllowed","url","apiHosts","parsed","URL","protocol","username","password","port","hash","endpointError","name","search","pluginConnectionEndpointHosts","connection","hosts","Set","authorizationUrl","tokenUrl","revocationUrl","add","isPluginConnectionPath","segments","every","segment","readPluginConnectionPath","source","path","current","undefined","Array","isArray","Number","Object","prototype","hasOwnProperty","call","templateRefs","refs","match","matchAll","inner","resource","exec","error","push","stripped","replace","isPluginConnectionChoiceId","preparePluginConnectionRequest","request","options","fill","missing","out","_whole","String","trim","choice","choices","ok","key","entries","query","filled","searchParams","set","cursor","pagination","cursorParam","finalUrl","toString","method","body","JSON","stringify","fail","isRecord","boundedText","max","intIn","min","isInteger","templateUrlError","where","authorityEnd","indexOf","head","probe","validatePagination","raw","maxPages","cursorPath","validateRequest","context","urlError","collect","urlRefs","isFinite","ref","resourceIds","itemsPath","requireItems","keys","validateField","type","join","field","ceiling","maxLength","map","validateFieldSet","each","required","verdict","validateSync","intervalHours","requestsRaw","requests","index","entry","at","id","recordRaw","requestIds","fields","items","itemFields","itemsRaw","find","maxItems","record","validatePluginConnection","provider","description","text","scopesRaw","scope","scopeSeparator","authParams","tokenAuthMethod","apiHostsRaw","resources","list","where2","resourceId","resourceLabel","idPath","labelPath","sync","scopes","validatePluginConnections","serialized","validatePluginImageHosts","findPluginConnection","manifest","connectionId","connections","pluginConnectionAuthorizeUrl","clientId","redirectUri","state","VARIABLE_ID_MAX","VARIABLE_ID_REF","pluginConnectionVariableId","listingId","VARIABLE_TYPE_OF","string","number","boolean","datetime","pluginConnectionRecordVariables","declared","declaration","stored","date","Date","isNaN","getTime","toISOString"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC;AA8ID,sEAAsE,GACtE,wEAAwE,GACxE,sEAAsE,GAEtE,OAAO,MAAMA,wBAAwB,EAAC;AACtC,OAAO,MAAMC,+BAA+B,yBAAwB;AACpE,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,OAAO,MAAMC,kCAAkC,GAAE;AACjD,OAAO,MAAMC,oCAAoC,GAAE;AACnD,OAAO,MAAMC,kCAAkC,EAAC;AAChD,OAAO,MAAMC,uCAAuC,IAAG;AACvD,OAAO,MAAMC,sCAAsC,EAAC;AACpD,OAAO,MAAMC,8BAA8B,GAAE;AAC7C,OAAO,MAAMC,uCAAuC,EAAC;AACrD,OAAO,MAAMC,uCAAuC,IAAG;AACvD,OAAO,MAAMC,sCAAsC,GAAE;AACrD,OAAO,MAAMC,qCAAqC,IAAG;AACrD,OAAO,MAAMC,sCAAsC,KAAI;AACvD,OAAO,MAAMC,mCAAmC,KAAI;AACpD,OAAO,MAAMC,oCAAoC,GAAE;AACnD,sFAAsF,GACtF,OAAO,MAAMC,0CAA0C,MAAM;AAC7D;;;CAGC,GACD,OAAO,MAAMC,yBAAyB,EAAC;AAEvC,MAAMC,WAAW;AACjB,MAAMC,YAAY;AAClB,MAAMC,aAAa;AACnB,MAAMC,eAAe;AACrB,MAAMC,oBAAoB;AAC1B,MAAMC,QAAQ;AACd,MAAMC,aAAa;AACnB,MAAMC,kBAAkB;AACxB,MAAMC,qBAAqB;AAC3B,MAAMC,gBAAgB;AACtB,MAAMC,iBAAiB;AACvB,MAAMC,aAAa;AACnB,MAAMC,cAAc;AACpB,MAAMC,uBAAuB;AAC7B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
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { PluginCapabilities, PluginElementDeclaration, PluginPropSchema } from './plugin-manifest';
18
+ /**
19
+ * WHAT A PLACED PLUGIN SHOWS IN THE EDITOR, APART FROM THE VALIDATOR (AGL-4201).
20
+ *
21
+ * These resolvers read a pinned install's declared props and elements. They
22
+ * were in `plugin-manifest.ts`, and the mui plugin's site module calls
23
+ * `resolvePluginElements` (its install-to-preset mapper), so every published
24
+ * page loaded the whole manifest module, and with it every validator that
25
+ * module imports. When the connections validator joined it (AGL-4193), every
26
+ * published page grew by about 19 KB on the wire. They import only types from
27
+ * the manifest, so a caller of these pays for these and nothing else.
28
+ * The sandboxed element's component id lives here for the same reason.
29
+ * `plugin-manifest.ts` re-exports all of it, so its API is unchanged.
30
+ */
31
+ /** Component id of the sandboxed plugin canvas element (plugins-mui). */
32
+ export declare const PLUGIN_COMPONENT_ID = "marketplacePlugin";
33
+ /** One editable setting on a placed plugin, resolved for the attributes panel. */
34
+ export interface PluginPropField {
35
+ name: string;
36
+ type: NonNullable<PluginPropSchema['type']>;
37
+ label: string;
38
+ description?: string;
39
+ default?: string | number | boolean;
40
+ options?: Array<{
41
+ value: string;
42
+ label?: string;
43
+ }>;
44
+ }
45
+ /**
46
+ * The settings an author may edit on a placed plugin (AGL-1049).
47
+ *
48
+ * Driven by `capabilities.props` — THE allowlist — and decorated by
49
+ * `propSchema` where the publisher supplied one. That order is the whole
50
+ * security property: the list of editable settings can never be longer than
51
+ * the list of props that cross the bridge, whatever the schema says, so a
52
+ * publisher cannot describe their way into a prop they did not declare.
53
+ *
54
+ * A plugin published before `propSchema` existed still gets a field per
55
+ * declared prop, as plain text. That is the difference between guessing key
56
+ * names in a JSON textarea and being shown them, and it needs no manifest
57
+ * change to work — which matters, because every plugin installed today
58
+ * predates this.
59
+ */
60
+ export declare function resolvePluginPropFields(manifest: {
61
+ capabilities?: PluginCapabilities;
62
+ } | null | undefined): PluginPropField[];
63
+ /**
64
+ * Keys an author has set that the plugin will silently ignore.
65
+ *
66
+ * The failure this exists to surface: `filterPluginProps` drops anything not
67
+ * in the allowlist, so a typo does not fail — it just quietly does nothing,
68
+ * which is the worst of the options. Naming the key is the whole fix.
69
+ */
70
+ export declare function unknownPluginPropKeys(manifest: {
71
+ capabilities?: PluginCapabilities;
72
+ } | null | undefined, values: Record<string, unknown> | null | undefined): string[];
73
+ /** A declared element, resolved for the palette. */
74
+ export interface PluginPaletteElement {
75
+ listingId: string;
76
+ elementId: string;
77
+ displayName: string;
78
+ description?: string;
79
+ category: string;
80
+ /** mdi icon NAME; the surface looks it up, never renders it as markup. */
81
+ icon?: string;
82
+ fields: PluginPropField[];
83
+ }
84
+ /**
85
+ * The palette entries an installed plugin contributes (AGL-1031).
86
+ *
87
+ * Resolved from the PINNED install, which is what makes the two guarantees in
88
+ * the issue hold without extra machinery: an element only appears where the
89
+ * plugin is installed, and a revoked or downgraded version's elements vanish
90
+ * with it, because the palette is rebuilt from whatever the pin now points at.
91
+ *
92
+ * Attributes come back through `resolvePluginPropFields`, so an element's
93
+ * editable fields are bounded by `capabilities.props` exactly like the generic
94
+ * plugin element's are. A declared element cannot widen what crosses the
95
+ * bridge; it only gives the same props a better name and a better editor.
96
+ */
97
+ export declare function resolvePluginElements(install: {
98
+ listingId?: string;
99
+ capabilities?: PluginCapabilities;
100
+ manifest?: {
101
+ elements?: PluginElementDeclaration[];
102
+ };
103
+ elements?: PluginElementDeclaration[];
104
+ } | null | undefined): PluginPaletteElement[];
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ /**
18
+ * WHAT A PLACED PLUGIN SHOWS IN THE EDITOR, APART FROM THE VALIDATOR (AGL-4201).
19
+ *
20
+ * These resolvers read a pinned install's declared props and elements. They
21
+ * were in `plugin-manifest.ts`, and the mui plugin's site module calls
22
+ * `resolvePluginElements` (its install-to-preset mapper), so every published
23
+ * page loaded the whole manifest module, and with it every validator that
24
+ * module imports. When the connections validator joined it (AGL-4193), every
25
+ * published page grew by about 19 KB on the wire. They import only types from
26
+ * the manifest, so a caller of these pays for these and nothing else.
27
+ * The sandboxed element's component id lives here for the same reason.
28
+ * `plugin-manifest.ts` re-exports all of it, so its API is unchanged.
29
+ */ /** Component id of the sandboxed plugin canvas element (plugins-mui). */ export const PLUGIN_COMPONENT_ID = 'marketplacePlugin';
30
+ /**
31
+ * The settings an author may edit on a placed plugin (AGL-1049).
32
+ *
33
+ * Driven by `capabilities.props` — THE allowlist — and decorated by
34
+ * `propSchema` where the publisher supplied one. That order is the whole
35
+ * security property: the list of editable settings can never be longer than
36
+ * the list of props that cross the bridge, whatever the schema says, so a
37
+ * publisher cannot describe their way into a prop they did not declare.
38
+ *
39
+ * A plugin published before `propSchema` existed still gets a field per
40
+ * declared prop, as plain text. That is the difference between guessing key
41
+ * names in a JSON textarea and being shown them, and it needs no manifest
42
+ * change to work — which matters, because every plugin installed today
43
+ * predates this.
44
+ */ export function resolvePluginPropFields(manifest) {
45
+ var _ref, _ref1;
46
+ var _manifest_capabilities, _manifest_capabilities1;
47
+ const props = (_ref = manifest == null ? void 0 : (_manifest_capabilities = manifest.capabilities) == null ? void 0 : _manifest_capabilities.props) != null ? _ref : [];
48
+ const schema = new Map(((_ref1 = manifest == null ? void 0 : (_manifest_capabilities1 = manifest.capabilities) == null ? void 0 : _manifest_capabilities1.propSchema) != null ? _ref1 : []).map((entry)=>[
49
+ entry.name,
50
+ entry
51
+ ]));
52
+ return props.map((name)=>{
53
+ var _ref, _ref1;
54
+ const declared = schema.get(name);
55
+ return _extends({
56
+ name,
57
+ type: (_ref = declared == null ? void 0 : declared.type) != null ? _ref : 'string',
58
+ label: (_ref1 = declared == null ? void 0 : declared.label) != null ? _ref1 : name
59
+ }, (declared == null ? void 0 : declared.description) ? {
60
+ description: declared.description
61
+ } : {}, (declared == null ? void 0 : declared.default) !== undefined ? {
62
+ default: declared.default
63
+ } : {}, (declared == null ? void 0 : declared.options) ? {
64
+ options: declared.options
65
+ } : {});
66
+ });
67
+ }
68
+ /**
69
+ * Keys an author has set that the plugin will silently ignore.
70
+ *
71
+ * The failure this exists to surface: `filterPluginProps` drops anything not
72
+ * in the allowlist, so a typo does not fail — it just quietly does nothing,
73
+ * which is the worst of the options. Naming the key is the whole fix.
74
+ */ export function unknownPluginPropKeys(manifest, values) {
75
+ var _ref;
76
+ var _manifest_capabilities;
77
+ if (!values) return [];
78
+ const allowed = new Set((_ref = manifest == null ? void 0 : (_manifest_capabilities = manifest.capabilities) == null ? void 0 : _manifest_capabilities.props) != null ? _ref : []);
79
+ return Object.keys(values).filter((key)=>!allowed.has(key));
80
+ }
81
+ /**
82
+ * The palette entries an installed plugin contributes (AGL-1031).
83
+ *
84
+ * Resolved from the PINNED install, which is what makes the two guarantees in
85
+ * the issue hold without extra machinery: an element only appears where the
86
+ * plugin is installed, and a revoked or downgraded version's elements vanish
87
+ * with it, because the palette is rebuilt from whatever the pin now points at.
88
+ *
89
+ * Attributes come back through `resolvePluginPropFields`, so an element's
90
+ * editable fields are bounded by `capabilities.props` exactly like the generic
91
+ * plugin element's are. A declared element cannot widen what crosses the
92
+ * bridge; it only gives the same props a better name and a better editor.
93
+ */ export function resolvePluginElements(install) {
94
+ var _ref, _ref1;
95
+ var _install_manifest;
96
+ const listingId = install == null ? void 0 : install.listingId;
97
+ if (!listingId) return [];
98
+ const declared = (_ref = (_ref1 = install == null ? void 0 : install.elements) != null ? _ref1 : install == null ? void 0 : (_install_manifest = install.manifest) == null ? void 0 : _install_manifest.elements) != null ? _ref : [];
99
+ const capabilities = install == null ? void 0 : install.capabilities;
100
+ return declared.map((element)=>{
101
+ var _element_category;
102
+ var _element_attributes;
103
+ return _extends({
104
+ listingId,
105
+ elementId: element.id,
106
+ displayName: element.displayName
107
+ }, element.description ? {
108
+ description: element.description
109
+ } : {}, {
110
+ category: (_element_category = element.category) != null ? _element_category : 'Data Display'
111
+ }, element.icon ? {
112
+ icon: element.icon
113
+ } : {}, {
114
+ // Per-element attributes when declared; otherwise the plugin's whole
115
+ // declared prop set, which is still better than a JSON box.
116
+ fields: ((_element_attributes = element.attributes) == null ? void 0 : _element_attributes.length) ? resolvePluginPropFields({
117
+ capabilities: {
118
+ props: element.attributes.map((attribute)=>attribute.name),
119
+ propSchema: element.attributes
120
+ }
121
+ }) : resolvePluginPropFields({
122
+ capabilities
123
+ })
124
+ });
125
+ });
126
+ }
127
+
128
+ //# sourceMappingURL=plugin-elements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/plugin-elements.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n PluginCapabilities,\n PluginElementDeclaration,\n PluginPropSchema,\n} from './plugin-manifest'\n\n/**\n * WHAT A PLACED PLUGIN SHOWS IN THE EDITOR, APART FROM THE VALIDATOR (AGL-4201).\n *\n * These resolvers read a pinned install's declared props and elements. They\n * were in `plugin-manifest.ts`, and the mui plugin's site module calls\n * `resolvePluginElements` (its install-to-preset mapper), so every published\n * page loaded the whole manifest module, and with it every validator that\n * module imports. When the connections validator joined it (AGL-4193), every\n * published page grew by about 19 KB on the wire. They import only types from\n * the manifest, so a caller of these pays for these and nothing else.\n * The sandboxed element's component id lives here for the same reason.\n * `plugin-manifest.ts` re-exports all of it, so its API is unchanged.\n */\n\n/** Component id of the sandboxed plugin canvas element (plugins-mui). */\nexport const PLUGIN_COMPONENT_ID = 'marketplacePlugin'\n\n/** One editable setting on a placed plugin, resolved for the attributes panel. */\nexport interface PluginPropField {\n name: string\n type: NonNullable<PluginPropSchema['type']>\n label: string\n description?: string\n default?: string | number | boolean\n options?: Array<{ value: string; label?: string }>\n}\n\n/**\n * The settings an author may edit on a placed plugin (AGL-1049).\n *\n * Driven by `capabilities.props` — THE allowlist — and decorated by\n * `propSchema` where the publisher supplied one. That order is the whole\n * security property: the list of editable settings can never be longer than\n * the list of props that cross the bridge, whatever the schema says, so a\n * publisher cannot describe their way into a prop they did not declare.\n *\n * A plugin published before `propSchema` existed still gets a field per\n * declared prop, as plain text. That is the difference between guessing key\n * names in a JSON textarea and being shown them, and it needs no manifest\n * change to work — which matters, because every plugin installed today\n * predates this.\n */\nexport function resolvePluginPropFields(\n manifest: { capabilities?: PluginCapabilities } | null | undefined,\n): PluginPropField[] {\n const props = manifest?.capabilities?.props ?? []\n const schema = new Map(\n (manifest?.capabilities?.propSchema ?? []).map((entry) => [\n entry.name,\n entry,\n ]),\n )\n return props.map((name) => {\n const declared = schema.get(name)\n return {\n name,\n type: declared?.type ?? 'string',\n label: declared?.label ?? name,\n ...(declared?.description ? { description: declared.description } : {}),\n ...(declared?.default !== undefined ? { default: declared.default } : {}),\n ...(declared?.options ? { options: declared.options } : {}),\n }\n })\n}\n\n/**\n * Keys an author has set that the plugin will silently ignore.\n *\n * The failure this exists to surface: `filterPluginProps` drops anything not\n * in the allowlist, so a typo does not fail — it just quietly does nothing,\n * which is the worst of the options. Naming the key is the whole fix.\n */\nexport function unknownPluginPropKeys(\n manifest: { capabilities?: PluginCapabilities } | null | undefined,\n values: Record<string, unknown> | null | undefined,\n): string[] {\n if (!values) return []\n const allowed = new Set(manifest?.capabilities?.props ?? [])\n return Object.keys(values).filter((key) => !allowed.has(key))\n}\n\n/** A declared element, resolved for the palette. */\nexport interface PluginPaletteElement {\n listingId: string\n elementId: string\n displayName: string\n description?: string\n category: string\n /** mdi icon NAME; the surface looks it up, never renders it as markup. */\n icon?: string\n fields: PluginPropField[]\n}\n\n/**\n * The palette entries an installed plugin contributes (AGL-1031).\n *\n * Resolved from the PINNED install, which is what makes the two guarantees in\n * the issue hold without extra machinery: an element only appears where the\n * plugin is installed, and a revoked or downgraded version's elements vanish\n * with it, because the palette is rebuilt from whatever the pin now points at.\n *\n * Attributes come back through `resolvePluginPropFields`, so an element's\n * editable fields are bounded by `capabilities.props` exactly like the generic\n * plugin element's are. A declared element cannot widen what crosses the\n * bridge; it only gives the same props a better name and a better editor.\n */\nexport function resolvePluginElements(\n install:\n | {\n listingId?: string\n capabilities?: PluginCapabilities\n manifest?: { elements?: PluginElementDeclaration[] }\n elements?: PluginElementDeclaration[]\n }\n | null\n | undefined,\n): PluginPaletteElement[] {\n const listingId = install?.listingId\n if (!listingId) return []\n const declared = install?.elements ?? install?.manifest?.elements ?? []\n const capabilities = install?.capabilities\n return declared.map((element) => ({\n listingId,\n elementId: element.id,\n displayName: element.displayName,\n ...(element.description ? { description: element.description } : {}),\n category: element.category ?? 'Data Display',\n ...(element.icon ? { icon: element.icon } : {}),\n // Per-element attributes when declared; otherwise the plugin's whole\n // declared prop set, which is still better than a JSON box.\n fields: element.attributes?.length\n ? resolvePluginPropFields({\n capabilities: {\n props: element.attributes.map((attribute) => attribute.name),\n propSchema: element.attributes,\n },\n })\n : resolvePluginPropFields({ capabilities }),\n }))\n}\n"],"names":["PLUGIN_COMPONENT_ID","resolvePluginPropFields","manifest","props","capabilities","schema","Map","propSchema","map","entry","name","declared","get","type","label","description","default","undefined","options","unknownPluginPropKeys","values","allowed","Set","Object","keys","filter","key","has","resolvePluginElements","install","listingId","elements","element","elementId","id","displayName","category","icon","fields","attributes","length","attribute"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAQD;;;;;;;;;;;;CAYC,GAED,uEAAuE,GACvE,OAAO,MAAMA,sBAAsB,oBAAmB;AAYtD;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,wBACdC,QAAkE;;QAEpDA,wBAEXA;IAFH,MAAMC,gBAAQD,6BAAAA,yBAAAA,SAAUE,YAAY,qBAAtBF,uBAAwBC,KAAK,mBAAI,EAAE;IACjD,MAAME,SAAS,IAAIC,IACjB,UAACJ,6BAAAA,0BAAAA,SAAUE,YAAY,qBAAtBF,wBAAwBK,UAAU,oBAAI,EAAE,EAAEC,GAAG,CAAC,CAACC,QAAU;YACxDA,MAAMC,IAAI;YACVD;SACD;IAEH,OAAON,MAAMK,GAAG,CAAC,CAACE;;QAChB,MAAMC,WAAWN,OAAOO,GAAG,CAACF;QAC5B,OAAO;YACLA;YACAG,IAAI,UAAEF,4BAAAA,SAAUE,IAAI,mBAAI;YACxBC,KAAK,WAAEH,4BAAAA,SAAUG,KAAK,oBAAIJ;WACtBC,CAAAA,4BAAAA,SAAUI,WAAW,IAAG;YAAEA,aAAaJ,SAASI,WAAW;QAAC,IAAI,CAAC,GACjEJ,CAAAA,4BAAAA,SAAUK,OAAO,MAAKC,YAAY;YAAED,SAASL,SAASK,OAAO;QAAC,IAAI,CAAC,GACnEL,CAAAA,4BAAAA,SAAUO,OAAO,IAAG;YAAEA,SAASP,SAASO,OAAO;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I;oBAC3DH,YAAYyB,QAAQO,UAAU;gBAChC;YACF,KACAtC,wBAAwB;gBAAEG;YAAa;;;AAE/C"}
@@ -14,8 +14,10 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import type { PluginConfigField } from '../plugin-manager/plugin-config';
17
+ import { type PluginConfigField } from '../plugin-manager/plugin-config';
18
18
  import { type PluginContributions } from '../plugin-manager/plugin-contributions';
19
+ import { type PluginConnectionDeclaration } from './plugin-connections';
20
+ import { PLUGIN_COMPONENT_ID } from './plugin-elements';
19
21
  /**
20
22
  * Executable-plugin manifest, artifact-path, CSP, and revocation helpers
21
23
  * (AGL-45), per the accepted AGL-43 design. Plugins — unlike declarative
@@ -131,6 +133,13 @@ export interface PluginCapabilities {
131
133
  width?: number;
132
134
  height?: number;
133
135
  };
136
+ /**
137
+ * Hosts the plugin's elements may show images from on a published site
138
+ * (AGL-4193): an exact public hostname or `*.<domain>` with one wildcard
139
+ * label. Validated here; the tenant's `img-src` reads it for a site that
140
+ * runs the plugin.
141
+ */
142
+ imageHosts?: string[];
134
143
  }
135
144
  export interface PluginManifest {
136
145
  /** Stable plugin id (matches the listing); persisted, never renamed. */
@@ -193,6 +202,14 @@ export interface PluginManifest {
193
202
  * page never loads the plugin anywhere the declaration does not place it.
194
203
  */
195
204
  contributes?: PluginContributions;
205
+ /**
206
+ * Declared connections (AGL-4193): OAuth providers the PLATFORM connects a
207
+ * site to on the plugin's behalf, the hosts it may call with the grant, the
208
+ * picker that chooses what to connect, and the scheduled fetch that maps the
209
+ * provider's answer into the site's public record. The plugin's own code
210
+ * never sees a token. See `plugin-connections.ts`.
211
+ */
212
+ connections?: PluginConnectionDeclaration[];
196
213
  }
197
214
  /** A published, content-addressed version of a plugin listing. */
198
215
  export interface PluginListingVersion {
@@ -422,8 +439,7 @@ export declare const PLUGIN_FETCH_MAX_BODY_BYTES: number;
422
439
  * no host-mediated network; https-only.
423
440
  */
424
441
  export declare function isPluginNetworkAllowed(url: string, capabilities: PluginCapabilities | undefined): boolean;
425
- /** Component id of the sandboxed plugin canvas element (plugins-mui). */
426
- export declare const PLUGIN_COMPONENT_ID = "marketplacePlugin";
442
+ export { PLUGIN_COMPONENT_ID };
427
443
  /** Resolved install data injected into a plugin node's props at compose. */
428
444
  export interface ResolvedPluginInstall {
429
445
  listingId: string;
@@ -442,75 +458,4 @@ export interface ResolvedPluginInstall {
442
458
  * "not installed" placeholder rather than taking the screen down).
443
459
  */
444
460
  export declare function attachPluginInstalls<T extends Record<string, any>>(nodes: T, installsByListingId: Record<string, ResolvedPluginInstall | undefined>): T;
445
- /** One editable setting on a placed plugin, resolved for the attributes panel. */
446
- export interface PluginPropField {
447
- name: string;
448
- type: NonNullable<PluginPropSchema['type']>;
449
- label: string;
450
- description?: string;
451
- default?: string | number | boolean;
452
- options?: Array<{
453
- value: string;
454
- label?: string;
455
- }>;
456
- }
457
- /**
458
- * The settings an author may edit on a placed plugin (AGL-1049).
459
- *
460
- * Driven by `capabilities.props` — THE allowlist — and decorated by
461
- * `propSchema` where the publisher supplied one. That order is the whole
462
- * security property: the list of editable settings can never be longer than
463
- * the list of props that cross the bridge, whatever the schema says, so a
464
- * publisher cannot describe their way into a prop they did not declare.
465
- *
466
- * A plugin published before `propSchema` existed still gets a field per
467
- * declared prop, as plain text. That is the difference between guessing key
468
- * names in a JSON textarea and being shown them, and it needs no manifest
469
- * change to work — which matters, because every plugin installed today
470
- * predates this.
471
- */
472
- export declare function resolvePluginPropFields(manifest: {
473
- capabilities?: PluginCapabilities;
474
- } | null | undefined): PluginPropField[];
475
- /**
476
- * Keys an author has set that the plugin will silently ignore.
477
- *
478
- * The failure this exists to surface: `filterPluginProps` drops anything not
479
- * in the allowlist, so a typo does not fail — it just quietly does nothing,
480
- * which is the worst of the options. Naming the key is the whole fix.
481
- */
482
- export declare function unknownPluginPropKeys(manifest: {
483
- capabilities?: PluginCapabilities;
484
- } | null | undefined, values: Record<string, unknown> | null | undefined): string[];
485
- /** A declared element, resolved for the palette. */
486
- export interface PluginPaletteElement {
487
- listingId: string;
488
- elementId: string;
489
- displayName: string;
490
- description?: string;
491
- category: string;
492
- /** mdi icon NAME; the surface looks it up, never renders it as markup. */
493
- icon?: string;
494
- fields: PluginPropField[];
495
- }
496
- /**
497
- * The palette entries an installed plugin contributes (AGL-1031).
498
- *
499
- * Resolved from the PINNED install, which is what makes the two guarantees in
500
- * the issue hold without extra machinery: an element only appears where the
501
- * plugin is installed, and a revoked or downgraded version's elements vanish
502
- * with it, because the palette is rebuilt from whatever the pin now points at.
503
- *
504
- * Attributes come back through `resolvePluginPropFields`, so an element's
505
- * editable fields are bounded by `capabilities.props` exactly like the generic
506
- * plugin element's are. A declared element cannot widen what crosses the
507
- * bridge; it only gives the same props a better name and a better editor.
508
- */
509
- export declare function resolvePluginElements(install: {
510
- listingId?: string;
511
- capabilities?: PluginCapabilities;
512
- manifest?: {
513
- elements?: PluginElementDeclaration[];
514
- };
515
- elements?: PluginElementDeclaration[];
516
- } | null | undefined): PluginPaletteElement[];
461
+ export { resolvePluginElements, resolvePluginPropFields, unknownPluginPropKeys, type PluginPaletteElement, type PluginPropField, } from './plugin-elements';