@joripspace/cli 0.4.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.
@@ -0,0 +1,198 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { spawnSync } = require('node:child_process');
4
+ const { resolveProjectFileTarget } = require('./project-paths');
5
+
6
+ const PROJECT_ENV_FILE = '.env.joripspace';
7
+ function readProjectEnv(workspaceDir) {
8
+ assertProjectEnvUntracked(workspaceDir);
9
+ const envPath = managedProjectFilePath(workspaceDir, PROJECT_ENV_FILE);
10
+ return readDotEnvFile(envPath);
11
+ }
12
+
13
+ function readDotEnvFile(filePath) {
14
+ const values = {};
15
+ try {
16
+ for (const line of fs.readFileSync(filePath, 'utf8').split(/\r?\n/)) {
17
+ const trimmed = line.trim();
18
+ if (!trimmed || trimmed.startsWith('#')) continue;
19
+ const index = trimmed.indexOf('=');
20
+ if (index <= 0) continue;
21
+ const key = trimmed.slice(0, index).trim();
22
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
23
+ values[key] = parseDotEnvValue(trimmed.slice(index + 1));
24
+ }
25
+ } catch {}
26
+ return values;
27
+ }
28
+
29
+ function updateDotEnvFile(filePath, updates) {
30
+ if (path.basename(filePath).toLowerCase() === PROJECT_ENV_FILE) {
31
+ const workspaceDir = path.dirname(filePath);
32
+ assertProjectEnvUntracked(workspaceDir);
33
+ ensureProjectEnvIgnored(workspaceDir);
34
+ filePath = managedProjectFilePath(workspaceDir, PROJECT_ENV_FILE);
35
+ }
36
+ let lines = [];
37
+ try {
38
+ lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
39
+ } catch {}
40
+ const pending = new Map(
41
+ Object.entries(updates).filter(([, value]) => value !== undefined && value !== null && value !== '')
42
+ );
43
+ const written = new Set();
44
+ const next = lines
45
+ .filter((line, index) => index < lines.length - 1 || line !== '')
46
+ .flatMap((line) => {
47
+ const match = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
48
+ if (!match || !pending.has(match[1])) return [line];
49
+ if (written.has(match[1])) return [];
50
+ const value = pending.get(match[1]);
51
+ written.add(match[1]);
52
+ return [`${match[1]}=${formatDotEnvValue(value)}`];
53
+ });
54
+ for (const [key, value] of pending) {
55
+ if (!written.has(key)) next.push(`${key}=${formatDotEnvValue(value)}`);
56
+ }
57
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
58
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
59
+ fs.writeFileSync(temporaryPath, `${next.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 });
60
+ replaceFileAtomically(temporaryPath, filePath);
61
+ if (process.platform !== 'win32') fs.chmodSync(filePath, 0o600);
62
+ }
63
+
64
+ function parseDotEnvValue(value) {
65
+ const trimmed = String(value || '').trim();
66
+ if (trimmed.length < 2) return trimmed;
67
+ const quote = trimmed[0];
68
+ if ((quote !== '"' && quote !== "'") || trimmed.at(-1) !== quote) return trimmed;
69
+ const inner = trimmed.slice(1, -1);
70
+ if (quote === "'") return inner;
71
+ return inner.replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
72
+ }
73
+
74
+ function formatDotEnvValue(value) {
75
+ const source = String(value);
76
+ if (/^[^\s#'"\\]+$/.test(source)) return source;
77
+ return `"${source.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\r/g, '\\r').replace(/\n/g, '\\n')}"`;
78
+ }
79
+
80
+ function ensureProjectEnvIgnored(workspaceDir) {
81
+ assertProjectEnvUntracked(workspaceDir);
82
+ const filePath = managedProjectFilePath(workspaceDir, '.gitignore');
83
+ const ignored = git(workspaceDir, ['check-ignore', '--no-index', '--quiet', '--', PROJECT_ENV_FILE]);
84
+ if (ignored.status === 0) return false;
85
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
86
+ const lines = existing.split(/\r?\n/).filter((line) => line.trim() !== PROJECT_ENV_FILE);
87
+ while (lines.at(-1) === '') lines.pop();
88
+ lines.push(PROJECT_ENV_FILE);
89
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
90
+ fs.writeFileSync(temporaryPath, `${lines.join('\n')}\n`, 'utf8');
91
+ replaceFileAtomically(temporaryPath, filePath);
92
+ const verified = git(workspaceDir, ['check-ignore', '--no-index', '--quiet', '--', PROJECT_ENV_FILE]);
93
+ if (verified.status !== 0 && findGitMetadata(workspaceDir)) {
94
+ const error = new Error(`${PROJECT_ENV_FILE} is not effectively ignored by Git`);
95
+ error.code = 'project_env_not_ignored';
96
+ throw error;
97
+ }
98
+ return true;
99
+ }
100
+
101
+ function assertProjectEnvUntracked(workspaceDir) {
102
+ const tracked = git(workspaceDir, ['ls-files', '--error-unmatch', '--', `:(icase)${PROJECT_ENV_FILE}`]);
103
+ if (tracked.status === 0) {
104
+ const error = new Error(
105
+ `${PROJECT_ENV_FILE} is tracked by Git. Remove it from the index before storing a token: git rm --cached -- ${PROJECT_ENV_FILE}`
106
+ );
107
+ error.code = 'project_env_tracked';
108
+ throw error;
109
+ }
110
+ if (tracked.status !== 1 && findGitMetadata(workspaceDir)) {
111
+ const error = new Error(`Git could not verify that ${PROJECT_ENV_FILE} is untracked`);
112
+ error.code = 'project_env_git_verification_failed';
113
+ throw error;
114
+ }
115
+ assertCanonicalProjectEnvCasing(workspaceDir);
116
+ }
117
+
118
+ function assertCanonicalProjectEnvCasing(workspaceDir) {
119
+ const matches = fs
120
+ .readdirSync(path.resolve(workspaceDir))
121
+ .filter((entry) => entry.toLowerCase() === PROJECT_ENV_FILE);
122
+ if (!matches.length) return;
123
+ if (matches.length !== 1 || matches[0] !== PROJECT_ENV_FILE) {
124
+ const error = new Error(`${PROJECT_ENV_FILE} must use canonical lowercase casing`);
125
+ error.code = 'non_canonical_workspace_path';
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ function findGitMetadata(workspaceDir) {
131
+ let current = path.resolve(workspaceDir);
132
+ while (true) {
133
+ if (fs.existsSync(path.join(current, '.git'))) return true;
134
+ const parent = path.dirname(current);
135
+ if (parent === current) return false;
136
+ current = parent;
137
+ }
138
+ }
139
+
140
+ function git(workspaceDir, args) {
141
+ return spawnSync('git', ['-C', path.resolve(workspaceDir), ...args], {
142
+ encoding: 'utf8',
143
+ windowsHide: true,
144
+ });
145
+ }
146
+
147
+ function replaceFileAtomically(temporaryPath, filePath) {
148
+ try {
149
+ fs.renameSync(temporaryPath, filePath);
150
+ return;
151
+ } catch (error) {
152
+ const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
153
+ try {
154
+ if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
155
+ fs.renameSync(temporaryPath, filePath);
156
+ fs.rmSync(backupPath, { force: true });
157
+ return;
158
+ } catch {
159
+ try {
160
+ if (fs.existsSync(backupPath) && !fs.existsSync(filePath)) fs.renameSync(backupPath, filePath);
161
+ } catch {}
162
+ fs.rmSync(temporaryPath, { force: true });
163
+ throw error;
164
+ }
165
+ }
166
+ }
167
+
168
+ function removeGitignoreEntries(workspaceDir, entries) {
169
+ const filePath = managedProjectFilePath(workspaceDir, '.gitignore');
170
+ if (!fs.existsSync(filePath)) return;
171
+ const existing = fs.readFileSync(filePath, 'utf8');
172
+ const removals = new Set(entries);
173
+ const lines = existing.split(/\r?\n/).filter((line) => !removals.has(line.trim()));
174
+ while (lines.at(-1) === '') lines.pop();
175
+ const next = lines.length > 0 ? `${lines.join('\n')}\n` : '';
176
+ if (next === existing) return;
177
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
178
+ fs.writeFileSync(temporaryPath, next);
179
+ replaceFileAtomically(temporaryPath, filePath);
180
+ }
181
+
182
+ function managedProjectFilePath(workspaceDir, relative) {
183
+ const location = resolveProjectFileTarget(workspaceDir, relative);
184
+ if (location.blockers.length) {
185
+ throw new Error(`managed project file path is blocked: ${location.blockers.join(', ')}`);
186
+ }
187
+ return location.target;
188
+ }
189
+
190
+ module.exports = {
191
+ PROJECT_ENV_FILE,
192
+ assertProjectEnvUntracked,
193
+ ensureProjectEnvIgnored,
194
+ readDotEnvFile,
195
+ readProjectEnv,
196
+ removeGitignoreEntries,
197
+ updateDotEnvFile,
198
+ };
@@ -0,0 +1,257 @@
1
+ const fs = require('node:fs');
2
+ const crypto = require('node:crypto');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+
6
+ function safeProjectRelativePath(value, errorPrefix = 'unsafe project file path') {
7
+ const normalized = String(value || '')
8
+ .replace(/\\/g, '/')
9
+ .replace(/^\.\//, '');
10
+ if (
11
+ !normalized ||
12
+ normalized.startsWith('/') ||
13
+ /^[A-Za-z]:\//.test(normalized) ||
14
+ normalized
15
+ .split('/')
16
+ .some(
17
+ (part) =>
18
+ !part ||
19
+ part === '.' ||
20
+ part === '..' ||
21
+ /[ .]$/.test(part) ||
22
+ /[<>:"|?*\x00-\x1f]/.test(part) ||
23
+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part)
24
+ )
25
+ ) {
26
+ throw new Error(`${errorPrefix}: ${value}`);
27
+ }
28
+ return normalized;
29
+ }
30
+
31
+ function resolveProjectFileTarget(root, value, errorPrefix = 'unsafe project file path') {
32
+ const relative = safeProjectRelativePath(value, errorPrefix);
33
+ const rootPath = realProjectRoot(root);
34
+ const target = path.resolve(rootPath, ...relative.split('/'));
35
+ assertContained(rootPath, target, relative);
36
+ const blockers = [];
37
+ let current = rootPath;
38
+ const parts = relative.split('/');
39
+ for (let index = 0; index < parts.length; index += 1) {
40
+ current = path.join(current, parts[index]);
41
+ const stat = lstatOrNull(current);
42
+ if (!stat) continue;
43
+ if (stat.isSymbolicLink()) {
44
+ throw new Error(
45
+ `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
46
+ );
47
+ }
48
+ const isTarget = index === parts.length - 1;
49
+ if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
50
+ blockers.push(parts.slice(0, index + 1).join('/'));
51
+ break;
52
+ }
53
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
54
+ }
55
+ return { blockers, relative, root: rootPath, target };
56
+ }
57
+
58
+ function backupAndRemoveProjectPaths(root, relatives, backupRoot) {
59
+ const selected = minimalPaths(relatives);
60
+ const rootPath = realProjectRoot(root);
61
+ if (!path.isAbsolute(backupRoot)) {
62
+ throw new Error('project backups must use an absolute directory outside the workspace');
63
+ }
64
+ const backupLocation = fs.realpathSync.native(path.resolve(backupRoot));
65
+ const fromWorkspace = path.relative(rootPath, backupLocation);
66
+ if (isContainedRelative(fromWorkspace)) {
67
+ throw new Error('project backups must use an absolute directory outside the workspace');
68
+ }
69
+ const backupStat = fs.lstatSync(backupLocation);
70
+ if (!backupStat.isDirectory() || backupStat.isSymbolicLink()) {
71
+ throw new Error('project backup target is not a safe directory');
72
+ }
73
+ for (const relative of selected) {
74
+ const location = resolveExistingProjectPath(root, relative);
75
+ if (!location) continue;
76
+ const backup = path.join(backupLocation, ...relative.split('/'));
77
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
78
+ if (location.stat.isDirectory()) {
79
+ fs.cpSync(location.target, backup, { recursive: true, errorOnExist: true });
80
+ } else {
81
+ fs.copyFileSync(location.target, backup, fs.constants.COPYFILE_EXCL);
82
+ }
83
+ fs.rmSync(location.target, { recursive: location.stat.isDirectory(), force: true });
84
+ }
85
+ return selected;
86
+ }
87
+
88
+ function createExternalBackupRoot(workspaceDir, category = 'restore', dataRootOverride = '') {
89
+ const workspace = realProjectRoot(workspaceDir);
90
+ const configuredRoot = String(dataRootOverride || process.env.JORIPSPACE_DATA_DIR || '').trim();
91
+ const dataRoot = configuredRoot
92
+ ? path.resolve(configuredRoot)
93
+ : process.platform === 'win32'
94
+ ? path.join(process.env.LOCALAPPDATA || os.homedir(), 'JoripSpace')
95
+ : process.platform === 'darwin'
96
+ ? path.join(os.homedir(), 'Library', 'Application Support', 'JoripSpace')
97
+ : path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'joripspace');
98
+ const workspaceKey = crypto
99
+ .createHash('sha256')
100
+ .update(process.platform === 'win32' ? workspace.toLowerCase() : workspace)
101
+ .digest('hex')
102
+ .slice(0, 20);
103
+ const safeCategory = String(category || 'restore').toLowerCase();
104
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(safeCategory)) {
105
+ throw new Error('invalid backup category');
106
+ }
107
+ const resolvedDataRoot = prospectiveRealPath(dataRoot);
108
+ const dataFromWorkspace = path.relative(workspace, resolvedDataRoot);
109
+ if (isContainedRelative(dataFromWorkspace)) {
110
+ throw new Error('JoripSpace user data directory must be outside the project workspace');
111
+ }
112
+ const parent = path.join(resolvedDataRoot, 'backups', workspaceKey, safeCategory);
113
+ fs.mkdirSync(parent, { recursive: true });
114
+ const realParent = fs.realpathSync.native(parent);
115
+ const fromWorkspace = path.relative(workspace, realParent);
116
+ if (isContainedRelative(fromWorkspace)) {
117
+ throw new Error('JoripSpace user data directory must be outside the project workspace');
118
+ }
119
+ const backupRoot = path.join(
120
+ realParent,
121
+ `${new Date().toISOString().replace(/[:.]/g, '-')}-${crypto.randomUUID()}`
122
+ );
123
+ fs.mkdirSync(backupRoot, { recursive: false, mode: 0o700 });
124
+ return fs.realpathSync.native(backupRoot);
125
+ }
126
+
127
+ function prospectiveRealPath(target) {
128
+ let current = path.resolve(target);
129
+ const missing = [];
130
+ while (!fs.existsSync(current)) {
131
+ const parent = path.dirname(current);
132
+ if (parent === current) break;
133
+ missing.unshift(path.basename(current));
134
+ current = parent;
135
+ }
136
+ const existing = fs.realpathSync.native(current);
137
+ return path.join(existing, ...missing);
138
+ }
139
+
140
+ function resolveProjectDirectoryTarget(root, value) {
141
+ const relative = safeProjectRelativePath(value);
142
+ const rootPath = realProjectRoot(root);
143
+ const target = path.resolve(rootPath, ...relative.split('/'));
144
+ assertContained(rootPath, target, relative);
145
+ let current = rootPath;
146
+ for (const [index, part] of relative.split('/').entries()) {
147
+ current = path.join(current, part);
148
+ const stat = lstatOrNull(current);
149
+ if (!stat) continue;
150
+ if (stat.isSymbolicLink()) {
151
+ throw new Error(
152
+ `project path contains a symbolic link or junction: ${relative
153
+ .split('/')
154
+ .slice(0, index + 1)
155
+ .join('/')}`
156
+ );
157
+ }
158
+ if (!stat.isDirectory()) throw new Error(`project directory path is blocked by a file: ${relative}`);
159
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
160
+ }
161
+ return { relative, root: rootPath, target };
162
+ }
163
+
164
+ function resolveExistingProjectPath(root, value) {
165
+ const relative = safeProjectRelativePath(value);
166
+ const rootPath = realProjectRoot(root);
167
+ let current = rootPath;
168
+ const parts = relative.split('/');
169
+ for (const [index, part] of parts.entries()) {
170
+ current = path.join(current, part);
171
+ const stat = lstatOrNull(current);
172
+ if (!stat) return null;
173
+ if (stat.isSymbolicLink()) {
174
+ throw new Error(
175
+ `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
176
+ );
177
+ }
178
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
179
+ if (index < parts.length - 1 && !stat.isDirectory()) return null;
180
+ if (index === parts.length - 1) return { relative, root: rootPath, stat, target: current };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function assertNonOverlappingFilePlan(relatives) {
186
+ const paths = new Map();
187
+ for (const relative of relatives) {
188
+ const key = relative.toLowerCase();
189
+ if (paths.has(key)) {
190
+ throw new Error(`project file plan contains a duplicate cross-platform path: ${relative}`);
191
+ }
192
+ paths.set(key, relative);
193
+ }
194
+ for (const relative of paths.values()) {
195
+ const parts = relative.split('/');
196
+ for (let length = 1; length < parts.length; length += 1) {
197
+ const parent = parts.slice(0, length).join('/');
198
+ const plannedParent = paths.get(parent.toLowerCase());
199
+ if (plannedParent) {
200
+ throw new Error(`project file plan contains a file/directory collision: ${plannedParent}`);
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ function minimalPaths(relatives) {
207
+ const unique = new Map(relatives.map((relative) => [relative.toLowerCase(), relative]));
208
+ const sorted = [...unique.values()].sort(
209
+ (left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right)
210
+ );
211
+ return sorted.filter(
212
+ (candidate) =>
213
+ !sorted.some(
214
+ (parent) => parent !== candidate && candidate.toLowerCase().startsWith(`${parent.toLowerCase()}/`)
215
+ )
216
+ );
217
+ }
218
+
219
+ function realProjectRoot(root) {
220
+ const resolved = path.resolve(root);
221
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
222
+ throw new Error(`project workspace does not exist: ${resolved}`);
223
+ }
224
+ return fs.realpathSync.native(resolved);
225
+ }
226
+
227
+ function assertContained(root, target, relative) {
228
+ const fromRoot = path.relative(root, target);
229
+ if (fromRoot === '..' || fromRoot.startsWith(`..${path.sep}`) || path.isAbsolute(fromRoot)) {
230
+ throw new Error(`project path escapes the workspace: ${relative}`);
231
+ }
232
+ }
233
+
234
+ function isContainedRelative(relative) {
235
+ return (
236
+ relative === '' ||
237
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
238
+ );
239
+ }
240
+
241
+ function lstatOrNull(target) {
242
+ try {
243
+ return fs.lstatSync(target);
244
+ } catch (error) {
245
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
246
+ throw error;
247
+ }
248
+ }
249
+
250
+ module.exports = {
251
+ assertNonOverlappingFilePlan,
252
+ backupAndRemoveProjectPaths,
253
+ createExternalBackupRoot,
254
+ resolveProjectDirectoryTarget,
255
+ resolveProjectFileTarget,
256
+ safeProjectRelativePath,
257
+ };
@@ -0,0 +1,42 @@
1
+ function createRealtimeV2Commands(deps) {
2
+ return async function realtimeV2(rest, flags) {
3
+ const command = rest[0] || 'status';
4
+ if (command === 'docs') {
5
+ deps.output(
6
+ flags,
7
+ {
8
+ sdk_version: '2.0.1',
9
+ manual: 'manual://realtime/v2',
10
+ source: 'packages/realtime-sdk',
11
+ example: 'examples/realtime-v2-orders',
12
+ manifest_url: 'https://joripspace.com/sdk/realtime/2.0.1/manifest.json',
13
+ example_url: 'https://joripspace.com/sdk/realtime/2.0.1/examples/orders/README.md',
14
+ },
15
+ (value) => console.log(JSON.stringify(value, null, 2))
16
+ );
17
+ return;
18
+ }
19
+ const project = deps.requireProjectId(flags);
20
+ const actions = {
21
+ status: ['GET', ''],
22
+ activate: ['POST', '/activate'],
23
+ rotate: ['POST', '/rotate'],
24
+ disable: ['POST', '/disable'],
25
+ keys: ['GET', '/keys'],
26
+ deletion: ['GET', '/deletion'],
27
+ };
28
+ let action = actions[command];
29
+ if (command === 'revoke-key') {
30
+ const kid = deps.stringFlag(flags, 'kid');
31
+ if (!/^[a-zA-Z0-9_-]+$/.test(kid || '')) throw new Error('revoke-key requires --kid');
32
+ action = ['DELETE', '/keys/' + encodeURIComponent(kid)];
33
+ }
34
+ if (!action)
35
+ throw new Error('realtime-v2: status, activate, rotate, disable, keys, revoke-key, deletion, docs');
36
+ const cursor = deps.stringFlag(flags, 'cursor');
37
+ const path = `/v1/projects/${encodeURIComponent(project)}/realtime-v2${action[1]}${command === 'keys' && cursor ? '?after=' + encodeURIComponent(cursor) : ''}`;
38
+ const result = await deps.apiRequest(flags, path, { method: action[0], ...deps.projectAuth(flags) });
39
+ deps.output(flags, result, (value) => console.log(JSON.stringify(value, null, 2)));
40
+ };
41
+ }
42
+ module.exports = { createRealtimeV2Commands };