@capybara-hq/kernel 0.1.0-rc.10 → 0.1.0-rc.11

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 (79) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/catalog/catalog-content.d.ts +33 -1
  3. package/dist/catalog/catalog-content.js +65 -2
  4. package/dist/catalog/catalog-items.js +1 -0
  5. package/dist/catalog/catalog-scope.service.d.ts +29 -3
  6. package/dist/catalog/catalog-scope.service.js +82 -10
  7. package/dist/catalog/catalog.service.d.ts +7 -5
  8. package/dist/catalog/catalog.service.js +26 -5
  9. package/dist/catalog/claude/translate.js +3 -0
  10. package/dist/catalog/component-scope.schemas.d.ts +4 -0
  11. package/dist/catalog/component-scope.service.d.ts +48 -9
  12. package/dist/catalog/component-scope.service.js +152 -27
  13. package/dist/catalog/component-state.d.ts +12 -3
  14. package/dist/catalog/component-state.js +21 -3
  15. package/dist/catalog/marketplaces.service.d.ts +1 -1
  16. package/dist/catalog/org-catalog.service.js +3 -0
  17. package/dist/catalog/owned-items.js +7 -0
  18. package/dist/catalog/platform-components.d.ts +23 -3
  19. package/dist/catalog/platform-components.js +118 -9
  20. package/dist/catalog/platform-migration.js +2 -1
  21. package/dist/catalog/plugin-import.d.ts +24 -4
  22. package/dist/catalog/plugin-import.js +37 -6
  23. package/dist/catalog/plugin-install.d.ts +20 -1
  24. package/dist/catalog/plugin-install.js +71 -1
  25. package/dist/catalog/plugin-package.d.ts +41 -4
  26. package/dist/catalog/plugin-package.js +127 -7
  27. package/dist/catalog/plugin-upgrade.d.ts +13 -2
  28. package/dist/catalog/plugin-upgrade.js +124 -6
  29. package/dist/catalog/unshare.js +1 -0
  30. package/dist/db/kernel-schema.d.ts +41 -4
  31. package/dist/errors.d.ts +25 -0
  32. package/dist/errors.js +25 -0
  33. package/dist/http/api.module.js +7 -0
  34. package/dist/identity/accounts.d.ts +11 -4
  35. package/dist/identity/accounts.js +23 -10
  36. package/dist/identity/me.controller.d.ts +10 -10
  37. package/dist/identity/me.controller.js +8 -6
  38. package/dist/identity/me.schemas.d.ts +13 -3
  39. package/dist/identity/me.schemas.js +10 -2
  40. package/dist/identity/settings.d.ts +27 -0
  41. package/dist/identity/settings.js +64 -0
  42. package/dist/orgs/settings.service.d.ts +31 -0
  43. package/dist/orgs/settings.service.js +31 -1
  44. package/dist/platform/exclusions.js +16 -0
  45. package/dist/platform/operation.js +6 -2
  46. package/dist/platform/ops/admin.ops.d.ts +3 -1
  47. package/dist/platform/ops/admin.ops.js +25 -7
  48. package/dist/platform/ops/components.ops.js +1 -0
  49. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  50. package/dist/platform/ops/org-settings.ops.js +33 -8
  51. package/dist/platform/ops/orgs.ops.js +1 -0
  52. package/dist/platform/ops/platform.ops.d.ts +3 -1
  53. package/dist/platform/ops/platform.ops.js +43 -16
  54. package/dist/platform/ops/themes.ops.d.ts +14 -0
  55. package/dist/platform/ops/themes.ops.js +47 -0
  56. package/dist/platform/platform-ops.module.d.ts +2 -1
  57. package/dist/platform/platform-ops.module.js +5 -0
  58. package/dist/platform/route-schemas.js +3 -0
  59. package/dist/themes/render-css.d.ts +12 -0
  60. package/dist/themes/render-css.js +132 -0
  61. package/dist/themes/theme-delivery.service.d.ts +34 -0
  62. package/dist/themes/theme-delivery.service.js +111 -0
  63. package/dist/themes/theme-state.d.ts +95 -0
  64. package/dist/themes/theme-state.js +203 -0
  65. package/dist/themes/theme-usage.d.ts +61 -0
  66. package/dist/themes/theme-usage.js +98 -0
  67. package/dist/themes/themes-public.controller.d.ts +28 -0
  68. package/dist/themes/themes-public.controller.js +92 -0
  69. package/dist/themes/themes.controller.d.ts +13 -0
  70. package/dist/themes/themes.controller.js +38 -0
  71. package/dist/themes/themes.module.d.ts +3 -0
  72. package/dist/themes/themes.module.js +21 -0
  73. package/dist/themes/themes.schemas.d.ts +3 -0
  74. package/dist/themes/themes.schemas.js +2 -0
  75. package/dist/themes/themes.service.d.ts +50 -0
  76. package/dist/themes/themes.service.js +99 -0
  77. package/package.json +3 -3
  78. package/src/migrations/0102_themes.sql +64 -0
  79. package/src/migrations/0103_ui_theme_setting.sql +7 -0
