drone-path 1.0.0-rc1 → 1.1.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.
package/README.md CHANGED
@@ -1,20 +1,24 @@
1
1
  # drone-path
2
2
 
3
- Render a flight-path map overlay video from a DJI recording with CAM-meta
4
- telemetry or a matching SRT sidecar. Use Node.js 24 or later.
3
+ Render flight-path map overlay videos from DJI recordings with CAM-meta
4
+ telemetry or a matching SRT sidecar, index and search a local recording library,
5
+ or expose your library to AI agents over an MCP server. Use Node.js 24 or later.
5
6
 
6
7
  ```sh
7
8
  npx drone-path "my-flight.mp4"
9
+ npx drone-path archive scan "./flights" --recurse --json
10
+ npx drone-path mcp --allow-root "./flights"
8
11
  npx drone-path --help
9
12
  ```
10
13
 
11
- By default, the command writes the overlay to `out/my-flight_map.mp4`.
14
+ By default, rendering writes the overlay to `out/my-flight_map.mp4`.
12
15
  See the [CLI guide](https://github.com/MrManny/drone-path/blob/main/docs/user/cli.md)
13
- for configuration, rendering requirements, and track export.
16
+ for configuration, archive search, MCP tools, rendering requirements, and track
17
+ export.
14
18
 
15
- The `drone-path` export provides typed CLI functions for Node.js. For
16
- telemetry and rendering APIs, use `drone-path-core` and
17
- `drone-path-engine`.
19
+ The `drone-path` export provides typed CLI functions for Node.js. For telemetry,
20
+ library indexing, and rendering APIs, use `drone-path-core`,
21
+ `drone-path-archive`, and `drone-path-engine`.
18
22
 
19
23
  Install `@types/node` for your Node.js major version. In TypeScript 6, list
20
24
  `node` in `compilerOptions.types` to load the Node declarations.
@@ -1,5 +1,7 @@
1
1
  # Third-party notices
2
2
 
3
- Commander is licensed under MIT and includes its license text in its npm
4
- package. See the notices shipped with `drone-path-core` and
5
- `drone-path-engine` for the telemetry and rendering dependencies.
3
+ Commander and Zod are licensed under MIT and ship their license texts in their
4
+ npm packages. `@modelcontextprotocol/server` and `@modelcontextprotocol/core` are
5
+ licensed under Apache-2.0 and ship their `LICENSE` files in their npm packages.
6
+ See the notices shipped with `drone-path-core` and `drone-path-engine` for the
7
+ telemetry and rendering dependencies.
@@ -0,0 +1 @@
1
+ export declare function runArchive(argv: string[]): Promise<void>;
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import { Command } from 'commander';
3
+ import { scanArchive } from 'drone-path-archive/indexed-scan';
4
+ import { archiveDbPath } from 'drone-path-archive/paths';
5
+ import { requireFfmpegTools } from 'drone-path-core/ffmpeg';
6
+ import { resolveFfmpegTools } from 'drone-path-core/ffmpeg-tools';
7
+ import { addArchiveQueries, archiveCommand } from './archive-query-cli.js';
8
+ export async function runArchive(argv) {
9
+ const program = new Command('drone-path archive')
10
+ .description('Inspect a library of drone recordings.')
11
+ .exitOverride();
12
+ const scan = archiveCommand(program.command('scan'))
13
+ .description('Scan folders for drone recordings.')
14
+ .argument('<dirs...>', 'folders to scan for recordings')
15
+ .option('--recurse', 'include subfolders')
16
+ .option('--prune', 'remove missing recordings from the index')
17
+ .option('--json', 'write one JSON record per clip to stdout')
18
+ .action(async (dirs) => {
19
+ const { recurse, json, archiveDb, prune } = scan.opts();
20
+ const controller = new AbortController();
21
+ const interrupt = () => controller.abort(new Error('archive scan canceled'));
22
+ process.on('SIGINT', interrupt);
23
+ try {
24
+ const records = await scanArchive(dirs, {
25
+ db: archiveDbPath(archiveDb), recurse, prune, signal: controller.signal,
26
+ getTools: async () => {
27
+ const tools = resolveFfmpegTools({ ffmpeg: null, ffprobe: null });
28
+ await requireFfmpegTools(tools, controller.signal);
29
+ return tools;
30
+ },
31
+ onRecord: (record) => {
32
+ process.stderr.write(`[drone-path] ${record.status}: ${record.path}\n`);
33
+ },
34
+ });
35
+ if (json)
36
+ for (const record of records)
37
+ fs.writeSync(1, JSON.stringify(record) + '\n');
38
+ process.stderr.write(`[drone-path] scanned ${records.length} recording(s)\n`);
39
+ }
40
+ catch (error) {
41
+ controller.signal.throwIfAborted();
42
+ throw error;
43
+ }
44
+ finally {
45
+ process.off('SIGINT', interrupt);
46
+ }
47
+ });
48
+ addArchiveQueries(program);
49
+ await program.parseAsync(argv, { from: 'user' });
50
+ }
@@ -0,0 +1,3 @@
1
+ import type { Command } from 'commander';
2
+ export declare function archiveCommand(command: Command): Command;
3
+ export declare function addArchiveQueries(program: Command): void;
@@ -0,0 +1,167 @@
1
+ import { Option } from 'commander';
2
+ import { exportArchiveMap, exportArchiveMarkers, exportArchiveTracks } from 'drone-path-archive/export';
3
+ import { archiveDbPath } from 'drone-path-archive/paths';
4
+ import { DEFAULT_RADIUS_M, listArchive, listArchiveFlights, listArchiveSegments, nearArchive, parseDateBound } from 'drone-path-archive/query';
5
+ import { SHOT_TYPES } from 'drone-path-core/shot-segmentation';
6
+ function decimal(text) {
7
+ const value = text.trim();
8
+ return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu.test(value) ? Number(value) : NaN;
9
+ }
10
+ function meters(text) {
11
+ const value = decimal(text);
12
+ if (!Number.isFinite(value) || value < 0)
13
+ throw new Error('expected a nonnegative distance in meters');
14
+ return value;
15
+ }
16
+ function availability(text) {
17
+ if (text !== 'online' && text !== 'offline')
18
+ throw new Error('expected online or offline status');
19
+ return text;
20
+ }
21
+ function smoothnessScore(text) {
22
+ const value = decimal(text);
23
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
24
+ throw new Error('expected a smoothness score between 0 and 1');
25
+ }
26
+ return value;
27
+ }
28
+ function point(text) {
29
+ const [lat, lon, extra] = text.split(',').map(decimal);
30
+ if (!(Math.abs(lat) <= 90 && Math.abs(lon) <= 180) || extra !== undefined) {
31
+ throw new Error('expected a latitude,longitude pair within ±90 and ±180 degrees');
32
+ }
33
+ return { lat, lon };
34
+ }
35
+ function bbox(text) {
36
+ const parts = text.split(',');
37
+ if (parts.length !== 4)
38
+ throw new Error('expected a bounding box as south,west,north,east');
39
+ const southWest = point(parts.slice(0, 2).join(','));
40
+ const northEast = point(parts.slice(2).join(','));
41
+ if (southWest.lat > northEast.lat)
42
+ throw new Error('expected south latitude at or below north latitude');
43
+ return { minLat: southWest.lat, minLon: southWest.lon, maxLat: northEast.lat, maxLon: northEast.lon };
44
+ }
45
+ function writeJson(value) {
46
+ process.stdout.write(JSON.stringify(value) + '\n');
47
+ }
48
+ function listOptions(options) {
49
+ const { inBbox, after, before, minDist, status, segmentType, minSmoothness } = options;
50
+ if (after !== undefined && before !== undefined && after > before) {
51
+ throw new Error('expected --after at or before --before');
52
+ }
53
+ return {
54
+ bbox: inBbox,
55
+ afterMs: after,
56
+ beforeMs: before,
57
+ minDistanceM: minDist,
58
+ availability: status,
59
+ ...(segmentType !== undefined ? { segmentType } : {}),
60
+ ...(minSmoothness !== undefined ? { minSmoothness } : {}),
61
+ };
62
+ }
63
+ export function archiveCommand(command) {
64
+ return command
65
+ .option('--archive-db <path>', 'override the per-user archive database path')
66
+ .exitOverride();
67
+ }
68
+ function queryOptions(command) {
69
+ return archiveCommand(command).option('--json', 'write a JSON array to stdout');
70
+ }
71
+ function listFilters(command) {
72
+ return command.option('--in-bbox <s,w,n,e>', 'filter clips by a viewport bounding box', bbox)
73
+ .option('--after <date>', 'earliest camera date or timestamp, inclusive', parseDateBound)
74
+ .option('--before <date>', 'latest camera date or timestamp, exclusive', parseDateBound)
75
+ .option('--min-dist <m>', 'minimum track distance in meters', meters)
76
+ .option('--status <state>', 'filter by online or offline availability', availability)
77
+ .addOption(new Option('--segment-type <type>', 'filter by kinematic shot segment type').choices([...SHOT_TYPES]))
78
+ .option('--min-smoothness <score>', 'minimum segment smoothness score between 0 and 1', smoothnessScore);
79
+ }
80
+ function exportOptions(command) {
81
+ return archiveCommand(listFilters(command))
82
+ .option('--redact-launch <m>', 'exclude geometry near the first and last indexed fix of each flight', meters);
83
+ }
84
+ export function addArchiveQueries(program) {
85
+ listFilters(queryOptions(program.command('list').description('List indexed recordings.')))
86
+ .addOption(new Option('--group-by <kind>', 'group matching clips into flights').choices(['flight']))
87
+ .action((options) => {
88
+ const db = archiveDbPath(options.archiveDb);
89
+ const filters = listOptions(options);
90
+ if (options.groupBy === 'flight') {
91
+ const flights = listArchiveFlights(db, filters);
92
+ if (options.json)
93
+ writeJson(flights);
94
+ else
95
+ for (const { flightId, clips } of flights) {
96
+ process.stdout.write(`Flight ${flightId}\n`);
97
+ for (const clip of clips) {
98
+ const continuation = clip.splitFromKey === null ? '' : ' (split continuation)';
99
+ process.stdout.write(` [${clip.availability}] ${clip.path}${continuation}\n`);
100
+ }
101
+ }
102
+ return;
103
+ }
104
+ if (options.segmentType !== undefined || options.minSmoothness !== undefined) {
105
+ const segments = listArchiveSegments(db, filters);
106
+ if (options.json)
107
+ writeJson(segments);
108
+ else
109
+ for (const segment of segments) {
110
+ const exposure = segment.exposureStable ? 'stable' : 'exposure-shift';
111
+ process.stdout.write(`${segment.type} ${segment.startSec.toFixed(1)}s-${segment.endSec.toFixed(1)}s ` +
112
+ `(smoothness ${segment.smoothness.toFixed(3)}, ${exposure}) ` +
113
+ `[${segment.clip.availability}] ${segment.clip.path}\n`);
114
+ }
115
+ return;
116
+ }
117
+ const clips = listArchive(db, filters);
118
+ if (options.json)
119
+ writeJson(clips);
120
+ else
121
+ for (const clip of clips)
122
+ process.stdout.write(`[${clip.availability}] ${clip.path}\n`);
123
+ });
124
+ queryOptions(program.command('near'))
125
+ .description('Find where indexed recordings pass near a location.')
126
+ // Commander treats a negative coordinate pair as an option, but the
127
+ // required argument parser still rejects anything besides a coordinate.
128
+ .allowUnknownOption()
129
+ .argument('<lat,lon>', 'query latitude and longitude', point)
130
+ .option('--radius <m>', 'search radius in meters', meters, DEFAULT_RADIUS_M)
131
+ .option('--include-gaze', 'also match points inside estimated camera ground footprints')
132
+ .action((location, options) => {
133
+ const hits = nearArchive(archiveDbPath(options.archiveDb), location, options.radius, options.includeGaze);
134
+ if (options.json)
135
+ writeJson(hits);
136
+ else
137
+ for (const hit of hits) {
138
+ const label = hit.matchType === 'gaze' ? 'in camera view' : `${hit.distanceM.toFixed(1)} m`;
139
+ process.stdout.write(`${label} at ${hit.tSec.toFixed(2)} s [${hit.clip.availability}] ${hit.clip.path}\n`);
140
+ }
141
+ });
142
+ exportOptions(program.command('export-map'))
143
+ .description('Write a standalone HTML map of matching flights.')
144
+ .argument('<out.html>', 'output HTML file')
145
+ .option('--include-gaze', 'show estimated camera ground footprints')
146
+ .action((output, options) => {
147
+ exportArchiveMap(archiveDbPath(options.archiveDb), output, {
148
+ filters: listOptions(options), redactLaunchM: options.redactLaunch, includeGaze: options.includeGaze,
149
+ });
150
+ });
151
+ exportOptions(program.command('export-tracks'))
152
+ .description('Write matching flight tracks in GPX, GeoJSON, KML, or KMZ format.')
153
+ .argument('<out>', 'output .gpx, .geojson, .kml, or .kmz file')
154
+ .action((output, options) => {
155
+ exportArchiveTracks(archiveDbPath(options.archiveDb), output, {
156
+ filters: listOptions(options), redactLaunchM: options.redactLaunch,
157
+ });
158
+ });
159
+ archiveCommand(listFilters(program.command('export-markers')))
160
+ .description('Write matching shot segments as DaVinci Resolve CSV or FCPXML markers.')
161
+ .argument('<out>', 'output .csv or .fcpxml file')
162
+ .action((output, options) => {
163
+ exportArchiveMarkers(archiveDbPath(options.archiveDb), output, {
164
+ filters: listOptions(options),
165
+ });
166
+ });
167
+ }
package/dist/cli.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import { Command, Option } from 'commander';
3
3
  import { ERROR_PREFIX, errorMessage } from 'drone-path-core/errors';
