@cosmicdrift/kumiko-samples 0.377.0 → 0.378.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -1
  3. package/packages/bundled-features/src/cap-counter/changes.json +12 -0
  4. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +9 -0
  5. package/packages/bundled-features/src/config/web/i18n.ts +1 -0
  6. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  7. package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-accounts.query.ts +11 -4
  8. package/packages/bundled-features/src/mail-foundation/changes.json +6 -0
  9. package/packages/bundled-features/src/mail-foundation/i18n.ts +3 -2
  10. package/packages/bundled-features/src/mail-transport-smtp/i18n.ts +1 -1
  11. package/packages/bundled-features/src/template-resolver/changes.json +20 -0
  12. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +61 -3
  13. package/packages/bundled-features/src/template-resolver/constants.ts +3 -0
  14. package/packages/bundled-features/src/template-resolver/document-blocks.ts +3 -1
  15. package/packages/bundled-features/src/template-resolver/document-images.ts +29 -0
  16. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +35 -0
  17. package/packages/bundled-features/src/template-resolver/document-schema.ts +5 -0
  18. package/packages/bundled-features/src/template-resolver/feature.ts +77 -36
  19. package/packages/bundled-features/src/template-resolver/handlers/collection-item.query.ts +1 -1
  20. package/packages/bundled-features/src/template-resolver/handlers/collection-list.query.ts +1 -1
  21. package/packages/bundled-features/src/template-resolver/handlers/collection-set.write.ts +2 -6
  22. package/packages/bundled-features/src/template-resolver/handlers/collection-shared.ts +0 -6
  23. package/packages/bundled-features/src/template-resolver/handlers/copy-locale.write.ts +67 -58
  24. package/packages/bundled-features/src/template-resolver/handlers/discard-draft.write.ts +36 -13
  25. package/packages/bundled-features/src/template-resolver/handlers/import-bundle.write.ts +37 -28
  26. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +66 -62
  27. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +105 -96
  28. package/packages/bundled-features/src/template-resolver/handlers/reset-to-system.write.ts +62 -49
  29. package/packages/bundled-features/src/template-resolver/handlers/resource-link-pdf.write.ts +44 -29
  30. package/packages/bundled-features/src/template-resolver/handlers/resource-remove.write.ts +52 -36
  31. package/packages/bundled-features/src/template-resolver/handlers/resource-upload.write.ts +126 -106
  32. package/packages/bundled-features/src/template-resolver/handlers/send-test-shared.ts +38 -0
  33. package/packages/bundled-features/src/template-resolver/handlers/send-test-status.query.ts +31 -0
  34. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +105 -111
  35. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +110 -103
  36. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +56 -28
  37. package/packages/bundled-features/src/template-resolver/handlers/upsert-tenant.write.ts +38 -29
  38. package/packages/bundled-features/src/template-resolver/index.ts +8 -1
  39. package/packages/bundled-features/src/template-resolver/qualified-names.ts +2 -0
  40. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +91 -0
  41. package/packages/bundled-features/src/template-resolver/template-preview.ts +8 -2
  42. package/packages/bundled-features/src/template-resolver/template-validation.ts +31 -10
  43. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +29 -0
  44. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +42 -4
  45. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +2 -0
  46. package/packages/bundled-features/src/template-resolver/web/i18n.ts +6 -0
  47. package/samples/apps/ui-walkthrough/src/app/help-action.tsx +37 -0
  48. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  49. package/samples/apps/ui-walkthrough/src/app/shell.tsx +6 -0
  50. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +20 -0
  51. package/samples/apps/ui-walkthrough/src/features/rental/feature.ts +65 -1
  52. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +70 -0
  53. package/samples/apps/ui-walkthrough/src/features/rental/invoice-receive.ts +20 -0
  54. package/samples/apps/ui-walkthrough/src/features/rental/lease-support.ts +15 -0
  55. package/samples/apps/ui-walkthrough/src/features/rental/qualified-names.ts +2 -0
  56. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +79 -0
  57. package/samples/apps/ui-walkthrough/src/features/rental/web/index.ts +2 -0
  58. package/samples/apps/ui-walkthrough/src/features/rental/web/upload-standard-layout.tsx +61 -0
  59. package/samples/apps/ui-walkthrough/src/features/tasks/i18n.ts +8 -0
  60. package/samples/apps/ui-walkthrough/src/run-config.ts +32 -3
  61. package/samples/apps/use-all-bundled/feature-manifest.json +2 -2
  62. package/samples/recipes/delivery-notifications/README.md +1 -1
  63. package/samples/recipes/embedded/README.md +8 -0
  64. package/samples/recipes/embedded/src/feature.ts +8 -0
  65. package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +38 -0
  66. package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +59 -0
