@aaa_iii/fzv 0.1.1 → 0.2.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.
@@ -1 +1 @@
1
- import{t as e}from"./java-D112xljv.js";var t=Object.freeze(JSON.parse(`{"displayName":"XML","name":"xml","patterns":[{"begin":"(<\\\\?)\\\\s*([-0-9A-Z_a-z]+)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.xml"}},"end":"(\\\\?>)","name":"meta.tag.preprocessor.xml","patterns":[{"match":" ([-A-Za-z]+)","name":"entity.other.attribute-name.xml"},{"include":"#doublequotedString"},{"include":"#singlequotedString"}]},{"begin":"(<!)(DOCTYPE)\\\\s+([:A-Z_a-z][-.0-:A-Z_a-z]*)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"keyword.other.doctype.xml"},"3":{"name":"variable.language.documentroot.xml"}},"end":"\\\\s*(>)","name":"meta.tag.sgml.doctype.xml","patterns":[{"include":"#internalSubset"}]},{"include":"#comments"},{"begin":"(<)((?:([-0-9A-Z_a-z]+)(:))?([-0-:A-Z_a-z]+))(?=(\\\\s[^>]*)?></\\\\2>)","beginCaptures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.xml"},"3":{"name":"entity.name.tag.namespace.xml"},"4":{"name":"punctuation.separator.namespace.xml"},"5":{"name":"entity.name.tag.localname.xml"}},"end":"(>)(</)((?:([-0-9A-Z_a-z]+)(:))?([-0-:A-Z_a-z]+))(>)","endCaptures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"punctuation.definition.tag.xml"},"3":{"name":"entity.name.tag.xml"},"4":{"name":"entity.name.tag.namespace.xml"},"5":{"name":"punctuation.separator.namespace.xml"},"6":{"name":"entity.name.tag.localname.xml"},"7":{"name":"punctuation.definition.tag.xml"}},"name":"meta.tag.no-content.xml","patterns":[{"include":"#tagStuff"}]},{"begin":"(</?)(?:([-.\\\\w]+)((:)))?([-.:\\\\w]+)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.namespace.xml"},"3":{"name":"entity.name.tag.xml"},"4":{"name":"punctuation.separator.namespace.xml"},"5":{"name":"entity.name.tag.localname.xml"}},"end":"(/?>)","name":"meta.tag.xml","patterns":[{"include":"#tagStuff"}]},{"include":"#entity"},{"include":"#bare-ampersand"},{"begin":"<%@","beginCaptures":{"0":{"name":"punctuation.section.embedded.begin.xml"}},"end":"%>","endCaptures":{"0":{"name":"punctuation.section.embedded.end.xml"}},"name":"source.java-props.embedded.xml","patterns":[{"match":"page|include|taglib","name":"keyword.other.page-props.xml"}]},{"begin":"<%[!=]?(?!--)","beginCaptures":{"0":{"name":"punctuation.section.embedded.begin.xml"}},"end":"(?!--)%>","endCaptures":{"0":{"name":"punctuation.section.embedded.end.xml"}},"name":"source.java.embedded.xml","patterns":[{"include":"source.java"}]},{"begin":"<!\\\\[CDATA\\\\[","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"]]>","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.unquoted.cdata.xml"}],"repository":{"EntityDecl":{"begin":"(<!)(ENTITY)\\\\s+(%\\\\s+)?([:A-Z_a-z][-.0-:A-Z_a-z]*)(\\\\s+(?:SYSTEM|PUBLIC)\\\\s+)?","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"keyword.other.entity.xml"},"3":{"name":"punctuation.definition.entity.xml"},"4":{"name":"variable.language.entity.xml"},"5":{"name":"keyword.other.entitytype.xml"}},"end":"(>)","patterns":[{"include":"#doublequotedString"},{"include":"#singlequotedString"}]},"bare-ampersand":{"match":"&","name":"invalid.illegal.bad-ampersand.xml"},"comments":{"patterns":[{"begin":"<%--","captures":{"0":{"name":"punctuation.definition.comment.xml"},"end":"--%>","name":"comment.block.xml"}},{"begin":"<!--","captures":{"0":{"name":"punctuation.definition.comment.xml"}},"end":"-->","name":"comment.block.xml","patterns":[{"begin":"--(?!>)","captures":{"0":{"name":"invalid.illegal.bad-comments-or-CDATA.xml"}}}]}]},"doublequotedString":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"\\"","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.quoted.double.xml","patterns":[{"include":"#entity"},{"include":"#bare-ampersand"}]},"entity":{"captures":{"1":{"name":"punctuation.definition.constant.xml"},"3":{"name":"punctuation.definition.constant.xml"}},"match":"(&)([:A-Z_a-z][-.0-:A-Z_a-z]*|#[0-9]+|#x\\\\h+)(;)","name":"constant.character.entity.xml"},"internalSubset":{"begin":"(\\\\[)","captures":{"1":{"name":"punctuation.definition.constant.xml"}},"end":"(])","name":"meta.internalsubset.xml","patterns":[{"include":"#EntityDecl"},{"include":"#parameterEntity"},{"include":"#comments"}]},"parameterEntity":{"captures":{"1":{"name":"punctuation.definition.constant.xml"},"3":{"name":"punctuation.definition.constant.xml"}},"match":"(%)([:A-Z_a-z][-.0-:A-Z_a-z]*)(;)","name":"constant.character.parameter-entity.xml"},"singlequotedString":{"begin":"'","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"'","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.quoted.single.xml","patterns":[{"include":"#entity"},{"include":"#bare-ampersand"}]},"tagStuff":{"patterns":[{"captures":{"1":{"name":"entity.other.attribute-name.namespace.xml"},"2":{"name":"entity.other.attribute-name.xml"},"3":{"name":"punctuation.separator.namespace.xml"},"4":{"name":"entity.other.attribute-name.localname.xml"}},"match":"(?:^|\\\\s+)(?:([-.\\\\w]+)((:)))?([-.:\\\\w]+)\\\\s*="},{"include":"#doublequotedString"},{"include":"#singlequotedString"}]}},"scopeName":"text.xml","embeddedLangs":["java"]}`)),n=[...e,t];export{n as default};
1
+ import{t as e}from"./java-D_0z2NwT.js";var t=Object.freeze(JSON.parse(`{"displayName":"XML","name":"xml","patterns":[{"begin":"(<\\\\?)\\\\s*([-0-9A-Z_a-z]+)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.xml"}},"end":"(\\\\?>)","name":"meta.tag.preprocessor.xml","patterns":[{"match":" ([-A-Za-z]+)","name":"entity.other.attribute-name.xml"},{"include":"#doublequotedString"},{"include":"#singlequotedString"}]},{"begin":"(<!)(DOCTYPE)\\\\s+([:A-Z_a-z][-.0-:A-Z_a-z]*)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"keyword.other.doctype.xml"},"3":{"name":"variable.language.documentroot.xml"}},"end":"\\\\s*(>)","name":"meta.tag.sgml.doctype.xml","patterns":[{"include":"#internalSubset"}]},{"include":"#comments"},{"begin":"(<)((?:([-0-9A-Z_a-z]+)(:))?([-0-:A-Z_a-z]+))(?=(\\\\s[^>]*)?></\\\\2>)","beginCaptures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.xml"},"3":{"name":"entity.name.tag.namespace.xml"},"4":{"name":"punctuation.separator.namespace.xml"},"5":{"name":"entity.name.tag.localname.xml"}},"end":"(>)(</)((?:([-0-9A-Z_a-z]+)(:))?([-0-:A-Z_a-z]+))(>)","endCaptures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"punctuation.definition.tag.xml"},"3":{"name":"entity.name.tag.xml"},"4":{"name":"entity.name.tag.namespace.xml"},"5":{"name":"punctuation.separator.namespace.xml"},"6":{"name":"entity.name.tag.localname.xml"},"7":{"name":"punctuation.definition.tag.xml"}},"name":"meta.tag.no-content.xml","patterns":[{"include":"#tagStuff"}]},{"begin":"(</?)(?:([-.\\\\w]+)((:)))?([-.:\\\\w]+)","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"entity.name.tag.namespace.xml"},"3":{"name":"entity.name.tag.xml"},"4":{"name":"punctuation.separator.namespace.xml"},"5":{"name":"entity.name.tag.localname.xml"}},"end":"(/?>)","name":"meta.tag.xml","patterns":[{"include":"#tagStuff"}]},{"include":"#entity"},{"include":"#bare-ampersand"},{"begin":"<%@","beginCaptures":{"0":{"name":"punctuation.section.embedded.begin.xml"}},"end":"%>","endCaptures":{"0":{"name":"punctuation.section.embedded.end.xml"}},"name":"source.java-props.embedded.xml","patterns":[{"match":"page|include|taglib","name":"keyword.other.page-props.xml"}]},{"begin":"<%[!=]?(?!--)","beginCaptures":{"0":{"name":"punctuation.section.embedded.begin.xml"}},"end":"(?!--)%>","endCaptures":{"0":{"name":"punctuation.section.embedded.end.xml"}},"name":"source.java.embedded.xml","patterns":[{"include":"source.java"}]},{"begin":"<!\\\\[CDATA\\\\[","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"]]>","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.unquoted.cdata.xml"}],"repository":{"EntityDecl":{"begin":"(<!)(ENTITY)\\\\s+(%\\\\s+)?([:A-Z_a-z][-.0-:A-Z_a-z]*)(\\\\s+(?:SYSTEM|PUBLIC)\\\\s+)?","captures":{"1":{"name":"punctuation.definition.tag.xml"},"2":{"name":"keyword.other.entity.xml"},"3":{"name":"punctuation.definition.entity.xml"},"4":{"name":"variable.language.entity.xml"},"5":{"name":"keyword.other.entitytype.xml"}},"end":"(>)","patterns":[{"include":"#doublequotedString"},{"include":"#singlequotedString"}]},"bare-ampersand":{"match":"&","name":"invalid.illegal.bad-ampersand.xml"},"comments":{"patterns":[{"begin":"<%--","captures":{"0":{"name":"punctuation.definition.comment.xml"},"end":"--%>","name":"comment.block.xml"}},{"begin":"<!--","captures":{"0":{"name":"punctuation.definition.comment.xml"}},"end":"-->","name":"comment.block.xml","patterns":[{"begin":"--(?!>)","captures":{"0":{"name":"invalid.illegal.bad-comments-or-CDATA.xml"}}}]}]},"doublequotedString":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"\\"","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.quoted.double.xml","patterns":[{"include":"#entity"},{"include":"#bare-ampersand"}]},"entity":{"captures":{"1":{"name":"punctuation.definition.constant.xml"},"3":{"name":"punctuation.definition.constant.xml"}},"match":"(&)([:A-Z_a-z][-.0-:A-Z_a-z]*|#[0-9]+|#x\\\\h+)(;)","name":"constant.character.entity.xml"},"internalSubset":{"begin":"(\\\\[)","captures":{"1":{"name":"punctuation.definition.constant.xml"}},"end":"(])","name":"meta.internalsubset.xml","patterns":[{"include":"#EntityDecl"},{"include":"#parameterEntity"},{"include":"#comments"}]},"parameterEntity":{"captures":{"1":{"name":"punctuation.definition.constant.xml"},"3":{"name":"punctuation.definition.constant.xml"}},"match":"(%)([:A-Z_a-z][-.0-:A-Z_a-z]*)(;)","name":"constant.character.parameter-entity.xml"},"singlequotedString":{"begin":"'","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.xml"}},"end":"'","endCaptures":{"0":{"name":"punctuation.definition.string.end.xml"}},"name":"string.quoted.single.xml","patterns":[{"include":"#entity"},{"include":"#bare-ampersand"}]},"tagStuff":{"patterns":[{"captures":{"1":{"name":"entity.other.attribute-name.namespace.xml"},"2":{"name":"entity.other.attribute-name.xml"},"3":{"name":"punctuation.separator.namespace.xml"},"4":{"name":"entity.other.attribute-name.localname.xml"}},"match":"(?:^|\\\\s+)(?:([-.\\\\w]+)((:)))?([-.:\\\\w]+)\\\\s*="},{"include":"#doublequotedString"},{"include":"#singlequotedString"}]}},"scopeName":"text.xml","embeddedLangs":["java"]}`)),n=[...e,t];export{n as default};
@@ -10,7 +10,7 @@
10
10
  />