4
+ import { runArchive } from './archive-cli.js';
5
+ import { runExtractFrame } from './extract-frame-cli.js';
6
+ import { runMcp } from './mcp-cli.js';
4
7
  import { VERSION } from './version.js';
5
8
  import { CONFIG_FILE_OPTION, CONFIG_OPTIONS, OVERRIDE_NORMALIZERS, TELEMETRY_JSON_ALIAS, cliDefaultOf, } from 'drone-path-engine/config';
6
9
  import { resolveConfig } from 'drone-path-engine/configfile';
@@ -28,7 +31,7 @@ export function buildProgram() {
28
31
  }
29
32
  program.addOption(new Option(TELEMETRY_JSON_ALIAS.flags, TELEMETRY_JSON_ALIAS.help));
30
33
  program.option(CONFIG_FILE_OPTION.flags, CONFIG_FILE_OPTION.help);
31
- return program;
34
+ return program.addHelpText('after', '\nLibrary inventory: drone-path archive scan --help\nMCP stdio server: drone-path mcp --help');
32
35
  }
33
36
  function givenOnCommandLine(program, name) {
34
37
  return program.getOptionValueSource(name) === 'cli';
@@ -47,18 +50,20 @@ function collectOverrides(program, onDeprecated) {
47
50
  const raw = row.cli.parse ? row.cli.parse(opts[row.key]) : opts[row.key];
48
51
  Object.assign(cli, row.normalize(raw, flag));
49
52
  }
53
+ const hasAlias = givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.inputKey);
54
+ const hasCanonical = givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.key);
50
55
  // The deprecated alias lands on the same trackOut override key; both
