@uibot/cli 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +2 -0
  2. package/dist/app-host-template.json +1 -1
  3. package/dist/cli.js +2305 -160
  4. package/dist/commands/app.d.ts +2 -0
  5. package/dist/commands/data.d.ts +6 -0
  6. package/dist/commands/materialize.d.ts +7 -0
  7. package/dist/commands/spec.d.ts +7 -0
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +9370 -1155
  10. package/dist/resources/agent-kit/manifest.json +22 -2
  11. package/dist/resources/agent-kit/prompt-data/en.md +8 -0
  12. package/dist/resources/agent-kit/prompt-data/zh.md +8 -0
  13. package/dist/resources/agent-kit/prompt-documents/en.md +2 -0
  14. package/dist/resources/agent-kit/prompt-documents/zh.md +2 -0
  15. package/dist/resources/agent-kit/recipe-admin-workbench/en.md +9 -1
  16. package/dist/resources/agent-kit/recipe-admin-workbench/zh.md +9 -1
  17. package/dist/resources/agent-kit/uibot-architect/en.md +62 -0
  18. package/dist/resources/agent-kit/uibot-architect/zh.md +62 -0
  19. package/dist/resources/agent-kit/uibot-data-workbench/en.md +8 -0
  20. package/dist/resources/agent-kit/uibot-data-workbench/zh.md +8 -0
  21. package/dist/resources/agent-kit/uibot-knowledge-interface/en.md +2 -0
  22. package/dist/resources/agent-kit/uibot-knowledge-interface/zh.md +2 -0
  23. package/dist/resources/agent-kit/uibot-logo/en.md +25 -5
  24. package/dist/resources/agent-kit/uibot-logo/zh.md +25 -5
  25. package/dist/resources/bundle.json +1 -1
  26. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/admin-apps.json +61 -0
  27. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/admin-chats.json +54 -0
  28. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-settings-account.json +1 -1
  29. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-settings-appearance.json +1 -1
  30. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-settings-display.json +1 -1
  31. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-settings-notifications.json +1 -1
  32. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-settings-profile.json +1 -1
  33. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/admin-settings.json +65 -0
  34. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-shell.json +1 -1
  35. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/admin-tasks.json +66 -0
  36. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/admin-users.json +66 -0
  37. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/agent-run-console.json +64 -0
  38. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/auth-minimal.json +59 -0
  39. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/billing-overview.json +66 -0
  40. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/billing-usage-ledger.json +66 -0
  41. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-workspace.json +1 -1
  42. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/collection-kanban.json +134 -0
  43. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/collection-shared.json +1 -1
  44. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/commerce-workspace.json +1 -1
  45. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/console-billing.json +68 -0
  46. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/console-page.json +13 -13
  47. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/console-shell.json +29 -0
  48. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/creation-shared.json +2 -2
  49. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/crm-workspace.json +1 -1
  50. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/dashboard-01.json +78 -0
  51. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/data-crud-gallery.json +66 -0
  52. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/data-crud-kanban.json +66 -0
  53. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/data-crud-master-detail.json +66 -0
  54. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/data-crud-table.json +66 -0
  55. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/document-workspace.json +1 -1
  56. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/education-workspace.json +1 -1
  57. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/launch-site.json +72 -0
  58. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/layout.json +806 -0
  59. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/onboarding-checklist.json +63 -0
  60. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/onboarding-wizard.json +66 -0
  61. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/prompt-eval-workbench.json +65 -0
  62. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/record-master-detail.json +132 -0
  63. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/r/shadcn-admin.json +77 -0
  64. package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/workspace.json +1 -1
  65. package/dist/snapshots/d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773/snapshot.json +1 -0
  66. package/dist/templates/shadcn-admin.yaml +1491 -334
  67. package/package.json +13 -9
  68. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/admin-apps.json +0 -61
  69. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/admin-chats.json +0 -54
  70. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/admin-settings.json +0 -65
  71. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/admin-tasks.json +0 -66
  72. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/admin-users.json +0 -66
  73. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/console-billing.json +0 -68
  74. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/console-shell.json +0 -29
  75. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/dashboard-01.json +0 -78
  76. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/layout.json +0 -790
  77. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/r/shadcn-admin.json +0 -77
  78. package/dist/snapshots/4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f/snapshot.json +0 -1
  79. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/licenses/UIBot-LICENSE +0 -0
  80. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/licenses/blocks-icons-LICENSE +0 -0
  81. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/licenses/shadcn-THIRD_PARTY_LICENSE +0 -0
  82. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-dashboard.json +0 -0
  83. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-error-401.json +0 -0
  84. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-error-403.json +0 -0
  85. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-error-404.json +0 -0
  86. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-error-500.json +0 -0
  87. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-error-503.json +0 -0
  88. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-forgot-password.json +0 -0
  89. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-help.json +0 -0
  90. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-otp.json +0 -0
  91. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-overview.json +0 -0
  92. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-sign-in-2.json +0 -0
  93. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-sign-in.json +0 -0
  94. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/admin-sign-up.json +0 -0
  95. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/ai-chat.json +0 -0
  96. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/analytics-dashboard.json +0 -0
  97. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-floating.json +0 -0
  98. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-icon-rail.json +0 -0
  99. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-inset.json +0 -0
  100. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-settings.json +0 -0
  101. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-sidebar.json +0 -0
  102. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/app-shell-workspace.json +0 -0
  103. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth-centered.json +0 -0
  104. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth-enterprise.json +0 -0
  105. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth-recovery.json +0 -0
  106. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth-registration.json +0 -0
  107. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth-split.json +0 -0
  108. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/auth.json +0 -0
  109. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/blog.json +0 -0
  110. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/charts.json +0 -0
  111. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-artifact.json +0 -0
  112. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-focused.json +0 -0
  113. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-history.json +0 -0
  114. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-knowledge.json +0 -0
  115. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/chat-support.json +0 -0
  116. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/content.json +0 -0
  117. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/crm.json +0 -0
  118. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/dashboard.json +0 -0
  119. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/data-studio.json +0 -0
  120. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/data-table.json +0 -0
  121. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/data.json +0 -0
  122. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/document-assistant.json +0 -0
  123. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/document-library.json +0 -0
  124. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/document-reading.json +0 -0
  125. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/document-writing.json +0 -0
  126. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/drilldown-menu.json +0 -0
  127. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/ecommerce.json +0 -0
  128. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/feedback.json +0 -0
  129. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/field.json +0 -0
  130. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/form.json +0 -0
  131. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/grid.json +0 -0
  132. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/interactive.json +0 -0
  133. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/item-grid.json +0 -0
  134. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/kanban.json +0 -0
  135. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/lms.json +0 -0
  136. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/marketing.json +0 -0
  137. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/nav.json +0 -0
  138. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/portfolio.json +0 -0
  139. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/presentation.json +0 -0
  140. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/pricing.json +0 -0
  141. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/primitives.json +0 -0
  142. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/saas-landing.json +0 -0
  143. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sections.json +0 -0
  144. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/settings.json +0 -0
  145. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/shadcn-admin-shell.json +0 -0
  146. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-01.json +0 -0
  147. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-02.json +0 -0
  148. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-03.json +0 -0
  149. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-04.json +0 -0
  150. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-05.json +0 -0
  151. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-06.json +0 -0
  152. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-07.json +0 -0
  153. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-08.json +0 -0
  154. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-09.json +0 -0
  155. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-10.json +0 -0
  156. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-11.json +0 -0
  157. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-12.json +0 -0
  158. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-13.json +0 -0
  159. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-14.json +0 -0
  160. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-15.json +0 -0
  161. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-16.json +0 -0
  162. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-drilldown.json +0 -0
  163. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/sidebar-primitives.json +0 -0
  164. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/store.json +0 -0
  165. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/support-inbox.json +0 -0
  166. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/team-directory.json +0 -0
  167. /package/dist/snapshots/{4501a880e17691677109b35118b89434252d4e65aa7b9a7c3a174a38ce2b418f → d7bd93f1056f9b65c17b3146d456b92f6acffa6afe32bc53ee20bcca4a946773}/r/uibot-base.json +0 -0
@@ -1 +1 @@
1
- {"contract":"uibot.app-host-template.v1","version":"0.20.0","files":{"src/app.tsx":"import \"./app-styles.css\";\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { compileSpec, parseConfig } from \"@uibot/compiler\";\nimport type {\n AppDocument,\n CompiledUIBotSpec,\n LinkedSpecIdentity,\n UIBotSpec,\n LinkedAppSnapshot,\n AppRelease,\n} from \"@uibot/contracts\";\nimport { createShadcnReactRegistry, CATALOG_ENTRIES, ScrollArea } from \"@uibot/blocks-shadcn\";\nimport {\n createLinkedAppSync,\n createPublishedAppSync,\n createPublishedAppHttpReader,\n createLinkedSpecHttpReader,\n verifyAppModules,\n UIBotAppHost,\n type LinkedSpecStatus,\n} from \"@uibot/runtime\";\nimport LocalPage from \"./app-local\";\nimport localSource from \"./app-local.tsx?raw\";\nimport { AppPageNavigator } from \"./app-page-navigator\";\nimport { createAppNavigation } from \"./app-navigation\";\nimport { protectUnsavedUnload } from \"./admin-navigation\";\nimport {\n createLinkedAppRuntime,\n createLinkedTasksDriver,\n prepareLinkedAppSource,\n} from \"./app-runtime\";\nimport type { AppRoutePage } from \"./app-route-tree\";\nimport { bindCompiledSessionIdentity } from \"./app-session-source\";\nimport { createAppSessionClient, type AppSessionClient } from \"./app-session-client\";\nimport { createLinkedAdminDriver, createAdminSummaryDriver } from \"./admin-business-driver\";\nimport { accountFlowKey, accountPageState, isAccountRoute } from \"./app-account-source\";\nimport \"./admin.css\";\nimport \"./app-shell.css\";\nconst registry = createShadcnReactRegistry();\nconst catalog = { components: CATALOG_ENTRIES, actions: {}, templates: {} };\nconst sha256 = async (text: string) =>\n Array.from(\n new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text))),\n (b) => b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\nfunction Consumer({\n identity,\n installedHash,\n channel,\n intervalMs = 1000,\n demoData,\n tasksData,\n adminData = false,\n accountFlows = false,\n session,\n sessionState,\n returnPath = \"/tasks\",\n}: {\n identity: LinkedSpecIdentity;\n installedHash: string;\n channel: \"development\" | \"production\";\n intervalMs?: number;\n demoData: boolean;\n tasksData: boolean;\n adminData?: boolean;\n accountFlows?: boolean;\n session?: AppSessionClient;\n sessionState?: ReturnType<AppSessionClient[\"snapshot\"]>;\n returnPath?: string;\n}) {\n const [status, setStatus] = useState<LinkedSpecStatus>(\"loading\");\n const [checking, setChecking] = useState(false);\n const [signingOut, setSigningOut] = useState(false);\n const retry = useRef<(() => Promise<void>) | undefined>(undefined);\n const activeRuntime = useRef<ReturnType<typeof createLinkedAppRuntime> | undefined>(undefined);\n useEffect(() => {\n const unload = (event: BeforeUnloadEvent) =>\n protectUnsavedUnload(event, Boolean(activeRuntime.current?.pendingPages().length));\n window.addEventListener(\"beforeunload\", unload);\n return () => window.removeEventListener(\"beforeunload\", unload);\n }, []);\n const [route, setRoute] = useState(window.location.pathname);\n const navigation = useMemo(\n () =>\n createAppNavigation({\n readUrl: () => window.location.href,\n writeUrl: (url, replace) =>\n window.history[replace ? \"replaceState\" : \"pushState\"](window.history.state, \"\", url),\n onRoute: setRoute,\n }),\n [],\n );\n useEffect(() => {\n const pop = () => {\n navigation.navigate(window.location.href);\n };\n window.addEventListener(\"popstate\", pop);\n return () => window.removeEventListener(\"popstate\", pop);\n }, [navigation]);\n const [counter, setCounter] = useState(0);\n const [detailsOpen, setDetailsOpen] = useState(false);\n const [navigatorOpen, setNavigatorOpen] = useState(false);\n const navigatorToggle = useRef<HTMLButtonElement>(null);\n const canvas = useRef<HTMLElement>(null);\n const [current, setCurrent] = useState<{\n document: AppDocument;\n spec: CompiledUIBotSpec;\n runtime: ReturnType<typeof createLinkedAppRuntime>;\n revision?: number;\n revisionId: string;\n release?: number;\n }>();\n useEffect(() => {\n const follow =\n channel === \"production\"\n ? createPublishedAppSync<CompiledUIBotSpec>\n : createLinkedAppSync<CompiledUIBotSpec>;\n const sync = follow({\n ...identity,\n intervalMs,\n read: (channel === \"production\" ? createPublishedAppHttpReader : createLinkedSpecHttpReader)({\n url: \"/linked-app.json\",\n }),\n canApply: () => !activeRuntime.current?.pendingPages().length,\n prepare: async (snapshot) => {\n await verifyAppModules(snapshot.document, { \"local-about\": { sourceHash: installedHash } });\n const result = await compileSpec(\n prepareLinkedAppSource(\n parseConfig(snapshot.document.spec) as UIBotSpec,\n tasksData,\n Boolean(session),\n adminData,\n accountFlows,\n ),\n catalog,\n { strict: true },\n );\n if (\n result.gaps.length ||\n Object.values(result.spec.blocks).some((block) => !registry.get(block.type))\n )\n throw Error(\"Application dependencies unavailable\");\n if (session) bindCompiledSessionIdentity(result.spec, session.snapshot().info?.user);\n return result.spec;\n },\n apply: (spec, snapshot: LinkedAppSnapshot | AppRelease) => {\n const runtime = createLinkedAppRuntime({\n spec,\n source: parseConfig(snapshot.document.spec) as UIBotSpec,\n identity,\n demoData,\n tasksDriver: tasksData\n ? (adminData ? createLinkedAdminDriver : createLinkedTasksDriver)({\n url: window.location.origin,\n ...(session ? { fetch: session.fetch } : {}),\n })\n : undefined,\n authDriver: session?.driver,\n summaryDriver: adminData && session ? createAdminSummaryDriver(session.fetch) : undefined,\n adminData,\n canBatch: session ? () => session.snapshot().info?.canBatch === true : undefined,\n storage: sessionStorage,\n navigate: (destination) => {\n navigation.navigate(destination);\n },\n });\n activeRuntime.current = runtime;\n setCurrent({\n document: snapshot.document,\n spec,\n revisionId: snapshot.revisionId,\n ...(\"releaseSequence\" in snapshot\n ? { release: snapshot.releaseSequence }\n : { revision: snapshot.revisionNumber }),\n runtime,\n });\n if (window.location.pathname === \"/app.html\")\n navigation.navigate(\n snapshot.document.entryPath + window.location.search + window.location.hash,\n true,\n );\n },\n onStatus: setStatus,\n });\n retry.current = sync.refresh;\n return () => {\n retry.current = undefined;\n sync.stop();\n activeRuntime.current = undefined;\n };\n }, [\n identity,\n installedHash,\n channel,\n intervalMs,\n navigation,\n demoData,\n tasksData,\n adminData,\n accountFlows,\n session,\n ]);\n useEffect(() => () => current?.runtime.dispose(), [current]);\n const visible = status === \"denied\" || status === \"unpublished\" ? undefined : current;\n const returnRoute = useRef<string>(returnPath);\n const authenticated = !session || Boolean(sessionState?.info);\n useEffect(() => {\n if (!session || !sessionState?.ready) return;\n if (!authenticated) {\n if (!(accountFlows ? isAccountRoute(route) : route.startsWith(\"/sign-in\"))) {\n returnRoute.current = route;\n navigation.navigate(\"/sign-in\", true);\n }\n } else if (isAccountRoute(route)) navigation.navigate(returnRoute.current, true);\n }, [session, sessionState?.ready, authenticated, navigation, route, accountFlows]);\n const displayRoute =\n authenticated || (accountFlows && isAccountRoute(route)) ? route : \"/sign-in\";\n useEffect(() => {\n if (!current || !accountFlows || authenticated) return;\n const otp = current.runtime.forPage(\"/otp\");\n const sync = () => {\n void otp.dispatch(\n Object.entries(\n accountPageState(\n sessionState?.accountFlow ?? null,\n Date.now(),\n sessionState?.accountPending,\n otp.snapshot().accountFlowKey,\n ),\n ).map(([path, value]) => ({ action: \"SetState\", params: { path, value } })),\n );\n };\n sync();\n const interval = window.setInterval(sync, 1000);\n return () => clearInterval(interval);\n }, [\n current,\n accountFlows,\n authenticated,\n sessionState?.accountFlow,\n sessionState?.accountPending,\n ]);\n useEffect(() => {\n current?.runtime.refreshPermissions(sessionState?.info?.canBatch);\n }, [current, sessionState?.info?.canBatch]);\n useEffect(() => {\n if (!current || !session || !authenticated || !accountFlows) return;\n // Verified sign-in completes anonymous forms, including a same-user reauthentication.\n for (const page of current.spec.pages.filter((page) => isAccountRoute(page.path)))\n void current.runtime.forPage(page.path).dispatch([\n { action: \"SetState\", params: { path: \"accountDirty\", value: false } },\n { action: \"SetState\", params: { path: \"accountPending\", value: false } },\n ]);\n }, [current, session, authenticated, accountFlows]);\n const statusLabels: Record<LinkedSpecStatus, string> = {\n loading: \"Connecting\",\n synced: \"Connected\",\n offline: \"Connection interrupted\",\n denied: \"Access required\",\n conflict: \"Update waiting\",\n invalid: \"Update unavailable\",\n unpublished: \"Not published\",\n };\n async function checkConnection() {\n if (!retry.current || checking) return;\n setChecking(true);\n try {\n await retry.current();\n } finally {\n setChecking(false);\n }\n }\n const retryAction = (\n <button\n type=\"button\"\n className=\"linked-app-retry\"\n disabled={checking}\n onClick={() => void checkConnection()}\n >\n {checking ? \"Checking…\" : \"Retry connection\"}\n </button>\n );\n const pages = useMemo<AppRoutePage[]>(\n () =>\n visible\n ? [\n ...visible.spec.pages\n .filter(\n (page) =>\n authenticated ||\n (accountFlows ? isAccountRoute(page.path) : page.path.startsWith(\"/sign-in\")),\n )\n .map((page) => ({\n path: page.path,\n title: page.title ?? page.id,\n format: \"Spec\" as const,\n })),\n ...(authenticated ? visible.document.tsx : []).map((page) => ({\n path: page.path,\n title: page.title,\n format: \"TSX\" as const,\n })),\n ]\n : [],\n [visible, authenticated, accountFlows],\n );\n const selectPage = (path: string) => {\n navigation.navigate(path);\n if (window.matchMedia(\"(max-width: 640px)\").matches) {\n setNavigatorOpen(false);\n navigatorToggle.current?.focus();\n }\n };\n useEffect(() => {\n const click = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey ||\n !(event.target instanceof Element)\n )\n return;\n const anchor = event.target.closest<HTMLAnchorElement>(\"a[href]\");\n if (\n !anchor ||\n !canvas.current?.contains(anchor) ||\n anchor.hasAttribute(\"download\") ||\n (anchor.target && anchor.target !== \"_self\")\n )\n return;\n const url = new URL(anchor.href);\n if (pages.some((page) => page.path === url.pathname) && navigation.navigate(url.href))\n event.preventDefault();\n };\n document.addEventListener(\"click\", click);\n return () => document.removeEventListener(\"click\", click);\n }, [navigation, pages]);\n const selectedPage = visible?.spec.pages.find((page) => page.path === displayRoute);\n const hasFrame = selectedPage?.rootBlockIds.some(\n (id) => visible?.spec.blocks[id]?.type === \"PageLayout\",\n );\n const renderSpecPage = (path: string) =>\n visible && (\n <UIBotAppHost\n key={\n path === \"/otp\"\n ? `${path}:${accountFlowKey(sessionState?.accountFlow ?? null)}`\n : \"business\"\n }\n spec={visible.spec}\n registry={registry}\n adapter={visible.runtime.forPage(path)}\n pagePath={path}\n fallback={(resolution) => <p role=\"alert\">{resolution.status}</p>}\n />\n );\n // Keep anonymous form DOM in memory across routes; credentials never enter Spec state.\n const specPreview =\n visible && accountFlows && !authenticated\n ? visible.spec.pages\n .filter((page) => isAccountRoute(page.path))\n .map((page) => (\n <div key={page.path} hidden={page.path !== displayRoute}>\n {renderSpecPage(page.path)}\n </div>\n ))\n : renderSpecPage(displayRoute);\n return (\n <main className=\"linked-app\">\n <header className=\"linked-app-bar\">\n <button\n type=\"button\"\n className=\"linked-app-navigator-toggle\"\n ref={navigatorToggle}\n aria-label={navigatorOpen ? \"Hide page navigator\" : \"Show page navigator\"}\n title={navigatorOpen ? \"Hide page navigator\" : \"Show page navigator\"}\n aria-expanded={navigatorOpen}\n aria-controls=\"app-page-navigator\"\n onClick={() => setNavigatorOpen((open) => !open)}\n >\n <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M9 4v16\" />\n <path d={navigatorOpen ? \"m6 10-2 2 2 2\" : \"m5 10 2 2-2 2\"} />\n </svg>\n </button>\n <div className=\"linked-app-brand\">\n <span className=\"linked-app-mark\" aria-hidden=\"true\">\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\" fill=\"none\">\n <path d=\"m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3Z\" />\n <path d=\"m4 7.5 8 4.5 8-4.5M12 12v9M8 5.25l8 4.5\" />\n </svg>\n </span>\n <div className=\"linked-app-identity\">\n <h1 title={visible?.document.title}>\n {visible?.document.title ?? \"Application preview\"}\n </h1>\n <span>\n {channel === \"production\" ? \"Published application\" : \"Development preview\"}\n </span>\n </div>\n </div>\n <div className=\"linked-app-actions\">\n {session && sessionState?.info && (\n <div className=\"linked-app-account\">\n <span title={sessionState.info.user.email}>{sessionState.info.user.email}</span>\n <small>{sessionState.info.user.role === \"admin\" ? \"Administrator\" : \"Member\"}</small>\n <button\n className=\"linked-app-retry\"\n type=\"button\"\n disabled={signingOut}\n onClick={() => {\n if (\n activeRuntime.current?.pendingPages().length &&\n !window.confirm(\"Sign out and discard your unsaved work?\")\n )\n return;\n setSigningOut(true);\n void session.logout().finally(() => setSigningOut(false));\n }}\n >\n {signingOut ? \"Signing out…\" : \"Sign out\"}\n </button>\n </div>\n )}\n <div className=\"linked-app-connection\" role=\"status\" aria-live=\"polite\">\n <span className=\"linked-app-status\" data-status={status}>\n <span aria-hidden=\"true\" />\n {statusLabels[status]}\n </span>\n <span className=\"linked-app-revision\">\n {visible?.release\n ? `Release ${visible.release} · ${visible.revisionId.slice(0, 8)}`\n : visible\n ? `Revision ${visible.revision}`\n : channel === \"production\"\n ? \"No release loaded\"\n : \"No revision loaded\"}\n </span>\n </div>\n <button\n type=\"button\"\n className=\"linked-app-details-toggle\"\n aria-expanded={detailsOpen}\n aria-controls=\"preview-details\"\n onClick={() => setDetailsOpen((open) => !open)}\n >\n <svg aria-hidden=\"true\" viewBox=\"0 0 20 20\" fill=\"none\">\n <circle cx=\"10\" cy=\"10\" r=\"7\" />\n <path d=\"M10 9v4m0-7v.2\" />\n </svg>\n <span>Preview details</span>\n </button>\n </div>\n </header>\n {visible && (\n <div className=\"linked-app-data-notice\" role=\"status\">\n {adminData && authenticated\n ? \"Connected workspace · Your session controls access. Changes persist in the test database.\"\n : tasksData\n ? session && !authenticated\n ? \"Sign in to access your workspace. Business records are scoped to your account.\"\n : route === \"/tasks\"\n ? session\n ? \"Tasks · Your account’s records. Changes persist in the connected test database.\"\n : \"Tasks · Connected to the development database. Changes are shared and persist after refresh.\"\n : \"Tasks is connected. Business services for this page are not connected.\"\n : demoData\n ? \"Demo data · Changes are saved only in this browser tab.\"\n : \"Business services are not connected. Data actions require a host connection.\"}\n </div>\n )}\n <section id=\"preview-details\" className=\"linked-app-details\" hidden={!detailsOpen}>\n <div>\n <h2>\n {channel === \"production\" ? \"Production release channel\" : \"Development environment\"}\n </h2>\n <p>\n {channel === \"production\"\n ? \"Only explicit releases update this application. There is no development fallback.\"\n : \"Saved changes sync here automatically.\"}\n {tasksData &&\n (session\n ? \" Business pages use individual user sessions in this local test host. Credentials stay on the server; a production host is still required.\"\n : \" Tasks uses a development server connection; production user authentication is not configured.\")}\n </p>\n </div>\n <button type=\"button\" onClick={() => setCounter((n) => n + 1)}>\n Local TSX counter: {counter}\n </button>\n </section>\n {sessionState?.error && (\n <div className=\"linked-app-notice\" role=\"alert\">\n {sessionState.error}\n </div>\n )}\n {sessionState?.info && !sessionState.info.canBatch && (\n <div className=\"linked-app-notice\" role=\"status\">\n Signed in as a member. Your records and settings are private; the business directory and\n batch actions require an application administrator.\n </div>\n )}\n {visible && status === \"conflict\" && (\n <div className=\"linked-app-notice\" role=\"status\">\n <p>\n An application update is waiting. Save or close your pending forms first. Your current\n work is preserved; the update will apply automatically when ready.\n </p>\n {visible.runtime.pendingPages().map((page) => (\n <button\n type=\"button\"\n className=\"linked-app-retry\"\n key={page.path}\n onClick={() => selectPage(page.path)}\n >\n Review {page.title}\n </button>\n ))}\n </div>\n )}\n {visible && (status === \"offline\" || status === \"invalid\") && (\n <div className=\"linked-app-notice\" role=\"status\">\n <p>\n {status === \"offline\"\n ? \"Connection interrupted. You can keep viewing the last loaded version.\"\n : \"The latest version could not be loaded. The last working version is still displayed.\"}\n </p>\n {retryAction}\n </div>\n )}\n <div className=\"linked-app-body\" data-navigator-open={navigatorOpen}>\n <AppPageNavigator\n open={navigatorOpen}\n pages={pages}\n route={route}\n onSelect={selectPage}\n onClose={() => {\n setNavigatorOpen(false);\n navigatorToggle.current?.focus();\n }}\n />\n <section className=\"linked-app-canvas\" aria-label=\"Application preview\" ref={canvas}>\n {visible && status !== \"denied\" && (\n <>\n <style>{visible.document.css}</style>\n {authenticated && visible.document.tsx.some((page) => page.path === route) ? (\n <ScrollArea\n style={{ height: \"100%\" }}\n viewportProps={{ \"aria-label\": \"Page content\" }}\n >\n <div className=\"linked-app-module\">\n <LocalPage key={visible.document.tsx.find((page) => page.path === route)?.id} />\n </div>\n </ScrollArea>\n ) : hasFrame ? (\n specPreview\n ) : (\n <ScrollArea\n style={{ height: \"100%\" }}\n viewportProps={{ \"aria-label\": \"Page content\" }}\n >\n {specPreview}\n </ScrollArea>\n )}\n </>\n )}\n {!visible && (\n <ScrollArea style={{ height: \"100%\" }}>\n <div className=\"linked-app-empty\" role=\"status\">\n <span className=\"linked-app-empty-mark\" aria-hidden=\"true\">\n ◇\n </span>\n <h2>\n {status === \"denied\"\n ? \"Application access unavailable\"\n : status === \"unpublished\"\n ? \"Application not published yet\"\n : status === \"offline\"\n ? \"Cannot connect to this application\"\n : status === \"invalid\"\n ? \"This version could not be loaded\"\n : \"Connecting your application\"}\n </h2>\n <p>\n {status === \"denied\"\n ? \"Check your workspace access, then reload this page.\"\n : status === \"unpublished\"\n ? \"Publish a saved revision in NowUI to make it available here.\"\n : status === \"offline\"\n ? \"Check the application service connection, then try again.\"\n : status === \"invalid\"\n ? \"The saved version needs a compatibility check. Open NowUI to review it before trying again.\"\n : \"Your saved application will appear here when the connection is ready.\"}\n </p>\n {[\"denied\", \"offline\", \"invalid\"].includes(status) && retryAction}\n </div>\n </ScrollArea>\n )}\n </section>\n </div>\n </main>\n );\n}\nconst root = document.getElementById(\"root\");\nfunction SessionConsumer({\n client,\n ...props\n}: Parameters<typeof Consumer>[0] & { client: AppSessionClient }) {\n const state = useSyncExternalStore(client.subscribe, client.snapshot);\n const returnPath = useRef(\n isAccountRoute(window.location.pathname) ? \"/tasks\" : window.location.pathname,\n );\n useEffect(() => {\n void client.load();\n const interval = window.setInterval(() => void client.load(), 30000);\n const focus = () => void client.load();\n window.addEventListener(\"focus\", focus);\n return () => {\n clearInterval(interval);\n window.removeEventListener(\"focus\", focus);\n };\n }, [client]);\n return state.ready ? (\n <Consumer\n key={state.lastUserId ?? \"anonymous\"}\n {...props}\n session={client}\n sessionState={state}\n returnPath={returnPath.current}\n />\n ) : (\n <main className=\"linked-app-empty\" role=\"status\">\n Checking your session…\n </main>\n );\n}\nif (!root) throw Error(\"No root\");\nvoid Promise.all([\n fetch(\"/linked-app-config.json\").then(async (response) => {\n if (!response.ok) throw Error(\"Configure UIBOT_LINKED_APP_URL\");\n const config = (await response.json()) as LinkedSpecIdentity & {\n channel?: string;\n intervalMs?: number;\n demoData?: boolean;\n tasksData?: boolean;\n sessions?: boolean;\n adminData?: boolean;\n accountFlows?: boolean;\n };\n if (config.demoData !== undefined && typeof config.demoData !== \"boolean\")\n throw Error(\"Invalid demo data configuration\");\n if (\n (config.tasksData !== undefined && typeof config.tasksData !== \"boolean\") ||\n (config.tasksData && config.demoData)\n )\n throw Error(\"Invalid business data configuration\");\n if (config.channel !== undefined && ![\"development\", \"production\"].includes(config.channel))\n throw Error(\"Invalid application channel\");\n if (\n config.intervalMs !== undefined &&\n (!Number.isSafeInteger(config.intervalMs) ||\n config.intervalMs < 250 ||\n config.intervalMs > 60000)\n )\n throw Error(\"Invalid polling interval\");\n if (\n config.sessions !== undefined &&\n (typeof config.sessions !== \"boolean\" || (config.sessions && !config.tasksData))\n )\n throw Error(\"Invalid session configuration\");\n if (\n config.adminData !== undefined &&\n (typeof config.adminData !== \"boolean\" || (config.adminData && !config.sessions))\n )\n throw Error(\"Admin business pages require per-user sessions\");\n if (\n config.accountFlows !== undefined &&\n (typeof config.accountFlows !== \"boolean\" || (config.accountFlows && !config.sessions))\n )\n throw Error(\"Account flows require per-user sessions\");\n return {\n identity: { projectId: config.projectId, artifactId: config.artifactId },\n channel: (config.channel ?? \"development\") as \"development\" | \"production\",\n intervalMs: config.intervalMs ?? 1000,\n demoData: config.demoData === true,\n tasksData: config.tasksData === true,\n sessions: config.sessions === true,\n adminData: config.adminData === true,\n accountFlows: config.accountFlows === true && config.sessions === true,\n };\n }),\n sha256(localSource),\n])\n .then(([config, installedHash]) => {\n const props = {\n identity: config.identity,\n channel: config.channel,\n intervalMs: config.intervalMs,\n demoData: config.demoData,\n tasksData: config.tasksData,\n adminData: config.adminData,\n accountFlows: config.accountFlows,\n installedHash,\n };\n createRoot(root).render(\n config.sessions ? (\n <SessionConsumer {...props} client={createAppSessionClient(window.location.origin)} />\n ) : (\n <Consumer {...props} />\n ),\n );\n })\n .catch(() =>\n createRoot(root).render(\n <main className=\"linked-app\">\n <div className=\"linked-app-empty\" role=\"alert\">\n <h2>Application connection unavailable</h2>\n <p>Check the server connection settings, then reload this page.</p>\n <button\n className=\"linked-app-retry\"\n type=\"button\"\n onClick={() => window.location.reload()}\n >\n Reload application\n </button>\n </div>\n </main>,\n ),\n );\n","src/app-local.tsx":"import { useState } from \"react\";\nexport default function Example() {\n const [count, setCount] = useState(0);\n return (\n <section>\n <h1>Installed TSX page</h1>\n <button type=\"button\" onClick={() => setCount((value) => value + 1)}>\n TSX page counter: {count}\n </button>\n </section>\n );\n}\n","src/app-page-navigator.tsx":"import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { ScrollArea } from \"@uibot/blocks-shadcn\";\nimport { appRouteTree, type AppRouteNode, type AppRoutePage } from \"./app-route-tree\";\n\nexport function AppPageNavigator({\n open,\n pages,\n route,\n onSelect,\n onClose,\n}: {\n open: boolean;\n pages: AppRoutePage[];\n route: string;\n onSelect: (path: string) => void;\n onClose: () => void;\n}) {\n const [query, setQuery] = useState(\"\");\n const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());\n const current = useRef<HTMLButtonElement>(null);\n const panel = useRef<HTMLElement>(null);\n const nodes = useMemo(() => appRouteTree(pages, query), [pages, query]);\n useEffect(() => {\n if (!open) return;\n setCollapsed(\n (previous) => new Set([...previous].filter((path) => !route.startsWith(`${path}/`))),\n );\n const frame = requestAnimationFrame(() =>\n current.current?.scrollIntoView({ block: \"nearest\" }),\n );\n return () => cancelAnimationFrame(frame);\n }, [route, open]);\n useEffect(() => {\n const closeOnEscape = (event: KeyboardEvent) => {\n if (\n event.key === \"Escape\" &&\n event.target instanceof Node &&\n panel.current?.contains(event.target)\n ) {\n event.preventDefault();\n event.stopPropagation();\n onClose();\n }\n };\n document.addEventListener(\"keydown\", closeOnEscape);\n return () => document.removeEventListener(\"keydown\", closeOnEscape);\n }, [onClose]);\n const toggle = (path: string) =>\n setCollapsed((previous) => {\n const next = new Set(previous);\n if (next.has(path)) next.delete(path);\n else next.add(path);\n return next;\n });\n function renderNodes(items: AppRouteNode[]) {\n return items.map((node) => {\n const branch = node.children.length > 0;\n const expanded = Boolean(query.trim()) || !collapsed.has(node.path);\n const selected = node.page?.path === route;\n return (\n <li key={node.path}>\n <div className=\"app-route-row\" data-selected={selected}>\n {branch ? (\n <button\n type=\"button\"\n className=\"app-route-disclosure\"\n aria-label={`${expanded ? \"Collapse\" : \"Expand\"} ${node.path}`}\n aria-expanded={expanded}\n onClick={() => toggle(node.path)}\n disabled={Boolean(query.trim())}\n >\n <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" data-expanded={expanded}>\n <path d=\"m6 4 4 4-4 4\" />\n </svg>\n </button>\n ) : (\n <span className=\"app-route-spacer\" />\n )}\n <button\n type=\"button\"\n className=\"app-route-target\"\n ref={selected ? current : undefined}\n aria-current={selected ? \"page\" : undefined}\n aria-label={\n node.page\n ? `${node.page.title} (${node.path})`\n : `${expanded ? \"Collapse\" : \"Expand\"} folder ${node.path}`\n }\n aria-expanded={!node.page && branch ? expanded : undefined}\n disabled={!node.page && Boolean(query.trim())}\n onClick={() => (node.page ? onSelect(node.page.path) : toggle(node.path))}\n >\n <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n {branch ? (\n <path d=\"M2.5 5.5h5l2-2h3l2 2h3v11h-15Z\" />\n ) : (\n <>\n <path d=\"M5 2.5h6l4 4v11H5Z\" />\n <path d=\"M11 2.5v4h4\" />\n </>\n )}\n </svg>\n <span>\n <strong>{node.page?.title ?? node.segment}</strong>\n <small>{node.path}</small>\n </span>\n {node.page && <em>{node.page.format}</em>}\n </button>\n </div>\n {branch && expanded && <ul>{renderNodes(node.children)}</ul>}\n </li>\n );\n });\n }\n return (\n <aside\n hidden={!open}\n ref={panel}\n className=\"app-page-navigator\"\n id=\"app-page-navigator\"\n aria-label=\"Page navigator\"\n >\n <div className=\"app-page-navigator-heading\">\n <h2>Pages</h2>\n <span>{pages.length}</span>\n </div>\n <label className=\"app-route-search\">\n <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n <circle cx=\"8.5\" cy=\"8.5\" r=\"5.5\" />\n <path d=\"m13 13 4 4\" />\n </svg>\n <input\n aria-label=\"Search pages or routes\"\n placeholder=\"Search pages or routes…\"\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n />\n {query && (\n <button type=\"button\" aria-label=\"Clear page search\" onClick={() => setQuery(\"\")}>\n ×\n </button>\n )}\n </label>\n <ScrollArea className=\"app-route-tree\" viewportProps={{ \"aria-label\": \"Application pages\" }}>\n <nav aria-label=\"Application pages\">\n <ul>{renderNodes(nodes)}</ul>\n {!nodes.length && (\n <p className=\"app-route-empty\">No matching pages. Try another name or route.</p>\n )}\n </nav>\n </ScrollArea>\n <p className=\"app-page-navigator-footer\">Select a page to preview</p>\n </aside>\n );\n}\n","src/app-route-tree.ts":"export interface AppRoutePage {\n path: string;\n title: string;\n format: \"Spec\" | \"TSX\";\n}\nexport interface AppRouteNode {\n path: string;\n segment: string;\n page?: AppRoutePage;\n children: AppRouteNode[];\n}\n\n/** Group only by full path segments; titles never establish route ancestry. */\nexport function appRouteTree(pages: AppRoutePage[], query = \"\"): AppRouteNode[] {\n const roots: AppRouteNode[] = [];\n const index = new Map<string, AppRouteNode>();\n const search = query.trim().toLowerCase();\n for (const page of pages) {\n if (!`${page.title} ${page.path} ${page.format}`.toLowerCase().includes(search)) continue;\n let siblings = roots;\n let path = \"\";\n const segments = page.path === \"/\" ? [\"\"] : page.path.slice(1).split(\"/\");\n for (const [position, segment] of segments.entries()) {\n path += `/${segment}`;\n let node = index.get(path);\n if (!node) {\n node = { path, segment: segment || \"/\", children: [] };\n index.set(path, node);\n siblings.push(node);\n }\n if (position === segments.length - 1) node.page = page;\n siblings = node.children;\n }\n }\n return roots;\n}\n","src/app-navigation.ts":"/** The consumer owns browser history; runtime and installed modules share this route. */\nexport function createAppNavigation(port: {\n readUrl: () => string;\n writeUrl: (url: string, replace: boolean) => void;\n onRoute: (path: string) => void;\n}) {\n return {\n navigate(destination: string, replace = false): boolean {\n let url: URL;\n const current = new URL(port.readUrl());\n try {\n url = new URL(destination, current);\n } catch {\n return false;\n }\n if (url.origin !== current.origin || ![\"http:\", \"https:\"].includes(url.protocol))\n return false;\n if (url.href !== current.href) port.writeUrl(url.pathname + url.search + url.hash, replace);\n port.onRoute(url.pathname);\n return true;\n },\n };\n}\n","src/admin-navigation.ts":"type NavigationPorts = {\n index: number;\n isDirty(): boolean;\n push(url: string, index: number): void;\n go(delta: number): void;\n commit(url: string): void;\n prompt(decide: (discard: boolean) => void): void;\n};\n\ntype Pending =\n | { kind: \"link\"; url: string }\n | { kind: \"pop\"; delta: number; phase: \"restore\" | \"prompt\" | \"travel\" };\n\nexport function createAdminNavigation(ports: NavigationPorts) {\n let index = ports.index;\n let pending: Pending | undefined;\n function ask() {\n const request = pending;\n ports.prompt((discard) => {\n if (!request || pending !== request) return;\n if (!discard) {\n pending = undefined;\n } else if (request.kind === \"link\") {\n pending = undefined;\n ports.push(request.url, ++index);\n ports.commit(request.url);\n } else {\n request.phase = \"travel\";\n ports.go(request.delta);\n }\n });\n }\n return {\n link(url: string) {\n if (pending) return;\n if (ports.isDirty()) {\n pending = { kind: \"link\", url };\n ask();\n } else {\n ports.push(url, ++index);\n ports.commit(url);\n }\n },\n pop(nextIndex: number, url: string) {\n if (pending?.kind === \"pop\") {\n if (pending.phase === \"travel\") {\n pending = undefined;\n index = nextIndex;\n ports.commit(url);\n } else if (nextIndex !== index) {\n ports.go(index - nextIndex);\n } else if (pending.phase === \"restore\") {\n pending.phase = \"prompt\";\n ask();\n }\n return;\n }\n if (nextIndex !== index && (pending || ports.isDirty())) {\n pending = { kind: \"pop\", delta: nextIndex - index, phase: \"restore\" };\n ports.go(index - nextIndex);\n } else if (!pending) {\n index = nextIndex;\n ports.commit(url);\n }\n },\n };\n}\n\nfunction fingerprint(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(fingerprint).join(\",\")}]`;\n if (value && typeof value === \"object\")\n return `{${Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => `${JSON.stringify(key)}:${fingerprint(item)}`)\n .join(\",\")}}`;\n return JSON.stringify(value) ?? \"null\";\n}\n\nexport function createFormDirtyTracker(initial: Record<string, unknown>) {\n // Request clears loading before its onSuccess assigns form from preferences.\n const loadedForm = (state: Record<string, unknown>) => {\n const record = Array.isArray(state.preferences) ? state.preferences[0] : undefined;\n return record?.values ?? state.form;\n };\n let baseline = fingerprint(loadedForm(initial));\n let dirty = false;\n let initialRead = false;\n let initialReadFinished = false;\n let wasSaved = initial.saved === true;\n let successfulSave = false;\n let reloaded = initial.settingsReloaded;\n return {\n update(state: Record<string, unknown>) {\n const current = fingerprint(state.form);\n if (state.settingsReloaded !== reloaded) {\n reloaded = state.settingsReloaded;\n if (!state.uiError && !state.loading && !state.saving) baseline = current;\n }\n if (!initialReadFinished && state.loading && !state.saving && !dirty) initialRead = true;\n if (initialRead && !state.loading) {\n initialRead = false;\n initialReadFinished = true;\n if (!state.uiError) baseline = fingerprint(loadedForm(state));\n }\n if (state.saved === true && !wasSaved) successfulSave = true;\n if (state.saved !== true || state.uiError) successfulSave = false;\n if (successfulSave && !state.loading && !state.saving) {\n baseline = current;\n successfulSave = false;\n }\n wasSaved = state.saved === true;\n dirty = initialRead ? false : current !== baseline;\n return dirty;\n },\n };\n}\n\nexport function protectUnsavedUnload(\n event: { preventDefault(): void; returnValue: string },\n dirty: boolean,\n) {\n if (!dirty) return;\n event.preventDefault();\n event.returnValue = \"\";\n}\n\nexport function hasUnsavedAdminEditor(state: Record<string, unknown>): boolean {\n const computed = state.__computed as Record<string, unknown> | undefined;\n return state.editorOpen === true && computed?.editorDirty === true;\n}\n","src/app-runtime.ts":"import type {\n CompiledUIBotSpec,\n ConnectionDriver,\n LinkedSpecIdentity,\n UIBotSpec,\n} from \"@uibot/contracts\";\nimport { createLiveRuntimeAdapter, type UIBotAppRuntimeAdapter } from \"@uibot/runtime\";\nimport { createAdminPreviewDriver, protectSolutionEditors } from \"@uibot/blocks-shadcn/solutions\";\nimport { NowAPICollectionDriver, type NowAPIClientConfig } from \"@uibot/connection-nowapi\";\nimport { prepareAdminServerMode } from \"./admin-server-mode\";\nimport { createAdminServerTable } from \"./admin-server-table\";\nimport { createFormDirtyTracker, hasUnsavedAdminEditor } from \"./admin-navigation\";\nimport { bindAppSessionSource } from \"./app-session-source\";\nimport { bindAdminBusinessSource } from \"./admin-business-source\";\nimport { createAdminConversations } from \"./admin-conversations\";\nimport { isAccountRoute } from \"./app-account-source\";\n\n/** Host assembly only; the saved revision is never rewritten. */\nexport function prepareLinkedAppSource(\n source: UIBotSpec,\n tasksData: boolean,\n sessions = false,\n adminData = false,\n accountFlows = false,\n): UIBotSpec {\n const prepared = prepareAdminServerMode(\n source,\n tasksData,\n adminData ? [\"tasks\", \"users\"] : [\"tasks\"],\n );\n protectSolutionEditors(prepared);\n if (sessions) bindAppSessionSource(prepared, accountFlows);\n if (adminData) bindAdminBusinessSource(prepared);\n if (tasksData)\n for (const page of prepared.pages) {\n page.state = { ...page.state, currentUserId: \"\" };\n for (const key of [\"rows\", \"conversations\", \"messages\", \"integrations\"])\n if (key in page.state) page.state[key] = [];\n }\n return prepared;\n}\n\n/** The host binds exactly one business connection, regardless of edited Spec options. */\nexport function createLinkedTasksDriver(\n config: Pick<NowAPIClientConfig, \"url\" | \"fetch\">,\n): ConnectionDriver {\n const driver = new NowAPICollectionDriver({ ...config, project: \"shadcn-admin\", version: \"v1\" });\n return {\n type: driver.type,\n execute(request, context) {\n if (context.connectionId !== \"tasks-db\")\n return Promise.resolve({\n status: 503,\n data: { message: \"This business service is not connected.\" },\n });\n return driver.execute(request, context);\n },\n };\n}\n\nexport function createLinkedAppRuntime(options: {\n spec: CompiledUIBotSpec;\n source: UIBotSpec;\n identity: LinkedSpecIdentity;\n demoData: boolean;\n tasksDriver?: ConnectionDriver;\n authDriver?: ConnectionDriver;\n summaryDriver?: ConnectionDriver;\n adminData?: boolean;\n canBatch?: () => boolean;\n storage: Pick<Storage, \"getItem\" | \"setItem\">;\n navigate: (destination: string) => void;\n}) {\n if (options.demoData && options.tasksDriver)\n throw Error(\"Demo data and a Tasks business connection cannot be combined\");\n const prefix = `uibot.linked-app.demo.v1:${encodeURIComponent(options.identity.projectId)}:${encodeURIComponent(options.identity.artifactId)}:`;\n const driver = options.demoData\n ? createAdminPreviewDriver(options.source, {\n getItem: (key) => options.storage.getItem(prefix + key),\n setItem: (key, value) => options.storage.setItem(prefix + key, value),\n })\n : undefined;\n const pages = new Map<string, UIBotAppRuntimeAdapter>();\n const dirtyForms = new Map<string, boolean>();\n const subscriptions: (() => void)[] = [];\n const controllers: { dispose(): void }[] = [];\n let appearance: { font: string; theme: string; direction: string } | undefined;\n let appearanceRead: Promise<void> | undefined;\n let appearanceKey = \"\";\n let appearanceVersion = 0;\n let disposed = false;\n const adoptAppearance = (rows: unknown) => {\n const row = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;\n const values = row?.values as Record<string, unknown> | undefined;\n if (\n !values ||\n typeof values.font !== \"string\" ||\n typeof values.theme !== \"string\" ||\n typeof values.direction !== \"string\" ||\n ![\"Inter\", \"System\", \"Manrope\"].includes(values.font) ||\n ![\"light\", \"dark\", \"system\"].includes(values.theme) ||\n ![\"ltr\", \"rtl\"].includes(values.direction)\n )\n return;\n const key = JSON.stringify([row?.id, row?.version, values]);\n const version = typeof row?.version === \"number\" ? row.version : 0;\n if (disposed || key === appearanceKey || version < appearanceVersion) return;\n appearanceVersion = version;\n appearanceKey = key;\n appearance = { font: values.font, theme: values.theme, direction: values.direction };\n for (const adapter of pages.values())\n void adapter.dispatch(\n Object.entries(appearance).map(([path, value]) => ({\n action: \"SetState\",\n params: { path, value },\n })),\n );\n };\n return {\n refreshPermissions(canBatch = options.canBatch?.() ?? true) {\n for (const [key, adapter] of pages) {\n const changed = adapter.snapshot().hostCanBatch !== canBatch;\n void adapter.dispatch([\n {\n action: \"SetState\",\n params: { path: \"hostCanBatch\", value: canBatch },\n },\n ...(key === \"users\" && changed\n ? [\n { action: \"SetState\", params: { path: \"rows\", value: [] } },\n {\n action: \"SetState\",\n params: { path: \"reloadRequested\", value: !adapter.snapshot().reloadRequested },\n },\n ]\n : []),\n ]);\n }\n },\n pendingPages() {\n if (disposed) return [];\n return options.spec.pages\n .filter((page) => {\n const state = pages.get(page.id)?.snapshot();\n return (\n state &&\n (dirtyForms.get(page.id) ||\n hasUnsavedAdminEditor(state) ||\n state.saving === true ||\n state.accountDirty === true ||\n state.accountPending === true ||\n state.sending === true ||\n state.creatingConversation === true ||\n state.reloadSettingsOpen === true ||\n state.chatHasDrafts === true ||\n (page.id === \"apps\" && state.editorOpen === true) ||\n state.bulkOpen === true ||\n state.deleteOpen === true)\n );\n })\n .map((page) => ({ path: page.path, title: page.title ?? page.id }));\n },\n forPage(path: string) {\n if (disposed) throw new Error(\"Application runtime disposed\");\n const page = options.spec.pages.find((item) => item.path === path) ?? options.spec.pages[0];\n const key = page?.id ?? \"\";\n let adapter = pages.get(key);\n if (!adapter) {\n adapter = createLiveRuntimeAdapter({\n spec: {\n ...options.spec,\n pages: page ? [page, ...options.spec.pages.filter((item) => item.id !== key)] : [],\n },\n drivers: [\n ...(options.tasksDriver ? [options.tasksDriver] : driver ? [driver] : []),\n ...(options.authDriver ? [options.authDriver] : []),\n ...(options.summaryDriver ? [options.summaryDriver] : []),\n ],\n navigate: ({ destination }) => options.navigate(destination),\n });\n pages.set(key, adapter);\n void adapter.dispatch([\n {\n action: \"SetState\",\n params: { path: \"hostCanBatch\", value: options.canBatch?.() ?? true },\n },\n ]);\n if (appearance)\n void adapter.dispatch(\n Object.entries(appearance).map(([path, value]) => ({\n action: \"SetState\",\n params: { path, value },\n })),\n );\n if (options.adminData && options.tasksDriver && !isAccountRoute(page?.path ?? \"\")) {\n if (!appearanceRead) {\n const current = adapter;\n appearanceRead = current\n .dispatch([\n {\n action: \"Request\",\n params: {\n connectionId: \"preferences-db\",\n request: {\n id: \"host-appearance\",\n payload: { operation: \"Find\", filter: { section: \"appearance\" } },\n },\n responsePath: \"hostAppearance\",\n errorPath: \"hostAppearanceError\",\n },\n },\n ])\n .then(() => {\n if (!current.snapshot().hostAppearanceError)\n adoptAppearance(current.snapshot().hostAppearance);\n })\n .catch(() => {\n /* Keep host defaults when the saved appearance cannot be read. */\n });\n }\n if (page?.id === \"settings-appearance\") {\n const current = adapter;\n subscriptions.push(\n current.subscribeAny(() => {\n const state = current.snapshot();\n if (!state.loading && !state.uiError) adoptAppearance(state.preferences);\n }),\n );\n }\n }\n if (page?.id.startsWith(\"settings-\")) {\n const tracker = createFormDirtyTracker(adapter.snapshot());\n const observed = adapter;\n const update = () => dirtyForms.set(key, tracker.update(observed.snapshot()));\n update();\n subscriptions.push(adapter.subscribeAny(update));\n }\n if (options.adminData && page?.id === \"chats\")\n controllers.push(createAdminConversations(adapter));\n if (\n options.tasksDriver &&\n (page?.id === \"tasks\" || (options.adminData && page?.id === \"users\"))\n )\n controllers.push(\n createAdminServerTable(adapter, {\n connectionId: page.id === \"users\" ? \"users-db\" : \"tasks-db\",\n fields:\n page.id === \"users\"\n ? {\n search: [\"username\", \"firstName\", \"lastName\", \"email\"],\n sort: [\"id\", \"username\", \"firstName\", \"lastName\", \"email\", \"status\", \"role\"],\n facets: [\"status\", \"role\"],\n }\n : {\n search: [\"id\", \"title\"],\n sort: [\"id\", \"title\", \"status\", \"priority\"],\n facets: [\"status\", \"priority\"],\n },\n statuses:\n page.id === \"users\"\n ? [\"active\", \"inactive\", \"invited\", \"suspended\"]\n : [\"backlog\", \"todo\", \"in progress\", \"done\", \"canceled\"],\n canBatch: options.canBatch,\n }),\n );\n }\n return adapter;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n for (const stop of subscriptions) stop();\n dirtyForms.clear();\n for (const controller of controllers) controller.dispose();\n for (const adapter of pages.values()) adapter.dispose();\n pages.clear();\n },\n };\n}\n","src/admin-server-mode.ts":"import type { ActionChain, BlockNode, UIBotSpec } from \"@uibot/contracts\";\n\n/** Explicit host assembly removes client collection reloads before compilation. */\nexport function prepareAdminServerMode(\n source: UIBotSpec,\n live: boolean,\n pageIds: readonly string[] = [\"tasks\", \"users\"],\n): UIBotSpec {\n const spec = structuredClone(source);\n for (const page of spec.pages) {\n if (!pageIds.includes(page.id)) continue;\n page.state = {\n ...page.state,\n serverMode: live,\n ...(live ? { queryError: null, deleteIntent: \"\" } : {}),\n };\n if (!live) continue;\n const rewrite = (chain: ActionChain): ActionChain =>\n chain.map((action): ActionChain[number] => {\n const request = action.params.request;\n if (\n action.action === \"Request\" &&\n request &&\n typeof request === \"object\" &&\n !Array.isArray(request) &&\n \"payload\" in request &&\n request.payload &&\n typeof request.payload === \"object\" &&\n !Array.isArray(request.payload) &&\n \"operation\" in request.payload &&\n request.payload.operation === \"FindAll\"\n ) {\n return {\n action: \"SetState\",\n params: {\n path: \"reloadRequested\",\n value: { _not: { _state: \"reloadRequested\" } },\n },\n };\n }\n return {\n ...action,\n ...(action.action === \"Request\" &&\n request &&\n typeof request === \"object\" &&\n \"payload\" in request &&\n request.payload &&\n typeof request.payload === \"object\" &&\n \"operation\" in request.payload &&\n request.payload.operation === \"DeleteOne\"\n ? {\n params: {\n ...action.params,\n request: {\n ...request,\n payload: { ...request.payload, idempotencyKey: { _state: \"deleteIntent\" } },\n },\n },\n }\n : {}),\n ...(action.onSuccess ? { onSuccess: rewrite(action.onSuccess) } : {}),\n ...(action.onError ? { onError: rewrite(action.onError) } : {}),\n };\n });\n if (page.lifecycle?.onMount)\n page.lifecycle.onMount = rewrite(page.lifecycle.onMount).filter(\n (action) => action.params.path !== \"reloadRequested\",\n );\n const visit = (blocks: BlockNode[]) => {\n for (const block of blocks) {\n if (block.type === \"DataTable\")\n block.props = { ...block.props, error: { _state: \"queryError.message\" } };\n for (const [name, chain] of Object.entries(block.events ?? {}))\n if (block.events) block.events[name] = rewrite(chain);\n visit(block.children ?? []);\n for (const children of Object.values(block.slots ?? {})) visit(children);\n }\n };\n visit(page.blocks);\n }\n return spec;\n}\n","src/admin-server-table.ts":"import type { UIBotAppRuntimeAdapter } from \"@uibot/runtime\";\nimport type { PropValue, RequestPayload } from \"@uibot/contracts\";\nimport type { FilterExpr, PageEnvelope, PageQuery } from \"@uibot/connection-nowapi\";\n\nimport { createAdminServerBatch } from \"./admin-server-batch\";\n\nexport interface AdminTableView {\n search: string;\n filters: Record<string, string[]>;\n sort: string;\n descending: boolean;\n page: number;\n pageSize: number;\n hiddenColumns: string[];\n}\nexport interface AdminTableFields {\n search: readonly string[];\n sort: readonly string[];\n facets: readonly string[];\n}\nconst record = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nexport function normalizeAdminTableView(value: unknown): AdminTableView {\n let raw = value;\n if (typeof raw === \"string\") {\n try {\n raw = JSON.parse(raw);\n } catch {\n raw = {};\n }\n }\n const v = record(raw) ? raw : {};\n const integer = (value: unknown, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : fallback;\n return {\n search: typeof v.search === \"string\" ? v.search : \"\",\n filters: record(v.filters)\n ? Object.fromEntries(\n Object.entries(v.filters)\n .filter(([, values]) => Array.isArray(values))\n .map(([key, values]) => [\n key,\n (values as unknown[]).filter((x): x is string => typeof x === \"string\"),\n ]),\n )\n : {},\n sort: typeof v.sort === \"string\" ? v.sort : \"\",\n descending: v.descending === true,\n page: integer(v.page, 0),\n pageSize: Math.max(1, Math.min(200, integer(v.pageSize, 10))),\n hiddenColumns: Array.isArray(v.hiddenColumns)\n ? v.hiddenColumns.filter((x): x is string => typeof x === \"string\")\n : [],\n };\n}\n\n/** SQL LIKE wildcards % and _ retain the backend's documented semantics. */\nexport function mapAdminTableQuery(view: AdminTableView, fields: AdminTableFields): PageQuery {\n if (view.sort && !fields.sort.includes(view.sort)) throw new Error(\"Unsupported sort field\");\n const operands: FilterExpr[] = [];\n if (view.search && fields.search.length)\n operands.push({\n op: \"or\",\n operands: fields.search.map((field) => ({ op: \"ilike\", field, value: `%${view.search}%` })),\n });\n for (const [field, values] of Object.entries(view.filters)) {\n if (!fields.facets.includes(field)) throw new Error(\"Unsupported filter field\");\n if (values.length) operands.push({ op: \"in\", field, value: [...new Set(values)] });\n }\n return {\n limit: view.pageSize,\n ...(operands.length\n ? { queryFilter: operands.length === 1 ? operands[0] : { op: \"and\" as const, operands } }\n : {}),\n ...(view.sort\n ? {\n order: [\n { field: view.sort, direction: view.descending ? (\"desc\" as const) : (\"asc\" as const) },\n ],\n }\n : {}),\n };\n}\n\nexport interface AdminServerTableOptions {\n connectionId: string;\n fields: AdminTableFields;\n statuses?: readonly string[];\n canBatch?: () => boolean;\n}\n\n/** Host-owned cursor state. Uses only public adapter dispatch/snapshot/subscription. */\nexport function createAdminServerTable(\n adapter: UIBotAppRuntimeAdapter,\n options: AdminServerTableOptions,\n) {\n const batch = createAdminServerBatch(\n adapter,\n options.statuses ?? [],\n options.connectionId,\n options.canBatch,\n );\n let processing = false;\n let disposed = false,\n scheduled = false,\n generation = 0;\n let pending: { generation: number; page: number; payload: RequestPayload } | undefined;\n const active = new Set<number>();\n let cursors: (string | undefined)[] = [undefined];\n let queryKey = \"\",\n seenView = \"\",\n seenReload: unknown,\n first = true;\n let currentPage = 0;\n // Deduplicate by request intent, not the last successful response.\n let requestedPage: number | undefined;\n const write = async (values: Record<string, unknown>) => {\n if (disposed) return;\n await adapter.dispatch(\n Object.entries(values).map(([path, value]) => ({\n action: \"SetState\",\n params: { path, value: value as PropValue },\n })),\n );\n };\n const start = () => {\n if (disposed || !pending || active.size >= 2) return;\n const task = pending;\n pending = undefined;\n const slot = active.has(0) ? 1 : 0;\n active.add(slot);\n const base = `adminQueryScratch.slot${slot}`;\n void (async () => {\n let failure: unknown;\n try {\n await adapter.dispatch([\n {\n action: \"Request\",\n params: {\n connectionId: options.connectionId,\n request: { id: \"admin-page\", payload: task.payload },\n responsePath: `${base}.result`,\n errorPath: `${base}.error`,\n },\n },\n ]);\n } catch {\n failure = (\n adapter.snapshot().adminQueryScratch as\n | Record<string, Record<string, unknown>>\n | undefined\n )?.[`slot${slot}`]?.error ?? { message: \"Records could not be loaded.\" };\n }\n const scratch = adapter.snapshot().adminQueryScratch as\n | Record<string, Record<string, unknown>>\n | undefined;\n const page = scratch?.[`slot${slot}`]?.result as\n | PageEnvelope<Record<string, unknown>>\n | undefined;\n if (!disposed && task.generation === generation) {\n if (failure || !page)\n await write({\n rows: [],\n queryError: failure ?? { message: \"Invalid page response\" },\n loading: false,\n total: null,\n hasNextPage: false,\n });\n else {\n cursors = cursors.slice(0, task.page + 1);\n if (page.nextCursor !== null) cursors[task.page + 1] = page.nextCursor;\n currentPage = task.page;\n await write({\n rows: page.items,\n total: page.total ?? null,\n hasNextPage: page.nextCursor !== null,\n loading: false,\n queryError: null,\n });\n }\n }\n // Requests already in flight may complete after disposal; erase only their bounded scratch.\n await adapter.dispatch([{ action: \"SetState\", params: { path: base, value: null } }]);\n active.delete(slot);\n start();\n })();\n };\n const observe = async () => {\n if (disposed) return;\n const state = adapter.snapshot();\n const rawView = JSON.stringify(state.tableView);\n const reload = state.reloadRequested;\n if (!first && rawView === seenView && reload === seenReload) return;\n let view = normalizeAdminTableView(state.tableView);\n let query: PageQuery;\n try {\n query = mapAdminTableQuery(view, options.fields);\n } catch {\n generation++;\n pending = undefined;\n requestedPage = undefined;\n seenView = rawView;\n seenReload = reload;\n first = false;\n await write({\n rows: [],\n loading: false,\n queryError: { message: \"Unsupported table query. Reset the view to try again.\" },\n hasNextPage: false,\n total: null,\n });\n return;\n }\n const key = JSON.stringify(query);\n const changed = key !== queryKey;\n const reloading = !first && reload !== seenReload;\n const reset = first || changed || reloading;\n const restoredPage = first && view.page > 0;\n if (reset) {\n cursors = [undefined];\n view = { ...view, page: 0 };\n }\n if (\n view.page !== currentPage &&\n !reset &&\n (Math.abs(view.page - currentPage) !== 1 || view.page >= cursors.length)\n ) {\n view = { ...view, page: 0 };\n cursors = [undefined];\n await write({ pageNotice: \"Cursor history is unavailable. Returned to the first page.\" });\n }\n const normalized = JSON.stringify(view);\n seenView = JSON.stringify(normalized);\n seenReload = reload;\n const needRequest = reset || view.page !== requestedPage;\n first = false;\n queryKey = key;\n if (!needRequest) {\n await write({ tableView: normalized });\n return;\n }\n requestedPage = view.page;\n const nextGeneration = ++generation;\n pending = {\n generation: nextGeneration,\n page: view.page,\n payload: JSON.parse(\n JSON.stringify({\n operation: \"FindPage\",\n ...query,\n ...(cursors[view.page] ? { cursor: cursors[view.page] } : {}),\n }),\n ) as RequestPayload,\n };\n await write({\n tableView: normalized,\n ...(reset ? { selectedIds: [], bulkDisabled: true, bulkOpen: false } : {}),\n ...(restoredPage\n ? { pageNotice: \"Cursor history is unavailable. Returned to the first page.\" }\n : {}),\n rows: [],\n loading: true,\n queryError: null,\n });\n start();\n };\n const schedule = () => {\n if (disposed) return;\n scheduled = true;\n if (processing) return;\n processing = true;\n void Promise.resolve().then(async () => {\n try {\n while (scheduled && !disposed) {\n scheduled = false;\n await observe();\n }\n } finally {\n processing = false;\n }\n });\n };\n const stop = adapter.subscribeAny(schedule);\n schedule();\n return {\n dispose() {\n disposed = true;\n batch.dispose();\n generation++;\n pending = undefined;\n stop();\n },\n };\n}\n","src/admin-server-batch.ts":"import type { UIBotAppRuntimeAdapter } from \"@uibot/runtime\";\nimport type { PropValue } from \"@uibot/contracts\";\nimport type { BatchItem } from \"@uibot/connection-nowapi\";\nconst record = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === \"object\" && !Array.isArray(v);\ninterface Confirmation {\n action: \"delete\" | \"status\";\n items: BatchItem[];\n status: string;\n key: string;\n}\n\n/** Selection is an explicit versioned set, never an entire filtered query. */\nexport function createAdminServerBatch(\n adapter: UIBotAppRuntimeAdapter,\n statuses: readonly string[],\n connectionId: string,\n canBatch: () => boolean = () => true,\n) {\n let disposed = false,\n processing = false,\n scheduled = false,\n busy = false;\n let confirmation: Confirmation | undefined;\n let submit: unknown = adapter.snapshot().bulkSubmit;\n let rowsSeen: unknown;\n let deleteFingerprint = \"\";\n const versions = new Map<string, number>();\n const write = async (values: Record<string, unknown>) => {\n if (disposed) return;\n const changed = Object.entries(values).filter(\n ([path, value]) => JSON.stringify(adapter.snapshot()[path]) !== JSON.stringify(value),\n );\n if (changed.length)\n await adapter.dispatch(\n changed.map(([path, value]) => ({\n action: \"SetState\",\n params: { path, value: value as PropValue },\n })),\n );\n };\n const send = (intent: Confirmation) => {\n busy = true;\n void (async () => {\n await write({ saving: true, bulkConfirmDisabled: true, bulkError: null });\n let failure: unknown;\n try {\n await adapter.dispatch([\n {\n action: \"Request\",\n params: {\n connectionId: connectionId,\n request: {\n id: \"admin-batch\",\n payload: {\n operation: intent.action === \"delete\" ? \"DeleteBatch\" : \"UpdateBatch\",\n items: intent.items.map((item) => ({ ...item })),\n ...(intent.action === \"status\" ? { input: { status: intent.status } } : {}),\n idempotencyKey: intent.key,\n },\n },\n responsePath: \"adminBatchScratch.result\",\n errorPath: \"adminBatchScratch.error\",\n },\n },\n ]);\n } catch {\n failure = (adapter.snapshot().adminBatchScratch as Record<string, unknown> | undefined)\n ?.error ?? { message: \"Batch failed\" };\n }\n if (!disposed) {\n if (failure) await write({ saving: false, bulkConfirmDisabled: false, bulkError: failure });\n else {\n confirmation = undefined;\n versions.clear();\n await write({\n saving: false,\n selectedIds: [],\n bulkOpen: false,\n bulkError: null,\n reloadRequested: !adapter.snapshot().reloadRequested,\n });\n }\n }\n await adapter.dispatch([\n { action: \"SetState\", params: { path: \"adminBatchScratch\", value: null } },\n ]);\n busy = false;\n schedule();\n })();\n };\n const observe = async () => {\n if (disposed) return;\n const state = adapter.snapshot();\n if (state.deleteOpen === true && record(state.draft)) {\n const fingerprint = JSON.stringify([state.draft.id, state.draft.version]);\n if (fingerprint !== deleteFingerprint) {\n deleteFingerprint = fingerprint;\n await write({ deleteIntent: crypto.randomUUID() });\n }\n }\n const selected = Array.isArray(state.selectedIds)\n ? [...new Set(state.selectedIds.filter((id): id is string => typeof id === \"string\"))]\n : [];\n if (rowsSeen !== state.rows) {\n rowsSeen = state.rows;\n const keep = new Set(selected);\n for (const id of versions.keys()) if (!keep.has(id)) versions.delete(id);\n for (const row of Array.isArray(state.rows) ? state.rows : []) {\n if (record(row) && typeof row.id === \"string\") {\n if (\n typeof row.version === \"number\" &&\n Number.isSafeInteger(row.version) &&\n row.version > 0\n )\n versions.set(row.id, row.version);\n else versions.delete(row.id);\n }\n }\n }\n const unavailable = !canBatch()\n ? \"Administrator access is required for batch actions.\"\n : !statuses.length\n ? \"Atomic batch actions are unavailable for this transport.\"\n : selected.length > 100\n ? \"Select at most 100 records for a batch.\"\n : !selected.length\n ? \"Select records with known versions to enable batch actions.\"\n : selected.some((id) => !versions.has(id))\n ? \"Selected records have missing versions. Reload before a batch.\"\n : \"\";\n await write({\n bulkDisabled: !canBatch() || Boolean(unavailable) || busy || state.loading === true,\n bulkUnavailable: unavailable,\n });\n const request = state.bulkRequest;\n if (record(request)) {\n await write({ bulkRequest: null });\n const ids = Array.isArray(request.ids) ? request.ids : [];\n if (\n !unavailable &&\n canBatch() &&\n !busy &&\n state.loading !== true &&\n (request.action === \"delete\" || request.action === \"status\") &&\n ids.length === selected.length &&\n new Set(ids).size === ids.length &&\n ids.every((id) => typeof id === \"string\" && selected.includes(id))\n ) {\n const status =\n typeof state.bulkStatus === \"string\" && statuses.includes(state.bulkStatus)\n ? state.bulkStatus\n : (statuses[0] ?? \"\");\n confirmation = {\n action: request.action,\n items: selected.map((id) => ({ id, expectedVersion: versions.get(id) ?? 0 })),\n status,\n key: crypto.randomUUID(),\n };\n await write({\n bulkOpen: true,\n bulkAction: request.action,\n bulkStatus: status,\n bulkError: null,\n });\n }\n }\n if (confirmation && state.bulkOpen === false && !record(request) && !busy)\n confirmation = undefined;\n if (confirmation) {\n const status =\n typeof adapter.snapshot().bulkStatus === \"string\"\n ? String(adapter.snapshot().bulkStatus)\n : \"\";\n if (!busy && confirmation.action === \"status\" && status !== confirmation.status) {\n confirmation = { ...confirmation, status, key: crypto.randomUUID() };\n }\n const invalidStatus =\n !canBatch() ||\n (confirmation.action === \"status\" && !statuses.includes(confirmation.status));\n const latestError = adapter.snapshot().bulkError;\n const permissionError = !canBatch()\n ? {\n code: \"host-role-required\",\n message:\n \"Administrator access is required. Your selection is preserved; cancel this action or contact your workspace administrator.\",\n }\n : record(latestError) && latestError.code === \"host-role-required\"\n ? null\n : undefined;\n await write({\n bulkConfirmDisabled: busy || invalidStatus,\n ...(permissionError !== undefined ? { bulkError: permissionError } : {}),\n bulkSummary: JSON.stringify(\n {\n items: confirmation.items,\n ...(confirmation.action === \"status\" ? { input: { status: confirmation.status } } : {}),\n },\n null,\n 2,\n ),\n });\n if (state.bulkSubmit !== submit) {\n submit = state.bulkSubmit;\n if (!busy && !invalidStatus && adapter.snapshot().bulkOpen === true)\n send(structuredClone(confirmation));\n }\n } else submit = state.bulkSubmit;\n };\n const schedule = () => {\n if (disposed) return;\n scheduled = true;\n if (processing) return;\n processing = true;\n void Promise.resolve().then(async () => {\n try {\n while (scheduled && !disposed) {\n scheduled = false;\n await observe();\n }\n } finally {\n processing = false;\n }\n });\n };\n const stop = adapter.subscribeAny(schedule);\n schedule();\n return {\n dispose() {\n disposed = true;\n confirmation = undefined;\n versions.clear();\n stop();\n },\n };\n}\n","src/app-session-source.ts":"import type {\n ActionChain,\n BlockNode,\n CompiledUIBotSpec,\n UIBotSpec,\n PropValue,\n} from \"@uibot/contracts\";\nimport { bindAccountPage } from \"./app-account-source\";\n\n/** Host wiring changes only the compiled copy of the authored authentication pages. */\nexport function bindAppSessionSource(spec: UIBotSpec, accountFlows = false) {\n if (!spec.pages.some((page) => page.path === \"/sign-in\"))\n throw Error(\"Session host requires the Admin sign-in page.\");\n spec.connections = [\n ...(spec.connections ?? []).filter((c) => c.id !== \"host-session\"),\n { id: \"host-session\", type: \"UIBot.HostSession\", options: {} },\n ];\n for (const page of spec.pages) {\n if ([\"/sign-up\", \"/forgot-password\", \"/otp\"].includes(page.path)) {\n if (accountFlows) {\n bindAccountPage(page);\n continue;\n }\n const copy: Record<string, string> = {\n \"Enter your email and password to create an account.\":\n \"Accounts are provisioned by your workspace administrator.\",\n \"Enter your registered email and we will send you a reset link.\":\n \"Password recovery is managed by your workspace administrator.\",\n \"Please enter the authentication code sent to your email.\":\n \"Two-factor verification requires a connected authentication provider.\",\n \"By continuing, you agree to our Terms of Service and Privacy Policy.\":\n \"This page does not create an account, send email or verify a code.\",\n };\n const disable = (blocks: BlockNode[]) => {\n for (const block of blocks) {\n if (typeof block.props?.text === \"string\" && copy[block.props.text])\n block.props = { ...block.props, text: copy[block.props.text] ?? \"\" };\n if (block.type === \"Form\") {\n block.events = { ...block.events };\n delete block.events.onSubmit;\n block.props = { ...block.props, pending: false };\n block.children = [\n {\n type: \"Paragraph\",\n props: {\n text: \"This account service is not connected. Contact your workspace administrator.\",\n muted: true,\n size: \"sm\",\n },\n },\n ...(block.children ?? []),\n ];\n }\n if ([\"Field\", \"Form.Submit\", \"Button\"].includes(block.type))\n block.props = { ...block.props, disabled: true };\n disable(block.children ?? []);\n for (const children of Object.values(block.slots ?? {})) disable(children);\n }\n };\n disable(page.blocks);\n continue;\n }\n if (![\"/sign-in\", \"/sign-in-2\"].includes(page.path)) continue;\n page.state = { ...page.state, uiError: null };\n const submit: ActionChain = [\n {\n action: \"Request\",\n params: {\n connectionId: \"host-session\",\n request: {\n id: \"session-login\",\n payload: {\n operation: \"Login\",\n data: { _event: \"values\" },\n },\n },\n loadingPath: \"saving\",\n errorPath: \"uiError\",\n },\n ...(accountFlows\n ? {\n onSuccess: [\n { action: \"SetState\" as const, params: { path: \"accountDirty\", value: false } },\n ],\n }\n : {}),\n },\n ];\n let forms = 0;\n const visit = (blocks: BlockNode[]) => {\n for (const block of blocks) {\n if (block.type === \"Form\") {\n forms++;\n block.events = { ...block.events, onSubmit: submit };\n if (accountFlows)\n block.events.onChange = [\n { action: \"SetState\", params: { path: \"accountDirty\", value: true } },\n ];\n block.children = [\n ...(block.children ?? []),\n {\n type: \"Paragraph\",\n props: { text: { _state: \"uiError.message\" }, className: \"text-destructive text-sm\" },\n },\n ...(accountFlows\n ? [\n {\n type: \"Link\",\n props: {\n label: \"Sign in with an email code\",\n href: \"/otp\",\n className: \"text-sm\",\n },\n },\n ]\n : []),\n ];\n }\n if (block.type === \"Form.Submit\")\n block.props = { ...block.props, disabled: { _state: \"saving\" } };\n if (\n block.type === \"Paragraph\" &&\n block.props?.text === \"Connect an authentication provider to continue.\"\n )\n block.props = {\n ...block.props,\n text: \"Sign in to your connected workspace. Your account controls access to business records.\",\n };\n if (\n block.type === \"Link\" &&\n !accountFlows &&\n [\"/forgot-password\", \"/sign-up\"].includes(String(block.props?.href))\n ) {\n const recovery = block.props?.href === \"/forgot-password\";\n block.type = \"Paragraph\";\n block.props = {\n text: recovery\n ? \"Password recovery: contact your workspace administrator.\"\n : \"Accounts are provisioned by your workspace administrator.\",\n muted: true,\n size: \"sm\",\n };\n }\n if (\n block.type === \"Paragraph\" &&\n String(block.props?.text).startsWith(\"By continuing, you agree\")\n )\n block.props = {\n ...block.props,\n text: \"Credentials are sent only through this host to the connected identity service.\",\n };\n visit(block.children ?? []);\n for (const children of Object.values(block.slots ?? {})) visit(children);\n }\n };\n visit(page.blocks);\n if (!forms) throw Error(\"Session host requires the Admin login form.\");\n }\n return spec;\n}\n\n/** The host account replaces sample identity only in the compiled native shell. */\nexport function bindCompiledSessionIdentity(\n spec: CompiledUIBotSpec,\n user?: { email: string; id?: string },\n) {\n const email = user?.email ?? \"\";\n const name = email.split(\"@\")[0] || \"Account\";\n const removeSampleBadge = (value: PropValue): PropValue => {\n if (Array.isArray(value)) return value.map(removeSampleBadge);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== \"badge\" || !(\"href\" in value) || value.href !== \"/chats\")\n .map(([key, item]) => [key, removeSampleBadge(item)]),\n );\n };\n for (const page of spec.pages) {\n page.state = { ...page.state, currentUserId: user?.id ?? \"\" };\n if (page.id === \"settings-profile\" && page.state.preferencesReady === false)\n page.state.form = { username: name, email, bio: \"\", urls: [] };\n }\n for (const block of Object.values(spec.blocks)) {\n if ([\"PageLayout\", \"AppNavigation\"].includes(block.type))\n block.props = Object.fromEntries(\n Object.entries(block.props ?? {}).map(([key, value]) => [\n key,\n [\"routes\", \"groups\"].includes(key) ? removeSampleBadge(value) : value,\n ]),\n );\n if (block.type === \"PageLayout\")\n block.props = { ...block.props, initials: name.slice(0, 2).toUpperCase() };\n if (block.type !== \"AppNavigation\") continue;\n block.props = {\n ...block.props,\n userName: name,\n email,\n initials: name.slice(0, 2).toUpperCase(),\n workspaces: [],\n };\n }\n}\n","src/app-account-source.ts":"import type { ActionChain, BlockNode, BlockTreePage } from \"@uibot/contracts\";\n\nexport const isAccountRoute = (path: string) =>\n [\"/sign-in\", \"/sign-in-2\", \"/sign-up\", \"/forgot-password\", \"/otp\"].includes(path);\nconst state = (path: string) => ({ _state: path });\nconst set = (path: string, value: boolean | string) => ({\n action: \"SetState\",\n params: { path, value },\n});\nconst digitCodeState = (available: boolean) => ({\n accountCodeKind: \"otp\",\n accountCodePlaceholder: \"000000\",\n accountCodeHint: \"Enter the 6 digits from your latest email. Keep any leading zeroes.\",\n accountUseLegacyAvailable: available,\n});\nfunction submit(operation: string, destination?: string): ActionChain {\n return [\n {\n action: \"Request\",\n params: {\n connectionId: \"host-session\",\n request: { id: operation, payload: { operation, data: { _event: \"values\" } } },\n loadingPath: \"saving\",\n errorPath: \"uiError\",\n },\n onSuccess: [\n set(\"accountDirty\", false),\n ...(destination ? [{ action: \"Link\", params: { path: destination } }] : []),\n ],\n },\n ];\n}\nconst field = (name: string, label: string, kind = \"text\"): BlockNode => ({\n type: \"Field\",\n props: {\n name,\n label,\n kind,\n required: true,\n ...(name === \"token\"\n ? {\n kind: state(\"accountCodeKind\"),\n length: 6,\n autoComplete: \"one-time-code\",\n placeholder: state(\"accountCodePlaceholder\"),\n description: state(\"accountCodeHint\"),\n }\n : {}),\n },\n});\nconst message: BlockNode = {\n type: \"Paragraph\",\n props: { text: state(\"uiError.message\"), className: \"text-destructive text-sm\" },\n};\nfunction form(\n operation: string,\n fields: BlockNode[],\n label: string,\n destination?: string,\n): BlockNode {\n return {\n type: \"Form\",\n props: { label, pending: state(\"saving\") },\n children: [\n ...fields,\n { type: \"Form.Submit\", props: { label, full: true, disabled: state(\"saving\") } },\n message,\n ],\n events: { onChange: [set(\"accountDirty\", true)], onSubmit: submit(operation, destination) },\n };\n}\n\n/** Adapt the existing authored frame; authentication state remains host-owned. */\nexport function bindAccountPage(page: BlockTreePage) {\n const otp = page.path === \"/otp\";\n page.state = {\n ...page.state,\n uiError: null,\n accountDirty: false,\n accountHasFlow: false,\n accountNoFlow: true,\n accountNeedsPassword: false,\n accountVerifyDisabled: true,\n accountRetryBlocked: true,\n accountTitle: \"Email code sign-in\",\n accountMessage: \"Enter your email to request a one-time sign-in code.\",\n accountRetryLabel: \"Resend code\",\n accountExpiryLabel: \"\",\n ...digitCodeState(false),\n };\n if (otp) page.title = \"Email verification\";\n const copy: Record<string, string> = {\n \"Enter your email and password to create an account.\":\n \"Verify your email, then choose a password to create your account.\",\n \"Enter your registered email and we will send you a reset link.\":\n \"Request a recovery code, then choose a new password. Previous sessions will be revoked.\",\n \"By continuing, you agree to our Terms of Service and Privacy Policy.\":\n \"Email verification is handled by the connected identity service. Request a code to see the delivery method.\",\n \"Connect an authentication provider to continue.\":\n \"Codes can be used once. Use the latest code and check its expiry time below.\",\n };\n const visit = (blocks: BlockNode[]) =>\n blocks.flatMap((block): BlockNode[] => {\n if (block.type === \"Form\") {\n if (!otp)\n return [\n form(\n page.path === \"/sign-up\" ? \"StartSignup\" : \"StartRecovery\",\n [field(\"email\", \"Email\", \"email\")],\n \"Send verification code\",\n \"/otp\",\n ),\n ];\n const start = form(\"StartOtp\", [field(\"email\", \"Email\", \"email\")], \"Send sign-in code\");\n start.visible = { _state: \"accountNoFlow\" };\n const verify = form(\n \"VerifyAccount\",\n [\n field(\"token\", \"Verification code\"),\n {\n ...field(\"password\", \"New password (12–128 characters)\", \"password\"),\n visible: state(\"accountNeedsPassword\"),\n },\n {\n ...field(\"confirm\", \"Confirm password\", \"password\"),\n visible: state(\"accountNeedsPassword\"),\n },\n ],\n \"Verify code\",\n \"/sign-in\",\n );\n verify.visible = state(\"accountHasFlow\");\n const button = verify.children?.find((item) => item.type === \"Form.Submit\");\n if (button) button.props = { ...button.props, disabled: state(\"accountVerifyDisabled\") };\n return [\n start,\n verify,\n {\n type: \"Paragraph\",\n visible: state(\"accountHasFlow\"),\n props: { text: state(\"accountExpiryLabel\"), size: \"sm\" },\n },\n {\n type: \"Button\",\n visible: state(\"accountUseLegacyAvailable\"),\n props: {\n label: \"Use an older email code\",\n variant: \"ghost\",\n disabled: state(\"saving\"),\n },\n events: {\n onClick: [\n set(\"accountCodeKind\", \"text\"),\n set(\"accountCodePlaceholder\", \"Complete email code\"),\n set(\n \"accountCodeHint\",\n \"Paste the complete code from an older email. Its original expiry still applies.\",\n ),\n set(\"accountUseLegacyAvailable\", false),\n ],\n },\n },\n {\n type: \"Button\",\n visible: state(\"accountHasFlow\"),\n props: {\n label: state(\"accountRetryLabel\"),\n disabled: state(\"accountRetryBlocked\"),\n variant: \"outline\",\n },\n events: { onClick: submit(\"ResendAccount\") },\n },\n {\n type: \"Paragraph\",\n visible: state(\"accountHasFlow\"),\n props: {\n text: \"Requesting a fresh code clears the current verification fields.\",\n muted: true,\n size: \"sm\",\n },\n },\n { type: \"Link\", props: { label: \"Back to sign in\", href: \"/sign-in\" } },\n ];\n }\n if (typeof block.props?.text === \"string\") {\n const text = block.props.text;\n if (\n otp &&\n [\n \"Two-factor Authentication\",\n \"Please enter the authentication code sent to your email.\",\n ].includes(text)\n )\n block.props = {\n ...block.props,\n text: state(text === \"Two-factor Authentication\" ? \"accountTitle\" : \"accountMessage\"),\n };\n else if (copy[text]) block.props = { ...block.props, text: copy[text] };\n }\n if (block.type === \"Link\" && block.props?.href === page.path)\n block.props = { ...block.props, href: \"/sign-in\", label: \"Back to sign in\" };\n if (block.children) block.children = visit(block.children);\n for (const [key, children] of Object.entries(block.slots ?? {}))\n (block.slots as Record<string, BlockNode[]>)[key] = visit(children);\n return [block];\n });\n page.blocks = visit(page.blocks);\n}\n\ntype AccountFlow = {\n purpose: string;\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n unknown: boolean;\n} | null;\n\n/** Metadata identity only; credentials stay in the form DOM, never runtime state. */\nexport function accountFlowKey(flow: AccountFlow) {\n return flow ? JSON.stringify([flow.purpose, flow.email, flow.expiresAt, flow.retryAt]) : \"new\";\n}\n\nexport function accountPageState(\n flow: AccountFlow,\n now: number,\n pending = false,\n previousFlowKey?: unknown,\n) {\n const key = accountFlowKey(flow);\n const remaining = Math.max(0, Math.ceil(((flow?.retryAt ?? 0) - now) / 1000));\n const expired = Boolean(flow && flow.expiresAt <= now);\n const seconds = Math.max(0, Math.ceil(((flow?.expiresAt ?? 0) - now) / 1000));\n return {\n accountFlowKey: key,\n ...(previousFlowKey !== key\n ? { uiError: null, accountDirty: false, ...digitCodeState(Boolean(flow)) }\n : {}),\n accountHasFlow: Boolean(flow),\n accountNoFlow: !flow,\n accountNeedsPassword: Boolean(flow && flow.purpose !== \"otp\"),\n accountPending: pending,\n accountVerifyDisabled: pending || !flow || expired || Boolean(flow.unknown),\n accountRetryBlocked: pending || remaining > 0,\n accountRetryLabel: remaining ? `Resend code in ${remaining}s` : \"Resend code\",\n accountExpiryLabel: !flow\n ? \"\"\n : expired\n ? \"Code expired. Request a new code to continue.\"\n : `Code expires in ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")} (${new Date(flow.expiresAt).toLocaleTimeString()}).`,\n accountTitle:\n flow?.purpose === \"signup\"\n ? \"Verify your email\"\n : flow?.purpose === \"recovery\"\n ? \"Reset your password\"\n : \"Email code sign-in\",\n accountMessage: !flow\n ? \"Enter your email to request a one-time sign-in code.\"\n : flow.unknown\n ? \"The previous request outcome is unknown. Try signing in, or request a fresh code after the cooldown. It will not be repeated.\"\n : expired\n ? \"This code has expired. Request a new code to continue.\"\n : `If this account is eligible, ${flow.delivery === \"smtp\" ? \"check the email sent to\" : \"use the controlled local test inbox for\"} ${flow.email}. Use the latest email for this request. ${flow.delivery === \"local_http\" ? \"External email delivery is not configured for this request.\" : \"\"}`.trim(),\n };\n}\n","src/admin-business-source.ts":"import type { ActionChain, BlockNode, PropValue, UIBotSpec } from \"@uibot/contracts\";\n\nconst state = (path: string) => ({ _state: path });\nconst set = (path: string, value: PropValue) => ({ action: \"SetState\", params: { path, value } });\nfunction visit(blocks: BlockNode[], apply: (block: BlockNode) => void) {\n for (const block of blocks) {\n apply(block);\n visit(block.children ?? [], apply);\n for (const children of Object.values(block.slots ?? {})) visit(children, apply);\n }\n}\n\n/** Adapt the authored pages in a detached host copy; no business data enters revisions. */\nexport function bindAdminBusinessSource(spec: UIBotSpec) {\n spec.connections = [\n ...(spec.connections ?? []).filter((c) => c.id !== \"host-summary\"),\n { id: \"host-summary\", type: \"UIBot.AdminSummary\" },\n ];\n for (const page of spec.pages) {\n if (page.id === \"dashboard\") {\n // The fixed live-data adapter owns queries, but keeps the authored Overview\n // component choices. Only copy supported presentation, never demo data/actions.\n let authoredChart: BlockNode | undefined;\n let authoredRecords: BlockNode | undefined;\n visit(page.blocks, (block) => {\n if (!authoredChart && (block.type === \"BarChart\" || block.type === \"SeriesChart\"))\n authoredChart = block;\n if (!authoredRecords && (block.type === \"AvatarList\" || block.type === \"RecordCards\"))\n authoredRecords = block;\n });\n const chart: BlockNode = {\n ...(authoredChart?.id ? { id: authoredChart.id } : {}),\n type: authoredChart?.type ?? \"BarChart\",\n props: {\n data: state(\"summary.taskStatus\"),\n label: \"Tasks by status\",\n ...(typeof authoredChart?.props?.height === \"number\" &&\n Number.isFinite(authoredChart.props.height) &&\n authoredChart.props.height >= 100 &&\n authoredChart.props.height <= 800\n ? { height: authoredChart.props.height }\n : {}),\n ...(authoredChart?.type === \"SeriesChart\"\n ? { variant: authoredChart.props?.variant === \"area\" ? \"area\" : \"line\" }\n : {}),\n },\n };\n const records: BlockNode | undefined = authoredRecords\n ? {\n ...(authoredRecords.id ? { id: authoredRecords.id } : {}),\n type: authoredRecords.type,\n props: {\n items: [\n [\"Tasks\", \"tasks\", \"T\"],\n [\"Conversations\", \"conversations\", \"C\"],\n [\"Integration preferences\", \"integrations\", \"I\"],\n [\"Saved settings\", \"preferences\", \"S\"],\n ].map(([name, key, initials]) => ({\n id: key ?? \"\",\n name: name ?? \"\",\n initials: initials ?? \"\",\n description: \"Visible to your account\",\n value: state(`summary.${key}`),\n })),\n },\n }\n : undefined;\n page.state = {\n currentPath: \"/\",\n summary: null,\n loading: false,\n uiError: null,\n hostCanBatch: false,\n theme: \"light\",\n font: \"Inter\",\n direction: \"ltr\",\n };\n const load: ActionChain = [\n {\n action: \"Request\",\n params: {\n connectionId: \"host-summary\",\n request: { id: \"summary\", payload: { operation: \"Summary\" } },\n responsePath: \"summary\",\n loadingPath: \"loading\",\n errorPath: \"uiError\",\n },\n },\n ];\n page.lifecycle = { onMount: load };\n const root = page.blocks.find((b) => b.type === \"PageLayout\");\n if (root)\n root.children = [\n { type: \"Heading\", props: { level: 1, text: \"Workspace overview\" } },\n {\n type: \"Paragraph\",\n props: {\n text: \"Live totals for records your account can access. No sample revenue or sales data.\",\n muted: true,\n },\n },\n {\n type: \"Button\",\n props: { label: \"Refresh overview\", variant: \"outline\", disabled: state(\"loading\") },\n events: { onClick: load },\n },\n {\n type: \"Paragraph\",\n props: { text: state(\"uiError.message\"), className: \"text-destructive\" },\n visible: state(\"uiError\"),\n },\n {\n type: \"Box\",\n visible: state(\"summary\"),\n props: { className: \"!grid gap-4 sm:grid-cols-2 xl:grid-cols-4\" },\n children: [\n [\"Tasks\", \"tasks\"],\n [\"Conversations\", \"conversations\"],\n [\"Integration preferences\", \"integrations\"],\n [\"Saved settings\", \"preferences\"],\n ].map(([label, key]) => ({\n type: \"StatCard\",\n props: {\n label: label ?? \"\",\n value: state(`summary.${key}`),\n description: \"Visible to your account\",\n },\n })),\n },\n {\n type: \"StatCard\",\n visible: { _and: [state(\"hostCanBatch\"), state(\"summary\")] },\n props: {\n label: \"Directory records\",\n value: state(\"summary.users\"),\n description: \"Business directory · does not grant sign-in access\",\n },\n },\n {\n type: \"Card\",\n visible: state(\"summary\"),\n props: { title: \"Tasks by status\" },\n children: [chart],\n },\n ...(records\n ? [\n {\n type: \"Card\",\n visible: state(\"summary\"),\n props: { title: \"Workspace records\" },\n children: [records],\n },\n ]\n : []),\n {\n type: \"Paragraph\",\n props: {\n text: {\n _concat: [\n \"Observed at \",\n state(\"summary.observedAt\"),\n \". Counts are separate authorized reads, not an atomic snapshot.\",\n ],\n },\n muted: true,\n size: \"sm\",\n },\n visible: state(\"summary\"),\n },\n ];\n }\n if (page.id === \"users\") {\n page.state = { ...page.state, hostCanBatch: false };\n visit(page.blocks, (block) => {\n if (\n block.type === \"Paragraph\" &&\n block.props?.text === \"Manage your users and their roles here.\"\n )\n block.props = {\n ...block.props,\n text: \"Maintain business contacts. These records and role labels do not create accounts or change access.\",\n };\n });\n const root = page.blocks.find((b) => b.type === \"PageLayout\");\n if (root)\n root.children = [\n {\n type: \"Paragraph\",\n props: {\n text: \"Administrator access is required to view and maintain the business directory. Directory role labels do not grant sign-in permissions.\",\n muted: true,\n },\n },\n { type: \"Box\", visible: state(\"hostCanBatch\"), children: root.children ?? [] },\n ];\n }\n if (page.id.startsWith(\"settings-\")) {\n page.state = {\n ...page.state,\n preferences: [],\n preferencesReady: false,\n reloadSettingsOpen: false,\n settingsReloaded: false,\n };\n if (page.id === \"settings-profile\")\n page.state.form = { username: \"\", email: \"\", bio: \"\", urls: [] };\n if (page.id === \"settings-account\")\n page.state.form = { name: \"\", birthday: \"\", language: \"English\" };\n const load = page.lifecycle?.onMount;\n if (load)\n for (const action of load) {\n if (action.action === \"Request\")\n action.onSuccess = [...(action.onSuccess ?? []), set(\"preferencesReady\", true)];\n }\n if (page.id === \"settings-appearance\") {\n for (const action of load ?? [])\n if (action.action === \"Request\")\n action.onSuccess = [\n ...(action.onSuccess ?? []),\n ...[\"theme\", \"font\", \"direction\"].map((key) => set(key, state(`form.${key}`))),\n ];\n }\n visit(page.blocks, (block) => {\n if (block.type === \"Form\")\n block.props = {\n ...block.props,\n pending: {\n _or: [state(\"saving\"), state(\"loading\"), { _not: state(\"preferencesReady\") }],\n },\n };\n if (block.type === \"Form.Submit\")\n block.props = {\n ...block.props,\n disabled: {\n _or: [state(\"saving\"), state(\"loading\"), { _not: state(\"preferencesReady\") }],\n },\n };\n if (\n block.type === \"Field\" &&\n page.id === \"settings-profile\" &&\n block.props?.name === \"email\"\n )\n block.props = {\n ...block.props,\n label: \"Contact email\",\n description: \"Profile contact only. Changing this does not change your sign-in email.\",\n };\n if (\n block.type === \"Paragraph\" &&\n page.id === \"settings-notifications\" &&\n block.props?.text === \"Configure how you receive notifications.\"\n )\n block.props = {\n ...block.props,\n text: \"Save your notification preferences. Email delivery is not connected in this host.\",\n };\n if (\n block.type === \"Paragraph\" &&\n page.id === \"settings-display\" &&\n block.props?.text === \"Turn items on or off to control what’s displayed in the app.\"\n )\n block.props = {\n ...block.props,\n text: \"Save sidebar display preferences for a compatible host. This Admin layout keeps its fixed business navigation.\",\n };\n });\n const root = page.blocks.find((b) => b.type === \"PageLayout\");\n const reload = structuredClone(load ?? []);\n for (const action of reload)\n if (action.action === \"Request\")\n action.onSuccess = [\n ...(action.onSuccess ?? []),\n set(\"settingsReloaded\", { _not: state(\"settingsReloaded\") }),\n set(\"saved\", false),\n set(\"reloadSettingsOpen\", false),\n ];\n root?.children?.push({\n type: \"Button\",\n visible: { _not: state(\"preferencesReady\") },\n props: { label: \"Retry loading settings\", variant: \"outline\", disabled: state(\"loading\") },\n events: { onClick: load ?? [] },\n });\n root?.children?.push(\n {\n type: \"Button\",\n visible: { _and: [state(\"preferencesReady\"), state(\"uiError\")] },\n props: { label: \"Reload saved settings\", variant: \"outline\", disabled: state(\"saving\") },\n events: { onClick: [set(\"reloadSettingsOpen\", true)] },\n },\n {\n type: \"Modal\",\n props: {\n title: \"Reload saved settings?\",\n description: \"Your current edits will be replaced by the saved settings.\",\n open: state(\"reloadSettingsOpen\"),\n },\n events: { onClose: [set(\"reloadSettingsOpen\", false)] },\n children: [\n {\n type: \"Button\",\n props: { label: \"Keep editing\", variant: \"outline\" },\n events: { onClick: [set(\"reloadSettingsOpen\", false)] },\n },\n { type: \"Button\", props: { label: \"Reload settings\" }, events: { onClick: reload } },\n ],\n },\n );\n }\n if (page.id === \"apps\") {\n page.state = {\n ...page.state,\n integrationSettings: [],\n integrationsReady: false,\n loading: false,\n };\n for (const action of page.lifecycle?.onMount ?? [])\n if (action.action === \"Request\") action.onSuccess = [set(\"integrationsReady\", true)];\n visit(page.blocks, (block) => {\n if (block.type === \"IntegrationGrid\")\n block.props = {\n ...block.props,\n pending: {\n _or: [state(\"saving\"), state(\"loading\"), { _not: state(\"integrationsReady\") }],\n },\n };\n if (\n block.type === \"Paragraph\" &&\n typeof block.props?.text === \"string\" &&\n block.props.text.startsWith(\"Here’s a list\")\n )\n block.props = {\n ...block.props,\n text: \"Save your integration preferences. External provider authorization is not connected.\",\n };\n });\n const root = page.blocks.find((b) => b.type === \"PageLayout\");\n root?.children?.push({\n type: \"Button\",\n visible: { _not: state(\"integrationsReady\") },\n props: {\n label: \"Retry loading integrations\",\n variant: \"outline\",\n disabled: state(\"loading\"),\n },\n events: { onClick: page.lifecycle?.onMount ?? [] },\n });\n }\n if (page.id === \"chats\") {\n page.state = {\n ...page.state,\n conversations: [],\n messages: [],\n draft: \"\",\n selectedId: \"\",\n conversationName: \"\",\n conversationLoading: false,\n conversationError: null,\n newConversationOpen: false,\n creatingConversation: false,\n chatLoading: false,\n chatHasMore: false,\n conversationHasMore: false,\n chatReload: false,\n conversationReload: false,\n conversationLoadMore: false,\n chatLoadMore: false,\n };\n page.lifecycle = undefined;\n const root = page.blocks.find((b) => b.type === \"PageLayout\");\n if (!root) continue;\n visit(root.children ?? [], (block) => {\n if (block.type !== \"ChatPanel\") return;\n block.props = {\n ...block.props,\n pending: { _or: [state(\"sending\"), state(\"chatLoading\")] },\n };\n block.events = {\n ...block.events,\n onSend: [set(\"messageSubmission\", { _event: \"values\" })],\n };\n });\n const toggle = (path: string): ActionChain => [set(path, { _not: state(path) })];\n root.children = [\n { type: \"Heading\", props: { text: \"Conversation notes\", level: 1 } },\n {\n type: \"Paragraph\",\n props: {\n text: \"Private notes saved to your account. Messages are not delivered to another person or external provider.\",\n muted: true,\n size: \"sm\",\n },\n },\n {\n type: \"Box\",\n props: { className: \"!flex-row flex-wrap gap-2\" },\n children: [\n {\n type: \"Button\",\n props: { label: \"New conversation\" },\n events: { onClick: [set(\"newConversationOpen\", true)] },\n },\n {\n type: \"Button\",\n props: {\n label: \"Refresh conversations\",\n variant: \"outline\",\n disabled: state(\"conversationLoading\"),\n },\n events: { onClick: toggle(\"conversationReload\") },\n },\n {\n type: \"Button\",\n visible: state(\"conversationHasMore\"),\n props: {\n label: \"More conversations\",\n variant: \"outline\",\n disabled: state(\"conversationLoading\"),\n },\n events: { onClick: toggle(\"conversationLoadMore\") },\n },\n {\n type: \"Button\",\n visible: state(\"selectedId\"),\n props: {\n label: \"Refresh messages\",\n variant: \"outline\",\n disabled: state(\"chatLoading\"),\n },\n events: { onClick: toggle(\"chatReload\") },\n },\n {\n type: \"Button\",\n visible: state(\"chatHasMore\"),\n props: {\n label: \"Load older messages\",\n variant: \"outline\",\n disabled: state(\"chatLoading\"),\n },\n events: { onClick: toggle(\"chatLoadMore\") },\n },\n ],\n },\n ...(root.children ?? []),\n {\n type: \"Drawer\",\n props: {\n title: \"New conversation\",\n open: state(\"newConversationOpen\"),\n pending: state(\"creatingConversation\"),\n },\n events: { onClose: [set(\"newConversationOpen\", false)] },\n children: [\n {\n type: \"Form\",\n props: {\n label: \"New conversation\",\n idempotent: true,\n pending: state(\"creatingConversation\"),\n },\n events: {\n onSubmit: [\n set(\"conversationSubmission\", {\n values: { _event: \"values\" },\n requestId: { _event: \"value\" },\n }),\n ],\n },\n children: [\n {\n type: \"Field\",\n props: {\n name: \"name\",\n label: \"Conversation name\",\n required: true,\n value: { _bindState: \"conversationName\" },\n },\n },\n {\n type: \"Paragraph\",\n props: {\n text: state(\"conversationError.message\"),\n className: \"text-destructive\",\n },\n },\n { type: \"Form.Submit\", props: { label: \"Create conversation\" } },\n ],\n },\n ],\n },\n ];\n }\n }\n}\n","src/admin-conversations.ts":"import type { PropValue, RequestPayload } from \"@uibot/contracts\";\nimport type { UIBotAppRuntimeAdapter } from \"@uibot/runtime\";\n\ntype Row = Record<string, unknown>;\ntype Page = { items: Row[]; nextCursor: string | null };\nconst record = (v: unknown): v is Row => !!v && typeof v === \"object\" && !Array.isArray(v);\n\n/** Cursor reads are bounded and late results cannot replace a newer conversation. */\nexport function createAdminConversations(adapter: UIBotAppRuntimeAdapter) {\n let disposed = false,\n scheduled = false,\n observing = false;\n let selection = \"\",\n seenDraft = \"\",\n first = true;\n let seenReload: unknown,\n seenMore: unknown,\n seenConversationReload: unknown,\n seenConversationMore: unknown;\n let messageIntent: unknown, conversationIntent: unknown;\n let messageBusy = false,\n conversationBusy = false;\n let messageCursor: string | null = null,\n conversationCursor: string | null = null;\n const drafts = new Map<string, string>();\n const sendErrors = new Map<string, unknown>();\n const write = async (values: Row) => {\n if (disposed) return;\n const changed = Object.entries(values).filter(\n ([key, value]) => JSON.stringify(adapter.snapshot()[key]) !== JSON.stringify(value),\n );\n if (changed.length)\n await adapter.dispatch(\n changed.map(([path, value]) => ({\n action: \"SetState\",\n params: { path, value: value as PropValue },\n })),\n );\n };\n const request = async (connectionId: string, payload: RequestPayload, scratch: string) => {\n try {\n await adapter.dispatch([\n {\n action: \"Request\",\n params: {\n connectionId,\n request: { id: scratch, payload },\n responsePath: `${scratch}.result`,\n errorPath: `${scratch}.error`,\n },\n },\n ]);\n return { data: (adapter.snapshot()[scratch] as Row | undefined)?.result };\n } catch {\n return {\n error: (adapter.snapshot()[scratch] as Row | undefined)?.error ?? {\n message: \"The request could not be completed.\",\n },\n };\n } finally {\n await adapter.dispatch([{ action: \"SetState\", params: { path: scratch, value: null } }]);\n }\n };\n function reader(\n connectionId: string,\n scratch: string,\n apply: (result: { data?: unknown; error?: unknown }, append: boolean) => Promise<void>,\n ) {\n let generation = 0;\n const active = new Set<number>();\n let pending: { payload: RequestPayload; append: boolean; ticket: number } | undefined;\n const start = () => {\n if (disposed || !pending || active.size >= 2) return;\n const task = pending;\n pending = undefined;\n const slot = active.has(0) ? 1 : 0;\n active.add(slot);\n void request(connectionId, task.payload, `${scratch}${slot}`)\n .then(async (result) => {\n if (!disposed && task.ticket === generation) await apply(result, task.append);\n })\n .finally(() => {\n active.delete(slot);\n start();\n });\n };\n return {\n load(payload: RequestPayload, append: boolean) {\n pending = { payload, append, ticket: ++generation };\n start();\n },\n invalidate() {\n generation++;\n pending = undefined;\n },\n };\n }\n const conversations = reader(\"conversations-db\", \"conversationRead\", async (result, append) => {\n const page = result.data as Page | undefined;\n if (result.error || !page) {\n await write({ conversationLoading: false, uiError: result.error });\n return;\n }\n conversationCursor = page.nextCursor;\n const previous =\n append && Array.isArray(adapter.snapshot().conversations)\n ? (adapter.snapshot().conversations as Row[])\n : [];\n const items = [...new Map([...previous, ...page.items].map((row) => [row.id, row])).values()];\n const selected = String(adapter.snapshot().selectedId ?? \"\");\n const current = (adapter.snapshot().conversations as Row[] | undefined)?.find(\n (row) => row.id === selected,\n );\n if (current && !items.some((row) => row.id === selected)) items.push(current);\n await write({\n conversations: items,\n conversationLoading: false,\n conversationHasMore: page.nextCursor !== null,\n uiError: sendErrors.get(selection) ?? null,\n ...(!selected && items[0] ? { selectedId: items[0].id } : {}),\n });\n });\n const messages = reader(\"messages-db\", \"messageRead\", async (result, append) => {\n const page = result.data as Page | undefined;\n if (result.error || !page) {\n await write({ chatLoading: false, uiError: result.error });\n return;\n }\n messageCursor = page.nextCursor;\n const previous =\n append && Array.isArray(adapter.snapshot().messages)\n ? (adapter.snapshot().messages as Row[])\n : [];\n const items: Row[] = page.items.map((row) => ({\n ...row,\n createdAt: row.created_at,\n senderId: row.author_id,\n }));\n await write({\n messages: [...new Map([...previous, ...items].map((row) => [row.id, row])).values()],\n chatLoading: false,\n chatHasMore: page.nextCursor !== null,\n uiError: sendErrors.get(selection) ?? null,\n });\n });\n const loadConversations = async (append: boolean) => {\n if (append && !conversationCursor) return;\n await write({ conversationLoading: true, uiError: null });\n conversations.load(\n {\n operation: \"FindPage\",\n limit: 30,\n order: [{ field: \"created_at\", direction: \"desc\" }],\n ...(append ? { cursor: conversationCursor } : {}),\n },\n append,\n );\n };\n const loadMessages = async (append: boolean) => {\n if (!selection || (append && !messageCursor)) return;\n await write({ chatLoading: true, uiError: null, ...(!append ? { messages: [] } : {}) });\n messages.load(\n {\n operation: \"FindPage\",\n limit: 50,\n filter: { conversationId: selection },\n order: [{ field: \"created_at\", direction: \"desc\" }],\n ...(append ? { cursor: messageCursor } : {}),\n },\n append,\n );\n };\n const observe = async () => {\n const value = adapter.snapshot();\n const selected = String(value.selectedId ?? \"\");\n if (selected !== selection) {\n if (selection) drafts.set(selection, String(value.draft ?? seenDraft));\n selection = selected;\n seenDraft = drafts.get(selection) ?? \"\";\n messageCursor = null;\n messages.invalidate();\n await write({\n draft: seenDraft,\n messages: [],\n chatHasMore: false,\n chatLoading: false,\n uiError: null,\n });\n await loadMessages(false);\n } else {\n seenDraft = String(value.draft ?? \"\");\n if (selection) drafts.set(selection, seenDraft);\n }\n const initial = first;\n first = false;\n if (initial || seenConversationReload !== value.conversationReload) {\n seenConversationReload = value.conversationReload;\n await loadConversations(false);\n }\n if (seenConversationMore !== value.conversationLoadMore) {\n const changed = seenConversationMore !== undefined;\n seenConversationMore = value.conversationLoadMore;\n if (changed) await loadConversations(true);\n }\n if (seenReload !== value.chatReload) {\n const changed = seenReload !== undefined;\n seenReload = value.chatReload;\n if (changed) await loadMessages(false);\n }\n if (seenMore !== value.chatLoadMore) {\n const changed = seenMore !== undefined;\n seenMore = value.chatLoadMore;\n if (changed) await loadMessages(true);\n }\n if (!messageBusy && value.messageSubmission !== messageIntent) {\n messageIntent = value.messageSubmission;\n const input = messageIntent;\n if (\n record(input) &&\n typeof input.conversationId === \"string\" &&\n typeof input.text === \"string\" &&\n typeof input.requestId === \"string\"\n ) {\n const id = input.conversationId,\n text = input.text;\n messageBusy = true;\n await write({ sending: true, uiError: null });\n void request(\n \"messages-db\",\n {\n operation: \"InsertOne\",\n data: { conversationId: id, text },\n idempotencyKey: input.requestId,\n },\n \"messageWrite\",\n )\n .then(async (result) => {\n if (disposed) return;\n if (result.error) sendErrors.set(id, result.error);\n else sendErrors.delete(id);\n if (!result.error && (drafts.get(id) ?? \"\").trim() === text) drafts.set(id, \"\");\n await write({\n sending: false,\n ...(selection === id\n ? {\n uiError: result.error ?? null,\n ...(!result.error && String(adapter.snapshot().draft ?? \"\").trim() === text\n ? { draft: \"\" }\n : {}),\n }\n : {}),\n });\n if (!result.error && selection === id) await loadMessages(false);\n })\n .finally(() => {\n messageBusy = false;\n schedule();\n });\n }\n }\n if (!conversationBusy && value.conversationSubmission !== conversationIntent) {\n conversationIntent = value.conversationSubmission;\n const input = conversationIntent;\n if (\n record(input) &&\n record(input.values) &&\n typeof input.values.name === \"string\" &&\n typeof input.requestId === \"string\"\n ) {\n conversationBusy = true;\n await write({ creatingConversation: true, conversationError: null });\n void request(\n \"conversations-db\",\n {\n operation: \"InsertOne\",\n data: { name: input.values.name },\n idempotencyKey: input.requestId,\n },\n \"conversationWrite\",\n )\n .then(async (result) => {\n if (disposed) return;\n if (result.error)\n await write({ creatingConversation: false, conversationError: result.error });\n else {\n const row = result.data as Row;\n await write({\n creatingConversation: false,\n newConversationOpen: false,\n conversationName: \"\",\n conversationError: null,\n conversations: [row, ...(adapter.snapshot().conversations as Row[])],\n selectedId: row.id,\n });\n await loadConversations(false);\n }\n })\n .finally(() => {\n conversationBusy = false;\n schedule();\n });\n }\n }\n await write({\n chatHasDrafts:\n [...drafts.values()].some((draft) => Boolean(draft.trim())) ||\n Boolean(String(adapter.snapshot().conversationName ?? \"\").trim()),\n conversations: (Array.isArray(adapter.snapshot().conversations)\n ? (adapter.snapshot().conversations as Row[])\n : []\n ).map((row) => ({\n ...row,\n preview: drafts.get(String(row.id))?.trim()\n ? `Draft: ${drafts.get(String(row.id))}`\n : \"Private notes\",\n })),\n });\n };\n function schedule() {\n if (disposed) return;\n scheduled = true;\n if (observing) return;\n observing = true;\n void Promise.resolve().then(async () => {\n try {\n while (scheduled && !disposed) {\n scheduled = false;\n await observe();\n }\n } finally {\n observing = false;\n }\n });\n }\n const stop = adapter.subscribeAny(schedule);\n schedule();\n return {\n dispose() {\n disposed = true;\n stop();\n conversations.invalidate();\n messages.invalidate();\n drafts.clear();\n sendErrors.clear();\n },\n };\n}\n","src/app-session-client.ts":"import {\n ConnectionRequestError,\n requestFailureFromStatus,\n isConnectionRequestError,\n type ConnectionDriver,\n} from \"@uibot/contracts\";\nimport { adminBusinessRoute } from \"../admin-business\";\n\nexport type AppSessionInfo = {\n authenticated: true;\n user: { id: string; email: string; role: string };\n canBatch: boolean;\n accessExpiresAt: number;\n sessionExpiresAt: number;\n};\ntype State = {\n ready: boolean;\n info: AppSessionInfo | null;\n lastUserId: string | null;\n error: string;\n accountPending: boolean;\n accountFlow: {\n purpose: \"signup\" | \"recovery\" | \"otp\";\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n unknown: boolean;\n } | null;\n};\nfunction accountFailure(status: number, code: unknown) {\n if (code === \"sign-in-required\" || code === \"csrf-denied\")\n return \"This verification session has expired or changed. Request a new code to continue.\";\n if (status === 429) return \"Please wait before requesting or trying another code.\";\n if (status === 401)\n return \"The code is invalid, expired or already used. Check the latest code or request a new one.\";\n if (status === 400)\n return \"Check your email and code. New passwords must match and contain 12 to 128 characters.\";\n if (status === 409) return \"This verification is unavailable. Sign in or request a new code.\";\n if (code === \"account-delivery-unavailable\")\n return \"The delivery service is unavailable. No delivery is confirmed. Wait before requesting another code.\";\n return \"The verification outcome is unknown. Check sign-in or request a new code after the cooldown; this request will not be repeated.\";\n}\n\n/** Browser keeps only non-bearer metadata and a CSRF token, in memory. */\nexport function createAppSessionClient(origin: string, send: typeof fetch = fetch) {\n let csrf = \"\";\n let epoch = 0;\n let mutations = 0;\n let loadPending: Promise<void> | undefined;\n let logoutPending: Promise<void> | undefined;\n let state: State = {\n ready: false,\n info: null,\n lastUserId: null,\n error: \"\",\n accountFlow: null,\n accountPending: false,\n };\n const listeners = new Set<() => void>();\n const update = (change: Partial<State>) => {\n state = { ...state, ...change };\n for (const listener of listeners) listener();\n };\n async function accept(response: Response, ticket: number, account = false) {\n const data = (await response.json()) as Record<string, unknown>;\n if (ticket !== epoch) return false;\n if (!response.ok)\n throw new ConnectionRequestError(\n requestFailureFromStatus(\n response.status,\n account\n ? accountFailure(response.status, data.code)\n : response.status === 401\n ? \"Email or password was not accepted. Please sign in again.\"\n : response.status === 429\n ? \"Too many sign-in attempts. Please wait before trying again.\"\n : \"The session service could not complete this request.\",\n ),\n );\n if (typeof data.csrfToken !== \"string\" || typeof data.authenticated !== \"boolean\")\n throw Error(\"Invalid session response.\");\n csrf = data.csrfToken;\n if (data.authenticated) {\n const info = data as unknown as AppSessionInfo;\n if (\n !info.user ||\n typeof info.user.id !== \"string\" ||\n typeof info.user.email !== \"string\" ||\n typeof info.user.role !== \"string\" ||\n typeof info.canBatch !== \"boolean\"\n )\n throw Error(\"Invalid session response.\");\n update({\n ready: true,\n info: {\n authenticated: true,\n user: info.user,\n canBatch: info.canBatch,\n accessExpiresAt: info.accessExpiresAt,\n sessionExpiresAt: info.sessionExpiresAt,\n },\n lastUserId: info.user.id,\n error: \"\",\n accountFlow: null,\n });\n } else {\n const flow = data.accountFlow as State[\"accountFlow\"];\n if (\n flow &&\n (![\"signup\", \"recovery\", \"otp\"].includes(flow.purpose) ||\n ![\"local_http\", \"smtp\"].includes(flow.delivery) ||\n typeof flow.email !== \"string\" ||\n typeof flow.unknown !== \"boolean\" ||\n !Number.isFinite(flow.expiresAt) ||\n !Number.isFinite(flow.retryAt))\n )\n throw Error(\"Invalid account response.\");\n update({\n ready: true,\n info: null,\n accountFlow: flow\n ? {\n purpose: flow.purpose,\n delivery: flow.delivery,\n email: flow.email,\n expiresAt: flow.expiresAt,\n retryAt: flow.retryAt,\n unknown: flow.unknown,\n }\n : null,\n ...(data.recovered === true\n ? {\n lastUserId: null,\n error:\n \"Password updated. Previous sessions were revoked. Sign in with your new password.\",\n }\n : {}),\n });\n }\n return true;\n }\n const request = (path: string, body?: unknown) =>\n send(origin + path, {\n credentials: \"same-origin\",\n cache: \"no-store\",\n ...(body !== undefined\n ? {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-UIBot-CSRF\": csrf },\n body: JSON.stringify(body),\n }\n : {}),\n });\n const performLoad = async () => {\n if (mutations) return;\n const ticket = ++epoch;\n try {\n await accept(await request(\"/api/app-session\"), ticket);\n } catch {\n if (ticket !== epoch) return;\n csrf = \"\";\n update({\n ready: true,\n info: null,\n error: \"Session unavailable. Sign in again; your unsaved work is preserved.\",\n });\n }\n };\n const load = () => {\n if (mutations) return Promise.resolve();\n if (!loadPending)\n loadPending = performLoad().finally(() => {\n loadPending = undefined;\n });\n return loadPending;\n };\n const hostFetch: typeof fetch = Object.assign(\n async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = new URL(\n typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url,\n origin,\n );\n if (\n url.origin !== origin ||\n (!adminBusinessRoute(url.pathname, true) &&\n url.pathname !== \"/api/shadcn-admin/v1/dashboard\")\n )\n throw Error(\"Unsupported business request\");\n const headers = new Headers(init?.headers);\n if (![\"GET\", \"HEAD\"].includes(init?.method ?? \"GET\")) {\n headers.set(\"X-UIBot-CSRF\", csrf);\n headers.set(\"Content-Type\", \"application/json\");\n }\n const ticket = epoch;\n const response = await send(url, {\n ...init,\n headers,\n credentials: \"same-origin\",\n cache: \"no-store\",\n });\n if (ticket !== epoch) return response;\n if (response.status === 401) {\n ++epoch;\n csrf = \"\";\n update({\n info: null,\n error: \"Your session ended. Sign in again to continue; your unsaved work is preserved.\",\n });\n } else if (response.status === 403) void load();\n return response;\n },\n { preconnect: send.preconnect },\n );\n const login = async (email: string, password: string) => {\n if (mutations) throw Error(\"A session request is already in progress.\");\n mutations++;\n const pending = loadPending;\n const ticket = ++epoch;\n try {\n await pending;\n if (!(await accept(await request(\"/api/app-session\"), ticket)))\n throw Error(\"Sign-in canceled.\");\n if (!(await accept(await request(\"/api/app-session/login\", { email, password }), ticket)))\n throw Error(\"Sign-in canceled.\");\n } catch (error) {\n if (ticket === epoch) csrf = \"\";\n throw error;\n } finally {\n mutations--;\n }\n };\n const account = async (path: \"account-start\" | \"account-verify\", data: unknown) => {\n if (mutations) throw Error(\"A session request is already in progress.\");\n mutations++;\n update({ accountPending: true });\n const pending = loadPending;\n const ticket = ++epoch;\n let attempted = false;\n try {\n await pending;\n // Renew an idle anonymous cookie before the single explicit issuance request.\n if (\n (path === \"account-start\" || !csrf) &&\n !(await accept(await request(\"/api/app-session\"), ticket))\n )\n throw Error(\"Account request canceled.\");\n attempted = true;\n if (!(await accept(await request(`/api/app-session/${path}`, data), ticket, true)))\n throw Error(\"Account request canceled.\");\n if (path === \"account-start\") update({ error: \"\" });\n } catch (error) {\n if (!attempted)\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message:\n \"The verification session could not be prepared. No code was requested. Please try again.\",\n });\n // Reconcile metadata only; never replay challenge issuance or consumption.\n try {\n await accept(await request(\"/api/app-session\"), ticket);\n } catch {}\n if (isConnectionRequestError(error)) throw error;\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message:\n \"The account request outcome is unknown. Check sign-in or request a new code after the cooldown; this request will not be repeated.\",\n });\n } finally {\n mutations--;\n update({ accountPending: false });\n }\n };\n const driver: ConnectionDriver = {\n type: \"UIBot.HostSession\",\n async execute(request, context) {\n if (context.connectionId !== \"host-session\")\n return { status: 403, data: { message: \"Unsupported account connection.\" } };\n const input = request.payload;\n const data = input?.data as Record<string, unknown> | undefined;\n const purposes: Record<string, \"signup\" | \"recovery\" | \"otp\"> = {\n StartSignup: \"signup\",\n StartRecovery: \"recovery\",\n StartOtp: \"otp\",\n };\n if (\n typeof input?.operation === \"string\" &&\n (Object.hasOwn(purposes, input.operation) ||\n [\"VerifyAccount\", \"ResendAccount\"].includes(input.operation))\n ) {\n if (input.operation === \"VerifyAccount\") await account(\"account-verify\", data);\n else {\n const email =\n input.operation === \"ResendAccount\" ? state.accountFlow?.email : data?.email;\n const purpose =\n input.operation === \"ResendAccount\"\n ? state.accountFlow?.purpose\n : purposes[input.operation];\n if (typeof email !== \"string\" || !purpose)\n return { status: 400, data: { message: \"Request a code first.\" } };\n await account(\"account-start\", { email, purpose });\n }\n return { status: 200, data: { authenticated: Boolean(state.info) } };\n }\n if (\n input?.operation !== \"Login\" ||\n typeof data?.email !== \"string\" ||\n typeof data?.password !== \"string\"\n )\n return { status: 400, data: { message: \"Invalid sign-in request.\" } };\n try {\n await login(data.email, data.password);\n return { status: 200, data: { authenticated: true } };\n } catch (error) {\n if (isConnectionRequestError(error)) throw error;\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message: \"The session service is unavailable. Please try signing in again.\",\n });\n }\n },\n };\n return {\n snapshot: () => state,\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n load,\n login,\n fetch: hostFetch,\n driver,\n async refresh() {\n if (mutations) return;\n mutations++;\n const ticket = ++epoch;\n try {\n await accept(await request(\"/api/app-session/refresh\", {}), ticket);\n } catch {\n if (ticket !== epoch) return;\n csrf = \"\";\n update({ info: null, error: \"Session refresh was not confirmed. Sign in again.\" });\n } finally {\n mutations--;\n }\n },\n logout() {\n if (logoutPending) return logoutPending;\n const ticket = ++epoch;\n mutations++;\n const response = request(\"/api/app-session/logout\", {});\n csrf = \"\";\n update({ info: null, lastUserId: null, accountFlow: null });\n logoutPending = (async () => {\n let revoked = false;\n try {\n revoked = (await response).ok;\n } catch {\n /* local access is already cleared */\n } finally {\n if (ticket === epoch)\n update({\n error: revoked ? \"\" : \"Signed out locally. Remote revocation was not confirmed.\",\n });\n mutations--;\n logoutPending = undefined;\n }\n })();\n return logoutPending;\n },\n };\n}\nexport type AppSessionClient = ReturnType<typeof createAppSessionClient>;\n","admin-business.ts":"/** Fixed host bindings. Edited Spec connections cannot expand this list. */\nexport const ADMIN_BUSINESS_CONNECTIONS = [\n \"tasks-db\",\n \"users-db\",\n \"preferences-db\",\n \"integrations-db\",\n \"conversations-db\",\n \"messages-db\",\n] as const;\n\nexport function adminBusinessRoute(path: string, enabled: boolean) {\n const match =\n /^\\/api\\/shadcn-admin\\/v1\\/(tasks|users|preferences|integrations|conversations|messages)(?:\\/([A-Za-z0-9_-]{1,128})|\\/actions\\/(update|delete))?$/.exec(\n path,\n );\n if (!match || (!enabled && match[1] !== \"tasks\")) return undefined;\n const table = match[1] ?? \"\";\n const item = match[2];\n const batch = match[3];\n if (batch && ![\"tasks\", \"users\"].includes(table)) return undefined;\n return { table, item, batch };\n}\n\nexport function adminBusinessMethod(\n route: NonNullable<ReturnType<typeof adminBusinessRoute>>,\n method: string,\n) {\n if (route.batch) return method === \"POST\";\n if (route.item)\n return (route.table === \"messages\" ? [\"GET\"] : [\"GET\", \"PATCH\", \"DELETE\"]).includes(method);\n return [\"GET\", \"POST\"].includes(method);\n}\n","src/admin-business-driver.ts":"import {\n ConnectionRequestError,\n requestFailureFromStatus,\n type ConnectionDriver,\n type RequestResult,\n} from \"@uibot/contracts\";\nimport { NowAPICollectionDriver, type NowAPIClientConfig } from \"@uibot/connection-nowapi\";\nimport { ADMIN_BUSINESS_CONNECTIONS } from \"../admin-business\";\n\nexport function createLinkedAdminDriver(\n config: Pick<NowAPIClientConfig, \"url\" | \"fetch\">,\n): ConnectionDriver {\n const driver = new NowAPICollectionDriver({ ...config, project: \"shadcn-admin\", version: \"v1\" });\n const checked = (result: RequestResult) => {\n if (result.status >= 400)\n throw new ConnectionRequestError(\n requestFailureFromStatus(\n result.status,\n result.status === 403\n ? \"Your account does not have access to this service. Your edits are preserved.\"\n : result.status === 404\n ? \"This service or record is unavailable. Reload when the workspace service is ready.\"\n : result.status === 409\n ? \"The saved record changed or already exists. Keep your edits and reload the saved version before trying again.\"\n : result.status === 413\n ? \"Too many settings records. Contact your workspace administrator.\"\n : \"The request could not be confirmed. Your input is preserved; check the saved record before trying again.\",\n ),\n );\n return result;\n };\n return {\n type: driver.type,\n async execute(request, context) {\n if (!ADMIN_BUSINESS_CONNECTIONS.some((id) => id === context.connectionId))\n return { status: 503, data: { message: \"This business service is not connected.\" } };\n const operation = request.payload?.operation;\n if (\n [\"preferences-db\", \"integrations-db\"].includes(context.connectionId) &&\n [\"Find\", \"FindAll\"].includes(String(operation))\n ) {\n const result = await driver.execute(\n { ...request, payload: { ...request.payload, operation: \"FindPage\", limit: 100 } },\n context,\n );\n if (result.status >= 400) return checked(result);\n const page = result.data as { items: unknown[]; nextCursor: string | null };\n if (page.nextCursor !== null)\n return checked({\n status: 413,\n data: { message: \"Too many settings records. Contact your administrator.\" },\n });\n return { status: 200, data: page.items };\n }\n if (\n [\"conversations-db\", \"messages-db\", \"users-db\"].includes(context.connectionId) &&\n [\"FindAll\", \"Find\"].includes(String(operation))\n )\n return { status: 400, data: { message: \"Use the paginated record view.\" } };\n return checked(await driver.execute(request, context));\n },\n };\n}\n\nexport function createAdminSummaryDriver(send: typeof fetch): ConnectionDriver {\n return {\n type: \"UIBot.AdminSummary\",\n async execute(request, context) {\n if (context.connectionId !== \"host-summary\" || request.payload?.operation !== \"Summary\")\n return { status: 400, data: { message: \"Unsupported overview request.\" } };\n try {\n const response = await send(\"/api/shadcn-admin/v1/dashboard\");\n if (!response.ok)\n throw new ConnectionRequestError(\n requestFailureFromStatus(\n response.status,\n \"The overview could not be loaded. Refresh to try again.\",\n ),\n );\n return { status: 200, data: await response.json() };\n } catch (error) {\n if (error instanceof ConnectionRequestError) throw error;\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message: \"The overview service is unavailable.\",\n });\n }\n },\n };\n}\n","src/admin.css":":root{--background:#fff;--foreground:#0f172a;--card:#fff;--primary:#0f172a;--primary-foreground:#f8fafc;--muted:#f1f5f9;--muted-foreground:#64748b;--border:#e2e8f0;--ring:#94a3b8;color:var(--foreground);font-family:Inter,ui-sans-serif,system-ui,sans-serif;font-synthesis:none;text-rendering:optimizeLegibility}\n.dark{--background:#09090b!important;--foreground:#fafafa!important;--card:#09090b;--primary:#fafafa;--primary-foreground:#18181b;--muted:#27272a;--muted-foreground:#a1a1aa;--border:#27272a;--ring:#d4d4d8;color-scheme:dark}\nbody{margin:0}button,input,select,textarea{font:inherit}input[type=checkbox],input[type=radio]{accent-color:var(--primary)}h1.uibot-heading{font-size:26px;font-weight:700;letter-spacing:-1px;line-height:1.3}.uibot-admin{--background:#fff!important;--foreground:#0f172a!important;background:var(--nui-sidebar,#fff)!important;color:var(--nui-foreground,#0f172a)!important}.uibot-admin.dark{--background:#09090b!important;--foreground:#fafafa!important;background:#141414!important;color:#fafafa!important}.uibot-admin.dark .nui-mobile{background:#141414;color:#fafafa}.preview-note{position:relative;margin:8px 12px;width:fit-content;max-width:calc(100% - 24px);border:1px solid var(--border);background:var(--background);border-radius:6px;padding:4px 10px;font-size:11px;color:var(--muted-foreground)}.uibot-admin .nui-main{min-height:calc(100dvh - 16px)}.uibot-admin [data-uibot-type=StatCard]{min-height:150px}.uibot-admin [data-uibot-type=Card]{height:100%}.uibot-admin .nui-content:has([data-uibot-type=ChatPanel]){padding-top:8px}\n\n*,::before,::after{border-color:var(--border)}\n","src/app-shell.css":".linked-app {\n --preview-ink: #17213b;\n --preview-muted: #a6b2ca;\n --preview-line: #dce2ed;\n height: 100dvh;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n background: #f4f6fa;\n}\n\n.linked-app-bar {\n position: relative;\n z-index: 20;\n flex: none;\n display: flex;\n align-items: center;\n gap: 32px;\n min-height: 80px;\n padding: 14px 28px;\n background: #17213b;\n color: #f7f9ff;\n border-bottom: 1px solid #2f3a54;\n box-shadow: 0 2px 10px #14203c12;\n}\n\n.linked-app-brand { display: flex; align-items: center; gap: 13px; min-width: 0; flex: 1; }\n.linked-app-mark { display: grid; place-items: center; width: 40px; height: 40px; flex: none; border: 1px solid #7485c366; border-radius: 12px; background: #5363c733; color: #c3cdff; }\n.linked-app-mark svg { width: 25px; height: 25px; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; }\n.linked-app-identity { min-width: 0; }\n.linked-app-identity h1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin: 0; font-size: 16px; font-weight: 600; line-height: 1.5; letter-spacing: -.3px; }\n.linked-app-identity > span { display: block; color: var(--preview-muted); font-size: 11px; line-height: 1.6; }\n.linked-app-actions { display: flex; align-items: center; gap: 24px; }\n.linked-app-account { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; align-items: center; font-size: 12px; }\n.linked-app-account > span { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.linked-app-account > small { color: var(--preview-muted); grid-row: 2; }\n.linked-app-account > button { grid-column: 2; grid-row: 1 / 3; }\n.linked-app-connection { display: flex; flex-direction: column; gap: 4px; white-space: nowrap; }\n.linked-app-status { display: flex; align-items: center; gap: 7px; color: #e2e8f5; font-size: 12px; line-height: 1.4; text-transform: capitalize; }\n.linked-app-status > span { height: 6px; width: 6px; border-radius: 50%; background: #f4c46b; }\n.linked-app-status[data-status=\"synced\"] > span { background: #68dcb3; box-shadow: 0 0 0 3px #68dcb314; }\n.linked-app-status[data-status=\"denied\"] > span, .linked-app-status[data-status=\"invalid\"] > span { background: #ff9b9b; }\n.linked-app-revision { color: var(--preview-muted); font-size: 10px; padding-left: 13px; }\n.linked-app-details-toggle { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px; padding: 0 10px; border: 1px solid #52617b; border-radius: 7px; background: transparent; color: #dbe3f6; font-size: 11px; cursor: pointer; }\n.linked-app-details-toggle svg { width: 17px; height: 17px; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; }\n.linked-app-details-toggle:hover, .linked-app-details-toggle[aria-expanded=\"true\"] { background: #2c3a56; border-color: #8390ab; }\n.linked-app-bar button:focus-visible { outline: 2px solid #b4c1ff; outline-offset: 4px; }\n.linked-app-details { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 16px 28px; border-bottom: 1px solid var(--preview-line); background: #edf1f8; color: var(--preview-ink); }\n.linked-app-details[hidden] { display: none; }\n.linked-app-details h2 { font-size: 12px; font-weight: 600; margin: 0 0 4px; }\n.linked-app-details p { font-size: 12px; color: #53617b; margin: 0; line-height: 1.6; max-width: 70ch; }\n.linked-app-details > button { flex: none; min-height: 36px; padding: 7px 12px; border: 1px solid #c4cde0; border-radius: 7px; background: #fff; color: #364c8a; font-size: 12px; cursor: pointer; }\n.linked-app-details > button:focus-visible { outline: 2px solid #4c57d6; outline-offset: 3px; }\n.linked-app-data-notice { flex: none; padding: 8px 28px; border-bottom: 1px solid var(--preview-line); background: #edf1f8; color: #53617b; font-size: 12px; line-height: 1.5; }\n.linked-app-canvas { position: relative; flex: 1; min-height: 0; overflow: hidden; background: var(--background); color: var(--foreground); isolation: isolate; }\n.linked-app-canvas .uibot-admin { height: 100%; min-height: 0; }\n.linked-app-canvas .uibot-admin .nui-main { min-height: 0; }\n.linked-app-canvas .uibot-standalone-layout { height: 100%; }\n.linked-app-module { max-width: 960px; margin: 48px auto; padding: 0 28px; }\n.linked-app-module > section { padding: 40px; border: 1px solid var(--preview-line); border-radius: 16px; background: #f8faff; color: var(--preview-ink); }\n.linked-app-module h1 { margin: 0 0 24px; font-size: 28px; line-height: 1.3; font-weight: 600; letter-spacing: -.8px; }\n.linked-app-module button { min-height: 42px; padding: 10px 18px; border: 1px solid #4554ac; border-radius: 8px; background: #4c5db6; color: #fff; font-size: 14px; cursor: pointer; }\n.linked-app-module button:hover { background: #3f4e9d; }\n.linked-app-module button:focus-visible { outline: 2px solid #4c57d6; outline-offset: 4px; }\n.linked-app-empty { min-height: 100%; padding: 60px 24px; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; color: var(--preview-ink); }\n.linked-app-empty-mark { font-size: 40px; color: #6879ad; margin-bottom: 16px; }\n.linked-app-empty h2 { font-size: 20px; letter-spacing: -.5px; margin: 0 0 10px; }\n.linked-app-empty p { font-size: 14px; color: #62718b; line-height: 1.7; max-width: 45ch; margin: 0; }\n\n@media (max-width: 1000px) {\n .linked-app-bar { padding-inline: 20px; gap: 20px; }\n .linked-app-actions { gap: 16px; }\n .linked-app-details-toggle { width: 36px; padding: 0; }\n .linked-app-details-toggle > span { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n}\n\n@media (max-width: 640px) {\n .linked-app-bar { flex-wrap: wrap; gap: 14px 16px; padding: 16px; }\n .linked-app-mark { height: 36px; width: 36px; border-radius: 10px; }\n .linked-app-identity h1 { font-size: 14px; }\n .linked-app-actions { width: 100%; justify-content: space-between; gap: 8px; }\n .linked-app-account { flex: 1; min-width: 0; max-width: 220px; }\n .linked-app-details { align-items: flex-start; flex-direction: column; padding: 16px; gap: 12px; }\n .linked-app-module { margin-block: 24px; padding-inline: 16px; }\n .linked-app-module > section { padding: 24px; }\n}\n\n.linked-app-navigator-toggle { display: grid; place-items: center; flex: none; width: 36px; height: 36px; border: 1px solid #52617b; border-radius: 7px; background: transparent; color: #dbe3f6; cursor: pointer; margin-right: -16px; }\n.linked-app-navigator-toggle:hover, .linked-app-navigator-toggle[aria-expanded=true] { background: #2c3a56; border-color: #8390ab; }\n.linked-app-navigator-toggle svg { width: 21px; height: 21px; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }\n.linked-app-body { display: flex; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }\n.linked-app-body > .linked-app-canvas { min-width: 0; }\n.app-page-navigator { width: 280px; flex: none; display: flex; flex-direction: column; min-height: 0; color: #34415a; background: #f6f8fc; border-right: 1px solid var(--preview-line); }\n.app-page-navigator[hidden] { display: none; }\n.app-page-navigator-heading { display: flex; align-items: center; gap: 8px; padding: 22px 20px 16px; }\n.app-page-navigator-heading h2 { margin: 0; color: var(--preview-ink); font-size: 13px; font-weight: 600; }\n.app-page-navigator-heading > span { padding: 1px 6px; border-radius: 4px; background: #e7ecf5; color: #61708b; font-size: 10px; }\n.app-route-search { display: flex; align-items: center; gap: 7px; margin: 0 14px 14px; padding: 8px 9px; border: 1px solid #d7deeb; border-radius: 6px; background: #fff; }\n.app-route-search > svg { width: 15px; height: 15px; flex: none; fill: none; stroke: #78849b; stroke-width: 1.5; }\n.app-route-search input { width: 100%; min-width: 0; border: 0; background: transparent; font-size: 11px; color: var(--preview-ink); outline: none; }\n.app-route-search:focus-within { outline: 2px solid #566cc9; outline-offset: 2px; }\n.app-route-search button { flex: none; width: 20px; height: 20px; color: #61708b; cursor: pointer; }\n.app-route-tree { flex: 1; min-height: 0; }\n.app-route-tree .uibot-scroll-viewport { padding: 0 10px 16px; box-sizing: border-box; overscroll-behavior: contain; }\n.app-route-tree ul { margin: 0; padding: 0; list-style: none; }\n.app-route-tree li > ul { margin-left: 17px; padding-left: 8px; border-left: 1px solid #dce2ed; }\n.app-route-row { display: flex; align-items: center; min-width: 0; margin-bottom: 2px; border: 1px solid transparent; border-radius: 6px; }\n.app-route-row:hover { background: #eaf0f8; }\n.app-route-row[data-selected=true] { background: #e4eaff; border-color: #d4dcfa; color: #354cb0; }\n.app-route-disclosure, .app-route-spacer { width: 20px; height: 28px; flex: none; }\n.app-route-disclosure { display: grid; place-items: center; color: #7a87a0; cursor: pointer; }\n.app-route-disclosure svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.5; }\n.app-route-disclosure svg[data-expanded=true] { transform: rotate(90deg); }\n.app-route-target { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; padding: 9px 8px 9px 0; text-align: left; cursor: pointer; }\n.app-route-target:disabled, .app-route-disclosure:disabled { cursor: default; }\n.app-route-target > svg { width: 15px; height: 15px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.25; stroke-linejoin: round; }\n.app-route-target > span { display: flex; flex-direction: column; min-width: 0; gap: 3px; flex: 1; }\n.app-route-target strong { font-size: 11px; line-height: 1.5; font-weight: 500; overflow-wrap: anywhere; }\n.app-route-target small { color: #79849a; font-size: 10px; line-height: 1.5; overflow-wrap: anywhere; }\n.app-route-target em { color: #78849b; font-size: 8px; font-style: normal; border: 1px solid #d8dfec; border-radius: 3px; padding: 1px 3px; }\n.app-page-navigator button:focus-visible { outline: 2px solid #566cc9; outline-offset: 1px; }\n.app-route-empty { padding: 20px 10px; color: #6a7890; font-size: 12px; line-height: 1.7; }\n.app-page-navigator-footer { margin: 0; padding: 12px 18px; color: #8791a5; border-top: 1px solid var(--preview-line); font-size: 10px; }\n@media (max-width: 1000px) { .linked-app-navigator-toggle { margin-right: -8px; } }\n@media (max-width: 640px) {\n .linked-app-navigator-toggle { margin-right: 0; width: 32px; height: 36px; }\n .linked-app-brand { gap: 8px; }\n .linked-app-bar { gap: 12px; }\n .linked-app-mark { display: none; }\n .linked-app-body[data-navigator-open=true] > .linked-app-canvas { display: none; }\n .app-page-navigator { width: 100%; border-right: 0; }\n .app-route-target strong { font-size: 13px; }\n .app-route-target { min-height: 44px; }\n}\n.linked-app-notice { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 10px 24px; border-bottom: 1px solid #d9c9a7; background: #fffbef; color: #66512b; }\n.linked-app-notice p { margin: 0; font-size: 12px; line-height: 1.7; }\n.linked-app-retry { flex: none; min-height: 36px; padding: 7px 12px; border: 1px solid #b8c4dc; border-radius: 7px; background: #fff; color: #344775; font-size: 12px; cursor: pointer; }\n.linked-app-retry:disabled { cursor: wait; opacity: .6; }\n.linked-app-retry:hover:enabled { background: #f0f4fb; }\n.linked-app-retry:focus-visible { outline: 2px solid #566cc9; outline-offset: 3px; }\n.linked-app-empty .linked-app-retry { margin-top: 20px; }\n@media (max-width: 640px) {\n .linked-app-notice { flex-wrap: wrap; gap: 8px; padding: 12px 16px; }\n .linked-app-actions { min-width: 0; }\n .linked-app-retry { min-height: 40px; }\n}\n","linked-backend.ts":"type LinkedMiddleware = (\n request: {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n },\n response: {\n statusCode: number;\n setHeader(name: string, value: string): void;\n end(body?: string): void;\n },\n next: () => void,\n) => void;\n\nimport { adminBackendProxy } from \"./admin-backend\";\nimport { readFileSync } from \"node:fs\";\nimport { appConnectionUrl, readAppConnection } from \"@uibot/contracts\";\n\nexport function isLinkedTasksRequest(path: string, method: string | undefined): boolean {\n const route = path.split(\"?\")[0];\n if (route === \"/api/shadcn-admin/v1/tasks\") return method === \"GET\" || method === \"POST\";\n if (/^\\/api\\/shadcn-admin\\/v1\\/tasks\\/actions\\/(update|delete)$/.test(route ?? \"\"))\n return method === \"POST\";\n return (\n /^\\/api\\/shadcn-admin\\/v1\\/tasks\\/[A-Za-z0-9_-]{1,128}$/.test(route ?? \"\") &&\n [\"GET\", \"PATCH\", \"DELETE\"].includes(method ?? \"\")\n );\n}\n\n/** Fixed application reads. Business sessions are owned by the calling host. */\nexport function createLinkedBackend(\n kind: \"spec\" | \"app\" = \"spec\",\n options: { trusted?: boolean } = {},\n) {\n const app = kind === \"app\";\n const tasksData = app && process.env.UIBOT_LINKED_APP_TASKS === \"true\";\n const adminData = app && process.env.UIBOT_LINKED_APP_ADMIN === \"true\";\n const accountFlows = app && process.env.UIBOT_LINKED_APP_AUTH === \"true\";\n if (accountFlows && process.env.UIBOT_LINKED_APP_SESSIONS !== \"true\")\n throw Error(\"Account flows require the per-user session host\");\n if (adminData && (!tasksData || process.env.UIBOT_LINKED_APP_SESSIONS !== \"true\"))\n throw Error(\"Admin business pages require the per-user session host and Tasks transport\");\n if (\n tasksData &&\n (process.env.UIBOT_LINKED_APP_DEMO_DATA === \"true\" ||\n !adminBackendProxy(process.env.UIBOT_ADMIN_TRANSPORT_FILE, options.trusted))\n )\n throw Error(\"Tasks requires a private development transport and demo data disabled\");\n const channel = process.env.UIBOT_LINKED_APP_CHANNEL ?? \"development\";\n if (app && ![\"development\", \"production\"].includes(channel))\n throw Error(\"Invalid linked application channel\");\n const configPath = app ? \"/linked-app-config.json\" : \"/linked-config.json\";\n const sourcePath = app ? \"/linked-app.json\" : \"/linked-spec.json\";\n const connectionFile = app ? process.env.UIBOT_LINKED_APP_CONNECTION_FILE : undefined;\n if (connectionFile && process.env.UIBOT_LINKED_APP_URL)\n throw Error(\"Choose a connection file or UIBOT_LINKED_APP_URL, not both\");\n const connection = connectionFile\n ? readAppConnection(JSON.parse(readFileSync(connectionFile, \"utf8\")))\n : undefined;\n const raw = connection\n ? appConnectionUrl(connection, channel as \"development\" | \"production\")\n : app\n ? process.env.UIBOT_LINKED_APP_URL\n : process.env.UIBOT_LINKED_SPEC_URL;\n const bearer =\n (app ? process.env.UIBOT_LINKED_APP_BEARER : undefined) ?? process.env.UIBOT_LINKED_SPEC_BEARER;\n let upstream: URL | undefined;\n let identity: { projectId: string; artifactId: string } | undefined;\n if (raw) {\n upstream = new URL(raw);\n const match = upstream.pathname.match(\n app\n ? new RegExp(\n `^/api/studio/creation/apps/([A-Za-z0-9_-]{1,128})/([A-Za-z0-9_-]{1,128})/${channel === \"production\" ? \"releases/current\" : \"live\"}$`,\n )\n : /^\\/api\\/studio\\/creation\\/projects\\/([A-Za-z0-9_-]{1,128})\\/artifacts\\/([A-Za-z0-9_-]{1,128})\\/live$/,\n );\n if (\n !match ||\n ![\"http:\", \"https:\"].includes(upstream.protocol) ||\n upstream.username ||\n upstream.password ||\n upstream.search ||\n upstream.hash\n )\n throw new Error(\"Invalid UIBOT_LINKED_SPEC_URL\");\n identity = { projectId: match[1] as string, artifactId: match[2] as string };\n }\n const middleware: LinkedMiddleware = (request, response, next) => {\n if (\n tasksData &&\n request.url?.startsWith(\"/api/shadcn-admin/\") &&\n !isLinkedTasksRequest(request.url, request.method)\n ) {\n response.statusCode = 503;\n response.setHeader(\"Content-Type\", \"application/json\");\n response.setHeader(\"Cache-Control\", \"no-store\");\n response.end(JSON.stringify({ message: \"This business service is not connected.\" }));\n return;\n }\n if (request.url !== configPath && request.url !== sourcePath) {\n const path = request.url?.split(\"?\")[0] ?? \"\";\n const accept = request.headers.accept;\n if (\n app &&\n upstream &&\n (request.method === \"GET\" || request.method === \"HEAD\") &&\n typeof accept === \"string\" &&\n accept.includes(\"text/html\") &&\n !/^\\/(?:@|src\\/|node_modules\\/|assets\\/|api(?:\\/|$))/.test(path) &&\n !/\\.(?:js|mjs|css|json|map|svg|png|jpe?g|gif|ico|webp|woff2?|ttf|wasm)$/i.test(path)\n )\n request.url = \"/app.html\";\n return next();\n }\n response.setHeader(\"Cache-Control\", \"no-store\");\n response.setHeader(\"Content-Type\", \"application/json\");\n if (request.method !== \"GET\" || !upstream || !identity) {\n response.statusCode = 503;\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n return;\n }\n if (request.url === configPath) {\n response.end(\n JSON.stringify({\n ...identity,\n ...(app\n ? {\n channel,\n ...(connection ? { intervalMs: connection.intervalMs } : {}),\n demoData: process.env.UIBOT_LINKED_APP_DEMO_DATA === \"true\",\n tasksData,\n sessions: process.env.UIBOT_LINKED_APP_SESSIONS === \"true\",\n adminData,\n accountFlows,\n }\n : {}),\n }),\n );\n return;\n }\n const etag = request.headers[\"if-none-match\"];\n void fetch(upstream, {\n redirect: \"error\",\n signal: AbortSignal.timeout(10000),\n headers: {\n ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),\n ...(typeof etag === \"string\" ? { \"if-none-match\": etag } : {}),\n },\n })\n .then(async (result) => {\n response.statusCode = result.status;\n const tag = result.headers.get(\"etag\");\n if (tag) response.setHeader(\"ETag\", tag);\n if (result.status === 304) {\n response.end();\n return;\n }\n if (!result.ok) {\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n return;\n }\n const text = await result.text();\n if (text.length > 8_000_000) throw new Error(\"Oversized snapshot\");\n response.end(text);\n })\n .catch(() => {\n response.statusCode = 502;\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n });\n };\n return {\n name: `uibot-linked-${kind}-proxy`,\n middleware,\n config: () => (app && upstream ? { appType: \"mpa\" as const } : undefined),\n configureServer(server: { middlewares: { use(handler: LinkedMiddleware): void } }) {\n server.middlewares.use(middleware);\n },\n };\n}\n\n/** Vite adapter; deployed hosts use the same fixed reads without Vite middleware. */\nexport const linkedBackendPlugin = createLinkedBackend;\n","admin-backend.ts":"import { readFileSync } from \"node:fs\";\n\n/** Development-only service transport. Never import this module from browser code. */\nexport function adminBackendProxy(file: string | undefined, trusted = false) {\n if (!file) return undefined;\n const value: unknown = JSON.parse(readFileSync(file, \"utf8\"));\n if (!value || typeof value !== \"object\")\n throw new Error(\"Invalid backend transport configuration\");\n const config = value as Record<string, unknown>;\n for (const field of [\"gateway\", \"project\", \"workspace\", \"version\", \"serviceKey\"])\n if (typeof config[field] !== \"string\" || !config[field])\n throw new Error(\"Incomplete backend transport configuration\");\n const url = new URL(config.gateway as string);\n if (\n (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname) &&\n !(trusted && url.protocol === \"https:\")) ||\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash\n )\n throw new Error(\"Development backend must use a loopback gateway\");\n for (const field of [\"project\", \"workspace\", \"version\"])\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(config[field] as string))\n throw new Error(\"Invalid backend transport scope\");\n const prefix = `/api/${encodeURIComponent(config.project as string)}/${encodeURIComponent(config.version as string)}`;\n return {\n target: url.origin,\n changeOrigin: true,\n headers: {\n \"X-API-Key\": config.serviceKey as string,\n ...(typeof config.userToken === \"string\"\n ? { Authorization: `Bearer ${config.userToken}` }\n : {}),\n \"X-NowAPI-Project\": config.project as string,\n \"X-NowAPI-Workspace\": config.workspace as string,\n },\n rewrite: (path: string) => path.replace(/^\\/api\\/shadcn-admin\\/v1(?=\\/)/, prefix),\n };\n}\n\nexport function adminBackendSession(file: string | undefined): { userId: string | null } {\n if (!file) return { userId: null };\n const config = JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>;\n return { userId: typeof config.userId === \"string\" ? config.userId : null };\n}\n","app-session-plugin.ts":"import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { createAppSessionHost } from \"./app-session\";\n\nexport function appSessionPlugin() {\n const enabled = process.env.UIBOT_LINKED_APP_SESSIONS === \"true\";\n if (!enabled) return { name: \"uibot-app-session-disabled\" };\n const origin = process.env.UIBOT_LINKED_APP_SESSION_ORIGIN;\n const transportFile = process.env.UIBOT_ADMIN_TRANSPORT_FILE;\n if (\n !origin ||\n !transportFile ||\n process.env.UIBOT_LINKED_APP_TASKS !== \"true\" ||\n process.env.UIBOT_LINKED_APP_DEMO_DATA === \"true\"\n )\n throw Error(\n \"Sessions require an exact host origin, private Tasks transport and demo data disabled\",\n );\n const host = createAppSessionHost({\n origin,\n transportFile,\n adminBusiness: process.env.UIBOT_LINKED_APP_ADMIN === \"true\",\n accountFlows: process.env.UIBOT_LINKED_APP_AUTH === \"true\",\n });\n return {\n name: \"uibot-app-session-host\",\n configureServer(server: {\n httpServer: { once(event: \"close\", stop: () => void): void } | null;\n middlewares: {\n use(handler: (req: IncomingMessage, res: ServerResponse, next: () => void) => void): void;\n };\n }) {\n server.httpServer?.once(\"close\", host.dispose);\n server.middlewares.use((req, res, next) => {\n if (\n !/^\\/api\\/(?:app-session(?:\\/|$)|shadcn-admin(?:\\/|$))/.test(req.url?.split(\"?\")[0] ?? \"\")\n )\n return next();\n void (async () => {\n if (\n req.headers.host !== new URL(origin).host ||\n !req.url?.startsWith(\"/\") ||\n req.url.startsWith(\"//\") ||\n /%|\\.\\./.test(req.url.split(\"?\")[0] ?? \"\")\n ) {\n res.writeHead(403, { \"Cache-Control\": \"no-store\", \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ message: \"Host or route denied.\" }));\n return;\n }\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers))\n if (typeof value === \"string\") headers.set(key, value);\n const response = await host.handle(\n new Request(origin + req.url, {\n method: req.method,\n headers,\n ...(![\"GET\", \"HEAD\"].includes(req.method ?? \"\")\n ? { body: Readable.toWeb(req), duplex: \"half\" }\n : {}),\n } as RequestInit),\n );\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n res.end(await response.text());\n })().catch(() => {\n if (!res.headersSent)\n res.writeHead(502, { \"Cache-Control\": \"no-store\", \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ message: \"Session service unavailable.\" }));\n });\n });\n },\n };\n}\n","app-session.ts":"import { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { statSync } from \"node:fs\";\nimport { adminBackendProxy } from \"./admin-backend\";\nimport { adminBusinessRoute, adminBusinessMethod } from \"./admin-business\";\nimport {\n AccountFault,\n accountFlowMetadata,\n createAccountFlows,\n type AccountFlow,\n} from \"./app-account-flow\";\n\ntype User = { id: string; email: string; role: string };\nexport type AppSession = {\n csrf: string;\n expires: number;\n closed: boolean;\n attempts: number;\n access?: string;\n refresh?: string;\n accessExpires?: number;\n user?: User;\n refreshing?: Promise<void>;\n account?: AccountFlow;\n accountRetryAt?: number;\n busy?: boolean;\n};\nclass Fault extends Error {\n constructor(\n public status: number,\n public code: string,\n ) {\n super(code);\n }\n}\nconst secret = () => randomBytes(32).toString(\"base64url\");\nconst object = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === \"object\" && !Array.isArray(v);\nconst equal = (a: string, b: string) => {\n const left = Buffer.from(a),\n right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n};\nasync function textBody(request: Request | Response, limit = 65536) {\n const reader = request.body?.getReader();\n if (!reader) return \"\";\n const chunks: Uint8Array[] = [];\n let size = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Fault(408, \"body-timeout\")), 10000);\n });\n try {\n while (true) {\n const part = await Promise.race([reader.read(), timeout]);\n if (part.done) break;\n size += part.value.byteLength;\n if (size > limit) throw new Fault(413, \"body-too-large\");\n chunks.push(part.value);\n }\n } finally {\n clearTimeout(timer);\n void reader.cancel().catch(() => {});\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\nfunction parse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new Fault(400, \"invalid-json\");\n }\n}\n\n/** Loopback host example. Tokens never enter browser responses, Spec or browser storage. */\nexport function createAppSessionHost(options: {\n origin: string;\n transportFile: string;\n fetch?: typeof fetch;\n now?: () => number;\n maxSessions?: number;\n adminBusiness?: boolean;\n accountFlows?: boolean;\n trusted?: boolean;\n store?: {\n load(): [string, AppSession][];\n save(entries: [string, AppSession][]): void;\n close(): void;\n };\n}) {\n const origin = new URL(options.origin);\n if (\n origin.origin !== options.origin ||\n ![\"http:\", \"https:\"].includes(origin.protocol) ||\n (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(origin.hostname) &&\n !(options.trusted && origin.protocol === \"https:\"))\n )\n throw Error(\"Session example requires an exact loopback origin\");\n const configured = adminBackendProxy(options.transportFile, options.trusted);\n if ((statSync(options.transportFile).mode & 0o077) !== 0)\n throw Error(\"Session transport must be private\");\n if (!configured || configured.headers.Authorization)\n throw Error(\"Session transport must not contain a static user bearer\");\n const transport = configured;\n const send = options.fetch ?? fetch;\n const now = options.now ?? Date.now;\n const sessions = new Map<string, AppSession>(options.store?.load());\n let unavailable = false;\n let disposed = false;\n function checkpoint(exclude?: AppSession) {\n if (!options.store || disposed) return;\n try {\n options.store.save(\n [...sessions].filter(\n ([, entry]) =>\n entry !== exclude &&\n !entry.closed &&\n !entry.busy &&\n !entry.refreshing &&\n entry.expires > now(),\n ),\n );\n } catch {\n unavailable = true;\n sessions.clear();\n throw new Fault(503, \"session-store-unavailable\");\n }\n }\n const name = `${origin.protocol === \"https:\" ? \"__Host-\" : \"\"}uibot-session-${origin.port || \"default\"}`;\n const cookie = (id: string, seconds: number) =>\n `${name}=${id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${Math.max(0, Math.floor(seconds))}${origin.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n const headers = (access?: string) => ({\n ...transport.headers,\n ...(access ? { Authorization: `Bearer ${access}` } : {}),\n });\n async function upstream(\n path: string,\n method: string,\n body?: string,\n access?: string,\n extra?: Headers,\n ) {\n try {\n return await send(transport.target + path, {\n method,\n redirect: \"error\",\n signal: AbortSignal.timeout(10000),\n headers: {\n ...headers(access),\n ...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n ...(extra ? Object.fromEntries(extra) : {}),\n },\n ...(body !== undefined ? { body } : {}),\n });\n } catch {\n throw new Fault(502, \"upstream-unavailable\");\n }\n }\n const accounts = createAccountFlows({\n now,\n send: (path, body) => upstream(path, \"POST\", body),\n read: async (response) => parse(await textBody(response)),\n });\n async function readUser(access: string): Promise<User> {\n const response = await upstream(\"/auth/v1/user\", \"GET\", undefined, access);\n if (!response.ok) throw new Fault(response.status === 401 ? 401 : 502, \"session-unavailable\");\n const data = parse(await textBody(response));\n if (\n !object(data) ||\n typeof data.id !== \"string\" ||\n typeof data.email !== \"string\" ||\n typeof data.role !== \"string\"\n )\n throw new Fault(502, \"invalid-session-response\");\n return { id: data.id, email: data.email, role: data.role };\n }\n async function tokens(response: Response) {\n if (!response.ok)\n throw new Fault(\n response.status === 400 || response.status === 401 ? 401 : 502,\n \"sign-in-failed\",\n );\n const data = parse(await textBody(response));\n if (\n !object(data) ||\n typeof data.access_token !== \"string\" ||\n data.access_token.length > 16384 ||\n typeof data.refresh_token !== \"string\" ||\n data.refresh_token.length > 16384 ||\n typeof data.expires_in !== \"number\" ||\n data.expires_in <= 0 ||\n !Number.isFinite(data.expires_in) ||\n typeof data.session_expires_at !== \"number\" ||\n !Number.isFinite(data.session_expires_at) ||\n data.session_expires_at * 1000 <= now()\n )\n throw new Fault(502, \"invalid-session-response\");\n const user = await readUser(data.access_token);\n return {\n access: data.access_token,\n refresh: data.refresh_token,\n user,\n accessExpires: now() + data.expires_in * 1000,\n expires: data.session_expires_at * 1000,\n };\n }\n function close(session: AppSession) {\n session.closed = true;\n session.access = undefined;\n session.refresh = undefined;\n session.account = undefined;\n for (const [id, entry] of sessions) if (entry === session) sessions.delete(id);\n checkpoint();\n }\n async function authorize(session: AppSession) {\n if (session.closed || !session.access || !session.refresh || session.expires <= now())\n throw new Fault(401, \"sign-in-required\");\n if (session.refreshing || (session.accessExpires ?? 0) <= now() + 30000) {\n if (!session.refreshing) {\n // Remove durable credentials before a possibly committed token rotation.\n checkpoint(session);\n session.refreshing = (async () => {\n try {\n const next = await tokens(\n await upstream(\n \"/auth/v1/token?grant_type=refresh_token\",\n \"POST\",\n JSON.stringify({ refresh_token: session.refresh }),\n ),\n );\n if (session.closed || next.user.id !== session.user?.id)\n throw new Fault(401, \"session-changed\");\n Object.assign(session, next);\n } catch {\n close(session);\n // Rotation may have committed: never retry the old refresh token.\n throw new Fault(401, \"session-lost\");\n }\n })().finally(() => {\n session.refreshing = undefined;\n });\n }\n await session.refreshing;\n }\n if (session.closed || !session.access) throw new Fault(401, \"sign-in-required\");\n try {\n const user = await readUser(session.access);\n if (user.id !== session.user?.id) throw new Fault(401, \"session-changed\");\n session.user = user;\n } catch (error) {\n if (error instanceof Fault && error.status === 401) close(session);\n throw error;\n }\n }\n const metadata = (s: AppSession) =>\n s.user && !s.closed\n ? {\n authenticated: true,\n user: s.user,\n canBatch: s.user.role === \"admin\",\n csrfToken: s.csrf,\n accessExpiresAt: s.accessExpires,\n sessionExpiresAt: s.expires,\n }\n : {\n authenticated: false,\n csrfToken: s.csrf,\n ...(options.accountFlows ? { accountFlow: accountFlowMetadata(s.account) } : {}),\n };\n\n const host = {\n dispose() {\n checkpoint();\n disposed = true;\n for (const entry of sessions.values()) {\n entry.closed = true;\n entry.access = undefined;\n entry.refresh = undefined;\n entry.account = undefined;\n }\n sessions.clear();\n options.store?.close();\n },\n async handle(request: Request): Promise<Response> {\n let session: AppSession | undefined;\n let setCookie: string | undefined;\n let busySession: AppSession | undefined;\n const reply = (data: unknown, status = 200) =>\n new Response(JSON.stringify(data), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store\",\n \"X-Content-Type-Options\": \"nosniff\",\n ...(setCookie ? { \"Set-Cookie\": setCookie } : {}),\n },\n });\n try {\n const url = new URL(request.url);\n if (\n url.origin !== origin.origin ||\n (request.headers.get(\"origin\") && request.headers.get(\"origin\") !== origin.origin) ||\n [\"cross-site\", \"same-site\"].includes(request.headers.get(\"sec-fetch-site\") ?? \"\")\n )\n throw new Fault(403, \"origin-denied\");\n const match =\n request.headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((s) => s.trim())\n .filter((s) => s.startsWith(`${name}=`)) ?? [];\n if (match.length > 1) throw new Fault(401, \"invalid-session\");\n const id = match[0]?.slice(name.length + 1);\n session = id ? sessions.get(id) : undefined;\n if (session && (session.closed || session.expires <= now())) {\n close(session);\n session = undefined;\n }\n const path = url.pathname;\n const authPath =\n /^\\/api\\/app-session(?:\\/(login|refresh|logout|account-start|account-verify))?$/.exec(\n path,\n );\n const business = adminBusinessRoute(path, options.adminBusiness === true);\n const dashboard = options.adminBusiness && path === \"/api/shadcn-admin/v1/dashboard\";\n if (!authPath && !business && !dashboard) throw new Fault(404, \"route-not-found\");\n const action = authPath?.[1];\n const read = request.method === \"GET\";\n if (authPath && (url.search || request.method !== (action ? \"POST\" : \"GET\")))\n throw new Fault(405, \"method-not-allowed\");\n if (\n !read &&\n (request.headers.get(\"origin\") !== origin.origin ||\n !request.headers.get(\"content-type\")?.startsWith(\"application/json\"))\n )\n throw new Fault(403, \"csrf-denied\");\n if (authPath && !action && !session) {\n for (const entry of sessions.values()) if (entry.expires <= now()) close(entry);\n if (sessions.size >= (options.maxSessions ?? 100))\n throw new Fault(503, \"session-capacity\");\n const fresh = secret();\n session = { csrf: secret(), expires: now() + 300000, closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, 300);\n }\n if (!session) throw new Fault(401, \"sign-in-required\");\n if (!read && !equal(request.headers.get(\"x-uibot-csrf\") ?? \"\", session.csrf))\n throw new Fault(403, \"csrf-denied\");\n if (action) {\n if (session.busy) throw new Fault(409, \"session-request-pending\");\n session.busy = true;\n busySession = session;\n // A crash during authentication must never replay stored credentials/challenges.\n checkpoint();\n }\n if (action === \"account-start\" || action === \"account-verify\") {\n if (!options.accountFlows) throw new Fault(404, \"account-service-disabled\");\n if (session.user) throw new Fault(409, \"sign-out-before-account-flow\");\n const input = parse(await textBody(request));\n if (action === \"account-start\") {\n if ((session.accountRetryAt ?? 0) > now()) throw new Fault(429, \"account-cooldown\");\n if (++session.attempts > 5) throw new Fault(429, \"account-start-rate-limit\");\n session.accountRetryAt = now() + 60000;\n if (session.account) session.account.unknown = true;\n const flow = await accounts.start(input, session.account);\n if (session.closed) throw new Fault(401, \"session-changed\");\n session.account = flow;\n session.expires = Math.max(session.expires, session.account.expiresAt + 60000);\n setCookie = cookie(id as string, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n const response = await accounts.verify(session.account, input);\n if (session.closed) throw new Fault(401, \"session-changed\");\n if (session.account?.purpose === \"recovery\") {\n const data = parse(await textBody(response));\n if (!object(data) || data.recovered !== true || data.sessionsRevoked !== true)\n throw new Fault(502, \"invalid-account-response\");\n const email = session.account.email;\n for (const entry of sessions.values()) if (entry.user?.email === email) close(entry);\n close(session);\n const fresh = secret();\n session = { csrf: secret(), expires: now() + 300000, closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, 300);\n return reply({ ...metadata(session), recovered: true });\n }\n const next = await tokens(response);\n if (session.closed || next.user.email !== session.account?.email)\n throw new Fault(401, \"session-changed\");\n close(session);\n const fresh = secret();\n session = { ...next, csrf: secret(), closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n if (action === \"login\") {\n if (session.user) throw new Fault(409, \"sign-out-before-login\");\n if (++session.attempts > 5) throw new Fault(429, \"sign-in-rate-limit\");\n const input = parse(await textBody(request));\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"email\", \"password\"].includes(key)) ||\n typeof input.email !== \"string\" ||\n typeof input.password !== \"string\" ||\n input.email.length > 320 ||\n input.password.length > 1024 ||\n !input.email ||\n !input.password\n )\n throw new Fault(400, \"invalid-login\");\n const next = await tokens(\n await upstream(\"/auth/v1/token?grant_type=password\", \"POST\", JSON.stringify(input)),\n );\n if (session.closed) throw new Fault(401, \"session-changed\");\n close(session);\n const fresh = secret();\n session = { ...next, csrf: secret(), closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n if (action === \"logout\") {\n const access = session.access;\n const refreshing = session.refreshing;\n close(session);\n setCookie = cookie(\"\", 0);\n // A concurrent rotation makes remote revocation uncertain; local access is always removed.\n let revoked = false;\n if (access && !refreshing) {\n try {\n revoked = (await upstream(\"/auth/v1/logout\", \"POST\", \"{}\", access)).ok;\n } catch {}\n }\n return reply({ authenticated: false, revoked }, revoked || !access ? 200 : 502);\n }\n if (action === \"refresh\") session.accessExpires = 0;\n if (authPath) {\n if (session.user || action) await authorize(session);\n return reply(metadata(session));\n }\n await authorize(session);\n if (dashboard) {\n if (!read || url.search) throw new Fault(405, \"method-not-allowed\");\n const count = async (table: string, status?: string) => {\n const query = new URLSearchParams({ limit: \"1\" });\n if (status)\n query.set(\"filter\", JSON.stringify({ op: \"eq\", field: \"status\", value: status }));\n const response = await upstream(\n `${transport.rewrite(`/api/shadcn-admin/v1/${table}`)}?${query}`,\n \"GET\",\n undefined,\n session?.access,\n );\n if (!response.ok)\n throw new Fault(response.status === 401 ? 401 : 503, \"summary-unavailable\");\n const data = parse(await textBody(response));\n if (\n !object(data) ||\n typeof data.total !== \"number\" ||\n !Number.isSafeInteger(data.total) ||\n data.total < 0\n )\n throw new Fault(503, \"summary-unavailable\");\n return data.total;\n };\n const statuses = [\"backlog\", \"todo\", \"in progress\", \"done\", \"canceled\"];\n const [tasks, conversations, integrations, preferences, users, ...totals] =\n await Promise.all([\n count(\"tasks\"),\n count(\"conversations\"),\n count(\"integrations\"),\n count(\"preferences\"),\n session.user?.role === \"admin\" ? count(\"users\") : Promise.resolve(null),\n ...statuses.map((status) => count(\"tasks\", status)),\n ]);\n return reply({\n observedAt: new Date(now()).toISOString(),\n atomic: false,\n tasks,\n conversations,\n integrations,\n preferences,\n users,\n taskStatus: statuses.map((label, i) => ({ label, value: totals[i] })),\n });\n }\n if (!business) throw new Fault(404, \"route-not-found\");\n const { item, batch, table } = business;\n if (!adminBusinessMethod(business, request.method))\n throw new Fault(405, \"method-not-allowed\");\n if (table === \"users\" && session.user?.role !== \"admin\")\n throw new Fault(403, \"permission-denied\");\n if (batch && session.user?.role !== \"admin\") throw new Fault(403, \"permission-denied\");\n const query = [...url.searchParams.keys()];\n if (\n url.search.length > 8192 ||\n query.some((key) => ![\"limit\", \"filter\", \"order\", \"cursor\"].includes(key)) ||\n new Set(query).size !== query.length ||\n (!read && url.search)\n )\n throw new Fault(400, \"invalid-query\");\n const extra = new Headers();\n if (!read) {\n const key = request.headers.get(\"idempotency-key\");\n if (!key || !/^[\\x21-\\x7e]{1,128}$/.test(key))\n throw new Fault(400, \"write-intent-required\");\n extra.set(\"Idempotency-Key\", key);\n if (item) {\n const version = request.headers.get(\"if-match\");\n if (!version || !/^[1-9][0-9]{0,14}$/.test(version))\n throw new Fault(428, \"version-required\");\n extra.set(\"If-Match\", version);\n }\n }\n const body = read ? undefined : await textBody(request);\n const target = transport.rewrite(path) + url.search;\n const response = await upstream(target, request.method, body, session.access, extra);\n if (response.status === 401) {\n close(session);\n // A late response must not erase a newly signed-in browser cookie.\n }\n if (!response.ok)\n return reply(\n {\n message:\n response.status === 403\n ? \"Permission denied.\"\n : response.status === 409\n ? \"This record changed. Reload before saving again.\"\n : response.status === 401\n ? \"Sign in to continue. Your unsaved input is preserved.\"\n : \"The request could not be completed.\",\n code: response.status === 401 ? \"sign-in-required\" : \"request-rejected\",\n },\n response.status,\n );\n const result = parse(await textBody(response, 2_000_000));\n return reply(result, response.status);\n } catch (error) {\n const fault =\n error instanceof Fault || error instanceof AccountFault\n ? error\n : new Fault(502, \"request-unavailable\");\n if (fault.status === 401) {\n if (session?.access || session?.closed) close(session);\n // Anonymous login failures retain their bounded attempt counter.\n }\n return reply(\n {\n code: fault.code,\n message:\n fault.status === 401\n ? \"Sign in to continue. Your unsaved input is preserved.\"\n : fault.status === 403\n ? \"Permission denied.\"\n : \"The request could not be completed.\",\n },\n fault.status,\n );\n } finally {\n if (busySession) busySession.busy = false;\n }\n },\n };\n return {\n dispose: host.dispose,\n async handle(request: Request): Promise<Response> {\n try {\n if (unavailable) throw new Fault(503, \"session-store-unavailable\");\n const response = await host.handle(request);\n checkpoint();\n return response;\n } catch {\n unavailable = true;\n sessions.clear();\n return Response.json(\n { code: \"session-store-unavailable\", message: \"Session service unavailable.\" },\n { status: 503, headers: { \"Cache-Control\": \"no-store\" } },\n );\n }\n },\n };\n}\n","app-account-flow.ts":"export type AccountPurpose = \"signup\" | \"recovery\" | \"otp\";\nexport type AccountFlow = {\n id: string;\n purpose: AccountPurpose;\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n attempts: number;\n unknown: boolean;\n};\nexport class AccountFault extends Error {\n constructor(\n public status: number,\n public code: string,\n ) {\n super(code);\n }\n}\nconst object = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === \"object\" && !Array.isArray(v);\nexport const accountFlowMetadata = (flow?: AccountFlow) =>\n flow\n ? {\n purpose: flow.purpose,\n delivery: flow.delivery,\n email: flow.email,\n expiresAt: flow.expiresAt,\n retryAt: flow.retryAt,\n unknown: flow.unknown,\n }\n : null;\n\n/** Challenge identity and credentials stay in the host; this has no browser storage. */\nexport function createAccountFlows(options: {\n now(): number;\n send(path: string, body: string): Promise<Response>;\n read(response: Response): Promise<unknown>;\n}) {\n const fail = (status: number, code: string): never => {\n throw new AccountFault(status, code);\n };\n return {\n async start(input: unknown, previous?: AccountFlow): Promise<AccountFlow> {\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"email\", \"purpose\"].includes(key)) ||\n typeof input.email !== \"string\" ||\n input.email.length > 254 ||\n !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(input.email) ||\n ![\"signup\", \"recovery\", \"otp\"].includes(String(input.purpose))\n )\n return fail(400, \"invalid-account-request\");\n if (previous && previous.retryAt > options.now()) return fail(429, \"account-cooldown\");\n const response = await options.send(\"/auth/v1/challenge\", JSON.stringify(input));\n if (!response.ok)\n return fail(response.status === 429 ? 429 : 503, \"account-delivery-unavailable\");\n const data = await options.read(response);\n if (\n response.status !== 202 ||\n !object(data) ||\n data.accepted !== true ||\n typeof data.challengeId !== \"string\" ||\n !/^[a-f0-9-]{36}$/i.test(data.challengeId) ||\n typeof data.expiresIn !== \"number\" ||\n !Number.isSafeInteger(data.expiresIn) ||\n data.expiresIn < 1 ||\n data.expiresIn > (input.purpose === \"signup\" ? 1800 : 600) ||\n ![\"local_http\", \"smtp\"].includes(String(data.delivery))\n )\n return fail(502, \"invalid-account-response\");\n return {\n id: data.challengeId,\n email: input.email.trim().toLowerCase(),\n purpose: input.purpose as AccountPurpose,\n delivery: data.delivery as AccountFlow[\"delivery\"],\n expiresAt: options.now() + data.expiresIn * 1000,\n retryAt: options.now() + 60000,\n attempts: 0,\n unknown: false,\n };\n },\n async verify(flow: AccountFlow | undefined, input: unknown): Promise<Response> {\n if (!flow || flow.unknown || flow.expiresAt <= options.now())\n return fail(409, \"account-challenge-unavailable\");\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"token\", \"password\", \"confirm\"].includes(key)) ||\n typeof input.token !== \"string\" ||\n !/^(?:[0-9]{6}|[a-f0-9]{64})$/i.test(input.token) ||\n (flow.purpose !== \"otp\" &&\n (typeof input.password !== \"string\" ||\n [...input.password].length < 12 ||\n [...input.password].length > 128 ||\n new TextEncoder().encode(input.password).byteLength > 1024 ||\n input.confirm !== input.password)) ||\n (flow.purpose === \"otp\" && (\"password\" in input || \"confirm\" in input))\n )\n return fail(400, \"invalid-account-verification\");\n if (++flow.attempts > 5) return fail(429, \"account-verification-rate-limit\");\n try {\n const response = await options.send(\n \"/auth/v1/challenge/verify\",\n JSON.stringify({\n challengeId: flow.id,\n purpose: flow.purpose,\n token: input.token,\n ...(flow.purpose !== \"otp\" ? { password: input.password } : {}),\n }),\n );\n if (!response.ok) {\n if (response.status >= 500) flow.unknown = true;\n if ([400, 422].includes(response.status))\n return fail(400, \"invalid-account-verification\");\n if (response.status === 409) return fail(409, \"account-challenge-unavailable\");\n return fail(\n response.status === 401 ? 401 : response.status === 429 ? 429 : 502,\n response.status === 401 ? \"invalid-account-code\" : \"account-verification-unknown\",\n );\n }\n // Any later parsing/session failure may follow a committed consumption.\n flow.unknown = true;\n return response;\n } catch (error) {\n if (!(error instanceof AccountFault)) flow.unknown = true;\n throw error;\n }\n },\n };\n}\n","app-server.ts":"import { createHash } from \"node:crypto\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { resolve, sep } from \"node:path\";\nimport { createLinkedBackend } from \"./linked-backend\";\nimport { createAppSessionHost } from \"./app-session\";\nimport { createSessionStorage } from \"./app-session-storage\";\n\n/** Fixed-route application server, independent of Vite and its development middleware. */\nexport function createAppServer(options: { root: string; origin: string }) {\n const origin = new URL(options.origin);\n const loopback = [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(origin.hostname);\n if (\n origin.origin !== options.origin ||\n (origin.protocol !== \"https:\" && !(loopback && origin.protocol === \"http:\"))\n )\n throw Error(\"Host requires an exact HTTPS origin or local HTTP loopback\");\n if (process.env.UIBOT_LINKED_APP_DEMO_DATA === \"true\")\n throw Error(\"Server does not permit demo data\");\n const root = realpathSync(options.root);\n const proxy = createLinkedBackend(\"app\", { trusted: true }).middleware;\n let session: ReturnType<typeof createAppSessionHost> | undefined;\n if (process.env.UIBOT_LINKED_APP_SESSIONS === \"true\") {\n const transportFile = process.env.UIBOT_ADMIN_TRANSPORT_FILE;\n const file = process.env.UIBOT_APP_SESSION_DB;\n const keyFile = process.env.UIBOT_APP_SESSION_KEY_FILE;\n if (\n !transportFile ||\n !file ||\n !keyFile ||\n process.env.UIBOT_LINKED_APP_SESSION_ORIGIN !== options.origin\n )\n throw Error(\n \"Server sessions require private transport, persistent storage, key and matching origin\",\n );\n const scope = createHash(\"sha256\")\n .update(options.origin)\n .update(readFileSync(transportFile))\n .digest(\"hex\");\n session = createAppSessionHost({\n origin: options.origin,\n transportFile,\n trusted: true,\n store: createSessionStorage({ file, keyFile, scope }),\n adminBusiness: process.env.UIBOT_LINKED_APP_ADMIN === \"true\",\n accountFlows: process.env.UIBOT_LINKED_APP_AUTH === \"true\",\n });\n } else if (process.env.UIBOT_LINKED_APP_TASKS === \"true\") {\n throw Error(\"Server business routes require per-user sessions\");\n }\n const security = {\n \"X-Content-Type-Options\": \"nosniff\",\n \"Referrer-Policy\": \"no-referrer\",\n \"Content-Security-Policy\":\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\",\n ...(origin.protocol === \"https:\" ? { \"Strict-Transport-Security\": \"max-age=31536000\" } : {}),\n };\n const json = (status: number, message: string) =>\n Response.json({ message }, { status, headers: { \"Cache-Control\": \"no-store\" } });\n async function handle(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname === \"/healthz\" && request.method === \"GET\") return json(200, \"ready\");\n if (request.headers.get(\"host\") !== origin.host) return json(403, \"Host denied.\");\n const path = url.pathname;\n if (/%|\\\\|\\/\\./.test(path)) return json(400, \"Invalid route.\");\n if (/^\\/api\\/(app-session|shadcn-admin)(\\/|$)/.test(path)) {\n return session\n ? session.handle(new Request(options.origin + path + url.search, request))\n : json(503, \"Business service unavailable.\");\n }\n if ([\"/linked-app-config.json\", \"/linked-app.json\"].includes(path)) {\n if (url.search) return json(400, \"Invalid query.\");\n return new Promise<Response>((done) => {\n const headers = new Headers();\n const response = {\n statusCode: 200,\n setHeader(k: string, v: string) {\n headers.set(k, v);\n },\n end(body?: string) {\n done(new Response(body, { status: response.statusCode, headers }));\n },\n };\n proxy(\n { url: path, method: request.method, headers: Object.fromEntries(request.headers) },\n response,\n () => done(json(404, \"Not found.\")),\n );\n });\n }\n if (![\"GET\", \"HEAD\"].includes(request.method)) return json(405, \"Method not allowed.\");\n if (/^\\/(api|src|node_modules|@)(\\/|$)/.test(path)) return json(404, \"Not found.\");\n let candidate = resolve(root, `.${path}`);\n try {\n candidate = realpathSync(candidate);\n if (candidate !== root && !candidate.startsWith(root + sep)) return json(404, \"Not found.\");\n } catch {\n if (!request.headers.get(\"accept\")?.includes(\"text/html\") || /\\.[^/]+$/.test(path))\n return json(404, \"Not found.\");\n candidate = resolve(root, \"index.html\");\n }\n if (candidate === root || path === \"/\") candidate = resolve(root, \"index.html\");\n const file = Bun.file(candidate);\n if (!(await file.exists())) return json(404, \"Not found.\");\n return new Response(request.method === \"HEAD\" ? null : file, {\n headers: {\n \"Content-Type\": file.type,\n \"Cache-Control\": candidate.endsWith(\".html\") ? \"no-store\" : \"public, max-age=3600\",\n },\n });\n }\n return {\n dispose() {\n session?.dispose();\n },\n async handle(request: Request) {\n let response: Response;\n try {\n response = await handle(request);\n } catch {\n response = json(503, \"Service unavailable.\");\n }\n for (const [key, value] of Object.entries(security)) response.headers.set(key, value);\n return response;\n },\n };\n}\n\nif (import.meta.main) {\n process.umask(0o077);\n const origin = process.env.UIBOT_APP_ORIGIN;\n if (\n !origin ||\n !process.env.UIBOT_LINKED_APP_CONNECTION_FILE ||\n !process.env.UIBOT_LINKED_APP_BEARER\n )\n throw Error(\n \"Configure application origin, connection file and server-only Viewer authorization\",\n );\n if (\n ![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(new URL(origin).hostname) &&\n process.env.UIBOT_LINKED_APP_CHANNEL !== \"production\"\n )\n throw Error(\"Public application hosts require the production release channel\");\n const port = Number(process.env.PORT ?? \"8080\");\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error(\"Invalid server port\");\n const app = createAppServer({ root: resolve(\"dist\"), origin });\n const server = Bun.serve({\n hostname:\n process.env.HOST ??\n ([\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(new URL(origin).hostname)\n ? new URL(origin).hostname.replace(/^\\[|\\]$/g, \"\")\n : \"0.0.0.0\"),\n port,\n maxRequestBodySize: 65536,\n fetch: app.handle,\n });\n const stop = () => {\n server.stop(true);\n try {\n app.dispose();\n process.exit(0);\n } catch {\n process.exit(1);\n }\n };\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGINT\", stop);\n console.log(`UIBot application listening on port ${port}`);\n}\n","app-session-storage.ts":"import { Database } from \"bun:sqlite\";\nimport { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport { chmodSync, lstatSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type { AppSession } from \"./app-session\";\n\n/** Single-process store. SQLite owns the writer lock; credentials are encrypted at rest. */\nexport function createSessionStorage(options: { file: string; keyFile: string; scope: string }) {\n const file = resolve(options.file);\n const parent = lstatSync(dirname(file));\n const keyStat = lstatSync(options.keyFile);\n if (\n !parent.isDirectory() ||\n parent.isSymbolicLink() ||\n parent.mode & 0o077 ||\n !keyStat.isFile() ||\n keyStat.isSymbolicLink() ||\n keyStat.mode & 0o077\n )\n throw Error(\"Session directory and encryption key must be private\");\n try {\n const stat = lstatSync(file);\n if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077)\n throw Error(\"Session database must be a private regular file\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n const raw = readFileSync(options.keyFile, \"utf8\").trim();\n if (!/^[a-f0-9]{64}$/.test(raw)) throw Error(\"Session key must contain 32 random bytes as hex\");\n const key = Buffer.from(raw, \"hex\");\n const aad = Buffer.from(`uibot.host-sessions.v1:${options.scope}`);\n const db = new Database(file, { create: true, strict: true });\n chmodSync(file, 0o600);\n try {\n db.exec(\n \"PRAGMA busy_timeout=0; PRAGMA journal_mode=DELETE; PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY CHECK(id=1), payload BLOB NOT NULL); COMMIT;\",\n );\n } catch {\n db.close();\n throw Error(\"Session database is unavailable or owned by another host\");\n }\n return {\n load(): [string, AppSession][] {\n try {\n const row = db.query(\"SELECT payload FROM sessions WHERE id=1\").get() as {\n payload: Uint8Array;\n } | null;\n if (!row) return [];\n const bytes = Buffer.from(row.payload);\n if (bytes.length < 29 || bytes.length > 8_000_000) throw Error();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, bytes.subarray(0, 12));\n decipher.setAAD(aad);\n decipher.setAuthTag(bytes.subarray(12, 28));\n const entries = JSON.parse(\n Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString(),\n );\n if (\n !Array.isArray(entries) ||\n entries.length > 100 ||\n entries.some(\n (entry) =>\n !Array.isArray(entry) ||\n entry.length !== 2 ||\n !/^[A-Za-z0-9_-]{43}$/.test(entry[0]) ||\n !entry[1] ||\n typeof entry[1].csrf !== \"string\" ||\n !Number.isFinite(entry[1].expires) ||\n entry[1].closed !== false ||\n entry[1].busy ||\n entry[1].refreshing,\n )\n )\n throw Error();\n return entries;\n } catch {\n db.close();\n throw Error(\"Session storage cannot be authenticated; restore its original key and scope\");\n }\n },\n save(entries: [string, AppSession][]) {\n const plain = Buffer.from(JSON.stringify(entries));\n if (entries.length > 100 || plain.length > 7_999_000)\n throw Error(\"Session capacity exceeded\");\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n cipher.setAAD(aad);\n const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]);\n db.query(\"INSERT OR REPLACE INTO sessions (id,payload) VALUES (1,?)\").run(\n Buffer.concat([iv, cipher.getAuthTag(), ciphertext]),\n );\n },\n close() {\n db.close();\n key.fill(0);\n },\n };\n}\n","src/app-styles.css":"@import \"tailwindcss\" source(none);\n@source \"./\";\n@source \"../node_modules/@uibot\";\n@source \"../uibot.app.json\";\n@custom-variant dark (&:where(.dark, .dark *));\n@theme inline {\n --color-background: var(--background);\n --color-foreground: var(--foreground);\n --color-card: var(--card);\n --color-card-foreground: var(--foreground);\n --color-popover: var(--background);\n --color-popover-foreground: var(--foreground);\n --color-primary: var(--primary);\n --color-primary-foreground: var(--primary-foreground);\n --color-muted: var(--muted);\n --color-muted-foreground: var(--muted-foreground);\n --color-border: var(--border);\n --color-input: var(--border);\n --color-ring: var(--ring);\n --color-accent: var(--muted);\n --color-accent-foreground: var(--foreground);\n --color-destructive: #dc2626;\n}\n","app.html":"<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Linked application consumer</title>\n </head>\n <body><div id=\"root\"></div><script type=\"module\" src=\"/src/app.tsx\"></script></body>\n</html>\n","index.html":"<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Linked application consumer</title>\n </head>\n <body><div id=\"root\"></div><script type=\"module\" src=\"/src/app.tsx\"></script></body>\n</html>\n"}}
1
+ {"contract":"uibot.app-host-template.v1","version":"0.22.0","files":{"src/app.tsx":"import \"./app-styles.css\";\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { compileSpec, parseConfig } from \"@uibot/compiler\";\nimport type {\n AppDocument,\n CompiledUIBotSpec,\n LinkedSpecIdentity,\n UIBotSpec,\n AvailableAppHostView,\n AppHostReadiness,\n} from \"@uibot/contracts\";\nimport { createShadcnReactRegistry, CATALOG_ENTRIES, ScrollArea } from \"@uibot/blocks-shadcn\";\nimport {\n createAppHostViewSync,\n createHostDataDriver,\n createLinkedSpecHttpReader,\n verifyAppModules,\n UIBotAppHost,\n type LinkedSpecStatus,\n} from \"@uibot/runtime\";\nimport { installedModuleHashes, installedPages } from \"./app-modules\";\nimport { AppPageNavigator } from \"./app-page-navigator\";\nimport { createAppNavigation } from \"./app-navigation\";\nimport { protectUnsavedUnload } from \"./admin-navigation\";\nimport { createLinkedAppRuntime, prepareLinkedAppSource } from \"./app-runtime\";\nimport type { AppRoutePage } from \"./app-route-tree\";\nimport { bindCompiledSessionIdentity } from \"./app-session-source\";\nimport { createAppSessionClient, type AppSessionClient } from \"./app-session-client\";\nimport { createAppFeatures } from \"./app-features\";\nimport { accountFlowKey, accountPageState, isAccountRoute } from \"./app-account-source\";\nimport { HOST_SESSION_ACTION } from \"./app-session-action\";\nimport \"./admin.css\";\nimport \"./app-shell.css\";\nconst registry = createShadcnReactRegistry();\nconst catalog = {\n components: CATALOG_ENTRIES,\n actions: { HostSession: HOST_SESSION_ACTION },\n templates: {},\n};\n/** Bounded, source-free explanation of why the newest revision was not adopted. */\nconst problemText = (names: Iterable<string>, label: string) => {\n const list = [...new Set(names)].sort();\n return `${label}: ${list.slice(0, 8).join(\", \")}${list.length > 8 ? ` and ${list.length - 8} more` : \"\"}`.slice(\n 0,\n 300,\n );\n};\nfunction InstalledPage({ id }: { id?: string }) {\n const Page = id ? installedPages[id] : undefined;\n return Page ? <Page key={id} /> : null;\n}\nfunction Consumer({\n identity,\n installedModules,\n channel,\n dataEnvironment = \"mock\",\n dataSession,\n intervalMs = 1000,\n accountFlows = false,\n session,\n sessionState,\n returnPath = \"/tasks\",\n}: {\n identity: LinkedSpecIdentity;\n installedModules: Readonly<Record<string, { sourceHash: string }>>;\n channel: \"development\" | \"production\";\n dataEnvironment?: string;\n dataSession?: AppSessionClient;\n intervalMs?: number;\n accountFlows?: boolean;\n session?: AppSessionClient;\n sessionState?: ReturnType<AppSessionClient[\"snapshot\"]>;\n returnPath?: string;\n}) {\n const [status, setStatus] = useState<LinkedSpecStatus>(\"loading\");\n const [problem, setProblem] = useState(\"\");\n const [checking, setChecking] = useState(false);\n const [signingOut, setSigningOut] = useState(false);\n const retry = useRef<(() => Promise<void>) | undefined>(undefined);\n const activeRuntime = useRef<ReturnType<typeof createLinkedAppRuntime> | undefined>(undefined);\n useEffect(() => {\n const unload = (event: BeforeUnloadEvent) =>\n protectUnsavedUnload(event, Boolean(activeRuntime.current?.pendingPages().length));\n window.addEventListener(\"beforeunload\", unload);\n return () => window.removeEventListener(\"beforeunload\", unload);\n }, []);\n const [route, setRoute] = useState(window.location.pathname);\n const navigation = useMemo(\n () =>\n createAppNavigation({\n readUrl: () => window.location.href,\n writeUrl: (url, replace) =>\n window.history[replace ? \"replaceState\" : \"pushState\"](window.history.state, \"\", url),\n onRoute: setRoute,\n }),\n [],\n );\n useEffect(() => {\n const pop = () => {\n navigation.navigate(window.location.href);\n };\n window.addEventListener(\"popstate\", pop);\n return () => window.removeEventListener(\"popstate\", pop);\n }, [navigation]);\n const [counter, setCounter] = useState(0);\n const [detailsOpen, setDetailsOpen] = useState(false);\n const [navigatorOpen, setNavigatorOpen] = useState(false);\n const navigatorToggle = useRef<HTMLButtonElement>(null);\n const canvas = useRef<HTMLElement>(null);\n const [current, setCurrent] = useState<{\n document: AppDocument;\n spec: CompiledUIBotSpec;\n runtime: ReturnType<typeof createLinkedAppRuntime>;\n revision?: number;\n revisionId: string;\n release?: number;\n dataReadiness: AppHostReadiness[];\n }>();\n useEffect(() => {\n const sync = createAppHostViewSync<CompiledUIBotSpec>({\n channel,\n environment: dataEnvironment,\n ...identity,\n intervalMs,\n read: createLinkedSpecHttpReader({\n url: \"/linked-app.json\",\n }),\n canApply: () => !activeRuntime.current?.pendingPages().length,\n prepare: async (snapshot) => {\n setProblem(\"\");\n try {\n await verifyAppModules(snapshot.document, installedModules);\n } catch {\n const stale: string[] = [];\n for (const page of snapshot.document.tsx)\n await verifyAppModules({ ...snapshot.document, tsx: [page] }, installedModules).catch(\n () => stale.push(page.id),\n );\n setProblem(\n `${problemText(stale, \"TSX pages need a host build\")}. Run uibot app pull, then rebuild.`,\n );\n throw Error(\"Application modules unavailable\");\n }\n const result = await compileSpec(\n prepareLinkedAppSource(parseConfig(snapshot.document.spec) as UIBotSpec, {\n sessions: Boolean(session),\n accountFlows,\n features: createAppFeatures({\n environment: dataEnvironment,\n canBatch: session ? () => session.snapshot().info?.canBatch === true : undefined,\n }),\n }),\n catalog,\n { strict: true },\n );\n const missing = [\n ...result.gaps\n .filter((gap) => gap.reason !== \"invalid-spec\")\n .map((gap) => gap.missingType),\n ...Object.values(result.spec.blocks)\n .filter((block) => !registry.get(block.type))\n .map((block) => block.type),\n ];\n if (result.gaps.length || missing.length) {\n setProblem(\n missing.length\n ? `${problemText(missing, \"Components not installed in this host\")}.`\n : \"The saved Spec has validation errors; fix them in the editor.\",\n );\n throw Error(\"Application dependencies unavailable\");\n }\n if (session) bindCompiledSessionIdentity(result.spec, session.snapshot().info?.user);\n return result.spec;\n },\n apply: (spec, snapshot: AvailableAppHostView) => {\n const runtime = createLinkedAppRuntime({\n spec,\n source: parseConfig(snapshot.document.spec) as UIBotSpec,\n identity,\n channel,\n dataEnvironment,\n dataDriver:\n dataEnvironment !== \"mock\"\n ? createHostDataDriver({\n endpoint: \"/api/uibot/data\",\n revisionId: () => snapshot.revision.revisionId,\n fetch: dataSession?.fetch ?? session?.fetch,\n })\n : undefined,\n sessionAction: session?.action,\n features: createAppFeatures({\n source: parseConfig(snapshot.document.spec) as UIBotSpec,\n environment: dataEnvironment,\n canBatch: session ? () => session.snapshot().info?.canBatch === true : undefined,\n }),\n storage: sessionStorage,\n urlState: {\n read: () => new URLSearchParams(location.search),\n write: (params) => {\n const url = new URL(location.href);\n url.search = params.toString();\n history.replaceState(history.state, \"\", url);\n },\n },\n navigate: (destination) => {\n navigation.navigate(destination);\n },\n });\n activeRuntime.current = runtime;\n setCurrent({\n document: snapshot.document,\n spec,\n revisionId: snapshot.revision.revisionId,\n dataReadiness: snapshot.dataReadiness,\n ...(snapshot.channel === \"production\"\n ? { release: snapshot.revision.releaseSequence }\n : { revision: snapshot.revision.revisionNumber }),\n runtime,\n });\n if (window.location.pathname === \"/app.html\")\n navigation.navigate(\n snapshot.document.entryPath + window.location.search + window.location.hash,\n true,\n );\n },\n onStatus: setStatus,\n });\n retry.current = sync.refresh;\n return () => {\n retry.current = undefined;\n sync.stop();\n activeRuntime.current = undefined;\n };\n }, [\n identity,\n installedModules,\n channel,\n dataEnvironment,\n dataSession,\n intervalMs,\n navigation,\n accountFlows,\n session,\n ]);\n useEffect(() => () => current?.runtime.dispose(), [current]);\n const visible = status === \"denied\" || status === \"unpublished\" ? undefined : current;\n const returnRoute = useRef<string>(returnPath);\n const authenticated = !session || Boolean(sessionState?.info);\n useEffect(() => {\n if (!session || !sessionState?.ready) return;\n if (!authenticated) {\n if (!(accountFlows ? isAccountRoute(route) : route.startsWith(\"/sign-in\"))) {\n returnRoute.current = route;\n navigation.navigate(\"/sign-in\", true);\n }\n } else if (isAccountRoute(route)) navigation.navigate(returnRoute.current, true);\n }, [session, sessionState?.ready, authenticated, navigation, route, accountFlows]);\n const displayRoute =\n authenticated || (accountFlows && isAccountRoute(route)) ? route : \"/sign-in\";\n useEffect(() => {\n if (!current || !accountFlows || authenticated) return;\n const otp = current.runtime.forPage(\"/otp\");\n const sync = () => {\n void otp.dispatch(\n Object.entries(\n accountPageState(\n sessionState?.accountFlow ?? null,\n Date.now(),\n sessionState?.accountPending,\n otp.snapshot().accountFlowKey,\n ),\n ).map(([path, value]) => ({ action: \"SetState\", params: { path, value } })),\n );\n };\n sync();\n const interval = window.setInterval(sync, 1000);\n return () => clearInterval(interval);\n }, [\n current,\n accountFlows,\n authenticated,\n sessionState?.accountFlow,\n sessionState?.accountPending,\n ]);\n useEffect(() => {\n if (!session || sessionState?.info) current?.runtime.refreshPermissions();\n }, [current, session, sessionState?.info]);\n useEffect(() => {\n if (!current || !session || !authenticated || !accountFlows) return;\n // Verified sign-in completes anonymous forms, including a same-user reauthentication.\n for (const page of current.spec.pages.filter((page) => isAccountRoute(page.path)))\n void current.runtime.forPage(page.path).dispatch([\n { action: \"SetState\", params: { path: \"accountDirty\", value: false } },\n { action: \"SetState\", params: { path: \"accountPending\", value: false } },\n ]);\n }, [current, session, authenticated, accountFlows]);\n const statusLabels: Record<LinkedSpecStatus, string> = {\n loading: \"Connecting\",\n synced: \"Connected\",\n offline: \"Connection interrupted\",\n denied: \"Access required\",\n conflict: \"Update waiting\",\n invalid: \"Update unavailable\",\n unpublished: \"Not published\",\n };\n async function checkConnection() {\n if (!retry.current || checking) return;\n setChecking(true);\n try {\n await retry.current();\n } finally {\n setChecking(false);\n }\n }\n const retryAction = (\n <button\n type=\"button\"\n className=\"linked-app-retry\"\n disabled={checking}\n onClick={() => void checkConnection()}\n >\n {checking ? \"Checking…\" : \"Retry connection\"}\n </button>\n );\n const pages = useMemo<AppRoutePage[]>(\n () =>\n visible\n ? [\n ...visible.spec.pages\n .filter(\n (page) =>\n authenticated ||\n (accountFlows ? isAccountRoute(page.path) : page.path.startsWith(\"/sign-in\")),\n )\n .map((page) => ({\n path: page.path,\n title: page.title ?? page.id,\n format: \"Spec\" as const,\n })),\n ...(authenticated ? visible.document.tsx : []).map((page) => ({\n path: page.path,\n title: page.title,\n format: \"TSX\" as const,\n })),\n ]\n : [],\n [visible, authenticated, accountFlows],\n );\n const selectPage = (path: string) => {\n navigation.navigate(path);\n if (window.matchMedia(\"(max-width: 640px)\").matches) {\n setNavigatorOpen(false);\n navigatorToggle.current?.focus();\n }\n };\n useEffect(() => {\n const click = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey ||\n !(event.target instanceof Element)\n )\n return;\n const anchor = event.target.closest<HTMLAnchorElement>(\"a[href]\");\n if (\n !anchor ||\n !canvas.current?.contains(anchor) ||\n anchor.hasAttribute(\"download\") ||\n (anchor.target && anchor.target !== \"_self\")\n )\n return;\n const url = new URL(anchor.href);\n if (pages.some((page) => page.path === url.pathname) && navigation.navigate(url.href))\n event.preventDefault();\n };\n document.addEventListener(\"click\", click);\n return () => document.removeEventListener(\"click\", click);\n }, [navigation, pages]);\n visible?.runtime.activatePage(displayRoute);\n const selectedPage = visible?.spec.pages.find((page) => page.path === displayRoute);\n const hasFrame = selectedPage?.rootBlockIds.some(\n (id) => visible?.spec.blocks[id]?.type === \"PageLayout\",\n );\n const renderSpecPage = (path: string) =>\n visible && (\n <UIBotAppHost\n key={\n path === \"/otp\"\n ? `${path}:${accountFlowKey(sessionState?.accountFlow ?? null)}`\n : \"business\"\n }\n spec={visible.spec}\n registry={registry}\n adapter={visible.runtime.forPage(path)}\n pagePath={path}\n fallback={(resolution) => <p role=\"alert\">{resolution.status}</p>}\n />\n );\n // Keep anonymous form DOM in memory across routes; credentials never enter Spec state.\n const specPreview =\n visible && accountFlows && !authenticated\n ? visible.spec.pages\n .filter((page) => isAccountRoute(page.path))\n .map((page) => (\n <div key={page.path} hidden={page.path !== displayRoute}>\n {renderSpecPage(page.path)}\n </div>\n ))\n : renderSpecPage(displayRoute);\n return (\n <main className=\"linked-app\">\n <header className=\"linked-app-bar\">\n <button\n type=\"button\"\n className=\"linked-app-navigator-toggle\"\n ref={navigatorToggle}\n aria-label={navigatorOpen ? \"Hide page navigator\" : \"Show page navigator\"}\n title={navigatorOpen ? \"Hide page navigator\" : \"Show page navigator\"}\n aria-expanded={navigatorOpen}\n aria-controls=\"app-page-navigator\"\n onClick={() => setNavigatorOpen((open) => !open)}\n >\n <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M9 4v16\" />\n <path d={navigatorOpen ? \"m6 10-2 2 2 2\" : \"m5 10 2 2-2 2\"} />\n </svg>\n </button>\n <div className=\"linked-app-brand\">\n <span className=\"linked-app-mark\" aria-hidden=\"true\">\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\" fill=\"none\">\n <path d=\"m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3Z\" />\n <path d=\"m4 7.5 8 4.5 8-4.5M12 12v9M8 5.25l8 4.5\" />\n </svg>\n </span>\n <div className=\"linked-app-identity\">\n <h1 title={visible?.document.title}>\n {visible?.document.title ?? \"Application preview\"}\n </h1>\n <span>\n {channel === \"production\" ? \"Published application\" : \"Development preview\"}\n {dataEnvironment === \"mock\" ? \" · 演示数据\" : \"\"}\n </span>\n </div>\n </div>\n <div className=\"linked-app-actions\">\n {session && sessionState?.info && (\n <div className=\"linked-app-account\">\n <span title={sessionState.info.user.email}>{sessionState.info.user.email}</span>\n <small>{sessionState.info.user.role === \"admin\" ? \"Administrator\" : \"Member\"}</small>\n <button\n className=\"linked-app-retry\"\n type=\"button\"\n disabled={signingOut}\n onClick={() => {\n if (\n activeRuntime.current?.pendingPages().length &&\n !window.confirm(\"Sign out and discard your unsaved work?\")\n )\n return;\n setSigningOut(true);\n void session.logout().finally(() => setSigningOut(false));\n }}\n >\n {signingOut ? \"Signing out…\" : \"Sign out\"}\n </button>\n </div>\n )}\n <div className=\"linked-app-connection\" role=\"status\" aria-live=\"polite\">\n <span className=\"linked-app-status\" data-status={status}>\n <span aria-hidden=\"true\" />\n {statusLabels[status]}\n </span>\n <span className=\"linked-app-revision\">\n {visible?.release\n ? `Release ${visible.release} · ${visible.revisionId.slice(0, 8)}`\n : visible\n ? `Revision ${visible.revision}`\n : channel === \"production\"\n ? \"No release loaded\"\n : \"No revision loaded\"}\n </span>\n </div>\n <button\n type=\"button\"\n className=\"linked-app-details-toggle\"\n aria-expanded={detailsOpen}\n aria-controls=\"preview-details\"\n onClick={() => setDetailsOpen((open) => !open)}\n >\n <svg aria-hidden=\"true\" viewBox=\"0 0 20 20\" fill=\"none\">\n <circle cx=\"10\" cy=\"10\" r=\"7\" />\n <path d=\"M10 9v4m0-7v.2\" />\n </svg>\n <span>Preview details</span>\n </button>\n </div>\n </header>\n {visible && (\n <div className=\"linked-app-data-notice\" role=\"status\">\n {dataEnvironment === \"mock\"\n ? \"Demo data · Changes are saved only in this browser tab.\"\n : session && !authenticated\n ? \"Sign in to access your workspace. Business records are scoped to your account.\"\n : \"Connected workspace · The host authorizes each request. Credentials stay on the server.\"}\n </div>\n )}\n <section id=\"preview-details\" className=\"linked-app-details\" hidden={!detailsOpen}>\n <div>\n <h2>\n {channel === \"production\" ? \"Production release channel\" : \"Development environment\"}\n </h2>\n <p>\n {channel === \"production\"\n ? \"Only explicit releases update this application. There is no development fallback.\"\n : \"Saved changes sync here automatically.\"}\n {dataEnvironment !== \"mock\" &&\n \" Data requests use the host's explicit authorization policy. No mock fallback is available.\"}\n </p>\n </div>\n <button type=\"button\" onClick={() => setCounter((n) => n + 1)}>\n Local TSX counter: {counter}\n </button>\n </section>\n {sessionState?.error && (\n <div className=\"linked-app-notice\" role=\"alert\">\n {sessionState.error}\n </div>\n )}\n {sessionState?.info && !sessionState.info.canBatch && (\n <div className=\"linked-app-notice\" role=\"status\">\n Signed in as a member. Your records and settings are private; the business directory and\n batch actions require an application administrator.\n </div>\n )}\n {visible && status === \"conflict\" && (\n <div className=\"linked-app-notice\" role=\"status\">\n <p>\n An application update is waiting. Save or close your pending forms first. Your current\n work is preserved; the update will apply automatically when ready.\n </p>\n {visible.runtime.pendingPages().map((page) => (\n <button\n type=\"button\"\n className=\"linked-app-retry\"\n key={page.path}\n onClick={() => selectPage(page.path)}\n >\n Review {page.title}\n </button>\n ))}\n </div>\n )}\n {visible && (status === \"offline\" || status === \"invalid\") && (\n <div className=\"linked-app-notice\" role=\"status\">\n <p>\n {status === \"offline\"\n ? \"Connection interrupted. You can keep viewing the last loaded version.\"\n : \"The latest version could not be loaded. The last working version is still displayed.\"}\n </p>\n {status === \"invalid\" && problem && <p>{problem}</p>}\n {retryAction}\n </div>\n )}\n <div className=\"linked-app-body\" data-navigator-open={navigatorOpen}>\n <AppPageNavigator\n open={navigatorOpen}\n pages={pages}\n route={route}\n onSelect={selectPage}\n onClose={() => {\n setNavigatorOpen(false);\n navigatorToggle.current?.focus();\n }}\n />\n <section className=\"linked-app-canvas\" aria-label=\"Application preview\" ref={canvas}>\n {visible?.dataReadiness.some((entry) => entry.state === \"unbound\") && (\n <div className=\"linked-app-notice\" role=\"status\" data-uibot-data-state=\"unbound\">\n 数据未连接。请为当前环境配置数据连接。\n </div>\n )}\n {visible && status !== \"denied\" && (\n <>\n <style>{visible.document.css}</style>\n {authenticated && visible.document.tsx.some((page) => page.path === route) ? (\n <ScrollArea\n style={{ height: \"100%\" }}\n viewportProps={{ \"aria-label\": \"Page content\" }}\n >\n <div className=\"linked-app-module\">\n <InstalledPage\n id={visible.document.tsx.find((page) => page.path === route)?.id}\n />\n </div>\n </ScrollArea>\n ) : hasFrame ? (\n specPreview\n ) : (\n <ScrollArea\n style={{ height: \"100%\" }}\n viewportProps={{ \"aria-label\": \"Page content\" }}\n >\n {specPreview}\n </ScrollArea>\n )}\n </>\n )}\n {!visible && (\n <ScrollArea style={{ height: \"100%\" }}>\n <div className=\"linked-app-empty\" role=\"status\">\n <span className=\"linked-app-empty-mark\" aria-hidden=\"true\">\n ◇\n </span>\n <h2>\n {status === \"denied\"\n ? \"Application access unavailable\"\n : status === \"unpublished\"\n ? \"Application not published yet\"\n : status === \"offline\"\n ? \"Cannot connect to this application\"\n : status === \"invalid\"\n ? \"This version could not be loaded\"\n : \"Connecting your application\"}\n </h2>\n <p>\n {status === \"denied\"\n ? \"Check your workspace access, then reload this page.\"\n : status === \"unpublished\"\n ? \"Publish a saved revision in NowUI to make it available here.\"\n : status === \"offline\"\n ? \"Check the application service connection, then try again.\"\n : status === \"invalid\"\n ? \"The saved version needs a compatibility check. Open NowUI to review it before trying again.\"\n : \"Your saved application will appear here when the connection is ready.\"}\n </p>\n {[\"denied\", \"offline\", \"invalid\"].includes(status) && retryAction}\n </div>\n </ScrollArea>\n )}\n </section>\n </div>\n </main>\n );\n}\nconst root = document.getElementById(\"root\");\nfunction SessionConsumer({\n client,\n ...props\n}: Parameters<typeof Consumer>[0] & { client: AppSessionClient }) {\n const state = useSyncExternalStore(client.subscribe, client.snapshot);\n const returnPath = useRef(\n isAccountRoute(window.location.pathname) ? \"/tasks\" : window.location.pathname,\n );\n useEffect(() => {\n void client.load();\n const interval = window.setInterval(() => void client.load(), 30000);\n const focus = () => void client.load();\n window.addEventListener(\"focus\", focus);\n return () => {\n clearInterval(interval);\n window.removeEventListener(\"focus\", focus);\n };\n }, [client]);\n return state.ready ? (\n <Consumer\n key={state.lastUserId ?? \"anonymous\"}\n {...props}\n session={client}\n dataSession={client}\n sessionState={state}\n returnPath={returnPath.current}\n />\n ) : (\n <main className=\"linked-app-empty\" role=\"status\">\n Checking your session…\n </main>\n );\n}\nfunction DataSessionConsumer({\n client,\n ...props\n}: Parameters<typeof Consumer>[0] & { client: AppSessionClient }) {\n const state = useSyncExternalStore(client.subscribe, client.snapshot);\n useEffect(() => {\n void client.load();\n }, [client]);\n return state.ready ? (\n <Consumer {...props} dataSession={client} />\n ) : (\n <main role=\"status\">Preparing data session…</main>\n );\n}\nif (!root) throw Error(\"No root\");\nvoid Promise.all([\n fetch(\"/linked-app-config.json\").then(async (response) => {\n if (!response.ok) throw Error(\"Configure UIBOT_LINKED_APP_URL\");\n const config = (await response.json()) as LinkedSpecIdentity & {\n channel?: string;\n dataEnvironment?: string;\n intervalMs?: number;\n sessions?: boolean;\n accountFlows?: boolean;\n };\n if (config.channel !== undefined && ![\"development\", \"production\"].includes(config.channel))\n throw Error(\"Invalid application channel\");\n if (\n config.intervalMs !== undefined &&\n (!Number.isSafeInteger(config.intervalMs) ||\n config.intervalMs < 250 ||\n config.intervalMs > 60000)\n )\n throw Error(\"Invalid polling interval\");\n if (config.sessions !== undefined && typeof config.sessions !== \"boolean\")\n throw Error(\"Invalid session configuration\");\n if (\n config.accountFlows !== undefined &&\n (typeof config.accountFlows !== \"boolean\" || (config.accountFlows && !config.sessions))\n )\n throw Error(\"Account flows require per-user sessions\");\n if (\n config.dataEnvironment !== undefined &&\n !/^[a-z][a-z0-9-]{0,31}$/.test(config.dataEnvironment)\n )\n throw Error(\"Invalid data environment\");\n if (\n config.channel === \"production\" &&\n (!config.dataEnvironment || config.dataEnvironment === \"mock\")\n )\n throw Error(\"Production data requires a real environment\");\n return {\n dataEnvironment: config.dataEnvironment ?? \"mock\",\n identity: { projectId: config.projectId, artifactId: config.artifactId },\n channel: (config.channel ?? \"development\") as \"development\" | \"production\",\n intervalMs: config.intervalMs ?? 1000,\n sessions: config.sessions === true,\n accountFlows: config.accountFlows === true && config.sessions === true,\n };\n }),\n installedModuleHashes(),\n])\n .then(([config, installedModules]) => {\n const props = {\n identity: config.identity,\n channel: config.channel,\n dataEnvironment: config.dataEnvironment,\n intervalMs: config.intervalMs,\n accountFlows: config.accountFlows,\n installedModules,\n };\n createRoot(root).render(\n config.sessions ? (\n <SessionConsumer {...props} client={createAppSessionClient(window.location.origin)} />\n ) : config.dataEnvironment !== \"mock\" ? (\n <DataSessionConsumer {...props} client={createAppSessionClient(window.location.origin)} />\n ) : (\n <Consumer {...props} />\n ),\n );\n })\n .catch(() =>\n createRoot(root).render(\n <main className=\"linked-app\">\n <div className=\"linked-app-empty\" role=\"alert\">\n <h2>Application connection unavailable</h2>\n <p>Check the server connection settings, then reload this page.</p>\n <button\n className=\"linked-app-retry\"\n type=\"button\"\n onClick={() => window.location.reload()}\n >\n Reload application\n </button>\n </div>\n </main>,\n ),\n );\n","src/app-modules.ts":"import type { ComponentType } from \"react\";\n\nconst pages = import.meta.glob<ComponentType>(\"./uibot-modules/*.tsx\", {\n eager: true,\n import: \"default\",\n});\nconst sources = import.meta.glob<string>(\"./uibot-modules/*.tsx\", {\n eager: true,\n query: \"?raw\",\n import: \"default\",\n});\nconst idOf = (file: string) => file.slice(file.lastIndexOf(\"/\") + 1, -\".tsx\".length);\n\n/** TSX pages built into this host, keyed by application module ID (`uibot app pull` writes them). */\nexport const installedPages: Readonly<Record<string, ComponentType>> = Object.fromEntries(\n Object.entries(pages).map(([file, page]) => [idOf(file), page]),\n);\n\n/** Hashes of the built sources; a revision whose module differs needs a host build. */\nexport async function installedModuleHashes(): Promise<Record<string, { sourceHash: string }>> {\n const result: Record<string, { sourceHash: string }> = {};\n for (const [file, source] of Object.entries(sources)) {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(source));\n result[idOf(file)] = {\n sourceHash: Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\"),\n };\n }\n return result;\n}\n","src/app-page-navigator.tsx":"import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { ScrollArea } from \"@uibot/blocks-shadcn\";\nimport { appRouteTree, type AppRouteNode, type AppRoutePage } from \"./app-route-tree\";\n\nexport function AppPageNavigator({\n open,\n pages,\n route,\n onSelect,\n onClose,\n}: {\n open: boolean;\n pages: AppRoutePage[];\n route: string;\n onSelect: (path: string) => void;\n onClose: () => void;\n}) {\n const [query, setQuery] = useState(\"\");\n const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());\n const current = useRef<HTMLButtonElement>(null);\n const panel = useRef<HTMLElement>(null);\n const nodes = useMemo(() => appRouteTree(pages, query), [pages, query]);\n useEffect(() => {\n if (!open) return;\n setCollapsed(\n (previous) => new Set([...previous].filter((path) => !route.startsWith(`${path}/`))),\n );\n const frame = requestAnimationFrame(() =>\n current.current?.scrollIntoView({ block: \"nearest\" }),\n );\n return () => cancelAnimationFrame(frame);\n }, [route, open]);\n useEffect(() => {\n const closeOnEscape = (event: KeyboardEvent) => {\n if (\n event.key === \"Escape\" &&\n event.target instanceof Node &&\n panel.current?.contains(event.target)\n ) {\n event.preventDefault();\n event.stopPropagation();\n onClose();\n }\n };\n document.addEventListener(\"keydown\", closeOnEscape);\n return () => document.removeEventListener(\"keydown\", closeOnEscape);\n }, [onClose]);\n const toggle = (path: string) =>\n setCollapsed((previous) => {\n const next = new Set(previous);\n if (next.has(path)) next.delete(path);\n else next.add(path);\n return next;\n });\n function renderNodes(items: AppRouteNode[]) {\n return items.map((node) => {\n const branch = node.children.length > 0;\n const expanded = Boolean(query.trim()) || !collapsed.has(node.path);\n const selected = node.page?.path === route;\n return (\n <li key={node.path}>\n <div className=\"app-route-row\" data-selected={selected}>\n {branch ? (\n <button\n type=\"button\"\n className=\"app-route-disclosure\"\n aria-label={`${expanded ? \"Collapse\" : \"Expand\"} ${node.path}`}\n aria-expanded={expanded}\n onClick={() => toggle(node.path)}\n disabled={Boolean(query.trim())}\n >\n <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" data-expanded={expanded}>\n <path d=\"m6 4 4 4-4 4\" />\n </svg>\n </button>\n ) : (\n <span className=\"app-route-spacer\" />\n )}\n <button\n type=\"button\"\n className=\"app-route-target\"\n ref={selected ? current : undefined}\n aria-current={selected ? \"page\" : undefined}\n aria-label={\n node.page\n ? `${node.page.title} (${node.path})`\n : `${expanded ? \"Collapse\" : \"Expand\"} folder ${node.path}`\n }\n aria-expanded={!node.page && branch ? expanded : undefined}\n disabled={!node.page && Boolean(query.trim())}\n onClick={() => (node.page ? onSelect(node.page.path) : toggle(node.path))}\n >\n <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n {branch ? (\n <path d=\"M2.5 5.5h5l2-2h3l2 2h3v11h-15Z\" />\n ) : (\n <>\n <path d=\"M5 2.5h6l4 4v11H5Z\" />\n <path d=\"M11 2.5v4h4\" />\n </>\n )}\n </svg>\n <span>\n <strong>{node.page?.title ?? node.segment}</strong>\n <small>{node.path}</small>\n </span>\n {node.page && <em>{node.page.format}</em>}\n </button>\n </div>\n {branch && expanded && <ul>{renderNodes(node.children)}</ul>}\n </li>\n );\n });\n }\n return (\n <aside\n hidden={!open}\n ref={panel}\n className=\"app-page-navigator\"\n id=\"app-page-navigator\"\n aria-label=\"Page navigator\"\n >\n <div className=\"app-page-navigator-heading\">\n <h2>Pages</h2>\n <span>{pages.length}</span>\n </div>\n <label className=\"app-route-search\">\n <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n <circle cx=\"8.5\" cy=\"8.5\" r=\"5.5\" />\n <path d=\"m13 13 4 4\" />\n </svg>\n <input\n aria-label=\"Search pages or routes\"\n placeholder=\"Search pages or routes…\"\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n />\n {query && (\n <button type=\"button\" aria-label=\"Clear page search\" onClick={() => setQuery(\"\")}>\n ×\n </button>\n )}\n </label>\n <ScrollArea className=\"app-route-tree\" viewportProps={{ \"aria-label\": \"Application pages\" }}>\n <nav aria-label=\"Application pages\">\n <ul>{renderNodes(nodes)}</ul>\n {!nodes.length && (\n <p className=\"app-route-empty\">No matching pages. Try another name or route.</p>\n )}\n </nav>\n </ScrollArea>\n <p className=\"app-page-navigator-footer\">Select a page to preview</p>\n </aside>\n );\n}\n","src/app-route-tree.ts":"export interface AppRoutePage {\n path: string;\n title: string;\n format: \"Spec\" | \"TSX\";\n}\nexport interface AppRouteNode {\n path: string;\n segment: string;\n page?: AppRoutePage;\n children: AppRouteNode[];\n}\n\n/** Group only by full path segments; titles never establish route ancestry. */\nexport function appRouteTree(pages: AppRoutePage[], query = \"\"): AppRouteNode[] {\n const roots: AppRouteNode[] = [];\n const index = new Map<string, AppRouteNode>();\n const search = query.trim().toLowerCase();\n for (const page of pages) {\n if (!`${page.title} ${page.path} ${page.format}`.toLowerCase().includes(search)) continue;\n let siblings = roots;\n let path = \"\";\n const segments = page.path === \"/\" ? [\"\"] : page.path.slice(1).split(\"/\");\n for (const [position, segment] of segments.entries()) {\n path += `/${segment}`;\n let node = index.get(path);\n if (!node) {\n node = { path, segment: segment || \"/\", children: [] };\n index.set(path, node);\n siblings.push(node);\n }\n if (position === segments.length - 1) node.page = page;\n siblings = node.children;\n }\n }\n return roots;\n}\n","src/app-navigation.ts":"/** The consumer owns browser history; runtime and installed modules share this route. */\nexport function createAppNavigation(port: {\n readUrl: () => string;\n writeUrl: (url: string, replace: boolean) => void;\n onRoute: (path: string) => void;\n}) {\n return {\n navigate(destination: string, replace = false): boolean {\n let url: URL;\n const current = new URL(port.readUrl());\n try {\n url = new URL(destination, current);\n } catch {\n return false;\n }\n if (url.origin !== current.origin || ![\"http:\", \"https:\"].includes(url.protocol))\n return false;\n if (url.href !== current.href) port.writeUrl(url.pathname + url.search + url.hash, replace);\n port.onRoute(url.pathname);\n return true;\n },\n };\n}\n","src/admin-navigation.ts":"type NavigationPorts = {\n index: number;\n isDirty(): boolean;\n push(url: string, index: number): void;\n go(delta: number): void;\n commit(url: string): void;\n prompt(decide: (discard: boolean) => void): void;\n};\n\ntype Pending =\n | { kind: \"link\"; url: string }\n | { kind: \"pop\"; delta: number; phase: \"restore\" | \"prompt\" | \"travel\" };\n\nexport function createAdminNavigation(ports: NavigationPorts) {\n let index = ports.index;\n let pending: Pending | undefined;\n function ask() {\n const request = pending;\n ports.prompt((discard) => {\n if (!request || pending !== request) return;\n if (!discard) {\n pending = undefined;\n } else if (request.kind === \"link\") {\n pending = undefined;\n ports.push(request.url, ++index);\n ports.commit(request.url);\n } else {\n request.phase = \"travel\";\n ports.go(request.delta);\n }\n });\n }\n return {\n link(url: string) {\n if (pending) return;\n if (ports.isDirty()) {\n pending = { kind: \"link\", url };\n ask();\n } else {\n ports.push(url, ++index);\n ports.commit(url);\n }\n },\n pop(nextIndex: number, url: string) {\n if (pending?.kind === \"pop\") {\n if (pending.phase === \"travel\") {\n pending = undefined;\n index = nextIndex;\n ports.commit(url);\n } else if (nextIndex !== index) {\n ports.go(index - nextIndex);\n } else if (pending.phase === \"restore\") {\n pending.phase = \"prompt\";\n ask();\n }\n return;\n }\n if (nextIndex !== index && (pending || ports.isDirty())) {\n pending = { kind: \"pop\", delta: nextIndex - index, phase: \"restore\" };\n ports.go(index - nextIndex);\n } else if (!pending) {\n index = nextIndex;\n ports.commit(url);\n }\n },\n };\n}\n\nfunction fingerprint(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(fingerprint).join(\",\")}]`;\n if (value && typeof value === \"object\")\n return `{${Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => `${JSON.stringify(key)}:${fingerprint(item)}`)\n .join(\",\")}}`;\n return JSON.stringify(value) ?? \"null\";\n}\n\nexport function createFormDirtyTracker(initial: Record<string, unknown>) {\n // Request clears loading before its onSuccess assigns form from preferences.\n const loadedForm = (state: Record<string, unknown>) => {\n const record = Array.isArray(state.preferences) ? state.preferences[0] : undefined;\n return record?.values ?? state.form;\n };\n let baseline = fingerprint(loadedForm(initial));\n let dirty = false;\n let initialRead = false;\n let initialReadFinished = false;\n let wasSaved = initial.saved === true;\n let successfulSave = false;\n let reloaded = initial.settingsReloaded;\n return {\n update(state: Record<string, unknown>) {\n const current = fingerprint(state.form);\n if (state.settingsReloaded !== reloaded) {\n reloaded = state.settingsReloaded;\n if (!state.uiError && !state.loading && !state.saving) baseline = current;\n }\n if (!initialReadFinished && state.loading && !state.saving && !dirty) initialRead = true;\n if (initialRead && !state.loading) {\n initialRead = false;\n initialReadFinished = true;\n if (!state.uiError) baseline = fingerprint(loadedForm(state));\n }\n if (state.saved === true && !wasSaved) successfulSave = true;\n if (state.saved !== true || state.uiError) successfulSave = false;\n if (successfulSave && !state.loading && !state.saving) {\n baseline = current;\n successfulSave = false;\n }\n wasSaved = state.saved === true;\n dirty = initialRead ? false : current !== baseline;\n return dirty;\n },\n };\n}\n\nexport function protectUnsavedUnload(\n event: { preventDefault(): void; returnValue: string },\n dirty: boolean,\n) {\n if (!dirty) return;\n event.preventDefault();\n event.returnValue = \"\";\n}\n\nexport function hasUnsavedAdminEditor(state: Record<string, unknown>): boolean {\n const computed = state.__computed as Record<string, unknown> | undefined;\n return state.editorOpen === true && computed?.editorDirty === true;\n}\n","src/app-runtime.ts":"import {\n ConnectionRequestError,\n type CompiledUIBotSpec,\n type ConnectionDriver,\n type LinkedSpecIdentity,\n type UIBotSpec,\n} from \"@uibot/contracts\";\nimport { createMockCollectionConnectionDriver } from \"@uibot/connection-mock/browser\";\nimport {\n createLiveRuntimeAdapter,\n bindUrlState,\n type UIBotAppRuntimeAdapter,\n type UrlStateIO,\n} from \"@uibot/runtime\";\nimport { createEngine } from \"@uibot/engine\";\nimport { bindAppSessionSource } from \"./app-session-source\";\nimport { registerAppSessionAction, type AppSessionAction } from \"./app-session-action\";\nimport type { AppFeatures } from \"./app-feature-contract\";\n\n/** Detached host assembly; neither the adopted server revision nor its bindings are rewritten. */\nexport function prepareLinkedAppSource(\n source: UIBotSpec,\n options: { sessions?: boolean; accountFlows?: boolean; features?: AppFeatures } = {},\n): UIBotSpec {\n const detached = structuredClone(source);\n const prepared = options.features?.prepareSource?.(detached) ?? detached;\n if (options.sessions) bindAppSessionSource(prepared, options.accountFlows);\n return prepared;\n}\nexport function createLinkedAppRuntime(options: {\n spec: CompiledUIBotSpec;\n source: UIBotSpec;\n identity: LinkedSpecIdentity;\n channel?: \"development\" | \"production\";\n dataEnvironment?: string;\n dataDriver?: ConnectionDriver;\n sessionAction?: AppSessionAction;\n features?: AppFeatures;\n storage: Pick<Storage, \"getItem\" | \"setItem\">;\n urlState?: UrlStateIO;\n navigate(destination: string): void;\n}) {\n const environment = options.dataEnvironment ?? \"mock\";\n if (options.channel === \"production\" && environment === \"mock\")\n throw Error(\"Production data requires a real environment\");\n const driver =\n environment === \"mock\"\n ? createMockCollectionConnectionDriver(options.source, {\n storage: options.storage,\n storageKey: `uibot.linked-app.data.v1:${encodeURIComponent(options.identity.projectId)}:${encodeURIComponent(options.identity.artifactId)}`,\n })\n : (options.dataDriver ?? {\n type: \"Collection\" as const,\n async execute() {\n throw new ConnectionRequestError({\n code: \"unbound\",\n message: \"Data connection is not connected\",\n });\n },\n });\n const pages = new Map<string, UIBotAppRuntimeAdapter>();\n let disposed = false;\n let activePage = \"\";\n const urlState = options.urlState;\n const publishUrl = new Map<string, () => void>();\n const urlStops: (() => void)[] = [];\n return {\n refreshPermissions() {\n options.features?.refreshPermissions?.();\n },\n pendingPages() {\n if (disposed) return [];\n return options.spec.pages\n .filter((page) => {\n const adapter = pages.get(page.id),\n state = adapter?.snapshot();\n const computed = state?.__computed as Record<string, unknown> | undefined;\n return (\n adapter &&\n state &&\n ((state.editorOpen === true && computed?.editorDirty === true) ||\n state.saving === true ||\n state.accountDirty === true ||\n state.accountPending === true ||\n options.features?.isPending?.(adapter, page.id))\n );\n })\n .map((page) => ({ path: page.path, title: page.title ?? page.id }));\n },\n activatePage(path: string) {\n const key = options.spec.pages.find((page) => page.path === path)?.id ?? \"\";\n if (disposed || activePage === key) return;\n activePage = key;\n publishUrl.get(key)?.();\n },\n forPage(path: string) {\n if (disposed) throw Error(\"Application runtime disposed\");\n const page = options.spec.pages.find((item) => item.path === path) ?? options.spec.pages[0];\n const key = page?.id ?? \"\";\n let adapter = pages.get(key);\n if (!adapter) {\n const engine = createEngine(page?.state ?? {});\n if (options.sessionAction) registerAppSessionAction(engine, options.sessionAction);\n adapter = createLiveRuntimeAdapter({\n engine,\n spec: {\n ...options.spec,\n pages: page\n ? [\n page,\n ...options.spec.pages\n .filter((item) => item.id !== key)\n .map(({ urlState: _inactive, ...item }) => item),\n ]\n : [],\n },\n drivers: [driver],\n navigate: ({ destination }) => options.navigate(destination),\n });\n if (page?.urlState && urlState) {\n let initialized = false;\n publishUrl.set(key, () => {\n if (!initialized) {\n initialized = true;\n urlStops.push(\n bindUrlState(engine.store, page.urlState ?? {}, {\n read: () => (activePage === key ? urlState.read() : new URLSearchParams()),\n write: (params, mode) => {\n if (!disposed && activePage === key) urlState.write(params, mode);\n },\n }),\n );\n } else\n engine.store.batch(() => {\n for (const statePath of Object.keys(page.urlState ?? {}))\n engine.store.set(statePath, engine.store.get(statePath), { notify: \"always\" });\n });\n });\n if (activePage === key) publishUrl.get(key)?.();\n }\n pages.set(key, adapter);\n if (page) options.features?.attachPage?.(adapter, page);\n }\n return adapter;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n options.features?.dispose?.();\n for (const stop of urlStops.splice(0)) stop();\n for (const adapter of pages.values()) adapter.dispose();\n pages.clear();\n publishUrl.clear();\n },\n };\n}\n","src/app-session-source.ts":"import type {\n ActionChain,\n BlockNode,\n CompiledUIBotSpec,\n UIBotSpec,\n PropValue,\n} from \"@uibot/contracts\";\nimport { bindAccountPage } from \"./app-account-source\";\n\n/** Host wiring changes only the compiled copy of the authored authentication pages. */\nexport function bindAppSessionSource(spec: UIBotSpec, accountFlows = false) {\n if (!spec.pages.some((page) => page.path === \"/sign-in\"))\n throw Error(\"Session host requires the Admin sign-in page.\");\n for (const page of spec.pages) {\n if ([\"/sign-up\", \"/forgot-password\", \"/otp\"].includes(page.path)) {\n if (accountFlows) {\n bindAccountPage(page);\n continue;\n }\n const copy: Record<string, string> = {\n \"Enter your email and password to create an account.\":\n \"Accounts are provisioned by your workspace administrator.\",\n \"Enter your registered email and we will send you a reset link.\":\n \"Password recovery is managed by your workspace administrator.\",\n \"Please enter the authentication code sent to your email.\":\n \"Two-factor verification requires a connected authentication provider.\",\n \"By continuing, you agree to our Terms of Service and Privacy Policy.\":\n \"This page does not create an account, send email or verify a code.\",\n };\n const disable = (blocks: BlockNode[]) => {\n for (const block of blocks) {\n if (typeof block.props?.text === \"string\" && copy[block.props.text])\n block.props = { ...block.props, text: copy[block.props.text] ?? \"\" };\n if (block.type === \"Form\") {\n block.events = { ...block.events };\n delete block.events.onSubmit;\n block.props = { ...block.props, pending: false };\n block.children = [\n {\n type: \"Paragraph\",\n props: {\n text: \"This account service is not connected. Contact your workspace administrator.\",\n muted: true,\n size: \"sm\",\n },\n },\n ...(block.children ?? []),\n ];\n }\n if ([\"Field\", \"Form.Submit\", \"Button\"].includes(block.type))\n block.props = { ...block.props, disabled: true };\n disable(block.children ?? []);\n for (const children of Object.values(block.slots ?? {})) disable(children);\n }\n };\n disable(page.blocks);\n continue;\n }\n if (![\"/sign-in\", \"/sign-in-2\"].includes(page.path)) continue;\n page.state = { ...page.state, uiError: null };\n const submit: ActionChain = [\n {\n action: \"HostSession\",\n params: {\n operation: \"Login\",\n data: { _event: \"values\" },\n loadingPath: \"saving\",\n errorPath: \"uiError\",\n },\n ...(accountFlows\n ? {\n onSuccess: [\n { action: \"SetState\" as const, params: { path: \"accountDirty\", value: false } },\n ],\n }\n : {}),\n },\n ];\n let forms = 0;\n const visit = (blocks: BlockNode[]) => {\n for (const block of blocks) {\n if (block.type === \"Form\") {\n forms++;\n block.events = { ...block.events, onSubmit: submit };\n if (accountFlows)\n block.events.onChange = [\n { action: \"SetState\", params: { path: \"accountDirty\", value: true } },\n ];\n block.children = [\n ...(block.children ?? []),\n {\n type: \"Paragraph\",\n props: { text: { _state: \"uiError.message\" }, className: \"text-destructive text-sm\" },\n },\n ...(accountFlows\n ? [\n {\n type: \"Link\",\n props: {\n label: \"Sign in with an email code\",\n href: \"/otp\",\n className: \"text-sm\",\n },\n },\n ]\n : []),\n ];\n }\n if (block.type === \"Form.Submit\")\n block.props = { ...block.props, disabled: { _state: \"saving\" } };\n if (\n block.type === \"Paragraph\" &&\n block.props?.text === \"Connect an authentication provider to continue.\"\n )\n block.props = {\n ...block.props,\n text: \"Sign in to your connected workspace. Your account controls access to business records.\",\n };\n if (\n block.type === \"Link\" &&\n !accountFlows &&\n [\"/forgot-password\", \"/sign-up\"].includes(String(block.props?.href))\n ) {\n const recovery = block.props?.href === \"/forgot-password\";\n block.type = \"Paragraph\";\n block.props = {\n text: recovery\n ? \"Password recovery: contact your workspace administrator.\"\n : \"Accounts are provisioned by your workspace administrator.\",\n muted: true,\n size: \"sm\",\n };\n }\n if (\n block.type === \"Paragraph\" &&\n String(block.props?.text).startsWith(\"By continuing, you agree\")\n )\n block.props = {\n ...block.props,\n text: \"Credentials are sent only through this host to the connected identity service.\",\n };\n visit(block.children ?? []);\n for (const children of Object.values(block.slots ?? {})) visit(children);\n }\n };\n visit(page.blocks);\n if (!forms) throw Error(\"Session host requires the Admin login form.\");\n }\n return spec;\n}\n\n/** The host account replaces sample identity only in the compiled native shell. */\nexport function bindCompiledSessionIdentity(\n spec: CompiledUIBotSpec,\n user?: { email: string; id?: string },\n) {\n const email = user?.email ?? \"\";\n const name = email.split(\"@\")[0] || \"Account\";\n const removeSampleBadge = (value: PropValue): PropValue => {\n if (Array.isArray(value)) return value.map(removeSampleBadge);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== \"badge\" || !(\"href\" in value) || value.href !== \"/chats\")\n .map(([key, item]) => [key, removeSampleBadge(item)]),\n );\n };\n for (const page of spec.pages) {\n page.state = { ...page.state, currentUserId: user?.id ?? \"\" };\n if (page.id === \"settings-profile\" && page.state.preferencesReady === false)\n page.state.form = { username: name, email, bio: \"\", urls: [] };\n }\n for (const block of Object.values(spec.blocks)) {\n if ([\"PageLayout\", \"AppNavigation\"].includes(block.type))\n block.props = Object.fromEntries(\n Object.entries(block.props ?? {}).map(([key, value]) => [\n key,\n [\"routes\", \"groups\"].includes(key) ? removeSampleBadge(value) : value,\n ]),\n );\n if (block.type === \"PageLayout\")\n block.props = { ...block.props, initials: name.slice(0, 2).toUpperCase() };\n if (block.type !== \"AppNavigation\") continue;\n block.props = {\n ...block.props,\n userName: name,\n email,\n initials: name.slice(0, 2).toUpperCase(),\n workspaces: [],\n };\n }\n}\n","src/app-account-source.ts":"import type { ActionChain, BlockNode, BlockTreePage } from \"@uibot/contracts\";\n\nexport const isAccountRoute = (path: string) =>\n [\"/sign-in\", \"/sign-in-2\", \"/sign-up\", \"/forgot-password\", \"/otp\"].includes(path);\nconst state = (path: string) => ({ _state: path });\nconst set = (path: string, value: boolean | string) => ({\n action: \"SetState\",\n params: { path, value },\n});\nconst digitCodeState = (available: boolean) => ({\n accountCodeKind: \"otp\",\n accountCodePlaceholder: \"000000\",\n accountCodeHint: \"Enter the 6 digits from your latest email. Keep any leading zeroes.\",\n accountUseLegacyAvailable: available,\n});\nfunction submit(operation: string, destination?: string): ActionChain {\n return [\n {\n action: \"HostSession\",\n params: {\n operation,\n data: { _event: \"values\" },\n loadingPath: \"saving\",\n errorPath: \"uiError\",\n },\n onSuccess: [\n set(\"accountDirty\", false),\n ...(destination ? [{ action: \"Link\", params: { path: destination } }] : []),\n ],\n },\n ];\n}\nconst field = (name: string, label: string, kind = \"text\"): BlockNode => ({\n type: \"Field\",\n props: {\n name,\n label,\n kind,\n required: true,\n ...(name === \"token\"\n ? {\n kind: state(\"accountCodeKind\"),\n length: 6,\n autoComplete: \"one-time-code\",\n placeholder: state(\"accountCodePlaceholder\"),\n description: state(\"accountCodeHint\"),\n }\n : {}),\n },\n});\nconst message: BlockNode = {\n type: \"Paragraph\",\n props: { text: state(\"uiError.message\"), className: \"text-destructive text-sm\" },\n};\nfunction form(\n operation: string,\n fields: BlockNode[],\n label: string,\n destination?: string,\n): BlockNode {\n return {\n type: \"Form\",\n props: { label, pending: state(\"saving\") },\n children: [\n ...fields,\n { type: \"Form.Submit\", props: { label, full: true, disabled: state(\"saving\") } },\n message,\n ],\n events: { onChange: [set(\"accountDirty\", true)], onSubmit: submit(operation, destination) },\n };\n}\n\n/** Adapt the existing authored frame; authentication state remains host-owned. */\nexport function bindAccountPage(page: BlockTreePage) {\n const otp = page.path === \"/otp\";\n page.state = {\n ...page.state,\n uiError: null,\n accountDirty: false,\n accountHasFlow: false,\n accountNoFlow: true,\n accountNeedsPassword: false,\n accountVerifyDisabled: true,\n accountRetryBlocked: true,\n accountTitle: \"Email code sign-in\",\n accountMessage: \"Enter your email to request a one-time sign-in code.\",\n accountRetryLabel: \"Resend code\",\n accountExpiryLabel: \"\",\n ...digitCodeState(false),\n };\n if (otp) page.title = \"Email verification\";\n const copy: Record<string, string> = {\n \"Enter your email and password to create an account.\":\n \"Verify your email, then choose a password to create your account.\",\n \"Enter your registered email and we will send you a reset link.\":\n \"Request a recovery code, then choose a new password. Previous sessions will be revoked.\",\n \"By continuing, you agree to our Terms of Service and Privacy Policy.\":\n \"Email verification is handled by the connected identity service. Request a code to see the delivery method.\",\n \"Connect an authentication provider to continue.\":\n \"Codes can be used once. Use the latest code and check its expiry time below.\",\n };\n const visit = (blocks: BlockNode[]) =>\n blocks.flatMap((block): BlockNode[] => {\n if (block.type === \"Form\") {\n if (!otp)\n return [\n form(\n page.path === \"/sign-up\" ? \"StartSignup\" : \"StartRecovery\",\n [field(\"email\", \"Email\", \"email\")],\n \"Send verification code\",\n \"/otp\",\n ),\n ];\n const start = form(\"StartOtp\", [field(\"email\", \"Email\", \"email\")], \"Send sign-in code\");\n start.visible = { _state: \"accountNoFlow\" };\n const verify = form(\n \"VerifyAccount\",\n [\n field(\"token\", \"Verification code\"),\n {\n ...field(\"password\", \"New password (12–128 characters)\", \"password\"),\n visible: state(\"accountNeedsPassword\"),\n },\n {\n ...field(\"confirm\", \"Confirm password\", \"password\"),\n visible: state(\"accountNeedsPassword\"),\n },\n ],\n \"Verify code\",\n \"/sign-in\",\n );\n verify.visible = state(\"accountHasFlow\");\n const button = verify.children?.find((item) => item.type === \"Form.Submit\");\n if (button) button.props = { ...button.props, disabled: state(\"accountVerifyDisabled\") };\n return [\n start,\n verify,\n {\n type: \"Paragraph\",\n visible: state(\"accountHasFlow\"),\n props: { text: state(\"accountExpiryLabel\"), size: \"sm\" },\n },\n {\n type: \"Button\",\n visible: state(\"accountUseLegacyAvailable\"),\n props: {\n label: \"Use an older email code\",\n variant: \"ghost\",\n disabled: state(\"saving\"),\n },\n events: {\n onClick: [\n set(\"accountCodeKind\", \"text\"),\n set(\"accountCodePlaceholder\", \"Complete email code\"),\n set(\n \"accountCodeHint\",\n \"Paste the complete code from an older email. Its original expiry still applies.\",\n ),\n set(\"accountUseLegacyAvailable\", false),\n ],\n },\n },\n {\n type: \"Button\",\n visible: state(\"accountHasFlow\"),\n props: {\n label: state(\"accountRetryLabel\"),\n disabled: state(\"accountRetryBlocked\"),\n variant: \"outline\",\n },\n events: { onClick: submit(\"ResendAccount\") },\n },\n {\n type: \"Paragraph\",\n visible: state(\"accountHasFlow\"),\n props: {\n text: \"Requesting a fresh code clears the current verification fields.\",\n muted: true,\n size: \"sm\",\n },\n },\n { type: \"Link\", props: { label: \"Back to sign in\", href: \"/sign-in\" } },\n ];\n }\n if (typeof block.props?.text === \"string\") {\n const text = block.props.text;\n if (\n otp &&\n [\n \"Two-factor Authentication\",\n \"Please enter the authentication code sent to your email.\",\n ].includes(text)\n )\n block.props = {\n ...block.props,\n text: state(text === \"Two-factor Authentication\" ? \"accountTitle\" : \"accountMessage\"),\n };\n else if (copy[text]) block.props = { ...block.props, text: copy[text] };\n }\n if (block.type === \"Link\" && block.props?.href === page.path)\n block.props = { ...block.props, href: \"/sign-in\", label: \"Back to sign in\" };\n if (block.children) block.children = visit(block.children);\n for (const [key, children] of Object.entries(block.slots ?? {}))\n (block.slots as Record<string, BlockNode[]>)[key] = visit(children);\n return [block];\n });\n page.blocks = visit(page.blocks);\n}\n\ntype AccountFlow = {\n purpose: string;\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n unknown: boolean;\n} | null;\n\n/** Metadata identity only; credentials stay in the form DOM, never runtime state. */\nexport function accountFlowKey(flow: AccountFlow) {\n return flow ? JSON.stringify([flow.purpose, flow.email, flow.expiresAt, flow.retryAt]) : \"new\";\n}\n\nexport function accountPageState(\n flow: AccountFlow,\n now: number,\n pending = false,\n previousFlowKey?: unknown,\n) {\n const key = accountFlowKey(flow);\n const remaining = Math.max(0, Math.ceil(((flow?.retryAt ?? 0) - now) / 1000));\n const expired = Boolean(flow && flow.expiresAt <= now);\n const seconds = Math.max(0, Math.ceil(((flow?.expiresAt ?? 0) - now) / 1000));\n return {\n accountFlowKey: key,\n ...(previousFlowKey !== key\n ? { uiError: null, accountDirty: false, ...digitCodeState(Boolean(flow)) }\n : {}),\n accountHasFlow: Boolean(flow),\n accountNoFlow: !flow,\n accountNeedsPassword: Boolean(flow && flow.purpose !== \"otp\"),\n accountPending: pending,\n accountVerifyDisabled: pending || !flow || expired || Boolean(flow.unknown),\n accountRetryBlocked: pending || remaining > 0,\n accountRetryLabel: remaining ? `Resend code in ${remaining}s` : \"Resend code\",\n accountExpiryLabel: !flow\n ? \"\"\n : expired\n ? \"Code expired. Request a new code to continue.\"\n : `Code expires in ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")} (${new Date(flow.expiresAt).toLocaleTimeString()}).`,\n accountTitle:\n flow?.purpose === \"signup\"\n ? \"Verify your email\"\n : flow?.purpose === \"recovery\"\n ? \"Reset your password\"\n : \"Email code sign-in\",\n accountMessage: !flow\n ? \"Enter your email to request a one-time sign-in code.\"\n : flow.unknown\n ? \"The previous request outcome is unknown. Try signing in, or request a fresh code after the cooldown. It will not be repeated.\"\n : expired\n ? \"This code has expired. Request a new code to continue.\"\n : `If this account is eligible, ${flow.delivery === \"smtp\" ? \"check the email sent to\" : \"use the controlled local test inbox for\"} ${flow.email}. Use the latest email for this request. ${flow.delivery === \"local_http\" ? \"External email delivery is not configured for this request.\" : \"\"}`.trim(),\n };\n}\n","src/app-session-action.ts":"import { isConnectionRequestError, type ActionDefinition } from \"@uibot/contracts\";\nimport { evaluatePropValue, makeEvalContext, type Engine } from \"@uibot/engine\";\n\nexport type AppSessionAction = (operation: string, data: Record<string, unknown>) => Promise<void>;\nexport const HOST_SESSION_ACTION: ActionDefinition = {\n name: \"HostSession\",\n description: \"Submit an explicit authentication action to the host session service\",\n params: {\n operation: { type: \"string\" },\n data: { type: \"object\" },\n loadingPath: { type: \"string\" },\n errorPath: { type: \"string\" },\n },\n generation: {\n evaluatedParams: [\"operation\", \"data\"],\n prerequisites: [\"The host registers its authenticated session action\"],\n example: {\n action: \"HostSession\",\n params: {\n operation: \"Login\",\n data: { _event: \"values\" },\n loadingPath: \"saving\",\n errorPath: \"uiError\",\n },\n },\n },\n};\n\n/** Authentication is host-owned and never passes through the data connection registry. */\nexport function registerAppSessionAction(engine: Engine, invoke: AppSessionAction): void {\n engine.runner.register(\"HostSession\", async (action, { store, scope }) => {\n const { loadingPath, errorPath } = action.params;\n if (typeof loadingPath === \"string\") store.set(loadingPath, true);\n if (typeof errorPath === \"string\") store.set(errorPath, null);\n try {\n const context = {\n ...makeEvalContext(store, engine.session),\n ...(scope.event ? { event: scope.event } : {}),\n };\n const operation = evaluatePropValue(action.params.operation, context);\n const data = evaluatePropValue(action.params.data, context);\n if (typeof operation !== \"string\" || !data || typeof data !== \"object\" || Array.isArray(data))\n throw Error(\"Invalid authentication action\");\n await invoke(operation, data as Record<string, unknown>);\n } catch (error) {\n const failure = isConnectionRequestError(error)\n ? { code: error.failure.code, message: error.failure.message.slice(0, 300) }\n : {\n code: \"transport-error\",\n message: \"The session service is unavailable. Please try signing in again.\",\n };\n if (typeof errorPath === \"string\") store.set(errorPath, failure);\n throw Error(failure.message);\n } finally {\n if (typeof loadingPath === \"string\") store.set(loadingPath, false);\n }\n });\n}\n","src/app-feature-contract.ts":"import type { BlockTreePage, UIBotSpec } from \"@uibot/contracts\";\nimport type { UIBotAppRuntimeAdapter } from \"@uibot/runtime\";\nexport interface AppFeatureOptions {\n source?: UIBotSpec;\n environment?: string;\n sessions?: boolean;\n accountFlows?: boolean;\n canBatch?: () => boolean;\n}\n/** Application-owned presentation assembly, outside the generic host/data driver. */\nexport interface AppFeatures {\n prepareSource?(source: UIBotSpec): UIBotSpec;\n attachPage?(adapter: UIBotAppRuntimeAdapter, page: Pick<BlockTreePage, \"id\" | \"path\">): void;\n refreshPermissions?(): void;\n isPending?(adapter: UIBotAppRuntimeAdapter, pageId: string): boolean;\n dispose?(): void;\n}\n","src/app-session-client.ts":"import {\n ConnectionRequestError,\n requestFailureFromStatus,\n isConnectionRequestError,\n} from \"@uibot/contracts\";\n\nexport type AppSessionInfo = {\n authenticated: true;\n user: { id: string; email: string; role: string };\n canBatch: boolean;\n accessExpiresAt: number;\n sessionExpiresAt: number;\n};\ntype State = {\n ready: boolean;\n info: AppSessionInfo | null;\n lastUserId: string | null;\n error: string;\n accountPending: boolean;\n accountFlow: {\n purpose: \"signup\" | \"recovery\" | \"otp\";\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n unknown: boolean;\n } | null;\n};\nfunction accountFailure(status: number, code: unknown) {\n if (code === \"sign-in-required\" || code === \"csrf-denied\")\n return \"This verification session has expired or changed. Request a new code to continue.\";\n if (status === 429) return \"Please wait before requesting or trying another code.\";\n if (status === 401)\n return \"The code is invalid, expired or already used. Check the latest code or request a new one.\";\n if (status === 400)\n return \"Check your email and code. New passwords must match and contain 12 to 128 characters.\";\n if (status === 409) return \"This verification is unavailable. Sign in or request a new code.\";\n if (code === \"account-delivery-unavailable\")\n return \"The delivery service is unavailable. No delivery is confirmed. Wait before requesting another code.\";\n return \"The verification outcome is unknown. Check sign-in or request a new code after the cooldown; this request will not be repeated.\";\n}\n\n/** Browser keeps only non-bearer metadata and a CSRF token, in memory. */\nexport function createAppSessionClient(origin: string, send: typeof fetch = fetch) {\n let csrf = \"\";\n let epoch = 0;\n let mutations = 0;\n let loadPending: Promise<void> | undefined;\n let logoutPending: Promise<void> | undefined;\n let state: State = {\n ready: false,\n info: null,\n lastUserId: null,\n error: \"\",\n accountFlow: null,\n accountPending: false,\n };\n const listeners = new Set<() => void>();\n const update = (change: Partial<State>) => {\n state = { ...state, ...change };\n for (const listener of listeners) listener();\n };\n async function accept(response: Response, ticket: number, account = false) {\n const data = (await response.json()) as Record<string, unknown>;\n if (ticket !== epoch) return false;\n if (!response.ok)\n throw new ConnectionRequestError(\n requestFailureFromStatus(\n response.status,\n account\n ? accountFailure(response.status, data.code)\n : response.status === 401\n ? \"Email or password was not accepted. Please sign in again.\"\n : response.status === 429\n ? \"Too many sign-in attempts. Please wait before trying again.\"\n : \"The session service could not complete this request.\",\n ),\n );\n if (typeof data.csrfToken !== \"string\" || typeof data.authenticated !== \"boolean\")\n throw Error(\"Invalid session response.\");\n csrf = data.csrfToken;\n if (data.authenticated) {\n const info = data as unknown as AppSessionInfo;\n if (\n !info.user ||\n typeof info.user.id !== \"string\" ||\n typeof info.user.email !== \"string\" ||\n typeof info.user.role !== \"string\" ||\n typeof info.canBatch !== \"boolean\"\n )\n throw Error(\"Invalid session response.\");\n update({\n ready: true,\n info: {\n authenticated: true,\n user: info.user,\n canBatch: info.canBatch,\n accessExpiresAt: info.accessExpiresAt,\n sessionExpiresAt: info.sessionExpiresAt,\n },\n lastUserId: info.user.id,\n error: \"\",\n accountFlow: null,\n });\n } else {\n const flow = data.accountFlow as State[\"accountFlow\"];\n if (\n flow &&\n (![\"signup\", \"recovery\", \"otp\"].includes(flow.purpose) ||\n ![\"local_http\", \"smtp\"].includes(flow.delivery) ||\n typeof flow.email !== \"string\" ||\n typeof flow.unknown !== \"boolean\" ||\n !Number.isFinite(flow.expiresAt) ||\n !Number.isFinite(flow.retryAt))\n )\n throw Error(\"Invalid account response.\");\n update({\n ready: true,\n info: null,\n accountFlow: flow\n ? {\n purpose: flow.purpose,\n delivery: flow.delivery,\n email: flow.email,\n expiresAt: flow.expiresAt,\n retryAt: flow.retryAt,\n unknown: flow.unknown,\n }\n : null,\n ...(data.recovered === true\n ? {\n lastUserId: null,\n error:\n \"Password updated. Previous sessions were revoked. Sign in with your new password.\",\n }\n : {}),\n });\n }\n return true;\n }\n const request = (path: string, body?: unknown) =>\n send(origin + path, {\n credentials: \"same-origin\",\n cache: \"no-store\",\n ...(body !== undefined\n ? {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-UIBot-CSRF\": csrf },\n body: JSON.stringify(body),\n }\n : {}),\n });\n const performLoad = async () => {\n if (mutations) return;\n const ticket = ++epoch;\n try {\n await accept(await request(\"/api/app-session\"), ticket);\n } catch {\n if (ticket !== epoch) return;\n csrf = \"\";\n update({\n ready: true,\n info: null,\n error: \"Session unavailable. Sign in again; your unsaved work is preserved.\",\n });\n }\n };\n const load = () => {\n if (mutations) return Promise.resolve();\n if (!loadPending)\n loadPending = performLoad().finally(() => {\n loadPending = undefined;\n });\n return loadPending;\n };\n const hostFetch: typeof fetch = Object.assign(\n async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = new URL(\n typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url,\n origin,\n );\n if (url.origin !== origin || url.pathname !== \"/api/uibot/data\")\n throw Error(\"Unsupported business request\");\n const headers = new Headers(init?.headers);\n if (![\"GET\", \"HEAD\"].includes(init?.method ?? \"GET\")) {\n headers.set(\"X-UIBot-CSRF\", csrf);\n headers.set(\"Content-Type\", \"application/json\");\n }\n const ticket = epoch;\n const response = await send(url, {\n ...init,\n headers,\n credentials: \"same-origin\",\n cache: \"no-store\",\n });\n if (ticket !== epoch) return response;\n if (response.status === 401) {\n ++epoch;\n csrf = \"\";\n update({\n info: null,\n error: \"Your session ended. Sign in again to continue; your unsaved work is preserved.\",\n });\n } else if (response.status === 403) void load();\n return response;\n },\n { preconnect: send.preconnect },\n );\n const login = async (email: string, password: string) => {\n if (mutations) throw Error(\"A session request is already in progress.\");\n mutations++;\n const pending = loadPending;\n const ticket = ++epoch;\n try {\n await pending;\n if (!(await accept(await request(\"/api/app-session\"), ticket)))\n throw Error(\"Sign-in canceled.\");\n if (!(await accept(await request(\"/api/app-session/login\", { email, password }), ticket)))\n throw Error(\"Sign-in canceled.\");\n } catch (error) {\n if (ticket === epoch) csrf = \"\";\n throw error;\n } finally {\n mutations--;\n }\n };\n const account = async (path: \"account-start\" | \"account-verify\", data: unknown) => {\n if (mutations) throw Error(\"A session request is already in progress.\");\n mutations++;\n update({ accountPending: true });\n const pending = loadPending;\n const ticket = ++epoch;\n let attempted = false;\n try {\n await pending;\n // Renew an idle anonymous cookie before the single explicit issuance request.\n if (\n (path === \"account-start\" || !csrf) &&\n !(await accept(await request(\"/api/app-session\"), ticket))\n )\n throw Error(\"Account request canceled.\");\n attempted = true;\n if (!(await accept(await request(`/api/app-session/${path}`, data), ticket, true)))\n throw Error(\"Account request canceled.\");\n if (path === \"account-start\") update({ error: \"\" });\n } catch (error) {\n if (!attempted)\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message:\n \"The verification session could not be prepared. No code was requested. Please try again.\",\n });\n // Reconcile metadata only; never replay challenge issuance or consumption.\n try {\n await accept(await request(\"/api/app-session\"), ticket);\n } catch {}\n if (isConnectionRequestError(error)) throw error;\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message:\n \"The account request outcome is unknown. Check sign-in or request a new code after the cooldown; this request will not be repeated.\",\n });\n } finally {\n mutations--;\n update({ accountPending: false });\n }\n };\n const action = async (operation: string, value: unknown): Promise<void> => {\n const input = { operation };\n const data =\n value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n const purposes: Record<string, \"signup\" | \"recovery\" | \"otp\"> = {\n StartSignup: \"signup\",\n StartRecovery: \"recovery\",\n StartOtp: \"otp\",\n };\n if (\n typeof input?.operation === \"string\" &&\n (Object.hasOwn(purposes, input.operation) ||\n [\"VerifyAccount\", \"ResendAccount\"].includes(input.operation))\n ) {\n if (input.operation === \"VerifyAccount\") await account(\"account-verify\", data);\n else {\n const email = input.operation === \"ResendAccount\" ? state.accountFlow?.email : data?.email;\n const purpose =\n input.operation === \"ResendAccount\"\n ? state.accountFlow?.purpose\n : purposes[input.operation];\n if (typeof email !== \"string\" || !purpose)\n throw new ConnectionRequestError({\n code: \"invalid-request\",\n message: \"Request a code first.\",\n });\n await account(\"account-start\", { email, purpose });\n }\n return;\n }\n if (\n input?.operation !== \"Login\" ||\n typeof data?.email !== \"string\" ||\n typeof data?.password !== \"string\"\n )\n throw new ConnectionRequestError({\n code: \"invalid-request\",\n message: \"Invalid sign-in request.\",\n });\n try {\n await login(data.email, data.password);\n return;\n } catch (error) {\n if (isConnectionRequestError(error)) throw error;\n throw new ConnectionRequestError({\n code: \"transport-error\",\n message: \"The session service is unavailable. Please try signing in again.\",\n });\n }\n };\n return {\n snapshot: () => state,\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n load,\n login,\n fetch: hostFetch,\n action,\n async refresh() {\n if (mutations) return;\n mutations++;\n const ticket = ++epoch;\n try {\n await accept(await request(\"/api/app-session/refresh\", {}), ticket);\n } catch {\n if (ticket !== epoch) return;\n csrf = \"\";\n update({ info: null, error: \"Session refresh was not confirmed. Sign in again.\" });\n } finally {\n mutations--;\n }\n },\n logout() {\n if (logoutPending) return logoutPending;\n const ticket = ++epoch;\n mutations++;\n const response = request(\"/api/app-session/logout\", {});\n csrf = \"\";\n update({ info: null, lastUserId: null, accountFlow: null });\n logoutPending = (async () => {\n let revoked = false;\n try {\n revoked = (await response).ok;\n } catch {\n /* local access is already cleared */\n } finally {\n if (ticket === epoch)\n update({\n error: revoked ? \"\" : \"Signed out locally. Remote revocation was not confirmed.\",\n });\n mutations--;\n logoutPending = undefined;\n }\n })();\n return logoutPending;\n },\n };\n}\nexport type AppSessionClient = ReturnType<typeof createAppSessionClient>;\n","src/app-features.ts":"import type { AppFeatureOptions, AppFeatures } from \"./app-feature-contract\";\n/** Generic scaffolds add application-specific presentation only by explicit host editing. */\nexport function createAppFeatures(_options: AppFeatureOptions = {}): AppFeatures {\n return {};\n}\n","src/admin.css":":root{--background:#fff;--foreground:#0f172a;--card:#fff;--primary:#0f172a;--primary-foreground:#f8fafc;--muted:#f1f5f9;--muted-foreground:#64748b;--border:#e2e8f0;--ring:#94a3b8;color:var(--foreground);font-family:Inter,ui-sans-serif,system-ui,sans-serif;font-synthesis:none;text-rendering:optimizeLegibility}\n.dark{--background:#09090b!important;--foreground:#fafafa!important;--card:#09090b;--primary:#fafafa;--primary-foreground:#18181b;--muted:#27272a;--muted-foreground:#a1a1aa;--border:#27272a;--ring:#d4d4d8;color-scheme:dark}\nbody{margin:0}button,input,select,textarea{font:inherit}input[type=checkbox],input[type=radio]{accent-color:var(--primary)}h1.uibot-heading{font-size:26px;font-weight:700;letter-spacing:-1px;line-height:1.3}.uibot-admin{--background:#fff!important;--foreground:#0f172a!important;background:var(--nui-sidebar,#fff)!important;color:var(--nui-foreground,#0f172a)!important}.uibot-admin.dark{--background:#09090b!important;--foreground:#fafafa!important;background:#141414!important;color:#fafafa!important}.uibot-admin.dark .nui-mobile{background:#141414;color:#fafafa}.preview-note{position:relative;margin:8px 12px;width:fit-content;max-width:calc(100% - 24px);border:1px solid var(--border);background:var(--background);border-radius:6px;padding:4px 10px;font-size:11px;color:var(--muted-foreground)}.uibot-admin .nui-main{min-height:calc(100dvh - 16px)}.uibot-admin [data-uibot-type=StatCard]{min-height:150px}.uibot-admin [data-uibot-type=Card]{height:100%}.uibot-admin .nui-content:has([data-uibot-type=ChatPanel]){padding-top:8px}\n\n*,::before,::after{border-color:var(--border)}\n","src/app-shell.css":".linked-app {\n --preview-ink: #17213b;\n --preview-muted: #a6b2ca;\n --preview-line: #dce2ed;\n height: 100dvh;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n background: #f4f6fa;\n}\n\n.linked-app-bar {\n position: relative;\n z-index: 20;\n flex: none;\n display: flex;\n align-items: center;\n gap: 32px;\n min-height: 80px;\n padding: 14px 28px;\n background: #17213b;\n color: #f7f9ff;\n border-bottom: 1px solid #2f3a54;\n box-shadow: 0 2px 10px #14203c12;\n}\n\n.linked-app-brand { display: flex; align-items: center; gap: 13px; min-width: 0; flex: 1; }\n.linked-app-mark { display: grid; place-items: center; width: 40px; height: 40px; flex: none; border: 1px solid #7485c366; border-radius: 12px; background: #5363c733; color: #c3cdff; }\n.linked-app-mark svg { width: 25px; height: 25px; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; }\n.linked-app-identity { min-width: 0; }\n.linked-app-identity h1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin: 0; font-size: 16px; font-weight: 600; line-height: 1.5; letter-spacing: -.3px; }\n.linked-app-identity > span { display: block; color: var(--preview-muted); font-size: 11px; line-height: 1.6; }\n.linked-app-actions { display: flex; align-items: center; gap: 24px; }\n.linked-app-account { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; align-items: center; font-size: 12px; }\n.linked-app-account > span { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.linked-app-account > small { color: var(--preview-muted); grid-row: 2; }\n.linked-app-account > button { grid-column: 2; grid-row: 1 / 3; }\n.linked-app-connection { display: flex; flex-direction: column; gap: 4px; white-space: nowrap; }\n.linked-app-status { display: flex; align-items: center; gap: 7px; color: #e2e8f5; font-size: 12px; line-height: 1.4; text-transform: capitalize; }\n.linked-app-status > span { height: 6px; width: 6px; border-radius: 50%; background: #f4c46b; }\n.linked-app-status[data-status=\"synced\"] > span { background: #68dcb3; box-shadow: 0 0 0 3px #68dcb314; }\n.linked-app-status[data-status=\"denied\"] > span, .linked-app-status[data-status=\"invalid\"] > span { background: #ff9b9b; }\n.linked-app-revision { color: var(--preview-muted); font-size: 10px; padding-left: 13px; }\n.linked-app-details-toggle { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px; padding: 0 10px; border: 1px solid #52617b; border-radius: 7px; background: transparent; color: #dbe3f6; font-size: 11px; cursor: pointer; }\n.linked-app-details-toggle svg { width: 17px; height: 17px; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; }\n.linked-app-details-toggle:hover, .linked-app-details-toggle[aria-expanded=\"true\"] { background: #2c3a56; border-color: #8390ab; }\n.linked-app-bar button:focus-visible { outline: 2px solid #b4c1ff; outline-offset: 4px; }\n.linked-app-details { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 16px 28px; border-bottom: 1px solid var(--preview-line); background: #edf1f8; color: var(--preview-ink); }\n.linked-app-details[hidden] { display: none; }\n.linked-app-details h2 { font-size: 12px; font-weight: 600; margin: 0 0 4px; }\n.linked-app-details p { font-size: 12px; color: #53617b; margin: 0; line-height: 1.6; max-width: 70ch; }\n.linked-app-details > button { flex: none; min-height: 36px; padding: 7px 12px; border: 1px solid #c4cde0; border-radius: 7px; background: #fff; color: #364c8a; font-size: 12px; cursor: pointer; }\n.linked-app-details > button:focus-visible { outline: 2px solid #4c57d6; outline-offset: 3px; }\n.linked-app-data-notice { flex: none; padding: 8px 28px; border-bottom: 1px solid var(--preview-line); background: #edf1f8; color: #53617b; font-size: 12px; line-height: 1.5; }\n.linked-app-canvas { position: relative; flex: 1; min-height: 0; overflow: hidden; background: var(--background); color: var(--foreground); isolation: isolate; }\n.linked-app-canvas .uibot-admin { height: 100%; min-height: 0; }\n.linked-app-canvas .uibot-admin .nui-main { min-height: 0; }\n.linked-app-canvas .uibot-standalone-layout { height: 100%; }\n.linked-app-module { max-width: 960px; margin: 48px auto; padding: 0 28px; }\n.linked-app-module > section { padding: 40px; border: 1px solid var(--preview-line); border-radius: 16px; background: #f8faff; color: var(--preview-ink); }\n.linked-app-module h1 { margin: 0 0 24px; font-size: 28px; line-height: 1.3; font-weight: 600; letter-spacing: -.8px; }\n.linked-app-module button { min-height: 42px; padding: 10px 18px; border: 1px solid #4554ac; border-radius: 8px; background: #4c5db6; color: #fff; font-size: 14px; cursor: pointer; }\n.linked-app-module button:hover { background: #3f4e9d; }\n.linked-app-module button:focus-visible { outline: 2px solid #4c57d6; outline-offset: 4px; }\n.linked-app-empty { min-height: 100%; padding: 60px 24px; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; color: var(--preview-ink); }\n.linked-app-empty-mark { font-size: 40px; color: #6879ad; margin-bottom: 16px; }\n.linked-app-empty h2 { font-size: 20px; letter-spacing: -.5px; margin: 0 0 10px; }\n.linked-app-empty p { font-size: 14px; color: #62718b; line-height: 1.7; max-width: 45ch; margin: 0; }\n\n@media (max-width: 1000px) {\n .linked-app-bar { padding-inline: 20px; gap: 20px; }\n .linked-app-actions { gap: 16px; }\n .linked-app-details-toggle { width: 36px; padding: 0; }\n .linked-app-details-toggle > span { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n}\n\n@media (max-width: 640px) {\n .linked-app-bar { flex-wrap: wrap; gap: 14px 16px; padding: 16px; }\n .linked-app-mark { height: 36px; width: 36px; border-radius: 10px; }\n .linked-app-identity h1 { font-size: 14px; }\n .linked-app-actions { width: 100%; justify-content: space-between; gap: 8px; }\n .linked-app-account { flex: 1; min-width: 0; max-width: 220px; }\n .linked-app-details { align-items: flex-start; flex-direction: column; padding: 16px; gap: 12px; }\n .linked-app-module { margin-block: 24px; padding-inline: 16px; }\n .linked-app-module > section { padding: 24px; }\n}\n\n.linked-app-navigator-toggle { display: grid; place-items: center; flex: none; width: 36px; height: 36px; border: 1px solid #52617b; border-radius: 7px; background: transparent; color: #dbe3f6; cursor: pointer; margin-right: -16px; }\n.linked-app-navigator-toggle:hover, .linked-app-navigator-toggle[aria-expanded=true] { background: #2c3a56; border-color: #8390ab; }\n.linked-app-navigator-toggle svg { width: 21px; height: 21px; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }\n.linked-app-body { display: flex; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }\n.linked-app-body > .linked-app-canvas { min-width: 0; }\n.app-page-navigator { width: 280px; flex: none; display: flex; flex-direction: column; min-height: 0; color: #34415a; background: #f6f8fc; border-right: 1px solid var(--preview-line); }\n.app-page-navigator[hidden] { display: none; }\n.app-page-navigator-heading { display: flex; align-items: center; gap: 8px; padding: 22px 20px 16px; }\n.app-page-navigator-heading h2 { margin: 0; color: var(--preview-ink); font-size: 13px; font-weight: 600; }\n.app-page-navigator-heading > span { padding: 1px 6px; border-radius: 4px; background: #e7ecf5; color: #61708b; font-size: 10px; }\n.app-route-search { display: flex; align-items: center; gap: 7px; margin: 0 14px 14px; padding: 8px 9px; border: 1px solid #d7deeb; border-radius: 6px; background: #fff; }\n.app-route-search > svg { width: 15px; height: 15px; flex: none; fill: none; stroke: #78849b; stroke-width: 1.5; }\n.app-route-search input { width: 100%; min-width: 0; border: 0; background: transparent; font-size: 11px; color: var(--preview-ink); outline: none; }\n.app-route-search:focus-within { outline: 2px solid #566cc9; outline-offset: 2px; }\n.app-route-search button { flex: none; width: 20px; height: 20px; color: #61708b; cursor: pointer; }\n.app-route-tree { flex: 1; min-height: 0; }\n.app-route-tree .uibot-scroll-viewport { padding: 0 10px 16px; box-sizing: border-box; overscroll-behavior: contain; }\n.app-route-tree ul { margin: 0; padding: 0; list-style: none; }\n.app-route-tree li > ul { margin-left: 17px; padding-left: 8px; border-left: 1px solid #dce2ed; }\n.app-route-row { display: flex; align-items: center; min-width: 0; margin-bottom: 2px; border: 1px solid transparent; border-radius: 6px; }\n.app-route-row:hover { background: #eaf0f8; }\n.app-route-row[data-selected=true] { background: #e4eaff; border-color: #d4dcfa; color: #354cb0; }\n.app-route-disclosure, .app-route-spacer { width: 20px; height: 28px; flex: none; }\n.app-route-disclosure { display: grid; place-items: center; color: #7a87a0; cursor: pointer; }\n.app-route-disclosure svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.5; }\n.app-route-disclosure svg[data-expanded=true] { transform: rotate(90deg); }\n.app-route-target { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; padding: 9px 8px 9px 0; text-align: left; cursor: pointer; }\n.app-route-target:disabled, .app-route-disclosure:disabled { cursor: default; }\n.app-route-target > svg { width: 15px; height: 15px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.25; stroke-linejoin: round; }\n.app-route-target > span { display: flex; flex-direction: column; min-width: 0; gap: 3px; flex: 1; }\n.app-route-target strong { font-size: 11px; line-height: 1.5; font-weight: 500; overflow-wrap: anywhere; }\n.app-route-target small { color: #79849a; font-size: 10px; line-height: 1.5; overflow-wrap: anywhere; }\n.app-route-target em { color: #78849b; font-size: 8px; font-style: normal; border: 1px solid #d8dfec; border-radius: 3px; padding: 1px 3px; }\n.app-page-navigator button:focus-visible { outline: 2px solid #566cc9; outline-offset: 1px; }\n.app-route-empty { padding: 20px 10px; color: #6a7890; font-size: 12px; line-height: 1.7; }\n.app-page-navigator-footer { margin: 0; padding: 12px 18px; color: #8791a5; border-top: 1px solid var(--preview-line); font-size: 10px; }\n@media (max-width: 1000px) { .linked-app-navigator-toggle { margin-right: -8px; } }\n@media (max-width: 640px) {\n .linked-app-navigator-toggle { margin-right: 0; width: 32px; height: 36px; }\n .linked-app-brand { gap: 8px; }\n .linked-app-bar { gap: 12px; }\n .linked-app-mark { display: none; }\n .linked-app-body[data-navigator-open=true] > .linked-app-canvas { display: none; }\n .app-page-navigator { width: 100%; border-right: 0; }\n .app-route-target strong { font-size: 13px; }\n .app-route-target { min-height: 44px; }\n}\n.linked-app-notice { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 10px 24px; border-bottom: 1px solid #d9c9a7; background: #fffbef; color: #66512b; }\n.linked-app-notice p { margin: 0; font-size: 12px; line-height: 1.7; }\n.linked-app-retry { flex: none; min-height: 36px; padding: 7px 12px; border: 1px solid #b8c4dc; border-radius: 7px; background: #fff; color: #344775; font-size: 12px; cursor: pointer; }\n.linked-app-retry:disabled { cursor: wait; opacity: .6; }\n.linked-app-retry:hover:enabled { background: #f0f4fb; }\n.linked-app-retry:focus-visible { outline: 2px solid #566cc9; outline-offset: 3px; }\n.linked-app-empty .linked-app-retry { margin-top: 20px; }\n@media (max-width: 640px) {\n .linked-app-notice { flex-wrap: wrap; gap: 8px; padding: 12px 16px; }\n .linked-app-actions { min-width: 0; }\n .linked-app-retry { min-height: 40px; }\n}\n","linked-backend.ts":"type LinkedMiddleware = (\n request: {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n },\n response: {\n statusCode: number;\n setHeader(name: string, value: string): void;\n end(body?: string): void;\n },\n next: () => void,\n) => void;\n\nimport { projectAppHostView } from \"./app-host-view\";\nimport type { DataUpstreams } from \"@uibot/application/data-gateway\";\nimport { readFileSync } from \"node:fs\";\nimport { appConnectionUrl, readAppConnection } from \"@uibot/contracts\";\n\nclass HostReadFailure extends Error {\n constructor(readonly status: number) {\n super(\"Application data unavailable\");\n }\n}\n\n/** Fixed application reads. Business sessions are owned by the calling host. */\nexport function createLinkedBackend(\n kind: \"spec\" | \"app\" = \"spec\",\n options: {\n trusted?: boolean;\n fetch?: typeof fetch;\n hostView?: { environment: string; upstreams: DataUpstreams };\n } = {},\n) {\n if (options.fetch !== undefined && typeof options.fetch !== \"function\")\n throw Error(\"Invalid server transport\");\n const send = options.fetch ?? fetch;\n const app = kind === \"app\";\n const accountFlows = app && process.env.UIBOT_LINKED_APP_AUTH === \"true\";\n if (accountFlows && process.env.UIBOT_LINKED_APP_SESSIONS !== \"true\")\n throw Error(\"Account flows require the per-user session host\");\n const channel = process.env.UIBOT_LINKED_APP_CHANNEL ?? \"development\";\n if (app && ![\"development\", \"production\"].includes(channel))\n throw Error(\"Invalid linked application channel\");\n const configPath = app ? \"/linked-app-config.json\" : \"/linked-config.json\";\n const sourcePath = app ? \"/linked-app.json\" : \"/linked-spec.json\";\n const connectionFile = app ? process.env.UIBOT_LINKED_APP_CONNECTION_FILE : undefined;\n if (connectionFile && process.env.UIBOT_LINKED_APP_URL)\n throw Error(\"Choose a connection file or UIBOT_LINKED_APP_URL, not both\");\n const connection = connectionFile\n ? readAppConnection(JSON.parse(readFileSync(connectionFile, \"utf8\")))\n : undefined;\n const raw = connection\n ? appConnectionUrl(connection, channel as \"development\" | \"production\")\n : app\n ? process.env.UIBOT_LINKED_APP_URL\n : process.env.UIBOT_LINKED_SPEC_URL;\n const bearer =\n (app ? process.env.UIBOT_LINKED_APP_BEARER : undefined) ?? process.env.UIBOT_LINKED_SPEC_BEARER;\n let upstream: URL | undefined;\n let identity: { projectId: string; artifactId: string } | undefined;\n if (raw) {\n upstream = new URL(raw);\n const match = upstream.pathname.match(\n app\n ? new RegExp(\n `^/api/studio/creation/apps/([A-Za-z0-9_-]{1,128})/([A-Za-z0-9_-]{1,128})/${channel === \"production\" ? \"releases/current\" : \"live\"}$`,\n )\n : /^\\/api\\/studio\\/creation\\/projects\\/([A-Za-z0-9_-]{1,128})\\/artifacts\\/([A-Za-z0-9_-]{1,128})\\/live$/,\n );\n if (\n !match ||\n ![\"http:\", \"https:\"].includes(upstream.protocol) ||\n upstream.username ||\n upstream.password ||\n upstream.search ||\n upstream.hash\n )\n throw new Error(\"Invalid UIBOT_LINKED_SPEC_URL\");\n identity = { projectId: match[1] as string, artifactId: match[2] as string };\n }\n async function readHostView() {\n if (!app || !upstream || !identity || !options.hostView)\n throw Error(\"Application data unavailable\");\n const result = await send(upstream, {\n redirect: \"error\",\n signal: AbortSignal.timeout(10000),\n headers: bearer ? { authorization: `Bearer ${bearer}` } : {},\n });\n if (!result.ok) throw new HostReadFailure(result.status);\n const text = await result.text();\n if (text.length > 8_000_000) throw Error(\"Oversized application revision\");\n return projectAppHostView(JSON.parse(text), {\n ...identity,\n channel: channel as \"development\" | \"production\",\n ...options.hostView,\n });\n }\n const middleware: LinkedMiddleware = (request, response, next) => {\n if (request.url !== configPath && request.url !== sourcePath) {\n const path = request.url?.split(\"?\")[0] ?? \"\";\n const accept = request.headers.accept;\n if (\n app &&\n upstream &&\n (request.method === \"GET\" || request.method === \"HEAD\") &&\n typeof accept === \"string\" &&\n accept.includes(\"text/html\") &&\n !/^\\/(?:@|src\\/|node_modules\\/|assets\\/|api(?:\\/|$))/.test(path) &&\n !/\\.(?:js|mjs|css|json|map|svg|png|jpe?g|gif|ico|webp|woff2?|ttf|wasm)$/i.test(path)\n )\n request.url = \"/app.html\";\n return next();\n }\n response.setHeader(\"Cache-Control\", \"no-store\");\n response.setHeader(\"Content-Type\", \"application/json\");\n if (request.method !== \"GET\" || !upstream || !identity) {\n response.statusCode = 503;\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n return;\n }\n if (request.url === configPath) {\n response.end(\n JSON.stringify({\n ...identity,\n ...(app\n ? {\n channel,\n ...(options.hostView ? { dataEnvironment: options.hostView.environment } : {}),\n ...(connection ? { intervalMs: connection.intervalMs } : {}),\n sessions: process.env.UIBOT_LINKED_APP_SESSIONS === \"true\",\n accountFlows,\n }\n : {}),\n }),\n );\n return;\n }\n if (app && options.hostView) {\n void readHostView()\n .then(({ view }) => {\n response.setHeader(\"ETag\", `\"uibot-host-view-${view.projectionHash}\"`);\n response.end(JSON.stringify(view));\n })\n .catch((error) => {\n response.statusCode = error instanceof HostReadFailure ? error.status : 502;\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n });\n return;\n }\n const etag = request.headers[\"if-none-match\"];\n void send(upstream, {\n redirect: \"error\",\n signal: AbortSignal.timeout(10000),\n headers: {\n ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),\n ...(typeof etag === \"string\" ? { \"if-none-match\": etag } : {}),\n },\n })\n .then(async (result) => {\n response.statusCode = result.status;\n const tag = result.headers.get(\"etag\");\n if (tag) response.setHeader(\"ETag\", tag);\n if (result.status === 304) {\n response.end();\n return;\n }\n if (!result.ok) {\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n return;\n }\n const text = await result.text();\n if (text.length > 8_000_000) throw new Error(\"Oversized snapshot\");\n response.end(text);\n })\n .catch(() => {\n response.statusCode = 502;\n response.end(JSON.stringify({ error: \"linked-unavailable\" }));\n });\n };\n return {\n name: `uibot-linked-${kind}-proxy`,\n middleware,\n async readRevision() {\n const result = await readHostView();\n if (!result.revision) throw Error(\"Application is not published\");\n return result.revision;\n },\n config: () => (app && upstream ? { appType: \"mpa\" as const } : undefined),\n configureServer(server: { middlewares: { use(handler: LinkedMiddleware): void } }) {\n server.middlewares.use(middleware);\n },\n };\n}\n\n/** Vite adapter; deployed hosts use the same fixed reads without Vite middleware. */\nexport const linkedBackendPlugin = createLinkedBackend;\n","app-host-view.ts":"import { createHash } from \"node:crypto\";\nimport { parse } from \"yaml\";\nimport {\n appDocumentText,\n appHostViewText,\n readAppHostView,\n readAppReleaseView,\n readLinkedAppSnapshot,\n resolveDataBindings,\n type AppHostView,\n type LinkedSpecIdentity,\n type UIBotSpec,\n} from \"@uibot/contracts\";\nimport { validateDataUpstreamBinding, type DataUpstreams } from \"@uibot/application/data-gateway\";\n\nconst hash = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n/** The original revision is verified intact; its identity never describes projected content. */\nexport function projectAppHostView(\n input: unknown,\n options: LinkedSpecIdentity & {\n channel: \"development\" | \"production\";\n environment: string;\n upstreams: DataUpstreams;\n },\n): { view: AppHostView; revision?: { revisionId: string; spec: UIBotSpec } } {\n const original =\n options.channel === \"production\" ? readAppReleaseView(input) : readLinkedAppSnapshot(input);\n if (original.projectId !== options.projectId || original.artifactId !== options.artifactId)\n throw Error(\"Foreign application revision\");\n const base = {\n contract: \"uibot.app-host-view.v1\" as const,\n projectId: original.projectId,\n artifactId: original.artifactId,\n environment: options.environment,\n projectionHash: \"0\".repeat(64),\n };\n if (\"published\" in original && !original.published) {\n const view = readAppHostView({ ...base, channel: \"production\", available: false });\n view.projectionHash = hash(appHostViewText(view));\n return { view };\n }\n if (hash(appDocumentText(original.document)) !== original.sourceHash)\n throw Error(\"Invalid original application hash\");\n const spec = parse(original.document.spec, {\n logLevel: \"silent\",\n maxAliasCount: 100,\n }) as UIBotSpec;\n const readiness = resolveDataBindings(spec, options);\n const dataReadiness = (spec.connections ?? [])\n .filter((connection) => connection.type === \"Collection\")\n .map((connection) => {\n const entry = readiness[connection.id];\n return {\n id: connection.id,\n state:\n entry?.state === \"mock\"\n ? \"mock\"\n : entry?.state === \"bound\" &&\n entry.binding &&\n validateDataUpstreamBinding(options.upstreams, entry.binding)\n ? \"bound\"\n : \"unbound\",\n };\n });\n const projected = structuredClone(spec);\n for (const connection of projected.connections ?? []) {\n if (connection.type !== \"Collection\") continue;\n delete connection.bindings;\n if (options.environment !== \"mock\") delete connection.mock;\n }\n const view = readAppHostView({\n ...base,\n available: true,\n channel: options.channel,\n revision:\n \"releaseId\" in original\n ? {\n revisionId: original.revisionId,\n sourceHash: original.sourceHash,\n releaseId: original.releaseId,\n releaseSequence: original.releaseSequence,\n }\n : {\n revisionId: original.revisionId,\n revisionNumber: original.revisionNumber,\n sourceHash: original.sourceHash,\n },\n document: { ...original.document, spec: JSON.stringify(projected) },\n dataReadiness,\n });\n view.projectionHash = hash(appHostViewText(view));\n return { view, revision: { revisionId: original.revisionId, spec } };\n}\n","app-session-plugin.ts":"import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { createAppSessionHost } from \"./app-session\";\n\nexport function appSessionPlugin(\n options: { host?: ReturnType<typeof createAppSessionHost>; origin?: string } = {},\n) {\n const enabled = process.env.UIBOT_LINKED_APP_SESSIONS === \"true\";\n if (!enabled && !options.host) return { name: \"uibot-app-session-disabled\", host: undefined };\n const origin = options.origin ?? process.env.UIBOT_LINKED_APP_SESSION_ORIGIN;\n const transportFile = process.env.UIBOT_ADMIN_TRANSPORT_FILE;\n if (!origin || (!options.host && !transportFile))\n throw Error(\"Sessions require an exact host origin and private session transport\");\n const host =\n options.host ??\n createAppSessionHost({\n origin,\n transportFile,\n accountFlows: process.env.UIBOT_LINKED_APP_AUTH === \"true\",\n });\n return {\n name: \"uibot-app-session-host\",\n host,\n configureServer(server: {\n httpServer: { once(event: \"close\", stop: () => void): void } | null;\n middlewares: {\n use(handler: (req: IncomingMessage, res: ServerResponse, next: () => void) => void): void;\n };\n }) {\n server.httpServer?.once(\"close\", host.dispose);\n server.middlewares.use((req, res, next) => {\n if (!/^\\/api\\/app-session(?:\\/|$)/.test(req.url?.split(\"?\")[0] ?? \"\")) return next();\n void (async () => {\n if (\n req.headers.host !== new URL(origin).host ||\n !req.url?.startsWith(\"/\") ||\n req.url.startsWith(\"//\") ||\n /%|\\.\\./.test(req.url.split(\"?\")[0] ?? \"\")\n ) {\n res.writeHead(403, { \"Cache-Control\": \"no-store\", \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ message: \"Host or route denied.\" }));\n return;\n }\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers))\n if (typeof value === \"string\") headers.set(key, value);\n const response = await host.handle(\n new Request(origin + req.url, {\n method: req.method,\n headers,\n ...(![\"GET\", \"HEAD\"].includes(req.method ?? \"\")\n ? { body: Readable.toWeb(req), duplex: \"half\" }\n : {}),\n } as RequestInit),\n );\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n res.end(await response.text());\n })().catch(() => {\n if (!res.headersSent)\n res.writeHead(502, { \"Cache-Control\": \"no-store\", \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ message: \"Session service unavailable.\" }));\n });\n });\n },\n };\n}\n","app-session.ts":"import { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { statSync } from \"node:fs\";\nimport { adminBackendProxy } from \"./admin-backend\";\nimport {\n AccountFault,\n accountFlowMetadata,\n createAccountFlows,\n type AccountFlow,\n} from \"./app-account-flow\";\n\ntype User = { id: string; email: string; role: string };\nexport type AppSession = {\n csrf: string;\n expires: number;\n closed: boolean;\n attempts: number;\n access?: string;\n refresh?: string;\n accessExpires?: number;\n user?: User;\n refreshing?: Promise<void>;\n account?: AccountFlow;\n accountRetryAt?: number;\n busy?: boolean;\n};\nclass Fault extends Error {\n constructor(\n public status: number,\n public code: string,\n ) {\n super(code);\n }\n}\nconst secret = () => randomBytes(32).toString(\"base64url\");\nconst object = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === \"object\" && !Array.isArray(v);\nconst equal = (a: string, b: string) => {\n const left = Buffer.from(a),\n right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n};\nasync function textBody(request: Request | Response, limit = 65536) {\n const reader = request.body?.getReader();\n if (!reader) return \"\";\n const chunks: Uint8Array[] = [];\n let size = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Fault(408, \"body-timeout\")), 10000);\n });\n try {\n while (true) {\n const part = await Promise.race([reader.read(), timeout]);\n if (part.done) break;\n size += part.value.byteLength;\n if (size > limit) throw new Fault(413, \"body-too-large\");\n chunks.push(part.value);\n }\n } finally {\n clearTimeout(timer);\n void reader.cancel().catch(() => {});\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\nfunction parse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new Fault(400, \"invalid-json\");\n }\n}\n\n/** Loopback host example. Tokens never enter browser responses, Spec or browser storage. */\nexport function createAppSessionHost(options: {\n origin: string;\n transportFile?: string;\n dataOnly?: boolean;\n fetch?: typeof fetch;\n now?: () => number;\n maxSessions?: number;\n accountFlows?: boolean;\n trusted?: boolean;\n store?: {\n load(): [string, AppSession][];\n save(entries: [string, AppSession][]): void;\n close(): void;\n };\n}) {\n const origin = new URL(options.origin);\n if (\n origin.origin !== options.origin ||\n ![\"http:\", \"https:\"].includes(origin.protocol) ||\n (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(origin.hostname) &&\n !(options.trusted && origin.protocol === \"https:\"))\n )\n throw Error(\"Session example requires an exact loopback origin\");\n if (!options.transportFile && (!options.dataOnly || options.accountFlows))\n throw Error(\"Session transport is required\");\n const configured = options.transportFile\n ? adminBackendProxy(options.transportFile, options.trusted)\n : undefined;\n if (\n options.transportFile &&\n ((statSync(options.transportFile).mode & 0o077) !== 0 || !configured)\n )\n throw Error(\"Session transport must be private and valid\");\n if (configured?.headers.Authorization)\n throw Error(\"Session transport must not contain a static user bearer\");\n const transport = configured;\n const send = options.fetch ?? fetch;\n const now = options.now ?? Date.now;\n const sessions = new Map<string, AppSession>(options.store?.load());\n let unavailable = false;\n let disposed = false;\n function checkpoint(exclude?: AppSession) {\n if (!options.store || disposed) return;\n try {\n options.store.save(\n [...sessions].filter(\n ([, entry]) =>\n entry !== exclude &&\n !entry.closed &&\n !entry.busy &&\n !entry.refreshing &&\n entry.expires > now(),\n ),\n );\n } catch {\n unavailable = true;\n sessions.clear();\n throw new Fault(503, \"session-store-unavailable\");\n }\n }\n const name = `${origin.protocol === \"https:\" ? \"__Host-\" : \"\"}uibot-session-${origin.port || \"default\"}`;\n const cookie = (id: string, seconds: number) =>\n `${name}=${id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${Math.max(0, Math.floor(seconds))}${origin.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n const headers = (access?: string) => ({\n ...transport?.headers,\n ...(access ? { Authorization: `Bearer ${access}` } : {}),\n });\n async function upstream(\n path: string,\n method: string,\n body?: string,\n access?: string,\n extra?: Headers,\n ) {\n if (!transport) throw new Fault(503, \"session-transport-unavailable\");\n try {\n return await send(transport.target + path, {\n method,\n redirect: \"error\",\n signal: AbortSignal.timeout(10000),\n headers: {\n ...headers(access),\n ...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n ...(extra ? Object.fromEntries(extra) : {}),\n },\n ...(body !== undefined ? { body } : {}),\n });\n } catch {\n throw new Fault(502, \"upstream-unavailable\");\n }\n }\n const accounts = createAccountFlows({\n now,\n send: (path, body) => upstream(path, \"POST\", body),\n read: async (response) => parse(await textBody(response)),\n });\n async function readUser(access: string): Promise<User> {\n const response = await upstream(\"/auth/v1/user\", \"GET\", undefined, access);\n if (!response.ok) throw new Fault(response.status === 401 ? 401 : 502, \"session-unavailable\");\n const data = parse(await textBody(response));\n if (\n !object(data) ||\n typeof data.id !== \"string\" ||\n typeof data.email !== \"string\" ||\n typeof data.role !== \"string\"\n )\n throw new Fault(502, \"invalid-session-response\");\n return { id: data.id, email: data.email, role: data.role };\n }\n async function tokens(response: Response) {\n if (!response.ok)\n throw new Fault(\n response.status === 400 || response.status === 401 ? 401 : 502,\n \"sign-in-failed\",\n );\n const data = parse(await textBody(response));\n if (\n !object(data) ||\n typeof data.access_token !== \"string\" ||\n data.access_token.length > 16384 ||\n typeof data.refresh_token !== \"string\" ||\n data.refresh_token.length > 16384 ||\n typeof data.expires_in !== \"number\" ||\n data.expires_in <= 0 ||\n !Number.isFinite(data.expires_in) ||\n typeof data.session_expires_at !== \"number\" ||\n !Number.isFinite(data.session_expires_at) ||\n data.session_expires_at * 1000 <= now()\n )\n throw new Fault(502, \"invalid-session-response\");\n const user = await readUser(data.access_token);\n return {\n access: data.access_token,\n refresh: data.refresh_token,\n user,\n accessExpires: now() + data.expires_in * 1000,\n expires: data.session_expires_at * 1000,\n };\n }\n function close(session: AppSession) {\n session.closed = true;\n session.access = undefined;\n session.refresh = undefined;\n session.account = undefined;\n for (const [id, entry] of sessions) if (entry === session) sessions.delete(id);\n checkpoint();\n }\n async function authorize(session: AppSession) {\n if (session.closed || !session.access || !session.refresh || session.expires <= now())\n throw new Fault(401, \"sign-in-required\");\n if (session.refreshing || (session.accessExpires ?? 0) <= now() + 30000) {\n if (!session.refreshing) {\n // Remove durable credentials before a possibly committed token rotation.\n checkpoint(session);\n session.refreshing = (async () => {\n try {\n const next = await tokens(\n await upstream(\n \"/auth/v1/token?grant_type=refresh_token\",\n \"POST\",\n JSON.stringify({ refresh_token: session.refresh }),\n ),\n );\n if (session.closed || next.user.id !== session.user?.id)\n throw new Fault(401, \"session-changed\");\n Object.assign(session, next);\n } catch {\n close(session);\n // Rotation may have committed: never retry the old refresh token.\n throw new Fault(401, \"session-lost\");\n }\n })().finally(() => {\n session.refreshing = undefined;\n });\n }\n await session.refreshing;\n }\n if (session.closed || !session.access) throw new Fault(401, \"sign-in-required\");\n try {\n const user = await readUser(session.access);\n if (user.id !== session.user?.id) throw new Fault(401, \"session-changed\");\n session.user = user;\n } catch (error) {\n if (error instanceof Fault && error.status === 401) close(session);\n throw error;\n }\n }\n function requestSession(request: Request) {\n const url = new URL(request.url);\n if (\n url.origin !== origin.origin ||\n (request.headers.get(\"origin\") && request.headers.get(\"origin\") !== origin.origin) ||\n [\"cross-site\", \"same-site\"].includes(request.headers.get(\"sec-fetch-site\") ?? \"\")\n )\n throw new Fault(403, \"origin-denied\");\n const matches =\n request.headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((s) => s.trim())\n .filter((s) => s.startsWith(`${name}=`)) ?? [];\n if (matches.length > 1) throw new Fault(401, \"invalid-session\");\n const id = matches[0]?.slice(name.length + 1);\n let session = id ? sessions.get(id) : undefined;\n if (session && (session.closed || session.expires <= now())) {\n close(session);\n session = undefined;\n }\n return { id, session };\n }\n function csrfRequest(request: Request, session: AppSession) {\n if (\n request.headers.get(\"origin\") !== origin.origin ||\n request.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase() !==\n \"application/json\" ||\n !equal(request.headers.get(\"x-uibot-csrf\") ?? \"\", session.csrf)\n )\n throw new Fault(403, \"csrf-denied\");\n }\n const metadata = (s: AppSession) =>\n s.user && !s.closed\n ? {\n authenticated: true,\n user: s.user,\n canBatch: s.user.role === \"admin\",\n csrfToken: s.csrf,\n accessExpiresAt: s.accessExpires,\n sessionExpiresAt: s.expires,\n }\n : {\n authenticated: false,\n csrfToken: s.csrf,\n ...(options.accountFlows ? { accountFlow: accountFlowMetadata(s.account) } : {}),\n };\n\n const host = {\n dispose() {\n checkpoint();\n disposed = true;\n for (const entry of sessions.values()) {\n entry.closed = true;\n entry.access = undefined;\n entry.refresh = undefined;\n entry.account = undefined;\n }\n sessions.clear();\n options.store?.close();\n },\n async handle(request: Request): Promise<Response> {\n let session: AppSession | undefined;\n let setCookie: string | undefined;\n let busySession: AppSession | undefined;\n const reply = (data: unknown, status = 200) =>\n new Response(JSON.stringify(data), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store\",\n \"X-Content-Type-Options\": \"nosniff\",\n ...(setCookie ? { \"Set-Cookie\": setCookie } : {}),\n },\n });\n try {\n const url = new URL(request.url);\n const selected = requestSession(request);\n const id = selected.id;\n session = selected.session;\n const path = url.pathname;\n const authPath =\n /^\\/api\\/app-session(?:\\/(login|refresh|logout|account-start|account-verify))?$/.exec(\n path,\n );\n if (!authPath) throw new Fault(404, \"route-not-found\");\n const action = authPath?.[1];\n const read = request.method === \"GET\";\n if (authPath && (url.search || request.method !== (action ? \"POST\" : \"GET\")))\n throw new Fault(405, \"method-not-allowed\");\n if (\n !read &&\n (request.headers.get(\"origin\") !== origin.origin ||\n !request.headers.get(\"content-type\")?.startsWith(\"application/json\"))\n )\n throw new Fault(403, \"csrf-denied\");\n if (authPath && !action && !session) {\n for (const entry of sessions.values()) if (entry.expires <= now()) close(entry);\n if (sessions.size >= (options.maxSessions ?? 100))\n throw new Fault(503, \"session-capacity\");\n const fresh = secret();\n session = { csrf: secret(), expires: now() + 300000, closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, 300);\n }\n if (!session) throw new Fault(401, \"sign-in-required\");\n if (!read) csrfRequest(request, session);\n if (action) {\n if (session.busy) throw new Fault(409, \"session-request-pending\");\n session.busy = true;\n busySession = session;\n // A crash during authentication must never replay stored credentials/challenges.\n checkpoint();\n }\n if (action === \"account-start\" || action === \"account-verify\") {\n if (!options.accountFlows) throw new Fault(404, \"account-service-disabled\");\n if (session.user) throw new Fault(409, \"sign-out-before-account-flow\");\n const input = parse(await textBody(request));\n if (action === \"account-start\") {\n if ((session.accountRetryAt ?? 0) > now()) throw new Fault(429, \"account-cooldown\");\n if (++session.attempts > 5) throw new Fault(429, \"account-start-rate-limit\");\n session.accountRetryAt = now() + 60000;\n if (session.account) session.account.unknown = true;\n const flow = await accounts.start(input, session.account);\n if (session.closed) throw new Fault(401, \"session-changed\");\n session.account = flow;\n session.expires = Math.max(session.expires, session.account.expiresAt + 60000);\n setCookie = cookie(id as string, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n const response = await accounts.verify(session.account, input);\n if (session.closed) throw new Fault(401, \"session-changed\");\n if (session.account?.purpose === \"recovery\") {\n const data = parse(await textBody(response));\n if (!object(data) || data.recovered !== true || data.sessionsRevoked !== true)\n throw new Fault(502, \"invalid-account-response\");\n const email = session.account.email;\n for (const entry of sessions.values()) if (entry.user?.email === email) close(entry);\n close(session);\n const fresh = secret();\n session = { csrf: secret(), expires: now() + 300000, closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, 300);\n return reply({ ...metadata(session), recovered: true });\n }\n const next = await tokens(response);\n if (session.closed || next.user.email !== session.account?.email)\n throw new Fault(401, \"session-changed\");\n close(session);\n const fresh = secret();\n session = { ...next, csrf: secret(), closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n if (action === \"login\") {\n if (session.user) throw new Fault(409, \"sign-out-before-login\");\n if (++session.attempts > 5) throw new Fault(429, \"sign-in-rate-limit\");\n const input = parse(await textBody(request));\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"email\", \"password\"].includes(key)) ||\n typeof input.email !== \"string\" ||\n typeof input.password !== \"string\" ||\n input.email.length > 320 ||\n input.password.length > 1024 ||\n !input.email ||\n !input.password\n )\n throw new Fault(400, \"invalid-login\");\n const next = await tokens(\n await upstream(\"/auth/v1/token?grant_type=password\", \"POST\", JSON.stringify(input)),\n );\n if (session.closed) throw new Fault(401, \"session-changed\");\n close(session);\n const fresh = secret();\n session = { ...next, csrf: secret(), closed: false, attempts: 0 };\n sessions.set(fresh, session);\n setCookie = cookie(fresh, (session.expires - now()) / 1000);\n return reply(metadata(session));\n }\n if (action === \"logout\") {\n const access = session.access;\n const refreshing = session.refreshing;\n close(session);\n setCookie = cookie(\"\", 0);\n // A concurrent rotation makes remote revocation uncertain; local access is always removed.\n let revoked = false;\n if (access && !refreshing) {\n try {\n revoked = (await upstream(\"/auth/v1/logout\", \"POST\", \"{}\", access)).ok;\n } catch {}\n }\n return reply({ authenticated: false, revoked }, revoked || !access ? 200 : 502);\n }\n if (action === \"refresh\") session.accessExpires = 0;\n if (authPath) {\n if (session.user || action) await authorize(session);\n return reply(metadata(session));\n }\n await authorize(session);\n throw new Fault(404, \"route-not-found\");\n } catch (error) {\n const fault =\n error instanceof Fault || error instanceof AccountFault\n ? error\n : new Fault(502, \"request-unavailable\");\n if (fault.status === 401) {\n if (session?.access || session?.closed) close(session);\n // Anonymous login failures retain their bounded attempt counter.\n }\n return reply(\n {\n code: fault.code,\n message:\n fault.status === 401\n ? \"Sign in to continue. Your unsaved input is preserved.\"\n : fault.status === 403\n ? \"Permission denied.\"\n : \"The request could not be completed.\",\n },\n fault.status,\n );\n } finally {\n if (busySession) busySession.busy = false;\n }\n },\n };\n return {\n dispose: host.dispose,\n async authorizeDataRequest(\n request: Request,\n ): Promise<{ user?: User; headers?: Record<string, string> }> {\n if (disposed || unavailable || request.method !== \"POST\")\n throw new Fault(403, \"data-session-denied\");\n const { session } = requestSession(request);\n if (!session) throw new Fault(403, \"data-session-denied\");\n csrfRequest(request, session);\n if (!session.user) return {};\n await authorize(session);\n if (\n disposed ||\n unavailable ||\n session.closed ||\n !session.user ||\n !session.access ||\n session.expires <= now()\n )\n throw new Fault(401, \"sign-in-required\");\n checkpoint();\n return { user: { ...session.user }, headers: { Authorization: `Bearer ${session.access}` } };\n },\n async handle(request: Request): Promise<Response> {\n try {\n if (unavailable) throw new Fault(503, \"session-store-unavailable\");\n const response = await host.handle(request);\n checkpoint();\n return response;\n } catch {\n unavailable = true;\n sessions.clear();\n return Response.json(\n { code: \"session-store-unavailable\", message: \"Session service unavailable.\" },\n { status: 503, headers: { \"Cache-Control\": \"no-store\" } },\n );\n }\n },\n };\n}\n","admin-backend.ts":"import { readFileSync } from \"node:fs\";\n\n/** Server-only session transport. Never import this module from browser code. */\nexport function adminBackendProxy(file: string | undefined, trusted = false) {\n if (!file) return undefined;\n const value: unknown = JSON.parse(readFileSync(file, \"utf8\"));\n if (!value || typeof value !== \"object\")\n throw new Error(\"Invalid backend transport configuration\");\n const config = value as Record<string, unknown>;\n for (const field of [\"gateway\", \"project\", \"workspace\", \"version\", \"serviceKey\"])\n if (typeof config[field] !== \"string\" || !config[field])\n throw new Error(\"Incomplete backend transport configuration\");\n const url = new URL(config.gateway as string);\n if (\n (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname) &&\n !(trusted && url.protocol === \"https:\")) ||\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash\n )\n throw new Error(\"Development backend must use a loopback gateway\");\n for (const field of [\"project\", \"workspace\", \"version\"])\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(config[field] as string))\n throw new Error(\"Invalid backend transport scope\");\n return {\n target: url.origin,\n headers: {\n \"X-API-Key\": config.serviceKey as string,\n ...(typeof config.userToken === \"string\"\n ? { Authorization: `Bearer ${config.userToken}` }\n : {}),\n \"X-NowAPI-Project\": config.project as string,\n \"X-NowAPI-Workspace\": config.workspace as string,\n },\n };\n}\n","app-account-flow.ts":"export type AccountPurpose = \"signup\" | \"recovery\" | \"otp\";\nexport type AccountFlow = {\n id: string;\n purpose: AccountPurpose;\n delivery: \"local_http\" | \"smtp\";\n email: string;\n expiresAt: number;\n retryAt: number;\n attempts: number;\n unknown: boolean;\n};\nexport class AccountFault extends Error {\n constructor(\n public status: number,\n public code: string,\n ) {\n super(code);\n }\n}\nconst object = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === \"object\" && !Array.isArray(v);\nexport const accountFlowMetadata = (flow?: AccountFlow) =>\n flow\n ? {\n purpose: flow.purpose,\n delivery: flow.delivery,\n email: flow.email,\n expiresAt: flow.expiresAt,\n retryAt: flow.retryAt,\n unknown: flow.unknown,\n }\n : null;\n\n/** Challenge identity and credentials stay in the host; this has no browser storage. */\nexport function createAccountFlows(options: {\n now(): number;\n send(path: string, body: string): Promise<Response>;\n read(response: Response): Promise<unknown>;\n}) {\n const fail = (status: number, code: string): never => {\n throw new AccountFault(status, code);\n };\n return {\n async start(input: unknown, previous?: AccountFlow): Promise<AccountFlow> {\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"email\", \"purpose\"].includes(key)) ||\n typeof input.email !== \"string\" ||\n input.email.length > 254 ||\n !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(input.email) ||\n ![\"signup\", \"recovery\", \"otp\"].includes(String(input.purpose))\n )\n return fail(400, \"invalid-account-request\");\n if (previous && previous.retryAt > options.now()) return fail(429, \"account-cooldown\");\n const response = await options.send(\"/auth/v1/challenge\", JSON.stringify(input));\n if (!response.ok)\n return fail(response.status === 429 ? 429 : 503, \"account-delivery-unavailable\");\n const data = await options.read(response);\n if (\n response.status !== 202 ||\n !object(data) ||\n data.accepted !== true ||\n typeof data.challengeId !== \"string\" ||\n !/^[a-f0-9-]{36}$/i.test(data.challengeId) ||\n typeof data.expiresIn !== \"number\" ||\n !Number.isSafeInteger(data.expiresIn) ||\n data.expiresIn < 1 ||\n data.expiresIn > (input.purpose === \"signup\" ? 1800 : 600) ||\n ![\"local_http\", \"smtp\"].includes(String(data.delivery))\n )\n return fail(502, \"invalid-account-response\");\n return {\n id: data.challengeId,\n email: input.email.trim().toLowerCase(),\n purpose: input.purpose as AccountPurpose,\n delivery: data.delivery as AccountFlow[\"delivery\"],\n expiresAt: options.now() + data.expiresIn * 1000,\n retryAt: options.now() + 60000,\n attempts: 0,\n unknown: false,\n };\n },\n async verify(flow: AccountFlow | undefined, input: unknown): Promise<Response> {\n if (!flow || flow.unknown || flow.expiresAt <= options.now())\n return fail(409, \"account-challenge-unavailable\");\n if (\n !object(input) ||\n Object.keys(input).some((key) => ![\"token\", \"password\", \"confirm\"].includes(key)) ||\n typeof input.token !== \"string\" ||\n !/^(?:[0-9]{6}|[a-f0-9]{64})$/i.test(input.token) ||\n (flow.purpose !== \"otp\" &&\n (typeof input.password !== \"string\" ||\n [...input.password].length < 12 ||\n [...input.password].length > 128 ||\n new TextEncoder().encode(input.password).byteLength > 1024 ||\n input.confirm !== input.password)) ||\n (flow.purpose === \"otp\" && (\"password\" in input || \"confirm\" in input))\n )\n return fail(400, \"invalid-account-verification\");\n if (++flow.attempts > 5) return fail(429, \"account-verification-rate-limit\");\n try {\n const response = await options.send(\n \"/auth/v1/challenge/verify\",\n JSON.stringify({\n challengeId: flow.id,\n purpose: flow.purpose,\n token: input.token,\n ...(flow.purpose !== \"otp\" ? { password: input.password } : {}),\n }),\n );\n if (!response.ok) {\n if (response.status >= 500) flow.unknown = true;\n if ([400, 422].includes(response.status))\n return fail(400, \"invalid-account-verification\");\n if (response.status === 409) return fail(409, \"account-challenge-unavailable\");\n return fail(\n response.status === 401 ? 401 : response.status === 429 ? 429 : 502,\n response.status === 401 ? \"invalid-account-code\" : \"account-verification-unknown\",\n );\n }\n // Any later parsing/session failure may follow a committed consumption.\n flow.unknown = true;\n return response;\n } catch (error) {\n if (!(error instanceof AccountFault)) flow.unknown = true;\n throw error;\n }\n },\n };\n}\n","app-host-plugin.ts":"import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { appSessionPlugin } from \"./app-session-plugin\";\nimport { createAppDataHost, type AppDataHostOptions } from \"./app-data-host\";\nimport { createLinkedBackend } from \"./linked-backend\";\n\n/** One session owner and one data perimeter, shared by the Vite adapters. */\nexport function appHostPlugins(options: Pick<AppDataHostOptions, \"authorize\"> = {}) {\n const channel = process.env.UIBOT_LINKED_APP_CHANNEL ?? \"development\";\n if (channel !== \"development\" && channel !== \"production\")\n throw Error(\"Invalid linked application channel\");\n const environment = process.env.UIBOT_DATA_ENV;\n const origin = process.env.UIBOT_LINKED_APP_SESSION_ORIGIN;\n if (environment && environment !== \"mock\" && !origin)\n throw Error(\"Real data requires an exact session host origin\");\n const legacySession = appSessionPlugin();\n let backend: ReturnType<typeof createLinkedBackend>;\n const data = createAppDataHost({\n origin: origin ?? \"http://127.0.0.1:5173\",\n channel,\n environment,\n upstreamsFile: process.env.UIBOT_DATA_UPSTREAMS_FILE,\n transportFile: process.env.UIBOT_ADMIN_TRANSPORT_FILE,\n session: legacySession.host,\n authorize: options.authorize,\n readRevision: () => backend.readRevision(),\n });\n backend = createLinkedBackend(\"app\", {\n hostView: { environment: data.environment, upstreams: data.privateConfig?.upstreams ?? {} },\n });\n return [\n ...(data.privateConfig ? [data.privateConfig.vitePlugin()] : []),\n legacySession.host\n ? legacySession\n : data.environment !== \"mock\"\n ? appSessionPlugin({ host: data.session, origin })\n : legacySession,\n {\n name: \"uibot-app-data-host\",\n configureServer(server: {\n httpServer: { once(event: \"close\", stop: () => void): void } | null;\n middlewares: {\n use(\n handler: (request: IncomingMessage, response: ServerResponse, next: () => void) => void,\n ): void;\n };\n }) {\n server.httpServer?.once(\"close\", () => {\n void data.dispose();\n });\n server.middlewares.use((request, response, next) => {\n if (request.url?.split(\"?\")[0] !== \"/api/uibot/data\") return next();\n void (async () => {\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers))\n if (typeof value === \"string\") headers.set(key, value);\n if (!origin || headers.get(\"host\") !== new URL(origin).host) throw Error();\n const result = await data.handle(\n new Request(origin + request.url, {\n method: request.method,\n headers,\n ...(![\"GET\", \"HEAD\"].includes(request.method ?? \"\")\n ? { body: Readable.toWeb(request), duplex: \"half\" }\n : {}),\n } as RequestInit),\n );\n response.statusCode = result.status;\n result.headers.forEach((value, key) => {\n response.setHeader(key, value);\n });\n response.end(await result.text());\n })().catch(() => {\n response.statusCode = 403;\n response.setHeader(\"content-type\", \"application/json\");\n response.end(\n JSON.stringify({\n error: { code: \"forbidden\", message: \"Data request is forbidden\" },\n }),\n );\n });\n });\n },\n },\n backend,\n ];\n}\n","app-data-host.ts":"import { createDataGatewayHandler, type DataUpstreams } from \"@uibot/application/data-gateway\";\nimport type { ConnectionBinding, DataOperation, UIBotSpec } from \"@uibot/contracts\";\nimport { createAppSessionHost } from \"./app-session\";\nimport { loadAppDataUpstreams } from \"./app-data-private\";\n\nexport interface AppDataHostOptions {\n origin: string;\n channel: \"development\" | \"production\";\n environment?: string;\n upstreamsFile?: string;\n transportFile?: string;\n trusted?: boolean;\n /** Server-only transport shared with revision reads and sessions by the owning host. */\n fetch?: typeof fetch;\n env?: Record<string, string | undefined>;\n session?: ReturnType<typeof createAppSessionHost>;\n readRevision(): Promise<{ revisionId: string; spec: UIBotSpec }>;\n authorize?(input: {\n user?: { id: string; email: string; role: string };\n connectionId: string;\n entityName: string;\n readonly binding: Readonly<ConnectionBinding>;\n upstreamAuth?: \"none\" | \"session\" | \"bearer\";\n operation: DataOperation;\n }): boolean | Promise<boolean>;\n}\n\n/** Server-owned revision, transports and session policy; browser input never selects a binding. */\nexport function createAppDataHost(options: AppDataHostOptions) {\n if (options.channel === \"production\" && (!options.environment || options.environment === \"mock\"))\n throw Error(\"Production data requires an explicit real environment\");\n const environment = options.environment ?? \"mock\";\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(environment)) throw Error(\"Invalid data environment\");\n const privateConfig =\n options.transportFile || (environment !== \"mock\" && options.upstreamsFile)\n ? loadAppDataUpstreams(\n environment !== \"mock\" ? options.upstreamsFile : undefined,\n environment,\n options.env ?? process.env,\n options.transportFile ? [options.transportFile] : [],\n )\n : undefined;\n const session =\n options.session ??\n createAppSessionHost({\n origin: options.origin,\n dataOnly: true,\n transportFile: options.transportFile,\n trusted: options.trusted,\n fetch: options.fetch,\n });\n const configuredUpstreams: DataUpstreams = privateConfig?.upstreams ?? Object.freeze({});\n const gateway = createDataGatewayHandler({\n channel: options.channel,\n environment,\n upstreams: configuredUpstreams,\n nowapiFetch: options.fetch,\n readRevision: options.readRevision,\n async authorize(input) {\n const context = await session.authorizeDataRequest(input.request);\n const allowed = options.authorize\n ? await options.authorize({\n user: context.user ? { ...context.user } : undefined,\n connectionId: input.connectionId,\n entityName: input.entityName,\n binding: input.binding,\n upstreamAuth: (() => {\n const upstream = configuredUpstreams[input.binding.upstream];\n return upstream && upstream.driver !== \"pg\" ? upstream.auth.type : undefined;\n })(),\n operation: input.operation,\n })\n : false;\n const current = await session.authorizeDataRequest(input.request);\n return {\n allowed:\n allowed &&\n current.user?.id === context.user?.id &&\n current.user?.role === context.user?.role &&\n current.user?.email === context.user?.email,\n headers: current.headers,\n };\n },\n });\n return {\n environment,\n session,\n readRevision: options.readRevision,\n privateConfig,\n async handle(request: Request): Promise<Response> {\n try {\n const url = new URL(request.url);\n if (\n url.origin !== options.origin ||\n url.pathname !== \"/api/uibot/data\" ||\n url.search ||\n request.method !== \"POST\"\n )\n throw Error();\n await session.authorizeDataRequest(request);\n } catch {\n return Response.json(\n { error: { code: \"forbidden\", message: \"Data request is forbidden\" } },\n { status: 403, headers: { \"cache-control\": \"no-store\" } },\n );\n }\n return gateway(request);\n },\n async dispose() {\n if (!options.session) session.dispose();\n await gateway.dispose();\n },\n };\n}\n","app-data-private.ts":"import { realpathSync, readdirSync, statSync } from \"node:fs\";\nimport { isAbsolute, resolve, sep } from \"node:path\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { loadDataUpstreamsFile } from \"@uibot/application/data-gateway\";\n\nconst privateTransports = new WeakMap<\n typeof fetch,\n {\n assertOutside(root: string): void;\n contains(file: string): boolean;\n }\n>();\n\n/** Associate server-only transport files with the exact transport selected by the host. */\nexport function registerPrivateServerTransport(send: typeof fetch, file: string): typeof fetch {\n const canonical = realpathSync(file);\n const identity = statSync(canonical);\n const guard = loadAppDataUpstreams(undefined, \"\", {}, [canonical]);\n privateTransports.set(send, {\n assertOutside: guard.assertOutside,\n contains(candidate) {\n try {\n const stat = statSync(candidate);\n return (\n realpathSync(candidate) === canonical ||\n (stat.dev === identity.dev && stat.ino === identity.ino)\n );\n } catch {\n return false;\n }\n },\n });\n return send;\n}\n\nexport function privateServerTransport(send: typeof fetch | undefined) {\n return send ? privateTransports.get(send) : undefined;\n}\n\n/** Keep the private loader's actual files out of both development and built public roots. */\nexport function loadAppDataUpstreams(\n file: string | undefined,\n environment: string,\n env: Record<string, string | undefined>,\n additionalFiles: readonly string[] = [],\n) {\n const files = new Set<string>();\n const track = (value: string) => {\n const path = realpathSync(value);\n files.add(path);\n return path;\n };\n for (const file of additionalFiles) track(file);\n const upstreams = file\n ? loadDataUpstreamsFile(track(file), environment, env, {\n resolveFile(reference, baseDirectory) {\n return track(resolve(baseDirectory, reference));\n },\n })\n : Object.freeze({});\n function privateFile(candidate: string): boolean {\n try {\n return files.has(realpathSync(candidate));\n } catch {\n return false;\n }\n }\n return {\n upstreams,\n assertOutside(publicRoot: string) {\n const root = realpathSync(publicRoot);\n if ([...files].some((file) => file === root || file.startsWith(root + sep)))\n throw Error(\"Private data configuration must be outside the public root\");\n },\n vitePlugin() {\n function checkPublicDirectory(directory: string | false, visited = new Set<string>()) {\n if (!directory) return;\n let entries: string[];\n try {\n directory = realpathSync(directory);\n if (visited.has(directory)) return;\n visited.add(directory);\n entries = readdirSync(directory);\n } catch {\n return;\n }\n for (const name of entries) {\n const path = resolve(directory, name);\n if (privateFile(path))\n throw Error(\"Private data file cannot be copied into public assets\");\n try {\n if (statSync(path).isDirectory()) checkPublicDirectory(path, visited);\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"Private data\")) throw error;\n }\n }\n }\n return {\n name: \"uibot-private-data-files\",\n enforce: \"pre\" as const,\n configResolved(config: { publicDir: string | false }) {\n checkPublicDirectory(config.publicDir);\n },\n load(id: string) {\n const path = id.split(\"?\")[0] ?? \"\";\n if (isAbsolute(path) && privateFile(path)) throw Error(\"Private data file denied\");\n },\n configureServer(server: {\n config: { root: string; publicDir: string | false };\n middlewares: {\n use(\n handler: (\n request: IncomingMessage,\n response: ServerResponse,\n next: () => void,\n ) => void,\n ): void;\n };\n }) {\n server.middlewares.use((request, response, next) => {\n let path = request.url?.split(\"?\")[0] ?? \"\";\n for (let n = 0; n < 4; n++) {\n try {\n const decoded = decodeURIComponent(path);\n if (decoded === path) break;\n path = decoded;\n } catch {\n path = \"\";\n break;\n }\n }\n const candidates = path.startsWith(\"/@fs/\")\n ? [path.slice(4)]\n : [\n resolve(server.config.root, `.${path}`),\n ...(server.config.publicDir\n ? [resolve(server.config.publicDir, `.${path}`)]\n : []),\n ];\n if (!candidates.some(privateFile)) return next();\n response.writeHead(403, {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n response.end(JSON.stringify({ message: \"Private data file denied.\" }));\n });\n },\n };\n },\n };\n}\n","app-server.ts":"import { createHash } from \"node:crypto\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { resolve, sep } from \"node:path\";\nimport { createAppDataHost, type AppDataHostOptions } from \"./app-data-host\";\nimport { privateServerTransport } from \"./app-data-private\";\nimport { createLinkedBackend } from \"./linked-backend\";\nimport { createAppSessionHost } from \"./app-session\";\nimport { createSessionStorage } from \"./app-session-storage\";\n\n/** Fixed-route application server, independent of Vite and its development middleware. */\nexport function createAppServer(options: {\n root: string;\n origin: string;\n authorize?: AppDataHostOptions[\"authorize\"];\n /** Explicit server-only transport; never selected by browser input or application Spec. */\n fetch?: typeof fetch;\n}) {\n if (options.fetch !== undefined && typeof options.fetch !== \"function\")\n throw Error(\"Invalid server transport\");\n const origin = new URL(options.origin);\n const loopback = [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(origin.hostname);\n if (\n origin.origin !== options.origin ||\n (origin.protocol !== \"https:\" && !(loopback && origin.protocol === \"http:\"))\n )\n throw Error(\"Host requires an exact HTTPS origin or local HTTP loopback\");\n const root = realpathSync(options.root);\n const transportPrivateFiles = privateServerTransport(options.fetch);\n transportPrivateFiles?.assertOutside(root);\n let session: ReturnType<typeof createAppSessionHost> | undefined;\n if (process.env.UIBOT_LINKED_APP_SESSIONS === \"true\") {\n const transportFile = process.env.UIBOT_ADMIN_TRANSPORT_FILE;\n const file = process.env.UIBOT_APP_SESSION_DB;\n const keyFile = process.env.UIBOT_APP_SESSION_KEY_FILE;\n if (\n !transportFile ||\n !file ||\n !keyFile ||\n process.env.UIBOT_LINKED_APP_SESSION_ORIGIN !== options.origin\n )\n throw Error(\n \"Server sessions require private transport, persistent storage, key and matching origin\",\n );\n const scope = createHash(\"sha256\")\n .update(options.origin)\n .update(readFileSync(transportFile))\n .digest(\"hex\");\n session = createAppSessionHost({\n origin: options.origin,\n transportFile,\n trusted: true,\n store: createSessionStorage({ file, keyFile, scope }),\n accountFlows: process.env.UIBOT_LINKED_APP_AUTH === \"true\",\n fetch: options.fetch,\n });\n }\n const channel = process.env.UIBOT_LINKED_APP_CHANNEL ?? \"development\";\n if (channel !== \"development\" && channel !== \"production\")\n throw Error(\"Invalid application channel\");\n let backend: ReturnType<typeof createLinkedBackend>;\n let data: ReturnType<typeof createAppDataHost> | undefined;\n try {\n data = createAppDataHost({\n origin: options.origin,\n channel,\n environment: process.env.UIBOT_DATA_ENV,\n upstreamsFile: process.env.UIBOT_DATA_UPSTREAMS_FILE,\n transportFile: process.env.UIBOT_ADMIN_TRANSPORT_FILE,\n trusted: true,\n session,\n authorize: options.authorize,\n fetch: options.fetch,\n readRevision: () => backend.readRevision(),\n });\n data.privateConfig?.assertOutside(root);\n backend = createLinkedBackend(\"app\", {\n trusted: true,\n fetch: options.fetch,\n hostView: { environment: data.environment, upstreams: data.privateConfig?.upstreams ?? {} },\n });\n } catch (error) {\n session?.dispose();\n void data?.dispose();\n throw error;\n }\n const dataHost = data;\n const proxy = backend.middleware;\n const security = {\n \"X-Content-Type-Options\": \"nosniff\",\n \"Referrer-Policy\": \"no-referrer\",\n \"Content-Security-Policy\":\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\",\n ...(origin.protocol === \"https:\" ? { \"Strict-Transport-Security\": \"max-age=31536000\" } : {}),\n };\n const json = (status: number, message: string) =>\n Response.json({ message }, { status, headers: { \"Cache-Control\": \"no-store\" } });\n async function handle(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname === \"/healthz\" && request.method === \"GET\") return json(200, \"ready\");\n if (request.headers.get(\"host\") !== origin.host) return json(403, \"Host denied.\");\n const path = url.pathname;\n if (/%|\\\\|\\/\\./.test(path)) return json(400, \"Invalid route.\");\n if (path === \"/api/uibot/data\")\n return dataHost.handle(new Request(options.origin + path + url.search, request));\n if (/^\\/api\\/(app-session|shadcn-admin)(\\/|$)/.test(path)) {\n const owner =\n session ??\n (dataHost.environment !== \"mock\" && path.startsWith(\"/api/app-session\")\n ? dataHost.session\n : undefined);\n return owner\n ? owner.handle(new Request(options.origin + path + url.search, request))\n : json(503, \"Business service unavailable.\");\n }\n if ([\"/linked-app-config.json\", \"/linked-app.json\"].includes(path)) {\n if (url.search) return json(400, \"Invalid query.\");\n return new Promise<Response>((done) => {\n const headers = new Headers();\n const response = {\n statusCode: 200,\n setHeader(k: string, v: string) {\n headers.set(k, v);\n },\n end(body?: string) {\n done(new Response(body, { status: response.statusCode, headers }));\n },\n };\n proxy(\n { url: path, method: request.method, headers: Object.fromEntries(request.headers) },\n response,\n () => done(json(404, \"Not found.\")),\n );\n });\n }\n if (![\"GET\", \"HEAD\"].includes(request.method)) return json(405, \"Method not allowed.\");\n if (/^\\/(api|src|node_modules|@)(\\/|$)/.test(path)) return json(404, \"Not found.\");\n let candidate = resolve(root, `.${path}`);\n try {\n candidate = realpathSync(candidate);\n if (candidate !== root && !candidate.startsWith(root + sep)) return json(404, \"Not found.\");\n } catch {\n if (!request.headers.get(\"accept\")?.includes(\"text/html\") || /\\.[^/]+$/.test(path))\n return json(404, \"Not found.\");\n candidate = resolve(root, \"index.html\");\n }\n if (candidate === root || path === \"/\") candidate = resolve(root, \"index.html\");\n try {\n candidate = realpathSync(candidate);\n if (candidate === root || !candidate.startsWith(root + sep)) return json(404, \"Not found.\");\n } catch {\n return json(404, \"Not found.\");\n }\n const file = Bun.file(candidate);\n if (transportPrivateFiles?.contains(candidate)) return json(404, \"Not found.\");\n if (!(await file.exists())) return json(404, \"Not found.\");\n return new Response(request.method === \"HEAD\" ? null : file, {\n headers: {\n \"Content-Type\": file.type,\n \"Cache-Control\": candidate.endsWith(\".html\") ? \"no-store\" : \"public, max-age=3600\",\n },\n });\n }\n return {\n async dispose() {\n session?.dispose();\n await dataHost.dispose();\n },\n async handle(request: Request) {\n let response: Response;\n try {\n response = await handle(request);\n } catch {\n response = json(503, \"Service unavailable.\");\n }\n for (const [key, value] of Object.entries(security)) response.headers.set(key, value);\n return response;\n },\n };\n}\n\nexport function startAppServer(\n options: { authorize?: AppDataHostOptions[\"authorize\"]; fetch?: typeof fetch } = {},\n) {\n process.umask(0o077);\n const origin = process.env.UIBOT_APP_ORIGIN;\n if (\n !origin ||\n !process.env.UIBOT_LINKED_APP_CONNECTION_FILE ||\n !process.env.UIBOT_LINKED_APP_BEARER\n )\n throw Error(\n \"Configure application origin, connection file and server-only Viewer authorization\",\n );\n if (\n ![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(new URL(origin).hostname) &&\n process.env.UIBOT_LINKED_APP_CHANNEL !== \"production\"\n )\n throw Error(\"Public application hosts require the production release channel\");\n const port = Number(process.env.PORT ?? \"8080\");\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error(\"Invalid server port\");\n const app = createAppServer({\n root: resolve(\"dist\"),\n origin,\n authorize: options.authorize,\n fetch: options.fetch,\n });\n const server = Bun.serve({\n hostname:\n process.env.HOST ??\n ([\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(new URL(origin).hostname)\n ? new URL(origin).hostname.replace(/^\\[|\\]$/g, \"\")\n : \"0.0.0.0\"),\n port,\n maxRequestBodySize: 65536,\n fetch: app.handle,\n });\n const stop = async () => {\n server.stop(true);\n try {\n await app.dispose();\n process.exit(0);\n } catch {\n process.exit(1);\n }\n };\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGINT\", stop);\n console.log(`UIBot application listening on port ${port}`);\n}\n\nif (import.meta.main) {\n startAppServer();\n}\n","app-session-storage.ts":"import { Database } from \"bun:sqlite\";\nimport { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport { chmodSync, lstatSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type { AppSession } from \"./app-session\";\n\n/** Single-process store. SQLite owns the writer lock; credentials are encrypted at rest. */\nexport function createSessionStorage(options: { file: string; keyFile: string; scope: string }) {\n const file = resolve(options.file);\n const parent = lstatSync(dirname(file));\n const keyStat = lstatSync(options.keyFile);\n if (\n !parent.isDirectory() ||\n parent.isSymbolicLink() ||\n parent.mode & 0o077 ||\n !keyStat.isFile() ||\n keyStat.isSymbolicLink() ||\n keyStat.mode & 0o077\n )\n throw Error(\"Session directory and encryption key must be private\");\n try {\n const stat = lstatSync(file);\n if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077)\n throw Error(\"Session database must be a private regular file\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n const raw = readFileSync(options.keyFile, \"utf8\").trim();\n if (!/^[a-f0-9]{64}$/.test(raw)) throw Error(\"Session key must contain 32 random bytes as hex\");\n const key = Buffer.from(raw, \"hex\");\n const aad = Buffer.from(`uibot.host-sessions.v1:${options.scope}`);\n const db = new Database(file, { create: true, strict: true });\n chmodSync(file, 0o600);\n try {\n db.exec(\n \"PRAGMA busy_timeout=0; PRAGMA journal_mode=DELETE; PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY CHECK(id=1), payload BLOB NOT NULL); COMMIT;\",\n );\n } catch {\n db.close();\n throw Error(\"Session database is unavailable or owned by another host\");\n }\n return {\n load(): [string, AppSession][] {\n try {\n const row = db.query(\"SELECT payload FROM sessions WHERE id=1\").get() as {\n payload: Uint8Array;\n } | null;\n if (!row) return [];\n const bytes = Buffer.from(row.payload);\n if (bytes.length < 29 || bytes.length > 8_000_000) throw Error();\n const decipher = createDecipheriv(\"aes-256-gcm\", key, bytes.subarray(0, 12));\n decipher.setAAD(aad);\n decipher.setAuthTag(bytes.subarray(12, 28));\n const entries = JSON.parse(\n Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString(),\n );\n if (\n !Array.isArray(entries) ||\n entries.length > 100 ||\n entries.some(\n (entry) =>\n !Array.isArray(entry) ||\n entry.length !== 2 ||\n !/^[A-Za-z0-9_-]{43}$/.test(entry[0]) ||\n !entry[1] ||\n typeof entry[1].csrf !== \"string\" ||\n !Number.isFinite(entry[1].expires) ||\n entry[1].closed !== false ||\n entry[1].busy ||\n entry[1].refreshing,\n )\n )\n throw Error();\n return entries;\n } catch {\n db.close();\n throw Error(\"Session storage cannot be authenticated; restore its original key and scope\");\n }\n },\n save(entries: [string, AppSession][]) {\n const plain = Buffer.from(JSON.stringify(entries));\n if (entries.length > 100 || plain.length > 7_999_000)\n throw Error(\"Session capacity exceeded\");\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n cipher.setAAD(aad);\n const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]);\n db.query(\"INSERT OR REPLACE INTO sessions (id,payload) VALUES (1,?)\").run(\n Buffer.concat([iv, cipher.getAuthTag(), ciphertext]),\n );\n },\n close() {\n db.close();\n key.fill(0);\n },\n };\n}\n","doon-egress.ts":"import { closeSync, fstatSync, openSync, readFileSync, constants } from \"node:fs\";\nimport { registerPrivateServerTransport } from \"./app-data-private\";\n\nconst requestLimit = 65_536;\nconst responseLimit = 32_000_000;\nconst headerLimit = 32_768;\nconst framingLimit = Math.ceil(responseLimit / 3) * 4 + headerLimit * 6 + 4096;\nconst failure = () => new Error(\"Controlled server transport unavailable\");\nconst record = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst text = (value: unknown, max: number): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\r\\n\\0]/.test(value);\n\nasync function bytes(\n body: ReadableStream<Uint8Array> | null,\n limit: number,\n signal: AbortSignal,\n): Promise<Uint8Array> {\n if (!body) return new Uint8Array();\n const reader = body.getReader();\n const abort = () => {\n void reader.cancel().catch(() => {});\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n let size = 0;\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n signal.throwIfAborted();\n const chunk = await reader.read();\n if (chunk.done) break;\n size += chunk.value.byteLength;\n if (size > limit) throw failure();\n chunks.push(chunk.value);\n }\n return Buffer.concat(chunks, size);\n } catch {\n await reader.cancel().catch(() => {});\n throw failure();\n } finally {\n reader.releaseLock();\n signal.removeEventListener(\"abort\", abort);\n }\n}\nfunction pairs(value: unknown): [string, string][] {\n if (!Array.isArray(value)) throw failure();\n const result: [string, string][] = [];\n const names = new Set<string>();\n let size = 0;\n for (const pair of value) {\n if (\n !Array.isArray(pair) ||\n pair.length !== 2 ||\n !text(pair[0], headerLimit) ||\n typeof pair[1] !== \"string\" ||\n /[\\r\\n\\0]/.test(pair[1])\n )\n throw failure();\n const name = pair[0].toLowerCase();\n if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(name) || names.has(name)) throw failure();\n names.add(name);\n size += Buffer.byteLength(pair[0]) + Buffer.byteLength(pair[1]) + 4;\n if (size > headerLimit) throw failure();\n result.push([pair[0], pair[1]]);\n }\n return result;\n}\n\n/** Optional native host adapter. This file and its bootstrap are server-only. */\nexport function createDoonEgressFetch(file: string): typeof fetch {\n let bootstrap: Record<string, unknown>;\n let endpoint: URL;\n let origin: string;\n try {\n const descriptor = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n const stat = fstatSync(descriptor);\n if (!stat.isFile() || (stat.mode & 0o177) !== 0 || stat.size > 65_536) throw failure();\n const parsed: unknown = JSON.parse(readFileSync(descriptor, \"utf8\"));\n if (\n !record(parsed) ||\n Object.keys(parsed).sort().join() !==\n [\"schema\", \"endpoint\", \"ca_pem\", \"grant\", \"policy_id\", \"policy_revision\", \"origin\"]\n .sort()\n .join() ||\n parsed.schema !== \"doon.egress-bootstrap.v1\" ||\n !text(parsed.endpoint, 2048) ||\n !text(parsed.origin, 2048) ||\n !text(parsed.grant, 16_384) ||\n !text(parsed.policy_id, 256) ||\n !Number.isSafeInteger(parsed.policy_revision) ||\n Number(parsed.policy_revision) < 1 ||\n typeof parsed.ca_pem !== \"string\" ||\n !parsed.ca_pem.includes(\"-----BEGIN CERTIFICATE-----\")\n )\n throw failure();\n bootstrap = parsed;\n } finally {\n closeSync(descriptor);\n }\n endpoint = new URL(String(bootstrap.endpoint));\n const target = new URL(String(bootstrap.origin));\n if (\n endpoint.protocol !== \"https:\" ||\n endpoint.pathname !== \"/v1/egress/fetch\" ||\n endpoint.username ||\n endpoint.password ||\n endpoint.search ||\n endpoint.hash ||\n target.protocol !== \"https:\" ||\n target.origin !== bootstrap.origin ||\n target.username ||\n target.password\n )\n throw failure();\n origin = target.origin;\n } catch {\n throw failure();\n }\n const send: typeof fetch = Object.assign(\n async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n try {\n const request =\n input instanceof Request ? new Request(input, init) : new Request(String(input), init);\n const url = new URL(request.url);\n if (url.origin !== origin || url.username || url.password || url.hash) throw failure();\n const signal = AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]);\n signal.throwIfAborted();\n const body = await bytes(request.body, requestLimit, signal);\n signal.throwIfAborted();\n const response = await fetch(endpoint, {\n method: \"POST\",\n redirect: \"error\",\n signal,\n tls: { ca: String(bootstrap.ca_pem), rejectUnauthorized: true },\n headers: {\n authorization: `Bearer ${bootstrap.grant}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n schema: \"doon.egress-request.v1\",\n policy_id: bootstrap.policy_id,\n policy_revision: bootstrap.policy_revision,\n method: request.method,\n path: url.pathname + url.search,\n headers: pairs([...request.headers]),\n body_base64: Buffer.from(body).toString(\"base64\"),\n }),\n });\n if (response.status !== 200) {\n await response.body?.cancel();\n throw failure();\n }\n const envelope: unknown = JSON.parse(\n Buffer.from(await bytes(response.body, framingLimit, signal)).toString(\"utf8\"),\n );\n signal.throwIfAborted();\n if (\n !record(envelope) ||\n Object.keys(envelope).sort().join() !==\n [\"schema\", \"status\", \"headers\", \"body_base64\"].sort().join() ||\n envelope.schema !== \"doon.egress-response.v1\" ||\n !Number.isInteger(envelope.status) ||\n Number(envelope.status) < 200 ||\n Number(envelope.status) > 599 ||\n (Number(envelope.status) >= 300 && Number(envelope.status) < 400) ||\n typeof envelope.body_base64 !== \"string\" ||\n envelope.body_base64.length > Math.ceil(responseLimit / 3) * 4 ||\n /[^A-Za-z0-9+/=]/.test(envelope.body_base64)\n )\n throw failure();\n const decoded = Buffer.from(envelope.body_base64, \"base64\");\n if (\n decoded.byteLength > responseLimit ||\n decoded.toString(\"base64\") !== envelope.body_base64\n )\n throw failure();\n const headers = pairs(envelope.headers);\n if (\n headers.some(\n ([name]) =>\n ![\"content-type\", \"cache-control\", \"etag\", \"retry-after\"].includes(\n name.toLowerCase(),\n ),\n )\n )\n throw failure();\n const status = Number(envelope.status);\n if ([204, 205, 304].includes(status) && decoded.byteLength) throw failure();\n return new Response([204, 205, 304].includes(status) ? null : decoded, { status, headers });\n } catch {\n throw failure();\n }\n },\n {\n preconnect() {\n throw failure();\n },\n },\n );\n return registerPrivateServerTransport(send, file);\n}\n","src/app-styles.css":"@import \"tailwindcss\" source(none);\n@source \"./\";\n@source \"../node_modules/@uibot\";\n@source \"../uibot.app.json\";\n@custom-variant dark (&:where(.dark, .dark *));\n@theme inline {\n --color-background: var(--background);\n --color-foreground: var(--foreground);\n --color-card: var(--card);\n --color-card-foreground: var(--foreground);\n --color-popover: var(--background);\n --color-popover-foreground: var(--foreground);\n --color-primary: var(--primary);\n --color-primary-foreground: var(--primary-foreground);\n --color-muted: var(--muted);\n --color-muted-foreground: var(--muted-foreground);\n --color-border: var(--border);\n --color-input: var(--border);\n --color-ring: var(--ring);\n --color-accent: var(--muted);\n --color-accent-foreground: var(--foreground);\n --color-destructive: #dc2626;\n}\n","src/uibot-modules/local-about.tsx":"import { useState } from \"react\";\nexport default function Example() {\n const [count, setCount] = useState(0);\n return (\n <section>\n <h1>Installed TSX page</h1>\n <button type=\"button\" onClick={() => setCount((value) => value + 1)}>\n TSX page counter: {count}\n </button>\n </section>\n );\n}\n","app.html":"<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Linked application consumer</title>\n </head>\n <body><div id=\"root\"></div><script type=\"module\" src=\"/src/app.tsx\"></script></body>\n</html>\n","index.html":"<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Linked application consumer</title>\n </head>\n <body><div id=\"root\"></div><script type=\"module\" src=\"/src/app.tsx\"></script></body>\n</html>\n"}}