@@ -3,43 +3,48 @@ import {
3
3
  createSystemConfig,
4
4
  defineFeature,
5
5
  } from "@cosmicdrift/kumiko-framework/engine";
6
- import { isCollectionRefusedKind } from "./constants.ts";
6
+ import { DEFAULT_COLLECTION_ACCESS, isCollectionRefusedKind } from "./constants.ts";
7
7
  import { bySlugQuery } from "./handlers/by-slug.query.ts";
8
8
  import { byTenantQuery } from "./handlers/by-tenant.query.ts";
9
9
  import { makeCollectionItemQuery } from "./handlers/collection-item.query.ts";
10
10
  import { makeCollectionListQuery } from "./handlers/collection-list.query.ts";
11
11
  import { makeCollectionSetWrite } from "./handlers/collection-set.write.ts";
12
- import { copyLocaleWrite } from "./handlers/copy-locale.write.ts";
12
+ import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.ts";
13
13
  import { diffToSystemQuery } from "./handlers/diff-to-system.query.ts";
14
- import { discardDraftSystemWrite, discardDraftWrite } from "./handlers/discard-draft.write.ts";
14
+ import {
15
+ makeDiscardDraftSystemWrite,
16
+ makeDiscardDraftWrite,
17
+ } from "./handlers/discard-draft.write.ts";
15
18
  import { documentBlocksQuery } from "./handlers/document-blocks.query.ts";
16
19
  import { exportBundleQuery } from "./handlers/export-bundle.query.ts";
17
20
  import { findByIdQuery } from "./handlers/find-by-id.query.ts";
18
- import { importBundleWrite } from "./handlers/import-bundle.write.ts";
21
+ import { makeImportBundleWrite } from "./handlers/import-bundle.write.ts";
19
22
  import { importBundleSystemWrite } from "./handlers/import-bundle-system.write.ts";
20
23
  import { layoutSourceQuery } from "./handlers/layout-source.query.ts";
21
24
  import { listQuery } from "./handlers/list.query.ts";
22
- import { overviewQuery } from "./handlers/overview.query.ts";
23
- import { patchDraftWrite } from "./handlers/patch-draft.write.ts";
25
+ import { makeOverviewQuery } from "./handlers/overview.query.ts";
26
+ import { makePatchDraftWrite } from "./handlers/patch-draft.write.ts";
24
27
  import { previewQuery } from "./handlers/preview.query.ts";
25
- import { resetToSystemWrite } from "./handlers/reset-to-system.write.ts";
26
- import { resourceLinkPdfWrite } from "./handlers/resource-link-pdf.write.ts";
27
- import { resourceRemoveWrite } from "./handlers/resource-remove.write.ts";
28
- import { resourceUploadWrite } from "./handlers/resource-upload.write.ts";
29
- import { sendTestWrite } from "./handlers/send-test.write.ts";
30
- import { setWrite } from "./handlers/set.write.ts";
28
+ import { makeResetToSystemWrite } from "./handlers/reset-to-system.write.ts";
29
+ import { makeResourceLinkPdfWrite } from "./handlers/resource-link-pdf.write.ts";
30
+ import { makeResourceRemoveWrite } from "./handlers/resource-remove.write.ts";
31
+ import { makeResourceUploadWrite } from "./handlers/resource-upload.write.ts";
32
+ import { makeSendTestWrite } from "./handlers/send-test.write.ts";
33
+ import { sendTestStatusQuery } from "./handlers/send-test-status.query.ts";
34
+ import { makeSetWrite } from "./handlers/set.write.ts";
31
35
  import { tenantOverridesQuery } from "./handlers/tenant-overrides.query.ts";
32
36
  import {
33
- archiveSystemWrite,
34
- archiveWrite,
35
- publishSystemWrite,
36
- publishWrite,
37
+ makeArchiveSystemWrite,
38
+ makeArchiveWrite,
39
+ makePublishSystemWrite,
40
+ makePublishWrite,
37
41
  } from "./handlers/toggle-status.write.ts";
38
42
  import { upsertSystemWrite } from "./handlers/upsert-system.write.ts";
39
- import { upsertTenantWrite } from "./handlers/upsert-tenant.write.ts";
43
+ import { makeUpsertTenantWrite } from "./handlers/upsert-tenant.write.ts";
40
44
  import { usageQuery } from "./handlers/usage.query.ts";
41
45
  import { validateQuery } from "./handlers/validate.query.ts";
42
46
  import { templateResourceEntity } from "./table.ts";
47
+ import type { TenantEditableTemplate } from "./template-edit-policy.ts";
43
48
  import { userContentEntryEntity } from "./user-content-table.ts";
44
49
 
45
50
  // template-resolver — structured template storage with tenant-override
