@christang/keel 5.201.0 → 5.203.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 (42) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +6 -10
  3. package/README.zh-CN.md +6 -10
  4. package/assets/bootstrap/AGENTS.md +1 -1
  5. package/assets/openspec/schemas/keel-spec-driven/schema.yaml +2 -2
  6. package/bin/keel.js +14 -15
  7. package/npm-shrinkwrap.json +2 -2
  8. package/package.json +1 -1
  9. package/plugins/keel/.claude-plugin/plugin.json +1 -1
  10. package/plugins/keel/.codex-plugin/plugin.json +1 -1
  11. package/plugins/keel/commands/chat.md +17 -0
  12. package/plugins/keel/commands/context.md +18 -0
  13. package/plugins/keel/commands/done.md +25 -0
  14. package/plugins/keel/commands/start.md +23 -0
  15. package/plugins/keel/skills/{keel-align-expectations → align-expectations}/SKILL.md +4 -3
  16. package/plugins/keel/skills/{keel-debug-failure → debug-failure}/SKILL.md +3 -2
  17. package/plugins/keel/skills/{keel-handoff → handoff}/SKILL.md +3 -2
  18. package/plugins/keel/skills/{keel-review-checklist → review-checklist}/SKILL.md +3 -2
  19. package/plugins/keel/skills/{keel-review-checklist → review-checklist}/conditional-checks.md +1 -1
  20. package/plugins/keel/skills/{keel-tdd-or-test-first → tdd-or-test-first}/SKILL.md +3 -2
  21. package/plugins/keel/skills/{keel-tdd-or-test-first → tdd-or-test-first}/guidance.md +1 -1
  22. package/scripts/install_to_repo.py +1 -1
  23. package/scripts/validation/baseline.py +5 -7
  24. package/scripts/validation/chat.py +56 -1
  25. package/scripts/validation/common.py +31 -10
  26. package/scripts/validation/contract.py +22 -21
  27. package/scripts/validation/docs.py +17 -16
  28. package/scripts/validation/export.py +37 -430
  29. package/scripts/validation/guard.py +13 -12
  30. package/scripts/validation/hosts.py +110 -9
  31. package/scripts/validation/install.py +14 -13
  32. package/scripts/validation/registry.py +3 -4
  33. package/scripts/validation/selfcheck.py +4 -4
  34. package/src/core/chat/store.js +6 -0
  35. package/src/core/gates.js +1 -1
  36. package/plugins/keel/skills/keel-md-docx/SKILL.md +0 -51
  37. package/plugins/keel/skills/keel-md-docx/scripts/fonts-macos.conf +0 -10
  38. package/plugins/keel/skills/keel-md-docx/scripts/md2word.py +0 -359
  39. package/plugins/keel/skills/keel-md-docx/scripts/package.json +0 -8
  40. package/plugins/keel/skills/keel-md-docx/scripts/requirements.txt +0 -3
  41. package/plugins/keel/skills/keel-md-docx/scripts/runtime.mjs +0 -31
  42. package/src/core/docx.js +0 -211
