|
| 1 | +import {existsSync} from "node:fs"; |
| 2 | +import {utimes, writeFile} from "node:fs/promises"; |
| 3 | +import {join} from "node:path"; |
| 4 | +import * as clack from "@clack/prompts"; |
| 5 | +import wrapAnsi from "wrap-ansi"; |
| 6 | +import type {ClackEffects} from "./clack.js"; |
| 7 | +import {CliError} from "./error.js"; |
| 8 | +import {prepareOutput} from "./files.js"; |
| 9 | +import {getObservableUiOrigin} from "./observableApiClient.js"; |
| 10 | +import {type TtyEffects, bold, cyan, faint, inverse, link, reset, defaultEffects as ttyEffects} from "./tty.js"; |
| 11 | + |
| 12 | +export interface ConvertEffects extends TtyEffects { |
| 13 | + clack: ClackEffects; |
| 14 | + prepareOutput(outputPath: string): Promise<void>; |
| 15 | + existsSync(outputPath: string): boolean; |
| 16 | + writeFile(outputPath: string, contents: Buffer | string): Promise<void>; |
| 17 | + touch(outputPath: string, date: Date | string | number): Promise<void>; |
| 18 | +} |
| 19 | + |
| 20 | +const defaultEffects: ConvertEffects = { |
| 21 | + ...ttyEffects, |
| 22 | + clack, |
| 23 | + async prepareOutput(outputPath: string): Promise<void> { |
| 24 | + await prepareOutput(outputPath); |
| 25 | + }, |
| 26 | + existsSync(outputPath: string): boolean { |
| 27 | + return existsSync(outputPath); |
| 28 | + }, |
| 29 | + async writeFile(outputPath: string, contents: Buffer | string): Promise<void> { |
| 30 | + await writeFile(outputPath, contents); |
| 31 | + }, |
| 32 | + async touch(outputPath: string, date: Date | string | number): Promise<void> { |
| 33 | + await utimes(outputPath, (date = new Date(date)), date); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +export async function convert( |
| 38 | + inputs: string[], |
| 39 | + {output, force = false, files: includeFiles = true}: {output: string; force?: boolean; files?: boolean}, |
| 40 | + effects: ConvertEffects = defaultEffects |
| 41 | +): Promise<void> { |
| 42 | + const {clack} = effects; |
| 43 | + clack.intro(`${inverse(" observable convert ")}`); |
| 44 | + let n = 0; |
| 45 | + for (const input of inputs) { |
| 46 | + let start = Date.now(); |
| 47 | + let s = clack.spinner(); |
| 48 | + const url = resolveInput(input); |
| 49 | + const name = inferFileName(url); |
| 50 | + const path = join(output, name); |
| 51 | + if (await maybeFetch(path, force, effects)) { |
| 52 | + s.start(`Downloading ${bold(path)}`); |
| 53 | + const response = await fetch(url); |
| 54 | + if (!response.ok) throw new Error(`error fetching ${url}: ${response.status}`); |
| 55 | + const {nodes, files, update_time} = await response.json(); |
| 56 | + s.stop(`Downloaded ${bold(path)} ${faint(`in ${(Date.now() - start).toLocaleString("en-US")}ms`)}`); |
| 57 | + await effects.prepareOutput(path); |
| 58 | + await effects.writeFile(path, convertNodes(nodes)); |
| 59 | + await effects.touch(path, update_time); |
| 60 | + n++; |
| 61 | + if (includeFiles) { |
| 62 | + for (const file of files) { |
| 63 | + const path = join(output, file.name); |
| 64 | + if (await maybeFetch(path, force, effects)) { |
| 65 | + start = Date.now(); |
| 66 | + s = clack.spinner(); |
| 67 | + s.start(`Downloading ${bold(file.name)}`); |
| 68 | + const response = await fetch(file.download_url); |
| 69 | + if (!response.ok) throw new Error(`error fetching ${file.download_url}: ${response.status}`); |
| 70 | + const buffer = Buffer.from(await response.arrayBuffer()); |
| 71 | + s.stop(`Downloaded ${bold(file.name)} ${faint(`in ${(Date.now() - start).toLocaleString("en-US")}ms`)}`); |
| 72 | + await effects.prepareOutput(path); |
| 73 | + await effects.writeFile(path, buffer); |
| 74 | + await effects.touch(path, file.create_time); |
| 75 | + n++; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + clack.note( |
| 82 | + wrapAnsi( |
| 83 | + "Due to syntax differences between Observable notebooks and " + |
| 84 | + "Observable Framework, converted notebooks may require further " + |
| 85 | + "changes to function correctly. To learn more about JavaScript " + |
| 86 | + "in Framework, please read:\n\n" + |
| 87 | + reset(cyan(link("https://observablehq.com/framework/javascript"))), |
| 88 | + Math.min(64, effects.outputColumns) |
| 89 | + ), |
| 90 | + "Note" |
| 91 | + ); |
| 92 | + clack.outro( |
| 93 | + `${inputs.length} notebook${inputs.length === 1 ? "" : "s"} converted; ${n} file${n === 1 ? "" : "s"} written` |
| 94 | + ); |
| 95 | +} |
| 96 | + |
| 97 | +async function maybeFetch(path: string, force: boolean, effects: ConvertEffects): Promise<boolean> { |
| 98 | + const {clack} = effects; |
| 99 | + if (effects.existsSync(path) && !force) { |
| 100 | + const choice = await clack.confirm({message: `${bold(path)} already exists; replace?`, initialValue: false}); |
| 101 | + if (!choice) return false; |
| 102 | + if (clack.isCancel(choice)) throw new CliError("Stopped convert", {print: false}); |
| 103 | + } |
| 104 | + return true; |
| 105 | +} |
| 106 | + |
| 107 | +export function convertNodes(nodes): string { |
| 108 | + let string = ""; |
| 109 | + let first = true; |
| 110 | + for (const node of nodes) { |
| 111 | + if (first) first = false; |
| 112 | + else string += "\n"; |
| 113 | + string += convertNode(node); |
| 114 | + } |
| 115 | + return string; |
| 116 | +} |
| 117 | + |
| 118 | +export function convertNode(node): string { |
| 119 | + let string = ""; |
| 120 | + if (node.mode !== "md") string += `\`\`\`${node.mode}${node.pinned ? " echo" : ""}\n`; |
| 121 | + string += `${node.value}\n`; |
| 122 | + if (node.mode !== "md") string += "```\n"; |
| 123 | + return string; |
| 124 | +} |
| 125 | + |
| 126 | +export function inferFileName(input: string): string { |
| 127 | + return new URL(input).pathname.replace(/^\/document(\/@[^/]+)?\//, "").replace(/\//g, ",") + ".md"; |
| 128 | +} |
| 129 | + |
| 130 | +export function resolveInput(input: string): string { |
| 131 | + let url: URL; |
| 132 | + if (isIdSpecifier(input)) url = new URL(`/d/${input}`, getObservableUiOrigin()); |
| 133 | + else if (isSlugSpecifier(input)) url = new URL(`/${input}`, getObservableUiOrigin()); |
| 134 | + else url = new URL(input); |
| 135 | + url.host = `api.${url.host}`; |
| 136 | + url.pathname = `/document${url.pathname.replace(/^\/d\//, "/")}`; |
| 137 | + return String(url); |
| 138 | +} |
| 139 | + |
| 140 | +function isIdSpecifier(string: string) { |
| 141 | + return /^([0-9a-f]{16})(?:@(\d+)|~(\d+)|@(\w+))?$/.test(string); |
| 142 | +} |
| 143 | + |
| 144 | +function isSlugSpecifier(string: string) { |
| 145 | + return /^(?:@([0-9a-z_-]+))\/([0-9a-z_-]+(?:\/[0-9]+)?)(?:@(\d+)|~(\d+)|@(\w+))?$/.test(string); |
| 146 | +} |
0 commit comments