|
| 1 | +import { copyFile, link, mkdir, mkdtemp, realpath } from "node:fs/promises"; |
| 2 | +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; |
| 3 | +import { lstat, rm, stat } from "@effectionx/fs"; |
| 4 | +import { elicit, isJsonObject } from "@executablemd/core"; |
| 5 | +import { cwd } from "@executablemd/runtime"; |
| 6 | +import { Permissions } from "@executablemd/runtime/api"; |
| 7 | +import { ensure, Err, Ok, scoped, until } from "effection"; |
| 8 | +import type { Operation, Result } from "effection"; |
| 9 | +import { ReplHost } from "./repl/host.ts"; |
| 10 | +import type { AssetImportRequest } from "./repl/host.ts"; |
| 11 | + |
| 12 | +const nativeOperations = { |
| 13 | + copyFile, |
| 14 | + link, |
| 15 | + mkdir: (path: string, options: { recursive: true }) => mkdir(path, options), |
| 16 | + mkdtemp: (path: string) => mkdtemp(path), |
| 17 | + realpath: (path: string) => realpath(path), |
| 18 | +}; |
| 19 | + |
| 20 | +export function* useNodeReplAssetImport(native = nativeOperations): Operation<void> { |
| 21 | + yield* ReplHost.around( |
| 22 | + { |
| 23 | + importAsset: ([request]) => importAsset(request, native), |
| 24 | + }, |
| 25 | + { at: "min" }, |
| 26 | + ); |
| 27 | +} |
| 28 | + |
| 29 | +function joined<T>(start: () => Promise<T>, adopt: (value: T) => void = () => {}): Operation<T> { |
| 30 | + return scoped(function* () { |
| 31 | + let pending: Promise<T> | undefined; |
| 32 | + yield* ensure(function* () { |
| 33 | + if (pending !== undefined) { |
| 34 | + yield* until( |
| 35 | + pending.then( |
| 36 | + () => undefined, |
| 37 | + () => undefined, |
| 38 | + ), |
| 39 | + ); |
| 40 | + } |
| 41 | + }); |
| 42 | + pending = start().then((value) => { |
| 43 | + adopt(value); |
| 44 | + return value; |
| 45 | + }); |
| 46 | + return yield* until(pending); |
| 47 | + }); |
| 48 | +} |
| 49 | + |
| 50 | +function* allowed(): Operation<void> { |
| 51 | + if ( |
| 52 | + !(yield* Permissions.operations.files("read")) || |
| 53 | + !(yield* Permissions.operations.files("write")) |
| 54 | + ) { |
| 55 | + throw new ImportRefusal("Asset import requires effective file read and write permission."); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +function inside(root: string, path: string): boolean { |
| 60 | + const suffix = relative(root, path); |
| 61 | + return ( |
| 62 | + suffix === "" || (!isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`)) |
| 63 | + ); |
| 64 | +} |
| 65 | + |
| 66 | +function code(error: unknown, name: string): boolean { |
| 67 | + return error instanceof Error && "code" in error && error.code === name; |
| 68 | +} |
| 69 | + |
| 70 | +function* vacant(path: string): Operation<void> { |
| 71 | + try { |
| 72 | + yield* lstat(path); |
| 73 | + } catch (error) { |
| 74 | + if (code(error, "ENOENT")) { |
| 75 | + return; |
| 76 | + } |
| 77 | + throw error; |
| 78 | + } |
| 79 | + throw new ImportRefusal( |
| 80 | + "The import destination is occupied. Choose another explicit destination and obtain new approval.", |
| 81 | + ); |
| 82 | +} |
| 83 | + |
| 84 | +function* destinationPath( |
| 85 | + root: string, |
| 86 | + destination: string, |
| 87 | + native: typeof nativeOperations, |
| 88 | +): Operation<string> { |
| 89 | + if (destination.length === 0 || isAbsolute(destination)) { |
| 90 | + throw new ImportRefusal("Choose a nonempty workspace-relative import destination."); |
| 91 | + } |
| 92 | + const target = resolve(root, destination); |
| 93 | + if (target === root || !inside(root, target)) { |
| 94 | + throw new ImportRefusal("Choose an import destination inside the session workspace."); |
| 95 | + } |
| 96 | + let parent = dirname(target); |
| 97 | + while (true) { |
| 98 | + try { |
| 99 | + const actual = yield* joined(() => native.realpath(parent)); |
| 100 | + if (!inside(root, actual)) { |
| 101 | + throw new ImportRefusal( |
| 102 | + "The import destination parent leaves the session workspace. Choose another destination.", |
| 103 | + ); |
| 104 | + } |
| 105 | + break; |
| 106 | + } catch (error) { |
| 107 | + if (!code(error, "ENOENT")) { |
| 108 | + throw error; |
| 109 | + } |
| 110 | + const next = dirname(parent); |
| 111 | + if (next === parent) { |
| 112 | + throw error; |
| 113 | + } |
| 114 | + parent = next; |
| 115 | + } |
| 116 | + } |
| 117 | + yield* vacant(target); |
| 118 | + return target; |
| 119 | +} |
| 120 | + |
| 121 | +function importAsset( |
| 122 | + request: AssetImportRequest, |
| 123 | + native: typeof nativeOperations, |
| 124 | +): Operation<Result<string>> { |
| 125 | + const { workspace, source: offeredSource, destination } = request; |
| 126 | + return scoped(function* () { |
| 127 | + let source: string; |
| 128 | + let root: string; |
| 129 | + let target: string; |
| 130 | + try { |
| 131 | + if ( |
| 132 | + typeof offeredSource !== "string" || |
| 133 | + offeredSource.length === 0 || |
| 134 | + typeof destination !== "string" || |
| 135 | + typeof workspace !== "string" || |
| 136 | + workspace.length === 0 |
| 137 | + ) { |
| 138 | + throw new ImportRefusal( |
| 139 | + "Import requires a source, a destination and this session's workspace.", |
| 140 | + ); |
| 141 | + } |
| 142 | + yield* allowed(); |
| 143 | + const current = yield* cwd(); |
| 144 | + source = yield* joined(() => native.realpath(resolve(current, offeredSource))); |
| 145 | + if (!(yield* stat(source)).isFile()) { |
| 146 | + throw new ImportRefusal("Choose a regular source file to import."); |
| 147 | + } |
| 148 | + root = yield* joined(() => native.realpath(workspace)); |
| 149 | + target = yield* destinationPath(root, destination, native); |
| 150 | + } catch (error) { |
| 151 | + return refused(error); |
| 152 | + } |
| 153 | + const answer = yield* elicit({ |
| 154 | + schema: { |
| 155 | + type: "object", |
| 156 | + properties: { |
| 157 | + decision: { type: "string", title: "Import this file?", enum: ["Import", "Decline"] }, |
| 158 | + }, |
| 159 | + required: ["decision"], |
| 160 | + additionalProperties: false, |
| 161 | + }, |
| 162 | + message: `Source: ${source}\nDestination: ${target}\nWorkspace path after import: ${destination}\nImport copies this file into your session workspace.`, |
| 163 | + }); |
| 164 | + if (!isJsonObject(answer) || answer.decision !== "Import") { |
| 165 | + return Err(new Error("Asset import declined. No file was copied.")); |
| 166 | + } |
| 167 | + let temporary: string | undefined; |
| 168 | + yield* ensure(function* () { |
| 169 | + if (temporary !== undefined) { |
| 170 | + yield* rm(temporary, { recursive: true, force: true }); |
| 171 | + } |
| 172 | + }); |
| 173 | + try { |
| 174 | + yield* allowed(); |
| 175 | + if (!(yield* stat(source)).isFile()) { |
| 176 | + throw new ImportRefusal( |
| 177 | + "The approved source is no longer a regular file. Request a new import.", |
| 178 | + ); |
| 179 | + } |
| 180 | + target = yield* destinationPath(root, destination, native); |
| 181 | + yield* joined(() => native.mkdir(dirname(target), { recursive: true })); |
| 182 | + yield* joined( |
| 183 | + () => native.mkdtemp(join(dirname(target), ".xmd-import-")), |
| 184 | + (path) => { |
| 185 | + temporary = path; |
| 186 | + }, |
| 187 | + ); |
| 188 | + if (temporary === undefined) { |
| 189 | + throw new Error("Asset import staging was not acquired."); |
| 190 | + } |
| 191 | + const payload = join(temporary, "payload"); |
| 192 | + yield* joined(() => native.copyFile(source, payload)); |
| 193 | + yield* allowed(); |
| 194 | + try { |
| 195 | + yield* joined(() => native.link(payload, target)); |
| 196 | + } catch (error) { |
| 197 | + if (code(error, "EEXIST")) { |
| 198 | + return Err( |
| 199 | + new Error( |
| 200 | + "The import destination became occupied. Choose another explicit destination and obtain new approval.", |
| 201 | + ), |
| 202 | + ); |
| 203 | + } |
| 204 | + throw new PublicationError(error); |
| 205 | + } |
| 206 | + } catch (error) { |
| 207 | + if (error instanceof PublicationError) { |
| 208 | + throw error; |
| 209 | + } |
| 210 | + return refused(error); |
| 211 | + } |
| 212 | + return Ok(destination); |
| 213 | + }); |
| 214 | +} |
| 215 | + |
| 216 | +class PublicationError extends Error { |
| 217 | + constructor(cause: unknown) { |
| 218 | + super( |
| 219 | + "Asset import publication could not be established. Inspect the destination before requesting another import.", |
| 220 | + { cause }, |
| 221 | + ); |
| 222 | + } |
| 223 | +} |
| 224 | + |
| 225 | +class ImportRefusal extends Error {} |
| 226 | + |
| 227 | +function refused(error: unknown): Result<never> { |
| 228 | + if ( |
| 229 | + error instanceof ImportRefusal || |
| 230 | + (error instanceof Error && "code" in error && typeof error.code === "string") |
| 231 | + ) { |
| 232 | + return Err(error); |
| 233 | + } |
| 234 | + throw error; |
| 235 | +} |
0 commit comments