@typeroll/mcp-server 0.45.168 → 0.45.170

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 (42) hide show
  1. package/AGENTS.md +2 -1
  2. package/dist/bundled-content.js +26 -13
  3. package/dist/server.js +4 -0
  4. package/dist/tools/apps.js +33 -0
  5. package/dist/tools/fonts.js +1 -1
  6. package/dist/tools/forms.js +4 -3
  7. package/dist/tools/media.js +2 -2
  8. package/dist/tools/migration.js +1 -1
  9. package/dist/tools/pages.js +4 -0
  10. package/dist/tools/preview.js +4 -0
  11. package/dist/tools/settings.js +1 -1
  12. package/dist/tools/styles.js +1 -1
  13. package/dist/version.d.ts +1 -1
  14. package/dist/version.js +1 -1
  15. package/dist/workspace.d.ts +1 -1
  16. package/dist/workspace.js +17 -8
  17. package/package.json +1 -1
  18. package/skills/tr-brand.md +1 -1
  19. package/skills/tr-migrate-astro.md +4 -13
  20. package/skills/tr-migrate-multisite.md +10 -31
  21. package/skills/tr-migrate-wp.md +73 -384
  22. package/skills/tr-responsive.md +14 -0
  23. package/workspace-templates/scripts/README.md +18 -0
  24. package/workspace-templates/scripts/typeroll/browser.cjs +6 -1
  25. package/workspace-templates/scripts/typeroll/call.py +5 -2
  26. package/workspace-templates/scripts/typeroll/css_report.py +45 -0
  27. package/workspace-templates/scripts/typeroll/inventory.py +264 -0
  28. package/workspace-templates/scripts/typeroll/media_fit.py +112 -0
  29. package/workspace-templates/scripts/typeroll/migration.py +254 -0
  30. package/workspace-templates/scripts/typeroll/page_part.cjs +34 -0
  31. package/workspace-templates/scripts/typeroll/page_source.py +148 -0
  32. package/workspace-templates/scripts/typeroll/pages.py +156 -0
  33. package/workspace-templates/scripts/typeroll/read_pages.cjs +169 -0
  34. package/workspace-templates/scripts/typeroll/shoot_hosted.cjs +13 -6
  35. package/workspace-templates/scripts/typeroll/trlib.py +45 -7
  36. package/workspace-templates/scripts/typeroll/verify_migration.cjs +47 -0
  37. package/workspace-templates/scripts/typeroll/verify_migration.py +274 -0
  38. package/workspace-templates/scripts/typeroll/write_pages.py +542 -0
  39. package/workspace-templates/skills/typeroll-migrate-sources.md +36 -0
  40. package/workspace-templates/skills/typeroll-migrate.md +109 -0
  41. package/workspace-templates/workflows/design.md +1 -1
  42. package/workspace-templates/workflows/migration.md +12 -5
