@app-studio/cli 0.0.0-stage → 0.1.0

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/install.mjs ADDED
@@ -0,0 +1,266 @@
1
+ import { createRequire } from 'node:module';
2
+ import {
3
+ link,
4
+ lstat,
5
+ mkdir,
6
+ mkdtemp,
7
+ readFile,
8
+ realpath,
9
+ rename,
10
+ rm,
11
+ rmdir,
12
+ unlink,
13
+ writeFile,
14
+ } from 'node:fs/promises';
15
+ import { basename, dirname, join } from 'node:path';
16
+ import {
17
+ confined,
18
+ digest,
19
+ fetchItem,
20
+ itemURL,
21
+ json,
22
+ platforms,
23
+ readJSON,
24
+ resolveItems,
25
+ } from './registry.mjs';
26
+
27
+ const ledgerPath = '.app-studio/registry-lock.json';
28
+ const lockPath = '.app-studio/install.lock';
29
+
30
+ async function engineVersion(root) {
31
+ try {
32
+ const require = createRequire(join(root, 'package.json'));
33
+ let directory = dirname(require.resolve('app-studio'));
34
+ while (directory !== dirname(directory)) {
35
+ const manifest = await readJSON(join(directory, 'package.json')).catch(
36
+ (error) => {
37
+ if (error.code !== 'ENOENT') throw error;
38
+ }
39
+ );
40
+ if (manifest?.name === 'app-studio') return manifest.version;
41
+ directory = dirname(directory);
42
+ }
43
+ } catch (error) {
44
+ if (error.code !== 'MODULE_NOT_FOUND') throw error;
45
+ }
46
+ throw new Error(
47
+ 'Install app-studio in this project before adding a component.'
48
+ );
49
+ }
50
+
51
+ async function localFile(root, path) {
52
+ const target = await confined(root, path);
53
+ return readFile(target).catch((error) => {
54
+ if (error.code !== 'ENOENT') throw error;
55
+ });
56
+ }
57
+
58
+ async function plan(url, selected, engine, load = fetchItem) {
59
+ const sources = new Map();
60
+ const dependencies = new Set();
61
+ const items = {};
62
+ const responses = new Map();
63
+ const read = (address) => {
64
+ if (!responses.has(address)) responses.set(address, load(address));
65
+ return responses.get(address);
66
+ };
67
+ for (const platform of selected) {
68
+ const resolved = await resolveItems(url, platform, engine, read);
69
+ for (const [address, item] of resolved) {
70
+ const meta = item.meta.appStudio;
71
+ const namespace = digest(new URL('.', address).href).slice(0, 16);
72
+ const directory = `components/app-studio/${namespace}`;
73
+ for (const value of [
74
+ ...(item.dependencies ?? []),
75
+ ...(meta.dependencies?.[platform] ?? []),
76
+ ]) {
77
+ dependencies.add(value);
78
+ }
79
+ const files = {};
80
+ for (const file of item.files) {
81
+ const path = `${directory}/${file.path}`;
82
+ const hash = digest(file.content);
83
+ const key = path.toLowerCase();
84
+ const existing = sources.get(key);
85
+ if (existing && (existing.hash !== hash || existing.path !== path)) {
86
+ throw new Error(`Conflicting registry files: ${path}`);
87
+ }
88
+ sources.set(key, { path, hash, content: file.content });
89
+ files[path] = hash;
90
+ }
91
+ items[address] = {
92
+ version: meta.version,
93
+ entry: `${directory}/${meta.entry}`,
94
+ files,
95
+ };
96
+ }
97
+ }
98
+ return {
99
+ sources,
100
+ dependencies: [...dependencies].sort(),
101
+ items,
102
+ entry: items[url].entry,
103
+ };
104
+ }
105
+
106
+ async function state(root) {
107
+ const stored = await localFile(root, ledgerPath);
108
+ if (!stored) return { version: 1, items: {} };
109
+ const value = JSON.parse(stored.toString('utf8'));
110
+ if (value.version !== 1 || !value.items || typeof value.items !== 'object') {
111
+ throw new Error('Unsupported App Studio registry lock file');
112
+ }
113
+ return value;
114
+ }
115
+
116
+ async function changes(root, plan, previous, installing) {
117
+ const tracked = new Set(
118
+ Object.values(previous.items).flatMap((item) =>
119
+ Object.keys(item.files ?? {})
120
+ )
121
+ );
122
+ const result = [];
123
+ for (const { path, hash, content } of plan.sources.values()) {
124
+ const current = await localFile(root, path);
125
+ if (!current) {
126
+ result.push({ path, status: 'new', content });
127
+ } else if (digest(current) !== hash || (installing && !tracked.has(path))) {
128
+ result.push({
129
+ path,
130
+ status: 'changed',
131
+ content,
132
+ local: current.toString('utf8'),
133
+ });
134
+ }
135
+ }
136
+ return result;
137
+ }
138
+
139
+ export async function runInstall({
140
+ directory,
141
+ ref,
142
+ registry,
143
+ platform = 'web',
144
+ mode = 'add',
145
+ dryRun = false,
146
+ load,
147
+ engine,
148
+ report = console.log,
149
+ }) {
150
+ const root = await realpath(directory);
151
+ await readJSON(join(root, 'package.json'));
152
+ const selected = platform === 'universal' ? platforms : [platform];
153
+ if (selected.some((value) => !platforms.includes(value)))
154
+ throw new Error(`Unknown platform: ${platform}`);
155
+ const url = itemURL(ref, registry);
156
+ const proposal = await plan(
157
+ url,
158
+ selected,
159
+ engine ?? (await engineVersion(root)),
160
+ load
161
+ );
162
+
163
+ async function review() {
164
+ const previous = await state(root);
165
+ const diff = await changes(root, proposal, previous, mode === 'add');
166
+ if (mode === 'diff') {
167
+ const installed = previous.items[url];
168
+ if (!installed) throw new Error(`This item is not tracked: ${url}`);
169
+ report(`${installed.version} → ${proposal.items[url].version}`);
170
+ for (const path of Object.keys(installed.files)) {
171
+ if (!proposal.sources.has(path.toLowerCase()))
172
+ diff.push({ path, status: 'removed upstream' });
173
+ }
174
+ for (const { path, status, local, content } of diff) {
175
+ report(`${status}: ${path}`);
176
+ if (status === 'changed')
177
+ report(
178
+ `--- local\n${printable(local)}\n+++ registry\n${printable(
179
+ content
180
+ )}`
181
+ );
182
+ }
183
+ if (!diff.length) report('No file changes.');
184
+ return;
185
+ }
186
+
187
+ const conflicts = diff.filter(({ status }) => status === 'changed');
188
+ if (conflicts.length)
189
+ throw new Error(
190
+ 'Existing files would be overwritten:\n' +
191
+ conflicts.map(({ path }) => path).join('\n')
192
+ );
193
+ report(`Entry: ${proposal.entry}`);
194
+ report(
195
+ `Dependencies to check: ${
196
+ proposal.dependencies.join(', ') ||
197
+ 'none beyond the platform and app-studio'
198
+ }`
199
+ );
200
+ for (const { path } of diff) report(`Add ${path}`);
201
+ if (dryRun) return;
202
+
203
+ const nextState = json({
204
+ version: 1,
205
+ items: { ...previous.items, ...proposal.items },
206
+ });
207
+ const staging = await mkdtemp(join(root, '.app-studio', 'stage-'));
208
+ const written = [];
209
+ const directories = [];
210
+ try {
211
+ await writeFile(join(staging, 'ledger'), nextState);
212
+ for (const [index, { path, content }] of diff.entries()) {
213
+ const target = await confined(root, path);
214
+ const created = await mkdir(dirname(target), { recursive: true });
215
+ if (created) {
216
+ for (
217
+ let at = dirname(target);
218
+ at !== dirname(created);
219
+ at = dirname(at)
220
+ )
221
+ directories.push(at);
222
+ }
223
+ const staged = join(staging, String(index));
224
+ await writeFile(staged, content);
225
+ // link never replaces a file created after the preflight check.
226
+ await link(staged, await confined(root, path));
227
+ written.push(target);
228
+ }
229
+ await rename(join(staging, 'ledger'), await confined(root, ledgerPath));
230
+ } catch (error) {
231
+ for (const path of written.reverse()) await unlink(path);
232
+ for (const folder of directories)
233
+ await rmdir(folder).catch((failure) => {
234
+ if (!['ENOENT', 'ENOTEMPTY'].includes(failure.code)) throw failure;
235
+ });
236
+ throw error;
237
+ } finally {
238
+ await rm(staging, { recursive: true, force: true });
239
+ }
240
+ }
241
+
242
+ if (mode === 'diff' || dryRun) return review();
243
+ const lock = await confined(root, lockPath);
244
+ const parent = dirname(lock);
245
+ await mkdir(parent, { recursive: true });
246
+ const stat = await lstat(parent);
247
+ if (stat.isSymbolicLink())
248
+ throw new Error(`Unsafe path: ${basename(parent)}`);
249
+ await mkdir(lock).catch((error) => {
250
+ if (error.code === 'EEXIST')
251
+ throw new Error('An App Studio installation is already running.');
252
+ throw error;
253
+ });
254
+ try {
255
+ await review();
256
+ } finally {
257
+ await rmdir(lock);
258
+ }
259
+ }
260
+
261
+ function printable(content) {
262
+ // Registry file content may contain terminal control sequences.
263
+ return content.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g, (char) =>
264
+ JSON.stringify(char).slice(1, -1)
265
+ );
266
+ }
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "@app-studio/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "bin": { "app-studio": "./cli.mjs" },
6
+ "files": ["*.mjs", "template"],
7
+ "engines": { "node": ">=20" },
8
+ "dependencies": { "semver": "^6.3.1" },
9
+ "license": "MIT",
10
+ "publishConfig": { "access": "public" }
11
+ }
package/registry.mjs ADDED
@@ -0,0 +1,211 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, readFile } from 'node:fs/promises';
3
+ import { resolve, sep } from 'node:path';
4
+ import semver from 'semver';
5
+
6
+ export const itemSchema = 'https://ui.shadcn.com/schema/registry-item.json';
7
+ export const officialRegistry = 'https://app-studio-6167b.web.app/registry/';
8
+ export const platforms = ['web', 'ios', 'android'];
9
+ export const digest = (content) =>
10
+ createHash('sha256').update(content).digest('hex');
11
+ export const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
12
+ export const json = (value) => JSON.stringify(value, null, 2) + '\n';
13
+ export const readJSON = async (path) =>
14
+ JSON.parse(await readFile(path, 'utf8'));
15
+ const exists = async (path) =>
16
+ lstat(path).catch((error) => {
17
+ if (error.code !== 'ENOENT') throw error;
18
+ });
19
+
20
+ export function sourcePath(path) {
21
+ const valid =
22
+ typeof path === 'string' &&
23
+ path.length <= 240 &&
24
+ path
25
+ .split('/')
26
+ .every(
27
+ (part) =>
28
+ /^[a-z0-9_-][a-z0-9_.-]*$/i.test(part) &&
29
+ !part.endsWith('.') &&
30
+ !/^(?:node_modules|package\.json|(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$))/i.test(
31
+ part
32
+ )
33
+ ) &&
34
+ /\.(tsx?|jsx?|css|json|md|txt)$/i.test(path);
35
+ if (!valid) throw new Error(`Invalid registry file path: ${path}`);
36
+ return path;
37
+ }
38
+
39
+ // The path is always relative to a directory chosen by the consumer.
40
+ export async function confined(root, path) {
41
+ const target = resolve(root, path);
42
+ if (!target.startsWith(root + sep))
43
+ throw new Error(`Path escapes project: ${path}`);
44
+ let current = root;
45
+ const parts = path.split('/');
46
+ for (let index = 0; index < parts.length; index++) {
47
+ current = resolve(current, parts[index]);
48
+ const stat = await exists(current);
49
+ if (
50
+ stat &&
51
+ (stat.isSymbolicLink() ||
52
+ (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory()))
53
+ ) {
54
+ throw new Error(`Unsafe path: ${path}`);
55
+ }
56
+ }
57
+ return target;
58
+ }
59
+
60
+ const list = (value) =>
61
+ Array.isArray(value) && value.every((entry) => typeof entry === 'string');
62
+ const npmDependency =
63
+ /^(@[a-z0-9._-]+\/[a-z0-9._-]+|[a-z0-9][a-z0-9._-]*)(?:@([^@]+))?$/;
64
+
65
+ export function validateItem(item, { content = true } = {}) {
66
+ const meta = item?.meta?.appStudio;
67
+ if (
68
+ !item ||
69
+ typeof item.name !== 'string' ||
70
+ !slug.test(item.name) ||
71
+ ![
72
+ 'registry:ui',
73
+ 'registry:block',
74
+ 'registry:component',
75
+ 'registry:lib',
76
+ ].includes(item.type) ||
77
+ !item.title ||
78
+ typeof item.title !== 'string' ||
79
+ !item.author ||
80
+ typeof item.author !== 'string' ||
81
+ !meta ||
82
+ typeof meta.license !== 'string' ||
83
+ !meta.license ||
84
+ typeof meta.version !== 'string' ||
85
+ !semver.valid(meta.version) ||
86
+ typeof meta.engine !== 'string' ||
87
+ !semver.validRange(meta.engine) ||
88
+ !list(meta.platforms) ||
89
+ !meta.platforms.length ||
90
+ meta.platforms.some((platform) => !platforms.includes(platform)) ||
91
+ !list(item.registryDependencies ?? []) ||
92
+ !list(item.dependencies ?? []) ||
93
+ !Array.isArray(item.files) ||
94
+ !item.files.length ||
95
+ item.files.length > 250
96
+ ) {
97
+ throw new Error(`Invalid registry item: ${item?.name ?? '(unnamed)'}`);
98
+ }
99
+ if (
100
+ item.css ||
101
+ item.tailwind ||
102
+ item.cssVars ||
103
+ item.envVars ||
104
+ item.font ||
105
+ item.devDependencies?.length
106
+ ) {
107
+ throw new Error(`Unsupported project configuration in ${item.name}`);
108
+ }
109
+ for (const dependency of [
110
+ ...(item.dependencies ?? []),
111
+ ...Object.values(meta.dependencies ?? {}).flat(),
112
+ ]) {
113
+ const match =
114
+ typeof dependency === 'string' && dependency.match(npmDependency);
115
+ if (!match || (match[2] && !semver.validRange(match[2]))) {
116
+ throw new Error(`Invalid npm dependency in ${item.name}: ${dependency}`);
117
+ }
118
+ }
119
+ for (const [platform, deps] of Object.entries(meta.dependencies ?? {})) {
120
+ if (!meta.platforms.includes(platform) || !list(deps)) {
121
+ throw new Error(`Invalid platform dependencies in ${item.name}`);
122
+ }
123
+ }
124
+ const paths = new Set();
125
+ for (const file of item.files) {
126
+ const path = sourcePath(file?.path).toLowerCase();
127
+ if (
128
+ paths.has(path) ||
129
+ file.target != null ||
130
+ (file.type != null && file.type !== item.type) ||
131
+ (content && typeof file.content !== 'string')
132
+ ) {
133
+ throw new Error(
134
+ `Invalid or duplicate file in ${item.name}: ${file.path}`
135
+ );
136
+ }
137
+ paths.add(path);
138
+ }
139
+ if (
140
+ !paths.has(sourcePath(meta.entry).toLowerCase()) ||
141
+ !item.files.some((file) => file.path === meta.entry)
142
+ ) {
143
+ throw new Error(`Missing entry in ${item.name}: ${meta.entry}`);
144
+ }
145
+ return item;
146
+ }
147
+
148
+ export function itemURL(ref, registry = officialRegistry) {
149
+ const url = new URL(slug.test(ref) ? ref + '.json' : ref, registry);
150
+ if (
151
+ !(
152
+ url.protocol === 'https:' ||
153
+ (url.protocol === 'http:' &&
154
+ ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
155
+ ) ||
156
+ url.username ||
157
+ url.password ||
158
+ url.hash ||
159
+ !url.pathname.endsWith('.json')
160
+ ) {
161
+ throw new Error(`Invalid registry URL: ${ref}`);
162
+ }
163
+ return url.href;
164
+ }
165
+
166
+ export async function fetchItem(url) {
167
+ const response = await fetch(url, {
168
+ redirect: 'error',
169
+ signal: AbortSignal.timeout(15000),
170
+ });
171
+ if (!response.ok || !response.body)
172
+ throw new Error(`Cannot read ${url} (HTTP ${response.status})`);
173
+ const chunks = [];
174
+ let size = 0;
175
+ for await (const chunk of response.body) {
176
+ size += chunk.length;
177
+ if (size > 4 * 1024 * 1024)
178
+ throw new Error(`Registry item exceeds 4 MiB: ${url}`);
179
+ chunks.push(chunk);
180
+ }
181
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
182
+ }
183
+
184
+ export async function resolveItems(url, platform, engine, load = fetchItem) {
185
+ const items = new Map();
186
+ const visiting = new Set();
187
+ async function visit(address) {
188
+ if (items.has(address)) return;
189
+ if (visiting.has(address))
190
+ throw new Error(`Circular registry dependency: ${address}`);
191
+ if (items.size + visiting.size >= 64)
192
+ throw new Error('Too many registry dependencies');
193
+ visiting.add(address);
194
+ const item = validateItem(await load(address));
195
+ const meta = item.meta.appStudio;
196
+ if (!meta.platforms.includes(platform))
197
+ throw new Error(`${item.name} does not support ${platform}`);
198
+ if (!semver.satisfies(engine, meta.engine, { includePrerelease: true })) {
199
+ throw new Error(
200
+ `${item.name} requires app-studio ${meta.engine}. Installed: ${engine}`
201
+ );
202
+ }
203
+ for (const ref of item.registryDependencies ?? []) {
204
+ await visit(itemURL(ref, address));
205
+ }
206
+ items.set(address, item);
207
+ visiting.delete(address);
208
+ }
209
+ await visit(url);
210
+ return items;
211
+ }