Repository navigation
Expand file tree
/
Copy pathmigrate-wordpress.mjs
More file actions
174 lines (162 loc) · 6.34 KB
/
Copy pathmigrate-wordpress.mjs
File metadata and controls
174 lines (162 loc) · 6.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/**
* Data migration: WordPress (WXR export) → TanStack CMS.
*
* Copy this file (with html-to-markdown.mjs and parse-wxr.mjs) into the target
* app's scripts/, then run it against a WordPress WXR export file (Tools →
* Export in wp-admin produces one; no running WordPress needed):
*
* node scripts/migrate-wordpress.mjs ../wordpress-before/export.wxr.xml
* node scripts/migrate-wordpress.mjs ../wordpress-before/export.wxr.xml --export cms-export.json
*
* It parses the WXR, resolves featured images (via `_thumbnail_id` → attachment
* URL), converts each post/page body (Gutenberg/HTML → Markdown), maps
* categories/tags to multiselect term slugs, records every published item's
* old permalink as a `redirect` document, and writes the TanStack CMS core
* store shape to OUT (src/seed-data.ts) as a committed seed. With
* `--export <file>` it also writes a CMS export (`tanstack-cms-export` v1) to
* load with `tanstack-cms import <file>`.
*
* This is the data half. The schema half is the hand-written src/cms.definition.ts
* (see SKILL.md's field/collection mapping tables).
*/
import { readFileSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join, resolve } from 'node:path'
import { parseWxr, resolveFeaturedImages } from './parse-wxr.mjs'
import { htmlToMarkdown } from './html-to-markdown.mjs'
const here = dirname(fileURLToPath(import.meta.url))
const args = process.argv.slice(2)
const exportFlag = args.indexOf('--export')
const EXPORT_FILE = exportFlag === -1 ? null : args[exportFlag + 1]
const positional =
exportFlag === -1
? args
: args.filter((_, i) => i !== exportFlag && i !== exportFlag + 1)
const SRC =
positional[0] || join(here, '..', '..', 'wordpress-before', 'export.wxr.xml')
const OUT = join(here, '..', 'src', 'seed-data.ts')
// ===========================================================================
// CONFIG — map WordPress post types to core collections. The core `page`
// collection must be named `page` and own a `blocks` field so the public
// renderer /p/:id + on-page agent work. `status === 'publish'` → published.
// `url(id)` is the item's public URL in the new app; the old permalink
// redirects there (set REDIRECTS to null to skip).
// ===========================================================================
const CONFIG = {
page: {
target: 'page',
url: (id) => `/p/${id}`,
row: (it) => ({
title: it.title,
slug: `/${it.slug}`,
blocks: [{ _type: 'richText', markdown: htmlToMarkdown(it.content) }],
published: it.status === 'publish',
}),
},
post: {
target: 'post',
url: (id) => `/post/${id}`,
row: (it, featuredUrl) => ({
title: it.title,
slug: `/${it.slug}`,
hero: featuredUrl ?? '',
author: it.creator,
excerpt: htmlToMarkdown(it.excerpt),
body: htmlToMarkdown(it.content),
categories: it.categorySlugs,
tags: it.tagSlugs,
published: it.status === 'publish',
}),
},
}
const REDIRECTS = 'redirect' // the redirectsCollection() name in cms.definition.ts
// ===========================================================================
/** Path of a WordPress permalink (`https://site/a-post/` → `/a-post/`), or null. */
function permalinkPath(link) {
try {
const url = new URL(link)
if (url.search) return null // `?p=123` drafts have no pretty permalink
return url.pathname
} catch {
return null
}
}
/** The documents as a CMS export (`tanstack-cms import` input). */
function toCmsExport(documents) {
return {
format: 'tanstack-cms-export',
version: 1,
exportedAt: new Date().toISOString(),
documents: Object.entries(documents).flatMap(([collection, docs]) =>
Object.entries(docs).map(([id, doc]) => ({ collection, id, doc })),
),
}
}
function main() {
const { site, items } = parseWxr(readFileSync(SRC, 'utf8'))
const featured = resolveFeaturedImages(items)
const documents = {}
const terms = { categories: new Map(), tags: new Map() }
for (const spec of Object.values(CONFIG)) documents[spec.target] = {}
if (REDIRECTS) documents[REDIRECTS] = {}
for (const it of items) {
const spec = CONFIG[it.type]
if (!spec) continue // attachment, nav_menu_item, etc. → skipped
// resolve the author login (in <dc:creator>) to its display name
it.creator = site.authors?.[it.creator] ?? it.creator
const id = it.slug || it.id
documents[spec.target][id] = spec.row(it, featured[it.id])
it.categorySlugs.forEach((s, i) =>
terms.categories.set(s, it.categories[i]),
)
it.tagSlugs.forEach((s, i) => terms.tags.set(s, it.tags[i]))
const from = permalinkPath(it.link)
const to = spec.url(id)
if (REDIRECTS && it.status === 'publish' && from && from !== '/') {
const fromPath = from.length > 1 ? from.replace(/\/+$/, '') : from
if (fromPath !== to) {
documents[REDIRECTS][`${it.type}-${id}`] = {
from: fromPath,
to,
permanent: true,
}
}
}
}
for (const [type, spec] of Object.entries(CONFIG)) {
console.log(
` ${type} → ${spec.target}: ${Object.keys(documents[spec.target]).length} docs`,
)
}
if (REDIRECTS) {
console.log(
` permalinks → ${REDIRECTS}: ${Object.keys(documents[REDIRECTS]).length} docs`,
)
}
const withHero = Object.values(documents.post ?? {}).filter(
(d) => d.hero,
).length
console.log(` featured images resolved: ${withHero}`)
for (const [name, map] of Object.entries(terms)) {
const list = [...map].map(([slug, label]) => `${slug} (${label})`)
console.log(` ${name} options: ${list.join(', ')}`)
}
console.log(` (source site: ${site.title})`)
const banner =
'// GENERATED by scripts/migrate-wordpress.mjs (wordpress-to-tanstack-cms skill).\n' +
'// Re-run against the WordPress WXR export, or treat this as the source of truth.\n'
const body =
`import type { SeedStore } from '@tanstack/cms-core'\n\n` +
`export const seedDocuments: SeedStore['documents'] =\n` +
`${JSON.stringify(documents, null, 2)}\n`
writeFileSync(OUT, banner + '\n' + body)
console.log(`Wrote ${OUT}`)
if (EXPORT_FILE) {
const file = resolve(EXPORT_FILE)
writeFileSync(file, JSON.stringify(toCmsExport(documents), null, 2) + '\n')
console.log(
`Wrote ${file} (load it with: tanstack-cms import ${EXPORT_FILE})`,
)
}
}
main()