@kidecms/core 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -248,6 +248,7 @@ function SortableBlock({
248
248
  meta={meta}
249
249
  value={block[fieldName]}
250
250
  onChange={(v) => onUpdateField(fieldName, v)}
251
+ siblings={block}
251
252
  linkOptions={linkOptions}
252
253
  />
253
254
  ))
@@ -283,6 +283,7 @@ function BlockNodeView(props: NodeViewProps) {
283
283
  meta={meta}
284
284
  value={fields[fieldName]}
285
285
  onChange={(v) => updateField(fieldName, v)}
286
+ siblings={fields}
286
287
  linkOptions={options.linkOptions ?? []}
287
288
  />
288
289
  ))}
@@ -108,6 +108,7 @@ const toSubFieldMeta = (subField: FieldConfig): SubFieldMeta => ({
108
108
  of: "of" in subField && subField.of ? { type: subField.of.type } : undefined,
109
109
  collection: "collection" in subField ? subField.collection : undefined,
110
110
  hasMany: "hasMany" in subField ? subField.hasMany : undefined,
111
+ condition: subField.condition,
111
112
  itemFields:
112
113
  "itemFields" in subField && subField.itemFields
113
114
  ? Object.fromEntries(Object.entries(subField.itemFields).map(([name, f]) => [name, toSubFieldMeta(f)]))
@@ -7,7 +7,7 @@ import DocumentCombobox from "./DocumentCombobox";
7
7
  /** A collection whose documents can be the target of an internal link. */
8
8
  export type LinkableCollection = { collection: string; label: string };
9
9
 
10
- export type LinkTarget = { id: string; label: string; href: string };
10
+ export type LinkTarget = { id: string; collection: string; label: string; href: string };
11
11
 
12
12
  /**
13
13
  * Picks an internal document by searching the linkable collections on the
@@ -42,7 +42,7 @@ export default function InternalLinkPicker({
42
42
  display={editTitle || editHref}
43
43
  isSelected={(hit) => !!editHref && hit.href === editHref}
44
44
  onPick={(hit) => {
45
- if (hit.href) onSelect({ id: hit.docId, label: hit.title, href: hit.href });
45
+ if (hit.href) onSelect({ id: hit.docId, collection: hit.collection, label: hit.title, href: hit.href });
46
46
  }}
47
47
  closeOnPick
48
48
  triggerClassName={cn("h-9 min-w-0 rounded-lg px-3", triggerClassName)}
@@ -8,12 +8,21 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
8
8
  import InternalLinkPicker, { type LinkableCollection } from "./InternalLinkPicker";
9
9
 
10
10
  // A structured link control: URL + label + open-in-new-tab, stored as
11
- // { type, url, label, title, newTab }. A leading "/" is treated as an internal
12
- // link. When linkable collections are provided, internal links are chosen with a
13
- // document picker instead of a hand-typed path (which silently breaks on slug edits).
14
- // `title` is the picked document's title — renderers use it as the link text
15
- // when `label` is left empty.
16
- type LinkValue = { type?: string; url?: string; label?: string; title?: string; newTab?: boolean };
11
+ // { type, url, label, title, newTab, docId, collection }. A leading "/" is
12
+ // treated as an internal link. When linkable collections are provided, internal
13
+ // links are chosen with a document picker; the pick stores the document
14
+ // reference (docId + collection) so renderers can resolve the current route via
15
+ // resolveLinkUrl(), with `url` kept as a cached fallback. `title` is the picked
16
+ // document's title — renderers use it as the link text when `label` is left empty.
17
+ type LinkValue = {
18
+ type?: string;
19
+ url?: string;
20
+ label?: string;
21
+ title?: string;
22
+ newTab?: boolean;
23
+ docId?: string;
24
+ collection?: string;
25
+ };
17
26
 
18
27
  type Props = {
19
28
  name?: string;
@@ -94,13 +103,17 @@ export default function LinkField({ name, value: initial, onChange, linkOptions
94
103
  editHref={value.url ?? ""}
95
104
  editTitle={value.title}
96
105
  collections={linkOptions}
97
- onSelect={(item) => set({ url: item.href, title: item.label })}
106
+ onSelect={(item) =>
107
+ set({ url: item.href, title: item.label, docId: item.id, collection: item.collection })
108
+ }
98
109
  />
99
110
  ) : (
100
111
  <Input
101
112
  value={value.url ?? ""}
102
113
  placeholder="https://example.com"
103
- onChange={(e) => set({ url: e.target.value, title: undefined })}
114
+ onChange={(e) =>
115
+ set({ url: e.target.value, title: undefined, docId: undefined, collection: undefined })
116
+ }
104
117
  />
105
118
  )}
106
119
  </div>
@@ -108,7 +121,7 @@ export default function LinkField({ name, value: initial, onChange, linkOptions
108
121
  <Input
109
122
  value={value.url ?? ""}
110
123
  placeholder="https://example.com or /about"
111
- onChange={(e) => set({ url: e.target.value, title: undefined })}
124
+ onChange={(e) => set({ url: e.target.value, title: undefined, docId: undefined, collection: undefined })}
112
125
  />
113
126
  )}
114
127
  </div>
@@ -80,6 +80,7 @@ export default function SharedSectionBlockField({ name, value, types }: Props) {
80
80
  meta={meta}
81
81
  value={block[fieldName]}
82
82
  onChange={(v) => updateField(fieldName, v)}
83
+ siblings={block}
83
84
  />
84
85
  ))}
85
86
  </div>
@@ -46,10 +46,20 @@ export type SubFieldMeta = {
46
46
  of?: { type: string };
47
47
  collection?: string;
48
48
  hasMany?: boolean;
49
+ condition?: { field: string; value: string | string[] | boolean };
49
50
  /** Typed repeater row schema (json + admin.component "repeater"). */
50
51
  itemFields?: Record<string, SubFieldMeta>;
51
52
  };
52
53
 
54
+ /** Same semantics as the edit form's conditional-visibility script (EditScripts). */
55
+ export function matchesCondition(expected: string | string[] | boolean, current: unknown): boolean {
56
+ if (Array.isArray(expected)) return expected.some((v) => String(v) === String(current ?? ""));
57
+ if (typeof expected === "boolean") {
58
+ return expected ? current === true || current === "true" : !current || current === "false";
59
+ }
60
+ return String(expected) === String(current ?? "");
61
+ }
62
+
53
63
  export type BlockTypesMeta = Record<string, Record<string, SubFieldMeta>>;
54
64
 
55
65
  export function generateKey() {
@@ -99,6 +109,7 @@ export function SubField({
99
109
  meta,
100
110
  value,
101
111
  onChange,
112
+ siblings,
102
113
  linkOptions = [],
103
114
  }: {
104
115
  blockKey: string;
@@ -106,11 +117,15 @@ export function SubField({
106
117
  meta: SubFieldMeta;
107
118
  value: unknown;
108
119
  onChange: (value: unknown) => void;
120
+ /** The block's other field values — evaluated against `meta.condition`. */
121
+ siblings?: Record<string, unknown>;
109
122
  linkOptions?: LinkableCollection[];
110
123
  }) {
111
124
  const label = meta.label ?? humanize(fieldName);
112
125
  const fieldId = `${blockKey}_${fieldName}`;
113
126
 
127
+ if (meta.condition && !matchesCondition(meta.condition.value, siblings?.[meta.condition.field])) return null;
128
+
114
129
  return (
115
130
  <div className="grid gap-2">
116
131
  <Label htmlFor={fieldId}>
@@ -527,6 +542,7 @@ function SortableRepeaterItem({
527
542
  meta={itemFields[key]}
528
543
  value={item[key]}
529
544
  onChange={(v) => onUpdate(key, v)}
545
+ siblings={item}
530
546
  linkOptions={linkOptions}
531
547
  />
532
548
  ))
package/core/api.ts CHANGED
@@ -553,8 +553,10 @@ export const createCms = (config: CMSConfig) => {
553
553
  // this, e.g. findOne({ slug, locale: "en" }) can never match a
554
554
  // translated slug.
555
555
  const tr = tables.translations;
556
+ // Raw SQL skips drizzle's column mapper, so booleans must be bound as 0/1.
557
+ const bound = typeof value === "boolean" ? (value ? 1 : 0) : value;
556
558
  conditions.push(
557
- sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} = ${value}) OR (${tables.main[key]} = ${value} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
559
+ sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} = ${bound}) OR (${tables.main[key]} = ${bound} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
558
560
  );
559
561
  } else {
560
562
  conditions.push(eq(tables.main[key], value));
package/core/generator.ts CHANGED
@@ -33,7 +33,7 @@ const isJsonField = (field: FieldConfig) =>
33
33
  field.type === "blocks" ||
34
34
  (field.type === "relation" && field.hasMany);
35
35
 
36
- const generateColumnDef = (fieldName: string, field: FieldConfig): string => {
36
+ const generateColumnDef = (fieldName: string, field: FieldConfig, options: { bare?: boolean } = {}): string => {
37
37
  const colName = snakeCase(fieldName);
38
38
  let col: string;
39
39
 
@@ -45,13 +45,17 @@ const generateColumnDef = (fieldName: string, field: FieldConfig): string => {
45
45
  col = `text("${colName}")`;
46
46
  }
47
47
 
48
- if (field.required && !field.condition) col += ".notNull()";
49
- if (field.unique) col += ".unique()";
50
- if (field.defaultValue !== undefined && !isJsonField(field)) {
51
- if (field.type === "number" || field.type === "boolean") {
52
- col += `.default(${field.defaultValue})`;
53
- } else {
54
- col += `.default(${JSON.stringify(field.defaultValue)})`;
48
+ // Translations rows are a sparse overlay (readers skip null): every column
49
+ // stays nullable, un-unique, and default-free regardless of the field config.
50
+ if (!options.bare) {
51
+ if (field.required && !field.condition) col += ".notNull()";
52
+ if (field.unique) col += ".unique()";
53
+ if (field.defaultValue !== undefined && !isJsonField(field)) {
54
+ if (field.type === "number" || field.type === "boolean") {
55
+ col += `.default(${field.defaultValue})`;
56
+ } else {
57
+ col += `.default(${JSON.stringify(field.defaultValue)})`;
58
+ }
55
59
  }
56
60
  }
57
61
 
@@ -117,7 +121,7 @@ const generateTranslationsTable = (config: CMSConfig, collection: CollectionConf
117
121
  ];
118
122
 
119
123
  for (const fieldName of translatableFields) {
120
- columns.push(generateColumnDef(fieldName, collection.fields[fieldName]));
124
+ columns.push(generateColumnDef(fieldName, collection.fields[fieldName], { bare: true }));
121
125
  }
122
126
 
123
127
  return `export const ${varName} = sqliteTable("${tableName}", {\n${columns.join("\n")}\n}, (table) => ({\n uniqueLocale: unique().on(table._entityId, table._languageCode),\n}));`;
package/core/index.ts CHANGED
@@ -165,11 +165,13 @@ export {
165
165
  slugify,
166
166
  escapeHtml,
167
167
  safeUrl,
168
+ resolveLinkUrl,
168
169
  serializeFieldValue,
169
170
  contentSegments,
170
171
  contentBlocks,
171
172
  contentToPlainText,
172
173
  } from "./values";
174
+ export type { StoredLink } from "./values";
173
175
  export type { ContentSegment } from "./values";
174
176
  export { cmsImageUrl, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
175
177
  export type { CropOptions, TransformOptions } from "./image";
package/core/migrate.ts CHANGED
@@ -123,18 +123,33 @@ export type ImportReport = {
123
123
  errors: Array<{ collection: string; id: unknown; message: string }>;
124
124
  };
125
125
 
126
+ /** Thrown by a real (non-dry) import run that had failures. Carries the full report. */
127
+ export class ImportFailedError extends Error {
128
+ report: ImportReport;
129
+ constructor(report: ImportReport) {
130
+ const first = report.errors[0]?.message ?? report.invalid[0]?.errors[0]?.message ?? "see report";
131
+ super(`Import failed for ${report.failed} of ${report.total} documents (first: ${first})`);
132
+ this.name = "ImportFailedError";
133
+ this.report = report;
134
+ }
135
+ }
136
+
126
137
  type AnyCms = Record<string, any>;
127
138
 
128
139
  /**
129
140
  * Validate then (unless dryRun) create every item via the typed API. Use
130
141
  * `{ _system: true, _skipSearch: true }` context for bulk imports and call
131
142
  * `reindex()` once afterwards.
143
+ *
144
+ * A real run throws ImportFailedError when any document fails, so a half-applied
145
+ * import can't look like success; pass `throwOnFailed: false` to get the report
146
+ * back instead. Dry runs always return the report.
132
147
  */
133
148
  export const importDocuments = async (
134
149
  cms: AnyCms,
135
150
  config: CMSConfig,
136
151
  items: ImportItem[],
137
- options: { dryRun?: boolean; context?: Record<string, unknown> } = {},
152
+ options: { dryRun?: boolean; throwOnFailed?: boolean; context?: Record<string, unknown> } = {},
138
153
  ): Promise<ImportReport> => {
139
154
  const dryRun = options.dryRun ?? false;
140
155
  const context = options.context ?? { _system: true, _skipSearch: true };
@@ -178,6 +193,7 @@ export const importDocuments = async (
178
193
  report.failed++;
179
194
  }
180
195
  }
196
+ if (!dryRun && report.failed > 0 && (options.throwOnFailed ?? true)) throw new ImportFailedError(report);
181
197
  return report;
182
198
  };
183
199
 
package/core/values.ts CHANGED
@@ -273,6 +273,38 @@ export const safeUrl = (value: string): string | null => {
273
273
  }
274
274
  };
275
275
 
276
+ /** Value shape stored by the admin's link field. */
277
+ export type StoredLink = {
278
+ type?: string;
279
+ url?: string;
280
+ label?: string;
281
+ title?: string;
282
+ newTab?: boolean;
283
+ docId?: string;
284
+ collection?: string;
285
+ };
286
+
287
+ /**
288
+ * Current href for a stored link value. A link picked with the internal
289
+ * document picker carries a document reference (docId + collection) — resolve
290
+ * the document's route fresh so the link survives slug edits. The stored `url`
291
+ * is the fallback: external links, hand-typed paths, links saved before the
292
+ * reference existed, and references to unpublished or deleted documents.
293
+ */
294
+ export const resolveLinkUrl = async (
295
+ cms: Record<string, any>,
296
+ link: StoredLink | null | undefined,
297
+ ): Promise<string | null> => {
298
+ if (!link) return null;
299
+ const fallback = link.url ? safeUrl(String(link.url)) : null;
300
+ if (!link.docId || !link.collection) return fallback;
301
+ const api = cms[link.collection];
302
+ if (!api?.findById) return fallback;
303
+ const doc = await api.findById(link.docId).catch(() => null);
304
+ if (!doc) return fallback;
305
+ return cms.meta?.getRouteForDocument?.(link.collection, doc) ?? fallback;
306
+ };
307
+
276
308
  const renderNode = (node: RichTextNode): string => {
277
309
  if (node.type === "text") {
278
310
  let content = escapeHtml(String(node.value ?? ""));
@@ -48,8 +48,10 @@ export const createCmsContext = async () => {
48
48
  /** The resolved CMS config. */
49
49
  config,
50
50
  /** Validate + create a batch of documents. Pass `{ dryRun: true }` for a report only. */
51
- load: (items: ImportItem[], options?: { dryRun?: boolean; context?: Record<string, unknown> }) =>
52
- importDocuments(cms as Record<string, any>, config, items, options),
51
+ load: (
52
+ items: ImportItem[],
53
+ options?: { dryRun?: boolean; throwOnFailed?: boolean; context?: Record<string, unknown> },
54
+ ) => importDocuments(cms as Record<string, any>, config, items, options),
53
55
  /** The machine-readable content model (same as `.kide/model.json`). */
54
56
  model: () => describeModel(config),
55
57
  /** Rebuild the search index for all searchable collections (uses this config's locales). */
package/internals/push.ts CHANGED
@@ -44,11 +44,17 @@ const parseRecreate = (): string[] => {
44
44
  const arg = process.argv.find((a) => a.startsWith("--recreate="))?.slice("--recreate=".length);
45
45
  const raw = process.env.RECREATE ?? arg ?? "";
46
46
  const tables = new Set<string>();
47
+ // Same slug → table-name mapping as the generator, so e.g. front-page finds cms_front_page.
48
+ const snakeCase = (value: string) =>
49
+ value
50
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
51
+ .replace(/[^a-zA-Z0-9]+/g, "_")
52
+ .toLowerCase();
47
53
  for (const name of raw
48
54
  .split(",")
49
55
  .map((s) => s.trim())
50
56
  .filter(Boolean)) {
51
- const base = name.startsWith("cms_") ? name : `cms_${name}`;
57
+ const base = name.startsWith("cms_") ? name : `cms_${snakeCase(name)}`;
52
58
  tables.add(base);
53
59
  tables.add(`${base}_translations`);
54
60
  tables.add(`${base}_versions`);
@@ -73,7 +79,7 @@ async function main() {
73
79
  sqlite.close();
74
80
  process.exit(1);
75
81
  }
76
- for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS ${t}`);
82
+ for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS "${t}"`);
77
83
  console.log(`[cms:push] dropped for recreate: ${recreate.join(", ")}`);
78
84
  }
79
85
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",