@marktiderman/genesis-core 1.12.0 → 1.14.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 (92) hide show
  1. package/README.md +77 -0
  2. package/dist/chunk-3B4IFDMK.js +117 -0
  3. package/dist/chunk-3B4IFDMK.js.map +1 -0
  4. package/dist/{chunk-S2ZXUNXB.js → chunk-3LZAZ5KB.js} +3 -3
  5. package/dist/{chunk-S2ZXUNXB.js.map → chunk-3LZAZ5KB.js.map} +1 -1
  6. package/dist/chunk-7FVTGKTX.js +8 -0
  7. package/dist/chunk-7FVTGKTX.js.map +1 -0
  8. package/dist/{chunk-NMFABW4Y.js → chunk-7YHGNPPO.js} +5 -5
  9. package/dist/{chunk-NMFABW4Y.js.map → chunk-7YHGNPPO.js.map} +1 -1
  10. package/dist/chunk-AUVKRXRC.js +81 -0
  11. package/dist/chunk-AUVKRXRC.js.map +1 -0
  12. package/dist/{chunk-TOU2CMDH.js → chunk-K7K6NY3C.js} +168 -168
  13. package/dist/chunk-K7K6NY3C.js.map +1 -0
  14. package/dist/chunk-LFWSTJWI.js +108 -0
  15. package/dist/chunk-LFWSTJWI.js.map +1 -0
  16. package/dist/{chunk-RCAP3Q4T.js → chunk-OYIUIW7C.js} +3 -2
  17. package/dist/chunk-OYIUIW7C.js.map +1 -0
  18. package/dist/chunk-OZYF55E3.js +6 -0
  19. package/dist/chunk-OZYF55E3.js.map +1 -0
  20. package/dist/chunk-PA6WJE5E.js +115 -0
  21. package/dist/chunk-PA6WJE5E.js.map +1 -0
  22. package/dist/chunk-PP3XFFQM.js +85 -0
  23. package/dist/chunk-PP3XFFQM.js.map +1 -0
  24. package/dist/{chunk-BGTXN2E6.js → chunk-RF6YVWHX.js} +4 -4
  25. package/dist/{chunk-BGTXN2E6.js.map → chunk-RF6YVWHX.js.map} +1 -1
  26. package/dist/{chunk-NZPJI7FC.js → chunk-UGGMJUFQ.js} +45 -13
  27. package/dist/chunk-UGGMJUFQ.js.map +1 -0
  28. package/dist/{chunk-KXVHDK3Q.js → chunk-UV3ROHQA.js} +27 -5
  29. package/dist/chunk-UV3ROHQA.js.map +1 -0
  30. package/dist/chunk-YDDPFSQ6.js +35 -0
  31. package/dist/chunk-YDDPFSQ6.js.map +1 -0
  32. package/dist/{chunk-OSPLIKSH.js → chunk-YFTGLQDQ.js} +18 -8
  33. package/dist/chunk-YFTGLQDQ.js.map +1 -0
  34. package/dist/chunk-ZIMQUFXD.js +154 -0
  35. package/dist/chunk-ZIMQUFXD.js.map +1 -0
  36. package/dist/csv.d.ts +41 -0
  37. package/dist/csv.js +77 -0
  38. package/dist/csv.js.map +1 -0
  39. package/dist/dates.js +1 -115
  40. package/dist/dates.js.map +1 -1
  41. package/dist/errors.d.ts +69 -0
  42. package/dist/errors.js +7 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/hooks/index.d.ts +7 -43
  45. package/dist/hooks/index.js +14 -11
  46. package/dist/hooks/live-cache.d.ts +15 -0
  47. package/dist/hooks/live-cache.js +3 -0
  48. package/dist/hooks/live-cache.js.map +1 -0
  49. package/dist/hooks/mutation-mode.d.ts +2 -2
  50. package/dist/hooks/mutation-mode.js +2 -2
  51. package/dist/hooks/related-keys.d.ts +2 -2
  52. package/dist/hooks/use-capabilities.d.ts +1 -1
  53. package/dist/hooks/use-infinite-resource.d.ts +18 -2
  54. package/dist/hooks/use-infinite-resource.js +4 -3
  55. package/dist/hooks/use-live.d.ts +15 -3
  56. package/dist/hooks/use-live.js +2 -1
  57. package/dist/hooks/use-one.d.ts +2 -2
  58. package/dist/hooks/use-one.js +4 -3
  59. package/dist/hooks/use-resource-form.d.ts +9 -2
  60. package/dist/hooks/use-resource-form.js +6 -5
  61. package/dist/hooks/use-resource.d.ts +2 -2
  62. package/dist/hooks/use-resource.js +5 -4
  63. package/dist/hooks/use-write.d.ts +2 -2
  64. package/dist/index.d.ts +14 -6
  65. package/dist/index.js +21 -14
  66. package/dist/provider/index.d.ts +11 -6
  67. package/dist/provider/index.js +3 -2
  68. package/dist/resource/index.d.ts +39 -0
  69. package/dist/resource/index.js +3 -0
  70. package/dist/resource/index.js.map +1 -0
  71. package/dist/resource-view/index.d.ts +468 -0
  72. package/dist/resource-view/index.js +542 -0
  73. package/dist/resource-view/index.js.map +1 -0
  74. package/dist/schema/index.d.ts +4 -4
  75. package/dist/schema/index.js +1 -0
  76. package/dist/status-BXRokZD9.d.ts +50 -0
  77. package/dist/testing/index.d.ts +3 -3
  78. package/dist/{types-B9DDfvWa.d.ts → types-CXhqXPN1.d.ts} +21 -4
  79. package/dist/{types-C7FJtFXV.d.ts → types-o8j7g6O6.d.ts} +38 -1
  80. package/dist/urls.d.ts +18 -0
  81. package/dist/urls.js +3 -0
  82. package/dist/urls.js.map +1 -0
  83. package/dist/viewer-scope-77MqxvmZ.d.ts +125 -0
  84. package/dist/{write-outcome-B2fE29yZ.d.ts → write-outcome-CFnpciUI.d.ts} +1 -1
  85. package/package.json +21 -1
  86. package/dist/chunk-5ORRAXIV.js +0 -30
  87. package/dist/chunk-5ORRAXIV.js.map +0 -1
  88. package/dist/chunk-KXVHDK3Q.js.map +0 -1
  89. package/dist/chunk-NZPJI7FC.js.map +0 -1
  90. package/dist/chunk-OSPLIKSH.js.map +0 -1
  91. package/dist/chunk-RCAP3Q4T.js.map +0 -1
  92. package/dist/chunk-TOU2CMDH.js.map +0 -1
