@panomc/theme-core 1.0.0-dev.60 → 1.0.0-dev.62

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 (308) hide show
  1. package/assets/css/pano-fallback-legacy.css +12381 -0
  2. package/assets/css/pano-fallback.css +3222 -0
  3. package/bin/__tests__/check/fixtures/plugin-contracts/market/controllers.json +4 -0
  4. package/bin/__tests__/check/fixtures/plugin-contracts/market/views.json +67 -0
  5. package/bin/__tests__/check/fixtures/routes.json +5 -0
  6. package/bin/__tests__/check/helpers.js +55 -0
  7. package/bin/__tests__/check/overrides.test.js +287 -0
  8. package/bin/__tests__/check/theme.test.js +332 -0
  9. package/bin/__tests__/cli/accept-and-list.test.js +159 -0
  10. package/bin/__tests__/cli/config-edit.test.js +213 -0
  11. package/bin/__tests__/cli/contracts-pull.test.js +187 -0
  12. package/bin/__tests__/cli/core-meta.test.js +305 -0
  13. package/bin/__tests__/cli/eject-view.test.js +356 -0
  14. package/bin/__tests__/cli/helpers.js +258 -0
  15. package/bin/__tests__/scaffold/scaffold.test.js +84 -0
  16. package/bin/bundle-internal-libs.js +14 -2
  17. package/bin/check.js +1150 -213
  18. package/bin/contracts.js +1643 -0
  19. package/bin/generate-contract.js +378 -0
  20. package/bin/generate-licenses.js +14 -2
  21. package/bin/generate-runtime-shims.js +27 -9
  22. package/bin/new.js +101 -2
  23. package/bin/package-zip.js +16 -2
  24. package/bin/sync.js +360 -7
  25. package/bin/theme-core.js +65 -107
  26. package/lang/en-US.json +1 -0
  27. package/lang/ru.json +1 -0
  28. package/lang/tr.json +1 -0
  29. package/package.json +8 -9
  30. package/skin-contract.json +864 -19
  31. package/src/kit/__tests__/hooks-server-fetch.test.js +56 -0
  32. package/src/kit/__tests__/route-map.test.js +154 -0
  33. package/src/kit/__tests__/theme-meta.test.js +249 -0
  34. package/src/kit/hooks-client.js +3 -0
  35. package/src/kit/hooks-server.js +79 -21
  36. package/src/kit/route-map.js +300 -0
  37. package/src/kit/specifiers.js +3 -62
  38. package/src/kit/svelte-config.js +3 -0
  39. package/src/kit/theme-meta.js +405 -0
  40. package/src/kit/vite-config.js +156 -12
  41. package/src/lib/NotificationManager.js +18 -0
  42. package/src/lib/PluginAPI.js +313 -9
  43. package/src/lib/Store.js +18 -5
  44. package/src/lib/__tests__/avatarVersion.test.js +25 -0
  45. package/src/lib/__tests__/check.test.js +201 -0
  46. package/src/lib/__tests__/controllerHost.test.js +363 -0
  47. package/src/lib/__tests__/cx03.test.js +245 -0
  48. package/src/lib/__tests__/engineBoot.test.js +151 -0
  49. package/src/lib/__tests__/engineParts.helper.js +284 -0
  50. package/src/lib/__tests__/engineParts.test.js +179 -0
  51. package/src/lib/__tests__/engineSidebars.helper.js +353 -0
  52. package/src/lib/__tests__/engineSidebars.test.js +273 -0
  53. package/src/lib/__tests__/engineStyles.test.js +227 -0
  54. package/src/lib/__tests__/engineWiring.test.js +1000 -0
  55. package/src/lib/__tests__/fallbackStyles.test.js +1254 -0
  56. package/src/lib/__tests__/fixtures/Probe.svelte +5 -0
  57. package/src/lib/__tests__/fixtures/engine-parts.ssr.json +29 -0
  58. package/src/lib/__tests__/fixtures/engine-sidebars.ssr.json +16 -0
  59. package/src/lib/__tests__/home.test.js +563 -0
  60. package/src/lib/__tests__/injectedScope.test.js +490 -0
  61. package/src/lib/__tests__/languageConcurrency.test.js +55 -0
  62. package/src/lib/__tests__/languageLayers.test.js +286 -0
  63. package/src/lib/__tests__/pageHead.test.js +167 -0
  64. package/src/lib/__tests__/pageMeta.util.test.js +216 -0
  65. package/src/lib/__tests__/pageTitle.util.test.js +96 -0
  66. package/src/lib/__tests__/pluginApiViews.test.js +529 -0
  67. package/src/lib/__tests__/plugins.test.js +53 -0
  68. package/src/lib/__tests__/profileNav.util.test.js +145 -0
  69. package/src/lib/__tests__/registryReady.test.js +26 -0
  70. package/src/lib/__tests__/returnTo.util.test.js +294 -0
  71. package/src/lib/__tests__/routeConfig.test.js +361 -0
  72. package/src/lib/__tests__/sidebarSpec.util.test.js +152 -0
  73. package/src/lib/__tests__/skinContract.test.js +558 -0
  74. package/src/lib/__tests__/svelteSsr.helper.js +68 -0
  75. package/src/lib/__tests__/tc03.test.js +427 -0
  76. package/src/lib/__tests__/tc11.test.js +184 -0
  77. package/src/lib/__tests__/translationLayers.test.js +161 -0
  78. package/src/lib/avatarVersion.js +39 -0
  79. package/src/lib/components/Breadcrumb.svelte +9 -40
  80. package/src/lib/components/Date.svelte +1 -1
  81. package/src/lib/components/DefaultToast.svelte +13 -3
  82. package/src/lib/components/FallbackLinks.svelte +28 -0
  83. package/src/lib/components/FallbackScope.svelte +24 -0
  84. package/src/lib/components/Footer.svelte +8 -8
  85. package/src/lib/components/Header.svelte +3 -3
  86. package/src/lib/components/Hook.svelte +12 -1
  87. package/src/lib/components/LoginFormBody.svelte +5 -5
  88. package/src/lib/components/Main.svelte +22 -47
  89. package/src/lib/components/Navbar.svelte +30 -29
  90. package/src/lib/components/NoContent.svelte +2 -2
  91. package/src/lib/components/NotificationContainer.svelte +31 -82
  92. package/src/lib/components/OnlineAdmins.svelte +3 -2
  93. package/src/lib/components/PageActions.svelte +1 -1
  94. package/src/lib/components/PageHead.svelte +50 -0
  95. package/src/lib/components/PageTitle.svelte +2 -2
  96. package/src/lib/components/Pagination.svelte +6 -6
  97. package/src/lib/components/PlayerHead.svelte +4 -4
  98. package/src/lib/components/PluginBlock.svelte +132 -0
  99. package/src/lib/components/PluginSlot.svelte +40 -0
  100. package/src/lib/components/Post.svelte +13 -230
  101. package/src/lib/components/Posts.svelte +7 -14
  102. package/src/lib/components/RegisterForm.svelte +12 -11
  103. package/src/lib/components/Sidebar.svelte +9 -7
  104. package/src/lib/components/TicketRow.svelte +8 -48
  105. package/src/lib/components/TicketStatus.svelte +10 -16
  106. package/src/lib/components/Tickets.svelte +8 -30
  107. package/src/lib/components/Toast.svelte +16 -14
  108. package/src/lib/components/ToastContainer.svelte +16 -9
  109. package/src/lib/components/ViewComponent.svelte +13 -1
  110. package/src/lib/components/modals/CloseTicketConfirmModal.svelte +15 -46
  111. package/src/lib/components/modals/ConfirmRemoveAllNotificationsModal.svelte +17 -39
  112. package/src/lib/components/modals/LogoutSessionConfirmModal.svelte +12 -30
  113. package/src/lib/components/sidebars/HomeSidebar.svelte +33 -284
  114. package/src/lib/components/sidebars/PlayerDetailSidebar.svelte +14 -63
  115. package/src/lib/components/sidebars/PluginSidebar.svelte +21 -0
  116. package/src/lib/components/sidebars/ProfileNavCard.svelte +24 -0
  117. package/src/lib/components/sidebars/ProfileSidebar.svelte +44 -84
  118. package/src/lib/components/sidebars/SupportSidebar.svelte +19 -22
  119. package/src/lib/components/sidebars/TicketCreateAndDetailSidebar.svelte +23 -35
  120. package/src/lib/components/sidebars/profileNav.util.js +105 -0
  121. package/src/lib/components/sidebars/sidebarSpec.util.js +92 -0
  122. package/src/lib/controllerHost.js +261 -0
  123. package/src/lib/fallbackStyles.js +317 -0
  124. package/src/lib/home.js +202 -0
  125. package/src/lib/language.util.js +70 -37
  126. package/src/lib/layouts/AppLayout.svelte +16 -8
  127. package/src/lib/layouts/AuthLayout.svelte +6 -4
  128. package/src/lib/layouts/MainLayout.svelte +17 -12
  129. package/src/lib/layouts/ProfileLayout.svelte +6 -4
  130. package/src/lib/layouts/ThemeSettingsLayout.svelte +6 -4
  131. package/src/lib/layouts/TicketsLayout.svelte +6 -5
  132. package/src/lib/pageMeta.util.js +212 -0
  133. package/src/lib/pageShape.js +33 -0
  134. package/src/lib/pageTitle.util.js +32 -0
  135. package/src/lib/pages/ActivateEmailPage.svelte +2 -7
  136. package/src/lib/pages/ConfirmNewEmailPage.svelte +2 -7
  137. package/src/lib/pages/ErrorPage.svelte +5 -2
  138. package/src/lib/pages/HomePage.svelte +31 -8
  139. package/src/lib/pages/LoginPage.svelte +38 -41
  140. package/src/lib/pages/NotificationsPage.svelte +2 -7
  141. package/src/lib/pages/PlayerDetailPage.svelte +2 -7
  142. package/src/lib/pages/PostDetailPage.svelte +2 -7
  143. package/src/lib/pages/PreviewPostPage.svelte +2 -7
  144. package/src/lib/pages/RegisterPage.svelte +10 -13
  145. package/src/lib/pages/RenewPasswordPage.svelte +2 -7
  146. package/src/lib/pages/ResetPasswordPage.svelte +2 -7
  147. package/src/lib/pages/RulesPage.svelte +3 -8
  148. package/src/lib/pages/SupportPage.svelte +2 -7
  149. package/src/lib/pages/ThemeSettingsPage.svelte +2 -7
  150. package/src/lib/pages/profile/ProfilePage.svelte +2 -7
  151. package/src/lib/pages/profile/SettingsPage.svelte +2 -7
  152. package/src/lib/pages/profile/TicketsPage.svelte +2 -7
  153. package/src/lib/pages/ticket/CreateTicketPage.svelte +2 -7
  154. package/src/lib/pages/ticket/TicketDetailPage.svelte +2 -7
  155. package/src/lib/plugins.js +61 -0
  156. package/src/lib/returnTo.util.js +116 -0
  157. package/src/lib/services/auth.js +11 -11
  158. package/src/lib/services/posts.js +21 -10
  159. package/src/lib/services/profile.js +5 -5
  160. package/src/lib/services/theme-setting.js +1 -1
  161. package/src/lib/services/tickets.js +36 -15
  162. package/src/lib/siteRealtime.js +55 -8
  163. package/src/lib/themePageLoad.js +38 -0
  164. package/src/lib/translationLayers.js +144 -0
  165. package/src/lib/ui-logics/layout-logics/AppLayoutLogics.js +160 -6
  166. package/src/lib/ui-logics/layout-logics/AuthLayoutLogics.js +3 -2
  167. package/src/lib/ui-logics/layout-logics/ProfileLayoutLogics.js +3 -2
  168. package/src/lib/ui-logics/layout-logics/TicketsLayoutLogics.js +3 -2
  169. package/src/lib/ui-logics/page-logics/ActiveEmailPageLogics.js +4 -4
  170. package/src/lib/ui-logics/page-logics/ConfirmNewEmailPageLogics.js +4 -4
  171. package/src/lib/ui-logics/page-logics/CreateTicketPageLogics.js +5 -5
  172. package/src/lib/ui-logics/page-logics/HomePageLogics.js +5 -3
  173. package/src/lib/ui-logics/page-logics/NotificationsPageLogics.js +40 -16
  174. package/src/lib/ui-logics/page-logics/PlayerDetailPageLogics.js +3 -3
  175. package/src/lib/ui-logics/page-logics/PostDetailPageLogics.js +3 -3
  176. package/src/lib/ui-logics/page-logics/PreviewPostPageLogics.js +1 -1
  177. package/src/lib/ui-logics/page-logics/RenewPasswordPageLogics.js +4 -4
  178. package/src/lib/ui-logics/page-logics/ResetPasswordPageLogics.js +6 -6
  179. package/src/lib/ui-logics/page-logics/SettingsPageLogics.js +8 -8
  180. package/src/lib/ui-logics/page-logics/TicketDetailPageLogics.js +3 -3
  181. package/src/lib/ui-logics/page-logics/TicketsPageLogics.js +5 -3
  182. package/src/lib/views/ActivateEmailView.samples.js +22 -0
  183. package/src/lib/views/ActivateEmailView.svelte +4 -4
  184. package/src/lib/views/AppLayoutView.samples.js +17 -0
  185. package/src/lib/views/AppLayoutView.svelte +1 -1
  186. package/src/lib/views/AuthLayoutView.samples.js +4 -0
  187. package/src/lib/views/AuthLayoutView.svelte +1 -1
  188. package/src/lib/views/Breadcrumb.samples.js +15 -0
  189. package/src/lib/views/CloseTicketConfirmModal.samples.js +12 -0
  190. package/src/lib/views/ConfirmNewEmailView.samples.js +22 -0
  191. package/src/lib/views/ConfirmNewEmailView.svelte +4 -4
  192. package/src/lib/views/ConfirmRemoveAllNotificationsModal.samples.js +9 -0
  193. package/src/lib/views/CreateTicketView.samples.js +21 -0
  194. package/src/lib/views/CreateTicketView.svelte +5 -5
  195. package/src/lib/views/Date.samples.js +9 -0
  196. package/src/lib/views/DefaultToast.samples.js +7 -0
  197. package/src/lib/views/ErrorView.samples.js +8 -0
  198. package/src/lib/views/ErrorView.svelte +4 -2
  199. package/src/lib/views/Footer.samples.js +8 -0
  200. package/src/lib/views/Header.samples.js +8 -0
  201. package/src/lib/views/HomeSidebar.samples.js +59 -0
  202. package/src/lib/views/HomeView.samples.js +34 -0
  203. package/src/lib/views/HomeView.svelte +14 -6
  204. package/src/lib/views/LoginFormBody.samples.js +8 -0
  205. package/src/lib/views/LoginView.samples.js +50 -0
  206. package/src/lib/views/LoginView.svelte +24 -22
  207. package/src/lib/views/LogoutSessionConfirmModal.samples.js +8 -0
  208. package/src/lib/views/Main.samples.js +23 -0
  209. package/src/lib/views/MainLayoutView.svelte +3 -4
  210. package/src/lib/views/Navbar.samples.js +8 -0
  211. package/src/lib/views/NoContent.samples.js +7 -0
  212. package/src/lib/views/NotificationContainer.samples.js +25 -0
  213. package/src/lib/views/NotificationsView.samples.js +36 -0
  214. package/src/lib/views/NotificationsView.svelte +21 -12
  215. package/src/lib/views/PageActions.samples.js +7 -0
  216. package/src/lib/views/PageTitle.samples.js +8 -0
  217. package/src/lib/views/Pagination.samples.js +7 -0
  218. package/src/lib/views/PlayerDetailSidebar.samples.js +35 -0
  219. package/src/lib/views/PlayerDetailView.samples.js +8 -0
  220. package/src/lib/views/PlayerDetailView.svelte +3 -3
  221. package/src/lib/views/PlayerHead.samples.js +8 -0
  222. package/src/lib/views/Post.samples.js +10 -0
  223. package/src/lib/views/PostDetailView.samples.js +28 -0
  224. package/src/lib/views/PostDetailView.svelte +24 -16
  225. package/src/lib/views/Posts.samples.js +9 -0
  226. package/src/lib/views/PreviewPostView.samples.js +20 -0
  227. package/src/lib/views/PreviewPostView.svelte +10 -10
  228. package/src/lib/views/ProfileLayoutView.samples.js +4 -0
  229. package/src/lib/views/ProfileSidebar.samples.js +33 -0
  230. package/src/lib/views/ProfileView.samples.js +29 -0
  231. package/src/lib/views/ProfileView.svelte +2 -2
  232. package/src/lib/views/RegisterForm.samples.js +7 -0
  233. package/src/lib/views/RegisterView.samples.js +28 -0
  234. package/src/lib/views/RegisterView.svelte +5 -3
  235. package/src/lib/views/RenewPasswordView.samples.js +24 -0
  236. package/src/lib/views/RenewPasswordView.svelte +6 -6
  237. package/src/lib/views/ResetPasswordView.samples.js +24 -0
  238. package/src/lib/views/ResetPasswordView.svelte +3 -3
  239. package/src/lib/views/RulesView.samples.js +14 -0
  240. package/src/lib/views/RulesView.svelte +3 -3
  241. package/src/lib/views/SettingsView.svelte +48 -17
  242. package/src/lib/views/Sidebar.samples.js +7 -0
  243. package/src/lib/views/SupportSidebar.samples.js +24 -0
  244. package/src/lib/views/SupportView.samples.js +16 -0
  245. package/src/lib/views/SupportView.svelte +8 -6
  246. package/src/lib/views/ThemeSettingsLayoutView.samples.js +9 -0
  247. package/src/lib/views/ThemeSettingsLayoutView.svelte +1 -1
  248. package/src/lib/views/ThemeSettingsView.svelte +89 -89
  249. package/src/lib/views/TicketCreateAndDetailSidebar.samples.js +33 -0
  250. package/src/lib/views/TicketDetailView.samples.js +34 -0
  251. package/src/lib/views/TicketDetailView.svelte +17 -15
  252. package/src/lib/views/TicketRow.samples.js +10 -0
  253. package/src/lib/views/TicketStatus.samples.js +8 -0
  254. package/src/lib/views/Tickets.samples.js +9 -0
  255. package/src/lib/views/TicketsLayoutView.samples.js +4 -0
  256. package/src/lib/views/TicketsView.samples.js +23 -0
  257. package/src/lib/views/TicketsView.svelte +11 -9
  258. package/src/lib/views/Toast.samples.js +9 -0
  259. package/src/lib/views/ToastContainer.samples.js +8 -0
  260. package/src/lib/views/parts/Breadcrumb.svelte +53 -0
  261. package/src/lib/views/parts/CloseTicketConfirmModal.svelte +63 -0
  262. package/src/lib/views/parts/ConfirmRemoveAllNotificationsModal.svelte +55 -0
  263. package/src/lib/views/parts/DefaultToast.svelte +22 -0
  264. package/src/lib/views/parts/HomeSidebar.svelte +334 -0
  265. package/src/lib/views/parts/LogoutSessionConfirmModal.svelte +46 -0
  266. package/src/lib/views/parts/Main.svelte +71 -0
  267. package/src/lib/views/parts/NotificationContainer.svelte +109 -0
  268. package/src/lib/views/parts/PlayerDetailSidebar.svelte +81 -0
  269. package/src/lib/views/parts/Post.svelte +255 -0
  270. package/src/lib/views/parts/Posts.svelte +25 -0
  271. package/src/lib/views/parts/ProfileSidebar.svelte +115 -0
  272. package/src/lib/views/parts/Sidebar.svelte +19 -0
  273. package/src/lib/views/parts/SupportSidebar.svelte +34 -0
  274. package/src/lib/views/parts/TicketCreateAndDetailSidebar.svelte +51 -0
  275. package/src/lib/views/parts/TicketRow.svelte +63 -0
  276. package/src/lib/views/parts/TicketStatus.svelte +24 -0
  277. package/src/lib/views/parts/Tickets.svelte +45 -0
  278. package/src/lib/views/parts/Toast.svelte +27 -0
  279. package/src/lib/views/parts/ToastContainer.svelte +17 -0
  280. package/src/lib/views/parts/engine-views.generated.js +63 -0
  281. package/src/lib/views/parts/publicHref.js +18 -0
  282. package/src/lib/views/parts/ticketStatuses.js +7 -0
  283. package/src/plugin-engine/__tests__/engine.test.js +161 -0
  284. package/src/plugin-engine/engine.js +80 -12
  285. package/src/registry/__tests__/registry.test.js +510 -0
  286. package/src/registry/__tests__/view.test.js +52 -0
  287. package/src/registry/index.js +700 -51
  288. package/src/registry/routes.js +62 -0
  289. package/src/registry/view.js +69 -0
  290. package/src/routes/RootLayout.svelte +24 -1
  291. package/src/routes/catalogue/List.svelte +163 -0
  292. package/src/routes/catalogue/Stage.svelte +355 -0
  293. package/src/routes/catalogue/__tests__/browserSafe.test.js +13 -0
  294. package/src/routes/catalogue/__tests__/catalogue.test.js +539 -0
  295. package/src/routes/catalogue/catalogue.js +129 -0
  296. package/src/routes/catalogue/deps.js +147 -0
  297. package/src/routes/catalogue/engineSamples.js +63 -0
  298. package/src/routes/catalogue/fixtures.js +77 -0
  299. package/src/routes/catalogue/list.js +37 -0
  300. package/src/routes/catalogue/model.js +286 -0
  301. package/src/routes/catalogue/stage.js +69 -0
  302. package/src/routes/catalogue/views-json.js +24 -0
  303. package/src/routes/plugin-ui/Layout.svelte +29 -4
  304. package/src/routes/plugin-ui/Page.svelte +86 -31
  305. package/src/routes/plugin-ui/load.js +173 -0
  306. package/src/routes/plugins-client-file.js +8 -3
  307. package/src/routes/plugins-ui-file.js +60 -0
  308. package/src/routes/root-layout-load.js +59 -2