@@ -0,0 +1,542 @@
1
+ """Steps 3 and 4: write the pages the agent made, as drafts.
2
+
3
+ write_pages.py prototype PATH [PATH ...] [--apply] the chosen pages
4
+ write_pages.py all [--apply] every page file; needs the approved prototype
5
+
6
+ The agent writes one file per page or record in sources/private/migration/new/:
7
+
8
+ {"path": "/about/", "title": "About", "content_type": "page", "template": null,
9
+ "fields": {}, "blocks": [{"type": "core/prose", "data": {"html": {"copy": "#about p"}}}],
10
+ "seo_title": "", "seo_description": "", "og_image": "", "date": ""}
11
+
12
+ A record without a page of its own has "path": null and an "id". Anywhere in it:
13
+ {"copy": "SELECTOR"} exact text of the saved page, as clean HTML
14
+ {"copy": "SELECTOR", "as": "text"} or "image", "alt" or "link"
15
+ {"ref": "/team/kim/"} the record that is at (or has) this path or id
16
+ Files on the old site are copied. Nothing else is done to what the agent wrote:
17
+ a part that is not running text is refused, an unknown field is refused. Without
18
+ --apply nothing is written. Run it again after an interruption. A page that
19
+ somebody changed in the CMS is left alone and reported. It never publishes.
20
+ """
21
+ import argparse
22
+ import json
23
+ import re
24
+ import unicodedata
25
+ import urllib.parse
26
+ import media_fit
27
+ import migration
28
+ import page_source
29
+ import pages as worksheet
30
+ import trlib
31
+
32
+ PATH = re.compile(r'^/(?:[a-z0-9_-]+(?:/[a-z0-9_-]+)*)?$')
33
+ MEDIA = re.compile(r'\.(?:jpe?g|png|gif|webp|avif|svg|pdf|mp4|webm|mp3|zip|docx?|xlsx?|pptx?)$', re.I)
34
+ KEYS = {'path', 'id', 'title', 'content_type', 'template', 'fields', 'blocks', 'seo_title', 'seo_description', 'og_image', 'date', 'noindex', 'excerpt', 'slug'}
35
+
36
+
37
+ class Journal:
38
+ """What was written, saved after every batch."""
39
+
40
+ def __init__(self):
41
+ self.file = migration.private() / 'journal.json'
42
+ data = migration.read_json(self.file, {})
43
+ config = trlib.workspace()
44
+ self.target = {key: config[key] for key in ('portal', 'organization_id', 'site_id', 'version')}
45
+ if data.get('target') not in (None, self.target):
46
+ raise migration.StepError('sources/private/migration/journal.json belongs to another site or version; move it away first')
47
+ self.pages, self.media = data.get('pages', {}), data.get('media', {})
48
+
49
+ def save(self):
50
+ migration.write_json(self.file, {'target': self.target, 'pages': self.pages, 'media': self.media})
51
+
52
+
53
+ def stored(page):
54
+ """The parts of a stored page this import is responsible for."""
55
+ return migration.digest({key: page.get(key) for key in ('title', 'slug', 'path', 'content_type', 'fields', 'blocks', 'excerpt', 'seo_title', 'seo_description')})
56
+
57
+
58
+ def clean_path(path):
59
+ return path.rstrip('/') or '/'
60
+
61
+
62
+ def folder():
63
+ return migration.private() / 'new'
64
+
65
+
66
+ def files():
67
+ """{path or id: page file}. A broken file stops everything: it would be missing without a word."""
68
+ found = {}
69
+ for name in sorted(folder().rglob('*.json')) if folder().is_dir() else []:
70
+ page = migration.read_json(name)
71
+ wrong = [key for key in ('title', 'content_type') if not isinstance(page.get(key), str) or not page[key].strip()] if isinstance(page, dict) else ['not an object']
72
+ wrong += sorted(set(page) - KEYS) if isinstance(page, dict) else []
73
+ if not wrong and not (page.get('path') or page.get('id')):
74
+ wrong = ['path or id']
75
+ if wrong:
76
+ raise migration.StepError(f'{name.name}: check {", ".join(wrong)}')
77
+ key = page.get('path') or page['id']
78
+ if key in found:
79
+ raise migration.StepError(f'Two page files for {key}')
80
+ found[key] = page
81
+ return found
82
+
83
+
84
+ def file_of(path):
85
+ return files().get(path)
86
+
87
+
88
+ def safe_path(path):
89
+ """An address Typeroll takes: lower case, letters without accents, dashes. The old one gets a redirect."""
90
+ text = unicodedata.normalize('NFKD', urllib.parse.unquote(path)).encode('ascii', 'ignore').decode().lower()
91
+ parts = [re.sub(r'[^a-z0-9_-]+', '-', part).strip('-') for part in text.split('/')]
92
+ return clean_path('/' + '/'.join(part for part in parts if part))
93
+
94
+
95
+ def page_id(page):
96
+ if page.get('id'):
97
+ return page['id']
98
+ path = clean_path(page['path'])
99
+ if path == '/':
100
+ return 'home'
101
+ name = re.sub(r'[^a-z0-9]+', '-', path.lower()).strip('-')
102
+ return f"{page['content_type']}-{name}".replace('_', '-')[:100]
103
+
104
+
105
+ def walk(value, change):
106
+ """The same value with every marked part replaced."""
107
+ if isinstance(value, dict):
108
+ if 'copy' in value and set(value) <= {'copy', 'as'} or set(value) == {'ref'}:
109
+ return change(value)
110
+ return {key: walk(item, change) for key, item in value.items()}
111
+ if isinstance(value, list):
112
+ return [walk(item, change) for item in value]
113
+ return change(value) if isinstance(value, str) else value
114
+
115
+
116
+ class Builder:
117
+ def __init__(self, model, inventory, journal, chosen):
118
+ self.model, self.journal, self.source, self.chosen = model, journal, inventory['source'], chosen
119
+ self.urls = {clean_path(row['path']): row['url'] for row in inventory['urls'] if row.get('read')}
120
+ self.entries = {entry['content_type']: entry for entry in model['types']}
121
+ everything = files()
122
+ self.ids = {key: page_id(page) for key, page in everything.items()} | {page_id(page): page_id(page) for page in everything.values()}
123
+ self.ids |= {clean_path(key): value for key, value in self.ids.items() if key.startswith('/')}
124
+ self.wanted, self.renamed, self.media_why = {}, {}, {}
125
+ wanted = {}
126
+ for page in chosen:
127
+ def collect(value, url=self.urls.get(clean_path(page['path'])) if page.get('path') else None):
128
+ if isinstance(value, dict) and 'copy' in value and url:
129
+ wanted.setdefault(url, set()).add(value['copy'])
130
+ return value
131
+ walk([page.get('fields'), page.get('blocks'), page.get('og_image')], collect)
132
+ self.parts = page_source.parts(wanted)
133
+
134
+ def old_host(self, url):
135
+ strip = lambda value: (urllib.parse.urlsplit(value).hostname or '').lower().removeprefix('www.')
136
+ return strip(url) == strip(self.source)
137
+
138
+ def file(self, url):
139
+ # A name like photo-300x200.jpg is a resized copy; the original has no size.
140
+ original = re.sub(r'-\d{2,4}x\d{2,4}(?=\.\w{3,4}$)', '', url.split('?')[0])
141
+ self.wanted.setdefault(original, url)
142
+ return self.journal.media.get(original, {}).get('url') or original
143
+
144
+ def link(self, href):
145
+ """Links to the old site become paths, so they work on the new one. Its files are copied."""
146
+ url = urllib.parse.urljoin(self.source + '/', href)
147
+ parts = urllib.parse.urlsplit(url)
148
+ if parts.scheme not in ('http', 'https') or not self.old_host(url):
149
+ return href
150
+ if MEDIA.search(parts.path):
151
+ return self.file(url)
152
+ path = parts.path or '/'
153
+ if not PATH.fullmatch(clean_path(path)):
154
+ path = safe_path(path) + ('/' if path.endswith('/') and safe_path(path) != '/' else '')
155
+ return urllib.parse.urlunsplit(('', '', path, parts.query, parts.fragment))
156
+
157
+ def page(self, page):
158
+ """(page as create_page takes it, problems)"""
159
+ problems, kind = [], page['content_type']
160
+ path = clean_path(page['path']) if page.get('path') else None
161
+ url = self.urls.get(path) if path else None
162
+ saved = self.parts.get(url, {})
163
+
164
+ def change(value):
165
+ if isinstance(value, str):
166
+ return self.link(value) if re.match(r'https?://\S+$', value) else value
167
+ if 'ref' in value:
168
+ target = self.ids.get(value['ref']) or self.ids.get(clean_path(value['ref']))
169
+ if not target:
170
+ problems.append(f"{value['ref']} is no page file")
171
+ return target
172
+ found = saved.get(value['copy']) or {'error': 'cannot be read: the page has no saved copy'}
173
+ if found.get('error'):
174
+ problems.append(f"copy {value['copy']} {found['error']}")
175
+ return ''
176
+ how = value.get('as', 'html')
177
+ if how == 'html':
178
+ text, other = page_source.clean(found['html'], self.link)
179
+ if other:
180
+ problems.append(f"copy {value['copy']} holds {', '.join(other)}: choose a smaller part, and make the rest as blocks")
181
+ return text
182
+ if how not in ('text', 'image', 'alt', 'link'):
183
+ problems.append(f'unknown way to copy: {how}')
184
+ return ''
185
+ # An empty alt marks a decorative picture; it is copied as it is.
186
+ if not found[how] and how != 'alt':
187
+ problems.append(f"copy {value['copy']} has no {how}")
188
+ return ''
189
+ return found[how] if how in ('text', 'alt') else self.link(urllib.parse.urljoin(self.source + '/', found[how]))
190
+
191
+ # Text the agent wrote can hold addresses too.
192
+ in_html = lambda value: re.sub(r'((?:href|src)=")([^"]+)"', lambda match: f'{match[1]}{self.link(match[2])}"', value) if isinstance(value, str) and '<' in value else value
193
+ entry = self.entries.get(kind)
194
+ if entry is None and kind != 'page':
195
+ problems.append(f'{kind} is not a content type of the model')
196
+ entry = {}
197
+ entry = entry or {}
198
+ allowed = {field['name'] for field in entry.get('fields') or []}
199
+ for name in sorted(set(page.get('fields') or {}) - allowed):
200
+ problems.append(f'{kind} has no field {name}')
201
+ result = {'id': page_id(page), 'title': page['title'], 'content_type': kind, 'content_mode': 'blocks',
202
+ 'blocks': walk(walk(page.get('blocks') or [], change), in_html), 'fields': walk(walk(page.get('fields') or {}, change), in_html),
203
+ 'status': 'draft', 'write_mode': 'import'}
204
+ if path is None or not entry.get('own_pages', True):
205
+ result.update(slug=page.get('slug') or result['id'], own_page=False)
206
+ else:
207
+ if not PATH.fullmatch(path):
208
+ # Mechanical, like a browser would: the old address redirects to this one.
209
+ self.renamed[page['path']] = safe_path(path) + ('/' if page['path'].endswith('/') else '')
210
+ path = safe_path(path)
211
+ if path == '/' and page['path'] not in ('/', ''):
212
+ problems.append(f"the address {page['path']} has no letters Typeroll can use; give the page file another path")
213
+ result['slug'] = '' if path == '/' else path.rsplit('/', 1)[1]
214
+ expected = clean_path((entry.get('route_template') or '/{slug}').replace('{slug}', result['slug']))
215
+ if path != expected:
216
+ result['path'] = path
217
+ template = page.get('template') or (self.model['pages'].get(page.get('path')) or {}).get('template') or entry.get('template')
218
+ if template:
219
+ result['template'] = template
220
+ for key in ('seo_title', 'seo_description', 'excerpt'):
221
+ if page.get(key):
222
+ result[key] = page[key]
223
+ if page.get('seo_title'):
224
+ result['append_seo_suffix'] = False
225
+ if page.get('og_image'):
226
+ result['og_image'] = walk(page['og_image'], change)
227
+ answer = (self.model['pages'].get(page.get('path')) or {}).get('type')
228
+ if path and url and answer != kind:
229
+ problems.append(f'the note says {answer}, the page file says {kind}')
230
+ return result, problems
231
+
232
+
233
+ def field_names(found, cache):
234
+ """The fields a block has right now, read from the CMS."""
235
+ if found not in cache:
236
+ try:
237
+ definition = trlib.call('read_block_type', {'type_id': found})
238
+ except RuntimeError as error:
239
+ raise migration.StepError(f'The block {found} could not be read: {error}') from None
240
+ definition = definition.get('block_type', definition)
241
+ cache[found] = {field['name'] for field in definition.get('schema') or []}
242
+ return cache[found]
243
+
244
+
245
+ def unknown_fields(blocks, cache):
246
+ problems = []
247
+ for block in trlib.walk(blocks):
248
+ extra = set(block.get('data') or {}) - field_names(block['type'], cache)
249
+ if extra:
250
+ problems.append(f"{block['type']} has no field {', '.join(sorted(extra))}")
251
+ return problems
252
+
253
+
254
+ def own_redirects(inventory, model):
255
+ """The old site's own redirects, aimed at where their target lives now."""
256
+ source = urllib.parse.urlsplit(inventory['source']).hostname or ''
257
+ found = []
258
+ for row in inventory['urls']:
259
+ target = row.get('redirects_to')
260
+ if row.get('status') not in (301, 302, 307, 308) or not target or not row.get('path'):
261
+ continue
262
+ parts = urllib.parse.urlsplit(target)
263
+ if (parts.hostname or source).removeprefix('www.') != source.removeprefix('www.'):
264
+ found.append({'from': row['path'], 'to': target})
265
+ continue
266
+ # The target as the new site spells it, so the visitor gets one hop, not two.
267
+ key = next((key for key in (parts.path, parts.path.rstrip('/') + '/') if key in model['pages']), None)
268
+ to = (model['pages'][key].get('to') if key else None) or key or parts.path or '/'
269
+ if clean_path(to) != clean_path(row['path']):
270
+ found.append({'from': row['path'], 'to': to})
271
+ return found
272
+
273
+
274
+ def empty_fields(model, pages):
275
+ """Fields of the model that no page file fills: content that was missed, or a field nobody needs."""
276
+ filled = {}
277
+ for page in pages:
278
+ filled.setdefault(page['content_type'], set()).update(name for name, value in (page.get('fields') or {}).items() if value not in (None, '', [], {}))
279
+ return {entry['content_type']: names for entry in model['types'] if entry['content_type'] in filled
280
+ for names in [[field['name'] for field in entry.get('fields') or [] if field['name'] not in filled[entry['content_type']]]] if names}
281
+
282
+
283
+ def make_redirects(rows, apply):
284
+ """Check every redirect, and with apply create them. Typeroll serves both slash forms itself.
285
+ Returns the problem per old address; nothing is written while one rule has a problem."""
286
+ rules = [{'from_path': row['from'], 'to_path': row['to'], 'status_code': 301} for row in rows if row['to']]
287
+ batches = [rules[start:start + 1000] for start in range(0, len(rules), 1000)]
288
+ problems = {}
289
+ for batch in batches:
290
+ answer = trlib.call('upsert_redirects', {'redirects': batch, 'dry_run': True})
291
+ problems.update({row['from_path']: row.get('error') or 'refused' for row in answer.get('results') or [] if not row.get('ok')})
292
+ if apply and not problems:
293
+ for batch in batches:
294
+ trlib.call('upsert_redirects', {'redirects': batch})
295
+ return problems
296
+
297
+
298
+ def ensure_types(model, apply):
299
+ """Create the content types of the model that do not exist. Never change one."""
300
+ answer = trlib.call('list_content_types')
301
+ rows = answer if isinstance(answer, list) else answer.get('content_types') or []
302
+ existing = {row['name']: row for row in rows}
303
+ answer = trlib.call('list_page_templates')
304
+ rows = answer if isinstance(answer, list) else answer.get('templates') or answer.get('page_templates') or []
305
+ templates = {row['id'] for row in rows}
306
+ problems, made = [], []
307
+ wanted = {page['template'] for page in model['pages'].values() if page['template']}
308
+ problems += [f'The template {name} does not exist. Create it, or change the note of its pages' for name in sorted(wanted - templates)]
309
+ # Every approved type is made, also one that has no pages yet: its list and its first record need it.
310
+ for entry in model['types']:
311
+ name = entry['content_type']
312
+ # Every key the agent set goes along, list fields with their own fields too; Typeroll checks them.
313
+ fields = [{key: value for key, value in field.items() if key not in ('why', 'note') and value not in (None, '', [])} for field in entry.get('fields') or []]
314
+ # A migration writes as an import; fields refuse imports unless they name it.
315
+ fields = [{**field, 'writable_by': field.get('writable_by') or ['portal', 'agent', 'import']} for field in fields]
316
+ if entry.get('template') and entry['template'] not in templates:
317
+ problems.append(f"The template {entry['template']} of {name} does not exist. Create it, or set template to null in the model")
318
+ if name in existing:
319
+ have = {field['name']: field['type'] for field in existing[name].get('fields') or []}
320
+ wrong = [field['name'] for field in fields if have.get(field['name']) != field['type']]
321
+ if wrong:
322
+ problems.append(f"{name} exists without these fields, or with another type: {', '.join(wrong)}")
323
+ else:
324
+ made.append(name)
325
+ if apply and not problems:
326
+ trlib.call('create_content_type', {'name': name, 'label_singular': entry['label_singular'], 'label_plural': entry['label_plural'],
327
+ 'fields': fields, 'route_template': entry.get('route_template') or '',
328
+ **({'template': entry['template']} if entry.get('template') else {})})
329
+ return problems, made
330
+
331
+
332
+ def copy_media(builder, urls):
333
+ """Copy files in batches. One that is still being copied counts as not ready."""
334
+ failed, pending = [], []
335
+ journal = builder.journal
336
+
337
+ def by_hand(key, candidates, last=True):
338
+ """The library refused the address. Copy the file from here: a shorter name, and smaller when it is too large."""
339
+ for candidate in candidates:
340
+ try:
341
+ copied = media_fit.copy(candidate)
342
+ journal.media[key] = {'media_id': copied['media_id'], 'url': copied['url']}
343
+ return True
344
+ except Exception as error: # noqa: BLE001 - the reason goes to the agent
345
+ builder.media_why[candidate] = ' '.join(str(error).split())[:300]
346
+ if last:
347
+ failed.append(candidates[-1])
348
+ return False
349
+ urls = [url for url in sorted(urls) if journal.media.get(url, {}).get('url') is None]
350
+ for start in range(0, len(urls), 50):
351
+ batch = urls[start:start + 50]
352
+ waiting = [url for url in batch if journal.media.get(url, {}).get('media_id')]
353
+ for url in waiting:
354
+ answer = trlib.call('read_media', {'media_id': journal.media[url]['media_id']})
355
+ state, address = (answer.get('import') or {}).get('state'), (answer.get('media') or {}).get('cdn_url')
356
+ if state == 'complete' and address:
357
+ journal.media[url]['url'] = address
358
+ elif state == 'failed':
359
+ del journal.media[url]
360
+ by_hand(url, [url])
361
+ else:
362
+ pending.append(url)
363
+ fresh = [url for url in batch if url not in waiting]
364
+ if fresh:
365
+ answer = trlib.call('upload_media_batch_from_urls', {'items': [{'source_url': url} for url in fresh]})
366
+ for url, row in zip(fresh, answer['results']):
367
+ if row.get('ok') and row.get('cdn_url'):
368
+ journal.media[url] = {'media_id': row['media_id'], 'url': row['cdn_url']}
369
+ elif row.get('ok') and row.get('media_id'):
370
+ journal.media[url] = {'media_id': row['media_id'], 'url': None}
371
+ pending.append(url)
372
+ else:
373
+ # The original made to fit is better than the smaller copy the page showed.
374
+ shown = builder.wanted.get(url)
375
+ if by_hand(url, [url], last=shown in (None, url)):
376
+ continue
377
+ again = trlib.call('upload_media_batch_from_urls', {'items': [{'source_url': shown}]})['results'][0]
378
+ if again.get('ok') and again.get('cdn_url'):
379
+ journal.media[url] = {'media_id': again['media_id'], 'url': again['cdn_url']}
380
+ else:
381
+ by_hand(url, [shown])
382
+ journal.save()
383
+ return failed, pending
384
+
385
+
386
+ def late(record):
387
+ """What can be set only on a page that exists."""
388
+ return {**({'date_published': record['date']} if record.get('date') else {}), **({'noindex': True} if record.get('noindex') else {})}
389
+
390
+
391
+ def write(rows, journal, apply):
392
+ """Create or update. Returns ids per outcome."""
393
+ outcome = {'created': [], 'updated': [], 'unchanged': [], 'changed_in_cms': [], 'taken': [], 'failed': []}
394
+ why = {}
395
+ current = {}
396
+ ids = [page['id'] for page, _ in rows]
397
+ for start in range(0, len(ids), 200):
398
+ current.update(trlib.call('batch_read_pages', {'page_ids': ids[start:start + 200]})['pages_by_id'])
399
+ updates, dates = [], []
400
+ for page, record in rows:
401
+ wanted, have, known = migration.digest(page), current.get(page['id']), journal.pages.get(page['id'])
402
+ if have and not known:
403
+ # Same id, not from this import: never replaced.
404
+ outcome['taken'].append(page['id'])
405
+ elif have and known.get('stored') not in (None, stored(have)):
406
+ outcome['changed_in_cms'].append(page['id'])
407
+ elif have and known.get('wanted') == wanted:
408
+ outcome['unchanged'].append(page['id'])
409
+ if late(record) and not known.get('dated'):
410
+ dates.append((page['id'], late(record)))
411
+ elif have:
412
+ updates.append((page, record, wanted))
413
+ else:
414
+ outcome['created'].append(page['id'])
415
+ if apply:
416
+ # Written down first: after a lost answer the next run still knows the page as ours.
417
+ journal.pages[page['id']] = {'wanted': wanted, 'stored': None}
418
+ journal.save()
419
+ try:
420
+ trlib.call('create_page', page)
421
+ except RuntimeError as error:
422
+ outcome['created'].pop()
423
+ outcome['failed'].append(page['id'])
424
+ why[page['id']] = str(error)
425
+ continue
426
+ dates.append((page['id'], late(record)))
427
+ for start in range(0, len(updates), 200):
428
+ batch = updates[start:start + 200]
429
+ outcome['updated'] += [page['id'] for page, _, _ in batch]
430
+ if apply:
431
+ skip = ('id', 'status', 'content_mode', 'write_mode', 'content_type')
432
+ answer = trlib.call('batch_update_pages', {'updates': [
433
+ {'page_id': page['id'], 'patch': {key: value for key, value in page.items() if key not in skip}, 'save': True, 'write_mode': 'import'} for page, _, _ in batch]})
434
+ good = {row['page_id'] for row in answer['results'] if row.get('ok')}
435
+ errors = {row['page_id']: row.get('error') for row in answer['results'] if not row.get('ok')}
436
+ for page, _, wanted in batch:
437
+ if page['id'] in good:
438
+ journal.pages[page['id']].update(wanted=wanted, stored=None)
439
+ else:
440
+ outcome['updated'].remove(page['id'])
441
+ outcome['failed'].append(page['id'])
442
+ why[page['id']] = str(errors.get(page['id']) or 'no answer for this page')
443
+ journal.save()
444
+ if apply:
445
+ dates = [(name, date) for name, date in dates if date]
446
+ for start in range(0, len(dates), 200):
447
+ answer = trlib.call('batch_update_pages', {'updates': [{'page_id': name, 'patch': date, 'save': True} for name, date in dates[start:start + 200]]})
448
+ for row in answer['results']:
449
+ if row.get('ok'):
450
+ journal.pages[row['page_id']]['dated'] = True
451
+ # Read back what the CMS stored; that is what a later run compares with.
452
+ fresh = [name for name, row in journal.pages.items() if row.get('stored') is None]
453
+ for start in range(0, len(fresh), 200):
454
+ found = trlib.call('batch_read_pages', {'page_ids': fresh[start:start + 200]})['pages_by_id']
455
+ for name, page in found.items():
456
+ journal.pages[name]['stored'] = stored(page)
457
+ journal.save()
458
+ outcome['why'] = why
459
+ return outcome
460
+
461
+
462
+ def run(step, chosen, apply):
463
+ migration.require(step)
464
+ model, inventory = migration.result('model'), migration.result('inventory')
465
+ if trlib.workspace()['version'] != 'main':
466
+ # Files belong to the whole site, and trlib does not write them from another version.
467
+ raise migration.StepError('Write to version main of a site that is not live yet; everything is created as drafts')
468
+ if not trlib.call('get_import_readiness').get('ready', True):
469
+ raise migration.StepError('The site is not ready for import; see get_import_readiness')
470
+ everything = files()
471
+ unknown = [path for path in chosen or [] if path not in everything]
472
+ if unknown:
473
+ raise migration.StepError('No page file for ' + ', '.join(unknown))
474
+ selected = [everything[path] for path in chosen] if chosen else list(everything.values())
475
+ if not selected:
476
+ raise migration.StepError('There are no page files in sources/private/migration/new/ yet')
477
+ missing = worksheet.left(model)['without_page_file'] if step == 'import' else []
478
+ if step == 'prototype':
479
+ # One page of every kind, so that the owner sees every layout before the rest is made.
480
+ kinds = {page['type'] for page in model['pages'].values()} - {None, 'skip'}
481
+ missing = sorted(kinds - {page['content_type'] for page in selected})
482
+ journal = Journal()
483
+ problems, made = ensure_types(model, apply)
484
+ if problems:
485
+ raise migration.StepError('\n'.join(problems))
486
+ builder = Builder(model, inventory, journal, selected)
487
+ # First pass finds the files; the second builds the pages with the new addresses.
488
+ for page in selected:
489
+ builder.page(page)
490
+ failed_media, pending = copy_media(builder, builder.wanted) if apply else ([], [])
491
+ cache, rows, refused = {}, [], {}
492
+ for page in selected:
493
+ built, found = builder.page(page)
494
+ found += unknown_fields(built['blocks'], cache)
495
+ if found:
496
+ refused[page.get('path') or page['id']] = found
497
+ else:
498
+ rows.append((built, page))
499
+ outcome = write(rows, journal, apply)
500
+ # A page that is gone answers 404 on the new site, so it gets no redirect.
501
+ skipped = [{'from': path, 'to': page['to']} for path, page in sorted(model['pages'].items()) if page['type'] == 'skip' and page.get('to') not in (None, '', 'gone')]
502
+ without = {entry['content_type'] for entry in model['types'] if not entry.get('own_pages', True)}
503
+ moved = [{'from': page['path'], 'to': (model['pages'].get(page['path']) or {}).get('to') or ''}
504
+ for page in selected if page.get('path') and page['content_type'] in without]
505
+ redirects = [*skipped, *moved, *({'from': old, 'to': new} for old, new in sorted(builder.renamed.items()))]
506
+ redirects += [row for row in own_redirects(inventory, model) if row['from'] not in {known['from'] for known in redirects}]
507
+ ok = apply and not (refused or missing or failed_media or pending or outcome['failed'] or outcome['taken'])
508
+ # The import makes every redirect itself; the prototype only checks them, so a problem shows early.
509
+ redirect_problems = make_redirects(redirects, ok and step == 'import') if redirects and apply else {}
510
+ ok = ok and not (step == 'import' and redirect_problems)
511
+ data = {'counts': {key: len(value) for key, value in outcome.items() if key != 'why'}, 'refused': refused, 'missing': missing, 'failed_media': failed_media, 'media_why': {url: builder.media_why[url] for url in failed_media if url in builder.media_why}, 'pending_media': pending,
512
+ 'media': len(builder.wanted), 'pages': [built['id'] for built, _ in rows], 'content_types_created': made, 'redirects': redirects, 'redirect_problems': redirect_problems,
513
+ **({'empty_fields': empty_fields(model, everything.values())} if step == 'import' else {}),
514
+ **{key: outcome[key] for key in ('changed_in_cms', 'taken', 'failed', 'why')}}
515
+ if apply:
516
+ migration.save(step, ok, **data)
517
+ if step == 'import':
518
+ trlib.call('add_migration_urls', {'source_origin': inventory['source'], 'urls': [{'url': row['url'], 'source': 'crawl'} for row in inventory['urls'] if row['status'] in (200, 301, 302, 307, 308)][:2000]})
519
+ return ok, data
520
+
521
+
522
+ def main():
523
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
524
+ parser.add_argument('step', choices=('prototype', 'all'))
525
+ parser.add_argument('paths', nargs='*')
526
+ parser.add_argument('--apply', action='store_true')
527
+ args = parser.parse_args()
528
+ if (args.step == 'prototype') != bool(args.paths):
529
+ raise migration.StepError('Name the prototype pages; "all" takes none')
530
+ ok, data = run('prototype' if args.step == 'prototype' else 'import', args.paths, args.apply)
531
+ print(json.dumps(data, ensure_ascii=False, indent=2))
532
+ if not args.apply:
533
+ print('Nothing was written. Add --apply to write drafts.')
534
+ return 0
535
+ return 0 if ok else 1
536
+
537
+
538
+ if __name__ == '__main__':
539
+ try:
540
+ raise SystemExit(main())
541
+ except migration.StepError as error:
542
+ raise SystemExit(str(error))
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: typeroll-migrate-sources
3
+ description: Extra ways to get at the content of an old website when moving it to Typeroll, such as a public API, an export or a source repository. Use together with typeroll-migrate.
4
+ ---
5
+
6
+ # Other ways to the content
7
+
8
+ Follow `typeroll-migrate`. It works from what visitors see, whatever the old site
9
+ is built with. Nothing here depends on a page builder, and no layout is read from
10
+ one. Use these only where the page does not show enough:
11
+
12
+ | What you need | Where it is |
13
+ | --- | --- |
14
+ | Exact field values | a public list such as WordPress `/wp-json`; `inventory.py` saves it in `sources/private/migration/records/` |
15
+ | Fields as structured data | JSON-LD in the page; read it yourself |
16
+ | Drafts, hidden records, exact menus | an export the owner approves |
17
+ | Old addresses and redirects | the owner's export; a crawl finds only some of them |
18
+ | Text in a source repository | the project's own parser (`tr-migrate-astro` for Astro); compare with the published page |
19
+
20
+ - Do not ask for a plugin when the pages are enough. If the old host refuses
21
+ (401, 403 or 429), ask the owner for access. Do not try to get around it.
22
+ - Platform rules: `tr-migrate-wp`, `tr-migrate-astro`, `tr-import-url` (`read_skill`).
23
+ - Keep exports and records in the ignored `sources/private/`. They may hold personal data.
24
+
25
+ ## Watch out for
26
+
27
+ - The address in Google is the whole path, such as `/2024/01/foo-bar/`, not the slug.
28
+ - `-300x200` in a file name is a resized copy. The original is copied first.
29
+ - A field with only a number is often a media id. Read the image from the page instead.
30
+ - Categories and tags are content types with one page per term. Link to them with
31
+ `page_ref_list` fields; never copy their names into every article. A public list
32
+ gives their old id numbers, so read the links or names on the page instead.
33
+ - Copy no JavaScript and no cookie plugin. Add analytics by ID in the Integrations
34
+ app with the cookie banner on. Leave out the old structured data; Typeroll writes its own.
35
+ - Forms are rebuilt. Agree on the recipient with the owner and test without
36
+ sending anything to outsiders.