@@ -0,0 +1,542 @@
1
+ import { readinessOf } from '../chunk-PP3XFFQM.js';
2
+ import { keyFields, encodeRecordKey } from '../chunk-KV2HW4G4.js';
3
+ import { NO_VIEWER } from '../chunk-OZYF55E3.js';
4
+ export { NO_VIEWER } from '../chunk-OZYF55E3.js';
5
+ import { titleCase } from '../chunk-RYEXWQFD.js';
6
+ import { isSafeUrl } from '../chunk-YDDPFSQ6.js';
7
+
8
+ // src/resource-view/define-view.ts
9
+ var ViewDefinitionError = class extends Error {
10
+ problems;
11
+ constructor(resource, problems) {
12
+ super(`defineView(${resource}): ${problems.join("; ")}`);
13
+ this.name = "ViewDefinitionError";
14
+ this.problems = problems;
15
+ }
16
+ };
17
+ function deriveDisplay(field) {
18
+ if (field.references) return "relation";
19
+ switch (field.widget) {
20
+ case "url":
21
+ return "url";
22
+ case "email":
23
+ return "email";
24
+ case "image":
25
+ return "image";
26
+ case "textarea":
27
+ return "longText";
28
+ case "date":
29
+ return "date";
30
+ }
31
+ if (field.enumValues?.length) return "badge";
32
+ switch (field.type) {
33
+ case "boolean":
34
+ return "boolean";
35
+ case "number":
36
+ return "number";
37
+ case "json":
38
+ return "json";
39
+ case "relation":
40
+ return "relation";
41
+ case "datetime":
42
+ return /^date$/i.test(field.dbType ?? "") ? "date" : "datetime";
43
+ }
44
+ return "text";
45
+ }
46
+ var SAME_OR_IRREGULAR = {
47
+ series: "series",
48
+ species: "species",
49
+ movies: "movie",
50
+ cookies: "cookie",
51
+ ties: "tie",
52
+ pies: "pie",
53
+ people: "person"
54
+ };
55
+ function singular(word) {
56
+ const last = word.split(" ").pop();
57
+ const head = word.slice(0, word.length - last.length);
58
+ const lower = last.toLowerCase();
59
+ const one = (s) => head + s;
60
+ if (SAME_OR_IRREGULAR[lower]) return one(SAME_OR_IRREGULAR[lower]);
61
+ if (/[^aeiou]ies$/.test(lower)) return one(`${last.slice(0, -3)}y`);
62
+ if (/(?:s|x|z|ch|sh)es$/.test(lower)) return one(last.slice(0, -2));
63
+ if (/(?:ss|us|is)$/.test(lower) || !lower.endsWith("s")) return word;
64
+ return one(last.slice(0, -1));
65
+ }
66
+ var RESERVED_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "delete"]);
67
+ var own = (record, key) => record && Object.hasOwn(record, key) ? record[key] : void 0;
68
+ function defineView(contract, definition = {}) {
69
+ const facts = contract;
70
+ const fields = contract.fields;
71
+ const byName = new Map(fields.map((f) => [f.name, f]));
72
+ const keys = new Set(keyFields(contract));
73
+ const scope = new Set(definition.scope ?? []);
74
+ const viewFields = Object.freeze(
75
+ Object.fromEntries(Object.entries(definition.fields ?? {}).map(([k, v]) => [k, Object.freeze({ ...v })]))
76
+ );
77
+ const columnLists = Object.freeze(
78
+ Object.fromEntries(
79
+ Object.entries(definition.columns ?? {}).map(([k, list]) => [
80
+ k,
81
+ Object.freeze((list ?? []).map((c) => typeof c === "string" ? c : Object.freeze({ ...c })))
82
+ ])
83
+ )
84
+ );
85
+ const formItems = Object.freeze(
86
+ (definition.form ?? []).map((item) => typeof item === "string" ? item : Object.freeze({ ...item, fields: Object.freeze([...item.fields]) }))
87
+ );
88
+ const presets = Object.freeze(
89
+ Object.fromEntries(
90
+ Object.entries(definition.presets ?? {}).map(([k, p]) => [k, Object.freeze({ ...p, ...p.filter ? { filter: Object.freeze({ ...p.filter }) } : {} })])
91
+ )
92
+ );
93
+ const actionList = Object.freeze(
94
+ // Names are trimmed, so " archive" and "archive" are one name.
95
+ (Array.isArray(definition.actions) ? definition.actions : []).map(
96
+ (a) => a && typeof a === "object" ? Object.freeze({ ...a, ...typeof a.name === "string" ? { name: a.name.trim() } : {} }) : a
97
+ )
98
+ );
99
+ const problems = [];
100
+ const known = (name, where) => {
101
+ if (!byName.has(name)) problems.push(`${where} names "${name}", which isn't a field`);
102
+ };
103
+ for (const name of Object.keys(viewFields)) known(name, "fields");
104
+ for (const [preset, list] of Object.entries(columnLists)) {
105
+ const seen = /* @__PURE__ */ new Set();
106
+ for (const column of list ?? []) {
107
+ const key = typeof column === "string" ? column : column.key;
108
+ if (typeof column === "string") known(column, `columns.${preset}`);
109
+ else if (byName.has(column.key)) problems.push(`columns.${preset}: computed "${column.key}" clashes with a field`);
110
+ if (seen.has(key)) problems.push(`columns.${preset} lists "${key}" twice`);
111
+ seen.add(key);
112
+ }
113
+ }
114
+ const formSeen = /* @__PURE__ */ new Set();
115
+ for (const item of formItems) {
116
+ for (const name of typeof item === "string" ? [item] : item.fields) {
117
+ known(name, "form");
118
+ if (formSeen.has(name)) problems.push(`form lists "${name}" twice`);
119
+ formSeen.add(name);
120
+ }
121
+ }
122
+ for (const name of scope) known(name, "scope");
123
+ if (definition.groupBy) known(definition.groupBy, "groupBy");
124
+ if (definition.orderBy) known(definition.orderBy.field, "orderBy");
125
+ for (const [name, preset] of Object.entries(presets)) {
126
+ if (preset.columns && preset.columns !== "default" && !own(columnLists, preset.columns)) {
127
+ problems.push(`presets.${name} uses columns "${preset.columns}", which isn't defined`);
128
+ }
129
+ for (const field of Object.keys(preset.filter ?? {})) known(field, `presets.${name}.filter`);
130
+ }
131
+ if (facts.labelField) known(facts.labelField, "the contract's labelField");
132
+ const actionSeen = /* @__PURE__ */ new Set();
133
+ if (definition.actions !== void 0 && !Array.isArray(definition.actions)) problems.push("actions isn't a list");
134
+ actionList.forEach((action, i) => {
135
+ const where = `actions[${i}]`;
136
+ if (!action || typeof action !== "object") {
137
+ problems.push(`${where} isn't an action`);
138
+ return;
139
+ }
140
+ if (typeof action.name !== "string" || !action.name.trim()) problems.push(`${where} has no name`);
141
+ else if (RESERVED_ACTIONS.has(action.name)) problems.push(`${where} is named "${action.name}", which is reserved for the view's own ${action.name}`);
142
+ else if (actionSeen.has(action.name)) problems.push(`actions lists "${action.name}" twice`);
143
+ else actionSeen.add(action.name);
144
+ if (typeof action.label !== "string" || !action.label.trim()) problems.push(`${where} has no label`);
145
+ if (action.confirm !== void 0 && typeof action.confirm !== "string") problems.push(`${where}.confirm isn't text`);
146
+ if (action.description !== void 0 && typeof action.description !== "string") {
147
+ problems.push(`${where}.description isn't text`);
148
+ }
149
+ if (action.can !== void 0 && typeof action.can !== "function") problems.push(`${where}.can isn't a function`);
150
+ if (action.destructive !== void 0 && typeof action.destructive !== "boolean") problems.push(`${where}.destructive isn't true or false`);
151
+ });
152
+ if (problems.length) throw new ViewDefinitionError(contract.name, problems);
153
+ const copy = definition.copy ?? {};
154
+ const base = contract.name.split(".").pop() ?? contract.name;
155
+ const noun = copy.noun ?? facts.noun ?? singular(base.replace(/_/g, " "));
156
+ const nounPlural = copy.nounPlural ?? facts.nounPlural ?? (copy.noun || facts.noun ? `${noun}s` : base.replace(/_/g, " "));
157
+ const title = copy.title ?? facts.label ?? titleCase(nounPlural);
158
+ const labelField = facts.labelField ?? fields.find((f) => /^(name|title|label|full_name|display_name)$/.test(f.name))?.name;
159
+ const label = (name) => own(viewFields, name)?.label ?? byName.get(name)?.label ?? titleCase(name);
160
+ const display = (name) => {
161
+ const field = byName.get(name);
162
+ return own(viewFields, name)?.display ?? (field ? deriveDisplay(field) : "text");
163
+ };
164
+ const readable = (name) => byName.get(name)?.permissions?.read !== false;
165
+ const readOnly = (field) => Boolean(
166
+ field.generated || field.readOnly || field.references || field.permissions?.update === false || own(viewFields, field.name)?.readOnly
167
+ );
168
+ const quiet = (f) => keys.has(f.name) || scope.has(f.name) || Boolean(f.sensitive) || Boolean(f.references);
169
+ const defaultColumns = own(columnLists, "default") ?? fields.filter((f) => !quiet(f)).map((f) => f.name);
170
+ const presetNames = Object.freeze(["default", ...Object.keys(columnLists).filter((p) => p !== "default")]);
171
+ const resolvedColumns = /* @__PURE__ */ new Map();
172
+ const columns = (preset = "default") => {
173
+ const cached = resolvedColumns.get(preset);
174
+ if (cached) return cached;
175
+ const list = preset === "default" ? defaultColumns : own(columnLists, preset);
176
+ if (!list) throw new ViewDefinitionError(contract.name, [`no column preset "${preset}"`]);
177
+ const out = Object.freeze(
178
+ list.filter((column) => typeof column !== "string" || readable(column)).map((column) => {
179
+ if (typeof column !== "string") {
180
+ return Object.freeze({ key: column.key, label: column.label, display: column.display ?? "text", value: column.value });
181
+ }
182
+ const v = own(viewFields, column);
183
+ return Object.freeze({
184
+ key: column,
185
+ label: label(column),
186
+ display: display(column),
187
+ field: byName.get(column),
188
+ value: (row) => row[column],
189
+ ...v?.tones ? { tones: v.tones } : {},
190
+ ...v?.when ? { when: (row, viewer = NO_VIEWER) => v.when(row, viewer) } : {},
191
+ ...v?.timeZone ? { timeZone: v.timeZone } : {}
192
+ });
193
+ })
194
+ );
195
+ resolvedColumns.set(preset, out);
196
+ return out;
197
+ };
198
+ const placed = definition.form ? formItems.flatMap(
199
+ (item) => typeof item === "string" ? [{ name: item, section: null, sectionTitle: null }] : item.fields.map((name) => ({ name, section: item.section, sectionTitle: item.title ?? titleCase(item.section) }))
200
+ ) : fields.filter((f) => !readOnly(f) && (!quiet(f) || keys.has(f.name) && !f.hasDefault && !f.sensitive) && f.type !== "json" && !f.array).map((f) => ({ name: f.name, section: null, sectionTitle: null }));
201
+ const serverKey = (f, mode) => keys.has(f.name) && (mode === "edit" || Boolean(f.hasDefault));
202
+ const resolvedForms = /* @__PURE__ */ new Map();
203
+ const form = (mode) => {
204
+ const cached = resolvedForms.get(mode);
205
+ if (cached) return cached;
206
+ const out = Object.freeze(placed.filter(({ name }) => !scope.has(name) && readable(name) && !serverKey(byName.get(name), mode)).map(({ name, section, sectionTitle }) => {
207
+ const field = byName.get(name);
208
+ const v = own(viewFields, name);
209
+ const locked = readOnly(field);
210
+ return Object.freeze({
211
+ field,
212
+ label: label(name),
213
+ display: display(name),
214
+ required: !locked && !field.nullable && !field.optional && (mode === "edit" || !field.hasDefault),
215
+ readOnly: locked,
216
+ section,
217
+ sectionTitle,
218
+ ...v?.max !== void 0 ? { max: v.max } : {},
219
+ ...v?.visible ? { visible: v.visible } : {}
220
+ });
221
+ }));
222
+ resolvedForms.set(mode, out);
223
+ return out;
224
+ };
225
+ const writable = (mode) => Object.freeze(form(mode).filter((f) => !f.readOnly).map((f) => f.field.name));
226
+ const guards = definition.can ?? {};
227
+ function can(action, rowOrViewer, maybeViewer) {
228
+ if (action === "create" && maybeViewer !== void 0) throw new TypeError(`[genesis-core] ${contract.name}: can("create", viewer) takes no row`);
229
+ if (action === "create") return guards.create?.(rowOrViewer ?? NO_VIEWER) ?? true;
230
+ const guard = guards[action];
231
+ const row = rowOrViewer;
232
+ return guard && row ? guard(row, maybeViewer ?? NO_VIEWER) : true;
233
+ }
234
+ const actionGuards = new Map(actionList.map((a) => [a.name, a.can]));
235
+ const resolvedActions = Object.freeze(
236
+ actionList.map(
237
+ (a) => Object.freeze({
238
+ name: a.name,
239
+ label: a.label,
240
+ ...a.confirm !== void 0 ? { confirm: a.confirm } : {},
241
+ ...a.description !== void 0 ? { description: a.description } : {},
242
+ ...a.destructive ? { destructive: true } : {}
243
+ })
244
+ )
245
+ );
246
+ function canAction(name, row, viewer = NO_VIEWER) {
247
+ if (!actionGuards.has(name)) throw new ViewDefinitionError(contract.name, [`no action "${name}"`]);
248
+ const guard = actionGuards.get(name);
249
+ if (!guard) return true;
250
+ const result = guard(row, viewer);
251
+ if (result === true) return true;
252
+ return typeof result === "string" && result.trim() ? result : "This isn't allowed.";
253
+ }
254
+ const summary = (row) => {
255
+ if (definition.summary) return definition.summary(row);
256
+ const value = labelField ? row[labelField] : void 0;
257
+ return { title: value === null || value === void 0 || value === "" ? titleCase(noun) : String(value) };
258
+ };
259
+ return Object.freeze({
260
+ contract,
261
+ definition: Object.freeze({
262
+ ...definition,
263
+ fields: viewFields,
264
+ columns: columnLists,
265
+ presets,
266
+ ...definition.form ? { form: formItems } : {},
267
+ ...definition.scope ? { scope: Object.freeze([...definition.scope]) } : {},
268
+ ...definition.actions ? { actions: actionList } : {}
269
+ }),
270
+ resource: contract.name,
271
+ noun,
272
+ nounPlural,
273
+ title,
274
+ labelField,
275
+ presets: presetNames,
276
+ field: (name) => byName.get(name),
277
+ label,
278
+ display,
279
+ columns,
280
+ form,
281
+ writable,
282
+ can,
283
+ actions: () => resolvedActions,
284
+ canAction,
285
+ summary
286
+ });
287
+ }
288
+
289
+ // src/resource-view/picture.ts
290
+ var segmenter;
291
+ var LETTER = /^\p{L}/u;
292
+ function firstLetter(word) {
293
+ if (segmenter === void 0) {
294
+ segmenter = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity: "grapheme" }) : null;
295
+ }
296
+ const parts = segmenter ? Array.from(segmenter.segment(word), (s) => s.segment) : Array.from(word);
297
+ return parts.find((part) => LETTER.test(part)) ?? "";
298
+ }
299
+ function initialsOf(name) {
300
+ const letters = (name ?? "").trim().split(/\s+/).map(firstLetter).filter(Boolean);
301
+ if (letters.length === 0) return "";
302
+ const pair = letters.length === 1 ? [letters[0]] : [letters[0], letters[letters.length - 1]];
303
+ return pair.map((l) => l.toUpperCase().length === l.length ? l.toUpperCase() : l).join("");
304
+ }
305
+ function isImageSrc(src) {
306
+ if (!isSafeUrl(src)) return false;
307
+ const value = src.trim();
308
+ return value.startsWith("/") || /^https?:/i.test(value);
309
+ }
310
+ function rowPicture(summary) {
311
+ const image = summary.image;
312
+ if (!image) return null;
313
+ const initials = initialsOf(image.name);
314
+ if (isImageSrc(image.src)) return { kind: "image", src: image.src.trim(), alt: image.alt ?? "", fallback: initials };
315
+ return initials ? { kind: "initials", text: initials } : null;
316
+ }
317
+
318
+ // src/resource-view/scope.ts
319
+ var camel = (key) => key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
320
+ function scopeValues(view, scope) {
321
+ const out = {};
322
+ const missing = [];
323
+ for (const key of view.definition.scope ?? []) {
324
+ const value = scope && Object.hasOwn(scope, key) ? scope[key] : scope?.[camel(key)];
325
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") out[key] = value;
326
+ else missing.push(key);
327
+ }
328
+ if (missing.length && process.env.NODE_ENV !== "production") {
329
+ throw new ViewDefinitionError(
330
+ view.resource,
331
+ missing.map((key) => `scope "${key}" has no single value in ViewerScope's scope`)
332
+ );
333
+ }
334
+ return Object.freeze(out);
335
+ }
336
+
337
+ // src/resource-view/workspace.ts
338
+ var WORKSPACE = /* @__PURE__ */ Symbol.for("genesis.resource-workspace");
339
+ var REFUSED = "This isn't allowed.";
340
+ var TONES = /* @__PURE__ */ new Set(["success", "warning", "danger", "info", "muted"]);
341
+ var SECTION_KEYS = /* @__PURE__ */ new Set(["id", "label", "list", "settings"]);
342
+ var dev = () => process.env.NODE_ENV !== "production";
343
+ function unsettable(field) {
344
+ if (!field) return null;
345
+ const facts = field;
346
+ if (field.type === "json") return "is JSON";
347
+ if (field.array) return "is a list";
348
+ if (field.references || field.type === "relation") return "is a link";
349
+ if (facts.sensitive) return "is sensitive";
350
+ return null;
351
+ }
352
+ function isWorkspace(value) {
353
+ return typeof value === "object" && value !== null && value[WORKSPACE] === true;
354
+ }
355
+ function isView(value) {
356
+ return typeof value === "object" && value !== null && typeof value.columns === "function" && typeof value.resource === "string";
357
+ }
358
+ function defineWorkspace(view, definition) {
359
+ const where = `${view.resource} workspace`;
360
+ const problems = [];
361
+ const writable = new Set(view.writable("edit"));
362
+ const actionNames = new Set(view.actions().map((a) => a.name));
363
+ const input = Array.isArray(definition?.sections) ? definition.sections : [];
364
+ if (!Array.isArray(definition?.sections)) problems.push("sections isn't a list");
365
+ else if (input.length === 0) problems.push("sections is empty");
366
+ const ids = /* @__PURE__ */ new Set();
367
+ const settingsSeen = /* @__PURE__ */ new Set();
368
+ const sections = [];
369
+ const filters = /* @__PURE__ */ new Map();
370
+ input.forEach((raw, i) => {
371
+ const at = `sections[${i}]`;
372
+ if (!raw || typeof raw !== "object") {
373
+ problems.push(`${at} isn't a section`);
374
+ return;
375
+ }
376
+ const s = raw;
377
+ const name = typeof s.id === "string" && s.id.trim() ? s.id : void 0;
378
+ if (!name) problems.push(`${at} has no id`);
379
+ else if (ids.has(name)) problems.push(`sections lists "${name}" twice`);
380
+ else ids.add(name);
381
+ const label = `sections.${name ?? i}`;
382
+ if (typeof s.label !== "string" || !s.label.trim()) problems.push(`${label} has no label`);
383
+ if (isWorkspace(s) || "sections" in s || "workspace" in s) {
384
+ problems.push(`${label} holds a workspace; sections don't nest`);
385
+ return;
386
+ }
387
+ const unknown = Object.keys(s).filter((k) => !SECTION_KEYS.has(k));
388
+ if (unknown.length) problems.push(`${label} has ${unknown.map((k) => `"${k}"`).join(", ")}, which isn't a section key (id, label, list, settings)`);
389
+ const hasList = s.list !== void 0;
390
+ const hasSettings = s.settings !== void 0;
391
+ if (hasList && hasSettings) {
392
+ problems.push(`${label} has both list and settings; a section has one`);
393
+ return;
394
+ }
395
+ if (hasList) {
396
+ const list = s.list;
397
+ if (isWorkspace(list?.view)) problems.push(`${label}.list.view is a workspace; sections don't nest`);
398
+ else if (!isView(list?.view)) problems.push(`${label}.list.view isn't a view`);
399
+ if (typeof list?.filter !== "function") problems.push(`${label}.list.filter isn't a function`);
400
+ if (name && isView(list?.view) && !isWorkspace(list.view) && typeof list.filter === "function") {
401
+ filters.set(name, list.filter);
402
+ sections.push(Object.freeze({ id: name, label: s.label, kind: "list", view: list.view }));
403
+ }
404
+ return;
405
+ }
406
+ if (hasSettings) {
407
+ if (!Array.isArray(s.settings)) {
408
+ problems.push(`${label}.settings isn't a list`);
409
+ return;
410
+ }
411
+ if (s.settings.length === 0) problems.push(`${label}.settings lists no fields`);
412
+ for (const field of s.settings) {
413
+ const why = unsettable(view.field(field));
414
+ if (why) problems.push(`${label}.settings names "${field}", which ${why}; it needs an editor of its own`);
415
+ else if (!writable.has(field)) problems.push(`${label}.settings names "${field}", which the view can't write on edit`);
416
+ if (settingsSeen.has(field)) problems.push(`settings lists "${field}" twice`);
417
+ settingsSeen.add(field);
418
+ }
419
+ if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: "settings", settings: Object.freeze(s.settings.map(String)) }));
420
+ return;
421
+ }
422
+ if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: "slot" }));
423
+ });
424
+ const requested = definition?.header?.actions;
425
+ if (requested !== void 0 && !Array.isArray(requested)) problems.push("header.actions isn't a list");
426
+ const headerActions = Object.freeze(
427
+ Array.isArray(requested) ? [...requested] : view.actions().map((a) => a.name)
428
+ );
429
+ const headerSeen = /* @__PURE__ */ new Set();
430
+ for (const name of headerActions) {
431
+ if (!actionNames.has(name)) problems.push(`header.actions names "${name}", which isn't a view action`);
432
+ if (headerSeen.has(name)) problems.push(`header.actions lists "${name}" twice`);
433
+ headerSeen.add(name);
434
+ }
435
+ if (definition?.readiness !== void 0 && typeof definition.readiness !== "function") {
436
+ problems.push("readiness isn't a function");
437
+ }
438
+ if (problems.length) throw new ViewDefinitionError(where, problems);
439
+ const frozenSections = Object.freeze(sections);
440
+ const byId = new Map(frozenSections.map((s) => [s.id, s]));
441
+ const actionByName = new Map(view.actions().map((a) => [a.name, a]));
442
+ const readiness = definition.readiness;
443
+ const settingsOf = (sectionId) => {
444
+ const s = byId.get(sectionId);
445
+ if (!s || s.kind !== "settings") throw new ViewDefinitionError(where, [`no settings section "${sectionId}"`]);
446
+ return s.settings;
447
+ };
448
+ const resolvedSettings = /* @__PURE__ */ new Map();
449
+ const settingsFields = (sectionId) => {
450
+ const key = sectionId ?? "";
451
+ const cached = resolvedSettings.get(key);
452
+ if (cached) return cached;
453
+ const names = sectionId === void 0 ? frozenSections.flatMap((s) => s.kind === "settings" ? s.settings : []) : settingsOf(sectionId);
454
+ const form = new Map(view.form("edit").map((f) => [f.field.name, f]));
455
+ const out = Object.freeze(names.map((n) => form.get(n)).filter((f) => f !== void 0));
456
+ resolvedSettings.set(key, out);
457
+ return out;
458
+ };
459
+ const headerFor = (row, options = {}) => {
460
+ const summary = view.summary(row);
461
+ const served = options.served ? new Set(options.served) : null;
462
+ const actions = [];
463
+ if (options.runnable !== false) {
464
+ for (const name of headerActions) {
465
+ if (served && !served.has(name)) continue;
466
+ const own2 = options.can?.(name, row);
467
+ if (own2 === false) continue;
468
+ const allowed = typeof own2 === "string" ? own2 || REFUSED : view.canAction(name, row, options.viewer);
469
+ actions.push(Object.freeze({ ...actionByName.get(name), allowed }));
470
+ }
471
+ }
472
+ return Object.freeze({
473
+ title: summary.title,
474
+ ...summary.subtitle !== void 0 ? { subtitle: summary.subtitle } : {},
475
+ chips: Object.freeze([...summary.chips ?? []]),
476
+ actions: Object.freeze(actions)
477
+ });
478
+ };
479
+ const readinessFor = (row) => {
480
+ if (!readiness) return Object.freeze([]);
481
+ return Object.freeze(
482
+ readiness(row).map((item, i) => {
483
+ let tone = item.tone ?? (item.ok ? "success" : "warning");
484
+ if (!TONES.has(tone)) {
485
+ if (dev()) console.warn(`[genesis-core] ${where}: readiness "${item.title}" has tone "${String(tone)}", which isn't a chip tone; showing it muted.`);
486
+ tone = "muted";
487
+ }
488
+ return Object.freeze({
489
+ key: item.id ?? `${i}:${item.title}`,
490
+ title: item.title,
491
+ ok: Boolean(item.ok),
492
+ ...item.reason !== void 0 ? { reason: item.reason } : {},
493
+ tone
494
+ });
495
+ })
496
+ );
497
+ };
498
+ const readinessSummary = (row) => readiness ? readinessOf(
499
+ readinessFor(row).filter((r) => !r.ok).map((r) => ({ level: r.tone === "danger" ? "error" : "warning" }))
500
+ ) : null;
501
+ return Object.freeze({
502
+ [WORKSPACE]: true,
503
+ view,
504
+ sections: frozenSections,
505
+ headerActions,
506
+ hasReadiness: Boolean(readiness),
507
+ section: (id) => byId.get(id),
508
+ recordId: (row) => encodeRecordKey(view.contract, row),
509
+ settingsLocked: (row, viewer) => {
510
+ const allowed = view.can("update", row, viewer);
511
+ return allowed === true ? null : typeof allowed === "string" && allowed.trim() ? allowed : REFUSED;
512
+ },
513
+ headerFor,
514
+ settingsFields,
515
+ settingsPatch: (sectionId, values) => {
516
+ const patch = {};
517
+ for (const name of settingsOf(sectionId)) if (Object.hasOwn(values, name)) patch[name] = values[name];
518
+ return patch;
519
+ },
520
+ listFilter: (sectionId, row) => {
521
+ const filter = filters.get(sectionId);
522
+ if (!filter) throw new ViewDefinitionError(where, [`no list section "${sectionId}"`]);
523
+ const out = filter(row);
524
+ if (dev()) {
525
+ const entries = out && typeof out === "object" ? Object.entries(out) : [];
526
+ const bad = entries.filter(([, v]) => !(v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean"));
527
+ if (entries.length === 0 || bad.length) {
528
+ throw new ViewDefinitionError(where, [
529
+ entries.length === 0 ? `sections.${sectionId}.list.filter gave no keys, which would list every row` : `sections.${sectionId}.list.filter gives ${bad.map(([k]) => `"${k}"`).join(", ")} no single value`
530
+ ]);
531
+ }
532
+ }
533
+ return Object.freeze({ ...out });
534
+ },
535
+ readinessFor,
536
+ readinessSummary
537
+ });
538
+ }
539
+
540
+ export { ViewDefinitionError, defineView, defineWorkspace, deriveDisplay, initialsOf, isWorkspace, rowPicture, scopeValues };
541
+ //# sourceMappingURL=index.js.map
542
+ //# sourceMappingURL=index.js.map