package/bin/check.js CHANGED
@@ -1,263 +1,1200 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * theme-core check — the machine-enforced theme contract.
3
+ * theme-core check — the machine-enforced theme contract (doc 01 section 10).
4
4
  *
5
- * Replaces the prose contract (PANO-THEME-DESIGN-CONTEXT.md) with checks that
6
- * fail CI before a broken theme ships:
7
- * 1. svelte is pinned to EXACTLY core's version (plugins compile against the
8
- * host runtime surface; skew silently drops plugins at runtime)
9
- * 2. every view in theme.config.js exists on disk and is a KNOWN view name
10
- * from skin-contract.json (typos = silent fallback to default views)
11
- * 3. overridden views mount every <ViewSlot>/<Hook> the default view mounts
12
- * (plugin injection points must not be lost by a restyle)
13
- * 4. lang-overrides files are valid JSON and only add/replace keys
14
- * 5. manifest.json carries the required keys
15
- * 6. settingsSchema (theme.config.js) is shape-valid, appends only, puts no
16
- * key in a different tab than the base does, and its defaultTab exists
17
- * Exit code 1 on any violation.
5
+ * bun check.js [--strict] [--fix]
6
+ *
7
+ * --strict warnings count as errors (`theme-core package` always runs strict, so every
8
+ * published theme, official or not, passes the same check)
9
+ * --fix writes what can be written for you: missing or outdated controller pins in
10
+ * theme.config.js (C12)
11
+ *
12
+ * Rules that existed before the open front-end:
13
+ * svelte pin svelte is pinned to EXACTLY core's version
14
+ * settings settingsSchema is shape-valid, appends only, defaultTab exists
15
+ * manifest manifest.json carries the required keys
16
+ * lang lang-overrides/*.json are valid JSON
17
+ * MainLayoutView an overridden MainLayoutView must not emit <meta name="description">
18
+ * i18n keys keys used by overridden views exist in the merged lang tree (warning)
19
+ *
20
+ * Rules C1-C16 (the table of doc 01 section 10):
21
+ * C1 override file exists error
22
+ * C2 override name is known (engine contract / snapshot) error; no snapshot: warning
23
+ * C3 `contract` equals the snapshot / engine contract warning
24
+ * C4 override keeps hooks, slots and slotProps of the default error
25
+ * C5 hook mounted in more than one effective view error
26
+ * C6 props read by the override are in the contract warning
27
+ * C7 <PluginBlock> / pluginView ids exist; literal props error; warning
28
+ * C8 claims info
29
+ * C9 routes error
30
+ * C10 home error
31
+ * C11 override exports load / uses context towards a plugin warning
32
+ * C12 controller pins (--fix writes them) warning
33
+ * C13 styles <-> provides.bootstrap, pano-tokens error; warning
34
+ * C14 override lacks the view's root class warning
35
+ * C15 lang-overrides/plugins/<ns>/*.json error
36
+ * C16 API path literals are Pano routes (pano-api check-paths) error
37
+ *
38
+ * Exit code 1 on any error. `runChecks()` is exported for tests and for `theme-core package`.
18
39
  */
