{"version":3,"file":"templateStore.mjs","names":[],"sources":["../../../src/web/stores/templateStore.ts"],"sourcesContent":["import { HOST_SLOTS, NO_BACKDROP } from '@agimon-ai/po-core/web';\nimport { useStore } from '@tanstack/react-store';\nimport { Store } from '@tanstack/store';\nimport { useEffect } from 'react';\n\nimport type { SettingsConfigView } from '../../types/settings';\nimport { hostSlotFills, webTemplateCatalog } from '../lib/pluginRegistry';\nimport { readSettingsConfig, writeSettingsValue } from '../lib/settingsApi';\nimport { backdropId } from '../lib/templateCatalog';\nimport { onHubConnected } from '../lib/transport';\nimport { traceStore } from '../lib/uiTrace';\n\nexport interface TemplateConfiguration {\n  config?: SettingsConfigView;\n  error?: string;\n  loading: boolean;\n  saving: boolean;\n}\n\nconst EMPTY: TemplateConfiguration = { loading: true, saving: false };\nconst HOST = 'host';\nconst KEY = 'web.template';\nconst BACKDROP_KEY = 'web.backdrop';\nconst requests = new Map<string, number>();\nconst pendingRequests = new Map<string, Promise<void>>();\n\n/** Preferences belong to Po config; this store caches only scoped API responses. */\nexport const templateStore = traceStore('templates', new Store<Record<string, TemplateConfiguration>>({}));\n\nfunction scopeKey(workspaceId?: string): string {\n  return workspaceId === undefined ? HOST : `workspace:${workspaceId}`;\n}\n\nfunction patch(key: string, update: Partial<TemplateConfiguration>): void {\n  templateStore.setState((state) => ({ ...state, [key]: { ...(state[key] ?? EMPTY), ...update } }));\n}\n\nexport function refreshTemplateConfiguration(workspaceId?: string): Promise<void> {\n  const key = scopeKey(workspaceId);\n  const request = (requests.get(key) ?? 0) + 1;\n  requests.set(key, request);\n  patch(key, { loading: true, error: undefined });\n  const pending = (async () => {\n    try {\n      const result = await readSettingsConfig('', [KEY, BACKDROP_KEY], workspaceId);\n      if (requests.get(key) !== request) return;\n      if (result.ok) patch(key, { config: result.config, loading: false, error: undefined });\n      else patch(key, { loading: false, error: result.error });\n    } catch (error) {\n      if (requests.get(key) === request)\n        patch(key, { loading: false, error: error instanceof Error ? error.message : String(error) });\n    } finally {\n      if (requests.get(key) === request) pendingRequests.delete(key);\n    }\n  })();\n  pendingRequests.set(key, pending);\n  return pending;\n}\n\n/** Initial consumers share a read and reuse resolved config; explicit refreshes can supersede it. */\nexport function ensureTemplateConfiguration(workspaceId?: string): Promise<void> {\n  const key = scopeKey(workspaceId);\n  return (\n    pendingRequests.get(key) ??\n    (templateStore.state[key]?.config === undefined ? refreshTemplateConfiguration(workspaceId) : Promise.resolve())\n  );\n}\n\nexport function useTemplateConfiguration(workspaceId?: string): TemplateConfiguration {\n  const key = scopeKey(workspaceId);\n  const entry = useStore(templateStore, (state) => state[key] ?? EMPTY);\n  useEffect(() => {\n    void ensureTemplateConfiguration(workspaceId);\n    return onHubConnected(() => {\n      void (pendingRequests.get(key) ?? refreshTemplateConfiguration(workspaceId));\n    });\n  }, [key, workspaceId]);\n  return entry;\n}\n\n/** Refuse unavailable choices before attempting the existing authorized, hash-checked write. */\nexport async function saveTemplateDefault(id: string | null, workspaceId?: string): Promise<boolean> {\n  const mount = workspaceId === undefined ? { scope: 'host' as const } : { scope: 'workspace' as const, workspaceId };\n  const available = id === null || webTemplateCatalog(mount).templates.some((template) => template.id === id);\n  return await saveWebChoice('template', id, available, workspaceId);\n}\n\n/** `null` clears the choice so Po's bamboo shows; `none` shows no background. */\nexport async function saveBackdropDefault(choice: string | null, workspaceId?: string): Promise<boolean> {\n  const available =\n    choice === null ||\n    choice === NO_BACKDROP ||\n    hostSlotFills(HOST_SLOTS.backdrop).some((fill) => backdropId(fill) === choice);\n  return await saveWebChoice('backdrop', choice, available, workspaceId);\n}\n\nasync function saveWebChoice(\n  field: 'template' | 'backdrop',\n  value: string | null,\n  available: boolean,\n  workspaceId: string | undefined,\n): Promise<boolean> {\n  const key = scopeKey(workspaceId);\n  const entry = templateStore.state[key];\n  if (entry?.saving) return false;\n  if (entry?.config === undefined) {\n    patch(key, { error: `Load the configuration before saving a ${field} default.` });\n    return false;\n  }\n  if (!available) {\n    patch(key, { error: `That ${field} is no longer available in this composition.` });\n    return false;\n  }\n  const scope = workspaceId === undefined ? 'host' : 'repository';\n  patch(key, { saving: true, error: undefined });\n  const result = await writeSettingsValue(\n    {\n      repoRoot: entry.config.repoRoot,\n      scope,\n      keyPath: ['web', field],\n      value,\n      expectedHash: entry.config.hashes[scope],\n    },\n    workspaceId,\n  );\n  if (!result.ok) {\n    // Keep the conflict visible. A reload is explicit, never an automatic overwrite.\n    patch(key, { saving: false, error: result.error });\n    return false;\n  }\n  requests.set(key, (requests.get(key) ?? 0) + 1);\n  pendingRequests.delete(key);\n  patch(key, { config: result.config, saving: false, loading: false, error: undefined });\n  // Workspace views may inherit a newly saved host value.\n  if (workspaceId === undefined) {\n    await Promise.all(\n      Object.keys(templateStore.state)\n        .filter((cached) => cached.startsWith('workspace:'))\n        .map((cached) => refreshTemplateConfiguration(cached.slice('workspace:'.length))),\n    );\n  }\n  return true;\n}\n\nexport function configuredTemplate(entry: TemplateConfiguration): string | undefined {\n  return entry.config?.values[KEY]?.value;\n}\n\nexport function configuredBackdrop(entry: TemplateConfiguration): string | undefined {\n  return entry.config?.values[BACKDROP_KEY]?.value;\n}\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,QAA+B;CAAE,SAAS;CAAM,QAAQ;AAAM;AACpE,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,eAAe;AACrB,MAAM,2BAAW,IAAI,IAAoB;AACzC,MAAM,kCAAkB,IAAI,IAA2B;;AAGvD,MAAa,gBAAgB,WAAW,aAAa,IAAI,MAA6C,CAAC,CAAC,CAAC;AAEzG,SAAS,SAAS,aAA8B;CAC9C,OAAO,gBAAgB,KAAA,IAAY,OAAO,aAAa;AACzD;AAEA,SAAS,MAAM,KAAa,QAA8C;CACxE,cAAc,UAAU,WAAW;EAAE,GAAG;GAAQ,MAAM;GAAE,GAAI,MAAM,QAAQ;GAAQ,GAAG;EAAO;CAAE,EAAE;AAClG;AAEA,SAAgB,6BAA6B,aAAqC;CAChF,MAAM,MAAM,SAAS,WAAW;CAChC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