@barqjs/ui-cli 0.0.0-stage → 0.2.0-next.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/LICENSE +21 -0
- package/README.md +195 -2
- package/dist/build-C65qsG0d.js +136 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1761 -0
- package/package.json +63 -4
- package/src/add.ts +124 -0
- package/src/build.ts +167 -0
- package/src/config.ts +76 -0
- package/src/diff.ts +111 -0
- package/src/files.ts +147 -0
- package/src/index.ts +989 -0
- package/src/project.ts +115 -0
- package/src/registry.ts +196 -0
- package/src/schema.ts +392 -0
- package/src/theme.ts +227 -0
- package/src/tty.ts +133 -0
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@barqjs/ui-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0-next.1",
|
|
4
|
+
"description": "Copy @barqjs/ui components into your project, and keep them in sync",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"barq",
|
|
7
|
+
"cli",
|
|
8
|
+
"components",
|
|
9
|
+
"registry",
|
|
10
|
+
"shadcn",
|
|
11
|
+
"ui"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/salamaashoush/barq#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/salamaashoush/barq/issues"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/salamaashoush/barq.git",
|
|
21
|
+
"directory": "packages/ui-cli"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"src",
|
|
26
|
+
"!src/**/*.test.ts",
|
|
27
|
+
"!src/**/*.test.tsx",
|
|
28
|
+
"!src/**/test-*.ts",
|
|
29
|
+
"!src/**/*-harness.ts",
|
|
30
|
+
"!src/**/*-probe.ts",
|
|
31
|
+
"!src/**/fixtures",
|
|
32
|
+
"!src/**/fixtures.ts",
|
|
33
|
+
"!src/**/ssr-fixtures.ts"
|
|
34
|
+
],
|
|
35
|
+
"type": "module",
|
|
36
|
+
"sideEffects": false,
|
|
37
|
+
"bin": {
|
|
38
|
+
"barq-ui": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"types": "./dist/index.d.ts",
|
|
43
|
+
"bun": "./src/index.ts",
|
|
44
|
+
"import": "./dist/index.js"
|
|
45
|
+
},
|
|
46
|
+
"./package.json": "./package.json"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"dev": "tsdown --watch",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"test": "bun test --timeout 60000"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/bun": "^1.4.4",
|
|
56
|
+
"typescript": "^7.0.2"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=20.19.0"
|
|
60
|
+
},
|
|
61
|
+
"publishConfig": {
|
|
62
|
+
"access": "public",
|
|
63
|
+
"provenance": true
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/add.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `add`: the item, everything it needs, and the files that result.
|
|
3
|
+
*
|
|
4
|
+
* A file already on disk is the only interesting case. Three answers, and which
|
|
5
|
+
* one applies is decided by the hash `components.json` recorded when the file
|
|
6
|
+
* was written:
|
|
7
|
+
*
|
|
8
|
+
* - **The same content**: nothing to do, and nothing is said about it.
|
|
9
|
+
* - **Unchanged since it was added**: replaced, because the project did not
|
|
10
|
+
* write it.
|
|
11
|
+
* - **Edited**: left alone and reported, unless `--overwrite`. That is the
|
|
12
|
+
* whole point of owning the code, and a tool that silently reverted an edit
|
|
13
|
+
* would be taking it back.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { relative } from "node:path";
|
|
17
|
+
|
|
18
|
+
import { hashOf, placed, read, rewrite, targetOf, write } from "./files.ts";
|
|
19
|
+
import type { RegistryItem } from "./schema.ts";
|
|
20
|
+
import type { Config } from "./schema.ts";
|
|
21
|
+
|
|
22
|
+
export type Outcome = "written" | "replaced" | "unchanged" | "kept";
|
|
23
|
+
|
|
24
|
+
export interface WrittenFile {
|
|
25
|
+
readonly item: string;
|
|
26
|
+
/** Relative to the project root, for printing. */
|
|
27
|
+
readonly path: string;
|
|
28
|
+
readonly absolute: string;
|
|
29
|
+
readonly outcome: Outcome;
|
|
30
|
+
/** The content on disk now, and what its hash is recorded as. */
|
|
31
|
+
readonly hash: string;
|
|
32
|
+
/** What the registry has for it, with its imports pointed at this project. */
|
|
33
|
+
readonly incoming: string;
|
|
34
|
+
/** What was on disk before, when there was anything. */
|
|
35
|
+
readonly existing?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface AddOptions {
|
|
39
|
+
readonly overwrite?: boolean;
|
|
40
|
+
/** Decide every outcome and write nothing, so the answer can be shown first. */
|
|
41
|
+
readonly dryRun?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function applyItems(
|
|
45
|
+
config: Config,
|
|
46
|
+
root: string,
|
|
47
|
+
items: readonly RegistryItem[],
|
|
48
|
+
options: AddOptions = {},
|
|
49
|
+
): { files: WrittenFile[]; config: Config } {
|
|
50
|
+
const files: WrittenFile[] = [];
|
|
51
|
+
const recorded: Record<string, Record<string, string>> = { ...config.items };
|
|
52
|
+
const together = placed(items);
|
|
53
|
+
const put = options.dryRun === true ? (): void => {} : write;
|
|
54
|
+
|
|
55
|
+
// Every destination first, and only then any write. `targetOf` refuses a
|
|
56
|
+
// path that leaves the project, and an item refused at its third file must
|
|
57
|
+
// not have left the first two behind.
|
|
58
|
+
const planned = items.map((item) => ({
|
|
59
|
+
item,
|
|
60
|
+
files: item.files.map((file) => {
|
|
61
|
+
const absolute = targetOf(config, root, file);
|
|
62
|
+
return {
|
|
63
|
+
key: file.path,
|
|
64
|
+
absolute,
|
|
65
|
+
path: relative(root, absolute).replaceAll("\\", "/"),
|
|
66
|
+
incoming: rewrite(config, root, file, together),
|
|
67
|
+
};
|
|
68
|
+
}),
|
|
69
|
+
}));
|
|
70
|
+
|
|
71
|
+
for (const { item, files: own } of planned) {
|
|
72
|
+
const forItem: Record<string, string> = { ...recorded[item.name] };
|
|
73
|
+
|
|
74
|
+
for (const { key, absolute, path, incoming } of own) {
|
|
75
|
+
const hash = hashOf(incoming);
|
|
76
|
+
const existing = read(absolute);
|
|
77
|
+
const common = { item: item.name, path, absolute, incoming };
|
|
78
|
+
|
|
79
|
+
if (existing === undefined) {
|
|
80
|
+
put(absolute, incoming);
|
|
81
|
+
files.push({ ...common, outcome: "written", hash });
|
|
82
|
+
} else if (existing === incoming) {
|
|
83
|
+
files.push({ ...common, outcome: "unchanged", hash, existing });
|
|
84
|
+
} else if (options.overwrite === true || hashOf(existing) === forItem[key]) {
|
|
85
|
+
put(absolute, incoming);
|
|
86
|
+
files.push({ ...common, outcome: "replaced", hash, existing });
|
|
87
|
+
} else {
|
|
88
|
+
files.push({ ...common, outcome: "kept", hash: hashOf(existing), existing });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
forItem[key] = hash;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
recorded[item.name] = forItem;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return { files, config: { ...config, items: recorded } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `zod@^3` and `@acme/kit@1` are `zod` and `@acme/kit` in a `package.json`. */
|
|
101
|
+
function packageName(dependency: string): string {
|
|
102
|
+
const at = dependency.indexOf("@", 1);
|
|
103
|
+
return at < 0 ? dependency : dependency.slice(0, at);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The npm packages these items want, minus what the project already has.
|
|
108
|
+
*
|
|
109
|
+
* `field` is which list to read: what the code imports, or what only its build
|
|
110
|
+
* and its tests need.
|
|
111
|
+
*/
|
|
112
|
+
export function missingDependencies(
|
|
113
|
+
items: readonly RegistryItem[],
|
|
114
|
+
installed: ReadonlySet<string>,
|
|
115
|
+
field: "dependencies" | "devDependencies" = "dependencies",
|
|
116
|
+
): string[] {
|
|
117
|
+
const wanted = new Set<string>();
|
|
118
|
+
for (const item of items) {
|
|
119
|
+
for (const dependency of item[field]) {
|
|
120
|
+
if (!installed.has(packageName(dependency))) wanted.add(dependency);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [...wanted].toSorted();
|
|
124
|
+
}
|
package/src/build.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `build`: a directory of components, as a registry someone else can `add`.
|
|
3
|
+
*
|
|
4
|
+
* The same rules `@barqjs/ui` builds its own with — a file's bare imports are
|
|
5
|
+
* its npm dependencies, its relative imports are the items it needs — so a
|
|
6
|
+
* registry of your own works the same way and can depend on this one's items by
|
|
7
|
+
* name.
|
|
8
|
+
*
|
|
9
|
+
* The directory a file is in says what it is: `lib`, `theme`, `hooks`,
|
|
10
|
+
* `blocks`, `components` and `examples` are each their own type, and anything
|
|
11
|
+
* else is a `ui` component.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
16
|
+
|
|
17
|
+
import type { ItemType, RegistryItem } from "./schema.ts";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `import … from "x"`, `export … from "x"` and a bare `import "x"`.
|
|
21
|
+
*
|
|
22
|
+
* `from` is required rather than "the first quoted string on the line", which
|
|
23
|
+
* is what this used to be: `export type ButtonVariant = "default" | …` then
|
|
24
|
+
* declared a dependency on a package called `default`.
|
|
25
|
+
*
|
|
26
|
+
* What stands between the keyword and `from` is an import CLAUSE and nothing
|
|
27
|
+
* else — names, braces, commas, `*`, whitespace. Matching "anything up to the
|
|
28
|
+
* end of the line" instead missed every import long enough to be wrapped, and
|
|
29
|
+
* that is most of them: `context-menu.tsx` declared no dependency on
|
|
30
|
+
* `@barqjs/aria` and none on `dropdown-menu`, so `add context-menu` wrote a
|
|
31
|
+
* file that imports a component the project does not have.
|
|
32
|
+
*/
|
|
33
|
+
const IMPORT =
|
|
34
|
+
/(?:^|\n)\s*(?:import|export)\s+(?:type\s+)?[\w*{}\s,$]+?\s*\bfrom\s*["']([^"']+)["']|(?:^|\n)\s*import\s+["']([^"']+)["']/g;
|
|
35
|
+
|
|
36
|
+
export function specifiersIn(source: string): string[] {
|
|
37
|
+
const out: string[] = [];
|
|
38
|
+
for (const match of source.matchAll(IMPORT)) {
|
|
39
|
+
const specifier = match[1] ?? match[2];
|
|
40
|
+
if (specifier !== undefined) out.push(specifier);
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `@barqjs/lucide/icons/check` -> `@barqjs/lucide`. What you install. */
|
|
46
|
+
export function packageOf(specifier: string): string {
|
|
47
|
+
const parts = specifier.split("/");
|
|
48
|
+
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : (parts[0] ?? specifier);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function titleOf(name: string): string {
|
|
52
|
+
return name
|
|
53
|
+
.split("-")
|
|
54
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
55
|
+
.join(" ");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every `.ts`/`.tsx` under `directory`, excluding tests, as paths relative to it. */
|
|
59
|
+
function sourcesIn(directory: string, prefix = ""): string[] {
|
|
60
|
+
const out: string[] = [];
|
|
61
|
+
for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) =>
|
|
62
|
+
a.name.localeCompare(b.name),
|
|
63
|
+
)) {
|
|
64
|
+
const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
65
|
+
if (entry.isDirectory()) out.push(...sourcesIn(join(directory, entry.name), path));
|
|
66
|
+
else if (/\.tsx?$/.test(entry.name) && !entry.name.includes(".test.")) out.push(path);
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const DIRECTORIES: Readonly<Record<string, ItemType>> = {
|
|
72
|
+
lib: "registry:lib",
|
|
73
|
+
theme: "registry:theme",
|
|
74
|
+
hooks: "registry:hook",
|
|
75
|
+
blocks: "registry:block",
|
|
76
|
+
components: "registry:component",
|
|
77
|
+
examples: "registry:example",
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
function typeOf(path: string): ItemType {
|
|
81
|
+
const first = path.includes("/") ? (path.split("/")[0] ?? "") : "";
|
|
82
|
+
return DIRECTORIES[first] ?? "registry:ui";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The item a file belongs to.
|
|
87
|
+
*
|
|
88
|
+
* A file is an item of its own, named for the file. A DIRECTORY under `blocks`
|
|
89
|
+
* is one item with everything in it, because that is what a block is: a page
|
|
90
|
+
* and the components only that page uses.
|
|
91
|
+
*/
|
|
92
|
+
function ownerOf(path: string): string {
|
|
93
|
+
const parts = path.split("/");
|
|
94
|
+
if (parts[0] === "blocks" && parts.length > 2) return parts[1] as string;
|
|
95
|
+
return (parts.at(-1) ?? path).replace(/\.tsx?$/, "");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function buildRegistry(from: string, to: string): number {
|
|
99
|
+
const paths = sourcesIn(from);
|
|
100
|
+
const owner = new Map<string, string>();
|
|
101
|
+
for (const path of paths) owner.set(path, ownerOf(path));
|
|
102
|
+
|
|
103
|
+
const grouped = new Map<string, string[]>();
|
|
104
|
+
for (const path of paths) {
|
|
105
|
+
const name = owner.get(path) as string;
|
|
106
|
+
grouped.set(name, [...(grouped.get(name) ?? []), path]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const items: RegistryItem[] = [...grouped].map(([name, own]) => {
|
|
110
|
+
const dependencies = new Set<string>();
|
|
111
|
+
const registryDependencies = new Set<string>();
|
|
112
|
+
const files = own.map((path) => {
|
|
113
|
+
const content = readFileSync(join(from, path), "utf8");
|
|
114
|
+
|
|
115
|
+
for (const specifier of specifiersIn(content)) {
|
|
116
|
+
if (!specifier.startsWith(".")) {
|
|
117
|
+
dependencies.add(packageOf(specifier));
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const resolved = relative(from, resolve(join(from, dirname(path)), specifier)).replaceAll(
|
|
121
|
+
"\\",
|
|
122
|
+
"/",
|
|
123
|
+
);
|
|
124
|
+
const found = owner.get(resolved);
|
|
125
|
+
if (found !== undefined && found !== name) registryDependencies.add(found);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { path, type: typeOf(path), content };
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
name,
|
|
133
|
+
type: typeOf(own[0] as string),
|
|
134
|
+
title: titleOf(name),
|
|
135
|
+
dependencies: [...dependencies].toSorted(),
|
|
136
|
+
devDependencies: [],
|
|
137
|
+
registryDependencies: [...registryDependencies].toSorted(),
|
|
138
|
+
files,
|
|
139
|
+
categories: [],
|
|
140
|
+
};
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
mkdirSync(to, { recursive: true });
|
|
144
|
+
for (const item of items) {
|
|
145
|
+
writeFileSync(join(to, `${item.name}.json`), `${JSON.stringify(item, null, 2)}\n`);
|
|
146
|
+
}
|
|
147
|
+
writeFileSync(
|
|
148
|
+
join(to, "index.json"),
|
|
149
|
+
`${JSON.stringify(
|
|
150
|
+
{
|
|
151
|
+
name: "registry",
|
|
152
|
+
items: items.map((item) => ({
|
|
153
|
+
name: item.name,
|
|
154
|
+
type: item.type,
|
|
155
|
+
title: item.title,
|
|
156
|
+
dependencies: item.dependencies,
|
|
157
|
+
registryDependencies: item.registryDependencies,
|
|
158
|
+
files: item.files.map((file) => file.path),
|
|
159
|
+
})),
|
|
160
|
+
},
|
|
161
|
+
null,
|
|
162
|
+
2,
|
|
163
|
+
)}\n`,
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
return items.length;
|
|
167
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `components.json`: finding it, reading it, writing it back.
|
|
3
|
+
*
|
|
4
|
+
* At the project root rather than anywhere on the path, and the root is where
|
|
5
|
+
* the file IS — so a command run from a subdirectory of a monorepo package
|
|
6
|
+
* finds that package's configuration and not the workspace's.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { dirname, join, resolve } from "node:path";
|
|
11
|
+
|
|
12
|
+
import { parseConfig, type Config } from "./schema.ts";
|
|
13
|
+
|
|
14
|
+
export const CONFIG_FILE = "components.json";
|
|
15
|
+
|
|
16
|
+
/** The nearest directory at or above `from` holding a `components.json`. */
|
|
17
|
+
export function findRoot(from: string): string | undefined {
|
|
18
|
+
let directory = resolve(from);
|
|
19
|
+
for (;;) {
|
|
20
|
+
if (existsSync(join(directory, CONFIG_FILE))) return directory;
|
|
21
|
+
const parent = dirname(directory);
|
|
22
|
+
if (parent === directory) return undefined;
|
|
23
|
+
directory = parent;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function readConfig(root: string): Config {
|
|
28
|
+
const path = join(root, CONFIG_FILE);
|
|
29
|
+
return parseConfig(JSON.parse(readFileSync(path, "utf8")));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Written with the keys in a fixed order and the item table last.
|
|
34
|
+
*
|
|
35
|
+
* The table grows with every `add`, and a person reading the file wants to see
|
|
36
|
+
* the settings they chose above the bookkeeping they did not.
|
|
37
|
+
*/
|
|
38
|
+
export function writeConfig(root: string, config: Config): void {
|
|
39
|
+
const ordered = {
|
|
40
|
+
...(config.$schema === undefined ? {} : { $schema: config.$schema }),
|
|
41
|
+
...(config.registry === undefined ? {} : { registry: config.registry }),
|
|
42
|
+
...(Object.keys(config.registries).length === 0
|
|
43
|
+
? {}
|
|
44
|
+
: {
|
|
45
|
+
registries: Object.fromEntries(
|
|
46
|
+
Object.entries(config.registries)
|
|
47
|
+
.toSorted(([a], [b]) => a.localeCompare(b))
|
|
48
|
+
.map(([scope, endpoint]) => [
|
|
49
|
+
scope,
|
|
50
|
+
Object.keys(endpoint.headers).length === 0 ? endpoint.url : endpoint,
|
|
51
|
+
]),
|
|
52
|
+
),
|
|
53
|
+
}),
|
|
54
|
+
paths: config.paths,
|
|
55
|
+
theme: config.theme,
|
|
56
|
+
reset: config.reset,
|
|
57
|
+
items: Object.fromEntries(
|
|
58
|
+
Object.entries(config.items)
|
|
59
|
+
.toSorted(([a], [b]) => a.localeCompare(b))
|
|
60
|
+
.map(([name, files]) => [
|
|
61
|
+
name,
|
|
62
|
+
Object.fromEntries(Object.entries(files).toSorted(([a], [b]) => a.localeCompare(b))),
|
|
63
|
+
]),
|
|
64
|
+
),
|
|
65
|
+
};
|
|
66
|
+
writeFileSync(join(root, CONFIG_FILE), `${JSON.stringify(ordered, null, 2)}\n`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The config, or an error naming the command that would create one. */
|
|
70
|
+
export function requireConfig(cwd: string): { root: string; config: Config } {
|
|
71
|
+
const root = findRoot(cwd);
|
|
72
|
+
if (root === undefined) {
|
|
73
|
+
throw new Error(`no ${CONFIG_FILE} here or above. Run \`barq-ui init\` first.`);
|
|
74
|
+
}
|
|
75
|
+
return { root, config: readConfig(root) };
|
|
76
|
+
}
|
package/src/diff.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A unified diff, in fifty lines and with no dependency.
|
|
3
|
+
*
|
|
4
|
+
* The classic Myers shortest-edit-script over LINES. A component file is a few
|
|
5
|
+
* hundred lines and the two versions are nearly identical, which is the case
|
|
6
|
+
* Myers is fastest on — it walks the diagonal, so the work is proportional to
|
|
7
|
+
* the size of the DIFFERENCE rather than to the size of the files.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type Op = "keep" | "add" | "remove";
|
|
11
|
+
|
|
12
|
+
export interface Change {
|
|
13
|
+
readonly op: Op;
|
|
14
|
+
readonly line: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The edit script turning `before` into `after`. */
|
|
18
|
+
export function diffLines(before: readonly string[], after: readonly string[]): Change[] {
|
|
19
|
+
const n = before.length;
|
|
20
|
+
const m = after.length;
|
|
21
|
+
const max = n + m;
|
|
22
|
+
// `v[k]` is the furthest `x` reached on diagonal `k`, and a copy is kept per
|
|
23
|
+
// step so the path can be walked back once the end is found.
|
|
24
|
+
const trace: Map<number, number>[] = [];
|
|
25
|
+
let v = new Map<number, number>([[1, 0]]);
|
|
26
|
+
|
|
27
|
+
for (let d = 0; d <= max; d++) {
|
|
28
|
+
trace.push(new Map(v));
|
|
29
|
+
for (let k = -d; k <= d; k += 2) {
|
|
30
|
+
const down = k === -d || (k !== d && (v.get(k - 1) ?? 0) < (v.get(k + 1) ?? 0));
|
|
31
|
+
let x = down ? (v.get(k + 1) ?? 0) : (v.get(k - 1) ?? 0) + 1;
|
|
32
|
+
let y = x - k;
|
|
33
|
+
while (x < n && y < m && before[x] === after[y]) {
|
|
34
|
+
x++;
|
|
35
|
+
y++;
|
|
36
|
+
}
|
|
37
|
+
v.set(k, x);
|
|
38
|
+
if (x >= n && y >= m) return walk(trace, before, after, d);
|
|
39
|
+
}
|
|
40
|
+
v = new Map(v);
|
|
41
|
+
}
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function walk(
|
|
46
|
+
trace: readonly Map<number, number>[],
|
|
47
|
+
before: readonly string[],
|
|
48
|
+
after: readonly string[],
|
|
49
|
+
end: number,
|
|
50
|
+
): Change[] {
|
|
51
|
+
const out: Change[] = [];
|
|
52
|
+
let x = before.length;
|
|
53
|
+
let y = after.length;
|
|
54
|
+
|
|
55
|
+
for (let d = end; d > 0; d--) {
|
|
56
|
+
const v = trace[d] as Map<number, number>;
|
|
57
|
+
const k = x - y;
|
|
58
|
+
const down = k === -d || (k !== d && (v.get(k - 1) ?? 0) < (v.get(k + 1) ?? 0));
|
|
59
|
+
const previousK = down ? k + 1 : k - 1;
|
|
60
|
+
const previousX = v.get(previousK) ?? 0;
|
|
61
|
+
const previousY = previousX - previousK;
|
|
62
|
+
|
|
63
|
+
while (x > previousX && y > previousY) {
|
|
64
|
+
out.push({ op: "keep", line: before[--x] as string });
|
|
65
|
+
y--;
|
|
66
|
+
}
|
|
67
|
+
if (down) out.push({ op: "add", line: after[--y] as string });
|
|
68
|
+
else out.push({ op: "remove", line: before[--x] as string });
|
|
69
|
+
}
|
|
70
|
+
while (x > 0 && y > 0) {
|
|
71
|
+
out.push({ op: "keep", line: before[--x] as string });
|
|
72
|
+
y--;
|
|
73
|
+
}
|
|
74
|
+
return out.toReversed();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface HunkOptions {
|
|
78
|
+
/** Unchanged lines kept either side of a change. @default 3 */
|
|
79
|
+
readonly context?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The changes as a unified diff, with the runs of untouched lines collapsed.
|
|
84
|
+
*
|
|
85
|
+
* A component is mostly untouched, so printing every line would bury the three
|
|
86
|
+
* that moved.
|
|
87
|
+
*/
|
|
88
|
+
export function unified(before: string, after: string, options: HunkOptions = {}): string {
|
|
89
|
+
const context = options.context ?? 3;
|
|
90
|
+
const changes = diffLines(before.split("\n"), after.split("\n"));
|
|
91
|
+
if (!changes.some((change) => change.op !== "keep")) return "";
|
|
92
|
+
|
|
93
|
+
const keep = new Set<number>();
|
|
94
|
+
changes.forEach((change, index) => {
|
|
95
|
+
if (change.op === "keep") return;
|
|
96
|
+
for (let at = index - context; at <= index + context; at++) keep.add(at);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const out: string[] = [];
|
|
100
|
+
let skipping = false;
|
|
101
|
+
changes.forEach((change, index) => {
|
|
102
|
+
if (!keep.has(index)) {
|
|
103
|
+
if (!skipping) out.push(" ...");
|
|
104
|
+
skipping = true;
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
skipping = false;
|
|
108
|
+
out.push(`${change.op === "add" ? "+ " : change.op === "remove" ? "- " : " "}${change.line}`);
|
|
109
|
+
});
|
|
110
|
+
return out.join("\n");
|
|
111
|
+
}
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing a component into a project, and the import rewriting that needs.
|
|
3
|
+
*
|
|
4
|
+
* A registry file's own imports are relative — `../lib/slot.ts` from
|
|
5
|
+
* `ui/button.tsx` — because that is what they are in the package they came
|
|
6
|
+
* from. A project may put `ui` and `lib` somewhere else entirely, so every
|
|
7
|
+
* relative specifier is recomputed against where the two files ACTUALLY land.
|
|
8
|
+
*
|
|
9
|
+
* That is the whole of it. shadcn rewrites imports to an alias
|
|
10
|
+
* (`@/components/ui/button`) and needs the project's `tsconfig` paths to agree;
|
|
11
|
+
* a relative path needs nothing to agree, and it is right in a project with no
|
|
12
|
+
* aliases at all.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
18
|
+
|
|
19
|
+
import type { Config, ItemType, RegistryFile } from "./schema.ts";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where a file of this type goes, as an absolute directory.
|
|
23
|
+
*
|
|
24
|
+
* `page` and `file` have none of their own and answer with the project root,
|
|
25
|
+
* which is what their `target` is relative to.
|
|
26
|
+
*/
|
|
27
|
+
export function directoryFor(config: Config, cwd: string, type: ItemType): string {
|
|
28
|
+
const paths = config.paths;
|
|
29
|
+
const chosen: Record<ItemType, string> = {
|
|
30
|
+
"registry:ui": paths.ui,
|
|
31
|
+
"registry:lib": paths.lib,
|
|
32
|
+
"registry:theme": paths.theme,
|
|
33
|
+
"registry:hook": paths.hooks,
|
|
34
|
+
"registry:block": paths.components,
|
|
35
|
+
"registry:component": paths.components,
|
|
36
|
+
"registry:example": paths.components,
|
|
37
|
+
"registry:page": ".",
|
|
38
|
+
"registry:file": ".",
|
|
39
|
+
};
|
|
40
|
+
return resolve(cwd, chosen[type]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The three whose registry path is a tree to keep rather than a name to file. */
|
|
44
|
+
const NESTED = new Set<ItemType>(["registry:block", "registry:component", "registry:example"]);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The absolute path a registry file is written to.
|
|
48
|
+
*
|
|
49
|
+
* A registry is someone else's data, and a `target` or a path that climbs out
|
|
50
|
+
* of the project would let `add` write anywhere the user can. So the answer is
|
|
51
|
+
* checked against the root before anything is written to it.
|
|
52
|
+
*/
|
|
53
|
+
export function targetOf(config: Config, cwd: string, file: RegistryFile): string {
|
|
54
|
+
const root = resolve(cwd);
|
|
55
|
+
const name = file.path.split("/").at(-1) ?? file.path;
|
|
56
|
+
const absolute =
|
|
57
|
+
file.target !== undefined
|
|
58
|
+
? resolve(root, file.target.replace(/^~\//, ""))
|
|
59
|
+
: NESTED.has(file.type)
|
|
60
|
+
? join(directoryFor(config, cwd, file.type), file.path.replace(/^components\//, ""))
|
|
61
|
+
: join(directoryFor(config, cwd, file.type), name);
|
|
62
|
+
|
|
63
|
+
const inside = relative(root, absolute);
|
|
64
|
+
if (inside.startsWith("..") || isAbsolute(inside)) {
|
|
65
|
+
throw new Error(`${file.path} would be written to ${absolute}, which is outside the project`);
|
|
66
|
+
}
|
|
67
|
+
return absolute;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The directory a registry path starts with, as the type it stands for. */
|
|
71
|
+
function typeOfPath(path: string): ItemType {
|
|
72
|
+
const directory = path.split("/")[0];
|
|
73
|
+
if (directory === "lib") return "registry:lib";
|
|
74
|
+
if (directory === "theme") return "registry:theme";
|
|
75
|
+
if (directory === "hooks") return "registry:hook";
|
|
76
|
+
if (directory === "blocks") return "registry:block";
|
|
77
|
+
if (directory === "components") return "registry:component";
|
|
78
|
+
return "registry:ui";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Registry path to the file that has it, for everything being written at once.
|
|
83
|
+
*
|
|
84
|
+
* A relative import names another registry file, and where THAT one lands is
|
|
85
|
+
* decided by its own type and `target`. Only the file itself knows those, so
|
|
86
|
+
* the files travelling together are looked up before the path is guessed at.
|
|
87
|
+
*/
|
|
88
|
+
export type Placed = ReadonlyMap<string, RegistryFile>;
|
|
89
|
+
|
|
90
|
+
export function placed(items: readonly { readonly files: readonly RegistryFile[] }[]): Placed {
|
|
91
|
+
const out = new Map<string, RegistryFile>();
|
|
92
|
+
for (const item of items) for (const file of item.files) out.set(file.path, file);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const SPECIFIER = /(from\s*|import\s*)(["'])(\.[^"']*)\2/g;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The file's own text, with every relative import pointed at where that file
|
|
100
|
+
* will be.
|
|
101
|
+
*
|
|
102
|
+
* The extension is kept: this package's own source imports `./button.tsx`, and
|
|
103
|
+
* so does what it writes. A project whose bundler wants extensionless imports
|
|
104
|
+
* is the one case this does not serve, and it is the rarer one now.
|
|
105
|
+
*/
|
|
106
|
+
export function rewrite(
|
|
107
|
+
config: Config,
|
|
108
|
+
cwd: string,
|
|
109
|
+
file: RegistryFile,
|
|
110
|
+
together: Placed = new Map(),
|
|
111
|
+
): string {
|
|
112
|
+
const here = dirname(targetOf(config, cwd, file));
|
|
113
|
+
|
|
114
|
+
return file.content.replaceAll(
|
|
115
|
+
SPECIFIER,
|
|
116
|
+
(_whole, lead: string, quote: string, specifier: string) => {
|
|
117
|
+
// Resolve against the file's position IN THE REGISTRY, which is what the
|
|
118
|
+
// specifier was written against.
|
|
119
|
+
const inRegistry = join(dirname(file.path), specifier).replaceAll("\\", "/");
|
|
120
|
+
const there = targetOf(
|
|
121
|
+
config,
|
|
122
|
+
cwd,
|
|
123
|
+
together.get(inRegistry) ?? { path: inRegistry, type: typeOfPath(inRegistry), content: "" },
|
|
124
|
+
);
|
|
125
|
+
let next = relative(here, there).replaceAll("\\", "/");
|
|
126
|
+
if (!next.startsWith(".")) next = `./${next}`;
|
|
127
|
+
return `${lead}${quote}${next}${quote}`;
|
|
128
|
+
},
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function hashOf(content: string): string {
|
|
133
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function write(path: string, content: string): void {
|
|
137
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
138
|
+
writeFileSync(path, content);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function read(path: string): string | undefined {
|
|
142
|
+
try {
|
|
143
|
+
return readFileSync(path, "utf8");
|
|
144
|
+
} catch {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
}
|