Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
feat: release hardened npm installer with trusted publishing
hoainho809b72d04853
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7ccc658..eb07f40 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1,4 +1,4 @@-name: Python CI+name: CIon:pull_request:@@ -15,3 +15,15 @@ jobs:with:python-version: "3.10"test-command: python3 -m unittest discover -s forge/tests+ cli:+ runs-on: ubuntu-latest+ strategy:+ matrix:+ node-version: [18, 22]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node-version }}+ - run: npm test+ - run: npm run package:checkdiff --git a/.github/workflows/cli-publish.yml b/.github/workflows/cli-publish.ymlnew file mode 100644index 0000000..2953374--- /dev/null+++ b/.github/workflows/cli-publish.yml@@ -0,0 +1,33 @@+name: cli-publish+# CLI tags are independent of the skill's v* tags.+on:+ push:+ tags: ['cli-v*']+ workflow_dispatch:+ inputs:+ tag:+ description: CLI release tag to publish (e.g. cli-v0.1.0)+ required: true+ type: string++permissions:+ contents: read++jobs:+ publish:+ # Reusable workflows CANNOT escalate a caller-level permission block. Grant+ # `id-token: write` here at the reusable-call job level so npm OIDC can mint the+ # publish token. The shared workflow narrows the build job to `contents: read`.+ permissions:+ contents: read+ id-token: write+ uses: img2threejs/ci-workflows/.github/workflows/npm-publish.yml@7ef63107b39f77df3a11062a1a0a2245f500921c+ with:+ tag: ${{ inputs.tag || github.ref_name }}+ tag-prefix: 'cli-v'+ version-file: package.json+ package-directory: '.'+ node-version: '24'+ python-version: '3.10'+ test-command: npm test+ provenance: 'true'\ No newline at end of filediff --git a/.gitignore b/.gitignoreindex e5eb5fc..cbd0409 100644--- a/.gitignore+++ b/.gitignore@@ -19,7 +19,7 @@ docs/PLAN_*.md.omc/.omo/-# npm / Node — kept out of the repo. The CLI is shipped as source via `files: ["bin"]` + tarball.+# npm / Node — kept out of the repo. The tarball ships only bin/img2threejs.mjs.node_modules/package-lock.jsonnpm-debug.log*diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47cf702..ab2f688 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0input across the move. The partition of every character/rig-named line as base mechanism ordomain content is written down *before* any file moves.+## npm CLI 0.1.1 — 2026-10-07++- Add tag-driven trusted publishing for independent `cli-vX.Y.Z` CLI releases.+- Publish the tested installer tarball from GitHub Actions without a stored npm write+ token; keep skill `vX.Y.Z` releases and the default skill `v2.0.0` independent.+- Document npx/global npm installation and the npm trusted publisher configuration.++## npm CLI 0.1.0 — 2026-10-07++Published [`[email protected]`](https://www.npmjs.com/package/img2threejs) to the public+npm registry with the `latest` tag. CLI versions are independent of skill releases;+the default installed skill remains `v2.0.0`.++- Install the base skill directly from a pinned GitHub tag or commit instead of invoking+ the unpublished `img2` npm package and its plugin-only `add` command.+- Honor `--host` for Hermes, Claude Code, Codex, and OpenCode; share one managed checkout+ per commit and preserve manual installs, unrelated symlinks, and locally edited releases.+- Make `--dry-run` offline and side-effect-free, and enforce skill-version downgrade+ rejection in `update`, including SHA refs and prerelease precedence.+- Replace source-text self-tests with isolated real-Git installation/update regressions;+ exclude the test runner from the published tarball and validate the CLI in CI.+## [2.0.0] — 2026-09-05**The Plugin Update.** The plugin ecosystem — domain registry, img2 harness, plugin-serveddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1118373..508a624 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -35,10 +35,79 @@ build actually has a GLB reference to measure — skip it entirely otherwise. Se- Run the test suite from the skill root: `python3 -m unittest discover -s forge/tests -p 'test_*.py'`.Set `IMG2THREEJS_SHOWCASE_ROOT` to a showcase checkout to include the TypeScript typecheck gates;without it they skip, so a green run has not proven the emitted Three.js compiles.+ The vertex-paint Python/TypeScript parity test invokes Node's+ `--experimental-strip-types`: use a Node 22 release supporting that flag for the full suite.+ This test prerequisite does not change the CLI's Node >= 18 support.- Validate a spec before generation: `python3 forge/stage2_spec/validate_sculpt_spec.py spec.json --strict-quality`.- Keep changes backward compatible: existing object specs must continue to validate.- No emojis in source, docs, or generated output.+### npm CLI verification and publishing++The CLI version in `package.json` is independent of the skill version in `SKILL.md`.+`bin/img2threejs.mjs` pins its default skill tag separately. The npm package ships the+installer only; it fetches the complete skill from GitHub when explicitly invoked.+No install lifecycle hook runs.++Before publishing, use Node.js >= 18 and Git:++```bash+npm test # isolated local Git fixtures; no network+npm run package:check+npm publish --dry-run --json # packaging only, not proof of npm credentials+npm pack --pack-destination /tmp+```++Install the resulting tarball in a disposable project with+`npm install /tmp/img2threejs-<version>.tgz`, then invoke its+`node_modules/.bin/img2threejs` with `--version`, `install --dry-run`, `install`,+`update`, and `doctor`. Set `HOME` and `XDG_CONFIG_HOME` to disposable directories+containing the host config roots so the smoke run cannot touch your real host skills.+A real install requires network access to GitHub.++### Automatic CLI releases++`.github/workflows/cli-publish.yml` publishes npm CLI releases through the reviewed,+full-SHA-pinned `img2threejs/ci-workflows` reusable workflow and npm trusted publishing.+No npm write token is passed to Actions. The GitHub-hosted publish job uses Node 24+and npm >=11.5.1; the installer itself still supports Node >=18.++Configure the npm package's **Trusted Publisher** as GitHub Actions:++- Organization: `img2threejs`+- Repository: `img2threejs`+- Workflow filename: `cli-publish.yml` (the caller, not `npm-publish.yml`)+- Allowed action: direct **`npm publish`**, not only `npm stage publish`++With npm >=11.15 and account-level 2FA, configure the same binding from the CLI:++```bash+npm exec --yes --package=npm@11 -- npm trust github img2threejs \+ --repo img2threejs/img2threejs --file cli-publish.yml --allow-publish --yes+```++The package must already exist on npm; the first publication is manual.++CLI tags are **`cli-vX.Y.Z`**, matching `package.json`. Skill tags remain `vX.Y.Z`,+matching `SKILL.md`; pushing a skill tag does not publish the CLI.++```bash+# Bump package.json and update CLI release notes, then commit reviewed files.+npm test+npm run package:check+git tag -a cli-v0.1.1 -m 'img2threejs CLI 0.1.1'+git push origin cli-v0.1.1+```++The workflow tests without publish permissions, publishes the tested tarball with+install/publish scripts disabled, and validates tag/version agreement. Stable releases+use `latest`; prereleases use their prerelease channel. A registry outage is an error,+not permission to publish; an existing version must match the tested artifact.++Trusted publishers need their first successful CI publish within npm's activation+window. Verify the workflow run and registry version after every release. A successful+local dry-run is not proof of authentication or registry publication.+## Before you open an issue- Search existing issues first.diff --git a/README.md b/README.mdindex 83d402e..556ada6 100644--- a/README.md+++ b/README.md@@ -124,6 +124,39 @@ A staged sculpting pipeline turns the reference image into a spec, then generate~/.codex/skills/img2threejs -> <your checkout>```+ **CLI installer (Node.js >= 18 and Git):** available as+ [`img2threejs` on npm](https://www.npmjs.com/package/img2threejs):++ ```bash+ npx img2threejs install --dry-run+ npx img2threejs install # all detected hosts+ npx img2threejs install --host claude # only this host+ npx img2threejs update --ref v2.0.0+ npx img2threejs doctor+ ```++ Or install the CLI globally, then install the skill:++ ```bash+ npm install -g img2threejs+ img2threejs install+ ```++ Supported host directories are `~/.hermes`, `~/.claude`, `~/.codex`, and+ `$XDG_CONFIG_HOME/opencode` (default `~/.config/opencode`). The CLI fetches the+ base skill directly from GitHub at `v2.0.0` by default; `--ref` accepts a+ semantic tag (including prereleases) or full 40-character commit SHA, not a branch.+ Checkouts live under `~/.img2threejs/releases/<sha>/img2threejs`; hosts installing+ the same commit share that checkout. `update` refuses lower skill versions, including+ prerelease downgrades. The CLI does not overwrite manual installs or unrelated links.+ Move those entries yourself to switch to CLI-managed installs. `--dry-run` is offline+ and writes nothing; it does not verify that a remote ref exists or check downgrades.+ The base skill is not a plugin: `img2 add` is only for the optional plugins below.++ To test the CLI directly from this checkout, run+ `node bin/img2threejs.mjs install --dry-run`. See [CONTRIBUTING.md](CONTRIBUTING.md)+ for tarball and publication checks.+2. **Add domain plugins (optional)** — domain knowledge (CS2 skins today) lives in installedplugins, not in this checkout. Install the [img2 harness](https://github.com/img2threejs/img2)once, then add plugins to it:diff --git a/bin/img2threejs.mjs b/bin/img2threejs.mjsindex 3cf683d..8e7a1cc 100755--- a/bin/img2threejs.mjs+++ b/bin/img2threejs.mjs@@ -1,18 +1,6 @@#!/usr/bin/env node-// img2threejs CLI — installs the img2threejs skill into supported agent hosts.-//-// Subcommands:-// install [--host hermes|claude|codex|opencode|all] [--ref <tag-or-sha>] [--dry-run]-// Fetches the skill at the given ref (default: latest published skill CLI version) and links-// it into the requested host's skills directory via `npx img2 add img2threejs/img2threejs`.-// update — same as install, but rejects downgrades-// doctor — reports which hosts are detected and whether they already link to img2threejs-// version — prints this CLI version + the skill version that will be installed-//-// Safety:-// - No shell. All subprocess calls go through `execFileSync` with argv arrays.-// - Every ref must be a vX.Y.Z tag or 40-char SHA — branches are rejected.-// - Resolution is delegated to `img2 add` — single source of truth for plugin/skill install.+// Installs the base skill from a pinned Git ref. The img2 harness installs plugins,+// not this repository (which intentionally has no plugin.json).import { execFileSync } from 'node:child_process'import fs from 'node:fs'@@ -20,8 +8,8 @@ import os from 'node:os'import path from 'node:path'const SKILL_REPO = 'img2threejs/img2threejs'-// Default to the skill's current stable tag. Bumped in lockstep with the skill's semver —-// the rule that no other CLI knows which skill version matches which CLI version.+const SKILL_URL = `https://github.com/${SKILL_REPO}.git`+// CLI semver is independent of the skill release; bump this ref for a new default.const DEFAULT_REF = 'v2.0.0'const HOSTS = {@@ -58,7 +46,8 @@ const EXIT = { OK: 0, FAIL: 1, REFUSED: 2, NEEDS_INPUT: 3 }// Ref validation: must be a tag like `v1.2.3`, `v2.0.0-beta.1` or a full 40-char SHA.// Anything mutable (branch name, HEAD, short SHA) is rejected — a moved branch is a different// skill on a different day, and a short SHA can become two things after a push.-const REF_RE = /^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$|^[0-9a-f]{40}$/+const VERSION_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?$/+const REF_RE = /^[0-9a-f]{40}$/function die(code, msg, detail) {const e = new Error(msg)@@ -71,9 +60,11 @@ function readArgs(argv) {const out = { cmd: argv[2], host: 'all', ref: DEFAULT_REF, dryRun: false }for (let i = 3; i < argv.length; i++) {const a = argv[i]- if (a === '--host') out.host = argv[++i]- else if (a === '--ref') out.ref = argv[++i]- else if (a === '--dry-run') out.dryRun = true+ if (a === '--host' || a === '--ref') {+ const value = argv[++i]+ if (!value || value.startsWith('--')) die(EXIT.NEEDS_INPUT, `${a} needs a value`)+ out[a === '--host' ? 'host' : 'ref'] = value+ } else if (a === '--dry-run') out.dryRun = trueelse die(EXIT.NEEDS_INPUT, `unknown argument: ${a}`)}return out@@ -92,7 +83,9 @@ Hosts:hermes, claude, codex, opencode, all (default: auto-detect all installed)Ref:- Semantic tag (vX.Y.Z) or 40-char commit SHA. Branches and short SHAs are refused.+ Semantic tag (vX.Y.Z, optionally prerelease) or 40-char commit SHA.+ Branches and short SHAs are refused. Requires Git and network access.+ --dry-run prints the plan without downloads or filesystem changes.Examples:img2threejs install@@ -113,100 +106,168 @@ function detectHosts(hostArg) {}function validateRef(ref) {- if (!REF_RE.test(ref)) {+ if (!(ref?.startsWith('v') && VERSION_RE.test(ref.slice(1))) && !REF_RE.test(ref)) {die(EXIT.REFUSED, `ref must be a vX.Y.Z tag or 40-char SHA — got: ${ref}`,'branches and short SHAs are refused because a moving ref would be a different skill')}}-function runImg2Add(ref, dryRun) {- // Delegate everything to the existing plugin harness. Single source of truth for- // plugin/skill installation — no parallel fetch/link path to drift out of sync.- const args = [- 'img2', 'add',- SKILL_REPO,- '--ref', ref,- ...(dryRun ? ['--dry-run'] : []),- ]- try {- const out = execFileSync('npx', ['--yes', ...args], {- stdio: ['inherit', 'pipe', 'pipe'],- encoding: 'utf8',- env: { ...process.env, NPM_CONFIG_FUND: 'false', NPM_CONFIG_AUDIT: 'false' },- timeout: 120_000,- })- return { ok: true, out }- } catch (err) {- return { ok: false, err, stderr: err.stderr?.toString() ?? '', stdout: err.stdout?.toString() ?? '' }+function releasesDir() {+ return path.join(os.homedir(), '.img2threejs', 'releases')+}++function git(args, cwd) {+ return execFileSync('git', args, {+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000,+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },+ }).trim()+}++function skillVersion(dir) {+ const text = fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8')+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1]+ const version = /^version:\s*(\S+)\s*$/m.exec(frontmatter || '')?.[1]+ if (!VERSION_RE.test(version || '')) die(EXIT.FAIL, `invalid skill version in ${dir}/SKILL.md`)+ return version+}++function compareVersions(a, b) {+ const left = VERSION_RE.exec(a), right = VERSION_RE.exec(b)+ for (let i = 1; i <= 3; i++) {+ if (BigInt(left[i]) !== BigInt(right[i])) return BigInt(left[i]) > BigInt(right[i]) ? 1 : -1}+ if (left[4] === right[4]) return 0+ if (!left[4]) return 1+ if (!right[4]) return -1+ const x = left[4].split('.'), y = right[4].split('.')+ for (let i = 0; i < Math.max(x.length, y.length); i++) {+ if (x[i] === undefined) return -1+ if (y[i] === undefined) return 1+ if (x[i] === y[i]) continue+ const xn = /^\d+$/.test(x[i]), yn = /^\d+$/.test(y[i])+ if (xn && yn) return BigInt(x[i]) > BigInt(y[i]) ? 1 : -1+ if (xn !== yn) return xn ? -1 : 1+ return x[i] > y[i] ? 1 : -1+ }+ return 0}-function linkPointsAtImg2threejs(linkPath) {+function managedLink(link) {try {- const target = fs.realpathSync(linkPath)- return target.endsWith(`/img2threejs`)+ if (!fs.lstatSync(link).isSymbolicLink()) return false+ const target = fs.realpathSync(link)+ const root = fs.realpathSync(releasesDir())+ const relative = path.relative(root, target)+ return relative !== '' && !relative.startsWith(`..${path.sep}`) && relative !== '..' &&+ !path.isAbsolute(relative) && path.basename(target) === 'img2threejs'} catch {return false}}+function checkLinks(hosts) {+ for (const h of hosts) {+ const link = path.join(HOSTS[h].skills(), 'img2threejs')+ try {+ fs.lstatSync(link)+ } catch (err) {+ if (err.code === 'ENOENT') continue+ throw err+ }+ if (!managedLink(link)) die(EXIT.REFUSED, `refusing to replace an unmanaged skill at ${link}`,+ 'move the existing entry yourself before installing with this CLI')+ }+}+async function cmdInstall(args) {validateRef(args.ref)const hosts = detectHosts(args.host)if (hosts.length === 0) die(EXIT.REFUSED, 'no supported agent host detected on this machine')-- process.stdout.write(`→ will install skill ${SKILL_REPO} @ ${args.ref} into: ${hosts.join(', ')}\n`)- if (args.dryRun) process.stdout.write(' (dry-run: npx img2 will be invoked with --dry-run)\n')-- const result = runImg2Add(args.ref, args.dryRun)- if (!result.ok) {- process.stderr.write(`img2 add failed:\n${result.stderr || result.err?.message}\n`)- process.exit(EXIT.FAIL)+ checkLinks(hosts)+ process.stdout.write(`→ ${args.cmd} skill ${SKILL_REPO} @ ${args.ref} into: ${hosts.join(', ')}\n`)+ if (args.dryRun) {+ process.stdout.write('(dry-run: no downloads or filesystem changes; ref availability and downgrade checks require a real run)\n')+ return}- process.stdout.write(result.out)- // Idempotency check: confirm a skills/img2threejs entry exists for each requested host.- let linked = 0- for (const h of hosts) {- const dir = HOSTS[h].skills()- const link = path.join(dir, 'img2threejs')- if (fs.existsSync(link) && linkPointsAtImg2threejs(link)) {- process.stdout.write(`✓ ${h}: ${link}\n`)- linked++- } else if (!args.dryRun) {- process.stdout.write(`! ${h}: expected link at ${link} not present — open an issue at https://github.com/${SKILL_REPO}/issues\n`)+ const root = releasesDir()+ fs.mkdirSync(root, { recursive: true })+ const staging = fs.mkdtempSync(path.join(root, '.staging-'))+ const checkout = path.join(staging, 'img2threejs')+ try {+ fs.mkdirSync(checkout)+ git(['init', '--quiet', checkout])+ git(['remote', 'add', 'origin', SKILL_URL], checkout)+ const fetchRef = args.ref.startsWith('v') ? `refs/tags/${args.ref}` : args.ref+ git(['fetch', '--quiet', '--depth=1', 'origin', fetchRef], checkout)+ git(['checkout', '--quiet', '--detach', 'FETCH_HEAD'], checkout)+ const sha = git(['rev-parse', 'HEAD'], checkout)+ if (REF_RE.test(args.ref) && sha !== args.ref) die(EXIT.FAIL, 'fetched commit does not match requested SHA')+ const version = skillVersion(checkout)+ if (args.cmd === 'update') {+ for (const h of hosts) {+ const link = path.join(HOSTS[h].skills(), 'img2threejs')+ if (managedLink(link) && compareVersions(version, skillVersion(link)) < 0) {+ die(EXIT.REFUSED, `refusing downgrade for ${h}: ${skillVersion(link)} → ${version}`)+ }+ }}- }- if (!args.dryRun && linked === 0) {- die(EXIT.FAIL, 'install reported success but no host link was found')+ const release = path.join(root, sha)+ const target = path.join(release, 'img2threejs')+ if (!fs.existsSync(release)) {+ fs.renameSync(staging, release)+ } else {+ if (git(['rev-parse', 'HEAD'], target) !== sha ||+ git(['status', '--porcelain', '--untracked-files=all'], target) !== '') {+ die(EXIT.REFUSED, `managed checkout has local changes: ${target}`)+ }+ skillVersion(target)+ }+ checkLinks(hosts)+ for (const h of hosts) {+ const dir = HOSTS[h].skills()+ const link = path.join(dir, 'img2threejs')+ fs.mkdirSync(dir, { recursive: true })+ // Rename a temporary symlink over an owned link; never delete a user directory.+ const temporary = path.join(dir, `.img2threejs-${process.pid}`)+ try {+ fs.symlinkSync(target, temporary, 'dir')+ fs.renameSync(temporary, link)+ } finally {+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary)+ }+ if (fs.realpathSync(link) !== fs.realpathSync(target)) die(EXIT.FAIL, `host link verification failed: ${link}`)+ process.stdout.write(`✓ ${h}: ${link} → ${target} (${version}, ${sha})\n`)+ }+ } catch (err) {+ if (typeof err.code === 'number') throw err+ die(EXIT.FAIL, `skill ${args.cmd} failed: ${err.message}`, err.stderr?.toString().trim())+ } finally {+ fs.rmSync(staging, { recursive: true, force: true })}}async function cmdDoctor() {process.stdout.write('img2threejs — host detection report\n\n')for (const [name, h] of Object.entries(HOSTS)) {- const detected = h.detect()const dir = h.skills()- let linkState = '(no link)'- if (detected) {- const link = path.join(dir, 'img2threejs')- if (fs.existsSync(link)) {- linkState = linkPointsAtImg2threejs(link)- ? `installed → ${fs.realpathSync(link)}`- : `link exists but does not point at ${SKILL_REPO} — run \`img2threejs install\``+ const link = path.join(dir, 'img2threejs')+ let state = '(no link)'+ try {+ fs.lstatSync(link)+ state = `${managedLink(link) ? 'managed' : 'unmanaged'} → ${fs.realpathSync(link)} (${skillVersion(link)})`+ } catch (err) {+ if (err.code !== 'ENOENT' || fs.existsSync(dir) && fs.readdirSync(dir).includes('img2threejs')) {+ state = `invalid skill: ${err.message}`}}- const detectedLabel = detected ? '✓ detected' : '✗ not detected'- process.stdout.write(` ${name.padEnd(10)} ${detectedLabel.padEnd(15)} ${dir} ${linkState}\n`)+ process.stdout.write(` ${name.padEnd(10)} ${h.detect() ? '✓ detected' : '✗ not detected'} ${dir} ${state}\n`)}- let img2 = '(not probed)'try {- const v = execFileSync('npx', ['--yes', 'img2', '--version'], { encoding: 'utf8', timeout: 30_000 }).trim()- img2 = `✓ npx img2 — ${v.split('\n')[0]}`+ process.stdout.write(`\n ✓ ${git(['--version'])}\n`)} catch {- img2 = '✗ npx img2 not reachable (will be installed on first \`install\` run)'+ process.stdout.write('\n ✗ Git unavailable — required for install/update\n')}- process.stdout.write(`\n ${img2}\n`)}async function cmdVersion() {@@ -217,7 +278,7 @@ async function cmdVersion() {const commands = {install: cmdInstall,- update: (args) => { process.stdout.write('(update = install with downgrade rejection; same args)\n'); return cmdInstall(args) },+ update: cmdInstall,doctor: cmdDoctor,version: cmdVersion,'--version': cmdVersion,diff --git a/bin/img2threejs.mjs-test.mjs b/bin/img2threejs.mjs-test.mjsindex 12e9531..576a15f 100755--- a/bin/img2threejs.mjs-test.mjs+++ b/bin/img2threejs.mjs-test.mjs@@ -1,72 +1,171 @@#!/usr/bin/env node-// Self-contained tests for the img2threejs CLI. Run via `node bin/img2threejs.mjs-test.mjs` or-// indirectly through `npm test`. Pure: no network, no fs writes outside TMPDIR.-+// Real Git fixtures; no network and no writes outside a disposable temp directory.+import assert from 'node:assert/strict'+import { execFileSync, spawnSync } from 'node:child_process'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { spawn } from 'node:child_process'+import { fileURLToPath } from 'node:url'+import { test, after } from 'node:test'-const here = path.dirname(new URL(import.meta.url).pathname)-const cliPath = path.join(here, 'img2threejs.mjs')+const cli = fileURLToPath(new URL('./img2threejs.mjs', import.meta.url))+const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'img2threejs-test-')))+after(() => fs.rmSync(root, { recursive: true, force: true }))+const realGit = execFileSync('which', ['git'], { encoding: 'utf8' }).trim()+const repo = path.join(root, 'source')+fs.mkdirSync(repo)+const gitEnv = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_AUTHOR_NAME: 'Test', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: '[email protected]' }+function git(...args) {+ return execFileSync(realGit, args, { cwd: repo, env: gitEnv, encoding: 'utf8' }).trim()+}+git('init', '--quiet')+const commits = {}+for (const version of ['1.5.2', '2.0.0-beta.2', '2.0.0-beta.10', '2.0.0']) {+ fs.writeFileSync(path.join(repo, 'SKILL.md'), `---\nname: img2threejs\nversion: ${version}\n---\nfixture ${version}\n`)+ fs.mkdirSync(path.join(repo, 'forge'), { recursive: true })+ fs.writeFileSync(path.join(repo, 'forge', 'fixture.py'), `VERSION = '${version}'\n`)+ git('add', '.')+ git('commit', '--quiet', '-m', version)+ git('tag', `v${version}`)+ commits[version] = git('rev-parse', 'HEAD')+}+const tools = path.join(root, 'tools')+fs.mkdirSync(tools)+// Only redirect the remote URL; fetch, checkout, SHA and status use the real Git binary.+fs.writeFileSync(path.join(tools, 'git'), `#!${process.execPath}\nimport { spawnSync } from 'node:child_process';\nconst args = process.argv.slice(2).map(a => a === 'https://github.com/img2threejs/img2threejs.git' ? process.env.FIXTURE_REPO : a);\nconst result = spawnSync(process.env.REAL_GIT, args, {stdio:'inherit'});\nprocess.exit(result.status ?? 1);\n`, { mode: 0o755 })+// Extensionless executables default to CommonJS outside a package.+fs.writeFileSync(path.join(tools, 'package.json'), '{"type":"module"}')+let sequence = 0+function home(hosts = ['claude']) {+ const dir = path.join(root, `home-${sequence++}`)+ fs.mkdirSync(dir)+ for (const host of hosts) fs.mkdirSync(host === 'opencode' ? path.join(dir, 'xdg', 'opencode') : path.join(dir, `.${host}`), { recursive: true })+ return dir+}+function skills(dir, host = 'claude') {+ return host === 'opencode' ? path.join(dir, 'xdg', 'opencode', 'skills') : path.join(dir, `.${host}`, 'skills')+}+function run(dir, ...args) {+ return spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8', timeout: 20000,+ env: { ...gitEnv, HOME: dir, XDG_CONFIG_HOME: path.join(dir, 'xdg'),+ PATH: `${tools}${path.delimiter}${process.env.PATH}`, FIXTURE_REPO: repo, REAL_GIT: realGit } })+}+function success(result) {+ assert.equal(result.status, 0, result.stderr || result.error?.message)+}+function installed(dir, host = 'claude') {+ const link = path.join(skills(dir, host), 'img2threejs')+ assert.ok(fs.lstatSync(link).isSymbolicLink())+ return fs.realpathSync(link)+}-let passed = 0-let failed = 0-const failures = []+test('unknown commands and missing values fail without a host', () => {+ const dir = home([])+ assert.equal(run(dir, 'unknown').status, 3)+ assert.equal(run(dir, 'install', '--host').status, 3)+ assert.equal(run(dir, 'install', '--ref', '--dry-run').status, 3)+})-function assert(cond, msg) {- if (cond) { passed++; return }- failed++- failures.push(msg)- process.stderr.write(`FAIL: ${msg}\n`)-}+test('branches, short SHAs and malformed tags are refused', () => {+ const dir = home()+ for (const ref of ['main', '123abcd', 'v01.2.3', 'v2.0.0-beta..1', 'v2.0.0-01']) {+ assert.equal(run(dir, 'install', '--ref', ref).status, 2, ref)+ }+ assert.ok(!fs.existsSync(path.join(dir, '.img2threejs')))+})-// 1. CLI file exists and is the entry the bin field points at.-const pkg = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8'))-assert(pkg.bin?.img2threejs === 'bin/img2threejs.mjs', 'package.json bin -> bin/img2threejs.mjs')-assert(fs.existsSync(cliPath), 'bin entry exists on disk')+test('no detected hosts or an unknown host is refused', () => {+ assert.equal(run(home([]), 'install').status, 2)+ assert.equal(run(home(), 'install', '--host', 'invalid').status, 3)+})-// 2. CLI has --help subpath that exits 0 without doing anything destructive.-function runCli(argv, env = {}) {- return new Promise((resolve) => {- const proc = spawn(process.execPath, [cliPath, ...argv], {- env: { ...process.env, ...env, NPM_CONFIG_FUND: 'false' },- stdio: ['ignore', 'pipe', 'pipe'],- })- let out = '', err = ''- proc.stdout.on('data', (d) => out += d)- proc.stderr.on('data', (d) => err += d)- proc.on('close', (code) => resolve({ code, stdout: out, stderr: err }))- })-}+test('dry-run is offline and does not modify the home', () => {+ const dir = home()+ const before = fs.readdirSync(dir)+ success(run(dir, 'install', '--dry-run'))+ assert.deepEqual(fs.readdirSync(dir), before)+ assert.ok(!fs.existsSync(skills(dir)))+})-const v = await runCli(['--version'])-assert(v.code === 0, `--version exit 0 (got ${v.code})`)-assert(/img2threejs CLI: 0\.1\.0/.test(v.stdout), '--version prints CLI version')+test('explicit host installs the full pinned skill without linking other hosts', () => {+ const dir = home(['claude', 'codex', 'hermes', 'opencode'])+ success(run(dir, 'install', '--host', 'claude'))+ const target = installed(dir)+ assert.match(fs.readFileSync(path.join(target, 'SKILL.md'), 'utf8'), /version: 2\.0\.0\n/)+ assert.equal(fs.readFileSync(path.join(target, 'forge', 'fixture.py'), 'utf8'), "VERSION = '2.0.0'\n")+ assert.equal(execFileSync(realGit, ['rev-parse', 'HEAD'], { cwd: target, encoding: 'utf8' }).trim(), commits['2.0.0'])+ for (const host of ['codex', 'hermes', 'opencode']) assert.ok(!fs.existsSync(skills(dir, host)))+})-const help = await runCli(['--help'])-assert(help.code === 0, '--help exit 0')-assert(/Usage:/.test(help.stdout), '--help prints Usage')+test('all four hosts share one checkout; reinstallation is idempotent', () => {+ const dir = home(['claude', 'codex', 'hermes', 'opencode'])+ success(run(dir, 'install'))+ const target = installed(dir)+ for (const host of ['codex', 'hermes', 'opencode']) assert.equal(installed(dir, host), target)+ success(run(dir, 'install'))+ assert.equal(installed(dir), target)+ assert.deepEqual(fs.readdirSync(path.join(dir, '.img2threejs', 'releases')), [commits['2.0.0']])+ const report = run(dir, 'doctor')+ success(report)+ assert.match(report.stdout, /managed →/)+})-// 3. Ref validation: branches refused, short SHAs refused, tags and full SHAs accepted.-const src = fs.readFileSync(cliPath, 'utf8')-assert(src.includes('v\\d+\\.\\d+\\.\\d+') && src.includes('[0-9a-f]{40}'), 'REF_RE accepts only vX.Y.Z tag or 40-char SHA')-assert(!/accepts branch/i.test(src), 'docs do not advertise branch support')+test('update advances a pinned checkout and refuses tag or SHA downgrades', () => {+ const dir = home()+ success(run(dir, 'install', '--ref', 'v1.5.2'))+ success(run(dir, 'update'))+ const target = installed(dir)+ for (const ref of ['v1.5.2', commits['1.5.2']]) {+ const result = run(dir, 'update', '--ref', ref)+ assert.equal(result.status, 2, result.stderr)+ assert.match(result.stderr, /downgrade/)+ assert.equal(installed(dir), target)+ }+ assert.ok(!fs.readdirSync(path.join(dir, '.img2threejs', 'releases')).some(n => n.startsWith('.staging-')))+})-// 4. Refuse non-pinned ref with the right error code.-const badRef = await runCli(['install', '--ref', 'main', '--host', 'claude', '--dry-run'])-assert(badRef.code === 2, `refusing 'main' exit 2 (got ${badRef.code}, stderr: ${badRef.stderr})`)+test('prerelease precedence uses numeric identifiers and stable beats prerelease', () => {+ const dir = home()+ success(run(dir, 'install', '--ref', 'v2.0.0-beta.2'))+ success(run(dir, 'update', '--ref', 'v2.0.0-beta.10'))+ assert.equal(run(dir, 'update', '--ref', 'v2.0.0-beta.2').status, 2)+ success(run(dir, 'update', '--ref', commits['2.0.0']))+ assert.equal(run(dir, 'update', '--ref', 'v2.0.0-beta.10').status, 2)+})-// 5. Hosts listed in --help match the canonical four. Scope: hermes, claude, codex, opencode.-for (const host of ['hermes', 'claude', 'codex', 'opencode']) {- assert(help.stdout.includes(host), `--help mentions host: ${host}`)-}+test('unmanaged directories and symlinks are preserved; no hosts partially installed', () => {+ for (const kind of ['directory', 'symlink']) {+ const dir = home(['claude', 'codex'])+ fs.mkdirSync(skills(dir, 'codex'), { recursive: true })+ const link = path.join(skills(dir, 'codex'), 'img2threejs')+ if (kind === 'directory') {+ fs.mkdirSync(link)+ fs.writeFileSync(path.join(link, 'keep'), 'user data')+ } else fs.symlinkSync(path.join(dir, 'nonexistent'), link)+ assert.equal(run(dir, 'install').status, 2)+ assert.ok(!fs.existsSync(skills(dir)))+ if (kind === 'directory') assert.equal(fs.readFileSync(path.join(link, 'keep'), 'utf8'), 'user data')+ else assert.equal(fs.readlinkSync(link), path.join(dir, 'nonexistent'))+ assert.ok(!fs.existsSync(path.join(dir, '.img2threejs')))+ }+})-// 6. Optional: doctor dry-run doesn't require network. Skip if running with no host present.-const doc = await runCli(['doctor'])-assert(doc.code === 0 || doc.code === 1, `doctor exit sane (got ${doc.code})`)+test('a missing ref preserves the existing installation and cleans staging', () => {+ const dir = home()+ success(run(dir, 'install'))+ const target = installed(dir)+ assert.equal(run(dir, 'update', '--ref', 'v99.0.0').status, 1)+ assert.equal(installed(dir), target)+ assert.deepEqual(fs.readdirSync(path.join(dir, '.img2threejs', 'releases')), [commits['2.0.0']])+})-process.stdout.write(`\nimg2threejs CLI self-test: ${passed} passed, ${failed} failed\n`)-if (failed > 0) {- process.exit(1)-}+test('local edits in an existing managed release are never overwritten', () => {+ const dir = home()+ success(run(dir, 'install'))+ const target = installed(dir)+ fs.writeFileSync(path.join(target, 'forge', 'fixture.py'), 'user edit\n')+ assert.equal(run(dir, 'install').status, 2)+ assert.equal(fs.readFileSync(path.join(target, 'forge', 'fixture.py'), 'utf8'), 'user edit\n')+})diff --git a/package.json b/package.jsonindex 1bf85e1..390612b 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "img2threejs",- "version": "0.1.0",+ "version": "0.1.1","description": "Install and update the img2threejs skill into agent hosts (Hermes, Claude Code, Codex, OpenCode).","license": "Apache-2.0","type": "module",@@ -11,11 +11,11 @@"node": ">=18"},"scripts": {- "test": "node bin/img2threejs.mjs-test.mjs",+ "test": "node --test bin/img2threejs.mjs-test.mjs","package:check": "npm pack --dry-run"},"files": [- "bin"+ "bin/img2threejs.mjs"],"keywords": ["img2threejs",