-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathadd-resource.ts
More file actions
233 lines (208 loc) · 7.06 KB
/
add-resource.ts
File metadata and controls
233 lines (208 loc) · 7.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { cancel, intro, outro } from "@clack/prompts";
import { Command } from "commander";
import { promptOneResource } from "../create/prompt-resource";
import {
DEFAULT_PERMISSION_BY_TYPE,
getDefaultFieldsForType,
getValidResourceTypes,
humanizeResourceType,
resourceKeyFromType,
} from "../create/resource-defaults";
import { resolveManifestInDir } from "../manifest-resolve";
import type { PluginManifest, ResourceRequirement } from "../manifest-types";
import { validateManifest } from "../validate/validate-manifest";
/** Extended manifest type that preserves extra JSON fields (e.g. $schema, author, version) for round-trip writes. */
interface ManifestWithExtras extends PluginManifest {
[key: string]: unknown;
}
interface AddResourceOptions {
path?: string;
type?: string;
required?: boolean;
resourceKey?: string;
description?: string;
permission?: string;
fieldsJson?: string;
dryRun?: boolean;
}
function loadManifest(
pluginDir: string,
): { manifest: ManifestWithExtras; manifestPath: string } | null {
const resolved = resolveManifestInDir(pluginDir, { allowJsManifest: true });
if (!resolved) {
console.error(
`No manifest found in ${pluginDir}. This command requires manifest.json (manifest.js cannot be edited in place).`,
);
console.error(
" appkit plugin add-resource --path <dir-with-manifest.json>",
);
process.exit(1);
}
if (resolved.type !== "json") {
console.error(
`Editable manifest not found. add-resource only supports plugin directories that contain manifest.json (found ${path.basename(resolved.path)}).`,
);
process.exit(1);
}
const manifestPath = resolved.path;
try {
const raw = fs.readFileSync(manifestPath, "utf-8");
const parsed = JSON.parse(raw) as unknown;
const result = validateManifest(parsed);
if (!result.valid || !result.manifest) {
console.error(
"Invalid manifest. Run `appkit plugin validate` for details.",
);
process.exit(1);
}
return { manifest: parsed as ManifestWithExtras, manifestPath };
} catch (err) {
console.error(
"Failed to read or parse manifest.json:",
err instanceof Error ? err.message : err,
);
process.exit(1);
}
}
function buildEntry(
type: string,
opts: AddResourceOptions,
): { entry: ResourceRequirement; isRequired: boolean } {
const alias = humanizeResourceType(type);
const isRequired = opts.required !== false;
let fields = getDefaultFieldsForType(type);
if (opts.fieldsJson) {
try {
const parsed = JSON.parse(opts.fieldsJson) as Record<
string,
{ env: string; description?: string }
>;
fields = { ...fields, ...parsed };
} catch {
console.error("Error: --fields-json must be valid JSON.");
console.error(
' Example: --fields-json \'{"id":{"env":"MY_WAREHOUSE_ID"}}\'',
);
process.exit(1);
}
}
const entry: ResourceRequirement = {
type: type as ResourceRequirement["type"],
alias,
resourceKey: opts.resourceKey ?? resourceKeyFromType(type),
description:
opts.description ||
`${isRequired ? "Required" : "Optional"} for ${alias} functionality.`,
permission:
opts.permission ?? DEFAULT_PERMISSION_BY_TYPE[type] ?? "CAN_VIEW",
fields,
};
return { entry, isRequired };
}
function runNonInteractive(opts: AddResourceOptions): void {
const cwd = process.cwd();
const pluginDir = path.resolve(cwd, opts.path ?? ".");
const loaded = loadManifest(pluginDir);
if (!loaded) return;
const { manifest, manifestPath } = loaded;
const type = opts.type as string;
const validTypes = getValidResourceTypes();
if (!validTypes.includes(type)) {
console.error(`Error: Unknown resource type "${type}".`);
console.error(` Valid types: ${validTypes.join(", ")}`);
process.exit(1);
}
const { entry, isRequired } = buildEntry(type, opts);
if (isRequired) {
manifest.resources.required.push(entry);
} else {
manifest.resources.optional.push(entry);
}
if (opts.dryRun) {
console.log(JSON.stringify(manifest, null, 2));
return;
}
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
console.log(
`Added ${entry.alias} as ${isRequired ? "required" : "optional"} to ${path.relative(cwd, manifestPath)}`,
);
}
async function runInteractive(opts: AddResourceOptions): Promise<void> {
intro("Add resource to plugin manifest");
const cwd = process.cwd();
const pluginDir = path.resolve(cwd, opts.path ?? ".");
const loaded = loadManifest(pluginDir);
if (!loaded) return;
const { manifest, manifestPath } = loaded;
const spec = await promptOneResource();
if (!spec) {
cancel("Cancelled.");
process.exit(0);
}
const alias = humanizeResourceType(spec.type);
const entry: ResourceRequirement = {
type: spec.type as ResourceRequirement["type"],
alias,
resourceKey: spec.resourceKey,
description: spec.description || `Required for ${alias} functionality.`,
permission: spec.permission,
fields: spec.fields,
};
if (spec.required) {
manifest.resources.required.push(entry);
} else {
manifest.resources.optional.push(entry);
}
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
outro("Resource added.");
console.log(
`\nAdded ${alias} as ${spec.required ? "required" : "optional"} to ${path.relative(cwd, manifestPath)}`,
);
}
async function runPluginAddResource(opts: AddResourceOptions): Promise<void> {
if (opts.type) {
runNonInteractive(opts);
} else {
await runInteractive(opts);
}
}
export const pluginAddResourceCommand = new Command("add-resource")
.description(
"Add a resource requirement to an existing plugin manifest. Overwrites manifest.json in place.",
)
.option(
"-p, --path <dir>",
"Plugin directory containing manifest.json (default: .)",
)
.option(
"-t, --type <resource_type>",
"Resource type (e.g. sql_warehouse, volume). Enables non-interactive mode.",
)
.option("--required", "Mark resource as required (default: true)", true)
.option("--no-required", "Mark resource as optional")
.option("--resource-key <key>", "Resource key (default: derived from type)")
.option("--description <text>", "Description of the resource requirement")
.option("--permission <perm>", "Permission level (default: from schema)")
.option(
"--fields-json <json>",
'JSON object overriding field env vars (e.g. \'{"id":{"env":"MY_WAREHOUSE_ID"}}\')',
)
.option("--dry-run", "Preview the updated manifest without writing")
.addHelpText(
"after",
`
Examples:
$ appkit plugin add-resource
$ appkit plugin add-resource --path plugins/my-plugin --type sql_warehouse
$ appkit plugin add-resource --path plugins/my-plugin --type volume --no-required --dry-run
$ appkit plugin add-resource --type sql_warehouse --fields-json '{"id":{"env":"MY_WAREHOUSE_ID"}}'`,
)
.action((opts) =>
runPluginAddResource(opts).catch((err) => {
console.error(err);
process.exit(1);
}),
);