@@ -0,0 +1,98 @@
1
+ // Who uses a theme (themes spec §6 "Losing access", §7): the platform default (`deployment_settings`
2
+ // key `uiTheme`), the orgs whose default it is (`orgs.settings.theme.id`) and the people who picked
3
+ // it (`accounts.theme`); the previews of changes that take a theme away list them, and the guard
4
+ // refuses any change that takes the platform default away from an org. Plain reads in the caller's
5
+ // context (a transaction's connection when there is one). The settings are read through the same
6
+ // readers and schemas as their services (`readUiTheme`, `parseOrgSettings`), so the two never drift.
7
+ import { sql } from "kysely";
8
+ import { ApiError } from "../errors.js";
9
+ import { readUiTheme, UI_THEME_SETTING } from "../identity/settings.js";
10
+ import { parseOrgSettings } from "../orgs/settings.service.js";
11
+ /**
12
+ * The platform default theme's id (null: the built-in theme, or not set), through the setting's
13
+ * typed reader; `lock`: the row is read FOR SHARE, so a concurrent write of the setting (which
14
+ * locks it FOR UPDATE first, see `SettingsService`) waits for the caller's transaction, and the
15
+ * reverse.
16
+ */
17
+ export async function platformDefaultThemeId(db, opts = {}) {
18
+ return (await readUiTheme(db, opts)).id;
19
+ }
20
+ /** Where theme `themeId` (a `platform_themes` id) is chosen: see {@link ThemeUsage}. */
21
+ export async function themeUsage(db, themeId) {
22
+ const platformDefault = (await platformDefaultThemeId(db)) === themeId;
23
+ // the jsonb filter narrows the rows; the typed parse decides (an invalid stored value is no default)
24
+ const orgs = (await db
25
+ .selectFrom("orgs")
26
+ .select(["id", "name", "settings"])
27
+ .where("deleted_at", "is", null)
28
+ .where(sql `settings -> 'theme' ->> 'id'`, "=", themeId)
29
+ .orderBy("name")
30
+ .orderBy("id")
31
+ .execute()).filter((o) => parseOrgSettings(o.settings).theme?.id === themeId);
32
+ const picked = await db
33
+ .selectFrom("accounts")
34
+ .select((eb) => eb.fn.countAll().as("n"))
35
+ .where("theme", "=", themeId)
36
+ .executeTakeFirstOrThrow();
37
+ return {
38
+ platformDefault,
39
+ orgDefaults: orgs.map((o) => ({ orgId: o.id, orgName: o.name })),
40
+ pickedBy: Number(picked.n),
41
+ };
42
+ }
43
+ /**
44
+ * The `themes` block of a preview: for each theme of `lost` (theme id -> the orgs losing it) that
45
+ * some org loses, the orgs among those whose default it is and how many of their members picked
46
+ * it, by id.
47
+ * Undefined when no theme is lost, so a preview without themes keeps its shape and its hash.
48
+ */
49
+ export async function themesPreview(db, lost) {
50
+ const out = [];
51
+ for (const id of [...lost.keys()].sort()) {
52
+ const orgs = lost.get(id);
53
+ if (!orgs || orgs.size === 0)
54
+ continue;
55
+ const u = await themeUsage(db, id);
56
+ out.push({
57
+ id,
58
+ orgDefaults: u.orgDefaults.filter((o) => orgs.has(o.orgId)),
59
+ pickedBy: await pickedByIn(db, id, orgs),
60
+ });
61
+ }
62
+ return out.length > 0 ? out : undefined;
63
+ }
64
+ /** How many members of `orgs` (each counted once) picked theme `id`. */
65
+ export async function pickedByIn(db, id, orgs) {
66
+ if (orgs.size === 0)
67
+ return 0;
68
+ const picked = await db
69
+ .selectFrom("accounts as a")
70
+ .select((eb) => eb.fn.count("a.id").distinct().as("n"))
71
+ .where("a.theme", "=", id)
72
+ .where((eb) => eb.exists(eb
73
+ .selectFrom("memberships as m")
74
+ .select("m.account_id")
75
+ .whereRef("m.account_id", "=", "a.id")
76
+ .where("m.org_id", "in", [...orgs])))
77
+ .executeTakeFirstOrThrow();
78
+ return Number(picked.n);
79
+ }
80
+ /** 409 `theme.platform_default`: theme `theme` is the platform default (spec §7). */
81
+ export const platformDefaultError = (theme) => new ApiError("theme.platform_default", `Theme ${theme} is the platform default theme (setting ${UI_THEME_SETTING}): it must stay on in every organization. Choose another platform default theme first, then narrow, disable or remove this one`, [{ theme, setting: UI_THEME_SETTING }]);
82
+ /**
83
+ * Refuses a change that takes the platform default theme away from any org (spec §7): when one of
84
+ * `themeIds` is the platform default and `after` says it would no longer be `all` (narrower, or
85
+ * gone), 409 `theme.platform_default`. Call it in the change's transaction before anything is
86
+ * written, after locking the catalog item or theme rows the change touches (the one theme lock
87
+ * order: catalog item, theme row, then the `uiTheme` row, which this reads FOR SHARE; the setting's
88
+ * write takes them in the same order).
89
+ */
90
+ export async function assertNotPlatformDefault(db, themeIds, after) {
91
+ if (themeIds.length === 0)
92
+ return;
93
+ const id = await platformDefaultThemeId(db, { lock: true });
94
+ if (id === null || !themeIds.includes(id))
95
+ return;
96
+ if (after(id) !== "all")
97
+ throw platformDefaultError(id);
98
+ }
@@ -0,0 +1,28 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
3
+ import type { ThemeRef } from "./theme-state.js";
4
+ import { ThemesService } from "./themes.service.js";
5
+ /**
6
+ * Theme delivery (themes spec §8): every theme version's stylesheet and assets, public (styles are
7
+ * not sensitive; the URLs reveal only that the theme exists) and immutable. The URLs are the ones
8
+ * `themeUrl` builds; an unknown theme, version or file is 404 `theme.not_found`.
9
+ */
10
+ export declare class ThemeDeliveryController {
11
+ private readonly delivery;
12
+ constructor(delivery: ThemeDeliveryService);
13
+ /** The version's stylesheet: scheme overrides, `@font-face` rules and font stacks. */
14
+ css(id: string, version: string, reply: FastifyReply): Promise<void>;
15
+ /**
16
+ * A font (`font/woff2`) or logo (`image/svg+xml`, sanitized at import, served under a CSP
17
+ * sandbox; `image/png`) the version names; `file` is its plugin path as one segment
18
+ * (`fonts%2FMiSans.woff2`).
19
+ */
20
+ asset(id: string, version: string, file: string, reply: FastifyReply): Promise<void>;
21
+ }
22
+ /** The platform default theme for pages before sign-in (themes spec §8-§9), public. */
23
+ export declare class PlatformThemeController {
24
+ private readonly themes;
25
+ constructor(themes: ThemesService);
26
+ /** The platform default's reference while it is eligible; null: the built-in theme. */
27
+ platformTheme(): Promise<ThemeRef | null>;
28
+ }
@@ -0,0 +1,92 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, Get, Header, Inject, Param, Res } from "@nestjs/common";
11
+ import { Public } from "../identity/principal.js";
12
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
13
+ import { ThemesService } from "./themes.service.js";
14
+ /** A theme version's stylesheet and assets never change (the version is in the URL). */
15
+ const IMMUTABLE = "public, max-age=31536000, immutable";
16
+ /**
17
+ * Theme delivery (themes spec §8): every theme version's stylesheet and assets, public (styles are
18
+ * not sensitive; the URLs reveal only that the theme exists) and immutable. The URLs are the ones
19
+ * `themeUrl` builds; an unknown theme, version or file is 404 `theme.not_found`.
20
+ */
21
+ let ThemeDeliveryController = class ThemeDeliveryController {
22
+ delivery;
23
+ constructor(delivery) {
24
+ this.delivery = delivery;
25
+ }
26
+ /** The version's stylesheet: scheme overrides, `@font-face` rules and font stacks. */
27
+ async css(id, version, reply) {
28
+ const css = await this.delivery.stylesheet(id, version);
29
+ await reply
30
+ .header("content-type", "text/css; charset=utf-8")
31
+ .header("x-content-type-options", "nosniff")
32
+ .header("cache-control", IMMUTABLE)
33
+ .send(css);
34
+ }
35
+ /**
36
+ * A font (`font/woff2`) or logo (`image/svg+xml`, sanitized at import, served under a CSP
37
+ * sandbox; `image/png`) the version names; `file` is its plugin path as one segment
38
+ * (`fonts%2FMiSans.woff2`).
39
+ */
40
+ async asset(id, version, file, reply) {
41
+ const a = await this.delivery.asset(id, version, file);
42
+ reply
43
+ .header("content-type", a.contentType)
44
+ .header("x-content-type-options", "nosniff")
45
+ .header("cache-control", IMMUTABLE);
46
+ if (a.contentType === "image/svg+xml") {
47
+ reply.header("content-security-policy", "default-src 'none'; sandbox");
48
+ }
49
+ await reply.send(Buffer.from(a.data.buffer, a.data.byteOffset, a.data.byteLength));
50
+ }
51
+ };
52
+ __decorate([
53
+ Public(),
54
+ Get("theme.css"),
55
+ __param(0, Param("id")),
56
+ __param(1, Param("version")),
57
+ __param(2, Res())
58
+ ], ThemeDeliveryController.prototype, "css", null);
59
+ __decorate([
60
+ Public(),
61
+ Get("assets/:file"),
62
+ __param(0, Param("id")),
63
+ __param(1, Param("version")),
64
+ __param(2, Param("file")),
65
+ __param(3, Res())
66
+ ], ThemeDeliveryController.prototype, "asset", null);
67
+ ThemeDeliveryController = __decorate([
68
+ Controller("api/v1/themes/:id/:version"),
69
+ __param(0, Inject(ThemeDeliveryService))
70
+ ], ThemeDeliveryController);
71
+ export { ThemeDeliveryController };
72
+ /** The platform default theme for pages before sign-in (themes spec §8-§9), public. */
73
+ let PlatformThemeController = class PlatformThemeController {
74
+ themes;
75
+ constructor(themes) {
76
+ this.themes = themes;
77
+ }
78
+ /** The platform default's reference while it is eligible; null: the built-in theme. */
79
+ platformTheme() {
80
+ return this.themes.platformDefault();
81
+ }
82
+ };
83
+ __decorate([
84
+ Public(),
85
+ Get(),
86
+ Header("cache-control", "no-store")
87
+ ], PlatformThemeController.prototype, "platformTheme", null);
88
+ PlatformThemeController = __decorate([
89
+ Controller("api/v1/platform/theme"),
90
+ __param(0, Inject(ThemesService))
91
+ ], PlatformThemeController);
92
+ export { PlatformThemeController };
@@ -0,0 +1,13 @@
1
+ import { type Principal } from "../identity/principal.js";
2
+ import { type OrgContext } from "../orgs/org.guard.js";
3
+ import { type OrgThemes, ThemesService } from "./themes.service.js";
4
+ /** The org's themes (`/api/v1/orgs/:orgId/themes`, themes spec §9): members only. */
5
+ export declare class OrgThemesController {
6
+ private readonly themes;
7
+ constructor(themes: ThemesService);
8
+ /**
9
+ * `{ themes, resolved, org }`: the themes on in the org (with swatches), the viewer's resolved
10
+ * theme (null: the built-in one) and the org's default and personal lock.
11
+ */
12
+ list(principal: Principal, org: OrgContext): Promise<OrgThemes>;
13
+ }
@@ -0,0 +1,38 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, Get, Inject } from "@nestjs/common";
11
+ import { CurrentPrincipal } from "../identity/principal.js";
12
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
13
+ import { ThemesService } from "./themes.service.js";
14
+ /** The org's themes (`/api/v1/orgs/:orgId/themes`, themes spec §9): members only. */
15
+ let OrgThemesController = class OrgThemesController {
16
+ themes;
17
+ constructor(themes) {
18
+ this.themes = themes;
19
+ }
20
+ /**
21
+ * `{ themes, resolved, org }`: the themes on in the org (with swatches), the viewer's resolved
22
+ * theme (null: the built-in one) and the org's default and personal lock.
23
+ */
24
+ async list(principal, org) {
25
+ return this.themes.forOrg(org.orgId, principal.kind === "user" ? principal.account.id : null);
26
+ }
27
+ };
28
+ __decorate([
29
+ Get(),
30
+ OrgAction("org.read"),
31
+ __param(0, CurrentPrincipal()),
32
+ __param(1, CurrentOrg())
33
+ ], OrgThemesController.prototype, "list", null);
34
+ OrgThemesController = __decorate([
35
+ Controller("api/v1/orgs/:orgId/themes"),
36
+ __param(0, Inject(ThemesService))
37
+ ], OrgThemesController);
38
+ export { OrgThemesController };
@@ -0,0 +1,3 @@
1
+ /** Themes (themes spec §7-§9): resolution, the org's theme listing and delivery. */
2
+ export declare class ThemesModule {
3
+ }
@@ -0,0 +1,21 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { StorageModule } from "../storage/storage.module.js";
9
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
10
+ import { ThemesService } from "./themes.service.js";
11
+ /** Themes (themes spec §7-§9): resolution, the org's theme listing and delivery. */
12
+ let ThemesModule = class ThemesModule {
13
+ };
14
+ ThemesModule = __decorate([
15
+ Module({
16
+ imports: [StorageModule],
17
+ providers: [ThemesService, ThemeDeliveryService],
18
+ exports: [ThemesService, ThemeDeliveryService],
19
+ })
20
+ ], ThemesModule);
21
+ export { ThemesModule };
@@ -0,0 +1,3 @@
1
+ import type { RouteSchemas } from "../platform/route-schemas.js";
2
+ /** The theme routes the Platform operations mirror (`check:platform-ops` keys). */
3
+ export declare const THEME_ROUTES: readonly RouteSchemas[];
@@ -0,0 +1,2 @@
1
+ /** The theme routes the Platform operations mirror (`check:platform-ops` keys). */
2
+ export const THEME_ROUTES = [{ route: "GET /api/v1/orgs/:orgId/themes" }];
@@ -0,0 +1,50 @@
1
+ import type { LocalizedName } from "@capybara-hq/plugin-sdk";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { type ListedTheme, type ThemeRef } from "./theme-state.js";
4
+ /** `GET /api/v1/orgs/:orgId/themes` (themes spec §9). */
5
+ export interface OrgThemes {
6
+ /** The themes on in the org, by English name. */
7
+ themes: ListedTheme[];
8
+ /** The viewer's theme ({@link ThemesService.resolve}); null: the built-in theme. */
9
+ resolved: ThemeRef | null;
10
+ /**
11
+ * The org's setting as stored: its default (null: follow the platform) and the personal lock.
12
+ * The stored id may name a theme absent from `themes` (it went off in the org after it was
13
+ * chosen; resolution skips it): the UI shows it as unavailable, not as selected.
14
+ */
15
+ org: {
16
+ id: string | null;
17
+ personal: "allowed" | "locked";
18
+ };
19
+ }
20
+ /**
21
+ * Which theme applies (themes spec §7) and the org's theme listing. Read-only; the levels are
22
+ * written by their settings services (deployment, org, person), which check availability with the
23
+ * same predicates (`theme-state.ts`).
24
+ */
25
+ export declare class ThemesService {
26
+ private readonly db;
27
+ constructor(db: KernelDb);
28
+ /** The themes on in the org with their references and swatches, by English name then id. */
29
+ listForOrg(orgId: string): Promise<ListedTheme[]>;
30
+ /**
31
+ * The theme of a signed-in page in the org (spec §7): the person's pick if it is on in the org
32
+ * and the org does not lock; else the org's default if on; else the platform default if on in
33
+ * the org; else null (the built-in theme). An unavailable choice is skipped, never an error.
34
+ * `accountId` null (a service token): no personal pick.
35
+ */
36
+ resolve(orgId: string, accountId: string | null): Promise<ThemeRef | null>;
37
+ /** The platform default for pages before sign-in, when it is still eligible (spec §7); else null. */
38
+ platformDefault(): Promise<ThemeRef | null>;
39
+ /**
40
+ * The listing, the viewer's resolved theme and the org's setting. Separate reads, not one
41
+ * snapshot: a change committed between them shows at the next read.
42
+ */
43
+ forOrg(orgId: string, accountId: string | null): Promise<OrgThemes>;
44
+ /** A live theme's name (the super admin's summaries); null when there is no such theme. */
45
+ nameOf(id: string): Promise<LocalizedName | null>;
46
+ /** Theme `id`'s name if it is on in the org, else null (a summary never names another org's theme). */
47
+ nameIn(orgId: string, id: string): Promise<LocalizedName | null>;
48
+ /** Theme `id`'s name if it is on in one of the person's orgs, else null (same reason). */
49
+ nameForAccount(accountId: string, id: string): Promise<LocalizedName | null>;
50
+ }
@@ -0,0 +1,99 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { readUiTheme } from "../identity/settings.js";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { DEFAULT_ORG_THEME, readOrgSettings } from "../orgs/settings.service.js";
14
+ import { eligiblePlatformDefault, themeDefinitions, themeOnForAccount, themeOnIn, themeRefOf, themeSwatches, themesOnIn, } from "./theme-state.js";
15
+ /**
16
+ * Which theme applies (themes spec §7) and the org's theme listing. Read-only; the levels are
17
+ * written by their settings services (deployment, org, person), which check availability with the
18
+ * same predicates (`theme-state.ts`).
19
+ */
20
+ let ThemesService = class ThemesService {
21
+ db;
22
+ constructor(db) {
23
+ this.db = db;
24
+ }
25
+ /** The themes on in the org with their references and swatches, by English name then id. */
26
+ async listForOrg(orgId) {
27
+ const on = await themesOnIn(this.db.db, orgId);
28
+ const defs = await themeDefinitions(this.db.db, on.map((c) => c.id));
29
+ const out = [];
30
+ for (const c of on) {
31
+ const d = defs.get(c.id);
32
+ if (!d)
33
+ continue;
34
+ out.push({
35
+ ...themeRefOf(c.id, d.version, d.definition),
36
+ swatches: themeSwatches(d.definition),
37
+ });
38
+ }
39
+ return out.sort((a, b) => a.name.en < b.name.en ? -1 : a.name.en > b.name.en ? 1 : a.id < b.id ? -1 : 1);
40
+ }
41
+ /**
42
+ * The theme of a signed-in page in the org (spec §7): the person's pick if it is on in the org
43
+ * and the org does not lock; else the org's default if on; else the platform default if on in
44
+ * the org; else null (the built-in theme). An unavailable choice is skipped, never an error.
45
+ * `accountId` null (a service token): no personal pick.
46
+ */
47
+ async resolve(orgId, accountId) {
48
+ return (await this.forOrg(orgId, accountId)).resolved;
49
+ }
50
+ /** The platform default for pages before sign-in, when it is still eligible (spec §7); else null. */
51
+ async platformDefault() {
52
+ const { id } = await readUiTheme(this.db.db);
53
+ if (id === null || (await eligiblePlatformDefault(this.db.db, id)) === null)
54
+ return null;
55
+ const d = (await themeDefinitions(this.db.db, [id])).get(id);
56
+ return d ? themeRefOf(id, d.version, d.definition) : null;
57
+ }
58
+ /**
59
+ * The listing, the viewer's resolved theme and the org's setting. Separate reads, not one
60
+ * snapshot: a change committed between them shows at the next read.
61
+ */
62
+ async forOrg(orgId, accountId) {
63
+ const themes = await this.listForOrg(orgId);
64
+ const org = (await readOrgSettings(this.db.db, orgId)).theme ?? DEFAULT_ORG_THEME;
65
+ const pick = accountId === null || org.personal === "locked"
66
+ ? null
67
+ : ((await this.db
68
+ .selectFrom("accounts")
69
+ .select("theme")
70
+ .where("id", "=", accountId)
71
+ .executeTakeFirst())?.theme ?? null);
72
+ const platform = (await readUiTheme(this.db.db)).id;
73
+ const on = (id) => (id === null ? undefined : themes.find((t) => t.id === id));
74
+ const hit = on(pick) ?? on(org.id) ?? on(platform);
75
+ let resolved = null;
76
+ if (hit) {
77
+ const { swatches: _swatches, ...ref } = hit;
78
+ resolved = ref;
79
+ }
80
+ return { themes, resolved, org: { id: org.id, personal: org.personal } };
81
+ }
82
+ /** A live theme's name (the super admin's summaries); null when there is no such theme. */
83
+ async nameOf(id) {
84
+ return (await themeDefinitions(this.db.db, [id])).get(id)?.definition.name ?? null;
85
+ }
86
+ /** Theme `id`'s name if it is on in the org, else null (a summary never names another org's theme). */
87
+ async nameIn(orgId, id) {
88
+ return (await themeOnIn(this.db.db, orgId, id)) ? this.nameOf(id) : null;
89
+ }
90
+ /** Theme `id`'s name if it is on in one of the person's orgs, else null (same reason). */
91
+ async nameForAccount(accountId, id) {
92
+ return (await themeOnForAccount(this.db.db, accountId, id)) ? this.nameOf(id) : null;
93
+ }
94
+ };
95
+ ThemesService = __decorate([
96
+ Injectable(),
97
+ __param(0, Inject(KernelDb))
98
+ ], ThemesService);
99
+ export { ThemesService };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.10",
3
+ "version": "0.1.0-rc.11",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.7"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.8"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,7 +74,7 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/testing": "0.1.0-rc.10"
77
+ "@capybara-hq/testing": "0.1.0-rc.11"
78
78
  },
