/** * Download MoveKit videos and posters to assets/ and write catalog.json, status.json * and README.md (how an app serves and plays the files). * movekit-import version 2026.11.29.2 * Save it as movekit/import.mjs and run it from the project root (Node 20 or newer, no packages): * node movekit/import.mjs * Its folders are relative to the folder it is run from, wherever the script is. With --install * it only puts a copy of itself at movekit/import.mjs: when there is none there, or an older one. * With no key it imports the sample exercises. With a key it imports what the * account owns, plus any sample exercise the account does not own. * The key is MOVEKIT_API_KEY from the environment, or a MOVEKIT_API_KEY= line * in .env.local, then .env, in the current folder. Optional environment variables: * MOVEKIT_API_BASE_URL (https://api.movekit.com/v1), * MOVEKIT_IMPORT_DIR (./movekit), MOVEKIT_IMPORT_LIMIT (0 for all files), * MOVEKIT_ASSETS_DIR (/assets: where the videos and posters go, for example * a web app's public/movekit, while catalog.json stays in the import folder). * The shipped app must read these local files and never call the API at runtime. */ import { createHash, randomBytes } from "node:crypto" import { constants as fsConstants, createReadStream, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs" import { copyFile, lstat, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises" import path from "node:path" import { fileURLToPath } from "node:url" // A closed pipe (| head) stops the output, never the run. for (const stream of [process.stdout, process.stderr]) stream.on("error", () => {}) const KEY = readKey() const API_KEY = KEY.value // Round sixteen (M3): whatever escapes main once the key is read (a timer or a callback that throws, a rejected promise // no one awaits) is said through say() too, and the run ends 1; Node never prints it itself. process.on("uncaughtException", escaped) process.on("unhandledRejection", escaped) const API_BASE = trimSlash(process.env.MOVEKIT_API_BASE_URL ?? "https://api.movekit.com/v1") // The route that ran it: the prompt and the skill set MOVEKIT_VIA on their first run; a copy inside a skill folder is the skill's. const VIA = ["prompt", "skill"].includes(process.env.MOVEKIT_VIA) ? process.env.MOVEKIT_VIA : import.meta.url.includes("/skills/movekit/") ? "skill" : "docs" // Sent on every request, downloads included, so the delivery network sees a named client. const USER_AGENT = `movekit-import/1 (via=${VIA})` // The import folder, relative to the folder the importer is run from (the project root), wherever the script itself is. // An absolute folder is taken by its real path (through any link in it), so the paths written stay inside the project // when they are; a relative one is taken as given. const IMPORT_DIR = givenFolder(process.env.MOVEKIT_IMPORT_DIR) || "./movekit" // The importer never deletes, moves or overwrites a file except the ones it writes in this run: its own temporary // files (*..part) and, through them, catalog.json, status.json, its own README.md and the clip files it is // placing. A file it no longer uses stays where it is and is reported (blind review, 20 Nov 2026, evening). // catalog.json and status.json are read, written or marked only when they are absent or the importer's own // (ownCatalog, ownStatus); a file of either name that is not stops the run before anything is written. const MARKER = "movekit-import" // A file name this importer gives a file it downloads: only such files are ever copied from or reported as unused. const IMPORTER_FILE = /^ex\d+-(?:video|poster)-[A-Za-z0-9_-]+\.(?:mp4|jpg|webp|png)$/ // The temporary file of a download or a copy a stopped run left: reported with the unused files, never touched. const IMPORTER_PART = /^ex\d+-(?:video|poster)-[A-Za-z0-9_-]+\.(?:mp4|jpg|webp|png)(?:\.[0-9a-f]{8})?(?:\.copy)?\.part$/ // Round sixteen (L1): frozen to the leaves, so nothing read from them, under any name, can be changed. const LAST_CATALOG_FILE = deepFreeze(ownFile(path.join(IMPORT_DIR, "catalog.json"), ownCatalog)) const LAST_STATUS_FILE = deepFreeze(ownFile(path.join(IMPORT_DIR, "status.json"), ownStatus)) const LAST_CATALOG = LAST_CATALOG_FILE.own ? LAST_CATALOG_FILE.data : null const LAST_STATUS = LAST_STATUS_FILE.own ? LAST_STATUS_FILE.data : null // The account the last import came from: status.json's, else catalog.json's (a project may keep only the catalogue). const LAST_ACCOUNT = accountId(LAST_STATUS?.account) ?? accountId(LAST_CATALOG?.account) // Where the last run put the clips, relative to the import folder: the folder a stopped run was filling (its mark), // else the one folder every path in the last catalog.json shares, else status.json's assetsDir; null on a first run. const LAST_FOLDER = lastClipsFolder() // A recorded folder outside the folder the importer runs from and the import folder is never switched away from in // silence: a run without MOVEKIT_ASSETS_DIR stops and says which value to set (main()). const LAST_FOLDER_OUTSIDE = LAST_FOLDER !== null && !insideProject(path.resolve(IMPORT_DIR, LAST_FOLDER)) // The last run's clips folder, absolute (/assets when nothing says otherwise). const PREVIOUS_ASSETS = path.resolve(IMPORT_DIR, LAST_FOLDER ?? "assets") // The videos and posters only. A web app can serve this folder while catalog.json, status.json and README.md stay unserved. // MOVEKIT_ASSETS_DIR wins when it is set, as given, even outside the project (a monorepo's shared package). Without it, // a run keeps the folder the last run used; the default is /assets. const RECORDED_ASSETS = process.env.MOVEKIT_ASSETS_DIR || LAST_FOLDER_OUTSIDE ? null : LAST_FOLDER const ASSETS_DIR = givenFolder(process.env.MOVEKIT_ASSETS_DIR) || (RECORDED_ASSETS && RECORDED_ASSETS !== "assets" ? path.resolve(IMPORT_DIR, RECORDED_ASSETS) : path.join(IMPORT_DIR, "assets")) const ASSETS_KEPT = Boolean(RECORDED_ASSETS && RECORDED_ASSETS !== "assets") // The assets folder as seen from catalog.json: every file's path in the catalog starts with it. const ASSETS_FROM_CATALOG = path.relative(path.resolve(IMPORT_DIR), path.resolve(ASSETS_DIR)).split(path.sep).join("/") // The clips folder outside the folder the importer runs from (set by MOVEKIT_ASSETS_DIR): named in one summary line. const ASSETS_OUTSIDE = !insideProject(path.resolve(ASSETS_DIR)) const IMPORT_LIMIT = /^\d+$/.test((process.env.MOVEKIT_IMPORT_LIMIT ?? "0").trim()) ? Number((process.env.MOVEKIT_IMPORT_LIMIT ?? "0").trim()) : null // A name no earlier run and no other file uses, for this run's temporary files: an existing file is never opened, // appended to or removed because it happens to carry a temporary name. const RUN_ID = randomBytes(4).toString("hex") const BATCH_SIZE = 50 const REQUEST_TIMEOUT_MS = 30_000 // Only tests set MOVEKIT_TEST_TIME_SCALE, a number from 0.001 to 1: it shortens the download timings below by that // factor. Anything else (unset, 0, more than 1, not a number) counts as 1, so it can never make a run slower. const TIME_SCALE = /^(?:0(?:\.[0-9]+)?|1(?:\.0+)?|\.[0-9]+)$/.test(process.env.MOVEKIT_TEST_TIME_SCALE ?? "") && Number(process.env.MOVEKIT_TEST_TIME_SCALE) >= 0.001 ? Number(process.env.MOVEKIT_TEST_TIME_SCALE) : 1 // A download that sends nothing for this long is a failed try (a slow one that keeps sending goes on). const DOWNLOAD_IDLE_MS = 30_000 * TIME_SCALE const GRANT_REFRESH_MARGIN_MS = 30_000 // A download the delivery host could not serve just now (502, 503, 504, a connection reset or ended early, nothing // sent for 30 s) is tried again from the bytes already here, after 1, 2, 4, 8 and 16 s (or what Retry-After says, at // most a minute): 6 tries at most, and none later than 90 s after the file's first failure. A link the host says is // spent or expired is replaced by a fresh one, and the same count goes on. A file still failing is held back like any // other: the rest of the run goes on. // The run's budget for passing faults is 3 minutes in all: each failed try counts its own time up to the idle timeout // (30 s; a long transfer that breaks late is not charged its whole length, yet every failure costs something), and the // waits between tries count in full. Once it is spent, a file still gets one try, and one that fails is held back at // once; after 3 such failures (FAILURES_AFTER_BUDGET, counted from the moment the budget ran out and never reset by a // file that arrives), every file left is held back without a try. So the time a run spends on failures is at most // about 5 minutes, however many files and whatever share of them fail: 3 minutes of budget, the try running when it // ran out (30 s at most), and 3 more failed tries of 30 s at most. A host that fails 2 of every 3 files costs that // plus the time the files that do arrive take to download. // And whatever a try sends before it fails: the failed tries' own time in full and the waits, counted from the first // failure, are capped at 5 minutes (FAILURE_TIME_CAP_MS). A wait that would go past it is not taken, and once it is // reached every file left is held back without a try and no more links are asked for. // Each try also has a deadline (round fifteen): 60 s (TRY_MIN_MS), or the time the bytes still to come take at 50 KB/s // (TRY_MIN_RATE), whichever is longer, checked as each piece arrives. A connection slower than 50 KB/s (400 kbit/s) // cannot bring clips in useful time, and a slow try keeps its bytes for the next one, so a slow host still finishes over // several tries while one that drips bytes for ever is ended. The most a run spends on failures is so 5 minutes plus // the try running when the cap is reached: its deadline and one more piece or silent wait (30 s at most). const DOWNLOAD_RETRIES = 5 const DOWNLOAD_RETRY_WINDOW_MS = 90_000 * TIME_SCALE const RUN_RETRY_BUDGET_MS = 180_000 * TIME_SCALE const RETRY_AFTER_CAP_MS = 60_000 * TIME_SCALE const FAILURES_AFTER_BUDGET = 3 const FAILURE_TIME_CAP_MS = 300_000 * TIME_SCALE const TRY_MIN_MS = 60_000 * TIME_SCALE const TRY_MIN_RATE = 50_000 const PASSING_STATUSES = new Set([502, 503, 504]) // Time spent on passing faults this run (failed tries and waits), and the files that failed after it ran out. let retrySpentMs = 0 let failedAfterBudget = 0 let failureTimeMs = 0 // Round sixteen (M1), round seventeen: link renewals. A renewal asks again for every file left in its batch, so it is // made only when it can help: the first in a batch at any time, then one more whenever bytes arrived since the last (a // host that answers 410 to everything gets one; a slow line that works gets as many as it needs), and at most // RENEWALS_PER_FILE for any one file in a run. Links that look expired as they arrive mean this computer's clock is // ahead of MoveKit's: the files are held, the run says so once and asks for no more. const RENEWALS_PER_FILE = 3 // Bytes the delivery host has sent this run, all files together: what tells a renewal that the line is working. let bytesReceived = 0 // Round sixteen (M2): a try cut at its deadline that still brought at least 10 KB/s is a slow line, not a failing one. const STEADY_RATE = 10_000 // How far this computer's clock is ahead of MoveKit's, from the Date of the API's last answer (null when unknown). let clockAheadMs = null const ASSET_ID = /^ex\d+-(?:video|poster)$/ const SAFE_VERSION = /^[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}$/ const RATE_LIMIT_RETRIES = 3 const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const EXTENSIONS = { "video/mp4": "mp4", "image/jpeg": "jpg", "image/webp": "webp", "image/png": "png" } const PACKS_URL = "https://movekit.com/packs" const KEYS_URL = "https://movekit.com/account/purchases?from=api#api-keys" const PROGRESS_EVERY = 10 // What to do when the API's list of exercises cannot be read. const LISTING_FORWARD = "Run the importer again in a few minutes. If it stops the same way, download the importer again (a newer one may read the answer), and if that does not help, tell MoveKit at https://movekit.com/contact." // Tries of the download links request when the API answers with a server error (parallel CI runs can contend). const LINK_ATTEMPTS = 4 // Refusals that hold one file back until 00:00 UTC; refusals that hold back every later file of the same kind (sample or account). const DAILY_REFUSALS = new Set(["link_limit_exceeded", "sample_busy", "daily_request_limit"]) const WHOLE_DAY_REFUSALS = new Set(["sample_busy", "daily_request_limit"]) // The README's first line: a README that does not start with it is the project's own and is never overwritten. const README_MARKER = "" const README_OURS = ["