@unieai/libreoffice-kit-wasm 0.0.0-stage → 0.2.3

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 (51) hide show
  1. package/README.md +7 -2
  2. package/assets/dsoffice.cjs +26 -0
  3. package/assets/dsoffice.data +0 -0
  4. package/assets/dsoffice.data.js.metadata +1 -0
  5. package/assets/dsoffice.wasm +4 -0
  6. package/assets/manifest.json +1888 -0
  7. package/licenses/LICENSE +4666 -0
  8. package/licenses/NOTICE +63 -0
  9. package/licenses/Rabi-Harness-MIT.txt +28 -0
  10. package/package.json +22 -4
  11. package/prebuilds.json +128 -0
  12. package/sources/build-autogen.input +35 -0
  13. package/sources/core-source.json +4 -0
  14. package/sources/docs/ui-resources.md +123 -0
  15. package/sources/engine/build-identity.mjs +49 -0
  16. package/sources/engine/core-source.mjs +27 -0
  17. package/sources/engine/document-operations.hxx +51 -0
  18. package/sources/engine/ui-resource-policy.mjs +33 -0
  19. package/sources/engine/wasm-source/autogen.input +33 -0
  20. package/sources/engine/wasm-source/build.mjs +300 -0
  21. package/sources/engine/wasm-source/lok.cxx +428 -0
  22. package/sources/engine/wasm-source/patches/0001-macos-build-tools.patch +87 -0
  23. package/sources/engine/wasm-source/patches/0002-system-font-demand.patch +322 -0
  24. package/sources/engine/wasm-source/patches/0003-node-runtime.patch +99 -0
  25. package/sources/engine/wasm-source/patches/0004-system-fonts-only.patch +10 -0
  26. package/sources/engine/wasm-source/patches/0005-cross-build-rules.patch +46 -0
  27. package/sources/engine/wasm-source/patches/0006-wasm-external-platforms.patch +55 -0
  28. package/sources/engine/wasm-source/patches/0008-disable-link-updates.patch +30 -0
  29. package/sources/engine/wasm-source/patches/0009-disable-optional-curl.patch +11 -0
  30. package/sources/engine/wasm-source/patches/0010-refresh-component-registry.patch +11 -0
  31. package/sources/engine/wasm-source/patches/0011-preserve-optimization-with-prefix-maps.patch +21 -0
  32. package/sources/engine/wasm-source/patches/0012-anonymize-explicit-source-paths.patch +39 -0
  33. package/sources/engine/wasm-source/patches/0023-pdfium-for-embedded-graphics.patch +14 -0
  34. package/sources/engine/wasm-source/patches/0024-pdfium-emscripten-platform.patch +11 -0
  35. package/sources/engine/wasm-source/patches/0025-browser-editing.patch +18 -0
  36. package/sources/engine/wasm-source/patches/0028-synchronous-workbook-calculation.patch +64 -0
  37. package/sources/engine/wasm-source/patches/0029-unloaded-external-blip.patch +21 -0
  38. package/sources/engine/wasm-source/patches/0030-no-password-strength-ui.patch +117 -0
  39. package/sources/engine/wasm-source/patches/0031-size-optimization-lto.patch +26 -0
  40. package/sources/engine/wasm-source/patches/0047-defer-offscreen-canvas-output.patch +59 -0
  41. package/sources/engine/wasm-source/slim.mjs +74 -0
  42. package/sources/engine/wasm-source/source.json +16 -0
  43. package/sources/engine/wasm-source/source.mjs +12 -0
  44. package/sources/engine/wasm-source/stage.mjs +91 -0
  45. package/sources/scripts/checkout-wasm.mjs +24 -0
  46. package/sources/scripts/core-checkout.mjs +39 -0
  47. package/sources/scripts/minimize-ui-resources.py +198 -0
  48. package/sources/scripts/pack-utils.mjs +69 -0
  49. package/sources/scripts/platform-matrix.mjs +122 -0
  50. package/sources/scripts/verify-artifacts.mjs +261 -0
  51. package/sources/source-changes.patch +1081 -0
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env python3
2
+ """Requalify the headless .ui allowlist with a real native helper and Poppler.
3
+
4
+ Only an isolated copy is changed. Baseline and every deletion trial use a fresh
5
+ process, profile and PDF per input, and compare page geometry, text and word boxes.
6
+ The result is corpus-specific, not proof for every document or backend.
7
+ """
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import platform
14
+ import shutil
15
+ import subprocess
16
+ import tempfile
17
+ import xml.etree.ElementTree as ET
18
+
19
+
20
+ FORMATS = {'.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'}
21
+
22
+
23
+ def digest(data):
24
+ return hashlib.sha256(data).hexdigest()
25
+
26
+
27
+ def word_layout(xml):
28
+ root = ET.fromstring(xml)
29
+ pages = []
30
+ for page in root.iter('{http://www.w3.org/1999/xhtml}page'):
31
+ words = [(word.attrib, word.text or '')
32
+ for word in page.iter('{http://www.w3.org/1999/xhtml}word')]
33
+ pages.append((page.attrib, words))
34
+ if not pages or not any(words for _, words in pages):
35
+ raise ValueError('PDF has no extractable words; use a text-bearing corpus')
36
+ # Ignore PDF producer/time metadata, but preserve page/word order and boxes.
37
+ return digest(json.dumps(pages, sort_keys=True, ensure_ascii=False).encode())
38
+
39
+
40
+ def greedy_minimize(paths, attempt):
41
+ """Try directories first, then files; revisit retained files until stable."""
42
+ retained = set(paths)
43
+ directories = {parent.as_posix() for name in paths
44
+ for parent in Path(name).parents if parent != Path('.')}
45
+ for directory in sorted(directories, key=lambda name: (name.count('/'), name)):
46
+ group = sorted(name for name in retained if name.startswith(directory + '/'))
47
+ if group and attempt(group):
48
+ retained.difference_update(group)
49
+ changed = True
50
+ while changed:
51
+ changed = False
52
+ for name in sorted(retained):
53
+ if attempt([name]):
54
+ retained.remove(name)
55
+ changed = True
56
+ return sorted(retained)
57
+
58
+
59
+ def main():
60
+ parser = argparse.ArgumentParser(description=__doc__)
61
+ parser.add_argument('--package', type=Path, required=True, help='native engine package')
62
+ parser.add_argument('--ui-source', type=Path, required=True,
63
+ help='complete, unpruned soffice.cfg from the same Core build')
64
+ parser.add_argument('--fixtures', type=Path, required=True, help='directory covering all six Office formats')
65
+ parser.add_argument('--output', type=Path, required=True, help='new evidence directory')
66
+ parser.add_argument('--mode', choices=['minimize', 'verify'], default='minimize')
67
+ parser.add_argument('--timeout', type=int, default=90, help='seconds per helper or Poppler call')
68
+ parser.add_argument('--font-file', type=Path, action='append', default=[])
69
+ args = parser.parse_args()
70
+ if args.timeout <= 0:
71
+ parser.error('--timeout must be positive')
72
+ package, source, corpus, output = [path.resolve() for path in
73
+ (args.package, args.ui_source, args.fixtures, args.output)]
74
+ for path in [package, source, corpus]:
75
+ if path == output or path in output.parents or output in path.parents:
76
+ parser.error('--output must be separate from all input directories')
77
+ manifest = json.loads((package / 'prebuilds.json').read_text())
78
+ if manifest['engine']['kind'] != 'native':
79
+ parser.error('minimization requires a matching-host native engine')
80
+ def package_path(name):
81
+ path = Path(name)
82
+ if path.is_absolute() or '..' in path.parts:
83
+ parser.error('engine paths must be package-relative')
84
+ return path
85
+ program = package_path(manifest['engine']['programDirectory'])
86
+ helper = package_path(manifest['engine']['executable'])
87
+ ui_relative = program.parent / ('Resources' if manifest['platform'].startswith('darwin-') else 'share') / 'config/soffice.cfg'
88
+ inputs = sorted(path for path in corpus.rglob('*') if path.suffix.lower() in FORMATS and path.is_file())
89
+ if {path.suffix.lower() for path in inputs} != FORMATS:
90
+ parser.error('the corpus must contain DOC/DOCX/XLS/XLSX/PPT/PPTX')
91
+ layouts = sorted(path.relative_to(source).as_posix() for path in source.rglob('*.ui') if path.is_file())
92
+ policy = Path(__file__).resolve().parents[1] / 'engine/ui-resource-policy.mjs'
93
+ expected = json.loads(subprocess.check_output([
94
+ 'node', '--input-type=module', '-e',
95
+ 'const m = await import(process.argv[1]); console.log(JSON.stringify(m.requiredUiResources));',
96
+ policy.as_uri()], text=True))
97
+ if len(layouts) <= len(expected) or (args.mode == 'verify' and not set(expected) < set(layouts)):
98
+ parser.error('--ui-source must include the required layouts and the unpruned layouts')
99
+ fonts = [path.resolve(strict=True) for path in args.font_file]
100
+ # Keep only OS execution settings; do not pass credentials or loader overrides.
101
+ env = {key: value for key, value in os.environ.items() if key in {
102
+ 'PATH', 'HOME', 'TMPDIR', 'TEMP', 'TMP', 'SystemRoot', 'WINDIR',
103
+ 'LANG', 'LC_ALL', 'TZ', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA'}}
104
+ poppler = subprocess.run(['pdftotext', '-v'], capture_output=True, env=env, check=True)
105
+ output.mkdir(parents=True, exist_ok=False)
106
+ candidate = output / 'candidate'
107
+ candidate.mkdir()
108
+ for name in ['bin', 'program']:
109
+ shutil.copytree(package / name, candidate / name, symlinks=False)
110
+ ui = candidate / ui_relative
111
+ shutil.rmtree(ui, ignore_errors=True)
112
+ shutil.copytree(source, ui, symlinks=False)
113
+ inventory = {name: {'bytes': (source / name).stat().st_size,
114
+ 'sha256': digest((source / name).read_bytes())} for name in layouts}
115
+ evidence = {
116
+ 'mode': args.mode, 'coreRevision': manifest['source']['revision'],
117
+ 'platform': manifest['platform'], 'host': platform.platform(),
118
+ 'helperSha256': digest((candidate / helper).read_bytes()),
119
+ 'packageManifestSha256': digest((package / 'prebuilds.json').read_bytes()),
120
+ 'policySha256': digest(policy.read_bytes()),
121
+ 'poppler': (poppler.stdout + poppler.stderr).decode().splitlines()[0],
122
+ 'fonts': [{'name': path.name, 'sha256': digest(path.read_bytes())} for path in fonts],
123
+ 'inputs': [{'file': path.relative_to(corpus).as_posix(), 'sha256': digest(path.read_bytes())} for path in inputs],
124
+ 'originalUi': inventory, 'trials': [],
125
+ }
126
+ def save():
127
+ (output / 'report.json').write_text(json.dumps(evidence, indent=2) + '\n')
128
+ def convert_all(label):
129
+ fingerprints = []
130
+ with tempfile.TemporaryDirectory(prefix='conversion-', dir=output) as work:
131
+ for index, path in enumerate(inputs):
132
+ pdf = Path(work) / f'{index}.pdf'
133
+ command = [str(candidate / helper), '--program-directory', str(candidate / program),
134
+ '--input-path', str(path), '--output-path', str(pdf),
135
+ '--profile-directory', str(Path(work) / f'profile-{index}'),
136
+ '--max-output-bytes', str(512 * 1024 * 1024), '--max-image-resolution', '192']
137
+ for font in fonts:
138
+ command += ['--font-file', str(font)]
139
+ for tool, argv in [('helper', command), ('pdftotext', ['pdftotext', '-bbox', str(pdf), '-'])]:
140
+ try:
141
+ result = subprocess.run(argv, capture_output=True, timeout=args.timeout, env=env)
142
+ except subprocess.TimeoutExpired as error:
143
+ raise RuntimeError(f'{path.name}: {tool} timeout') from error
144
+ if result.returncode:
145
+ (output / f'{label}-{index}-{tool}.log').write_bytes(result.stdout + result.stderr)
146
+ raise RuntimeError(f'{path.name}: {tool} exit {result.returncode}')
147
+ if label.startswith('baseline'):
148
+ (output / f'{label}-{index}.xml').write_bytes(result.stdout)
149
+ fingerprints.append(word_layout(result.stdout))
150
+ return fingerprints
151
+ save()
152
+ baseline = convert_all('baseline')
153
+ repeated = convert_all('baseline-repeat')
154
+ if repeated != baseline:
155
+ unstable = [inputs[index].name for index, value in enumerate(repeated) if value != baseline[index]]
156
+ raise RuntimeError(f'Baseline text/word coordinates are not deterministic: {unstable}; inspect baseline XML files')
157
+ evidence['baselineLayoutSha256'] = baseline
158
+ save()
159
+ def attempt(group):
160
+ for name in group:
161
+ (ui / name).unlink()
162
+ accepted = False
163
+ failure = None
164
+ try:
165
+ accepted = convert_all(f'trial-{len(evidence["trials"])}') == baseline
166
+ if not accepted:
167
+ failure = 'page geometry, text or word coordinates changed'
168
+ except (RuntimeError, ValueError, ET.ParseError) as error:
169
+ failure = str(error)
170
+ finally:
171
+ if not accepted:
172
+ for name in group:
173
+ shutil.copyfile(source / name, ui / name)
174
+ evidence['trials'].append({'removed': group, 'accepted': accepted, 'failure': failure})
175
+ save()
176
+ print(f'trial {len(evidence["trials"])}: {"removed" if accepted else "retained"} {len(group)} layouts', flush=True)
177
+ return accepted
178
+ if args.mode == 'verify':
179
+ if not attempt(sorted(set(layouts) - set(expected))):
180
+ raise RuntimeError('The checked-in allowlist failed conversion equivalence')
181
+ retained = sorted(expected)
182
+ else:
183
+ retained = greedy_minimize(layouts, attempt)
184
+ if convert_all('final') != baseline:
185
+ raise RuntimeError('Final conversion differs from baseline')
186
+ evidence.update(retainedUi=retained, matchesAllowlist=retained == sorted(expected),
187
+ removedFiles=len(layouts) - len(retained),
188
+ removedBytes=sum(item['bytes'] for name, item in inventory.items() if name not in retained),
189
+ retainedBytes=sum(inventory[name]['bytes'] for name in retained),
190
+ finalLayoutSha256=baseline, status='complete')
191
+ save()
192
+ print(json.dumps({key: evidence[key] for key in ['retainedUi', 'matchesAllowlist', 'removedFiles', 'removedBytes', 'retainedBytes']}))
193
+ if not evidence['matchesAllowlist']:
194
+ raise SystemExit('Minimized layouts differ: review report.json and update the policy before packaging')
195
+
196
+
197
+ if __name__ == '__main__':
198
+ main()
@@ -0,0 +1,69 @@
1
+ /** Local-only npm helpers shared by packaging and offline-install rehearsals. */
2
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
3
+ import { delimiter, dirname, join, resolve } from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { root } from './platform-matrix.mjs';
6
+
7
+ export function scratch(prefix = 'packaging-') {
8
+ const parent = join(root, '.cache');
9
+ mkdirSync(parent, { recursive: true });
10
+ return mkdtempSync(join(parent, prefix));
11
+ }
12
+
13
+ export function run(command, args, options = {}) {
14
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 180_000, maxBuffer: 16 * 1024 * 1024, ...options });
15
+ if (result.error) throw result.error;
16
+ if (result.status !== 0) throw new Error(`${command} exited ${result.status} (${result.signal ?? 'no signal'}):\n${result.stderr}\n${result.stdout}`);
17
+ return result.stdout;
18
+ }
19
+
20
+ /** Invoke npm's JS CLI directly, including on Windows; no command shell is used. */
21
+ export function npmCli() {
22
+ const directories = [dirname(process.execPath), dirname(realpathSync(process.execPath)), ...(process.env.PATH ?? '').split(delimiter)];
23
+ const candidates = [process.env.npm_execpath];
24
+ for (const directory of directories) {
25
+ candidates.push(join(directory, 'node_modules/npm/bin/npm-cli.js'), resolve(directory, '../lib/node_modules/npm/bin/npm-cli.js'));
26
+ const link = join(directory, 'npm');
27
+ if (existsSync(link)) candidates.push(realpathSync(link));
28
+ }
29
+ const found = candidates.find((file) => file && /(?:^|[\\/])npm-cli\.js$/.test(file) && existsSync(file));
30
+ if (!found) throw new Error('npm-cli.js was not found next to Node or on PATH');
31
+ return found;
32
+ }
33
+
34
+ export function npmEnvironment(work) {
35
+ const config = join(work, 'empty.npmrc');
36
+ const globalConfig = join(work, 'empty-global.npmrc');
37
+ writeFileSync(config, '');
38
+ writeFileSync(globalConfig, '');
39
+ return {
40
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !/KEY|TOKEN|SECRET|PASSWORD|^NODE_OPTIONS$|^NODE_PATH$|^NPM_CONFIG_/i.test(key))),
41
+ npm_config_cache: join(work, 'npm-cache'),
42
+ npm_config_userconfig: config,
43
+ npm_config_globalconfig: globalConfig,
44
+ npm_config_audit: 'false',
45
+ npm_config_fund: 'false',
46
+ npm_config_update_notifier: 'false',
47
+ npm_config_registry: 'http://127.0.0.1:9',
48
+ npm_config_offline: 'true',
49
+ };
50
+ }
51
+
52
+ export function npm(args, cwd, work) {
53
+ return run(process.execPath, [npmCli(), ...args], { cwd, env: npmEnvironment(work) });
54
+ }
55
+
56
+ /** Resolve pnpm without invoking a Windows command shim through a shell. */
57
+ export function pnpmInvocation(args, environment = process.env, platform = process.platform) {
58
+ const entry = environment.npm_execpath;
59
+ if (entry && /(?:^|[\\/])pnpm\.[cm]?js$/i.test(entry)) return { command: process.execPath, args: [entry, ...args] };
60
+ if (entry && /(?:^|[\\/])pnpm(?:\.exe)?$/i.test(entry)) return { command: entry, args };
61
+ if (platform === 'win32') throw new Error('Invoke adapter builds and local packs through pnpm run on Windows.');
62
+ return { command: 'pnpm', args };
63
+ }
64
+
65
+ /** Run the pnpm lifecycle executable, retaining each argument without shell parsing. */
66
+ export function pnpm(args, options = {}) {
67
+ const invocation = pnpmInvocation(args);
68
+ return run(invocation.command, invocation.args, options);
69
+ }
@@ -0,0 +1,122 @@
1
+ /** Package metadata shared by release tooling; runtime selection belongs to the adapter package. */
2
+ import { readFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const root = fileURLToPath(new URL('../', import.meta.url));
7
+ export const enginePrefix = '@unieai/libreoffice-kit';
8
+ /** Internal repository hosting qualified engine archives for application builds. */
9
+ export const releaseRepository = 'rabi-harness/libreoffice-kit';
10
+ /** Repository maintaining the source and Actions builds referenced by release evidence. */
11
+ export const sourceRepository = releaseRepository;
12
+ /**
13
+ * Public mirror whose master fast-forwards from the source repository's `public` branch.
14
+ * Package manifests name it, and npm records provenance only for its publications.
15
+ */
16
+ export const publicRepository = 'UnieAI/rabi-libreoffice-kit';
17
+ /** Repositories whose publish workflow may hold an npm trusted publisher. */
18
+ export const npmPublishingRepositories = Object.freeze([sourceRepository, publicRepository]);
19
+ export const wasmName = `${enginePrefix}-wasm`;
20
+ export const kitPackageName = '@unieai/libreoffice-kit';
21
+ export const nodeRange = '>=22.19.0';
22
+ export const targets = Object.freeze({
23
+ 'darwin-arm64': { os: 'darwin', cpu: 'arm64', runner: 'macos-15' },
24
+ 'darwin-x64': { os: 'darwin', cpu: 'x64', runner: 'macos-15-intel' },
25
+ 'linux-arm64-glibc': { os: 'linux', cpu: 'arm64', libc: 'glibc', runner: 'ubuntu-24.04-arm' },
26
+ 'linux-x64-glibc': { os: 'linux', cpu: 'x64', libc: 'glibc', runner: 'ubuntu-24.04' },
27
+ 'win32-arm64': { os: 'win32', cpu: 'arm64', runner: 'windows-11-arm' },
28
+ 'win32-x64': { os: 'win32', cpu: 'x64', runner: 'windows-2022' },
29
+ });
30
+
31
+ /** Exact package version selected for a platform by this checkout. */
32
+ export function engineVersion(platform, repo = root) {
33
+ if (platform !== 'wasm' && !Object.hasOwn(targets, platform)) throw new Error(`Unknown engine platform: ${platform}`);
34
+ return readJson(join(repo, 'packages', platform, 'package.json')).version;
35
+ }
36
+
37
+ export function readJson(file) {
38
+ return JSON.parse(readFileSync(file, 'utf8'));
39
+ }
40
+
41
+ /** The adapter package directory in this checkout; it declares this family's released engine targets. */
42
+ export function kitDirectory(repo = root) {
43
+ return join(repo, 'packages/entry');
44
+ }
45
+
46
+ /** The adapter package manifest that declares this family's released engine targets. */
47
+ export function kitManifest(repo = root) {
48
+ return readJson(join(kitDirectory(repo), 'package.json'));
49
+ }
50
+
51
+ /** Release tags identify this standalone kit family. */
52
+ export function releaseTag(version) {
53
+ return `libreoffice-kit-v${version}`;
54
+ }
55
+
56
+ /** Prerelease candidates may have immutable revisions while retaining an unpublished npm version. */
57
+ export function matchesReleaseTag(tag, version) {
58
+ const base = releaseTag(version);
59
+ return tag === base || (version.includes('-') && typeof tag === 'string'
60
+ && tag.startsWith(`${base}+candidate.`) && /^[1-9]\d*$/.test(tag.slice(`${base}+candidate.`.length)));
61
+ }
62
+
63
+ /** Retained 0.1.x helpers provide conversion and raster output without the native preview protocol. */
64
+ export function supportsNativePreview(record) {
65
+ return record.platform !== 'wasm' && !['0.1.1', '0.1.5'].includes(record.version);
66
+ }
67
+
68
+ /**
69
+ * Versioned download URL for one engine archive attached to the family release.
70
+ * @param version - Engine family version.
71
+ * @param file - Release asset file name.
72
+ * @returns the asset URL, requiring authenticated build-time preparation for internal releases.
73
+ */
74
+ export function releaseAssetUrl(version, file) {
75
+ return `https://github.com/${releaseRepository}/releases/download/${releaseTag(version)}/${encodeURIComponent(file)}`;
76
+ }
77
+
78
+ /** Return the complete declared matrix, including targets without built assets. */
79
+ export function packageMatrix(repo = root) {
80
+ return [...Object.keys(targets), 'wasm'].sort().map((platform) => {
81
+ const dir = join(repo, 'packages', platform);
82
+ return { dir, manifest: readJson(join(dir, 'package.json')), prebuild: readJson(join(dir, 'prebuilds.json')) };
83
+ });
84
+ }
85
+
86
+ /** An unrecognized Linux libc is deliberately not treated as glibc. */
87
+ export function hostTarget(platform = process.platform, arch = process.arch, report = process.report?.getReport()) {
88
+ if (platform !== 'linux') return Object.hasOwn(targets, `${platform}-${arch}`) ? `${platform}-${arch}` : undefined;
89
+ if (!report?.header?.glibcVersionRuntime) return undefined;
90
+ const candidate = `${platform}-${arch}-glibc`;
91
+ return Object.hasOwn(targets, candidate) ? candidate : undefined;
92
+ }
93
+
94
+ /** The adapter declares released native packages; targets also contains unfinished build recipes. */
95
+ export function kitNativeTargets(manifest) {
96
+ return Object.keys(manifest.optionalDependencies ?? {}).filter(name => name !== wasmName && name !== 'koffi').map((name) => {
97
+ const platform = name.slice(enginePrefix.length + 1);
98
+ if (!name.startsWith(`${enginePrefix}-`) || !Object.hasOwn(targets, platform)) throw new Error(`Unknown native optional dependency: ${name}`);
99
+ return platform;
100
+ });
101
+ }
102
+
103
+ /** Explicit development scopes may select a build recipe; defaults use the adapter's release declaration. */
104
+ export function releaseTargets(args, nativeTargets = kitNativeTargets(kitManifest())) {
105
+ const wasmOnly = args.includes('--wasm-only');
106
+ const index = args.indexOf('--platform');
107
+ if (wasmOnly && index !== -1) throw new Error('--wasm-only and --platform are mutually exclusive');
108
+ if (index !== -1) {
109
+ const platform = args[index + 1];
110
+ if (!Object.hasOwn(targets, platform)) throw new Error(`Unknown native platform: ${platform}`);
111
+ return [platform, 'wasm'];
112
+ }
113
+ return wasmOnly ? ['wasm'] : [...nativeTargets, 'wasm'];
114
+ }
115
+
116
+ export function tarballName(manifest) {
117
+ return `${manifest.name.replace(/^@/, '').replace('/', '-')}-${manifest.version}.tgz`;
118
+ }
119
+
120
+ export function isMain(url) {
121
+ return process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(url);
122
+ }
@@ -0,0 +1,261 @@
1
+ /** Validate staged or installed engine packages without compiling or downloading. */
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
4
+ import { join, resolve } from 'node:path';
5
+ import { enginePrefix, isMain, nodeRange, readJson, targets } from './platform-matrix.mjs';
6
+
7
+ const hashPattern = /^[a-f0-9]{64}$/;
8
+ const payloadRoots = ['assets', 'bin', 'program', 'sources', 'licenses'];
9
+
10
+ export function assert(condition, message) {
11
+ if (!condition) throw new Error(message);
12
+ }
13
+
14
+ export function sha256(file) {
15
+ const hash = createHash('sha256');
16
+ const fd = openSync(file, 'r');
17
+ const chunk = Buffer.alloc(1024 * 1024);
18
+ try {
19
+ for (let count; (count = readSync(fd, chunk)) !== 0;) hash.update(chunk.subarray(0, count));
20
+ } finally { closeSync(fd); }
21
+ return hash.digest('hex');
22
+ }
23
+
24
+ /** Manifest paths are POSIX relative paths on every host, including Windows. */
25
+ export function safePath(value) {
26
+ assert(typeof value === 'string' && value.length > 0 && !/[\\:\x00-\x1f]/.test(value)
27
+ && !value.split('/').some((part) => part === '' || part === '.' || part === '..'), `Unsafe package path: ${value}`);
28
+ return value;
29
+ }
30
+
31
+ export function regularFile(dir, relative) {
32
+ safePath(relative);
33
+ const parts = relative.split('/');
34
+ for (let index = 1; index <= parts.length; index++) {
35
+ const file = join(dir, ...parts.slice(0, index));
36
+ let stat;
37
+ try { stat = lstatSync(file); }
38
+ catch (error) {
39
+ if (error.code !== 'ENOENT') throw error;
40
+ throw new Error(`Missing package artifact: ${relative}`, { cause: error });
41
+ }
42
+ assert(index === parts.length ? stat.isFile() : stat.isDirectory(), `Not a regular package file/directory: ${relative}`);
43
+ }
44
+ return join(dir, ...parts);
45
+ }
46
+
47
+ function inventory(dir, prefix) {
48
+ let entries;
49
+ try { entries = readdirSync(join(dir, prefix), { withFileTypes: true }); }
50
+ catch (error) {
51
+ if (error.code === 'ENOENT') return [];
52
+ throw error;
53
+ }
54
+ assert(lstatSync(join(dir, prefix)).isDirectory(), `Not a regular payload directory: ${prefix}`);
55
+ return entries.flatMap((entry) => {
56
+ const name = prefix ? `${prefix}/${entry.name}` : entry.name;
57
+ assert(entry.isFile() || entry.isDirectory(), `Symlink or special payload file: ${name}`);
58
+ return entry.isDirectory() ? inventory(dir, name) : [name];
59
+ });
60
+ }
61
+
62
+ export function verifyNoInstallHooks(manifest, allowWorkspace = false) {
63
+ for (const hook of ['preinstall', 'install', 'postinstall', 'prepare']) {
64
+ assert(!Object.hasOwn(manifest.scripts ?? {}, hook), `${manifest.name}: forbidden install lifecycle ${hook}`);
65
+ }
66
+ assert(manifest.gypfile !== true && manifest.bin === undefined, `${manifest.name}: engine packages must not register install builds or CLI bins`);
67
+ for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
68
+ for (const [name, version] of Object.entries(manifest[field] ?? {})) {
69
+ assert(/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version) || (allowWorkspace && name.startsWith(`${enginePrefix}-`) && version === 'workspace:*'), `${manifest.name}: ${field} must pin a published version: ${name}`);
70
+ }
71
+ }
72
+ }
73
+
74
+ /** Validate metadata independently of whether the target has been built. */
75
+ export function verifyEngineMetadata(manifest, prebuild) {
76
+ verifyNoInstallHooks(manifest);
77
+ assert(manifest.type === 'module' && manifest.engines?.node === nodeRange, 'Engine package requires ESM and the declared Node baseline');
78
+ assert(manifest.exports?.['./prebuilds.json'] === './prebuilds.json'
79
+ && manifest.exports?.['./package.json'] === './package.json', 'Engine package must export prebuilds.json and package.json');
80
+ assert(prebuild.schemaVersion === 1 && ['unbuilt', 'built'].includes(prebuild.status), 'Unsupported engine schema/status');
81
+ assert(prebuild.version === manifest.version && manifest.name === `${enginePrefix}-${prebuild.platform}`, 'Engine package identity/version mismatch');
82
+ const target = targets[prebuild.platform];
83
+ const engine = prebuild.engine;
84
+ if (engine?.glibcMinimum !== undefined) {
85
+ assert(target?.libc === 'glibc' && typeof engine.glibcMinimum === 'string'
86
+ && /^(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?$/.test(engine.glibcMinimum)
87
+ && engine.glibcMinimum.split('.').every(part => Number.isSafeInteger(Number(part))), 'Invalid native glibcMinimum');
88
+ }
89
+ const exact = (actual, expected) => JSON.stringify(actual) === JSON.stringify(expected);
90
+ if (prebuild.platform === 'wasm') {
91
+ assert(manifest.os === undefined && manifest.cpu === undefined && manifest.libc === undefined, 'WASM package must install on every OS, CPU and libc');
92
+ assert(engine?.kind === 'wasm' && engine.loader === 'assets/dsoffice.cjs' && engine.wasm === 'assets/dsoffice.wasm'
93
+ && engine.data === 'assets/dsoffice.data' && engine.metadata === 'assets/dsoffice.data.js.metadata'
94
+ && engine.programDirectory === '/instdir/program', 'Unsupported WASM engine paths');
95
+ } else {
96
+ assert(target && exact(manifest.os, [target.os]) && exact(manifest.cpu, [target.cpu])
97
+ && (target.libc ? exact(manifest.libc, [target.libc]) : manifest.libc === undefined), 'Native platform disagrees with package os/cpu/libc');
98
+ assert(engine?.kind === 'native' && engine.executable === `bin/dsoffice${target.os === 'win32' ? '.exe' : ''}`
99
+ && typeof engine.programDirectory === 'string' && (engine.programDirectory === 'program' || engine.programDirectory.startsWith('program/')), 'Unsupported native engine paths');
100
+ safePath(engine.programDirectory);
101
+ }
102
+ assert(prebuild.files && typeof prebuild.files === 'object' && !Array.isArray(prebuild.files), 'Engine files must be a hash inventory');
103
+ for (const [file, hash] of Object.entries(prebuild.files)) {
104
+ safePath(file);
105
+ assert(payloadRoots.includes(file.split('/')[0]) && hashPattern.test(hash), `Invalid file inventory entry: ${file}`);
106
+ }
107
+ assert(Array.isArray(prebuild.licenses), 'Engine licenses must be an array');
108
+ if (prebuild.status === 'unbuilt') {
109
+ assert(Object.keys(prebuild.files).length === 0 && prebuild.source === null && prebuild.licenses.length === 0,
110
+ 'Unbuilt target must not claim built files or source/license receipts');
111
+ return;
112
+ }
113
+ const source = prebuild.source;
114
+ assert(source && /^https:\/\//.test(source.repository) && /^[a-f0-9]{40}$/.test(source.revision)
115
+ && typeof source.version === 'string' && source.version.length > 0 && Array.isArray(source.files) && source.files.length > 0,
116
+ 'Built engine requires source repository, full revision, version, and packaged build inputs');
117
+ assert(new Set(source.files).size === source.files.length, 'Duplicate source manifest paths');
118
+ for (const file of source.files) assert(file.startsWith('sources/') && Object.hasOwn(prebuild.files, file), `Missing hashed source: ${file}`);
119
+ assert(prebuild.licenses.some((license) => license.component === 'LibreOffice' && license.spdx === 'MPL-2.0'), 'Missing LibreOffice MPL-2.0 license');
120
+ for (const license of prebuild.licenses) {
121
+ assert(typeof license.component === 'string' && license.component.length > 0 && typeof license.spdx === 'string' && license.spdx.length > 0
122
+ && typeof license.path === 'string' && license.path.startsWith('licenses/') && Object.hasOwn(prebuild.files, license.path), 'Missing hashed redistribution license');
123
+ }
124
+ }
125
+
126
+ /** Header-only checks accept minimal test fixtures; they are not release validation. */
127
+ export function verifyNativeHeader(bytes, platform, shared = false) {
128
+ const target = targets[platform];
129
+ assert(target, `Unknown native target: ${platform}`);
130
+ if (target.os === 'linux') {
131
+ assert(bytes.length >= 64 && bytes.readUInt32LE(0) === 0x464c457f && bytes[4] === 2 && bytes[5] === 1, 'Expected little-endian ELF64 image');
132
+ assert(bytes.readUInt16LE(18) === (target.cpu === 'x64' ? 62 : 183), 'Wrong ELF architecture');
133
+ assert((shared ? [3] : [2, 3]).includes(bytes.readUInt16LE(16)), 'Wrong ELF executable/library type');
134
+ } else if (target.os === 'darwin') {
135
+ assert(bytes.length >= 32 && bytes.readUInt32LE(0) === 0xfeedfacf, 'Expected thin Mach-O 64-bit image');
136
+ assert(bytes.readUInt32LE(4) === (target.cpu === 'x64' ? 0x01000007 : 0x0100000c), 'Wrong Mach-O architecture');
137
+ assert((shared ? [6, 8] : [2]).includes(bytes.readUInt32LE(12)), 'Wrong Mach-O executable/library type');
138
+ } else {
139
+ assert(bytes.length >= 64 && bytes.readUInt16LE(0) === 0x5a4d, 'Expected PE executable');
140
+ const pe = bytes.readUInt32LE(60);
141
+ assert(pe >= 64 && pe + 26 <= bytes.length && bytes.readUInt32LE(pe) === 0x4550, 'Truncated or invalid PE header');
142
+ assert(bytes.readUInt16LE(pe + 4) === (target.cpu === 'x64' ? 0x8664 : 0xaa64), 'Wrong PE architecture');
143
+ assert(bytes.readUInt16LE(pe + 24) === 0x20b && (bytes.readUInt16LE(pe + 22) & 0x2002) === (shared ? 0x2002 : 2), 'Wrong PE32+ executable/DLL type');
144
+ }
145
+ }
146
+
147
+ /** Require executable code records in addition to the format/architecture header. */
148
+ export function verifyNativeImage(file, platform, shared = false) {
149
+ const bytes = readFileSync(file);
150
+ verifyNativeHeader(bytes, platform, shared);
151
+ const target = targets[platform];
152
+ if (process.platform !== 'win32' && target.os !== 'win32') assert((statSync(file).mode & 0o111) !== 0, 'Native engine is not executable');
153
+ if (target.os === 'linux') {
154
+ const offset = Number(bytes.readBigUInt64LE(32));
155
+ const width = bytes.readUInt16LE(54);
156
+ const count = bytes.readUInt16LE(56);
157
+ assert((shared || bytes.readBigUInt64LE(24) !== 0n) && width >= 56 && count > 0 && offset >= 64 && offset + width * count <= bytes.length, 'ELF image has no executable program table');
158
+ let code = false;
159
+ let interpreter;
160
+ for (let index = 0; index < count; index++) {
161
+ const record = offset + index * width;
162
+ const kind = bytes.readUInt32LE(record);
163
+ const start = Number(bytes.readBigUInt64LE(record + 8));
164
+ const size = Number(bytes.readBigUInt64LE(record + 32));
165
+ assert(start >= 0 && size >= 0 && start + size <= bytes.length, 'ELF segment outside image');
166
+ if (kind === 1 && (bytes.readUInt32LE(record + 4) & 1) && size > 0) code = true;
167
+ if (kind === 3) interpreter = bytes.subarray(start, start + size).toString('utf8').replace(/\0.*$/, '');
168
+ }
169
+ assert(code, 'ELF image has no executable segment');
170
+ if (interpreter) assert(/ld-linux/.test(interpreter), 'ELF interpreter disagrees with declared libc');
171
+ } else if (target.os === 'darwin') {
172
+ const count = bytes.readUInt32LE(16);
173
+ const size = bytes.readUInt32LE(20);
174
+ assert(count > 0 && size >= count * 8 && 32 + size <= bytes.length, 'Mach-O image has no load commands');
175
+ let offset = 32;
176
+ let code = false;
177
+ for (let index = 0; index < count; index++) {
178
+ assert(offset + 8 <= 32 + size, 'Truncated Mach-O load command');
179
+ const command = bytes.readUInt32LE(offset);
180
+ const length = bytes.readUInt32LE(offset + 4);
181
+ assert(length >= 8 && offset + length <= 32 + size, 'Invalid Mach-O load command');
182
+ if (command === 0x19 && length >= 72) {
183
+ const start = Number(bytes.readBigUInt64LE(offset + 40));
184
+ const lengthOnDisk = Number(bytes.readBigUInt64LE(offset + 48));
185
+ assert(start + lengthOnDisk <= bytes.length, 'Mach-O segment outside image');
186
+ if ((bytes.readUInt32LE(offset + 60) & 4) && lengthOnDisk > 0) code = true;
187
+ }
188
+ offset += length;
189
+ }
190
+ assert(code && offset === 32 + size, 'Mach-O image has no complete executable segment');
191
+ } else {
192
+ const pe = bytes.readUInt32LE(60);
193
+ const count = bytes.readUInt16LE(pe + 6);
194
+ const optionalSize = bytes.readUInt16LE(pe + 20);
195
+ const sections = pe + 24 + optionalSize;
196
+ assert(optionalSize >= 112 && count > 0 && sections + count * 40 <= bytes.length && (shared || bytes.readUInt32LE(pe + 40) !== 0), 'PE image has no executable sections');
197
+ let code = false;
198
+ for (let index = 0; index < count; index++) {
199
+ const record = sections + index * 40;
200
+ const size = bytes.readUInt32LE(record + 16);
201
+ const start = bytes.readUInt32LE(record + 20);
202
+ assert(start + size <= bytes.length, 'PE section outside image');
203
+ if ((bytes.readUInt32LE(record + 36) & 0x20000000) && size > 0) code = true;
204
+ }
205
+ assert(code, 'PE image has no executable code');
206
+ }
207
+ }
208
+
209
+ function verifyPayload(dir, prebuild, actual) {
210
+ const declared = Object.keys(prebuild.files).sort();
211
+ actual.sort();
212
+ assert(JSON.stringify(declared) === JSON.stringify(actual), 'Payload inventory contains missing or undeclared files');
213
+ for (const file of declared) assert(sha256(regularFile(dir, file)) === prebuild.files[file], `Artifact checksum mismatch: ${file}`);
214
+ for (const license of prebuild.licenses) assert(readFileSync(regularFile(dir, license.path), 'utf8').trim().length > 0, `Empty license: ${license.path}`);
215
+ }
216
+
217
+ /** Full payload gate: checksums, source/license closure, resources, and real engine exports. */
218
+ export function verifyEnginePackage(dir) {
219
+ const manifest = readJson(regularFile(dir, 'package.json'));
220
+ const prebuild = readJson(regularFile(dir, 'prebuilds.json'));
221
+ verifyEngineMetadata(manifest, prebuild);
222
+ assert(prebuild.status === 'built', `${prebuild.platform}: unbuilt target cannot be packed or released`);
223
+ verifyPayload(dir, prebuild, payloadRoots.flatMap((prefix) => inventory(dir, prefix)));
224
+ const declared = Object.keys(prebuild.files);
225
+ const engine = prebuild.engine;
226
+ if (engine.kind === 'native') {
227
+ verifyNativeImage(regularFile(dir, engine.executable), prebuild.platform);
228
+ assert(declared.some((file) => file.startsWith(`${engine.programDirectory}/`)), 'Native engine has no program resources');
229
+ } else {
230
+ for (const key of ['loader', 'wasm', 'data', 'metadata']) regularFile(dir, engine[key]);
231
+ const module = new WebAssembly.Module(readFileSync(join(dir, engine.wasm)));
232
+ const exports = new Set(WebAssembly.Module.exports(module).filter((entry) => entry.kind === 'function').map((entry) => entry.name.replace(/^_/, '')));
233
+ for (const name of ['rabi_lok_initialize', 'rabi_lok_document_load', 'rabi_lok_document_save_pdf',
234
+ 'rabi_lok_document_destroy', 'rabi_lok_destroy', 'rabi_lok_error', 'malloc', 'free']) {
235
+ assert(exports.has(name), `WASM engine missing conversion export: ${name}`);
236
+ }
237
+ const dataSize = statSync(join(dir, engine.data)).size;
238
+ const metadata = readJson(join(dir, engine.metadata));
239
+ assert(dataSize > 0 && Array.isArray(metadata.files) && metadata.files.length > 0, 'WASM data has no packaged resources');
240
+ const names = new Set();
241
+ const ranges = [];
242
+ for (const file of metadata.files) {
243
+ assert(typeof file.filename === 'string' && (file.filename.startsWith('/instdir/')
244
+ || ['/android/default-document/example.odt', '/android/default-document/example_test.ods'].includes(file.filename))
245
+ && !names.has(file.filename), 'Invalid or duplicate WASM resource path');
246
+ safePath(file.filename.slice(1));
247
+ names.add(file.filename);
248
+ assert(Number.isSafeInteger(file.start) && Number.isSafeInteger(file.end) && file.start >= 0 && file.end >= file.start && file.end <= dataSize, 'WASM resource outside data file');
249
+ ranges.push([file.start, file.end]);
250
+ }
251
+ ranges.sort((a, b) => a[0] - b[0]);
252
+ assert(ranges.every((range, index) => index === 0 || ranges[index - 1][1] <= range[0]), 'Overlapping WASM data ranges');
253
+ assert([...names].some((name) => name.startsWith(`${engine.programDirectory}/`)), 'WASM data lacks program resources');
254
+ assert(/\bmodule\[?[^;]*exports|\bmodule\.exports/.test(readFileSync(join(dir, engine.loader), 'utf8')), 'WASM loader must provide a Node CommonJS factory');
255
+ }
256
+ return { name: manifest.name, platform: prebuild.platform, files: declared.length };
257
+ }
258
+
259
+ if (isMain(import.meta.url)) {
260
+ console.log(JSON.stringify(verifyEnginePackage(resolve(process.argv[2] ?? '.'))));
261
+ }