11
11
  <title>fzv</title>
12
12
  <link rel="icon" href="data:," />
13
- <script type="module" crossorigin src="/_fzv/assets/index-DZRy_kMM.js"></script>
13
+ <script type="module" crossorigin src="/_fzv/assets/index-DmtUQAD5.js"></script>
14
14
  <link rel="stylesheet" crossorigin href="/_fzv/assets/index-CmRL0QNk.css">
15
15
  </head>
16
16
  <body>
@@ -54,10 +54,14 @@ const IMAGE = new Set([
54
54
  '.bmp',
55
55
  '.ico',
56
56
  ]);
57
+ const OFFICE = new Set(['.docx', '.pptx', '.xlsx']);
57
58
  const ASSET = new Set(['.eot', '.otf', '.ttf', '.woff', '.woff2']);
58
59
  const EXCLUDED = new Set(['node_modules', '__pycache__']);
59
60
  const MIME = {
60
61
  '.pdf': 'application/pdf',
62
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
63
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
64
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
61
65
  '.html': 'text/html; charset=utf-8',
62
66
  '.htm': 'text/html; charset=utf-8',
63
67
  '.png': 'image/png',
@@ -91,6 +95,8 @@ export function previewKind(filename) {
91
95
  return 'html';
92
96
  if (IMAGE.has(ext))
93
97
  return 'image';
98
+ if (OFFICE.has(ext))
99
+ return 'office';
94
100
  if (TEXT.has(ext) ||
95
101
  ['Makefile', 'Dockerfile', 'LICENSE', 'LICENCE', 'NOTICE'].includes(path.basename(filename)))
96
102
  return 'text';
@@ -2,20 +2,25 @@
2
2
  import { parseArgs } from 'node:util';
3
3
  import { createViewer } from './server.js';
4
4
  import { PRODUCT_NAME, VERSION } from '../shared.js';
5
- import { viewerUrls } from './network.js';
5
+ import { projectPort, viewerUrls } from './network.js';
6
+ import { findOfficeConverter, OFFICE_CONVERTER_NAMES } from './office.js';
6
7
  const HELP = `${PRODUCT_NAME} — the file viewer for agent-driven development
7
8
 
8
- Usage: ${PRODUCT_NAME} [--root PATH] [--host HOST] [--port PORT] [--watch] [--allow-html-network]
9
+ Usage: ${PRODUCT_NAME} [--root PATH] [--host HOST] [--port PORT] [--watch] [--allow-html-network] [--office-converter PATH]
9
10
 
10
11
  --root PATH Project directory (default: current working directory)
11
12
  --host HOST Bind address (default: 127.0.0.1)
12
- --port PORT HTTP port, 0 for a free port (default: 8000)
13
+ --port PORT HTTP port, 0 for a free port (default: a port derived from
14
+ the project path, or a free port if that one is unavailable)
13
15
  --watch Refresh files and previews when project files change
14
16
  --allow-html-network Allow HTML previews to run remote scripts and make network requests
17
+ --office-converter PATH ibisOffice or LibreOffice executable for Office previews
18
+ (default: ibisOffice, then soffice/libreoffice, found on PATH)
15
19
  -h, --help Show this help
16
20
  -v, --version Show version
17
21
 
18
- Find and preview PDF, HTML, images, and text. Files are read-only.
22
+ Find and preview PDF, HTML, images, text, and Office documents
23
+ (.docx, .xlsx, .pptx, converted to PDF). Files are read-only.
19
24
  Use --host 0.0.0.0 explicitly to allow devices on your network.
20
25
  `;
21
26
  async function main() {
@@ -25,9 +30,10 @@ async function main() {
25
30
  options: {
26
31
  root: { type: 'string' },
27
32
  host: { type: 'string', default: '127.0.0.1' },
28
- port: { type: 'string', default: '8000' },
33
+ port: { type: 'string' },
29
34
  watch: { type: 'boolean', default: false },
30
35
  'allow-html-network': { type: 'boolean', default: false },
36
+ 'office-converter': { type: 'string' },
31
37
  help: { type: 'boolean', short: 'h' },
32
38
  version: { type: 'boolean', short: 'v' },
33
39
  },
@@ -42,30 +48,49 @@ async function main() {
42
48
  console.log(VERSION);
43
49
  return;
44
50
  }
45
- if (!/^\d+$/.test(values.port) || Number(values.port) > 65535)
51
+ if (values.port !== undefined &&
52
+ (!/^\d+$/.test(values.port) || Number(values.port) > 65535))
46
53
  throw new Error('--port must be an integer between 0 and 65535.');
54
+ const officeConverter = await findOfficeConverter(values['office-converter']);
47
55
  const { server, catalog } = await createViewer({
48
56
  root: values.root ?? process.cwd(),
49
57
  host: values.host,
50
58
  watch: values.watch,
51
59
  allowHtmlNetwork: values['allow-html-network'],
60
+ officeConverter,
52
61
  });
53
62
  server.on('watchError', (error) => {
54
63
  console.error(`${PRODUCT_NAME}: file watching stopped: ${error.message}`);
55
64
  });
56
65
  if (values['allow-html-network'])
57
66
  console.warn(`${PRODUCT_NAME}: HTML previews can run network-loaded code. Use only with trusted projects.`);
67
+ let port = values.port === undefined
68
+ ? projectPort(catalog.project.id)
69
+ : Number(values.port);
58
70
  server.on('error', (error) => {
59
- console.error(`${PRODUCT_NAME}: ${error.code === 'EADDRINUSE' ? `Port ${values.port} is in use. Choose another with --port.` : error.message}`);
71
+ if (values.port === undefined &&
72
+ !server.listening &&
73
+ port !== 0 &&
74
+ (error.code === 'EADDRINUSE' || error.code === 'EACCES')) {
75
+ console.warn(`${PRODUCT_NAME}: Port ${port} is ${error.code === 'EADDRINUSE' ? 'in use' : 'unavailable'}; using a free port.`);
76
+ port = 0;
77
+ server.listen(port, values.host);
78
+ return;
79
+ }
80
+ console.error(`${PRODUCT_NAME}: ${error.code === 'EADDRINUSE' ? `Port ${port} is in use. Choose another with --port.` : error.message}`);
60
81
  process.exitCode = 1;
61
82
  });
62
- server.listen(Number(values.port), values.host, () => {
83
+ server.once('listening', () => {
63
84
  const address = server.address();
64
85
  if (!address || typeof address === 'string')
65
86
  return;
66
87
  const urls = viewerUrls(values.host, address.port);
67
- console.log(`\n ${PRODUCT_NAME} ${VERSION}\n Project ${catalog.root}\n${urls.map((url) => ` Viewer ${url}`).join('\n')}\n\n Press Ctrl+C to stop.\n`);
88
+ const office = officeConverter
89
+ ? `${OFFICE_CONVERTER_NAMES[officeConverter.kind]} (${officeConverter.command})`
90
+ : 'unavailable; install ibisOffice or LibreOffice';
91
+ console.log(`\n ${PRODUCT_NAME} ${VERSION}\n Project ${catalog.root}\n${urls.map((url) => ` Viewer ${url}`).join('\n')}\n Office ${office}\n\n Press Ctrl+C to stop.\n`);
68
92
  });
93
+ server.listen(port, values.host);
69
94
  const stop = () => {
70
95
  server.close();
71
96
  server.closeAllConnections();
@@ -21,3 +21,7 @@ export function viewerUrls(host, port, interfaces = networkInterfaces()) {
21
21
  addresses.add(host);
22
22
  return [...addresses].map((address) => `http://${address.includes(':') ? `[${address}]` : address}:${port}/`);
23
23
  }
24
+ // A stable port per project keeps the browser origin, and its saved session, across restarts.
25
+ export function projectPort(projectId) {
26
+ return 20000 + (Number.parseInt(projectId.slice(0, 8), 16) % 10000);
27
+ }
@@ -0,0 +1,244 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { access, mkdir, mkdtemp, rename, rm, stat, writeFile, } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ export const OFFICE_CONVERTER_NAMES = {
9
+ ibisoffice: 'ibisOffice',
10
+ libreoffice: 'LibreOffice',
11
+ };
12
+ const SEARCH_NAMES = ['ibisOffice', 'ibisoffice', 'soffice', 'libreoffice'];
13
+ const TIMEOUT = 60_000;
14
+ const CACHE_LIMIT = 32;
15
+ export function converterKind(command) {
16
+ return /^(?:soffice|libreoffice)/i.test(path.basename(command))
17
+ ? 'libreoffice'
18
+ : 'ibisoffice';
19
+ }
20
+ async function executable(filename) {
21
+ try {
22
+ await access(filename, constants.X_OK);
23
+ return (await stat(filename)).isFile();
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ async function which(name, env) {
30
+ const extensions = process.platform === 'win32'
31
+ ? (env.PATHEXT ?? '.EXE').split(';').filter(Boolean)
32
+ : [''];
33
+ for (const directory of (env.PATH ?? '').split(path.delimiter)) {
34
+ if (!directory)
35
+ continue;
36
+ for (const extension of extensions) {
37
+ const candidate = path.join(directory, name + extension);
38
+ if (await executable(candidate))
39
+ return candidate;
40
+ }
41
+ }
42
+ return undefined;
43
+ }
44
+ /** Resolves an explicit converter, or prefers ibisOffice over LibreOffice on PATH. */
45
+ export async function findOfficeConverter(explicit, env = process.env) {
46
+ if (explicit) {
47
+ const command = /[\\/]/.test(explicit)
48
+ ? (await executable(path.resolve(explicit)))
49
+ ? path.resolve(explicit)
50
+ : undefined
51
+ : await which(explicit, env);
52
+ if (!command)
53
+ throw new Error(`--office-converter: ${explicit} is not an executable file.`);
54
+ return { kind: converterKind(command), command };
55
+ }
56
+ const candidates = [];
57
+ for (const name of SEARCH_NAMES) {
58
+ const command = await which(name, env);
59
+ if (command)
60
+ candidates.push(command);
61
+ }
62
+ if (process.platform === 'darwin')
63
+ candidates.push('/Applications/ibisOffice.app/Contents/MacOS/ibisOffice', '/Applications/LibreOffice.app/Contents/MacOS/soffice');
64
+ if (process.platform === 'win32' && env.ProgramFiles)
65
+ candidates.push(path.join(env.ProgramFiles, 'LibreOffice', 'program', 'soffice.exe'));
66
+ for (const command of candidates)
67
+ if (await executable(command))
68
+ return { kind: converterKind(command), command };
69
+ return null;
70
+ }
71
+ export class OfficeConversionError extends Error {
72
+ status;
73
+ constructor(message, status) {
74
+ super(message);
75
+ this.status = status;
76
+ }
77
+ }
78
+ /**
79
+ * Converts Office documents to PDF in a private temporary directory.
80
+ * Inputs are copies of validated file contents, so the converter never reads project paths.
81
+ */
82
+ export class OfficeRenderer {
83
+ converter;
84
+ directory;
85
+ // Keyed by content, so watch-mode edits convert again and reverted files reuse the cache.
86
+ cache = new Map();
87
+ children = new Set();
88
+ queue = [];
89
+ limit;
90
+ running = 0;
91
+ sequence = 0;
92
+ closed = false;
93
+ constructor(converter) {
94
+ this.converter = converter;
95
+ // LibreOffice instances sharing a profile cannot run concurrently.
96
+ this.limit = converter.kind === 'libreoffice' ? 1 : 2;
97
+ }
98
+ get name() {
99
+ return OFFICE_CONVERTER_NAMES[this.converter.kind];
100
+ }
101
+ pdf(bytes, extension) {
102
+ const key = createHash('sha256')
103
+ .update(extension)
104
+ .update('\0')
105
+ .update(bytes)
106
+ .digest('hex');
107
+ const cached = this.cache.get(key);
108
+ if (cached) {
109
+ this.cache.delete(key);
110
+ this.cache.set(key, cached);
111
+ return cached;
112
+ }
113
+ const result = this.convert(key, bytes, extension);
114
+ this.cache.set(key, result);
115
+ result.catch(() => {
116
+ if (this.cache.get(key) === result)
117
+ this.cache.delete(key);
118
+ });
119
+ while (this.cache.size > CACHE_LIMIT) {
120
+ const [oldest, pending] = this.cache.entries().next().value;
121
+ this.cache.delete(oldest);
122
+ void pending.then((filename) => rm(filename, { force: true }), () => { });
123
+ }
124
+ return result;
125
+ }
126
+ async close() {
127
+ this.closed = true;
128
+ for (const child of this.children)
129
+ child.kill('SIGKILL');
130
+ for (const next of this.queue.splice(0))
131
+ next();
132
+ const directory = await this.directory?.catch(() => undefined);
133
+ if (directory)
134
+ await rm(directory, { recursive: true, force: true });
135
+ }
136
+ root() {
137
+ this.directory ??= mkdtemp(path.join(tmpdir(), 'fzv-office-'));
138
+ return this.directory;
139
+ }
140
+ acquire() {
141
+ if (this.running < this.limit) {
142
+ this.running++;
143
+ return Promise.resolve();
144
+ }
145
+ return new Promise((resolve) => this.queue.push(resolve));
146
+ }
147
+ release() {
148
+ const next = this.queue.shift();
149
+ if (next)
150
+ next();
151
+ else
152
+ this.running--;
153
+ }
154
+ async convert(key, bytes, extension) {
155
+ await this.acquire();
156
+ try {
157
+ if (this.closed)
158
+ throw new OfficeConversionError('The viewer is shutting down.', 503);
159
+ const root = await this.root();
160
+ const work = path.join(root, `work-${++this.sequence}`);
161
+ await mkdir(work);
162
+ try {
163
+ const input = path.join(work, `document${extension}`);
164
+ await writeFile(input, bytes, { flag: 'wx', mode: 0o600 });
165
+ const stderr = await this.run(root, work, input);
166
+ const target = path.join(root, `${key}.pdf`);
167
+ try {
168
+ await rename(path.join(work, 'document.pdf'), target);
169
+ }
170
+ catch {
171
+ throw new OfficeConversionError(stderr || `${this.name} did not produce a PDF.`, 422);
172
+ }
173
+ return target;
174
+ }
175
+ finally {
176
+ await rm(work, { recursive: true, force: true });
177
+ }
178
+ }
179
+ finally {
180
+ this.release();
181
+ }
182
+ }
183
+ /** Resolves with the last diagnostic line when the converter exits successfully. */
184
+ run(root, work, input) {
185
+ const args = this.converter.kind === 'libreoffice'
186
+ ? [
187
+ '--headless',
188
+ '--norestore',
189
+ '--nolockcheck',
190
+ `-env:UserInstallation=${pathToFileURL(path.join(root, 'libreoffice-profile')).href}`,
191
+ '--convert-to',
192
+ 'pdf',
193
+ '--outdir',
194
+ work,
195
+ input,
196
+ ]
197
+ : ['--export', 'pdf', '--out-dir', work, input];
198
+ return new Promise((resolve, reject) => {
199
+ const child = spawn(this.converter.command, args, {
200
+ cwd: work,
201
+ stdio: ['ignore', 'ignore', 'pipe'],
202
+ windowsHide: true,
203
+ });
204
+ this.children.add(child);
205
+ let stderr = '';
206
+ let timedOut = false;
207
+ child.stderr.setEncoding('utf8');
208
+ child.stderr.on('data', (chunk) => {
209
+ if (stderr.length < 8192)
210
+ stderr += chunk;
211
+ });
212
+ const timer = setTimeout(() => {
213
+ timedOut = true;
214
+ child.kill('SIGKILL');
215
+ }, TIMEOUT);
216
+ const finish = () => {
217
+ clearTimeout(timer);
218
+ this.children.delete(child);
219
+ };
220
+ // Diagnostics name the temporary copy; show only its file name.
221
+ const diagnostic = () => stderr
222
+ .replaceAll(work + path.sep, '')
223
+ .split(/\r?\n/)
224
+ .map((line) => line.trim())
225
+ .filter(Boolean)
226
+ .at(-1)
227
+ ?.slice(0, 500) ?? '';
228
+ child.once('error', (error) => {
229
+ finish();
230
+ reject(new OfficeConversionError(`Could not start ${this.name}: ${error.message}`, 503));
231
+ });
232
+ child.once('close', (code, signal) => {
233
+ finish();
234
+ if (code === 0)
235
+ resolve(diagnostic());
236
+ else
237
+ reject(new OfficeConversionError(timedOut
238
+ ? `${this.name} did not finish within ${TIMEOUT / 1000} seconds.`
239
+ : diagnostic() ||
240
+ `${this.name} exited with ${signal ?? `code ${code}`}.`, 422));
241
+ });
242
+ });
243
+ }
244
+ }
@@ -1,11 +1,12 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { networkInterfaces } from 'node:os';
3
- import { watch as watchFiles } from 'node:fs';
4
- import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import { constants, watch as watchFiles } from 'node:fs';
4
+ import { open, readFile, realpath, stat } from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { pipeline } from 'node:stream/promises';
8
8
  import { Catalog, contentType, FileUnavailable, isVisibleRelative, } from './catalog.js';
9
+ import { OfficeConversionError, OfficeRenderer } from './office.js';
9
10
  import { installNavigation } from '../navigation.js';
10
11
  const UI_ROOT = fileURLToPath(new URL('../client/', import.meta.url));
11
12
  const UI_CSP = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; frame-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'";
@@ -119,6 +120,7 @@ function allowedHosts(host) {
119
120
  }
120
121
  return values;
121
122
  }
123
+ export const OFFICE_UNAVAILABLE = 'Office previews need ibisOffice or LibreOffice. Install one and restart fzv, or pass --office-converter PATH.';
122
124
  export async function createViewer(options) {
123
125
  const catalog = await Catalog.create(options.root);
124
126
  const hosts = allowedHosts(options.host ?? '127.0.0.1');
@@ -126,6 +128,9 @@ export async function createViewer(options) {
126
128
  const allowHtmlNetwork = options.allowHtmlNetwork ?? false;
127
129
  const watchEnabled = options.watch ?? false;
128
130
  const previewCsp = allowHtmlNetwork ? NETWORK_PREVIEW_CSP : PREVIEW_CSP;
131
+ const office = options.officeConverter
132
+ ? new OfficeRenderer(options.officeConverter)
133
+ : undefined;
129
134
  const eventClients = new Set();
130
135
  let reloadTimer;
131
136
  // Unknown or excessive changes are sent as null so clients refresh every tab.
@@ -266,6 +271,34 @@ export async function createViewer(options) {
266
271
  }
267
272
  return;
268
273
  }
274
+ if (url.pathname === '/office-pdf') {
275
+ const relative = url.searchParams.get('path') ?? '';
276
+ const file = await catalog.openFile(relative);
277
+ let bytes;
278
+ try {
279
+ if (file.kind !== 'office')
280
+ throw new FileUnavailable();
281
+ if (!office)
282
+ throw new OfficeConversionError(OFFICE_UNAVAILABLE, 503);
283
+ // Convert the validated descriptor's contents, never a path the converter reopens.
284
+ bytes = await file.handle.readFile();
285
+ }
286
+ finally {
287
+ await file.handle.close();
288
+ }
289
+ const filename = await office.pdf(bytes, path.extname(file.filename).toLowerCase());
290
+ const handle = await open(filename, constants.O_RDONLY);
291
+ let size;
292
+ try {
293
+ size = (await handle.stat()).size;
294
+ }
295
+ catch (error) {
296
+ await handle.close();
297
+ throw error;
298
+ }
299
+ await sendProjectFile(req, res, { handle, size, filename, kind: 'pdf' }, relative, false, previewCsp, allowHtmlNetwork);
300
+ return;
301
+ }
269
302
  if (url.pathname === '/file' || url.pathname.startsWith('/asset/')) {
270
303
  const asset = url.pathname.startsWith('/asset/');
271
304
  const relative = asset
@@ -306,6 +339,10 @@ export async function createViewer(options) {
306
339
  res.destroy();
307
340
  return;
308
341
  }
342
+ if (error instanceof OfficeConversionError) {
343
+ reply(req, res, error.status, 'text/plain; charset=utf-8', error.message + '\n');
344
+ return;
345
+ }
309
346
  const status = error instanceof URIError
310
347
  ? 400
311
348
  : error instanceof FileUnavailable ||
@@ -325,6 +362,7 @@ export async function createViewer(options) {
325
362
  server.headersTimeout = 10_000;
326
363
  server.on('close', () => {
327
364
  watcher?.close();
365
+ void office?.close();
328
366
  clearTimeout(reloadTimer);
329
367
  for (const client of eventClients)
330
368
  client.end();
@@ -334,5 +372,5 @@ export async function createViewer(options) {
334
372
  watcher.close();
335
373
  server.emit('watchError', error);
336
374
  });
337
- return { server, catalog };
375
+ return { server, catalog, office };
338
376
  }
package/dist/shared.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export const PRODUCT_NAME = 'fzv';
2
- export const VERSION = '0.1.1';
2
+ export const VERSION = '0.2.0';
3
3
  export const MAX_FILE_SIZE = 20 * 1024 * 1024;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaa_iii/fzv",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A local file viewer for agent-driven development. Fuzzy find, open, and preview project files without an IDE.",
5
5
  "type": "module",
6
6
  "bin": {