79
79
  "scripts": {
80
80
  "build": "tsc -b"
@@ -0,0 +1,64 @@
1
+ -- Themes as a platform component kind (themes spec 2026-11-08-themes-design.md §6, §7): rows and
2
+ -- versions shaped like platform agent templates, with the owner columns of org-owned items; the
3
+ -- `theme` kind in the component scope, switch and install component tables; the person's pick on
4
+ -- the account. Expand-only: the only dropped objects are the three kind checks, re-added wider in
5
+ -- the next statement each.
6
+
7
+ CREATE TABLE IF NOT EXISTS platform_themes (
8
+ id text PRIMARY KEY,
9
+ catalog_item_id uuid REFERENCES catalog_items(id) ON DELETE SET NULL,
10
+ plugin_name text,
11
+ name text NOT NULL,
12
+ description text,
13
+ description_zh text,
14
+ current_version integer NOT NULL CHECK (current_version >= 1),
15
+ scope_mode text NOT NULL DEFAULT 'follow' CHECK (scope_mode IN ('follow', 'own')),
16
+ scope text NOT NULL DEFAULT 'optional' CHECK (scope IN ('all', 'optional', 'named')),
17
+ disabled boolean NOT NULL DEFAULT false,
18
+ shown_to_others boolean NOT NULL DEFAULT true,
19
+ scope_version integer NOT NULL DEFAULT 0,
20
+ -- The owning org (NULL = the platform), the org it was created in (no FK, immutable) and the
21
+ -- share switch, as on the other platform components (0084).
22
+ owner_org_id text REFERENCES orgs(id) ON DELETE SET NULL,
23
+ origin_org_id text,
24
+ shareable boolean NOT NULL DEFAULT false,
25
+ created_at timestamptz NOT NULL DEFAULT now(),
26
+ updated_at timestamptz NOT NULL DEFAULT now(),
27
+ deleted_at timestamptz
28
+ );
29
+ CREATE UNIQUE INDEX IF NOT EXISTS platform_themes_live_name_origin_uq
30
+ ON platform_themes ((coalesce(plugin_name, '')), name, (coalesce(origin_org_id, '')))
31
+ WHERE deleted_at IS NULL;
32
+
33
+ -- One version of a theme: `definition` is the parsed theme file (`ParsedTheme`); fonts and logo
34
+ -- live under `object_prefix` in `deployment/` (NULL for a theme without assets).
35
+ CREATE TABLE IF NOT EXISTS platform_theme_versions (
36
+ theme_id text NOT NULL REFERENCES platform_themes(id) ON DELETE CASCADE,
37
+ version integer NOT NULL CHECK (version >= 1),
38
+ definition jsonb NOT NULL,
39
+ object_prefix text,
40
+ catalog_version text,
41
+ updated_on_own boolean NOT NULL DEFAULT false,
42
+ created_by text,
43
+ created_at timestamptz NOT NULL DEFAULT now(),
44
+ PRIMARY KEY (theme_id, version)
45
+ );
46
+
47
+ -- 0081 declared these checks inline, so they carry the default names.
48
+ -- capybara:allow-destructive the check is added back with 'theme' in the next statement; existing rows satisfy it
49
+ ALTER TABLE component_scope_orgs DROP CONSTRAINT IF EXISTS component_scope_orgs_kind_check;
50
+ ALTER TABLE component_scope_orgs ADD CONSTRAINT component_scope_orgs_kind_check
51
+ CHECK (kind IN ('skill', 'agent_template', 'connector_template', 'theme'));
52
+ -- capybara:allow-destructive the check is added back with 'theme' in the next statement; existing rows satisfy it
53
+ ALTER TABLE component_org_switches DROP CONSTRAINT IF EXISTS component_org_switches_kind_check;
54
+ ALTER TABLE component_org_switches ADD CONSTRAINT component_org_switches_kind_check
55
+ CHECK (kind IN ('skill', 'agent_template', 'connector_template', 'theme'));
56
+ -- NOT VALID as in 0053: existing rows were checked by the narrower constraint already.
57
+ -- capybara:allow-destructive the check is added back with 'theme' in the next statement; existing rows satisfy it
58
+ ALTER TABLE plugin_install_components DROP CONSTRAINT IF EXISTS plugin_install_components_kind_check;
59
+ ALTER TABLE plugin_install_components ADD CONSTRAINT plugin_install_components_kind_check
60
+ CHECK (kind IN ('extension', 'connector', 'skill', 'plugin', 'agent_template', 'theme')) NOT VALID;
61
+
62
+ -- The person's theme (§7): one value across all their orgs; NULL follows the org. No FK: a pick
63
+ -- that is not on in the current org (or no longer exists) is skipped, never an error.
64
+ ALTER TABLE accounts ADD COLUMN IF NOT EXISTS theme text;
@@ -0,0 +1,7 @@
1
+ -- The platform default theme setting `uiTheme` (themes spec §7) always has a row: the guards that
2
+ -- refuse taking the default theme away from an org read it FOR SHARE, and the setting's write
3
+ -- locks it FOR UPDATE before checking the chosen theme, so the two serialize on this row.
4
+ -- `{"id": null}` is the built-in theme (the default when the key is missing).
5
+ INSERT INTO deployment_settings (key, value)
6
+ VALUES ('uiTheme', '{"id": null}'::jsonb)
7
+ ON CONFLICT (key) DO NOTHING;