synclet 2.0.1

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/index.js ADDED
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const { spawn, spawnSync } = require("child_process");
5
+
6
+ const RUNNER = path.join(__dirname, "update_check_runner.js");
7
+ const {
8
+ maybePrintCachedNotice,
9
+ spawnUpdateCheckRunner,
10
+ } = require("./update_check");
11
+
12
+ const exe = process.platform === "win32" ? "synclet.exe" : "synclet";
13
+ const binPath = path.join(__dirname, exe);
14
+
15
+ const PKG = (() => {
16
+ try {
17
+ return require("./package.json");
18
+ } catch {
19
+ return null;
20
+ }
21
+ })();
22
+
23
+ if (!fs.existsSync(binPath)) {
24
+ console.error(`Binary not found: ${binPath}. Attempting to download...`);
25
+ const result = spawnSync(
26
+ process.execPath,
27
+ [path.join(__dirname, "postinstall.js")],
28
+ { stdio: "inherit" },
29
+ );
30
+ if (result.status !== 0 || !fs.existsSync(binPath)) {
31
+ console.error("Failed to download binary.");
32
+ process.exit(1);
33
+ }
34
+ }
35
+
36
+ if (process.platform !== "win32") {
37
+ try {
38
+ fs.chmodSync(binPath, 0o755);
39
+ } catch {}
40
+ }
41
+
42
+ const child = spawn(binPath, process.argv.slice(2), {
43
+ stdio: "inherit",
44
+ windowsHide: true,
45
+ });
46
+
47
+ // Best-effort update notice.
48
+ try {
49
+ maybePrintCachedNotice({ installedVersion: PKG && PKG.version });
50
+ spawnUpdateCheckRunner();
51
+ } catch {}
52
+
53
+ child.on("exit", (code) => {
54
+ process.exitCode = code == null ? 1 : code;
55
+ });
56
+ child.on("error", (err) => {
57
+ console.error(err.message);
58
+ process.exitCode = 1;
59
+ });
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "synclet",
3
+ "version": "2.0.1",
4
+ "description": "CLI interface for syncing with Synclet (formerly ConfigMesh)",
5
+ "homepage": "https://synclet.dev",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/dvcrn/synclet-cli.git"
9
+ },
10
+ "keywords": [
11
+ "synclet",
12
+ "configmesh",
13
+ "dotfiles",
14
+ "sync",
15
+ "cli"
16
+ ],
17
+ "files": [
18
+ "index.js",
19
+ "postinstall.js",
20
+ "update_check.js",
21
+ "update_check_runner.js"
22
+ ],
23
+ "dependencies": {
24
+ "semver": "^7.7.2"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "bin": {
30
+ "synclet": "index.js"
31
+ },
32
+ "scripts": {
33
+ "postinstall": "node postinstall.js"
34
+ }
35
+ }
package/postinstall.js ADDED
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env node
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const os = require("os");
5
+ const https = require("https");
6
+ const crypto = require("crypto");
7
+ const { spawnSync } = require("child_process");
8
+
9
+ const OWNER = "dvcrn";
10
+ const REPO = "synclet-cli";
11
+ const BIN = "synclet";
12
+
13
+ // Synclet was previously named ConfigMesh. Each override is read as SYNCLET_*
14
+ // first and falls back to the legacy CONFIGMESH_* name.
15
+ function envOverride(suffix) {
16
+ const current = process.env[`SYNCLET_${suffix}`];
17
+ if (current) return current;
18
+ return process.env[`CONFIGMESH_${suffix}`] || "";
19
+ }
20
+
21
+ function httpGet(url, { headers } = {}) {
22
+ return new Promise((resolve, reject) => {
23
+ const req = https.get(url, { headers }, (res) => {
24
+ if (
25
+ res.statusCode &&
26
+ res.statusCode >= 300 &&
27
+ res.statusCode < 400 &&
28
+ res.headers.location
29
+ ) {
30
+ resolve(httpGet(res.headers.location, { headers }));
31
+ return;
32
+ }
33
+ if (res.statusCode !== 200) {
34
+ reject(new Error(`GET ${url} -> ${res.statusCode}`));
35
+ return;
36
+ }
37
+ const chunks = [];
38
+ res.on("data", (c) => chunks.push(c));
39
+ res.on("end", () => resolve(Buffer.concat(chunks)));
40
+ });
41
+ req.on("error", reject);
42
+ });
43
+ }
44
+
45
+ function sha256(buf) {
46
+ const h = crypto.createHash("sha256");
47
+ h.update(buf);
48
+ return h.digest("hex");
49
+ }
50
+
51
+ function parseChecksums(text) {
52
+ const map = new Map();
53
+ const lines = text
54
+ .split(/\r?\n/)
55
+ .map((l) => l.trim())
56
+ .filter(Boolean);
57
+ for (const line of lines) {
58
+ let m = line.match(/^([a-f0-9]{64})\s+(.+)$/i);
59
+ if (m) {
60
+ map.set(m[2], m[1]);
61
+ continue;
62
+ }
63
+ m = line.match(/^sha256:([a-f0-9]{64})\s+(.+)$/i);
64
+ if (m) {
65
+ map.set(m[2], m[1]);
66
+ continue;
67
+ }
68
+ m = line.match(/^SHA256\s+\((.+)\)\s+=\s+([a-f0-9]{64})$/i);
69
+ if (m) {
70
+ map.set(m[1], m[2]);
71
+ continue;
72
+ }
73
+ }
74
+ return map;
75
+ }
76
+
77
+ (async function main() {
78
+ try {
79
+ const platform = envOverride("PLATFORM") || process.platform;
80
+ if (!["darwin", "linux"].includes(platform)) {
81
+ console.error(
82
+ "synclet: npm install supports macOS (darwin) and Linux only",
83
+ );
84
+ process.exit(1);
85
+ }
86
+
87
+ const pkg = JSON.parse(
88
+ fs.readFileSync(path.join(__dirname, "package.json"), "utf8"),
89
+ );
90
+ const version = envOverride("VERSION") || pkg.version || "";
91
+ if (!version) {
92
+ console.error("postinstall: could not determine version");
93
+ process.exit(1);
94
+ }
95
+
96
+ const detectedArch =
97
+ process.arch === "x64"
98
+ ? "amd64"
99
+ : process.arch === "arm64"
100
+ ? "arm64"
101
+ : process.arch === "arm"
102
+ ? "armv7"
103
+ : process.arch;
104
+ const arch = envOverride("ARCH") || detectedArch;
105
+ if (!["amd64", "arm64", "armv7"].includes(arch)) {
106
+ console.error(`Unsupported arch: ${arch}`);
107
+ process.exit(1);
108
+ }
109
+
110
+ const assetName = `${BIN}_${version}_${platform}_${arch}.tar.gz`;
111
+ const base =
112
+ envOverride("BASE_URL") ||
113
+ `https://github.com/${OWNER}/${REPO}/releases/download/${version}`;
114
+ const url = `${base}/${assetName}`;
115
+ const checksumsUrl = `${base}/checksums.txt`;
116
+ const headers = { "User-Agent": `${REPO}-postinstall` };
117
+ const outDir = __dirname;
118
+ const exe = BIN;
119
+ const binPath = path.join(outDir, exe);
120
+
121
+ if (fs.existsSync(binPath)) {
122
+ try {
123
+ fs.chmodSync(binPath, 0o755);
124
+ } catch {}
125
+ return;
126
+ }
127
+
128
+ console.log(`postinstall: downloading ${assetName} from ${url}`);
129
+ const tarGz = await httpGet(url, { headers });
130
+
131
+ // checksum (best effort)
132
+ try {
133
+ const checksumsBuf = await httpGet(checksumsUrl, { headers });
134
+ const checksums = parseChecksums(checksumsBuf.toString("utf8"));
135
+ const sumExpected = checksums.get(assetName);
136
+ if (!sumExpected) throw new Error("asset not in checksums.txt");
137
+ const sumActual = sha256(tarGz);
138
+ if (sumActual.toLowerCase() !== sumExpected.toLowerCase())
139
+ throw new Error("checksum mismatch");
140
+ console.log("postinstall: checksum OK");
141
+ } catch (e) {
142
+ console.warn(`postinstall: checksum skipped/failed: ${e.message}`);
143
+ }
144
+
145
+ // extract only the binary into npm directory (archive contains binary at root)
146
+ const tmpFile = path.join(os.tmpdir(), `${REPO}-${Date.now()}.tar.gz`);
147
+ fs.writeFileSync(tmpFile, tarGz);
148
+ const tarRes = spawnSync("tar", ["-xzf", tmpFile, "-C", outDir, exe], {
149
+ stdio: "inherit",
150
+ });
151
+ if (tarRes.status !== 0) {
152
+ console.error("postinstall: failed to extract binary");
153
+ process.exit(1);
154
+ }
155
+ try {
156
+ fs.chmodSync(binPath, 0o755);
157
+ } catch {}
158
+ try {
159
+ fs.unlinkSync(tmpFile);
160
+ } catch {}
161
+ console.log(`postinstall: installed ${exe} to ${outDir}`);
162
+ process.exit(0);
163
+ } catch (err) {
164
+ console.error(`postinstall error: ${err.message}`);
165
+ process.exit(1);
166
+ }
167
+ })();
@@ -0,0 +1,221 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const https = require('https');
5
+ const { spawn } = require('child_process');
6
+ const semver = require('semver');
7
+
8
+ const DEFAULT_PACKAGE_NAME = 'synclet';
9
+ const DEFAULT_UPDATE_COMMAND = 'npm install -g synclet';
10
+
11
+ const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
12
+ const UPDATE_CHECK_TIMEOUT_MS = 1200;
13
+
14
+ const RUNNER_FILE = 'update_check_runner.js';
15
+
16
+ function isDisabled() {
17
+ return (
18
+ process.env.SYNCLET_NO_UPDATE_NOTICE === '1' ||
19
+ process.env.SYNCLET_NO_UPDATE_NOTICE === 'true' ||
20
+ process.env.CONFIGMESH_NO_UPDATE_NOTICE === '1' ||
21
+ process.env.CONFIGMESH_NO_UPDATE_NOTICE === 'true' ||
22
+ process.env.NO_UPDATE_NOTIFIER === '1' ||
23
+ process.env.NO_UPDATE_NOTIFIER === 'true' ||
24
+ process.env.CI === '1' ||
25
+ process.env.CI === 'true' ||
26
+ process.env.CI === 'yes'
27
+ );
28
+ }
29
+
30
+ function shouldPrintNotice() {
31
+ if (isDisabled()) return false;
32
+ if (!process.stderr.isTTY) return false;
33
+ return true;
34
+ }
35
+
36
+ function getCacheFile() {
37
+ const home = os.homedir();
38
+ if (!home) return null;
39
+
40
+ if (process.platform === 'win32') {
41
+ const base = process.env.LOCALAPPDATA || process.env.APPDATA;
42
+ if (!base) return path.join(home, 'AppData', 'Local', DEFAULT_PACKAGE_NAME, 'update.json');
43
+ return path.join(base, DEFAULT_PACKAGE_NAME, 'update.json');
44
+ }
45
+
46
+ if (process.platform === 'darwin') {
47
+ return path.join(home, 'Library', 'Caches', DEFAULT_PACKAGE_NAME, 'update.json');
48
+ }
49
+
50
+ const base = process.env.XDG_CACHE_HOME || path.join(home, '.cache');
51
+ return path.join(base, DEFAULT_PACKAGE_NAME, 'update.json');
52
+ }
53
+
54
+ function readCache() {
55
+ const file = getCacheFile();
56
+ if (!file) return null;
57
+ try {
58
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ function writeCache(data) {
65
+ const file = getCacheFile();
66
+ if (!file) return;
67
+ const tmp = file + '.tmp.' + process.pid + '.' + Date.now();
68
+ try {
69
+ fs.mkdirSync(path.dirname(file), { recursive: true });
70
+ fs.writeFileSync(tmp, JSON.stringify(data), 'utf8');
71
+ fs.renameSync(tmp, file);
72
+ } catch (e) {
73
+ try { fs.unlinkSync(tmp); } catch {}
74
+ }
75
+ }
76
+
77
+ function fetchLatestVersion(packageName, timeoutMs, signal) {
78
+ const url = `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`;
79
+
80
+ return new Promise((resolve, reject) => {
81
+ const req = https.get(
82
+ url,
83
+ { headers: { 'User-Agent': `${DEFAULT_PACKAGE_NAME}-update-check` } },
84
+ (res) => {
85
+ if (res.statusCode !== 200) {
86
+ reject(new Error(`GET ${url} -> ${res.statusCode}`));
87
+ res.resume();
88
+ return;
89
+ }
90
+
91
+ const chunks = [];
92
+ res.on('data', (c) => chunks.push(c));
93
+ res.on('end', () => {
94
+ try {
95
+ const json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
96
+ resolve(typeof json.version === 'string' ? json.version : '');
97
+ } catch (e) {
98
+ reject(e);
99
+ }
100
+ });
101
+ }
102
+ );
103
+
104
+ req.on('error', reject);
105
+ req.setTimeout(timeoutMs, () => req.destroy(new Error('timeout')));
106
+
107
+ if (signal) {
108
+ if (signal.aborted) {
109
+ req.destroy(new Error('aborted'));
110
+ return;
111
+ }
112
+ signal.addEventListener('abort', () => req.destroy(new Error('aborted')), { once: true });
113
+ }
114
+ });
115
+ }
116
+
117
+ function normalizeVersion(version) {
118
+ if (!version) return '';
119
+ const cleaned = semver.clean(version);
120
+ if (cleaned) return cleaned;
121
+ const coerced = semver.coerce(version);
122
+ return coerced ? semver.valid(coerced) || '' : '';
123
+ }
124
+
125
+ function printNotice({ packageName, installed, latest, updateCommand }) {
126
+ const prefix = `${packageName}:`;
127
+ if (installed && latest) {
128
+ console.error(
129
+ `${prefix} an update is available (installed ${installed}, latest ${latest}). Update with: ${updateCommand}`
130
+ );
131
+ return;
132
+ }
133
+ console.error(`${prefix} an update is available. Update with: ${updateCommand}`);
134
+ }
135
+
136
+ function getCachedUpdate({ installedVersion, now = Date.now() }) {
137
+ const installed = normalizeVersion(installedVersion);
138
+ if (!installed) return null;
139
+
140
+ const cache = readCache() || {};
141
+ const cachedLatest = typeof cache.latest === 'string' ? cache.latest : '';
142
+ const latest = normalizeVersion(cachedLatest);
143
+ if (!latest) return null;
144
+
145
+ if (!semver.gt(latest, installed)) return null;
146
+
147
+ const lastNotified = Number.isFinite(cache.lastNotified) ? cache.lastNotified : 0;
148
+ const canNotify = !lastNotified || (now - lastNotified) >= UPDATE_CHECK_INTERVAL_MS;
149
+ return {
150
+ latest,
151
+ installed,
152
+ canNotify,
153
+ cache,
154
+ };
155
+ }
156
+
157
+ function maybePrintCachedNotice({
158
+ packageName = DEFAULT_PACKAGE_NAME,
159
+ installedVersion,
160
+ updateCommand = DEFAULT_UPDATE_COMMAND,
161
+ } = {}) {
162
+ if (!shouldPrintNotice()) return false;
163
+
164
+ const now = Date.now();
165
+ const cached = getCachedUpdate({ installedVersion, now });
166
+ if (!cached || !cached.canNotify) return false;
167
+
168
+ printNotice({ packageName, installed: cached.installed, latest: cached.latest, updateCommand });
169
+ writeCache({ ...cached.cache, lastNotified: now });
170
+ return true;
171
+ }
172
+
173
+ async function refreshCache({ packageName = DEFAULT_PACKAGE_NAME, signal } = {}) {
174
+ if (isDisabled()) return;
175
+
176
+ const cache = readCache() || {};
177
+ const lastChecked = Number.isFinite(cache.lastChecked) ? cache.lastChecked : 0;
178
+ const now = Date.now();
179
+ if (lastChecked && (now - lastChecked) < UPDATE_CHECK_INTERVAL_MS) return;
180
+
181
+ const latestRaw = await fetchLatestVersion(packageName, UPDATE_CHECK_TIMEOUT_MS, signal);
182
+ const latest = normalizeVersion(latestRaw);
183
+
184
+ writeCache({
185
+ ...cache,
186
+ lastChecked: now,
187
+ latest: latest || latestRaw,
188
+ });
189
+ }
190
+
191
+ function needsCacheRefresh({ packageName = DEFAULT_PACKAGE_NAME, now = Date.now() } = {}) {
192
+ if (isDisabled()) return false;
193
+ // Only refresh when we're past the check interval.
194
+ const cache = readCache() || {};
195
+ const lastChecked = Number.isFinite(cache.lastChecked) ? cache.lastChecked : 0;
196
+ if (!lastChecked) return true;
197
+ return (now - lastChecked) >= UPDATE_CHECK_INTERVAL_MS;
198
+ }
199
+
200
+ function spawnUpdateCheckRunner() {
201
+ if (isDisabled()) return;
202
+ if (!needsCacheRefresh()) return;
203
+
204
+ try {
205
+ const runnerPath = path.join(__dirname, RUNNER_FILE);
206
+ const child = spawn(
207
+ process.execPath,
208
+ [runnerPath],
209
+ { stdio: 'ignore', detached: true, windowsHide: true }
210
+ );
211
+ child.unref();
212
+ } catch (e) {
213
+ // ignore errors starting the update check
214
+ }
215
+ }
216
+
217
+ module.exports = {
218
+ maybePrintCachedNotice,
219
+ refreshCache,
220
+ spawnUpdateCheckRunner,
221
+ };
@@ -0,0 +1,8 @@
1
+ const { refreshCache } = require('./update_check');
2
+
3
+ async function main() {
4
+ // Background refresh only; do not print from here.
5
+ await refreshCache();
6
+ }
7
+
8
+ main().catch(() => {});