@kidecms/wordpress 0.0.0-stage → 0.1.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.
package/src/profile.ts ADDED
@@ -0,0 +1,123 @@
1
+ /** Compact, agent-readable profile of the staged source: what exists, how often, and what it looks like. */
2
+ import { collectDomain, truncate } from "./domain";
3
+ import type { StagedMedia, StagedRecord } from "./staging";
4
+
5
+ export type PathStat = { path: string; records: number; sample: string };
6
+ export type TypeProfile = {
7
+ type: string;
8
+ records: number;
9
+ statuses: Record<string, number>;
10
+ locales: Record<string, number>;
11
+ groups: number;
12
+ /** Where the type's published URLs live (first segment after the locale), and how many go deeper than prefix + slug. */
13
+ prefixes: Array<{ locale: string; prefix: string; records: number }>;
14
+ nested: number;
15
+ paths: PathStat[];
16
+ };
17
+
18
+ export const reusableLookup = (records: StagedRecord[]) => {
19
+ const reusable = new Map(
20
+ records.filter((r) => r.type === "wp_block").map((r) => [r.id, String(r.content ?? "")] as const),
21
+ );
22
+ return (ref: number) => reusable.get(ref);
23
+ };
24
+
25
+ export const buildProfile = (records: StagedRecord[]): TypeProfile[] => {
26
+ const reusable = reusableLookup(records);
27
+ const byType = new Map<string, StagedRecord[]>();
28
+ for (const r of records) {
29
+ const list = byType.get(r.type);
30
+ if (list) list.push(r);
31
+ else byType.set(r.type, [r]);
32
+ }
33
+
34
+ return [...byType.entries()].map(([type, list]) => {
35
+ const stats = new Map<string, PathStat>();
36
+ const statuses: Record<string, number> = {};
37
+ const locales: Record<string, number> = {};
38
+ for (const record of list) {
39
+ statuses[record.status] = (statuses[record.status] ?? 0) + 1;
40
+ if (record.locale) locales[record.locale] = (locales[record.locale] ?? 0) + 1;
41
+ const seen = new Set<string>();
42
+ collectDomain(record, reusable, (path, value) => {
43
+ let stat = stats.get(path);
44
+ if (!stat) stats.set(path, (stat = { path, records: 0, sample: truncate(value) }));
45
+ if (!seen.has(path)) {
46
+ seen.add(path);
47
+ stat.records++;
48
+ }
49
+ });
50
+ }
51
+ return {
52
+ type,
53
+ records: list.length,
54
+ statuses,
55
+ locales,
56
+ groups: new Set(list.map((r) => r.group).filter(Boolean)).size,
57
+ ...urlShape(list),
58
+ paths: [...stats.values()],
59
+ };
60
+ });
61
+ };
62
+
63
+ const urlShape = (list: StagedRecord[]) => {
64
+ const prefixes = new Map<string, { locale: string; prefix: string; records: number }>();
65
+ let nested = 0;
66
+ for (const r of list) {
67
+ if (typeof r.permalink !== "string" || !["publish", "private"].includes(r.status)) continue;
68
+ const segments = r.permalink.split("/").filter(Boolean);
69
+ const localePrefix = r.locale && segments[0] === r.locale ? `/${segments.shift()}` : "";
70
+ if (segments.length > 2) nested++;
71
+ const prefix = `${localePrefix}${segments.length > 1 ? `/${segments[0]}` : ""}/…`;
72
+ const key = `${r.locale ?? ""}|${prefix}`;
73
+ const entry = prefixes.get(key) ?? { locale: r.locale ?? "", prefix, records: 0 };
74
+ entry.records++;
75
+ prefixes.set(key, entry);
76
+ }
77
+ return { prefixes: [...prefixes.values()].sort((a, b) => b.records - a.records).slice(0, 12), nested };
78
+ };
79
+
80
+ const counts = (o: Record<string, number>) =>
81
+ Object.entries(o)
82
+ .map(([k, v]) => `${k} ${v}`)
83
+ .join(", ");
84
+
85
+ const cell = (s: string) => s.replace(/\|/g, "\\|");
86
+
87
+ export const renderProfile = (meta: Record<string, string | undefined>, types: TypeProfile[], media: StagedMedia[]) => {
88
+ const lines = [
89
+ "# Source profile",
90
+ "",
91
+ `Source: ${meta.source} · site ${meta.siteUrl || "?"} · table prefix \`${meta.prefix}\` · scouted ${meta.scoutedAt}`,
92
+ `Media: ${media.length} attachments · uploads ${meta.uploadsDir ? `local \`${meta.uploadsDir}\`` : `download from ${meta.uploadsUrl}`}`,
93
+ "",
94
+ "Every path below must be mapped or dropped in `migration/*.map.ts` (`kide import plan` enforces it).",
95
+ "Inspect real records with `kide import sample <type>`.",
96
+ "",
97
+ "| source type | records | statuses | locales |",
98
+ "| --- | --- | --- | --- |",
99
+ ...types.map((t) => `| \`${t.type}\` | ${t.records} | ${counts(t.statuses)} | ${counts(t.locales) || "—"} |`),
100
+ ];
101
+ for (const t of types) {
102
+ const fields = t.paths.filter((p) => !p.path.startsWith("block:") && !p.path.startsWith("shortcode:"));
103
+ const blocks = t.paths.filter((p) => p.path.startsWith("block:"));
104
+ const shortcodes = t.paths.filter((p) => p.path.startsWith("shortcode:"));
105
+ lines.push("", `## \`${t.type}\` — ${t.records} records${t.groups ? ` · ${t.groups} translation groups` : ""}`, "");
106
+ if (t.prefixes.length)
107
+ lines.push(
108
+ `Published URLs: ${t.prefixes.map((p) => `\`${p.prefix}\` ${p.records}`).join(" · ")}${t.nested ? ` · ${t.nested} deeper than \`/<prefix>/<slug>\` (these URLs change in Kide)` : ""}`,
109
+ "",
110
+ );
111
+ lines.push("| path | filled | sample |", "| --- | --- | --- |");
112
+ for (const p of fields) lines.push(`| \`${p.path}\` | ${p.records}/${t.records} | ${cell(p.sample)} |`);
113
+ if (blocks.length) {
114
+ lines.push("", "Blocks:", "", "| path | in records | sample |", "| --- | --- | --- |");
115
+ for (const p of blocks)
116
+ lines.push(`| \`${p.path}\` | ${p.records} | ${cell(p.path.includes(".") ? p.sample : "")} |`);
117
+ }
118
+ if (shortcodes.length) {
119
+ lines.push("", "Shortcodes:", "", ...shortcodes.map((p) => `- \`${p.path}\` in ${p.records} records`));
120
+ }
121
+ }
122
+ return `${lines.join("\n")}\n`;
123
+ };
package/src/report.ts ADDED
@@ -0,0 +1,128 @@
1
+ import type { PlannedDoc, PlanResult, SourceLedger } from "./plan";
2
+ import type { Staging } from "./staging";
3
+
4
+ export const savePlan = (db: Staging, plan: PlanResult) => {
5
+ db.transaction(() => {
6
+ db.exec("DELETE FROM plan_docs; DELETE FROM plan_meta;");
7
+ const insert = db.prepare(
8
+ "INSERT OR REPLACE INTO plan_docs (doc_id, collection, source_keys, hash, data, translations, expected, media, text_match) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
9
+ );
10
+ for (const d of plan.docs)
11
+ insert.run(
12
+ d.docId,
13
+ d.collection,
14
+ JSON.stringify(d.sourceKeys),
15
+ d.hash,
16
+ JSON.stringify(d.data),
17
+ JSON.stringify(d.translations),
18
+ JSON.stringify(d.expected),
19
+ JSON.stringify(d.media),
20
+ d.textMatch,
21
+ );
22
+ const meta = db.prepare("INSERT INTO plan_meta (key, value) VALUES (?, ?)");
23
+ meta.run("createdAt", new Date().toISOString());
24
+ meta.run("blocking", JSON.stringify(plan.blocking));
25
+ meta.run("urlChanges", JSON.stringify(plan.urlChanges));
26
+ meta.run(
27
+ "media",
28
+ JSON.stringify(Object.fromEntries([...plan.media].filter(([k]) => plan.docs.some((d) => d.media.includes(k))))),
29
+ );
30
+ })();
31
+ };
32
+
33
+ export const loadPlan = (db: Staging) => {
34
+ const docs: PlannedDoc[] = (db.prepare("SELECT * FROM plan_docs ORDER BY collection, doc_id").all() as any[]).map(
35
+ (r) => ({
36
+ docId: r.doc_id,
37
+ collection: r.collection,
38
+ sourceKeys: JSON.parse(r.source_keys),
39
+ hash: r.hash,
40
+ data: JSON.parse(r.data),
41
+ translations: JSON.parse(r.translations),
42
+ expected: JSON.parse(r.expected),
43
+ media: JSON.parse(r.media),
44
+ textMatch: r.text_match === "set" ? "set" : "multiset",
45
+ }),
46
+ );
47
+ const meta = Object.fromEntries(
48
+ (db.prepare("SELECT key, value FROM plan_meta").all() as Array<{ key: string; value: string }>).map((r) => [
49
+ r.key,
50
+ r.value,
51
+ ]),
52
+ );
53
+ if (!meta.createdAt) return null;
54
+ return {
55
+ docs,
56
+ createdAt: meta.createdAt,
57
+ blocking: JSON.parse(meta.blocking ?? "[]") as string[],
58
+ urlChanges: JSON.parse(meta.urlChanges ?? "[]") as Array<{ key: string; from: string; to: string }>,
59
+ media: JSON.parse(meta.media ?? "{}") as Record<
60
+ string,
61
+ { key: string; file: string | null; url: string; mime: string | null; alt: string | null }
62
+ >,
63
+ };
64
+ };
65
+
66
+ const cell = (s: string) => s.replace(/\|/g, "\\|");
67
+ const pct = (n: number) => `${(n * 100).toFixed(1)}%`;
68
+
69
+ const ledgerSection = (l: SourceLedger): string[] => {
70
+ if (l.skip) return [`## \`${l.source}\` — skipped (${l.records} records): ${l.skip}`];
71
+ const filtered = Object.entries(l.filtered)
72
+ .map(([r, n]) => `${n} ${r}`)
73
+ .join(", ");
74
+ const open = l.paths.filter((p) => p.status === "unaccounted");
75
+ const lines = [
76
+ `## \`${l.source}\` → \`${l.collection}\``,
77
+ "",
78
+ `${l.records} records → ${l.docs} documents${filtered ? ` · filtered: ${filtered}` : ""} · text recall min ${pct(l.recall.min)}, avg ${pct(l.recall.avg)}`,
79
+ "",
80
+ ];
81
+ if (open.length) {
82
+ lines.push(
83
+ "**Unaccounted** — map these or add them to `drop` with a reason:",
84
+ "",
85
+ "| path | in records | sample |",
86
+ "| --- | --- | --- |",
87
+ );
88
+ for (const p of open) lines.push(`| \`${p.path}\` | ${p.records} | ${cell(p.sample)} |`);
89
+ lines.push("");
90
+ }
91
+ const byKind = new Map<string, typeof l.issues>();
92
+ for (const i of l.issues) byKind.set(i.kind, [...(byKind.get(i.kind) ?? []), i]);
93
+ for (const [kind, issues] of byKind) {
94
+ lines.push(`**${kind}** (${issues.length}):`, "");
95
+ for (const i of issues.slice(0, 25)) lines.push(`- ${i.key ? `\`${i.key}\` ` : ""}${i.message}`);
96
+ if (issues.length > 25) lines.push(`- … ${issues.length - 25} more`);
97
+ lines.push("");
98
+ }
99
+ if (l.staleDrops.length)
100
+ lines.push(`Stale drops (match nothing): ${l.staleDrops.map((d) => `\`${d}\``).join(", ")}`, "");
101
+ const mapped = l.paths.filter((p) => p.status === "mapped").map((p) => `\`${p.path}\``);
102
+ const dropped = l.paths.filter((p) => p.status === "dropped").map((p) => `\`${p.path}\` (${p.reason})`);
103
+ lines.push(`Mapped (${mapped.length}): ${mapped.join(", ") || "—"}`, "");
104
+ if (dropped.length) lines.push(`Dropped (${dropped.length}): ${dropped.join(", ")}`, "");
105
+ return lines;
106
+ };
107
+
108
+ export const renderLedger = (plan: PlanResult): string => {
109
+ const lines = [
110
+ "# Import plan ledger",
111
+ "",
112
+ plan.blocking.length
113
+ ? `**BLOCKED** — ${plan.blocking.length} problem(s). \`kide import apply\` refuses until they're fixed:`
114
+ : `**READY** — every source path is mapped or dropped; ${plan.docs.length} documents planned.`,
115
+ "",
116
+ ...plan.blocking.map((b) => `- ${b}`),
117
+ "",
118
+ ];
119
+ if (plan.unmapped.length)
120
+ lines.push(
121
+ "Unmapped source types (add a mapping or `skipSource(type, reason)`):",
122
+ "",
123
+ ...plan.unmapped.map((u) => `- \`${u.type}\` — ${u.records} records`),
124
+ "",
125
+ );
126
+ for (const l of plan.ledgers) lines.push(...ledgerSection(l), "");
127
+ return `${lines.join("\n")}\n`;
128
+ };
package/src/staging.ts ADDED
@@ -0,0 +1,77 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import Database from "better-sqlite3";
4
+
5
+ export const importDir = () => path.resolve(process.env.KIDE_IMPORT_DIR ?? path.join(process.cwd(), ".kide", "import"));
6
+
7
+ export type Staging = InstanceType<typeof Database>;
8
+
9
+ export type StagedRecord = {
10
+ key: string;
11
+ type: string;
12
+ id: number;
13
+ status: string;
14
+ locale?: string;
15
+ group?: string;
16
+ [field: string]: unknown;
17
+ };
18
+
19
+ export type StagedMedia = {
20
+ key: string;
21
+ attachmentId: number | null;
22
+ file: string | null;
23
+ url: string;
24
+ mime: string | null;
25
+ alt: string | null;
26
+ };
27
+
28
+ const SOURCE_TABLES = ["records", "media", "source_meta"];
29
+
30
+ export const openStaging = (dir = importDir()): Staging => {
31
+ mkdirSync(dir, { recursive: true });
32
+ const db = new Database(path.join(dir, "staging.db"));
33
+ db.pragma("journal_mode = WAL");
34
+ db.exec(`
35
+ CREATE TABLE IF NOT EXISTS source_meta (key TEXT PRIMARY KEY, value TEXT);
36
+ CREATE TABLE IF NOT EXISTS records (key TEXT PRIMARY KEY, type TEXT, data TEXT);
37
+ CREATE TABLE IF NOT EXISTS media (key TEXT PRIMARY KEY, attachment_id INTEGER, file TEXT, url TEXT, mime TEXT, alt TEXT);
38
+ CREATE TABLE IF NOT EXISTS plan_docs (doc_id TEXT PRIMARY KEY, collection TEXT, source_keys TEXT, hash TEXT, data TEXT, translations TEXT, expected TEXT, media TEXT);
39
+ CREATE TABLE IF NOT EXISTS plan_meta (key TEXT PRIMARY KEY, value TEXT);
40
+ CREATE TABLE IF NOT EXISTS applied (doc_id TEXT PRIMARY KEY, collection TEXT, hash TEXT, applied_at TEXT);
41
+ CREATE TABLE IF NOT EXISTS media_state (key TEXT PRIMARY KEY, storage_path TEXT, applied_at TEXT);
42
+ `);
43
+ const planColumns = db.prepare("PRAGMA table_info(plan_docs)").all() as Array<{ name: string }>;
44
+ if (!planColumns.some((c) => c.name === "text_match")) db.exec("ALTER TABLE plan_docs ADD COLUMN text_match TEXT");
45
+ return db;
46
+ };
47
+
48
+ /** Re-scouting replaces the source snapshot but keeps what was already applied, so re-runs stay incremental. */
49
+ export const resetSource = (db: Staging) => {
50
+ for (const table of SOURCE_TABLES) db.exec(`DELETE FROM ${table}`);
51
+ db.exec("DROP TABLE IF EXISTS plan_docs_old");
52
+ for (const t of db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'raw_%'").all() as Array<{
53
+ name: string;
54
+ }>)
55
+ db.exec(`DROP TABLE "${t.name}"`);
56
+ };
57
+
58
+ export const getMeta = (db: Staging, key: string): string | undefined =>
59
+ (db.prepare("SELECT value FROM source_meta WHERE key = ?").get(key) as { value: string } | undefined)?.value;
60
+
61
+ export const setMeta = (db: Staging, key: string, value: string) =>
62
+ db.prepare("INSERT OR REPLACE INTO source_meta (key, value) VALUES (?, ?)").run(key, value);
63
+
64
+ export const loadRecords = (db: Staging): StagedRecord[] =>
65
+ (db.prepare("SELECT data FROM records ORDER BY type, key").all() as Array<{ data: string }>).map((r) =>
66
+ JSON.parse(r.data),
67
+ );
68
+
69
+ export const loadMedia = (db: Staging): StagedMedia[] =>
70
+ (db.prepare("SELECT * FROM media").all() as Array<Record<string, any>>).map((r) => ({
71
+ key: r.key,
72
+ attachmentId: r.attachment_id,
73
+ file: r.file,
74
+ url: r.url,
75
+ mime: r.mime,
76
+ alt: r.alt,
77
+ }));
@@ -0,0 +1,199 @@
1
+ /**
2
+ * WordPress structures every site has, converted to the shapes of Kide's presets:
3
+ * nav menus → `menu-items`, a taxonomy → `taxonomy-terms`, a Gravity Form → a `forms` document.
4
+ * Built on the public `MapContext`, so what they read joins the mapping's coverage.
5
+ */
6
+ import { decodeEntities, slugify } from "@kidecms/core";
7
+ import type { MapContext, MenuItem, SourceRecord, TermNode } from "./mapping";
8
+ import { termParts } from "./terms";
9
+
10
+ const MAX_MENU_DEPTH = 3;
11
+ /** Reading a tracked value is what marks it covered. */
12
+ const touch = (..._values: unknown[]) => {};
13
+
14
+ export const menuItems = (menu: SourceRecord, ctx: MapContext): MenuItem[] => {
15
+ const rows = ctx
16
+ .records("nav_menu_item", (r) => ((r.terms as any)?.nav_menu ?? []).some((t: any) => t.id === menu.id))
17
+ .sort((a, b) => Number(a.menuOrder ?? 0) - Number(b.menuOrder ?? 0));
18
+ const items = new Map<string, MenuItem>();
19
+ const parents = new Map<string, string>();
20
+ for (const r of rows) {
21
+ touch(r.terms?.nav_menu?.[0]?.id, r.meta?._menu_item_object);
22
+ const m = r.meta ?? {};
23
+ const target = m._menu_item_type === "taxonomy" ? `term:${m._menu_item_object_id}` : m._menu_item_object_id;
24
+ const record = m._menu_item_type === "custom" ? undefined : ctx.record(target);
25
+ if (m._menu_item_type === "post_type" && !ctx.ref(target, { optional: true })) {
26
+ ctx.warn(
27
+ `menu "${menu.name}": item ${r.id} points to ${m._menu_item_object} ${target}, which isn't imported — left out`,
28
+ );
29
+ continue;
30
+ }
31
+ const url = record ? record.permalink : m._menu_item_url;
32
+ items.set(String(r.id), {
33
+ id: `item-${r.id}`,
34
+ label: String(r.title || record?.title || record?.name || ""),
35
+ href: ctx.link(String(url ?? ""))?.url ?? "",
36
+ ...(m._menu_item_target === "_blank" ? { target: "_blank" as const } : {}),
37
+ children: [],
38
+ });
39
+ const parent = String(m._menu_item_menu_item_parent ?? "0");
40
+ if (parent !== "0") parents.set(String(r.id), parent);
41
+ }
42
+ const roots: MenuItem[] = [];
43
+ for (const [id, item] of items) (items.get(parents.get(id) ?? "")?.children ?? roots).push(item);
44
+ const depth = (list: MenuItem[]): number => (list.length ? 1 + Math.max(...list.map((i) => depth(i.children))) : 0);
45
+ if (depth(roots) > MAX_MENU_DEPTH)
46
+ ctx.warn(`menu "${menu.name}" nests ${depth(roots)} levels; the menu editor shows ${MAX_MENU_DEPTH}`);
47
+ return roots;
48
+ };
49
+
50
+ /**
51
+ * Term ids follow the translation group, so every locale's tree uses the same ids. With `split`,
52
+ * a name that bundles several terms ("Business|Press releases") becomes one term per part, merged
53
+ * by slug; split the posts' values the same way with `termSlugs`.
54
+ */
55
+ export const termTree = (taxonomy: SourceRecord, ctx: MapContext, options: { split?: boolean } = {}): TermNode[] => {
56
+ const terms = ctx.records(`term:${taxonomy.taxonomy}`, (t) => t.locale === taxonomy.locale);
57
+ const nodes = new Map<number, TermNode>();
58
+ const roots: TermNode[] = [];
59
+ const bySlug = new Map<string, TermNode>();
60
+ for (const t of terms) {
61
+ const parts = options.split ? termParts(decodeEntities(String(t.name))) : [];
62
+ if (parts.length > 1) {
63
+ for (const name of parts) {
64
+ const slug = slugify(name);
65
+ if (!bySlug.has(slug))
66
+ roots.push(bySlug.set(slug, { id: `term-${slug}`, name, slug, children: [] }).get(slug)!);
67
+ }
68
+ continue;
69
+ }
70
+ nodes.set(t.id, {
71
+ id: t.group ? slugify(String(t.group)) : `term-${t.id}`,
72
+ name: decodeEntities(String(t.name)),
73
+ slug: String(t.slug),
74
+ children: [],
75
+ });
76
+ }
77
+ for (const t of terms) {
78
+ const node = nodes.get(t.id);
79
+ if (!node) continue;
80
+ if (bySlug.has(node.slug)) continue;
81
+ bySlug.set(node.slug, node);
82
+ (nodes.get(Number(t.parent))?.children ?? roots).push(node);
83
+ }
84
+ return roots;
85
+ };
86
+
87
+ /** A post's term list → slugs, splitting bundled names like `termTree(…, { split: true })` does. */
88
+ export const termSlugs = (terms: unknown, options: { split?: boolean } = {}): string[] => [
89
+ ...new Set(
90
+ (Array.isArray(terms) ? terms : []).flatMap((t: any) => {
91
+ const parts = options.split ? termParts(decodeEntities(String(t.name))) : [];
92
+ return parts.length > 1 ? parts.map((p) => slugify(p)) : [String(t.slug)];
93
+ }),
94
+ ),
95
+ ];
96
+
97
+ const FORM_TYPES: Record<string, string> = {
98
+ text: "text",
99
+ email: "email",
100
+ phone: "tel",
101
+ number: "number",
102
+ textarea: "textarea",
103
+ select: "select",
104
+ multiselect: "checkbox",
105
+ radio: "radio",
106
+ checkbox: "checkbox",
107
+ consent: "consent",
108
+ date: "date",
109
+ time: "time",
110
+ fileupload: "file",
111
+ html: "html",
112
+ section: "section",
113
+ website: "text",
114
+ hidden: "text",
115
+ };
116
+ const CHOICES = new Set(["select", "radio", "checkbox"]);
117
+ /** Spam protection and multi-page breaks are the form renderer's job, not fields. */
118
+ const SKIPPED_FIELDS = new Set(["captcha", "page"]);
119
+
120
+ /** Chained Selects: one select per level, each offering every choice that level can show. */
121
+ const chainedSelects = (
122
+ f: any,
123
+ common: Record<string, unknown>,
124
+ nameFor: (label: string, id: unknown) => string,
125
+ ): Record<string, unknown>[] => {
126
+ const levels = f.inputs?.length ? f.inputs : [{ id: f.id, label: f.label }];
127
+ let choices: any[] = f.choices ?? [];
128
+ return levels.map((input: any) => {
129
+ const unique = [...new Map(choices.map((c) => [String(c.text), c])).values()];
130
+ const field = {
131
+ type: "select",
132
+ name: nameFor(String(input.label || f.label), input.id),
133
+ label: String(input.label || f.label),
134
+ ...common,
135
+ options: unique.map((c) => String(c.text)),
136
+ values: unique.map((c) => String(c.value)),
137
+ };
138
+ choices = choices.flatMap((c) => c.choices ?? []);
139
+ return field;
140
+ });
141
+ };
142
+
143
+ /** A Gravity Forms record → the fields of `presets.forms`. Composite fields (name, address) become one field per input. */
144
+ export const gravityForm = (src: SourceRecord, ctx: MapContext): Record<string, unknown> => {
145
+ const used = new Set<string>();
146
+ const nameFor = (label: string, id: unknown) => {
147
+ let name = slugify(label) || `field-${id}`;
148
+ if (used.has(name)) name = `${name}-${slugify(String(id))}`;
149
+ used.add(name);
150
+ return name;
151
+ };
152
+ const number = (v: unknown) => (v === "" || v == null ? undefined : Number(v));
153
+ const fields = (src.fields ?? []).flatMap((f: any): Record<string, unknown>[] => {
154
+ if (SKIPPED_FIELDS.has(f.type)) return [];
155
+ const type = FORM_TYPES[f.type];
156
+ const common = { description: f.description ?? "", required: !!f.isRequired };
157
+ if (f.type === "chainedselect") return chainedSelects(f, common, nameFor);
158
+ if (!type && f.inputs?.length)
159
+ return f.inputs.map((i: any) => ({
160
+ type: "text",
161
+ name: nameFor(`${f.label} ${i.label}`, i.id),
162
+ label: `${f.label} – ${i.label}`,
163
+ ...common,
164
+ }));
165
+ if (!type) ctx.warn(`form ${src.id}: Gravity Forms field type "${f.type}" imported as text`);
166
+ const item: Record<string, unknown> = { type: type ?? "text", name: nameFor(String(f.label || f.type), f.id) };
167
+ if (type === "html") return [{ ...item, content: ctx.richText(f.content) }];
168
+ item.label = f.label ?? "";
169
+ if (type === "section") return [{ ...item, description: f.description ?? "" }];
170
+ Object.assign(item, common);
171
+ if (f.placeholder) item.placeholder = f.placeholder;
172
+ if (number(f.maxLength)) item.maxLength = number(f.maxLength);
173
+ if (CHOICES.has(type ?? "")) {
174
+ item.options = (f.choices ?? []).map((c: any) => String(c.text));
175
+ item.values = (f.choices ?? []).map((c: any) => String(c.value));
176
+ }
177
+ // Checkbox and consent inputs mirror their choices (GF sub-input ids).
178
+ for (const i of f.inputs ?? []) touch(i.id, i.label);
179
+ if (type === "consent") item.checkboxLabel = f.checkboxLabel || f.choices?.[0]?.text || "";
180
+ return [item];
181
+ });
182
+ const confirmation = src.confirmation ?? {};
183
+ const redirect =
184
+ confirmation.type === "redirect"
185
+ ? confirmation.url
186
+ : confirmation.type === "page"
187
+ ? ctx.refLink(confirmation.pageId)?.url
188
+ : "";
189
+ return {
190
+ title: src.title,
191
+ slug: slugify(String(src.title)),
192
+ description: src.description ?? "",
193
+ submitLabel: src.button ?? "",
194
+ successMessage: confirmation.type === "message" ? ctx.text(confirmation.message) : "",
195
+ submitRedirect: redirect ?? "",
196
+ notificationEmail: src.notifyEmail ?? "",
197
+ fields,
198
+ };
199
+ };
package/src/terms.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** Splits a term name that bundles several terms ("Business|Press releases", "News; Events") into its parts. */
2
+ export const termParts = (name: unknown): string[] =>
3
+ String(name ?? "")
4
+ .split(/\s*[|;]\s*/)
5
+ .map((part) => part.trim())
6
+ .filter(Boolean);