51
56
  // spellings at once is ambiguous and rejected.
52
- if (givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.inputKey)) {
53
- if (givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.key)) {
57
+ if (hasAlias) {
58
+ if (hasCanonical) {
54
59
  throw new Error(`${longFlagOf(TELEMETRY_JSON_ALIAS.flags)} and --track-out cannot be combined (use --track-out)`);
55
60
  }
56
61
  onDeprecated(TELEMETRY_JSON_ALIAS.cliWarning);
57
62
  Object.assign(cli, OVERRIDE_NORMALIZERS.trackOut(opts[TELEMETRY_JSON_ALIAS.inputKey], longFlagOf(TELEMETRY_JSON_ALIAS.flags)));
58
63
  }
59
- const trackOutSpelling = givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.inputKey)
64
+ const trackOutSpelling = hasAlias
60
65
  ? 'telemetry-json'
61
- : givenOnCommandLine(program, TELEMETRY_JSON_ALIAS.key)
66
+ : hasCanonical
62
67
  ? 'track-out'
63
68
  : null;
64
69
  return { cli, trackOutSpelling };
@@ -130,6 +135,18 @@ async function runPipeline(invocation, log) {
130
135
  }
131
136
  export async function main(argv = process.argv) {
132
137
  try {
138
+ if (argv[2] === 'archive') {
139
+ await runArchive(argv.slice(3));
140
+ return;
141
+ }
142
+ if (argv[2] === 'extract-frame') {
143
+ await runExtractFrame(argv.slice(3));
144
+ return;
145
+ }
146
+ if (argv[2] === 'mcp') {
147
+ await runMcp(argv.slice(3));
148
+ return;
149
+ }
133
150
  const invocation = resolveInvocation(argv);
134
151
  // Deprecation warnings are not progress output: they print even with --quiet.
135
152
  for (const warning of invocation.deprecationWarnings) {
@@ -0,0 +1 @@
1
+ export declare function runExtractFrame(argv: string[]): Promise<void>;
@@ -0,0 +1,63 @@
1
+ import { Command } from 'commander';
2
+ import { requireFfmpegTools } from 'drone-path-core/ffmpeg';
3
+ import { resolveFfmpegTools } from 'drone-path-core/ffmpeg-tools';
4
+ import { extractKeyframes, parseKeyframeSpecs } from 'drone-path-core/keyframes';
5
+ function parseMaxWidth(text) {
6
+ const trimmed = text.trim();
7
+ if (!/^\d+$/u.test(trimmed)) {
8
+ throw new Error('expected a positive integer for --max-width');
9
+ }
10
+ const value = Number(trimmed);
11
+ if (!Number.isSafeInteger(value) || value < 1) {
12
+ throw new Error('expected a positive integer for --max-width');
13
+ }
14
+ return value;
15
+ }
16
+ export async function runExtractFrame(argv) {
17
+ const program = new Command('drone-path extract-frame')
18
+ .description('Extract targeted JPEG keyframes and telemetry snapshots from a recording.')
19
+ .exitOverride()
20
+ .argument('<video>', 'recording video file')
21
+ .requiredOption('--at <specs>', 'comma-separated timestamps (s) or frames (fN, frame:N)')
22
+ .option('--max-width <px>', 'maximum output width in pixels, preserving aspect ratio', parseMaxWidth)
23
+ .option('--out-dir <dir>', 'output directory (defaults to video directory)')
24
+ .option('--ffmpeg <path>', 'path to the ffmpeg executable')
25
+ .option('--ffprobe <path>', 'path to the ffprobe executable')
26
+ .option('--json', 'write extracted keyframes JSON array to stdout');
27
+ program.parse(argv, { from: 'user' });
28
+ const [video] = program.args;
29
+ const opts = program.opts();
30
+ const requests = parseKeyframeSpecs(opts.at);
31
+ const tools = resolveFfmpegTools({
32
+ ffmpeg: opts.ffmpeg ?? null,
33
+ ffprobe: opts.ffprobe ?? null,
34
+ });
35
+ const controller = new AbortController();
36
+ const interrupt = () => controller.abort(new Error('keyframe extraction canceled'));
37
+ process.on('SIGINT', interrupt);
38
+ try {
39
+ await requireFfmpegTools(tools, controller.signal);
40
+ const keyframes = await extractKeyframes(video, {
41
+ at: requests,
42
+ maxWidth: opts.maxWidth,
43
+ outDir: opts.outDir,
44
+ tools,
45
+ signal: controller.signal,
46
+ });
47
+ if (opts.json) {
48
+ process.stdout.write(JSON.stringify(keyframes) + '\n');
49
+ return;
50
+ }
51
+ for (const kf of keyframes) {
52
+ process.stdout.write(`${kf.path} (frame ${kf.frame}, ${kf.tSec.toFixed(3)}s, ${kf.width}x${kf.height})\n`);
53
+ }
54
+ process.stderr.write(`[drone-path] extracted ${keyframes.length} keyframe(s)\n`);
55
+ }
56
+ catch (error) {
57
+ controller.signal.throwIfAborted();
58
+ throw error;
59
+ }
60
+ finally {
61
+ process.off('SIGINT', interrupt);
62
+ }
63
+ }
@@ -0,0 +1 @@
1
+ export declare function runMcp(argv: string[]): Promise<void>;
@@ -0,0 +1,29 @@
1
+ import { Command } from 'commander';
2
+ import { createMcpServer } from './mcp-server.js';
3
+ export async function runMcp(argv) {
4
+ const program = new Command('drone-path mcp')
5
+ .description('Run a stdio MCP server exposing archive, telemetry, keyframe, and rendering tools.')
6
+ .exitOverride()
7
+ .option('--archive-db <path>', 'override the per-user archive database path')
8
+ .requiredOption('--allow-root <dir...>', 'restrict file and folder tool access to these root directories (required)');
9
+ program.parse(argv, { from: 'user' });
10
+ const opts = program.opts();
11
+ const server = createMcpServer({
12
+ archiveDb: opts.archiveDb,
13
+ allowedRoots: opts.allowRoot,
14
+ });
15
+ const onSignal = () => {
16
+ void server.close();
17
+ };
18
+ process.on('SIGINT', onSignal);
19
+ process.on('SIGTERM', onSignal);
20
+ try {
21
+ const rootCount = server.allowedRoots.length;
22
+ process.stderr.write(`[drone-path] mcp stdio server ready (roots: ${rootCount})\n`);
23
+ await server.start();
24
+ }
25
+ finally {
26
+ process.off('SIGINT', onSignal);
27
+ process.off('SIGTERM', onSignal);
28
+ }
29
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Resolves a path by canonicalizing its deepest existing ancestor via realpath
3
+ * (following symlinks, including dangling symlinks) and reattaching remaining
4
+ * non-existent segments so boundary checks defeat `..` and symlink escapes.
5
+ */
6
+ export declare function canonicalizePath(targetPath: string, depth?: number, seen?: Set<string>): string;
7
+ export declare function resolveAllowedRoots(roots?: readonly string[]): string[];
8
+ export declare function isPathWithinRoot(canonicalTarget: string, canonicalRoot: string): boolean;
9
+ export declare function isPathInAllowedRoots(targetPath: string, allowedRoots: readonly string[]): boolean;
10
+ export declare function assertPathInAllowedRoots(targetPath: string, allowedRoots: readonly string[]): string;
11
+ export declare function isSamePath(a: string, b: string): boolean;
12
+ export declare function assertNotArchiveDb(outputPath: string, archiveDb: string): void;
@@ -0,0 +1,140 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const MAX_SYMLINK_DEPTH = 40;
4
+ function pathKey(filePath) {
5
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
6
+ }
7
+ function isErrno(error, code) {
8
+ return error?.code === code;
9
+ }
10
+ /**
11
+ * Resolves a path by canonicalizing its deepest existing ancestor via realpath
12
+ * (following symlinks, including dangling symlinks) and reattaching remaining
13
+ * non-existent segments so boundary checks defeat `..` and symlink escapes.
14
+ */
15
+ export function canonicalizePath(targetPath, depth = 0, seen = new Set()) {
16
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') {
17
+ throw new Error('path must not be empty');
18
+ }
19
+ if (targetPath.includes('\0')) {
20
+ throw new Error('path contains null byte');
21
+ }
22
+ const absolute = path.resolve(targetPath);
23
+ const pending = [];
24
+ let current = absolute;
25
+ for (;;) {
26
+ try {
27
+ const stat = fs.lstatSync(current);
28
+ try {
29
+ const real = fs.realpathSync(current);
30
+ return pending.length > 0 ? path.join(real, ...pending) : real;
31
+ }
32
+ catch (err) {
33
+ if (!isErrno(err, 'ENOENT') || !stat.isSymbolicLink()) {
34
+ throw err;
35
+ }
36
+ if (depth >= MAX_SYMLINK_DEPTH || seen.has(current)) {
37
+ throw new Error(`symlink loop detected while resolving path: ${targetPath}`, {
38
+ cause: err,
39
+ });
40
+ }
41
+ seen.add(current);
42
+ const linkTarget = fs.readlinkSync(current);
43
+ const resolvedTarget = path.resolve(path.dirname(current), linkTarget);
44
+ const canonicalTarget = canonicalizePath(resolvedTarget, depth + 1, seen);
45
+ return pending.length > 0 ? path.join(canonicalTarget, ...pending) : canonicalTarget;
46
+ }
47
+ }
48
+ catch (err) {
49
+ if (!isErrno(err, 'ENOENT')) {
50
+ throw err;
51
+ }
52
+ const parent = path.dirname(current);
53
+ if (parent === current) {
54
+ return pending.length > 0 ? path.join(current, ...pending) : current;
55
+ }
56
+ pending.unshift(path.basename(current));
57
+ current = parent;
58
+ }
59
+ }
60
+ }
61
+ export function resolveAllowedRoots(roots) {
62
+ if (!roots || roots.length === 0) {
63
+ throw new Error('at least one allowed root directory is required (pass --allow-root <dir>)');
64
+ }
65
+ const candidates = roots;
66
+ const resolved = [];
67
+ const seen = new Set();
68
+ for (const root of candidates) {
69
+ if (typeof root !== 'string' || root.trim() === '') {
70
+ throw new Error('allowed root must not be empty');
71
+ }
72
+ if (root.includes('\0')) {
73
+ throw new Error('allowed root contains null byte');
74
+ }
75
+ const absolute = path.resolve(root);
76
+ let canonical;
77
+ try {
78
+ canonical = fs.realpathSync(absolute);
79
+ }
80
+ catch (err) {
81
+ throw new Error(`allowed root does not exist: ${root}`, { cause: err });
82
+ }
83
+ if (!fs.statSync(canonical).isDirectory()) {
84
+ throw new Error(`allowed root is not a directory: ${root}`);
85
+ }
86
+ const key = pathKey(canonical);
87
+ if (!seen.has(key)) {
88
+ seen.add(key);
89
+ resolved.push(canonical);
90
+ }
91
+ }
92
+ return resolved;
93
+ }
94
+ export function isPathWithinRoot(canonicalTarget, canonicalRoot) {
95
+ const rel = path.relative(pathKey(canonicalRoot), pathKey(canonicalTarget));
96
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel));
97
+ }
98
+ export function isPathInAllowedRoots(targetPath, allowedRoots) {
99
+ try {
100
+ const canonical = canonicalizePath(targetPath);
101
+ return allowedRoots.some((root) => isPathWithinRoot(canonical, root));
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ export function assertPathInAllowedRoots(targetPath, allowedRoots) {
108
+ const canonical = canonicalizePath(targetPath);
109
+ if (!allowedRoots.some((root) => isPathWithinRoot(canonical, root))) {
110
+ throw new Error(`path is outside allowed roots: ${targetPath}`);
111
+ }
112
+ return canonical;
113
+ }
114
+ function sameInode(a, b) {
115
+ if (!fs.existsSync(a) || !fs.existsSync(b))
116
+ return false;
117
+ const statA = fs.statSync(a, { bigint: true });
118
+ const statB = fs.statSync(b, { bigint: true });
119
+ return statA.dev === statB.dev && statA.ino === statB.ino;
120
+ }
121
+ export function isSamePath(a, b) {
122
+ const canonicalA = canonicalizePath(a);
123
+ const canonicalB = canonicalizePath(b);
124
+ if (pathKey(canonicalA) === pathKey(canonicalB))
125
+ return true;
126
+ return sameInode(canonicalA, canonicalB);
127
+ }
128
+ export function assertNotArchiveDb(outputPath, archiveDb) {
129
+ const protectedPaths = [
130
+ archiveDb,
131
+ `${archiveDb}-wal`,
132
+ `${archiveDb}-shm`,
133
+ `${archiveDb}-journal`,
134
+ ];
135
+ for (const target of protectedPaths) {
136
+ if (isSamePath(outputPath, target)) {
137
+ throw new Error('output path cannot overwrite the archive database');
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,21 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
3
+ import type { LogFn } from 'drone-path-engine/logging';
4
+ import { runBatch } from 'drone-path-engine/pipeline';
5
+ export interface McpServerOptions {
6
+ archiveDb?: string;
7
+ allowedRoots?: readonly string[];
8
+ input?: Readable;
9
+ output?: Writable;
10
+ log?: LogFn;
11
+ tools?: FfmpegToolPaths;
12
+ getTools?: () => Promise<FfmpegToolPaths>;
13
+ runBatch?: typeof runBatch;
14
+ }
15
+ export interface McpServer {
16
+ readonly archiveDb: string;
17
+ readonly allowedRoots: readonly string[];
18
+ start: () => Promise<void>;
19
+ close: () => Promise<void>;
20
+ }
21
+ export declare function createMcpServer(options?: McpServerOptions): McpServer;