19
- import { existsSync, readFileSync, readdirSync } from "node:fs";
20
- import { join, dirname } from "node:path";
40
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
41
+ import { createRequire } from "node:module";
42
+ import { spawnSync } from "node:child_process";
43
+ import { join, dirname, resolve, relative, sep } from "node:path";
21
44
  import { fileURLToPath, pathToFileURL } from "node:url";
22
45
  import { pc } from "./ui.js";
23
46
 
24
- const pkgDir = join(dirname(fileURLToPath(import.meta.url)), "..");
25
- const themeDir = process.cwd();
26
- const problems = [];
27
- const warnings = [];
28
-
29
- const contract = JSON.parse(readFileSync(join(pkgDir, "skin-contract.json"), "utf-8"));
30
- const corePkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf-8"));
31
-
32
- // 1. svelte pin
33
- const themePkg = JSON.parse(readFileSync(join(themeDir, "package.json"), "utf-8"));
34
- const themeSvelte =
35
- themePkg.dependencies?.svelte ?? themePkg.devDependencies?.svelte;
36
- const coreSvelte = corePkg.dependencies.svelte;
37
- if (themeSvelte !== coreSvelte) {
38
- problems.push(
39
- `svelte must be pinned to exactly "${coreSvelte}" (core's pin); found "${themeSvelte}" — version skew silently drops plugins at runtime`,
40
- );
47
+ /** theme.config.js files this process has imported already. */
48
+ const importedConfigs = new Set();
49
+
50
+ const defaultPkgDir = join(dirname(fileURLToPath(import.meta.url)), "..");
51
+
52
+ /**
53
+ * @typedef {"error" | "warning" | "info"} Level
54
+ * @typedef {{ level: Level, rule: string | null, message: string }} Finding
55
+ * @typedef {{
56
+ * findings: Finding[],
57
+ * problems: Finding[],
58
+ * warnings: Finding[],
59
+ * infos: Finding[],
60
+ * fixed: string[],
61
+ * overrides: number,
62
+ * strict: boolean,
63
+ * }} Report
64
+ */
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Small text helpers
68
+ // ---------------------------------------------------------------------------
69
+
70
+ /** Blanks JS comments with spaces (same length, so indexes still point into the raw source). */
71
+ function blankJsComments(text) {
72
+ const blank = (m) => m.replace(/[^\n]/g, " ");
73
+ return text.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:"'`\w\\])(\/\/.*)$/gm, (m, a, b) => a + blank(b));
74
+ }
75
+
76
+ const stripHtmlComments = (text) => text.replace(/<!--[\s\S]*?-->/g, "");
77
+
78
+ /**
79
+ * Index of the closing bracket for the opener at `start`, skipping strings and template literals.
80
+ * @returns {number} -1 when unbalanced
81
+ */
82
+ function closing(text, start) {
83
+ const open = text[start];
84
+ const close = open === "{" ? "}" : open === "[" ? "]" : ")";
85
+ let depth = 0;
86
+ for (let i = start; i < text.length; i++) {
87
+ const c = text[i];
88
+ if (c === '"' || c === "'" || c === "`") {
89
+ for (i++; i < text.length && text[i] !== c; i++) if (text[i] === "\\") i++;
90
+ } else if (c === open) {
91
+ depth++;
92
+ } else if (c === close) {
93
+ depth--;
94
+ if (depth === 0) return i;
95
+ }
96
+ }
97
+ return -1;
41
98
  }
42
99
 
43
- // 2. view registry entries
44
- const themeConfigPath = join(themeDir, "theme.config.js");
45
- let registered = [];
46
- if (existsSync(themeConfigPath)) {
47
- const cfgSource = readFileSync(themeConfigPath, "utf-8")
48
- // strip comments so documentation examples aren't parsed as registrations
49
- .replace(/\/\*[\s\S]*?\*\//g, "")
50
- .replace(/^\s*\/\/.*$/gm, "");
51
- for (const m of cfgSource.matchAll(/([A-Za-z0-9]+)\s*:\s*\(\)\s*=>\s*import\("([^"]+)"\)/g)) {
52
- const [, name, path] = m;
53
- registered.push(name);
54
- if (!(name in contract.views) && !contract.registry_components.includes(name)) {
55
- problems.push(`theme.config.js registers unknown view '${name}' — not part of the core contract (typo? removed in this core version?)`);
56
- }
57
- if (!existsSync(join(themeDir, path))) {
58
- problems.push(`theme.config.js: view '${name}' points at missing file ${path}`);
59
- }
60
- }
61
- } else {
62
- warnings.push("no theme.config.js — theme runs with all default views");
100
+ /** `ProductCard` -> `product-card` (the same rule as plugin-kit's root class). */
101
+ function kebab(name) {
102
+ return String(name)
103
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
104
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
105
+ .replace(/[^A-Za-z0-9]+/g, "-")
106
+ .replace(/^-+|-+$/g, "")
107
+ .toLowerCase();
63
108
  }
64
109
 
65
- // 3. slot/hook preservation in overridden views
66
- for (const name of registered) {
67
- const defaultView = join(pkgDir, "src", "lib", "views", `${name}.svelte`);
68
- const overridePath = join(themeDir, "src", "views", `${name}.svelte`);
69
- if (!existsSync(defaultView) || !existsSync(overridePath)) continue;
70
- const wanted = new Set();
71
- const dv = readFileSync(defaultView, "utf-8");
72
- for (const m of dv.matchAll(/<ViewComponent[^>]*id="([^"]+)"/g)) wanted.add(`slot:${m[1]}`);
73
- for (const m of dv.matchAll(/<Hook[^>]*name="([^"]+)"/g)) wanted.add(`hook:${m[1]}`);
74
- const ov = readFileSync(overridePath, "utf-8");
75
- for (const item of wanted) {
76
- // hook ids themselves contain ':' (e.g. "page:top") — split on the FIRST
77
- // colon only.
78
- const sep = item.indexOf(":");
79
- const kind = item.slice(0, sep);
80
- const id = item.slice(sep + 1);
81
- const present =
82
- kind === "slot"
83
- ? new RegExp(`<ViewComponent[^>]*id="${id}"`).test(ov)
84
- : new RegExp(`<Hook[^>]*name="${id}"`).test(ov);
85
- if (!present) {
86
- problems.push(`view '${name}' override lost plugin ${kind} '${id}' — plugins mounting there will silently disappear`);
110
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
111
+
112
+ /** @param {string} dir @param {(name: string) => boolean} keep @param {string[]} [skipDirs] */
113
+ function walkFiles(dir, keep, skipDirs = ["node_modules", ".git", ".svelte-kit", "build"]) {
114
+ /** @type {string[]} */
115
+ const out = [];
116
+ if (!existsSync(dir)) return out;
117
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
118
+ const p = join(dir, entry.name);
119
+ if (entry.isDirectory()) {
120
+ if (!skipDirs.includes(entry.name)) out.push(...walkFiles(p, keep, skipDirs));
121
+ } else if (keep(entry.name)) {
122
+ out.push(p);
87
123
  }
88
124
  }
125
+ return out.sort();
89
126
  }
90
127
 
91
- // 3b. no hook may be mounted in MORE than one effective view (override when
92
- // registered, default otherwise): a duplicated hook renders every plugin
93
- // mounted there twice on the same page (e.g. page:home:top in both a
94
- // MainLayoutView override and HomeView).
95
- {
96
- const defaultViewsDir = join(pkgDir, "src", "lib", "views");
97
- const hookOwners = {};
98
- for (const file of readdirSync(defaultViewsDir)) {
99
- if (!file.endsWith(".svelte")) continue;
100
- const name = file.slice(0, -7);
101
- const overridePath = join(themeDir, "src", "views", file);
102
- const effective =
103
- registered.includes(name) && existsSync(overridePath)
104
- ? { path: overridePath, label: `src/views/${file}` }
105
- : { path: join(defaultViewsDir, file), label: `${file} (default)` };
106
- const src = readFileSync(effective.path, "utf-8");
107
- for (const m of src.matchAll(/<Hook[^>]*name="([^"]+)"/g)) {
108
- (hookOwners[m[1]] ??= []).push(effective.label);
109
- }
110
- }
111
- for (const [hook, owners] of Object.entries(hookOwners)) {
112
- if (new Set(owners).size > 1) {
113
- problems.push(
114
- `hook '${hook}' is mounted in multiple views (${[...new Set(owners)].join(", ")}) — plugins there render twice on the same page`,
115
- );
128
+ const lineOf = (text, index) => text.slice(0, index).split("\n").length;
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // theme.config.js: overrides (one regex for both forms), pins
132
+ // ---------------------------------------------------------------------------
133
+
134
+ /**
135
+ * One regex over the `views: { … }` block of theme.config.js: both entry forms, bare or quoted key
136
+ * (`Navbar`, `"market:ProductCard"`, `'pano-plugin-market:ProductCard'`).
137
+ * Navbar: () => import("./src/views/Navbar.svelte")
138
+ * "market:ProductCard": { contract: 2, controllers: ["market/cart"], component: () => import("./x.svelte") }
139
+ */
140
+ const VIEW_ENTRY =
141
+ /(?:(["'])([A-Za-z0-9_$:.-]+)\1|([A-Za-z_$][\w$]*))\s*:\s*(?:\(\s*\)\s*=>\s*import\(\s*(["'`])([^"'`\n]+)\4\s*\)|\{([^{}]*)\})/g;
142
+
143
+ /**
144
+ * @typedef {{
145
+ * key: string, path: string | null, contract: number, controllers: string[], objectForm: boolean,
146
+ * }} Override
147
+ */
148
+
149
+ /** @param {string} source raw theme.config.js @returns {Override[]} */
150
+ export function readOverrides(source) {
151
+ const blank = blankJsComments(source);
152
+ const start = /(?<![\w$.])views\s*:\s*\{/.exec(blank);
153
+ if (!start) return [];
154
+ const open = start.index + start[0].length - 1;
155
+ const end = closing(blank, open);
156
+ const block = blank.slice(open + 1, end < 0 ? undefined : end);
157
+
158
+ /** @type {Override[]} */
159
+ const out = [];
160
+ for (const m of block.matchAll(VIEW_ENTRY)) {
161
+ const key = m[2] ?? m[3];
162
+ if (m[5] !== undefined) {
163
+ out.push({ key, path: m[5], contract: 1, controllers: [], objectForm: false });
164
+ continue;
116
165
  }
166
+ const body = m[6];
167
+ const file = /\bimport\(\s*(["'`])([^"'`\n]+)\1\s*\)/.exec(body) ?? /\bcomponent\s*:\s*(["'`])([^"'`\n]+)\1/.exec(body);
168
+ if (!file) continue; // an object without a component (a `label` object, …) is not a view entry
169
+ const contract = /\bcontract\s*:\s*(\d+)/.exec(body);
170
+ const controllers = /\bcontrollers\s*:\s*\[([^\]]*)\]/.exec(body);
171
+ out.push({
172
+ key,
173
+ path: file[2],
174
+ contract: contract ? Number(contract[1]) : 1,
175
+ controllers: controllers ? [...controllers[1].matchAll(/(["'])([^"'\n]+)\1/g)].map((c) => c[2]) : [],
176
+ objectForm: true,
177
+ });
117
178
  }
179
+ return out;
118
180
  }
119
181
 
120
- // 4. lang-overrides sanity
121
- const langOverrides = join(themeDir, "lang-overrides");
122
- if (existsSync(langOverrides)) {
123
- for (const f of readdirSync(langOverrides)) {
124
- if (!f.endsWith(".json")) continue;
125
- try {
126
- JSON.parse(readFileSync(join(langOverrides, f), "utf-8"));
127
- } catch (e) {
128
- problems.push(`lang-overrides/${f} is not valid JSON: ${e.message}`);
182
+ /**
183
+ * Writes `controllers: { "ns/name": version }` pins into theme.config.js source.
184
+ * @param {string} source
185
+ * @param {Map<string, number>} pins
186
+ * @returns {string | null} null when the object could not be located
187
+ */
188
+ export function writePins(source, pins) {
189
+ const blank = blankJsComments(source);
190
+ const block = /(?<![\w$.])controllers\s*:\s*\{/.exec(blank);
191
+
192
+ if (block) {
193
+ const open = block.index + block[0].length - 1;
194
+ const end = closing(blank, open);
195
+ if (end < 0) return null;
196
+ let inner = source.slice(open + 1, end);
197
+ const lineStart = source.lastIndexOf("\n", block.index) + 1;
198
+ const indent = /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? "";
199
+ const added = [];
200
+ for (const [name, version] of pins) {
201
+ const existing = new RegExp(`(["']?)${escapeRe(name)}\\1(\\s*:\\s*)\\d+`);
202
+ if (existing.test(inner)) inner = inner.replace(existing, (_, q, colon) => `${q}${name}${q}${colon}${version}`);
203
+ else added.push(`${indent} ${JSON.stringify(name)}: ${version},`);
204
+ }
205
+ if (added.length) {
206
+ const trimmed = inner.replace(/\s+$/, "");
207
+ const needsComma = trimmed.trim() !== "" && !trimmed.endsWith(",");
208
+ inner = `${trimmed}${needsComma ? "," : ""}\n${added.join("\n")}\n${indent}`;
129
209
  }
210
+ return source.slice(0, open + 1) + inner + source.slice(end);
130
211
  }
212
+
213
+ const head = /export\s+default\s+(?:[A-Za-z_$][\w$.]*\s*\(\s*)?\{/.exec(blank);
214
+ if (!head) return null;
215
+ const at = head.index + head[0].length;
216
+ const lines = [...pins].map(([name, version]) => ` ${JSON.stringify(name)}: ${version},`);
217
+ return `${source.slice(0, at)}\n controllers: {\n${lines.join("\n")}\n },${source.slice(at)}`;
131
218
  }
132
219
 
133
- // 5. manifest required keys
134
- const manifestPath = join(themeDir, "manifest.json");
135
- if (existsSync(manifestPath)) {
136
- const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
137
- for (const key of ["id", "title", "version", "author", "panoVersion", "screenshots"]) {
138
- if (!(key in manifest)) problems.push(`manifest.json missing required key '${key}' (install is refused without it)`);
220
+ // ---------------------------------------------------------------------------
221
+ // Svelte source readers
222
+ // ---------------------------------------------------------------------------
223
+
224
+ /** Names destructured from `$props()` plus legacy `export let`. */
225
+ export function readProps(source) {
226
+ const text = stripHtmlComments(blankJsComments(source));
227
+ const names = new Set();
228
+ for (const m of text.matchAll(/(?:let|const)\s*\{/g)) {
229
+ const open = m.index + m[0].length - 1;
230
+ const end = closing(text, open);
231
+ if (end < 0) continue;
232
+ if (!/^\s*(?::[^=]*)?=\s*\$props\(\s*\)/.test(text.slice(end + 1, end + 200))) continue;
233
+ const inner = text.slice(open + 1, end);
234
+ // split on top-level commas
235
+ let depth = 0;
236
+ let part = "";
237
+ const parts = [];
238
+ for (const c of inner) {
239
+ if ("{[(".includes(c)) depth++;
240
+ else if ("}])".includes(c)) depth--;
241
+ if (c === "," && depth === 0) {
242
+ parts.push(part);
243
+ part = "";
244
+ } else part += c;
245
+ }
246
+ parts.push(part);
247
+ for (const p of parts) {
248
+ const name = /^\s*([A-Za-z_$][\w$]*)/.exec(p.trim().startsWith("...") ? "" : p)?.[1];
249
+ if (name) names.add(name);
250
+ }
139
251
  }
140
- if (manifest.id === "vanilla-theme" && themePkg.name !== "pano-vanilla-theme") {
141
- problems.push(`manifest id 'vanilla-theme' is reserved for the SYSTEM theme — installs would be refused`);
252
+ for (const m of text.matchAll(/\bexport\s+let\s+([A-Za-z_$][\w$]*)/g)) names.add(m[1]);
253
+ return [...names];
254
+ }
255
+
256
+ /** Hook names, slot ids (and `<ViewComponent id>`) mounted by a view's markup. */
257
+ export function readMounts(source) {
258
+ const text = stripHtmlComments(source);
259
+ const hooks = new Set();
260
+ const slots = new Set();
261
+ for (const m of text.matchAll(/<Hook\b[^>]*?\bname\s*=\s*(?:\{\s*)?(["'])([^"']+)\1/g)) hooks.add(m[2]);
262
+ for (const m of text.matchAll(/<(?:ViewComponent|PluginSlot)\b[^>]*?\bid\s*=\s*(?:\{\s*)?(["'])([^"']+)\1/g)) slots.add(m[2]);
263
+ return { hooks, slots };
264
+ }
265
+
266
+ /** @param {string} expr @returns {boolean} true when a `{expression}` attribute is a literal (blockKey rule) */
267
+ function isLiteralExpression(expr) {
268
+ const v = expr.trim();
269
+ if (v === "true" || v === "false") return true;
270
+ if (/^-?(\d+\.?\d*|\.\d+)$/.test(v)) return true;
271
+ const q = /^(["'`])([\s\S]*)\1$/.exec(v);
272
+ return !!q && !q[2].includes("\\") && !q[2].includes(q[1]) && !(q[1] === "`" && q[2].includes("${"));
273
+ }
274
+
275
+ /**
276
+ * Every <PluginBlock> and pluginView() placement in a file.
277
+ * @param {string} source @param {boolean} isSvelte
278
+ * @returns {{ id: string | null, line: number, nonLiteralProps: string[], kind: "block" | "proxy" }[]}
279
+ */
280
+ export function readPlacements(source, isSvelte) {
281
+ const raw = isSvelte ? stripHtmlComments(source) : source;
282
+ const out = [];
283
+ for (const m of raw.matchAll(/<PluginBlock(?=[\s/>])/g)) {
284
+ let i = m.index + m[0].length;
285
+ let id = null;
286
+ let idLiteral = false;
287
+ const bad = [];
288
+ while (i < raw.length) {
289
+ while (i < raw.length && /\s/.test(raw[i])) i++;
290
+ const c = raw[i];
291
+ if (c === undefined || c === ">") break;
292
+ if (c === "/") {
293
+ i++;
294
+ continue;
295
+ }
296
+ if (c === "{") {
297
+ const end = closing(raw, i);
298
+ if (end < 0) break;
299
+ const inner = raw.slice(i + 1, end).trim();
300
+ bad.push(inner.startsWith("...") ? "{...spread}" : inner);
301
+ i = end + 1;
302
+ continue;
303
+ }
304
+ let j = i;
305
+ while (j < raw.length && !/[\s=/>]/.test(raw[j])) j++;
306
+ const name = raw.slice(i, j);
307
+ i = j;
308
+ while (i < raw.length && /\s/.test(raw[i])) i++;
309
+ if (raw[i] !== "=") continue; // bare attribute: literal true
310
+ i++;
311
+ while (i < raw.length && /\s/.test(raw[i])) i++;
312
+ let literal = true;
313
+ let value = "";
314
+ if (raw[i] === '"' || raw[i] === "'") {
315
+ const end = raw.indexOf(raw[i], i + 1);
316
+ if (end < 0) break;
317
+ value = raw.slice(i + 1, end);
318
+ literal = !value.includes("{");
319
+ i = end + 1;
320
+ } else if (raw[i] === "{") {
321
+ const end = closing(raw, i);
322
+ if (end < 0) break;
323
+ const expr = raw.slice(i + 1, end);
324
+ literal = isLiteralExpression(expr);
325
+ value = literal ? expr.trim().replace(/^(["'`])([\s\S]*)\1$/, "$2") : "";
326
+ i = end + 1;
327
+ } else {
328
+ let k = i;
329
+ while (k < raw.length && !/[\s>]/.test(raw[k])) k++;
330
+ value = raw.slice(i, k);
331
+ i = k;
332
+ }
333
+ if (name === "id") {
334
+ idLiteral = literal && value !== "";
335
+ id = idLiteral ? value : null;
336
+ } else if (!literal) bad.push(name);
337
+ }
338
+ out.push({ id, line: lineOf(raw, m.index), nonLiteralProps: bad, kind: /** @type {const} */ ("block") });
142
339
  }
143
- } else {
144
- problems.push("manifest.json missing");
340
+ const js = isSvelte ? raw.replace(/<!--[\s\S]*?-->/g, "") : raw;
341
+ for (const m of js.matchAll(/\bpluginView\(\s*(["'`])?([^"'`),]*)/g)) {
342
+ const literal = m[1] && !(m[1] === "`" && m[2].includes("${"));
343
+ out.push({ id: literal ? m[2] : null, line: lineOf(js, m.index), nonLiteralProps: [], kind: /** @type {const} */ ("proxy") });
344
+ }
345
+ return out;
145
346
  }
146
347
 
147
- // 6. settings-schema extension (theme.config.js → settingsSchema)
148
- // Imported (not regex-scanned): the schema is a nested object literal, and the
149
- // view thunks stay lazy, so importing the config runs no Svelte code.
150
- if (existsSync(themeConfigPath) && contract.settings_tabs) {
151
- let settingsSchema;
152
- try {
153
- const mod = await import(pathToFileURL(themeConfigPath).href);
154
- settingsSchema = (mod.default ?? mod)?.settingsSchema ?? null;
155
- } catch (e) {
156
- problems.push(`theme.config.js could not be imported to validate settingsSchema: ${e.message}`);
157
- settingsSchema = null;
348
+ // ---------------------------------------------------------------------------
349
+ // The run
350
+ // ---------------------------------------------------------------------------
351
+
352
+ const ENGINE_CONTEXT_KEYS = new Set(["session", "themeSettings", "pageTitle", "sidebarProps", "sidebar", "breadcrumbs", "pano", "panoApi"]);
353
+
354
+ /** Canonical paths the engine serves, used when the theme has not been synced yet. */
355
+ const CORE_PAGE_PATHS = [
356
+ "/",
357
+ "/login",
358
+ "/register",
359
+ "/profile",
360
+ "/profile/settings",
361
+ "/activate",
362
+ "/activate-new-email",
363
+ "/notifications",
364
+ "/player/[player]",
365
+ "/post/[url]",
366
+ "/preview/post/[id]",
367
+ "/renew-password",
368
+ "/reset-password",
369
+ "/rules",
370
+ "/support",
371
+ "/tickets",
372
+ "/ticket/[id]",
373
+ "/ticket/create",
374
+ "/theme-settings",
375
+ ];
376
+
377
+ /** Two paths with the same shape are the same route (`/p/[a]` and `/p/[b]`). */
378
+ const shapeOf = (path) =>
379
+ path
380
+ .split("/")
381
+ .filter(Boolean)
382
+ .map((part) => (part.startsWith("[...") ? "**" : part.startsWith("[") ? "*" : part))
383
+ .join("/");
384
+
385
+ /**
386
+ * Runs every rule against one theme.
387
+ * @param {{ themeDir?: string, pkgDir?: string, strict?: boolean, fix?: boolean, env?: Record<string, string | undefined> }} [options]
388
+ * @returns {Promise<Report>}
389
+ */
390
+ export async function runChecks(options = {}) {
391
+ const themeDir = resolve(options.themeDir ?? process.cwd());
392
+ const pkgDir = options.pkgDir ?? defaultPkgDir;
393
+ const strict = !!options.strict;
394
+ const fix = !!options.fix;
395
+ const env = options.env ?? process.env;
396
+
397
+ /** @type {Finding[]} */
398
+ const findings = [];
399
+ /** @type {string[]} */
400
+ const fixed = [];
401
+ /** @param {Level} level @param {string | null} rule @param {string} message */
402
+ const add = (level, rule, message) => findings.push({ level, rule, message });
403
+ const error = (rule, message) => add("error", rule, message);
404
+ const warn = (rule, message) => add("warning", rule, message);
405
+ const info = (rule, message) => add("info", rule, message);
406
+ const rel = (p) => relative(themeDir, p).split(sep).join("/");
407
+ const read = (p) => readFileSync(p, "utf-8");
408
+
409
+ const contract = JSON.parse(read(join(pkgDir, "skin-contract.json")));
410
+ const corePkg = JSON.parse(read(join(pkgDir, "package.json")));
411
+
412
+ // --- svelte pin ------------------------------------------------------------------------
413
+ let themePkg = {};
414
+ const themePkgPath = join(themeDir, "package.json");
415
+ if (existsSync(themePkgPath)) {
416
+ themePkg = JSON.parse(read(themePkgPath));
417
+ } else {
418
+ error(null, "package.json missing — a theme is a package; run: theme-core new");
419
+ }
420
+ const themeSvelte = themePkg.dependencies?.svelte ?? themePkg.devDependencies?.svelte;
421
+ const coreSvelte = corePkg.dependencies.svelte;
422
+ if (themeSvelte !== coreSvelte) {
423
+ error(
424
+ null,
425
+ `svelte must be pinned to exactly "${coreSvelte}" (core's pin); found "${themeSvelte}" — version skew silently drops plugins at runtime; set it in package.json`,
426
+ );
427
+ }
428
+
429
+ // --- theme.config.js -------------------------------------------------------------------
430
+ const themeConfigPath = join(themeDir, "theme.config.js");
431
+ const hasConfig = existsSync(themeConfigPath);
432
+ const configSource = hasConfig ? read(themeConfigPath) : "";
433
+ /** @type {any} */
434
+ let cfg = null;
435
+ /** @type {Override[]} */
436
+ let overrides = [];
437
+
438
+ const importConfig = async () => {
439
+ // The module registry is keyed by path, so a config this process already imported (tests run
440
+ // many checks in one process) is imported from a throw-away sibling copy to see fresh text.
441
+ let copy = null;
442
+ try {
443
+ let target = themeConfigPath;
444
+ if (importedConfigs.has(themeConfigPath)) {
445
+ copy = join(themeDir, `.theme.config.check-${process.pid}-${importedConfigs.size}-${Date.now()}.mjs`);
446
+ writeFileSync(copy, configSource);
447
+ target = copy;
448
+ }
449
+ importedConfigs.add(themeConfigPath);
450
+ const mod = await import(pathToFileURL(target).href);
451
+ return mod.default ?? mod;
452
+ } catch (e) {
453
+ error(
454
+ null,
455
+ `theme.config.js could not be imported (${e.message}) — routes, home, claims, pins and settingsSchema were not checked; fix the syntax error`,
456
+ );
457
+ return null;
458
+ } finally {
459
+ if (copy) rmSync(copy, { force: true });
460
+ }
461
+ };
462
+
463
+ if (hasConfig) {
464
+ overrides = readOverrides(configSource);
465
+ cfg = await importConfig();
466
+ } else {
467
+ warn(null, "no theme.config.js — theme runs with all default views; create one with: theme-core new");
468
+ }
469
+
470
+ // --- snapshots (plugin-contracts/<ns>/views.json, controllers.json) ----------------------
471
+ const snapshotsDir = join(themeDir, "plugin-contracts");
472
+ /** @type {Map<string, { views: any, controllers: any, pluginId: string | null } | null>} */
473
+ const snapshotCache = new Map();
474
+ /** pluginId -> ns, from every snapshot on disk */
475
+ const aliases = new Map();
476
+ /** @type {string[]} */
477
+ const snapshotNamespaces = [];
478
+ if (existsSync(snapshotsDir)) {
479
+ for (const entry of readdirSync(snapshotsDir, { withFileTypes: true })) {
480
+ if (!entry.isDirectory()) continue;
481
+ snapshotNamespaces.push(entry.name);
482
+ try {
483
+ const views = JSON.parse(read(join(snapshotsDir, entry.name, "views.json")));
484
+ if (views.pluginId) aliases.set(views.pluginId, views.namespace ?? entry.name);
485
+ } catch {
486
+ /* a broken snapshot is reported when it is used */
487
+ }
488
+ }
158
489
  }
159
490
 
160
- if (settingsSchema != null) {
161
- if (typeof settingsSchema !== "object" || Array.isArray(settingsSchema)) {
162
- problems.push("theme.config.js: settingsSchema must be an object ({ tabs?, defaultTab? })");
491
+ const readJson = (file) => {
492
+ try {
493
+ return JSON.parse(read(file));
494
+ } catch {
495
+ return null;
496
+ }
497
+ };
498
+
499
+ /** @param {string} ns */
500
+ const snapshot = (ns) => {
501
+ if (snapshotCache.has(ns)) return snapshotCache.get(ns);
502
+ const dir = join(snapshotsDir, ns);
503
+ const entry = existsSync(dir)
504
+ ? { views: readJson(join(dir, "views.json")), controllers: readJson(join(dir, "controllers.json")), pluginId: null }
505
+ : null;
506
+ if (entry) entry.pluginId = entry.views?.pluginId ?? null;
507
+ snapshotCache.set(ns, entry);
508
+ return entry;
509
+ };
510
+
511
+ /**
512
+ * @param {string} id `Navbar`, `market:ProductCard`, `pano-plugin-market:ProductCard`
513
+ * @returns {{ plugin: false, name: string, id: string } | { plugin: true, ns: string, name: string, id: string }}
514
+ */
515
+ const parseViewId = (id) => {
516
+ const at = id.lastIndexOf(":");
517
+ if (at < 0) return { plugin: false, name: id, id };
518
+ const prefix = id.slice(0, at);
519
+ const name = id.slice(at + 1);
520
+ let ns = prefix;
521
+ if (!existsSync(join(snapshotsDir, prefix))) {
522
+ if (aliases.has(prefix)) ns = aliases.get(prefix);
523
+ else if (prefix.startsWith("pano-plugin-")) ns = prefix.slice("pano-plugin-".length);
524
+ }
525
+ return { plugin: true, ns, name, id: `${ns}:${name}` };
526
+ };
527
+
528
+ /** Record of a view in the engine contract or in a plugin snapshot. */
529
+ const recordOf = (parsed) => {
530
+ if (!parsed.plugin) return contract.views[parsed.name] ?? null;
531
+ return snapshot(parsed.ns)?.views?.views?.[parsed.id] ?? null;
532
+ };
533
+
534
+ // --- C1 / C2 / C3: overrides -------------------------------------------------------------
535
+ /** @type {{ ov: Override, parsed: any, record: any, file: string | null, text: string | null }[]} */
536
+ const views = [];
537
+ const noSnapshotWarned = new Set();
538
+
539
+ for (const ov of overrides) {
540
+ const parsed = parseViewId(ov.key);
541
+ const file = ov.path ? resolve(themeDir, ov.path.replace(/^\//, "")) : null;
542
+ const exists = !!file && existsSync(file);
543
+ if (!exists) {
544
+ error("C1", `theme.config.js: view '${ov.key}' points at a missing override file: ${ov.path}`);
545
+ }
546
+
547
+ let record = null;
548
+ if (!parsed.plugin) {
549
+ record = contract.views[parsed.name] ?? null;
550
+ if (!record && !contract.registry_components.includes(parsed.name)) {
551
+ error(
552
+ "C2",
553
+ `theme.config.js registers unknown view '${parsed.name}' — not part of the core contract (typo? removed in this core version?); run: theme-core list-views`,
554
+ );
555
+ }
163
556
  } else {
164
- // base tab → keys, dropping the "_note" doc string (non-array values)
165
- const baseTabs = {};
166
- for (const tab in contract.settings_tabs) {
167
- if (Array.isArray(contract.settings_tabs[tab])) baseTabs[tab] = contract.settings_tabs[tab];
168
- }
169
-
170
- // key → the single tab it may live in; base first, extension appends.
171
- // A key mapped to two different tabs is a save conflict (save/reset are
172
- // per-tab), so cross-tab duplicates FAIL; same-tab duplicates just dedupe.
173
- const keyToTab = {};
174
- for (const tab in baseTabs) for (const key of baseTabs[tab]) keyToTab[key] = tab;
175
- const tabSet = new Set(Object.keys(baseTabs));
176
-
177
- const extTabs = settingsSchema.tabs;
178
- if (extTabs != null) {
179
- if (typeof extTabs !== "object" || Array.isArray(extTabs)) {
180
- problems.push("theme.config.js: settingsSchema.tabs must be an object mapping tabId → string[]");
557
+ const snap = snapshot(parsed.ns);
558
+ if (!snap?.views) {
559
+ if (!noSnapshotWarned.has(parsed.ns)) {
560
+ noSnapshotWarned.add(parsed.ns);
561
+ warn("C2", `view '${ov.key}' cannot be checked: no contract snapshot for plugin '${parsed.ns}'; run: theme-core contracts pull`);
562
+ }
563
+ } else {
564
+ record = snap.views.views?.[parsed.id] ?? null;
565
+ if (!record) {
566
+ error("C2", `view '${ov.key}' is not in the '${parsed.ns}' snapshot (typo, or removed by the plugin); run: theme-core contracts pull`);
567
+ }
568
+ }
569
+ }
570
+
571
+ if (record && typeof record.contract === "number" && record.contract !== ov.contract) {
572
+ warn(
573
+ "C3",
574
+ `view '${ov.key}' override is at contract ${ov.contract}, the ${parsed.plugin ? "plugin" : "engine"} is at ${record.contract}: ` +
575
+ `shows the default view until updated; run: theme-core eject-view ${parsed.id}, merge <file>.new, then: theme-core accept ${parsed.id}`,
576
+ );
577
+ }
578
+
579
+ views.push({ ov, parsed, record, file: exists ? file : null, text: exists ? read(file) : null });
580
+ }
581
+
582
+ // --- C4: hooks, slots and slotProps of the default are kept ---------------------------------
583
+ const defaultViewsDir = join(pkgDir, "src", "lib", "views");
584
+ /** @param {{ parsed: any, record: any }} v */
585
+ const defaultMounts = (v) => {
586
+ const hooks = new Set(v.record?.hooks ?? []);
587
+ const slots = new Set(v.record?.slots ?? []);
588
+ if (!v.parsed.plugin) {
589
+ const src = join(defaultViewsDir, `${v.parsed.name}.svelte`);
590
+ if (existsSync(src)) {
591
+ const m = readMounts(read(src));
592
+ for (const h of m.hooks) hooks.add(h);
593
+ for (const s of m.slots) slots.add(s);
594
+ }
595
+ }
596
+ return { hooks, slots };
597
+ };
598
+
599
+ for (const v of views) {
600
+ if (v.text === null) continue;
601
+ const { hooks, slots } = defaultMounts(v);
602
+ const mine = readMounts(v.text);
603
+ const lost = [];
604
+ for (const h of hooks) if (!mine.hooks.has(h)) lost.push(`hook '${h}'`);
605
+ for (const s of slots) if (!mine.slots.has(s)) lost.push(`slot '${s}'`);
606
+ const body = stripHtmlComments(v.text);
607
+ for (const key of Object.keys(v.record?.slotProps ?? {})) {
608
+ if (key === "default") continue;
609
+ if (!new RegExp(`(?<![\\w$])${escapeRe(key)}(?![\\w$])`).test(body)) lost.push(`slot prop '${key}'`);
610
+ }
611
+ for (const item of lost) {
612
+ error("C4", `view '${v.ov.key}' override lost plugin ${item} — plugins mounting there will disappear`);
613
+ }
614
+ }
615
+
616
+ // MainLayoutView must not emit the description meta tag itself: <PageHead> (engine, AppLayout)
617
+ // emits exactly one per page, so a fork that kept the old line would serve two.
618
+ for (const v of views) {
619
+ if (v.parsed.plugin || v.parsed.name !== "MainLayoutView" || v.text === null) continue;
620
+ const ov = stripHtmlComments(v.text);
621
+ if (/\bname\s*=\s*(?:["']description["']|\{\s*["']description["']\s*\})/.test(ov)) {
622
+ error(
623
+ null,
624
+ `view 'MainLayoutView' override still emits <meta name="description"> — delete that line: the engine <PageHead> emits the description (and og / canonical tags) once per page, so the override would duplicate it`,
625
+ );
626
+ }
627
+ }
628
+
629
+ // --- C5: no hook mounted in more than one effective view -------------------------------------
630
+ {
631
+ const overrideByEngineName = new Map(views.filter((v) => !v.parsed.plugin && v.text !== null).map((v) => [v.parsed.name, v]));
632
+ const overrideByPluginId = new Map(views.filter((v) => v.parsed.plugin && v.text !== null).map((v) => [v.parsed.id, v]));
633
+ /** @type {Record<string, string[]>} */
634
+ const owners = {};
635
+ const own = (hook, label) => (owners[hook] ??= []).push(label);
636
+
637
+ if (existsSync(defaultViewsDir)) {
638
+ for (const file of readdirSync(defaultViewsDir)) {
639
+ if (!file.endsWith(".svelte")) continue;
640
+ const name = file.slice(0, -7);
641
+ const ov = overrideByEngineName.get(name);
642
+ const src = ov ? ov.text : read(join(defaultViewsDir, file));
643
+ const label = ov ? rel(ov.file) : `${file} (default)`;
644
+ for (const h of readMounts(src).hooks) own(h, label);
645
+ }
646
+ }
647
+ for (const ns of snapshotNamespaces) {
648
+ for (const [id, rec] of Object.entries(snapshot(ns)?.views?.views ?? {})) {
649
+ const ov = overrideByPluginId.get(id);
650
+ const hooks = ov ? readMounts(ov.text).hooks : new Set(rec.hooks ?? []);
651
+ for (const h of hooks) own(h, ov ? rel(ov.file) : `${id} (default)`);
652
+ }
653
+ }
654
+ // overrides of plugin views whose snapshot is missing still count
655
+ for (const v of views) {
656
+ if (!v.parsed.plugin || v.text === null || v.record) continue;
657
+ for (const h of readMounts(v.text).hooks) own(h, rel(v.file));
658
+ }
659
+ for (const [hook, list] of Object.entries(owners)) {
660
+ const unique = [...new Set(list)];
661
+ if (unique.length > 1) {
662
+ error("C5", `hook '${hook}' is mounted in multiple views (${unique.join(", ")}) — plugins there render twice on the same page; keep it in one of them`);
663
+ }
664
+ }
665
+ }
666
+
667
+ // --- C6 / C11: what the override reads and exports ----------------------------------------
668
+ for (const v of views) {
669
+ if (v.text === null) continue;
670
+ if (v.record?.props && typeof v.record.props === "object") {
671
+ const known = new Set(Object.keys(v.record.props));
672
+ const unknown = readProps(v.text).filter((p) => !known.has(p) && p !== "children");
673
+ if (unknown.length) {
674
+ warn("C6", `view '${v.ov.key}' override reads props that are not in its contract (always undefined; see: theme-core list-views): ${unknown.join(", ")}`);
675
+ }
676
+ }
677
+ const code = stripHtmlComments(blankJsComments(v.text));
678
+ if (/\bexport\s+(?:async\s+)?(?:function|const|let)\s+load\b/.test(code) || /\bexport\s*\{[^}]*\bload\b[^}]*\}/.test(code)) {
679
+ warn("C11", `view '${v.ov.key}' override exports load — ignored: data comes from the plugin; remove the export`);
680
+ }
681
+ if (v.parsed.plugin) {
682
+ for (const m of code.matchAll(/\b(set|get)Context\s*\(\s*(["'`])([^"'`]+)\2/g)) {
683
+ if (m[1] === "get" && ENGINE_CONTEXT_KEYS.has(m[3])) continue;
684
+ warn("C11", `view '${v.ov.key}' override calls ${m[1]}Context('${m[3]}') towards a plugin view — ignored: data comes from the plugin; pass props or use a controller`);
685
+ }
686
+ }
687
+ }
688
+
689
+ // --- C14: the root class of a plugin view stays on its override -----------------------------
690
+ for (const v of views) {
691
+ if (!v.parsed.plugin || v.text === null || !v.record) continue;
692
+ const root = `${v.parsed.ns}-${kebab(v.parsed.name)}`;
693
+ if (!new RegExp(`(?<![\\w-])${escapeRe(root)}(?![\\w-])`).test(v.text)) {
694
+ warn("C14", `view '${v.ov.key}' override lacks the view's root class; add class "${root}" to its root element: ${root}`);
695
+ }
696
+ }
697
+
698
+ // --- theme meta scan (claims, files) ---------------------------------------------------------
699
+ /** @type {{ claims: string[], files: string[] }} */
700
+ let meta = { claims: [], files: [] };
701
+ if (hasConfig && cfg) {
702
+ try {
703
+ const { scanThemeMeta } = await import(pathToFileURL(join(pkgDir, "src", "kit", "theme-meta.js")).href);
704
+ meta = scanThemeMeta({ themeDir, config: cfg });
705
+ } catch (e) {
706
+ warn(null, `theme meta scan failed (${e.message}) — claims and block placements were not checked`);
707
+ }
708
+ }
709
+
710
+ // --- C7: block / pluginView placements ---------------------------------------------------------
711
+ {
712
+ const seen = new Set();
713
+ for (const file of meta.files) {
714
+ const isSvelte = file.endsWith(".svelte");
715
+ let text;
716
+ try {
717
+ text = read(file);
718
+ } catch {
719
+ continue;
720
+ }
721
+ for (const place of readPlacements(text, isSvelte)) {
722
+ const at = `${rel(file)}:${place.line}`;
723
+ const what = place.kind === "block" ? "<PluginBlock>" : "pluginView()";
724
+ if (place.id === null) {
725
+ warn("C7", `${at} ${what} has an id that is not a literal: its data loads in the browser, not on the server`);
726
+ continue;
727
+ }
728
+ if (place.nonLiteralProps.length) {
729
+ warn("C7", `${at} <PluginBlock id="${place.id}"> has non-literal props (${place.nonLiteralProps.join(", ")}): its data loads in the browser, not on the server`);
730
+ }
731
+ const dedupe = `${at}|${place.id}`;
732
+ if (seen.has(dedupe)) continue;
733
+ seen.add(dedupe);
734
+ const parsed = parseViewId(place.id);
735
+ if (!parsed.plugin) {
736
+ if (!(parsed.name in contract.views) && !contract.registry_components.includes(parsed.name)) {
737
+ error("C7", `${at} ${what} references unknown view '${parsed.name}'; run: theme-core list-views`);
738
+ }
739
+ continue;
740
+ }
741
+ const snap = snapshot(parsed.ns);
742
+ if (!snap?.views) {
743
+ if (!noSnapshotWarned.has(parsed.ns)) {
744
+ noSnapshotWarned.add(parsed.ns);
745
+ warn("C7", `${at} ${what} references '${place.id}' but there is no contract snapshot for plugin '${parsed.ns}'; run: theme-core contracts pull`);
746
+ }
747
+ } else if (!snap.views.views?.[parsed.id]) {
748
+ error("C7", `${at} ${what} references '${place.id}', which is not in the '${parsed.ns}' snapshot (typo, or removed by the plugin); run: theme-core contracts pull`);
749
+ }
750
+ }
751
+ }
752
+ }
753
+
754
+ // --- C8: claims ------------------------------------------------------------------------------------
755
+ for (const id of meta.claims) {
756
+ const parsed = parseViewId(id);
757
+ const rec = recordOf(parsed);
758
+ for (const inj of rec?.inject ?? []) {
759
+ const target = inj.slot ?? inj.hook ?? inj.sidebar;
760
+ if (target) info("C8", `theme claims '${id}': its automatic copy in '${target}' is suppressed`);
761
+ }
762
+ }
763
+
764
+ // --- C9: routes ----------------------------------------------------------------------------------------
765
+ if (cfg) {
766
+ const routes = cfg.routes ?? {};
767
+ const { createRouteMap } = await import(pathToFileURL(join(pkgDir, "src", "kit", "route-map.js")).href);
768
+ try {
769
+ createRouteMap({ rename: routes.rename, disable: routes.disable });
770
+ } catch (e) {
771
+ error("C9", `theme.config.js routes: ${e.message}`);
772
+ }
773
+ for (const [from, to] of Object.entries(routes.rename ?? {})) {
774
+ const shape = shapeOf(String(to));
775
+ if (shape === "posts" || shape.startsWith("posts/")) {
776
+ error("C9", `routes.rename "${from}" -> "${to}": /posts is reserved for the posts feed; pick another public path`);
777
+ } else if (shape.startsWith("__pano")) {
778
+ error("C9", `routes.rename "${from}" -> "${to}": /__pano* is reserved; pick another public path`);
779
+ }
780
+ }
781
+
782
+ const added = Object.entries(routes.add ?? {});
783
+ if (added.length) {
784
+ const live = new Set(CORE_PAGE_PATHS.map(shapeOf));
785
+ // the pages of a synced theme, except the shims `sync` generated for routes.add itself
786
+ const addedShapes = new Set(added.map(([p]) => shapeOf(p)));
787
+ for (const file of walkFiles(join(themeDir, "src", "routes"), (n) => n === "+page.svelte")) {
788
+ if (file.includes("[...path]")) continue;
789
+ const parts = relative(join(themeDir, "src", "routes"), dirname(file)).split(sep).filter((p) => p && !/^\(.*\)$/.test(p));
790
+ const shape = shapeOf("/" + parts.join("/"));
791
+ if (!addedShapes.has(shape)) live.add(shape);
792
+ }
793
+ for (const ns of snapshotNamespaces) {
794
+ for (const rec of Object.values(snapshot(ns)?.views?.views ?? {})) {
795
+ if (rec?.page?.path) live.add(shapeOf(rec.page.path));
796
+ }
797
+ }
798
+ for (const [from] of Object.entries(routes.rename ?? {})) live.delete(shapeOf(from));
799
+
800
+ const publics = new Set(Object.values(routes.rename ?? {}).map((p) => shapeOf(String(p))));
801
+ const seenAdds = new Set();
802
+ for (const [p, file] of added) {
803
+ try {
804
+ createRouteMap({ disable: [p] });
805
+ } catch (e) {
806
+ error("C9", `routes.add "${p}": ${e.message}`);
807
+ continue;
808
+ }
809
+ const shape = shapeOf(p);
810
+ if (shape === "posts" || shape.startsWith("posts/")) error("C9", `routes.add "${p}": /posts is reserved for the posts feed; pick another path`);
811
+ else if (shape.startsWith("__pano")) error("C9", `routes.add "${p}": /__pano* is reserved; pick another path`);
812
+ else if (live.has(shape)) error("C9", `routes.add "${p}": the engine or a plugin already serves this path; use views to redraw it, or rename it`);
813
+ else if (publics.has(shape)) error("C9", `routes.add "${p}": a renamed route is already published at this path`);
814
+ else if (seenAdds.has(shape)) error("C9", `routes.add "${p}": two entries add the same route`);
815
+ seenAdds.add(shape);
816
+ if (typeof file !== "string" || !existsSync(resolve(themeDir, file.replace(/^\//, "")))) {
817
+ error("C9", `routes.add "${p}": page file ${JSON.stringify(file)} does not exist`);
818
+ }
819
+ }
820
+ }
821
+ }
822
+
823
+ // --- C10: home ----------------------------------------------------------------------------------------------
824
+ if (cfg?.home) {
825
+ const home = cfg.home;
826
+ const options = home.options ?? {};
827
+ for (const [id, opt] of Object.entries(options)) {
828
+ if (!/^[a-z0-9-]+$/.test(id)) error("C10", `home.options "${id}": ids are [a-z0-9-]+; rename the option`);
829
+ const o = /** @type {any} */ (opt) ?? {};
830
+ if (o.page !== undefined) {
831
+ const file = typeof o.page === "string" ? o.page : null;
832
+ let target = file;
833
+ if (!target) {
834
+ const probe = readOverridesFromEntry(o.page);
835
+ target = probe;
836
+ }
837
+ if (!target || !existsSync(resolve(themeDir, target.replace(/^\//, "")))) {
838
+ error("C10", `home.options "${id}": page file ${JSON.stringify(target ?? String(o.page))} does not exist`);
839
+ }
840
+ }
841
+ if (o.path !== undefined && !(typeof o.path === "string" && (o.path === "*" || o.path.startsWith("/")))) {
842
+ error("C10", `home.options "${id}": path must start with "/" or be "*"; found ${JSON.stringify(o.path)}`);
843
+ }
844
+ }
845
+ if (home.default !== undefined && home.default !== "posts" && !(home.default in options)) {
846
+ error("C10", `home.default "${home.default}" is not one of home.options (${Object.keys(options).join(", ") || "none"}); add the option or pick another default`);
847
+ }
848
+ }
849
+
850
+ // --- C12: controller pins ---------------------------------------------------------------------------------------
851
+ {
852
+ /** @type {Map<string, string[]>} name -> where it is used */
853
+ const used = new Map();
854
+ const useAt = (name, where) => used.set(name, [...(used.get(name) ?? []), where]);
855
+ for (const v of views) for (const c of v.ov.controllers) useAt(c, `view '${v.ov.key}'`);
856
+ const sources = walkFiles(join(themeDir, "src"), (n) => /\.(svelte|js|mjs)$/.test(n), [
857
+ "node_modules",
858
+ ".git",
859
+ ".svelte-kit",
860
+ "build",
861
+ "routes",
862
+ "lib",
863
+ ]);
864
+ for (const file of sources) {
865
+ const text = stripHtmlComments(blankJsComments(read(file)));
866
+ for (const m of text.matchAll(/\bplugin\(\s*(["'])([\w-]+)\1\s*\)\s*\.\s*(?:use|require|load)\(\s*(["'])([\w-]+)\3/g)) {
867
+ const parsed = parseViewId(`${m[2]}:x`);
868
+ useAt(`${parsed.ns}/${m[4]}`, `${rel(file)}:${lineOf(text, m.index)}`);
869
+ }
870
+ }
871
+
872
+ const pins = cfg?.controllers && typeof cfg.controllers === "object" ? cfg.controllers : {};
873
+ /** @type {Map<string, number>} */
874
+ const toWrite = new Map();
875
+ /** @type {Map<string, string>} */
876
+ const messages = new Map();
877
+ const ctrlNoSnapshot = new Set();
878
+ for (const [name, where] of used) {
879
+ const ns = name.split("/")[0];
880
+ const snap = snapshot(ns);
881
+ if (!snap?.controllers) {
882
+ if (!ctrlNoSnapshot.has(ns) && !noSnapshotWarned.has(ns)) {
883
+ ctrlNoSnapshot.add(ns);
884
+ warn("C12", `controller pins for plugin '${ns}' cannot be checked (${where[0]}): no controllers snapshot; run: theme-core contracts pull`);
885
+ }
886
+ continue;
887
+ }
888
+ const rec = snap.controllers[name];
889
+ if (!rec) {
890
+ warn("C12", `controller '${name}' (${where[0]}) is not in the '${ns}' snapshot (typo, or removed by the plugin); run: theme-core contracts pull`);
891
+ continue;
892
+ }
893
+ const current = pins[name];
894
+ if (current === rec.version) continue;
895
+ toWrite.set(name, rec.version);
896
+ messages.set(
897
+ name,
898
+ current === undefined
899
+ ? `controller '${name}' (${where[0]}) has no pin in theme.config.js controllers; the plugin is at version ${rec.version}: run: theme-core check --fix`
900
+ : `controller '${name}' is pinned to ${current}, the plugin is at version ${rec.version}; after merging the plugin's change: run: theme-core check --fix`,
901
+ );
902
+ }
903
+
904
+ if (toWrite.size) {
905
+ let written = false;
906
+ if (fix && hasConfig) {
907
+ const next = writePins(configSource, toWrite);
908
+ if (next !== null) {
909
+ writeFileSync(themeConfigPath, next);
910
+ written = true;
911
+ for (const [name, version] of toWrite) fixed.push(`pinned controller '${name}' to version ${version} in theme.config.js`);
181
912
  } else {
182
- for (const tab in extTabs) {
183
- tabSet.add(tab);
184
- const keys = extTabs[tab];
185
- if (!Array.isArray(keys) || keys.some((k) => typeof k !== "string")) {
186
- problems.push(`theme.config.js: settingsSchema.tabs['${tab}'] must be an array of setting-key strings`);
187
- continue;
188
- }
189
- for (const key of keys) {
190
- const owner = keyToTab[key];
191
- if (owner === undefined) keyToTab[key] = tab;
192
- else if (owner !== tab)
193
- problems.push(`settingsSchema key '${key}' is declared in tab '${tab}' but already belongs to tab '${owner}' — the same key in two tabs makes save/reset ambiguous`);
194
- // owner === tab → harmless duplicate, deduped at runtime
913
+ warn("C12", `theme.config.js could not be edited automatically; add to the default export: controllers: { ${[...toWrite].map(([n, v]) => `${JSON.stringify(n)}: ${v}`).join(", ")} }`);
914
+ }
915
+ }
916
+ if (!written && !(fix && hasConfig)) for (const m of messages.values()) warn("C12", m);
917
+ }
918
+ }
919
+
920
+ // --- C13: styles <-> provides.bootstrap ---------------------------------------------------------------------------------
921
+ {
922
+ const stylesDir = join(themeDir, "src", "styles");
923
+ const scss = walkFiles(stylesDir, (n) => n.endsWith(".scss"));
924
+ const provides = cfg?.provides?.bootstrap;
925
+ let bootstrapLine = null;
926
+ let sdkMain = false;
927
+ let tokens = false;
928
+ for (const file of scss) {
929
+ const lines = blankJsComments(read(file)).split("\n");
930
+ lines.forEach((line, i) => {
931
+ if (!/@(?:import|use|forward)\b/.test(line)) return;
932
+ if (/bootstrap\/scss/.test(line)) bootstrapLine ??= { at: `${rel(file)}:${i + 1}`, text: line.trim() };
933
+ if (/@panomc\/sdk\/core\/scss\/main/.test(line)) {
934
+ sdkMain = true;
935
+ bootstrapLine ??= { at: `${rel(file)}:${i + 1}`, text: line.trim() };
936
+ }
937
+ if (/pano-tokens/.test(line)) tokens = true;
938
+ });
939
+ }
940
+ if (provides === false) {
941
+ if (bootstrapLine) {
942
+ error("C13", `provides.bootstrap is false but ${bootstrapLine.at} imports Bootstrap; remove this import line: ${bootstrapLine.text}`);
943
+ }
944
+ info("C13", "provides.bootstrap is false: plugin fallback styles need @scope, color-mix() and @layer (Chrome 118, Safari 17.4, Firefox 146)");
945
+ } else if (scss.length) {
946
+ if (!bootstrapLine) {
947
+ warn("C13", `no Bootstrap import in src/styles/**/*.scss while provides.bootstrap is not false; add the line: @import "node_modules/@panomc/sdk/core/scss/main"; (or set provides: { bootstrap: false })`);
948
+ } else if (!sdkMain && !tokens) {
949
+ error("C13", `${bootstrapLine.at} imports Bootstrap directly but nothing imports pano-tokens, so the --pano-* variables are missing; add the line: @import "node_modules/@panomc/sdk/core/scss/pano-tokens";`);
950
+ }
951
+ }
952
+ }
953
+
954
+ // --- lang-overrides ------------------------------------------------------------------------------------------------------------
955
+ const langOverrides = join(themeDir, "lang-overrides");
956
+ if (existsSync(langOverrides)) {
957
+ for (const entry of readdirSync(langOverrides, { withFileTypes: true })) {
958
+ if (entry.isFile() && entry.name.endsWith(".json")) {
959
+ try {
960
+ JSON.parse(read(join(langOverrides, entry.name)));
961
+ } catch (e) {
962
+ error(null, `lang-overrides/${entry.name} is not valid JSON: ${e.message}; fix the syntax`);
963
+ }
964
+ }
965
+ }
966
+ // C15: lang-overrides/plugins/<ns>/<locale>.json
967
+ const pluginLang = join(langOverrides, "plugins");
968
+ if (existsSync(pluginLang)) {
969
+ for (const entry of readdirSync(pluginLang, { withFileTypes: true })) {
970
+ if (!entry.isDirectory()) {
971
+ error("C15", `lang-overrides/plugins/${entry.name}: expected a folder named after the plugin namespace (lang-overrides/plugins/<ns>/<locale>.json)`);
972
+ continue;
973
+ }
974
+ if (!/^[a-z0-9-]+$/.test(entry.name)) {
975
+ error("C15", `lang-overrides/plugins/${entry.name}: the folder must match ^[a-z0-9-]+$; rename it to the plugin namespace`);
976
+ }
977
+ for (const file of walkFiles(join(pluginLang, entry.name), (n) => n.endsWith(".json"))) {
978
+ let data;
979
+ try {
980
+ data = JSON.parse(read(file));
981
+ } catch (e) {
982
+ error("C15", `${rel(file)} is not valid JSON: ${e.message}; fix the syntax`);
983
+ continue;
984
+ }
985
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
986
+ error("C15", `${rel(file)} must hold a JSON object at the top: { "theme": { … } }`);
987
+ }
988
+ }
989
+ }
990
+ }
991
+ }
992
+
993
+ // --- manifest ----------------------------------------------------------------------------------------------------------------------
994
+ const manifestPath = join(themeDir, "manifest.json");
995
+ if (existsSync(manifestPath)) {
996
+ const manifest = JSON.parse(read(manifestPath));
997
+ for (const key of ["id", "title", "version", "author", "panoVersion", "screenshots"]) {
998
+ if (!(key in manifest)) error(null, `manifest.json missing required key '${key}' (install is refused without it); add it`);
999
+ }
1000
+ if (manifest.id === "vanilla-theme" && themePkg.name !== "pano-vanilla-theme") {
1001
+ error(null, `manifest id 'vanilla-theme' is reserved for the SYSTEM theme — installs would be refused; pick another id`);
1002
+ }
1003
+ } else {
1004
+ error(null, "manifest.json missing; create it (see: theme-core new)");
1005
+ }
1006
+
1007
+ // --- settingsSchema ------------------------------------------------------------------------------------------------------------------
1008
+ // The config is imported (not regex-scanned): the schema is a nested object literal, and the view
1009
+ // thunks stay lazy, so importing it runs no Svelte code.
1010
+ if (cfg && contract.settings_tabs) {
1011
+ const settingsSchema = cfg.settingsSchema ?? null;
1012
+ if (settingsSchema != null) {
1013
+ if (typeof settingsSchema !== "object" || Array.isArray(settingsSchema)) {
1014
+ error(null, "theme.config.js: settingsSchema must be an object ({ tabs?, defaultTab? })");
1015
+ } else {
1016
+ // base tab -> keys, dropping the "_note" doc string (non-array values)
1017
+ const baseTabs = {};
1018
+ for (const tab in contract.settings_tabs) {
1019
+ if (Array.isArray(contract.settings_tabs[tab])) baseTabs[tab] = contract.settings_tabs[tab];
1020
+ }
1021
+ // key -> the single tab it may live in; base first, extension appends. A key mapped to two
1022
+ // different tabs is a save conflict (save/reset are per-tab); same-tab duplicates dedupe.
1023
+ const keyToTab = {};
1024
+ for (const tab in baseTabs) for (const key of baseTabs[tab]) keyToTab[key] = tab;
1025
+ const tabSet = new Set(Object.keys(baseTabs));
1026
+
1027
+ const extTabs = settingsSchema.tabs;
1028
+ if (extTabs != null) {
1029
+ if (typeof extTabs !== "object" || Array.isArray(extTabs)) {
1030
+ error(null, "theme.config.js: settingsSchema.tabs must be an object mapping tabId -> string[]");
1031
+ } else {
1032
+ for (const tab in extTabs) {
1033
+ tabSet.add(tab);
1034
+ const keys = extTabs[tab];
1035
+ if (!Array.isArray(keys) || keys.some((k) => typeof k !== "string")) {
1036
+ error(null, `theme.config.js: settingsSchema.tabs['${tab}'] must be an array of setting-key strings`);
1037
+ continue;
1038
+ }
1039
+ for (const key of keys) {
1040
+ const owner = keyToTab[key];
1041
+ if (owner === undefined) keyToTab[key] = tab;
1042
+ else if (owner !== tab)
1043
+ error(null, `settingsSchema key '${key}' is declared in tab '${tab}' but already belongs to tab '${owner}' — the same key in two tabs makes save/reset ambiguous; keep it in one tab`);
1044
+ }
195
1045
  }
196
1046
  }
197
1047
  }
1048
+
1049
+ if (settingsSchema.defaultTab != null) {
1050
+ if (typeof settingsSchema.defaultTab !== "string") {
1051
+ error(null, "theme.config.js: settingsSchema.defaultTab must be a string");
1052
+ } else if (!tabSet.has(settingsSchema.defaultTab)) {
1053
+ error(null, `settingsSchema.defaultTab '${settingsSchema.defaultTab}' is not a known tab (base tabs + your settingsSchema.tabs) — the settings page would open on an empty tab; pick an existing tab`);
1054
+ }
1055
+ }
198
1056
  }
1057
+ }
1058
+ }
199
1059
 
200
- if (settingsSchema.defaultTab != null) {
201
- if (typeof settingsSchema.defaultTab !== "string") {
202
- problems.push("theme.config.js: settingsSchema.defaultTab must be a string");
203
- } else if (!tabSet.has(settingsSchema.defaultTab)) {
204
- problems.push(`settingsSchema.defaultTab '${settingsSchema.defaultTab}' is not a known tab (base tabs + your settingsSchema.tabs) — the settings page would open on an empty tab`);
1060
+ // --- i18n keys used by overridden views must exist in the MERGED lang tree -------------------------------------------------------------
1061
+ // (lang/ is generated: core base + lang-overrides). A missing key renders raw on screen. WARNING, not
1062
+ // error: some keys may be served by the backend's dynamic THEME translations at runtime.
1063
+ const viewsDir = join(themeDir, "src", "views");
1064
+ const mergedLangPath = join(themeDir, "lang", "en-US.json");
1065
+ if (existsSync(viewsDir) && existsSync(mergedLangPath)) {
1066
+ const lang = JSON.parse(read(mergedLangPath));
1067
+ const hasKey = (dotted) => {
1068
+ let node = lang;
1069
+ for (const part of dotted.split(".")) {
1070
+ if (node == null || typeof node !== "object" || !(part in node)) return false;
1071
+ node = node[part];
1072
+ }
1073
+ return true;
1074
+ };
1075
+ for (const file of walkFiles(viewsDir, (n) => n.endsWith(".svelte"))) {
1076
+ // static literals only: the closing quote must be followed by ')' or ',' so concatenated
1077
+ // dynamic keys like $_("errors." + code) are skipped
1078
+ for (const m of read(file).matchAll(/\$_\(\s*["']([\w.-]+)["']\s*[),]/g)) {
1079
+ if (!hasKey(m[1])) {
1080
+ warn(null, `src/views/${file.slice(viewsDir.length + 1)} uses i18n key '${m[1]}' missing from the merged lang tree — it will render raw; add it to lang-overrides/`);
205
1081
  }
206
1082
  }
207
1083
  }
208
1084
  }
209
- }
210
1085
 
211
- // 7. i18n keys used by overridden views must exist in the MERGED lang tree
212
- // (lang/ is generated: core base + lang-overrides). A missing key renders raw
213
- // on screen ("components.header.status"). WARNING not FAIL: some keys may be
214
- // served by the backend's dynamic THEME translations at runtime.
215
- const viewsDir = join(themeDir, "src", "views");
216
- const mergedLangPath = join(themeDir, "lang", "en-US.json");
217
- if (existsSync(viewsDir) && existsSync(mergedLangPath)) {
218
- const lang = JSON.parse(readFileSync(mergedLangPath, "utf-8"));
219
- const hasKey = (dotted) => {
220
- let node = lang;
221
- for (const part of dotted.split(".")) {
222
- if (node == null || typeof node !== "object" || !(part in node)) return false;
223
- node = node[part];
224
- }
225
- return true;
226
- };
227
- const scan = (dir) => {
228
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
229
- const p = join(dir, entry.name);
230
- if (entry.isDirectory()) scan(p);
231
- else if (entry.name.endsWith(".svelte")) {
232
- const src = readFileSync(p, "utf-8");
233
- // static literals only: $_("a.b.c") / $_('a.b.c') — the closing quote
234
- // must be followed by ')' or ',' so concatenated dynamic keys like
235
- // $_("errors." + code) are skipped
236
- for (const m of src.matchAll(/\$_\(\s*["']([\w.-]+)["']\s*[),]/g)) {
237
- if (!hasKey(m[1])) {
238
- warnings.push(
239
- `src/views/${p.slice(viewsDir.length + 1)} uses i18n key '${m[1]}' missing from the merged lang tree — it will render raw; add it to lang-overrides/`,
240
- );
241
- }
1086
+ // --- C16: API path literals are Pano routes -----------------------------------------------------------------------------------------------------
1087
+ {
1088
+ const panoApi = findPanoApi(themeDir, pkgDir);
1089
+ if (!panoApi) {
1090
+ warn("C16", "API paths were not checked: @panomc/sdk (pano-api) is not installed; run: bun install");
1091
+ } else {
1092
+ const args = [panoApi, "check-paths"];
1093
+ if (env.PANO_CHECK_ROUTES) args.push("--routes", env.PANO_CHECK_ROUTES);
1094
+ args.push(themeDir);
1095
+ const r = spawnSync(process.execPath, args, { encoding: "utf-8", cwd: themeDir });
1096
+ const lines = `${r.stdout ?? ""}${r.stderr ?? ""}`.split("\n").map((l) => l.trim()).filter(Boolean);
1097
+ if (r.status === 1) {
1098
+ for (const line of lines) {
1099
+ if (line.startsWith("check-paths:")) continue;
1100
+ error("C16", line);
242
1101
  }
1102
+ } else if (r.status !== 0) {
1103
+ const why = lines.find((l) => !l.startsWith("check-paths:")) ?? `exit ${r.status}`;
1104
+ warn("C16", `API paths were not checked (${why.replace(/^error:\s*/, "")}); run: bun install`);
243
1105
  }
244
1106
  }
1107
+ }
1108
+
1109
+ const levelOf = (f) => (strict && f.level === "warning" ? "error" : f.level);
1110
+ const settled = findings.map((f) => ({ ...f, level: levelOf(f) }));
1111
+ return {
1112
+ findings: settled,
1113
+ problems: settled.filter((f) => f.level === "error"),
1114
+ warnings: settled.filter((f) => f.level === "warning"),
1115
+ infos: settled.filter((f) => f.level === "info"),
1116
+ fixed,
1117
+ overrides: overrides.length,
1118
+ strict,
245
1119
  };
246
- scan(viewsDir);
247
1120
  }
248
1121
 
249
- console.log(pc.dim(`theme-core check — validating against core ${corePkg.version}`));
1122
+ /** A home page option given as a thunk: the path inside its source text. */
1123
+ function readOverridesFromEntry(entry) {
1124
+ if (typeof entry === "function") {
1125
+ const source = Function.prototype.toString.call(entry);
1126
+ return /\bimport\(\s*(["'`])([^"'`\n$]+)\1\s*\)/.exec(source)?.[2] ?? null;
1127
+ }
1128
+ if (entry && typeof entry === "object") return readOverridesFromEntry(entry.component ?? entry.page);
1129
+ return null;
1130
+ }
250
1131
 
251
- for (const w of warnings) console.log(` ${pc.yellow("▲")} ${w}`);
252
- if (problems.length) {
253
- for (const p of problems) console.error(` ${pc.red("✗")} ${p}`);
254
- console.error(
255
- pc.red(
256
- `\n${problems.length} problem${problems.length === 1 ? "" : "s"} must be fixed before this theme ships.`,
257
- ),
1132
+ /** pano-api.js of the theme's installed @panomc/sdk, else the sibling package of this monorepo. */
1133
+ function findPanoApi(themeDir, pkgDir) {
1134
+ const candidates = [];
1135
+ try {
1136
+ const req = createRequire(join(themeDir, "package.json"));
1137
+ candidates.push(join(dirname(req.resolve("@panomc/sdk/package.json")), "bin", "pano-api.js"));
1138
+ } catch {
1139
+ /* not installed in the theme */
1140
+ }
1141
+ candidates.push(join(themeDir, "node_modules", "@panomc", "sdk", "bin", "pano-api.js"));
1142
+ candidates.push(join(pkgDir, "..", "sdk", "bin", "pano-api.js"));
1143
+ try {
1144
+ const req = createRequire(join(pkgDir, "package.json"));
1145
+ candidates.push(join(dirname(req.resolve("@panomc/sdk/package.json")), "bin", "pano-api.js"));
1146
+ } catch {
1147
+ /* not resolvable from the engine either */
1148
+ }
1149
+ return candidates.find((c) => existsSync(c) && statSync(c).isFile()) ?? null;
1150
+ }
1151
+
1152
+ // ---------------------------------------------------------------------------
1153
+ // CLI
1154
+ // ---------------------------------------------------------------------------
1155
+
1156
+ /** @param {string[]} argv */
1157
+ export function parseArgs(argv) {
1158
+ const flags = { strict: false, fix: false, help: false };
1159
+ const unknown = [];
1160
+ for (const a of argv) {
1161
+ if (a === "--strict") flags.strict = true;
1162
+ else if (a === "--fix") flags.fix = true;
1163
+ else if (a === "--help" || a === "-h") flags.help = true;
1164
+ else unknown.push(a);
1165
+ }
1166
+ return { ...flags, unknown };
1167
+ }
1168
+
1169
+ async function main() {
1170
+ const args = parseArgs(process.argv.slice(2));
1171
+ if (args.help) {
1172
+ console.log("theme-core check [--strict] [--fix]\n --strict warnings count as errors (theme-core package always runs strict)\n --fix write controller pins into theme.config.js (C12)");
1173
+ return;
1174
+ }
1175
+ if (args.unknown.length) {
1176
+ console.error(`theme-core check: unknown argument ${args.unknown.map((a) => `'${a}'`).join(", ")}; use: theme-core check [--strict] [--fix]`);
1177
+ process.exit(2);
1178
+ }
1179
+
1180
+ const corePkg = JSON.parse(readFileSync(join(defaultPkgDir, "package.json"), "utf-8"));
1181
+ const report = await runChecks({ strict: args.strict, fix: args.fix });
1182
+ const tag = (f) => (f.rule ? `[${f.rule}] ` : "");
1183
+
1184
+ console.log(pc.dim(`theme-core check${args.strict ? " --strict" : ""} — validating against core ${corePkg.version}`));
1185
+ for (const f of report.infos) console.log(` ${pc.dim("i")} ${pc.dim(tag(f) + f.message)}`);
1186
+ for (const f of report.warnings) console.log(` ${pc.yellow("▲")} ${tag(f)}${f.message}`);
1187
+ for (const line of report.fixed) console.log(` ${pc.green("✓")} fixed: ${line}`);
1188
+
1189
+ if (report.problems.length) {
1190
+ for (const f of report.problems) console.error(` ${pc.red("✗")} ${tag(f)}${f.message}`);
1191
+ const n = report.problems.length;
1192
+ console.error(pc.red(`\n${n} problem${n === 1 ? "" : "s"} must be fixed before this theme ships${args.strict ? " (strict: warnings count)" : ""}.`));
1193
+ process.exit(1);
1194
+ }
1195
+ console.log(
1196
+ ` ${pc.green("✓")} ${pc.bold("OK")} — ${report.overrides} view override${report.overrides === 1 ? "" : "s"} validated against core ${corePkg.version}`,
258
1197
  );
259
- process.exit(1);
260
1198
  }
261
- console.log(
262
- ` ${pc.green("✓")} ${pc.bold("OK")} — ${registered.length} view override${registered.length === 1 ? "" : "s"} validated against core ${corePkg.version}`,
263
- );
1199
+
1200
+ if (import.meta.main) await main();