@@ -1,359 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Convert Markdown and embedded SVG to DOCX, with SVG + PNG fallback images.
3
-
4
- Usage: python md2word.py input.md -o output.docx
5
- Dependencies: python-docx, lxml, Pillow; Node.js with marked and sharp.
6
- """
7
- from __future__ import annotations
8
-
9
- import argparse
10
- import base64
11
- import io
12
- import json
13
- import os
14
- from pathlib import Path
15
- import re
16
- import shutil
17
- import subprocess
18
- import sys
19
- import tempfile
20
- from urllib.parse import unquote, urlsplit
21
-
22
- from docx import Document
23
- from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
24
- from docx.enum.text import WD_ALIGN_PARAGRAPH
25
- from docx.oxml import OxmlElement
26
- from docx.oxml.ns import qn
27
- from docx.opc.constants import RELATIONSHIP_TYPE as RT
28
- from docx.opc.packuri import PackURI
29
- from docx.opc.part import Part
30
- from docx.shared import Cm, Pt, RGBColor
31
- from lxml import etree, html
32
- from PIL import Image
33
-
34
- HERE = Path(__file__).resolve().parent
35
- SVG_NS = 'http://www.w3.org/2000/svg'
36
- ASVG_NS = 'http://schemas.microsoft.com/office/drawing/2016/SVG/main'
37
- SVG_PATTERN = re.compile(r'<svg\b[\s\S]*?</svg\s*>', re.IGNORECASE)
38
-
39
-
40
- def node_call(payload: dict) -> object:
41
- node = os.environ.get('MD2WORD_NODE') or shutil.which('node')
42
- if not node:
43
- raise ValueError('Node.js not found; install Node.js or set MD2WORD_NODE.')
44
- result = subprocess.run([node, str(HERE / 'runtime.mjs')],
45
- input=json.dumps(payload), text=True, capture_output=True,
46
- timeout=90, check=False)
47
- if result.returncode:
48
- raise ValueError(result.stderr.strip() or 'Markdown/SVG helper failed')
49
- return json.loads(result.stdout)
50
-
51
-
52
- class Converter:
53
- def __init__(self, source: Path, template: Path | None = None):
54
- self.source = source
55
- self.doc = Document(str(template)) if template else Document()
56
- if template:
57
- # Keep styles, headers and section settings; discard template body.
58
- body = self.doc._element.body
59
- for child in list(body):
60
- if child.tag != qn('w:sectPr'):
61
- body.remove(child)
62
- else:
63
- section = self.doc.sections[0]
64
- section.page_width, section.page_height = Cm(21), Cm(29.7)
65
- section.top_margin = section.bottom_margin = Cm(2)
66
- section.left_margin = section.right_margin = Cm(2)
67
- for name in ['Normal', 'Title', 'Heading 1', 'Heading 2', 'Heading 3',
68
- 'Heading 4', 'Heading 5', 'Heading 6', 'List Bullet', 'List Number']:
69
- style = self.doc.styles[name]
70
- style.font.name = 'Arial'
71
- style.font.color.rgb = RGBColor(0, 0, 0)
72
- rpr = style.element.get_or_add_rPr()
73
- fonts = rpr.find(qn('w:rFonts'))
74
- if fonts is None:
75
- fonts = OxmlElement('w:rFonts'); rpr.append(fonts)
76
- fonts.set(qn('w:eastAsia'), 'Heiti SC')
77
- normal = self.doc.styles['Normal']
78
- normal.font.size = Pt(11)
79
- normal.paragraph_format.space_after = Pt(6)
80
- normal.paragraph_format.line_spacing = 1.15
81
- self.images = 0
82
- self.warnings: list[str] = []
83
- self.temp = tempfile.TemporaryDirectory(prefix='md2word-')
84
-
85
- @property
86
- def usable_size(self):
87
- s = self.doc.sections[-1]
88
- return (s.page_width - s.left_margin - s.right_margin,
89
- s.page_height - s.top_margin - s.bottom_margin - Cm(1))
90
-
91
- def local_image(self, href: str) -> tuple[bytes, str]:
92
- if href.startswith('data:'):
93
- header, payload = href.split(',', 1)
94
- data = base64.b64decode(payload, validate=True) if ';base64' in header else unquote(payload).encode()
95
- return data, 'svg' if 'image/svg+xml' in header else 'raster'
96
- split = urlsplit(href)
97
- if split.scheme or split.netloc:
98
- raise ValueError(f'Remote image is unsupported; save it locally first: {href}')
99
- target = (self.source.parent / unquote(split.path)).resolve()
100
- return target.read_bytes(), 'svg' if target.suffix.lower() == '.svg' else 'raster'
101
-
102
- def image(self, data: bytes, kind: str, parent=None, alt=''):
103
- svg = None
104
- if kind == 'svg':
105
- parser = etree.XMLParser(resolve_entities=False, no_network=True)
106
- root = etree.fromstring(data, parser)
107
- if etree.QName(root).localname != 'svg':
108
- raise ValueError('Expected an SVG root element')
109
- if root.getroottree().docinfo.doctype:
110
- raise ValueError('SVG DOCTYPE is unsupported')
111
- # A self-contained SVG makes the resulting DOCX portable.
112
- for element in root.iter():
113
- if not isinstance(element.tag, str):
114
- continue
115
- tag = etree.QName(element).localname.lower()
116
- if tag in {'script', 'foreignObject'.lower()}:
117
- raise ValueError(f'SVG {tag} is unsupported; use SVG text/path labels.')
118
- for key, value in element.attrib.items():
119
- if etree.QName(key).localname.lower() in {'href', 'src'}:
120
- if not value.startswith(('#', 'data:')):
121
- raise ValueError('SVG external resource found; embed it as a data URI first.')
122
- text = data.decode('utf-8-sig')
123
- urls = re.findall(r'url\(\s*([^)]*)\)', text, re.IGNORECASE)
124
- if re.search(r'@import', text, re.IGNORECASE) or any(
125
- not value.strip().strip('\"\'').strip().startswith(('#', 'data:')) for value in urls
126
- ):
127
- raise ValueError('SVG external CSS/resource is unsupported')
128
- if not root.tag.startswith('{'):
129
- root.set('xmlns', SVG_NS)
130
- svg = etree.tostring(root, encoding='utf-8')
131
- target = Path(self.temp.name) / f'image-{self.images}.png'
132
- node_call({'action': 'svg', 'svg': svg.decode(), 'output': str(target)})
133
- data = target.read_bytes()
134
- with Image.open(io.BytesIO(data)) as picture:
135
- width, height = picture.size
136
- max_width, max_height = self.usable_size
137
- # Respect the source aspect ratio and avoid diagrams taller than a page.
138
- scale = min(max_width / width, max_height / height, 9525)
139
- p = parent if parent is not None else self.doc.add_paragraph()
140
- p.alignment = WD_ALIGN_PARAGRAPH.CENTER
141
- shape = p.add_run().add_picture(io.BytesIO(data), width=int(width * scale), height=int(height * scale))
142
- shape._inline.docPr.set('descr', alt or f'Figure {self.images + 1}')
143
- if svg is not None:
144
- existing = {str(part.partname) for part in self.doc.part.package.iter_parts()}
145
- index = 1
146
- while f'/word/media/vector{index}.svg' in existing:
147
- index += 1
148
- part = Part(PackURI(f'/word/media/vector{index}.svg'), 'image/svg+xml', svg, self.doc.part.package)
149
- rid = self.doc.part.relate_to(part, RT.IMAGE)
150
- blip = shape._inline.xpath('.//a:blip')[0]
151
- ext_list = OxmlElement('a:extLst')
152
- ext = OxmlElement('a:ext')
153
- ext.set('uri', '{96DAC541-7B7A-43D3-8B79-37D633B846F1}')
154
- vector = etree.SubElement(ext, f'{{{ASVG_NS}}}svgBlip', nsmap={'asvg': ASVG_NS})
155
- vector.set(qn('r:embed'), rid)
156
- ext_list.append(ext); blip.append(ext_list)
157
- self.images += 1
158
-
159
- def inline(self, p, tokens: list[dict], bold=False, italic=False, strike=False, link=None):
160
- for token in tokens:
161
- kind = token['type']
162
- if kind in {'strong', 'em', 'del'}:
163
- self.inline(p, token.get('tokens', []), bold or kind == 'strong',
164
- italic or kind == 'em', strike or kind == 'del', link)
165
- elif kind == 'link':
166
- self.inline(p, token.get('tokens', []), bold, italic, strike, token['href'])
167
- elif kind == 'image':
168
- data, image_kind = self.local_image(token['href'])
169
- self.image(data, image_kind, p, token.get('text', ''))
170
- elif kind == 'br':
171
- p.add_run().add_break()
172
- elif kind == 'html':
173
- text = token.get('text', '')
174
- if SVG_PATTERN.fullmatch(text.strip()):
175
- self.image(text.encode(), 'svg', p)
176
- elif re.match(r'<br\s*/?>', text, re.IGNORECASE):
177
- p.add_run().add_break()
178
- else:
179
- self.warnings.append('Inline HTML styling is not preserved: ' + text[:60])
180
- else:
181
- text = token.get('text', token.get('raw', ''))
182
- if token.get('tokens'):
183
- self.inline(p, token['tokens'], bold, italic, strike, link); continue
184
- run = p.add_run(html.fromstring(f'<span>{text}</span>').text_content() if '&' in text and '<' not in text else text)
185
- run.bold, run.italic, run.font.strike = bold, italic, strike
186
- if kind == 'codespan':
187
- run.font.name = 'Consolas'; run.font.size = Pt(10)
188
- if link:
189
- hyperlink = OxmlElement('w:hyperlink')
190
- if link.startswith('#'):
191
- # Heading bookmarks are not synthesized; keep the target visible.
192
- self.warnings.append(f'Internal link target not resolved: {link}')
193
- else:
194
- hyperlink.set(qn('r:id'), self.doc.part.relate_to(link, RT.HYPERLINK, is_external=True))
195
- p._p.remove(run._r); hyperlink.append(run._r); p._p.append(hyperlink)
196
-
197
- def raw_html(self, value: str):
198
- if re.search(r'<svg\b', value, re.IGNORECASE) and not SVG_PATTERN.search(value):
199
- raise ValueError('Unclosed SVG element')
200
- cursor = 0
201
- for match in SVG_PATTERN.finditer(value):
202
- self.html_fragment(value[cursor:match.start()])
203
- self.image(match.group().encode(), 'svg')
204
- cursor = match.end()
205
- self.html_fragment(value[cursor:])
206
-
207
- def html_fragment(self, value: str):
208
- if not value.strip():
209
- return
210
- try:
211
- root = html.fragment_fromstring(value, create_parent='div')
212
- except etree.ParserError:
213
- return
214
- for img in root.xpath('.//img'):
215
- data, kind = self.local_image(img.get('src', ''))
216
- self.image(data, kind, alt=img.get('alt', ''))
217
- text = root.text_content().strip()
218
- if text:
219
- self.doc.add_paragraph(text)
220
- self.warnings.append('HTML block preserved as plain text; use Markdown for formatting.')
221
-
222
- def blocks(self, tokens: list[dict], level=0):
223
- for token in tokens:
224
- kind = token['type']
225
- if kind in {'space', 'def'}:
226
- continue
227
- if kind == 'heading':
228
- p = self.doc.add_heading(level=token['depth'])
229
- self.inline(p, token.get('tokens', []))
230
- elif kind in {'paragraph', 'text'}:
231
- value = token.get('text', '')
232
- has_svg_html = any(child['type'] == 'html' and re.match(r'<svg\b', child.get('text', ''), re.IGNORECASE)
233
- for child in token.get('tokens', []))
234
- if has_svg_html:
235
- # CommonMark treats a one-line SVG as inline HTML tokens.
236
- # Read the original paragraph, not those individual tags.
237
- self.raw_html(value)
238
- else:
239
- p = self.doc.add_paragraph()
240
- self.inline(p, token.get('tokens') or [{'type': 'text', 'text': value}])
241
- elif kind == 'code':
242
- if (token.get('lang') or '').strip().lower() == 'svg':
243
- self.image(token['text'].encode(), 'svg')
244
- else:
245
- p = self.doc.add_paragraph()
246
- p.paragraph_format.space_before = Pt(4)
247
- run = p.add_run(token['text']); run.font.name = 'Consolas'; run.font.size = Pt(9)
248
- elif kind == 'html':
249
- self.raw_html(token['text'])
250
- elif kind == 'list':
251
- self.list_items(token, level)
252
- elif kind == 'blockquote':
253
- start = len(self.doc.paragraphs)
254
- self.blocks(token['tokens'], level)
255
- for p in self.doc.paragraphs[start:]:
256
- p.paragraph_format.left_indent = Cm(.7)
257
- elif kind == 'table':
258
- self.table(token)
259
- elif kind == 'hr':
260
- self.doc.add_paragraph()
261
- else:
262
- raise ValueError(f'Unsupported Markdown block: {kind}')
263
-
264
- def list_items(self, token: dict, level: int):
265
- for index, item in enumerate(token['items']):
266
- p = self.doc.add_paragraph()
267
- p.paragraph_format.left_indent = Cm(.6 * (level + 1))
268
- p.paragraph_format.first_line_indent = Cm(-.4)
269
- # Explicit markers preserve arbitrary Markdown starting numbers across renderers.
270
- prefix = f"{int(token.get('start') or 1) + index}. " if token['ordered'] else '• '
271
- if item.get('task'):
272
- prefix = '[x] ' if item.get('checked') else '[ ] '
273
- p.add_run(prefix)
274
- first = True
275
- for child in item['tokens']:
276
- if child['type'] in {'text', 'paragraph'}:
277
- if not first:
278
- p = self.doc.add_paragraph()
279
- p.paragraph_format.left_indent = Cm(.6 * (level + 1))
280
- self.inline(p, child.get('tokens') or [{'type': 'text', 'text': child['text']}])
281
- first = False
282
- elif child['type'] == 'list':
283
- self.list_items(child, level + 1)
284
- else:
285
- self.blocks([child], level + 1)
286
-
287
- def table(self, token: dict):
288
- rows = [token['header']] + token['rows']
289
- table = self.doc.add_table(rows=len(rows), cols=len(rows[0]))
290
- table.style = 'Table Grid'
291
- for i, row in enumerate(rows):
292
- trpr = table.rows[i]._tr.get_or_add_trPr()
293
- if i == 0:
294
- repeat = OxmlElement('w:tblHeader'); trpr.append(repeat)
295
- for j, cell in enumerate(row):
296
- target = table.cell(i, j)
297
- target.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
298
- self.inline(target.paragraphs[0], cell['tokens'])
299
- props = target._tc.get_or_add_tcPr()
300
- borders = OxmlElement('w:tcBorders')
301
- for side in ['top', 'left', 'bottom', 'right']:
302
- line = OxmlElement('w:' + side)
303
- for key, val in [('val', 'single'), ('sz', '4'), ('color', 'D9D9D9')]:
304
- line.set(qn('w:' + key), val)
305
- borders.append(line)
306
- props.append(borders)
307
- margins = OxmlElement('w:tcMar')
308
- for side in ['top', 'left', 'bottom', 'right']:
309
- margin = OxmlElement('w:' + side); margin.set(qn('w:w'), '90'); margin.set(qn('w:type'), 'dxa'); margins.append(margin)
310
- props.append(margins)
311
- if i == 0:
312
- shade = OxmlElement('w:shd'); shade.set(qn('w:fill'), 'E8EEF5'); props.append(shade)
313
- for run in target.paragraphs[0].runs:
314
- run.bold = True
315
- alignment = token.get('align', [None] * len(row))[j]
316
- if alignment in {'center', 'right'}:
317
- target.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER if alignment == 'center' else WD_ALIGN_PARAGRAPH.RIGHT
318
- self.doc.add_paragraph()
319
-
320
- def convert(self, output: Path):
321
- try:
322
- tokens = node_call({'action': 'parse', 'markdown': self.source.read_text(encoding='utf-8-sig')})
323
- self.blocks(tokens)
324
- output.parent.mkdir(parents=True, exist_ok=True)
325
- with tempfile.NamedTemporaryFile(dir=output.parent, suffix='.docx', delete=False) as file:
326
- scratch = Path(file.name)
327
- try:
328
- self.doc.save(scratch)
329
- os.replace(scratch, output)
330
- finally:
331
- scratch.unlink(missing_ok=True)
332
- finally:
333
- self.temp.cleanup()
334
-
335
-
336
- def main():
337
- parser = argparse.ArgumentParser(description=__doc__)
338
- parser.add_argument('input', type=Path)
339
- parser.add_argument('-o', '--output', type=Path)
340
- parser.add_argument('--template', type=Path, help='Optional DOCX style template; its body is discarded')
341
- args = parser.parse_args()
342
- source = args.input.expanduser().resolve()
343
- output = (args.output or source.with_suffix('.docx')).expanduser().resolve()
344
- if source == output:
345
- parser.error('Input and output must be different files')
346
- try:
347
- converter = Converter(source, args.template)
348
- converter.convert(output)
349
- print(f'Created {output} ({converter.images} images)')
350
- for message in dict.fromkeys(converter.warnings):
351
- print('Warning: ' + message, file=sys.stderr)
352
- except (ValueError, OSError, etree.XMLSyntaxError, subprocess.TimeoutExpired) as exc:
353
- print(f'Conversion failed: {exc}', file=sys.stderr)
354
- return 1
355
- return 0
356
-
357
-
358
- if __name__ == '__main__':
359
- raise SystemExit(main())
@@ -1,8 +0,0 @@
1
- {
2
- "private": true,
3
- "type": "module",
4
- "dependencies": {
5
- "marked": "17.0.5",
6
- "sharp": "0.35.5"
7
- }
8
- }
@@ -1,3 +0,0 @@
1
- python-docx>=1.1,<2
2
- lxml>=5,<7
3
- Pillow>=10,<13
@@ -1,31 +0,0 @@
1
- // Markdown parsing and SVG raster fallback, using local dependencies only.
2
- import fs from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { createRequire } from 'node:module';
5
- import { pathToFileURL } from 'node:url';
6
- const root = process.env.MD2WORD_NODE_MODULES;
7
- const req = root ? createRequire(path.join(root, '__md2word.cjs')) : createRequire(import.meta.url);
8
- const input = JSON.parse(await new Promise((resolve) => {
9
- let data = ''; process.stdin.setEncoding('utf8');
10
- process.stdin.on('data', chunk => data += chunk);
11
- process.stdin.on('end', () => resolve(data));
12
- }));
13
- try {
14
- if (input.action === 'parse') {
15
- const { marked } = await import(pathToFileURL(req.resolve('marked')).href);
16
- process.stdout.write(JSON.stringify(marked.lexer(input.markdown, { gfm: true })));
17
- } else if (input.action === 'svg') {
18
- const sharp = req('sharp');
19
- if (/<(?:\w+:)?foreignObject\b/i.test(input.svg)) {
20
- throw new Error('SVG contains foreignObject HTML labels; convert these labels to SVG text or paths first.');
21
- }
22
- const output = await sharp(Buffer.from(input.svg), { density: 192, limitInputPixels: 64000000 })
23
- .resize({ width: 2000, height: 2200, fit: 'inside', withoutEnlargement: false })
24
- .png().toBuffer();
25
- await fs.writeFile(input.output, output);
26
- const metadata = await sharp(output).metadata();
27
- process.stdout.write(JSON.stringify({ width: metadata.width, height: metadata.height }));
28
- } else throw new Error('Unknown action');
29
- } catch (error) {
30
- console.error(error.message); process.exitCode = 1;
31
- }
package/src/core/docx.js DELETED
@@ -1,211 +0,0 @@
1
- "use strict";
2
-
3
- // `keel docx`: Markdown with embedded SVG to Word, on request (#405).
4
- //
5
- // The converter ships with the `keel-md-docx` skill; its third-party packages
6
- // do not. `setup` lists them and installs nothing until it is given `--yes`,
7
- // which the skill asks the user for first, and then installs only into the
8
- // environment Keel manages under `$KEEL_HOME/docx/` — a Python virtual
9
- // environment and an npm prefix, never the system's.
10
-
11
- const fs = require("fs");
12
- const os = require("os");
13
- const path = require("path");
14
- const { spawnSync } = require("child_process");
15
- const { resolveInterpreter, describeTried, MINIMUM_PYTHON } = require("../../scripts/run_python");
16
- const PACKAGE_JSON = require("../../package.json");
17
-
18
- const SKILL_SCRIPTS = path.join(__dirname, "..", "..", "plugins", "keel", "skills", "keel-md-docx", "scripts");
19
-
20
- // What setup installs, as the registries listed it on 2026-10-21 for macOS
21
- // arm64 (#405); the versions that install are the ones requirements.txt and
22
- // package.json pin.
23
- const PACKAGES = [
24
- { name: "python-docx", via: "pip", version: ">=1.1,<2 (1.2.0)", licence: "MIT", size: "0.25 MB" },
25
- { name: "lxml", via: "pip", version: ">=5,<7 (6.0.2)", licence: "BSD-3-Clause", size: "8.6 MB" },
26
- { name: "Pillow", via: "pip", version: ">=10,<13 (12.0.0)", licence: "MIT-CMU", size: "4.65 MB" },
27
- { name: "marked", via: "npm", version: "17.0.5", licence: "MIT", size: "0.44 MB" },
28
- {
29
- name: "sharp",
30
- via: "npm",
31
- version: "0.35.5",
32
- licence: "Apache-2.0",
33
- size: "0.96 MB, plus its platform binary (Apache-2.0) and libvips (LGPL-3.0-or-later, 18.2 MB)",
34
- },
35
- ];
36
-
37
- const USAGE = [
38
- "Usage:",
39
- " keel docx setup [--yes] list what the export needs; install it into the Keel-managed environment with --yes",
40
- " keel docx convert <input.md> [-o <output.docx>] [--template <template.docx>] [--replace]",
41
- " convert in that environment; an existing output is kept unless --replace is given",
42
- ].join("\n");
43
-
44
- function docxHome() {
45
- return path.join(process.env.KEEL_HOME || path.join(os.homedir(), ".keel"), "docx");
46
- }
47
-
48
- function environmentPython(home) {
49
- return process.platform === "win32"
50
- ? path.join(home, "python", "Scripts", "python.exe")
51
- : path.join(home, "python", "bin", "python");
52
- }
53
-
54
- function npmCommand() {
55
- return process.env.KEEL_DOCX_NPM || (process.platform === "win32" ? "npm.cmd" : "npm");
56
- }
57
-
58
- function printPlan(home) {
59
- const lines = [
60
- `keel docx: Markdown with SVG to Word needs these packages, installed into ${home}:`,
61
- ...PACKAGES.map((item) => ` ${item.name} ${item.version} (${item.via}) — ${item.licence} — ${item.size}`),
62
- ` Python ${MINIMUM_PYTHON.join(".")} or newer runs a virtual environment in ${path.join(home, "python")};`,
63
- ` npm installs into ${path.join(home, "node")}. Nothing goes into the system Python or Node,`,
64
- " and no font or runtime is downloaded. Sizes are registry figures, not measured installs.",
65
- ];
66
- process.stdout.write(`${lines.join("\n")}\n`);
67
- }
68
-
69
- function step(name, command, args) {
70
- const result = spawnSync(command, args, {
71
- stdio: "inherit",
72
- shell: process.platform === "win32",
73
- });
74
- if (result.error || result.status !== 0) {
75
- const why = result.error ? result.error.message : `exited ${result.status}`;
76
- process.stderr.write(`keel docx setup: ${name} failed (${why}); the environment is not ready.\n`);
77
- return false;
78
- }
79
- return true;
80
- }
81
-
82
- function setup(argv) {
83
- let yes = false;
84
- for (const arg of argv) {
85
- if (arg === "--yes") yes = true;
86
- else {
87
- process.stderr.write(`keel docx setup: unexpected argument ${arg}\n${USAGE}\n`);
88
- return 2;
89
- }
90
- }
91
- const home = docxHome();
92
- const ready = path.join(home, "ready.json");
93
- printPlan(home);
94
- if (!yes) {
95
- const state = fs.existsSync(ready) ? "The environment is ready." : "Nothing was installed.";
96
- process.stdout.write(`${state} To install or reinstall, run \`keel docx setup --yes\`.\n`);
97
- return 0;
98
- }
99
-
100
- const { candidate, version, tried } = resolveInterpreter();
101
- if (!candidate) {
102
- process.stderr.write(
103
- `keel docx setup: Python ${MINIMUM_PYTHON.join(".")} or newer is required. `
104
- + `Tried ${describeTried(tried) || "nothing"}. Install one, or set KEEL_PYTHON.\n`
105
- );
106
- return 1;
107
- }
108
- // Written last, so an interrupted setup reads as not set up.
109
- fs.rmSync(ready, { force: true });
110
- fs.mkdirSync(path.join(home, "node"), { recursive: true });
111
- fs.copyFileSync(path.join(SKILL_SCRIPTS, "package.json"), path.join(home, "node", "package.json"));
112
- const ok = step("python -m venv", candidate.command, [...candidate.prefixArgs, "-m", "venv", path.join(home, "python")])
113
- && step("pip install", environmentPython(home), ["-m", "pip", "install", "-r", path.join(SKILL_SCRIPTS, "requirements.txt")])
114
- && step("npm install", npmCommand(), ["install", "--prefix", path.join(home, "node"), "--no-audit", "--no-fund"]);
115
- if (!ok) return 1;
116
- fs.writeFileSync(ready, `${JSON.stringify({
117
- keel: PACKAGE_JSON.version,
118
- python: version,
119
- packages: PACKAGES.map((item) => `${item.name} ${item.version}`),
120
- }, null, 2)}\n`);
121
- process.stdout.write(`keel docx: the environment in ${home} is ready.\n`);
122
- return 0;
123
- }
124
-
125
- // The real path of a file that may not exist yet: its directory's, plus its name.
126
- function realTarget(file) {
127
- const absolute = path.resolve(file);
128
- try {
129
- return fs.realpathSync(absolute);
130
- } catch {
131
- try {
132
- return path.join(fs.realpathSync(path.dirname(absolute)), path.basename(absolute));
133
- } catch {
134
- return absolute;
135
- }
136
- }
137
- }
138
-
139
- function convert(argv) {
140
- const fail = (message) => {
141
- process.stderr.write(`keel docx convert: ${message}\n`);
142
- return 1;
143
- };
144
- let input = null;
145
- let output = null;
146
- let template = null;
147
- let replace = false;
148
- for (let index = 0; index < argv.length; index += 1) {
149
- const arg = argv[index];
150
- if (arg === "--replace") replace = true;
151
- else if ((arg === "-o" || arg === "--output" || arg === "--template") && argv[index + 1] !== undefined) {
152
- index += 1;
153
- if (arg === "--template") template = argv[index];
154
- else output = argv[index];
155
- } else if (!arg.startsWith("-") && input === null) input = arg;
156
- else {
157
- process.stderr.write(`keel docx convert: unexpected argument ${arg}\n${USAGE}\n`);
158
- return 2;
159
- }
160
- }
161
- if (input === null) {
162
- process.stderr.write(`keel docx convert: no input file given\n${USAGE}\n`);
163
- return 2;
164
- }
165
-
166
- const source = realTarget(input);
167
- if (!fs.existsSync(source) || !fs.statSync(source).isFile()) return fail(`${input} does not exist.`);
168
- const target = realTarget(output === null ? `${source.slice(0, source.length - path.extname(source).length)}.docx` : output);
169
- if (target === source) return fail(`the output ${target} is the input; name a different output with -o.`);
170
- const styles = template === null ? null : realTarget(template);
171
- if (styles !== null && !fs.existsSync(styles)) return fail(`the template ${template} does not exist.`);
172
- const home = docxHome();
173
- if (!fs.existsSync(path.join(home, "ready.json"))) {
174
- return fail(`the environment in ${home} is not ready; run \`keel docx setup\` to see what it installs.`);
175
- }
176
- if (fs.existsSync(target) && !replace) {
177
- return fail(`${target} already exists and was left as it is; give --replace to overwrite it.`);
178
- }
179
-
180
- const env = {
181
- ...process.env,
182
- MD2WORD_NODE: process.execPath,
183
- MD2WORD_NODE_MODULES: path.join(home, "node", "node_modules"),
184
- };
185
- if (process.platform === "darwin" && !env.FONTCONFIG_FILE) {
186
- env.FONTCONFIG_FILE = path.join(SKILL_SCRIPTS, "fonts-macos.conf");
187
- }
188
- const args = [path.join(SKILL_SCRIPTS, "md2word.py"), source, "-o", target];
189
- if (styles !== null) args.push("--template", styles);
190
- // The converter writes a temporary file and renames it over the output, so
191
- // a failed run leaves the previous output as it was.
192
- const result = spawnSync(environmentPython(home), args, { stdio: "inherit", env });
193
- if (result.error) {
194
- return fail(`the environment's Python did not run (${result.error.message}); rerun \`keel docx setup --yes\`.`);
195
- }
196
- return result.status === null ? 1 : result.status;
197
- }
198
-
199
- function runDocx(argv) {
200
- const [sub, ...rest] = argv;
201
- if (sub === undefined || sub === "--help" || sub === "-h" || sub === "help") {
202
- process.stdout.write(`${USAGE}\n`);
203
- return sub === undefined ? 2 : 0;
204
- }
205
- if (sub === "setup") return setup(rest);
206
- if (sub === "convert") return convert(rest);
207
- process.stderr.write(`keel docx: unknown subcommand ${sub}\n${USAGE}\n`);
208
- return 2;
209
- }
210
-
211
- module.exports = { runDocx, docxHome, PACKAGES, SKILL_SCRIPTS };