@@ -61,6 +66,13 @@ export type TemplateResolverOptions = {
61
66
  * access rule, so the dispatcher enforces the separation instead of a
62
67
  * branch in a shared handler. */
63
68
  readonly collections?: readonly ContentCollectionDefinition[];
69
+ /** Templates a TenantAdmin may edit for the own tenant (override, draft, publish, archive,
70
+ * reset, copy-locale, import, resources). Without an entry only a SystemAdmin edits.
71
+ * A tenant-edited mail goes out under the platform's name, so the app opts in per
72
+ * template instead of the framework guessing which ones a tenant may reword.
73
+ * `access` is required: the host decides its role vocabulary here, like for
74
+ * `collections`. SystemAdmin always passes. */
75
+ readonly tenantEditable?: readonly TenantEditableTemplate[];
64
76
  };
65
77
 
66
78
  function assertCollectionKindsAllowed(collections: readonly ContentCollectionDefinition[]): void {
@@ -73,20 +85,45 @@ function assertCollectionKindsAllowed(collections: readonly ContentCollectionDef
73
85
  }
74
86
  }
75
87
 
88
+ function assertTenantEditableValid(entries: readonly TenantEditableTemplate[]): void {
89
+ const seen = new Set<string>();
90
+ for (const entry of entries) {
91
+ const key = `${entry.kind}/${entry.slug}`;
92
+ if (seen.has(key)) {
93
+ throw new Error(`template-resolver: tenantEditable lists "${key}" twice`);
94
+ }
95
+ seen.add(key);
96
+ if (entry.slug.trim() === "") {
97
+ throw new Error(
98
+ `template-resolver: tenantEditable entry of kind "${entry.kind}" has an empty slug`,
99
+ );
100
+ }
101
+ if (entry.access.roles.length === 0) {
102
+ throw new Error(
103
+ `template-resolver: tenantEditable entry "${entry.kind}/${entry.slug}" has no roles in access`,
104
+ );
105
+ }
106
+ }
107
+ }
108
+
76
109
  export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}) {
77
110
  const collections = opts.collections ?? [];
78
111
  assertCollectionKindsAllowed(collections);
112
+ const tenantEditable = opts.tenantEditable ?? [];
113
+ assertTenantEditableValid(tenantEditable);
114
+ const policy = { tenantEditable };
79
115
  const hasUserOwned = collections.some((c) => c.ownership === "user");
80
116
  return defineFeature("template-resolver", (r) => {
81
117
  r.describe(
82
118
  [
83
119
  "Every piece of editable text lives here, in one entity: mail bodies, notification texts, PDF document templates, AI prompts and plain text blocks. What a record is used for is the `kind` (`notification`, `mail`, `mail-layout`, `document-pdf`, `pdf-layout`, `ai-prompt`, `text-block`, `snippet`, `image-snapshot`).",
84
120
  "Reading is one call — `ctx.templateResolver.resolveTemplate({ tenantId, slug, kind, locale })`. It walks four levels: tenant+locale, system+locale, tenant+fallback-locale, system+fallback-locale. A tenant overrides a system default by simply having its own record; no application code changes. Writing programmatically goes through the `upsertSystem`, `upsertTenant`, `publish` and `archive` write handlers; a SystemAdmin retires or restores a system default with `publishSystem` and `archiveSystem`, and a tenant drops its override with `resetToSystem`. Saving a draft over an active template keeps the active version served and stores the edit beside it (column `draft`); `publish` makes it the served version, `discardDraft` / `discardDraftSystem` throws it away.",
121
+ 'Editing templates is for SystemAdmin only. A TenantAdmin edits only the templates the app unlocks at the mount site, `createTemplateResolverFeature({ tenantEditable: [{ kind: "mail", slug: "status-update", access: { roles: ["TenantAdmin"] } }] })`, and every write handler enforces that on the server (override, draft, publish, archive, reset, copy-locale, import, resources, `set`). Each entry carries the `access` roles allowed to edit it, because a bundled feature cannot know the host\'s roles. Reading and delivery do not depend on it: a tenant override that exists is served. A collection mounted without `access` is SystemAdmin only.',
85
122
  "Text an editor should be able to change belongs in a collection, declared at mount: `createTemplateResolverFeature({ collections: [{ id, kind, access: { roles }, nav }] })`. It appears in the navigation, and `access` is part of the mount because a bundled feature cannot know the host's roles. Each collection gets its own `<id>-list` / `<id>-item` / `<id>-set` handlers, so the dispatcher enforces the separation.",
86
123
  "How a collection is edited follows from `contentFormat`: `plain` gives a text area, `rich` a small WYSIWYG (bold, italic, headings, lists, links), `markdown` a text area that stores markdown text (same insertable chips as `plain`). All three offer the collection's `variableSchema` as insertable chips and a preview rendered with sample data — an editor sees what `{{firstName}}` becomes without sending a mail. An app can register its own editor for a format; the last `clientFeature` that registers a format wins (a conflict logs a warning).",
87
124
  'A collection is tenant-wide by default. With `ownership: "user"` every user keeps their own entries — mail signatures being the obvious case. Those rows live in the separate `user-content-entry` entity and count as user data, so mounting one also requires the `template-resolver-user-data` feature and a migration on the app side.',
88
125
  "`validate` dry-runs the write pipeline for a draft (sanitizer, layout rules, placeholders) and reports what the template uses and misses. `export-bundle` / `import-bundle` (and `import-bundle-system`) move one template with all locales and resource files between tenants or environments; `copy-locale` starts a translation from an existing locale. Layouts are structured: a mail or PDF layout is `data-header` / `data-content` / `data-signature` / `data-footer` regions, and mjml layout source is system-only.",
89
- "`preview` renders a draft (or the stored template) with sample values taken from the `example` of each declared variable, through the same gates and the same mail renderer as a real send, and returns subject, html, `displayHtml` (the html with cid images as data URIs for an editor), text, attachments (inline images and files) and `checks` (images resolved, plain text present, size under 10 MiB, required placeholders used); nothing is saved or sent. `send-test` mails that rendering to the calling user's own address only, subject prefixed with `[TEST]`, at most 10 per user and hour; it needs `delivery`, `channel-email` and `renderer-mail-html` to be mounted.",
126
+ "`preview` renders a draft (or the stored template) with sample values taken from the `example` of each declared variable, through the same gates and the same mail renderer as a real send, and returns subject, html, `displayHtml` (the html with cid images as data URIs for an editor), text, attachments (inline images and files) and `checks` (images resolved, plain text present, size under 10 MiB, required placeholders used); nothing is saved or sent. `send-test` mails that rendering to the calling user's own address only, subject prefixed with `[TEST]`, at most 10 per user and hour; it needs `delivery`, `channel-email` and `renderer-mail-html` to be mounted. `send-test-status` tells an editor beforehand whether that send can work for the caller (`canSend`, else `reason` `no_channel` or `no_address`), never returning the address.",
90
127
  'Images used by a template (`<img data-resource="logo">`) are uploaded with `resourceUpload`, which re-encodes them, stores a file and links it under the key; `resourceRemove` unlinks it. `linkedResources` is written only through these two handlers. With `purpose: "attachment"` and a `fileName`, `resourceUpload` stores a PDF, PNG or JPEG as a file attachment of a mail template (original bytes, at most 10) that the mail renderer attaches after the inline images. `resourceLinkPdf` instead links a `document-pdf` template under a key: every mail sent from the template then carries that PDF, rendered at send time with the mail\'s own variables and locale, under a file name pattern such as `invoice-{{number}}.pdf`; files and linked PDFs share the limit of 10.',
91
128
  "Replaces the former `text-content` feature; its blocks now live here as kind `text-block`.",
92
129
  ].join("\n\n"),
@@ -110,23 +147,23 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
110
147
 
111
148
  const handlers = {
112
149
  upsertSystem: r.writeHandler(upsertSystemWrite),
113
- upsertTenant: r.writeHandler(upsertTenantWrite),
114
- publish: r.writeHandler(publishWrite),
115
- archive: r.writeHandler(archiveWrite),
116
- publishSystem: r.writeHandler(publishSystemWrite),
117
- archiveSystem: r.writeHandler(archiveSystemWrite),
118
- discardDraft: r.writeHandler(discardDraftWrite),
119
- discardDraftSystem: r.writeHandler(discardDraftSystemWrite),
120
- resetToSystem: r.writeHandler(resetToSystemWrite),
121
- set: r.writeHandler(setWrite),
122
- importBundle: r.writeHandler(importBundleWrite),
150
+ upsertTenant: r.writeHandler(makeUpsertTenantWrite(policy)),
151
+ publish: r.writeHandler(makePublishWrite(policy)),
152
+ archive: r.writeHandler(makeArchiveWrite(policy)),
153
+ publishSystem: r.writeHandler(makePublishSystemWrite(policy)),
154
+ archiveSystem: r.writeHandler(makeArchiveSystemWrite(policy)),
155
+ discardDraft: r.writeHandler(makeDiscardDraftWrite(policy)),
156
+ discardDraftSystem: r.writeHandler(makeDiscardDraftSystemWrite(policy)),
157
+ resetToSystem: r.writeHandler(makeResetToSystemWrite(policy)),
158
+ set: r.writeHandler(makeSetWrite(policy)),
159
+ importBundle: r.writeHandler(makeImportBundleWrite(policy)),
123
160
  importBundleSystem: r.writeHandler(importBundleSystemWrite),
124
- copyLocale: r.writeHandler(copyLocaleWrite),
125
- resourceUpload: r.writeHandler(resourceUploadWrite),
126
- resourceRemove: r.writeHandler(resourceRemoveWrite),
127
- resourceLinkPdf: r.writeHandler(resourceLinkPdfWrite),
128
- sendTest: r.writeHandler(sendTestWrite),
129
- patchDraft: r.writeHandler(patchDraftWrite),
161
+ copyLocale: r.writeHandler(makeCopyLocaleWrite(policy)),
162
+ resourceUpload: r.writeHandler(makeResourceUploadWrite(policy)),
163
+ resourceRemove: r.writeHandler(makeResourceRemoveWrite(policy)),
164
+ resourceLinkPdf: r.writeHandler(makeResourceLinkPdfWrite(policy)),
165
+ sendTest: r.writeHandler(makeSendTestWrite(policy)),
166
+ patchDraft: r.writeHandler(makePatchDraftWrite(policy)),
130
167
  };
131
168
 
132
169
  const queries = {
@@ -135,7 +172,7 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
135
172
  bySlug: r.queryHandler(bySlugQuery),
136
173
  byTenant: r.queryHandler(byTenantQuery),
137
174
  usage: r.queryHandler(usageQuery),
138
- overview: r.queryHandler(overviewQuery),
175
+ overview: r.queryHandler(makeOverviewQuery(policy)),
139
176
  layoutSource: r.queryHandler(layoutSourceQuery),
140
177
  tenantOverrides: r.queryHandler(tenantOverridesQuery),
141
178
  diffToSystem: r.queryHandler(diffToSystemQuery),
@@ -143,10 +180,14 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
143
180
  preview: r.queryHandler(previewQuery),
144
181
  documentBlocks: r.queryHandler(documentBlocksQuery),
145
182
  exportBundle: r.queryHandler(exportBundleQuery),
183
+ sendTestStatus: r.queryHandler(sendTestStatusQuery),
146
184
  };
147
185
 
148
186
  for (const collection of collections) {
149
- r.contentCollection(collection);
187
+ r.contentCollection({
188
+ ...collection,
189
+ access: collection.access ?? DEFAULT_COLLECTION_ACCESS,
190
+ });
150
191
  r.queryHandler(makeCollectionListQuery(collection));
151
192
  r.queryHandler(makeCollectionItemQuery(collection));
152
193
  r.writeHandler(makeCollectionSetWrite(collection));
@@ -4,10 +4,10 @@ import {
4
4
  defineQueryHandler,
5
5
  } from "@cosmicdrift/kumiko-framework/engine";
6
6
  import * as z from "zod";
7
+ import { DEFAULT_COLLECTION_ACCESS } from "../constants.ts";
7
8
  import {
8
9
  type CollectionEntryRow,
9
10
  collectionStore,
10
- DEFAULT_COLLECTION_ACCESS,
11
11
  toCollectionEntry,
12
12
  } from "./collection-shared.ts";
13
13
 
@@ -4,10 +4,10 @@ import {
4
4
  defineQueryHandler,
5
5
  } from "@cosmicdrift/kumiko-framework/engine";
6
6
  import * as z from "zod";
7
+ import { DEFAULT_COLLECTION_ACCESS } from "../constants.ts";
7
8
  import {
8
9
  type CollectionEntryRow,
9
10
  collectionStore,
10
- DEFAULT_COLLECTION_ACCESS,
11
11
  toCollectionEntry,
12
12
  } from "./collection-shared.ts";
13
13
 
@@ -7,13 +7,9 @@ import {
7
7
  import { ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
8
8
  import * as z from "zod";
9
9
  import { requireForTenant } from "../../shared/index.ts";
10
- import { isCollectionRefusedKind } from "../constants.ts";
10
+ import { DEFAULT_COLLECTION_ACCESS, isCollectionRefusedKind } from "../constants.ts";
11
11
  import { documentViolationsToFieldIssues, sanitizeTemplateBody } from "../document-sanitizer.ts";
12
- import {
13
- type CollectionEntryRow,
14
- collectionStore,
15
- DEFAULT_COLLECTION_ACCESS,
16
- } from "./collection-shared.ts";
12
+ import { type CollectionEntryRow, collectionStore } from "./collection-shared.ts";
17
13
  import { contentFormatSchema, folderSchema, localeSchema, slugSchema } from "./shared.ts";
18
14
 
19
15
  // Upsert inside one collection. Mirrors set.write for text-blocks, but the
@@ -1,7 +1,6 @@
1
1
  import type { EventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { createEventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
3
3
  import type {
4
- AccessRule,
5
4
  ContentCollectionDefinition,
6
5
  SessionUser,
7
6
  TenantId,
@@ -11,11 +10,6 @@ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
11
10
  import { templateResourceEntity, templateResourcesTable } from "../table.ts";
12
11
  import { userContentEntriesTable, userContentEntryEntity } from "../user-content-table.ts";
13
12
 
14
- // Applies when an app mounts a collection without saying who may reach it.
15
- // Deliberately narrow: a collection whose access nobody decided should be
16
- // invisible to normal users rather than open by default.
17
- export const DEFAULT_COLLECTION_ACCESS: AccessRule = { roles: ["TenantAdmin", "SystemAdmin"] };
18
-
19
13
  const templateExecutor = createEventStoreExecutor(templateResourcesTable, templateResourceEntity, {
20
14
  entityName: "template-resource",
21
15
  });
@@ -25,6 +25,11 @@ import {
25
25
  } from "../store-template-resource.ts";
26
26
  import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
27
27
  import { toWorkingRow, type WorkingRow } from "../template-draft.ts";
28
+ import {
29
+ refuseTemplateEdit,
30
+ type TemplateEditPolicy,
31
+ templateEditAccess,
32
+ } from "../template-edit-policy.ts";
28
33
  import { attachTemplateResources } from "../template-resources.ts";
29
34
  import { resolveTemplateVariables } from "../template-validation.ts";
30
35
  import { targetExistsIssue } from "./bundle-import.ts";
@@ -97,6 +102,7 @@ type CopyRequest = {
97
102
  // Runs before the upload (reject early, store nothing) and again in the transaction on the fresh rows.
98
103
  async function checkCopyRequest(
99
104
  ctx: WriteCtx,
105
+ policy: TemplateEditPolicy,
100
106
  event: {
101
107
  readonly user: SessionUser;
102
108
  readonly payload: z.infer<typeof copyLocaleSchema>;
@@ -113,6 +119,7 @@ async function checkCopyRequest(
113
119
  }
114
120
  const tenantId = scope === "system" ? SYSTEM_TENANT_ID : event.user.tenantId;
115
121
  const refused =
122
+ (scope === "tenant" ? refuseTemplateEdit(policy, event.user, { slug, kind }) : null) ??
116
123
  refuseTenantScopeUnderSystemTenant(scope, tenantId) ??
117
124
  refuseSystemOnlyTenantOverride(ctx.registry, scope, slug, kind);
118
125
  if (refused !== null) return refused;
@@ -155,62 +162,64 @@ async function checkCopyRequest(
155
162
  };
156
163
  }
157
164
 
158
- export const copyLocaleWrite = defineWriteHandler({
159
- name: "copy-locale",
160
- schema: copyLocaleSchema,
161
- access: { roles: ["TenantAdmin", "SystemAdmin"] },
162
- description:
163
- "Copies the text of one locale of a template into another locale as a draft override of the caller's tenant, taking the tenant's own row or else the system default as the source; use it as the starting point for a translation. It refuses an existing target unless overwrite is set. With scope system (SystemAdmin only) both source and target are system-default rows and the target lands as a system draft; any other caller gets a 403.",
164
- beforeTransaction: async (event, ctx) => {
165
- const request = await checkCopyRequest(ctx, event);
166
- if (!request.isSuccess) return request;
167
- if (!request.data.sourceIsForeign) return { isSuccess: true, data: [] };
168
- return prepareLinkedResourceCopiesBeforeTransaction({
169
- ctx,
170
- user: event.user,
171
- tenantId: request.data.tenantId,
172
- resources: request.data.sourceResources,
173
- });
174
- },
175
- handler: async (event, ctx) => {
176
- const { slug, kind, toLocale } = event.payload;
177
- const request = await checkCopyRequest(ctx, event);
178
- if (!request.isSuccess) return request;
179
- const { scope, tenantId, source, contentFormat, sourceResources, sourceIsForeign } =
180
- request.data;
165
+ export function makeCopyLocaleWrite(policy: TemplateEditPolicy) {
166
+ return defineWriteHandler({
167
+ name: "copy-locale",
168
+ schema: copyLocaleSchema,
169
+ access: templateEditAccess(policy.tenantEditable),
170
+ description:
171
+ "Copies the text of one locale of a template into another locale as a draft override of the caller's tenant, taking the tenant's own row or else the system default as the source; use it as the starting point for a translation. It refuses an existing target unless overwrite is set. With scope system (SystemAdmin only) both source and target are system-default rows and the target lands as a system draft; any other caller gets a 403. A TenantAdmin may copy only templates the app lists in tenantEditable, otherwise SystemAdmin only.",
172
+ beforeTransaction: async (event, ctx) => {
173
+ const request = await checkCopyRequest(ctx, policy, event);
174
+ if (!request.isSuccess) return request;
175
+ if (!request.data.sourceIsForeign) return { isSuccess: true, data: [] };
176
+ return prepareLinkedResourceCopiesBeforeTransaction({
177
+ ctx,
178
+ user: event.user,
179
+ tenantId: request.data.tenantId,
180
+ resources: request.data.sourceResources,
181
+ });
182
+ },
183
+ handler: async (event, ctx) => {
184
+ const { slug, kind, toLocale } = event.payload;
185
+ const request = await checkCopyRequest(ctx, policy, event);
186
+ if (!request.isSuccess) return request;
187
+ const { scope, tenantId, source, contentFormat, sourceResources, sourceIsForeign } =
188
+ request.data;
181
189
 
182
- const variableSchema = storedRecord(source.variableSchema);
183
- const written = await writeTemplateRow({
184
- ctx,
185
- user: event.user,
186
- tenantId,
187
- scope,
188
- status: "draft",
189
- variables: resolveTemplateVariables(ctx.registry, slug, variableSchema),
190
- payload: {
191
- slug,
192
- kind,
193
- locale: toLocale,
194
- content: source.content,
195
- contentFormat,
196
- variableSchema,
197
- meta: parseStoredJson(source.meta),
198
- title: source.title,
199
- folder: source.folder,
200
- },
201
- });
202
- if (!written.isSuccess) return written;
203
- const resources = sourceIsForeign
204
- ? await createLinkedResourceCopies({ ctx, user: event.user, tenantId }, event.prepared)
205
- : { isSuccess: true as const, data: sourceResources };
206
- if (!resources.isSuccess) return resources;
207
- const attached = await attachTemplateResources(ctx, {
208
- user: event.user,
209
- tenantId,
210
- templateId: written.data.id,
211
- resources: resources.data,
212
- });
213
- if (!attached.isSuccess) return attached;
214
- return written;
215
- },
216
- });
190
+ const variableSchema = storedRecord(source.variableSchema);
191
+ const written = await writeTemplateRow({
192
+ ctx,
193
+ user: event.user,
194
+ tenantId,
195
+ scope,
196
+ status: "draft",
197
+ variables: resolveTemplateVariables(ctx.registry, slug, variableSchema),
198
+ payload: {
199
+ slug,
200
+ kind,
201
+ locale: toLocale,
202
+ content: source.content,
203
+ contentFormat,
204
+ variableSchema,
205
+ meta: parseStoredJson(source.meta),
206
+ title: source.title,
207
+ folder: source.folder,
208
+ },
209
+ });
210
+ if (!written.isSuccess) return written;
211
+ const resources = sourceIsForeign
212
+ ? await createLinkedResourceCopies({ ctx, user: event.user, tenantId }, event.prepared)
213
+ : { isSuccess: true as const, data: sourceResources };
214
+ if (!resources.isSuccess) return resources;
215
+ const attached = await attachTemplateResources(ctx, {
216
+ user: event.user,
217
+ tenantId,
218
+ templateId: written.data.id,
219
+ resources: resources.data,
220
+ });
221
+ if (!attached.isSuccess) return attached;
222
+ return written;
223
+ },
224
+ });
225
+ }
@@ -2,19 +2,36 @@ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { NotFoundError, ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import * as z from "zod";
4
4
  import { TemplateResolverErrors } from "../qualified-names.ts";
5
+ import {
6
+ refuseMissingTemplate,
7
+ refuseTemplateEdit,
8
+ type TemplateEditPolicy,
9
+ } from "../template-edit-policy.ts";
5
10
  import { executor } from "./shared.ts";
6
11
  import { loadTargetRow, type StatusTarget, writeAccessFor } from "./toggle-status.write.ts";
7
12
 
8
- function createDiscardDraftHandler(name: string, target: StatusTarget, description: string) {
13
+ function createDiscardDraftHandler(
14
+ policy: TemplateEditPolicy,
15
+ name: string,
16
+ target: StatusTarget,
17
+ description: string,
18
+ ) {
9
19
  return defineWriteHandler({
10
20
  name,
11
21
  schema: z.object({ id: z.string().min(1) }),
12
- access: writeAccessFor(target),
22
+ access: writeAccessFor(target, policy),
13
23
  ...(target === "system" ? { agent: { risk: "high" as const } } : {}),
14
24
  description,
15
25
  handler: async (event, ctx) => {
16
26
  const { db, scoped, row } = await loadTargetRow(ctx, target, event.user, event.payload.id);
17
- if (!row) return writeFailure(new NotFoundError("template-resource", event.payload.id));
27
+ if (!row) {
28
+ const refused = target === "own" ? refuseMissingTemplate(policy, event.user) : null;
29
+ return refused ?? writeFailure(new NotFoundError("template-resource", event.payload.id));
30
+ }
31
+ if (target === "own") {
32
+ const refused = refuseTemplateEdit(policy, event.user, row);
33
+ if (refused !== null) return refused;
34
+ }
18
35
  if (row.draft === null) {
19
36
  return writeFailure(
20
37
  new ValidationError({
@@ -40,13 +57,19 @@ function createDiscardDraftHandler(name: string, target: StatusTarget, descripti
40
57
  });
41
58
  }
42
59
 
43
- export const discardDraftWrite = createDiscardDraftHandler(
44
- "discard-draft",
45
- "own",
46
- "Throws away the open draft of one template resource of the caller's tenant so the editor shows the active version again; the served version is untouched. Refused with no_draft when there is no draft.",
47
- );
48
- export const discardDraftSystemWrite = createDiscardDraftHandler(
49
- "discard-draft-system",
50
- "system",
51
- "Throws away the open draft of one system-default template; the served version stays. SystemAdmin only, refused with no_draft when there is no draft.",
52
- );
60
+ export function makeDiscardDraftWrite(policy: TemplateEditPolicy) {
61
+ return createDiscardDraftHandler(
62
+ policy,
63
+ "discard-draft",
64
+ "own",
65
+ "Throws away the open draft of one template resource of the caller's tenant so the editor shows the active version again; the served version is untouched. Refused with no_draft when there is no draft. Outside the templates the app lists in tenantEditable only a SystemAdmin may use it.",
66
+ );
67
+ }
68
+ export function makeDiscardDraftSystemWrite(policy: TemplateEditPolicy) {
69
+ return createDiscardDraftHandler(
70
+ policy,
71
+ "discard-draft-system",
72
+ "system",
73
+ "Throws away the open draft of one system-default template; the served version stays. SystemAdmin only, refused with no_draft when there is no draft.",
74
+ );
75
+ }
@@ -1,33 +1,42 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import * as z from "zod";
3
3
  import { templateBundleSchema } from "../template-bundle.ts";
4
+ import {
5
+ refuseTemplateEdit,
6
+ type TemplateEditPolicy,
7
+ templateEditAccess,
8
+ } from "../template-edit-policy.ts";
4
9
  import { importTemplateBundle, prepareTemplateBundleBeforeTransaction } from "./bundle-import.ts";
5
10
 
6
- export const importBundleWrite = defineWriteHandler({
7
- name: "import-bundle",
8
- schema: z.object({ bundle: templateBundleSchema, overwrite: z.boolean().default(false) }),
9
- access: { roles: ["TenantAdmin", "SystemAdmin"] },
10
- description:
11
- "Imports a template bundle (all locales plus resource files, as produced by export-bundle) into the caller's tenant as drafts; it refuses a locale that already has an override unless overwrite is set, and publish makes the drafts live.",
12
- beforeTransaction: (event, ctx) =>
13
- prepareTemplateBundleBeforeTransaction({
14
- ctx,
15
- user: event.user,
16
- tenantId: event.user.tenantId,
17
- scope: "tenant",
18
- status: "draft",
19
- bundle: event.payload.bundle,
20
- overwrite: event.payload.overwrite,
21
- }),
22
- handler: (event, ctx) =>
23
- importTemplateBundle({
24
- ctx,
25
- user: event.user,
26
- tenantId: event.user.tenantId,
27
- scope: "tenant",
28
- status: "draft",
29
- bundle: event.payload.bundle,
30
- overwrite: event.payload.overwrite,
31
- prepared: event.prepared,
32
- }),
33
- });
11
+ export function makeImportBundleWrite(policy: TemplateEditPolicy) {
12
+ return defineWriteHandler({
13
+ name: "import-bundle",
14
+ schema: z.object({ bundle: templateBundleSchema, overwrite: z.boolean().default(false) }),
15
+ access: templateEditAccess(policy.tenantEditable),
16
+ description:
17
+ "Imports a template bundle (all locales plus resource files, as produced by export-bundle) into the caller's tenant as drafts; it refuses a locale that already has an override unless overwrite is set, and publish makes the drafts live. Outside the templates the app lists in tenantEditable only a SystemAdmin may use it.",
18
+ beforeTransaction: async (event, ctx) =>
19
+ refuseTemplateEdit(policy, event.user, event.payload.bundle) ??
20
+ prepareTemplateBundleBeforeTransaction({
21
+ ctx,
22
+ user: event.user,
23
+ tenantId: event.user.tenantId,
24
+ scope: "tenant",
25
+ status: "draft",
26
+ bundle: event.payload.bundle,
27
+ overwrite: event.payload.overwrite,
28
+ }),
29
+ handler: async (event, ctx) =>
30
+ refuseTemplateEdit(policy, event.user, event.payload.bundle) ??
31
+ importTemplateBundle({
32
+ ctx,
33
+ user: event.user,
34
+ tenantId: event.user.tenantId,
35
+ scope: "tenant",
36
+ status: "draft",
37
+ bundle: event.payload.bundle,
38
+ overwrite: event.payload.overwrite,
39
+ prepared: event.prepared,
40
+ }),
41
+ });
42
+ }