@vsceasy/cli 0.1.3 → 0.1.5
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/dist/bin/cli.js +3877 -48
- package/dist/index.js +3840 -11
- package/dist/lib/findProject.d.ts +13 -2
- package/dist/lib/templatesData.d.ts +2 -0
- package/dist/lib/wizard/run.d.ts +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -2237,6 +2237,3796 @@ var init_upgrade = __esm(() => {
|
|
|
2237
2237
|
];
|
|
2238
2238
|
});
|
|
2239
2239
|
|
|
2240
|
+
// src/lib/templatesData.ts
|
|
2241
|
+
var TEMPLATES_VERSION = "0.1.5", TEMPLATE_FILES;
|
|
2242
|
+
var init_templatesData = __esm(() => {
|
|
2243
|
+
TEMPLATE_FILES = {
|
|
2244
|
+
"_generators/command/command.ts.tpl": `import { defineCommand } from '../shared/vsceasy';
|
|
2245
|
+
|
|
2246
|
+
export default defineCommand({
|
|
2247
|
+
title: '{{title}}',{{categoryLine}}{{keybindingLine}}{{whenLine}}
|
|
2248
|
+
run: (vscode) => {
|
|
2249
|
+
vscode.window.showInformationMessage('{{title}} ran');
|
|
2250
|
+
},
|
|
2251
|
+
});
|
|
2252
|
+
`,
|
|
2253
|
+
"_generators/components/Button.tsx.tpl": `import React from 'react';
|
|
2254
|
+
|
|
2255
|
+
type Variant = 'primary' | 'secondary';
|
|
2256
|
+
|
|
2257
|
+
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
|
2258
|
+
variant?: Variant;
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
/** Theme-aware button using VS Code button tokens. */
|
|
2262
|
+
export function Button({ variant = 'primary', className = '', ...rest }: ButtonProps) {
|
|
2263
|
+
return <button className={\`vx-btn vx-btn--\${variant} \${className}\`.trim()} {...rest} />;
|
|
2264
|
+
}
|
|
2265
|
+
`,
|
|
2266
|
+
"_generators/components/Card.tsx.tpl": `import React from 'react';
|
|
2267
|
+
|
|
2268
|
+
export interface CardProps {
|
|
2269
|
+
title?: string;
|
|
2270
|
+
actions?: React.ReactNode;
|
|
2271
|
+
children: React.ReactNode;
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
/** Bordered surface for grouping content, with an optional title + actions row. */
|
|
2275
|
+
export function Card({ title, actions, children }: CardProps) {
|
|
2276
|
+
return (
|
|
2277
|
+
<section className="vx-card">
|
|
2278
|
+
{(title || actions) && (
|
|
2279
|
+
<header className="vx-card__head">
|
|
2280
|
+
{title ? <h2 className="vx-card__title">{title}</h2> : <span />}
|
|
2281
|
+
{actions ? <div className="vx-card__actions">{actions}</div> : null}
|
|
2282
|
+
</header>
|
|
2283
|
+
)}
|
|
2284
|
+
<div className="vx-card__body">{children}</div>
|
|
2285
|
+
</section>
|
|
2286
|
+
);
|
|
2287
|
+
}
|
|
2288
|
+
`,
|
|
2289
|
+
"_generators/components/Field.tsx.tpl": `import React from 'react';
|
|
2290
|
+
|
|
2291
|
+
export interface FieldProps {
|
|
2292
|
+
label: string;
|
|
2293
|
+
htmlFor?: string;
|
|
2294
|
+
hint?: string;
|
|
2295
|
+
error?: string;
|
|
2296
|
+
children: React.ReactNode;
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
/** Labeled form field wrapper with optional hint / error text. */
|
|
2300
|
+
export function Field({ label, htmlFor, hint, error, children }: FieldProps) {
|
|
2301
|
+
return (
|
|
2302
|
+
<div className="vx-field">
|
|
2303
|
+
<label className="vx-field__label" htmlFor={htmlFor}>{label}</label>
|
|
2304
|
+
{children}
|
|
2305
|
+
{error ? <span className="vx-field__error">{error}</span> : hint ? <span className="vx-field__hint">{hint}</span> : null}
|
|
2306
|
+
</div>
|
|
2307
|
+
);
|
|
2308
|
+
}
|
|
2309
|
+
`,
|
|
2310
|
+
"_generators/components/Input.tsx.tpl": `import React from 'react';
|
|
2311
|
+
|
|
2312
|
+
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
|
|
2313
|
+
|
|
2314
|
+
/** Theme-aware text input using VS Code input tokens. */
|
|
2315
|
+
export const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|
2316
|
+
function Input({ className = '', ...rest }, ref) {
|
|
2317
|
+
return <input ref={ref} className={\`vx-input \${className}\`.trim()} {...rest} />;
|
|
2318
|
+
},
|
|
2319
|
+
);
|
|
2320
|
+
`,
|
|
2321
|
+
"_generators/components/List.tsx.tpl": `import React from 'react';
|
|
2322
|
+
|
|
2323
|
+
export interface ListProps<T> {
|
|
2324
|
+
items: T[];
|
|
2325
|
+
getKey: (item: T, index: number) => string | number;
|
|
2326
|
+
renderItem: (item: T, index: number) => React.ReactNode;
|
|
2327
|
+
onSelect?: (item: T, index: number) => void;
|
|
2328
|
+
empty?: React.ReactNode;
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
/** Selectable, theme-aware list. Rows highlight on hover and on selection. */
|
|
2332
|
+
export function List<T>({ items, getKey, renderItem, onSelect, empty }: ListProps<T>) {
|
|
2333
|
+
if (items.length === 0) {
|
|
2334
|
+
return <div className="vx-list__empty">{empty ?? 'Nothing here yet.'}</div>;
|
|
2335
|
+
}
|
|
2336
|
+
return (
|
|
2337
|
+
<ul className="vx-list" role="list">
|
|
2338
|
+
{items.map((item, i) => (
|
|
2339
|
+
<li
|
|
2340
|
+
key={getKey(item, i)}
|
|
2341
|
+
className={\`vx-list__row\${onSelect ? ' vx-list__row--clickable' : ''}\`}
|
|
2342
|
+
onClick={onSelect ? () => onSelect(item, i) : undefined}
|
|
2343
|
+
>
|
|
2344
|
+
{renderItem(item, i)}
|
|
2345
|
+
</li>
|
|
2346
|
+
))}
|
|
2347
|
+
</ul>
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
`,
|
|
2351
|
+
"_generators/components/components.css.tpl": `.vx-btn {
|
|
2352
|
+
font: inherit;
|
|
2353
|
+
padding: 0.35rem 0.85rem;
|
|
2354
|
+
border-radius: 2px;
|
|
2355
|
+
border: 1px solid transparent;
|
|
2356
|
+
cursor: pointer;
|
|
2357
|
+
}
|
|
2358
|
+
.vx-btn:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 2px; }
|
|
2359
|
+
.vx-btn:disabled { opacity: 0.5; cursor: default; }
|
|
2360
|
+
.vx-btn--primary {
|
|
2361
|
+
color: var(--vscode-button-foreground);
|
|
2362
|
+
background: var(--vscode-button-background);
|
|
2363
|
+
}
|
|
2364
|
+
.vx-btn--primary:hover:not(:disabled) { background: var(--vscode-button-hoverBackground); }
|
|
2365
|
+
.vx-btn--secondary {
|
|
2366
|
+
color: var(--vscode-button-secondaryForeground, var(--vscode-foreground));
|
|
2367
|
+
background: var(--vscode-button-secondaryBackground, transparent);
|
|
2368
|
+
border-color: var(--vscode-button-border, var(--vscode-input-border, #555));
|
|
2369
|
+
}
|
|
2370
|
+
.vx-btn--secondary:hover:not(:disabled) { background: var(--vscode-button-secondaryHoverBackground, var(--vscode-list-hoverBackground)); }
|
|
2371
|
+
|
|
2372
|
+
.vx-input {
|
|
2373
|
+
font: inherit;
|
|
2374
|
+
width: 100%;
|
|
2375
|
+
box-sizing: border-box;
|
|
2376
|
+
padding: 0.35rem 0.5rem;
|
|
2377
|
+
border-radius: 2px;
|
|
2378
|
+
color: var(--vscode-input-foreground);
|
|
2379
|
+
background: var(--vscode-input-background);
|
|
2380
|
+
border: 1px solid var(--vscode-input-border, #555);
|
|
2381
|
+
}
|
|
2382
|
+
.vx-input:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; }
|
|
2383
|
+
.vx-input::placeholder { color: var(--vscode-input-placeholderForeground); }
|
|
2384
|
+
|
|
2385
|
+
.vx-field { display: flex; flex-direction: column; gap: 0.25rem; margin-bottom: 0.75rem; }
|
|
2386
|
+
.vx-field__label { font-size: 0.85em; color: var(--vscode-foreground); }
|
|
2387
|
+
.vx-field__hint { font-size: 0.8em; color: var(--vscode-descriptionForeground); }
|
|
2388
|
+
.vx-field__error { font-size: 0.8em; color: var(--vscode-errorForeground); }
|
|
2389
|
+
|
|
2390
|
+
.vx-card {
|
|
2391
|
+
border: 1px solid var(--vscode-panel-border, var(--vscode-input-border, #555));
|
|
2392
|
+
border-radius: 4px;
|
|
2393
|
+
margin-bottom: 0.75rem;
|
|
2394
|
+
background: var(--vscode-editorWidget-background, transparent);
|
|
2395
|
+
}
|
|
2396
|
+
.vx-card__head {
|
|
2397
|
+
display: flex;
|
|
2398
|
+
align-items: center;
|
|
2399
|
+
justify-content: space-between;
|
|
2400
|
+
gap: 0.5rem;
|
|
2401
|
+
padding: 0.5rem 0.75rem;
|
|
2402
|
+
border-bottom: 1px solid var(--vscode-panel-border, var(--vscode-input-border, #555));
|
|
2403
|
+
}
|
|
2404
|
+
.vx-card__title { font-size: 1em; font-weight: 600; margin: 0; }
|
|
2405
|
+
.vx-card__actions { display: flex; gap: 0.5rem; }
|
|
2406
|
+
.vx-card__body { padding: 0.75rem; }
|
|
2407
|
+
|
|
2408
|
+
.vx-list { list-style: none; margin: 0; padding: 0; }
|
|
2409
|
+
.vx-list__row {
|
|
2410
|
+
padding: 0.4rem 0.6rem;
|
|
2411
|
+
border-radius: 2px;
|
|
2412
|
+
line-height: 1.5;
|
|
2413
|
+
}
|
|
2414
|
+
.vx-list__row--clickable { cursor: pointer; }
|
|
2415
|
+
.vx-list__row--clickable:hover { background: var(--vscode-list-hoverBackground); }
|
|
2416
|
+
.vx-list__empty { color: var(--vscode-descriptionForeground); padding: 0.6rem; }
|
|
2417
|
+
`,
|
|
2418
|
+
"_generators/components/index.ts.tpl": `export { Button } from './Button';
|
|
2419
|
+
export type { ButtonProps } from './Button';
|
|
2420
|
+
export { Input } from './Input';
|
|
2421
|
+
export type { InputProps } from './Input';
|
|
2422
|
+
export { Field } from './Field';
|
|
2423
|
+
export type { FieldProps } from './Field';
|
|
2424
|
+
export { Card } from './Card';
|
|
2425
|
+
export type { CardProps } from './Card';
|
|
2426
|
+
export { List } from './List';
|
|
2427
|
+
export type { ListProps } from './List';
|
|
2428
|
+
`,
|
|
2429
|
+
"_generators/crud/formApp.tsx.tpl": `import { useCallback, useEffect, useState } from 'react';
|
|
2430
|
+
import { connectWebview } from '../../../shared/vsceasy/client';
|
|
2431
|
+
import type { {{Name}}FormApi } from '../../../shared/api';
|
|
2432
|
+
import type { {{Name}} } from '../../../models/{{Name}}';
|
|
2433
|
+
|
|
2434
|
+
const api = connectWebview<{{Name}}FormApi>();
|
|
2435
|
+
|
|
2436
|
+
type FormState = Partial<{{Name}}>;
|
|
2437
|
+
|
|
2438
|
+
const emptyForm: FormState = {{emptyFormLiteral}};
|
|
2439
|
+
|
|
2440
|
+
export function App() {
|
|
2441
|
+
const [form, setForm] = useState<FormState>(emptyForm);
|
|
2442
|
+
const [editingId, setEditingId] = useState<{{Name}}['{{primaryKey}}'] | null>(null);
|
|
2443
|
+
const [error, setError] = useState<string | null>(null);
|
|
2444
|
+
const [saving, setSaving] = useState(false);
|
|
2445
|
+
|
|
2446
|
+
const load = useCallback(async () => {
|
|
2447
|
+
// The list stashes the row id before revealing this panel. Pull it (the host
|
|
2448
|
+
// clears it after handing it over) and pre-fill the form for editing.
|
|
2449
|
+
const id = await api.pendingId();
|
|
2450
|
+
if (id == null || id === '') {
|
|
2451
|
+
setForm(emptyForm);
|
|
2452
|
+
setEditingId(null);
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
const row = await api.get(id);
|
|
2456
|
+
if (row) {
|
|
2457
|
+
setForm(row);
|
|
2458
|
+
setEditingId(row.{{primaryKey}});
|
|
2459
|
+
}
|
|
2460
|
+
}, []);
|
|
2461
|
+
|
|
2462
|
+
useEffect(() => {
|
|
2463
|
+
void load();
|
|
2464
|
+
// Webviews retain state when hidden, so re-load whenever the panel is
|
|
2465
|
+
// revealed — the list may have asked to edit a different row.
|
|
2466
|
+
const onFocus = () => { void load(); };
|
|
2467
|
+
const onVisible = () => { if (document.visibilityState === 'visible') void load(); };
|
|
2468
|
+
window.addEventListener('focus', onFocus);
|
|
2469
|
+
document.addEventListener('visibilitychange', onVisible);
|
|
2470
|
+
return () => {
|
|
2471
|
+
window.removeEventListener('focus', onFocus);
|
|
2472
|
+
document.removeEventListener('visibilitychange', onVisible);
|
|
2473
|
+
};
|
|
2474
|
+
}, [load]);
|
|
2475
|
+
|
|
2476
|
+
const onChange = <K extends keyof FormState>(k: K, v: FormState[K]) => {
|
|
2477
|
+
setForm((f) => ({ ...f, [k]: v }));
|
|
2478
|
+
};
|
|
2479
|
+
|
|
2480
|
+
const onSubmit = async (e: React.FormEvent) => {
|
|
2481
|
+
e.preventDefault();
|
|
2482
|
+
setSaving(true);
|
|
2483
|
+
setError(null);
|
|
2484
|
+
try {
|
|
2485
|
+
const wasNew = editingId == null;
|
|
2486
|
+
await api.save(form as {{Name}});
|
|
2487
|
+
// After creating a new row, reset for the next entry. After an edit, keep
|
|
2488
|
+
// the row loaded so further tweaks are possible.
|
|
2489
|
+
if (wasNew) {
|
|
2490
|
+
setForm(emptyForm);
|
|
2491
|
+
setEditingId(null);
|
|
2492
|
+
}
|
|
2493
|
+
} catch (err: any) {
|
|
2494
|
+
setError(String(err?.message ?? err));
|
|
2495
|
+
} finally {
|
|
2496
|
+
setSaving(false);
|
|
2497
|
+
}
|
|
2498
|
+
};
|
|
2499
|
+
|
|
2500
|
+
return (
|
|
2501
|
+
<form onSubmit={onSubmit} style={{ padding: 16, display: 'grid', gap: 12, color: 'var(--vscode-foreground)' }}>
|
|
2502
|
+
<h2 style={{ margin: 0 }}>{editingId ? 'Edit {{title}}' : 'New {{title}}'}</h2>
|
|
2503
|
+
{{formFieldInputs}}
|
|
2504
|
+
{error && <div style={{ color: 'var(--vscode-errorForeground)' }}>{error}</div>}
|
|
2505
|
+
<div style={{ display: 'flex', gap: 8 }}>
|
|
2506
|
+
<button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
|
|
2507
|
+
<button type="button" onClick={() => { setForm(emptyForm); setEditingId(null); }}>Reset</button>
|
|
2508
|
+
</div>
|
|
2509
|
+
</form>
|
|
2510
|
+
);
|
|
2511
|
+
}
|
|
2512
|
+
`,
|
|
2513
|
+
"_generators/crud/formNav.ts.tpl": `/**
|
|
2514
|
+
* In-memory hand-off for "open the {{Name}} form to edit row X". The list panel
|
|
2515
|
+
* sets the pending id before revealing the form; the form reads (and clears) it
|
|
2516
|
+
* on mount. Lives in the extension host, shared across the two panel modules.
|
|
2517
|
+
*/
|
|
2518
|
+
type {{Name}}Id = unknown;
|
|
2519
|
+
|
|
2520
|
+
let pendingId: {{Name}}Id | null = null;
|
|
2521
|
+
|
|
2522
|
+
export function setPending{{Name}}Id(id: {{Name}}Id | null): void {
|
|
2523
|
+
pendingId = id ?? null;
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
/** Returns the pending id once, then clears it. */
|
|
2527
|
+
export function takePending{{Name}}Id(): {{Name}}Id | null {
|
|
2528
|
+
const v = pendingId;
|
|
2529
|
+
pendingId = null;
|
|
2530
|
+
return v;
|
|
2531
|
+
}
|
|
2532
|
+
`,
|
|
2533
|
+
"_generators/crud/formPanel.ts.tpl": `import { definePanel } from '../shared/vsceasy';
|
|
2534
|
+
import { {{Name}}Service } from '../services/{{Name}}Service';
|
|
2535
|
+
import { takePending{{Name}}Id } from '../services/{{name}}FormNav';
|
|
2536
|
+
import type { {{Name}}FormApi } from '../shared/api';
|
|
2537
|
+
import type { {{Name}} } from '../models/{{Name}}';
|
|
2538
|
+
|
|
2539
|
+
export default definePanel<{{Name}}FormApi>({
|
|
2540
|
+
title: '{{title}}',
|
|
2541
|
+
column: 'beside',
|
|
2542
|
+
command: { title: '{{title}}: New / Edit' },
|
|
2543
|
+
rpc: (vscode) => ({
|
|
2544
|
+
async pendingId() {
|
|
2545
|
+
// Consumed once by the webview on mount to decide edit vs new.
|
|
2546
|
+
return (takePending{{Name}}Id() as {{Name}}['{{primaryKey}}'] | null) ?? null;
|
|
2547
|
+
},
|
|
2548
|
+
async get(id) {
|
|
2549
|
+
if (!id) return null;
|
|
2550
|
+
return {{Name}}Service.get(id as {{Name}}['{{primaryKey}}']);
|
|
2551
|
+
},
|
|
2552
|
+
async save(row) {
|
|
2553
|
+
const saved = await {{Name}}Service.save(row);
|
|
2554
|
+
void vscode.window.showInformationMessage(\`{{title}} saved (\${String(saved.{{primaryKey}})})\`);
|
|
2555
|
+
// Reveal the list so the new/edited row shows. Revealing fires the list
|
|
2556
|
+
// webview's focus/visibility listener, which reloads it.
|
|
2557
|
+
void vscode.commands.executeCommand('{{prefix}}.open{{Plural}}List');
|
|
2558
|
+
return saved;
|
|
2559
|
+
},
|
|
2560
|
+
async cancel() {
|
|
2561
|
+
// No-op — webview closes itself.
|
|
2562
|
+
},
|
|
2563
|
+
}),
|
|
2564
|
+
});
|
|
2565
|
+
`,
|
|
2566
|
+
"_generators/crud/listApp.tsx.tpl": `import { useEffect, useState, useCallback } from 'react';
|
|
2567
|
+
import { connectWebview } from '../../../shared/vsceasy/client';
|
|
2568
|
+
import type { {{Plural}}ListApi } from '../../../shared/api';
|
|
2569
|
+
import type { {{Name}} } from '../../../models/{{Name}}';
|
|
2570
|
+
|
|
2571
|
+
const api = connectWebview<{{Plural}}ListApi>();
|
|
2572
|
+
|
|
2573
|
+
export function App() {
|
|
2574
|
+
const [rows, setRows] = useState<{{Name}}[]>([]);
|
|
2575
|
+
const [loading, setLoading] = useState(true);
|
|
2576
|
+
const [error, setError] = useState<string | null>(null);
|
|
2577
|
+
|
|
2578
|
+
const reload = useCallback(async () => {
|
|
2579
|
+
setLoading(true);
|
|
2580
|
+
try {
|
|
2581
|
+
setRows(await api.list());
|
|
2582
|
+
setError(null);
|
|
2583
|
+
} catch (e: any) {
|
|
2584
|
+
setError(String(e?.message ?? e));
|
|
2585
|
+
} finally {
|
|
2586
|
+
setLoading(false);
|
|
2587
|
+
}
|
|
2588
|
+
}, []);
|
|
2589
|
+
|
|
2590
|
+
useEffect(() => {
|
|
2591
|
+
void reload();
|
|
2592
|
+
// Webviews keep their state when hidden (retainContextWhenHidden), so the
|
|
2593
|
+
// mount effect won't re-run when the panel is revealed again. Reload when the
|
|
2594
|
+
// webview regains focus/visibility so edits made in another panel show up.
|
|
2595
|
+
const onFocus = () => { void reload(); };
|
|
2596
|
+
const onVisible = () => { if (document.visibilityState === 'visible') void reload(); };
|
|
2597
|
+
window.addEventListener('focus', onFocus);
|
|
2598
|
+
document.addEventListener('visibilitychange', onVisible);
|
|
2599
|
+
return () => {
|
|
2600
|
+
window.removeEventListener('focus', onFocus);
|
|
2601
|
+
document.removeEventListener('visibilitychange', onVisible);
|
|
2602
|
+
};
|
|
2603
|
+
}, [reload]);
|
|
2604
|
+
|
|
2605
|
+
const onDelete = async (id: {{Name}}['{{primaryKey}}']) => {
|
|
2606
|
+
// \`confirm()\` is disabled inside VS Code webviews — confirmation happens in
|
|
2607
|
+
// the host (the \`delete\` RPC handler shows a modal). Just call + reload.
|
|
2608
|
+
await api.delete(id);
|
|
2609
|
+
await reload();
|
|
2610
|
+
};
|
|
2611
|
+
|
|
2612
|
+
return (
|
|
2613
|
+
<div style={{ padding: 16, color: 'var(--vscode-foreground)' }}>
|
|
2614
|
+
<header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
|
|
2615
|
+
<h2 style={{ margin: 0 }}>{{title}}</h2>
|
|
2616
|
+
<div style={{ display: 'flex', gap: 8 }}>
|
|
2617
|
+
<button onClick={() => void reload()} disabled={loading}>{loading ? 'Loading…' : 'Refresh'}</button>
|
|
2618
|
+
<button onClick={() => api.openForm()}>+ New</button>
|
|
2619
|
+
</div>
|
|
2620
|
+
</header>
|
|
2621
|
+
|
|
2622
|
+
{error && <div style={{ color: 'var(--vscode-errorForeground)', marginBottom: 8 }}>{error}</div>}
|
|
2623
|
+
{loading ? <div>Loading…</div> : (
|
|
2624
|
+
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
|
2625
|
+
<thead>
|
|
2626
|
+
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--vscode-panel-border)' }}>
|
|
2627
|
+
{{listHeaderCells}}
|
|
2628
|
+
<th style={{ padding: '6px 8px' }}></th>
|
|
2629
|
+
</tr>
|
|
2630
|
+
</thead>
|
|
2631
|
+
<tbody>
|
|
2632
|
+
{rows.length === 0 && (
|
|
2633
|
+
<tr><td colSpan={{{listColCount}}} style={{ padding: 16, opacity: 0.6 }}>No rows yet.</td></tr>
|
|
2634
|
+
)}
|
|
2635
|
+
{rows.map((r) => (
|
|
2636
|
+
<tr key={String(r.{{primaryKey}})} style={{ borderBottom: '1px solid var(--vscode-panel-border)' }}>
|
|
2637
|
+
{{listBodyCells}}
|
|
2638
|
+
<td style={{ padding: '6px 8px', whiteSpace: 'nowrap' }}>
|
|
2639
|
+
<button onClick={() => api.openForm(r.{{primaryKey}})}>Edit</button>{' '}
|
|
2640
|
+
<button onClick={() => onDelete(r.{{primaryKey}})}>Delete</button>
|
|
2641
|
+
</td>
|
|
2642
|
+
</tr>
|
|
2643
|
+
))}
|
|
2644
|
+
</tbody>
|
|
2645
|
+
</table>
|
|
2646
|
+
)}
|
|
2647
|
+
</div>
|
|
2648
|
+
);
|
|
2649
|
+
}
|
|
2650
|
+
`,
|
|
2651
|
+
"_generators/crud/listPanel.ts.tpl": `import { definePanel } from '../shared/vsceasy';
|
|
2652
|
+
import { {{Name}}Service } from '../services/{{Name}}Service';
|
|
2653
|
+
import { setPending{{Name}}Id } from '../services/{{name}}FormNav';
|
|
2654
|
+
import type { {{Plural}}ListApi } from '../shared/api';
|
|
2655
|
+
|
|
2656
|
+
export default definePanel<{{Plural}}ListApi>({
|
|
2657
|
+
title: '{{title}}',
|
|
2658
|
+
column: 'active',
|
|
2659
|
+
command: { title: '{{title}}: List' },
|
|
2660
|
+
rpc: (vscode) => ({
|
|
2661
|
+
async list() {
|
|
2662
|
+
return {{Name}}Service.list();
|
|
2663
|
+
},
|
|
2664
|
+
async delete(id) {
|
|
2665
|
+
// Confirm in the host — browser confirm() is disabled in webviews.
|
|
2666
|
+
const pick = await vscode.window.showWarningMessage(
|
|
2667
|
+
\`Delete {{title}} "\${String(id)}"?\`,
|
|
2668
|
+
{ modal: true },
|
|
2669
|
+
'Delete',
|
|
2670
|
+
);
|
|
2671
|
+
if (pick !== 'Delete') return false;
|
|
2672
|
+
return {{Name}}Service.delete(id);
|
|
2673
|
+
},
|
|
2674
|
+
async openForm(id) {
|
|
2675
|
+
// Stash the id so the form can pre-load it on mount, then reveal the form.
|
|
2676
|
+
setPending{{Name}}Id(id ?? null);
|
|
2677
|
+
await vscode.commands.executeCommand('{{prefix}}.open{{Name}}Form', id ?? null);
|
|
2678
|
+
},
|
|
2679
|
+
}),
|
|
2680
|
+
});
|
|
2681
|
+
`,
|
|
2682
|
+
"_generators/crud/main.tsx.tpl": `import React from 'react';
|
|
2683
|
+
import { createRoot } from 'react-dom/client';
|
|
2684
|
+
import { App } from './App';
|
|
2685
|
+
import '../../styles.css';
|
|
2686
|
+
|
|
2687
|
+
createRoot(document.getElementById('root')!).render(<App />);
|
|
2688
|
+
`,
|
|
2689
|
+
"_generators/crud/service.ts.tpl": `import { {{Plural}}Repo } from '../models/{{Name}}';
|
|
2690
|
+
import type { {{Name}} } from '../models/{{Name}}';
|
|
2691
|
+
|
|
2692
|
+
/**
|
|
2693
|
+
* {{Name}} service — business logic between RPC handlers and the repo.
|
|
2694
|
+
* Put validation, derivations (e.g. timestamps), and cross-entity work here.
|
|
2695
|
+
*/
|
|
2696
|
+
export const {{Name}}Service = {
|
|
2697
|
+
async list(): Promise<{{Name}}[]> {
|
|
2698
|
+
return {{Plural}}Repo().findMany({ orderBy: '{{primaryKey}}:desc' });
|
|
2699
|
+
},
|
|
2700
|
+
|
|
2701
|
+
async get(id: {{Name}}['{{primaryKey}}']): Promise<{{Name}} | null> {
|
|
2702
|
+
return {{Plural}}Repo().findById(id);
|
|
2703
|
+
},
|
|
2704
|
+
|
|
2705
|
+
async save(row: {{Name}}): Promise<{{Name}}> {
|
|
2706
|
+
if (!row.{{primaryKey}}) {
|
|
2707
|
+
throw new Error('{{Name}}: {{primaryKey}} is required');
|
|
2708
|
+
}
|
|
2709
|
+
return {{Plural}}Repo().upsert(row);
|
|
2710
|
+
},
|
|
2711
|
+
|
|
2712
|
+
async delete(id: {{Name}}['{{primaryKey}}']): Promise<boolean> {
|
|
2713
|
+
return {{Plural}}Repo().delete(id);
|
|
2714
|
+
},
|
|
2715
|
+
};
|
|
2716
|
+
`,
|
|
2717
|
+
"_generators/helper/cache.ts.tpl": `/**
|
|
2718
|
+
* In-memory TTL + LRU cache. Pair with the ORM for cheap reads:
|
|
2719
|
+
*
|
|
2720
|
+
* const cache = createCache<User>({ ttlMs: 60_000, max: 200 });
|
|
2721
|
+
* const u = await cache.wrap(\`user:\${id}\`, () => orm(User).findById(id));
|
|
2722
|
+
*
|
|
2723
|
+
* Survives only while the extension host is running (cleared on reload).
|
|
2724
|
+
* For persistent caches, write through to the ORM or \`globalState\`.
|
|
2725
|
+
*/
|
|
2726
|
+
|
|
2727
|
+
export interface CacheOptions {
|
|
2728
|
+
/** Time-to-live in ms. 0 = never expire. Default: 60000. */
|
|
2729
|
+
ttlMs?: number;
|
|
2730
|
+
/** Max entries. LRU eviction once exceeded. 0 = unlimited. Default: 500. */
|
|
2731
|
+
max?: number;
|
|
2732
|
+
}
|
|
2733
|
+
|
|
2734
|
+
export interface Cache<V> {
|
|
2735
|
+
get(key: string): V | undefined;
|
|
2736
|
+
set(key: string, value: V, ttlMsOverride?: number): void;
|
|
2737
|
+
delete(key: string): boolean;
|
|
2738
|
+
has(key: string): boolean;
|
|
2739
|
+
clear(): void;
|
|
2740
|
+
/** Memoize a loader. Returns cached value if fresh, else runs \`fn\` and stores. */
|
|
2741
|
+
wrap(key: string, fn: () => Promise<V>, ttlMsOverride?: number): Promise<V>;
|
|
2742
|
+
/** Force-refresh: invalidate then wrap. */
|
|
2743
|
+
refresh(key: string, fn: () => Promise<V>, ttlMsOverride?: number): Promise<V>;
|
|
2744
|
+
readonly size: number;
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
interface Entry<V> {
|
|
2748
|
+
value: V;
|
|
2749
|
+
expiresAt: number; // 0 = no expiry
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
export function createCache<V = unknown>(opts: CacheOptions = {}): Cache<V> {
|
|
2753
|
+
const ttl = opts.ttlMs ?? 60_000;
|
|
2754
|
+
const max = opts.max ?? 500;
|
|
2755
|
+
// Map preserves insertion order — re-insert on access for LRU behavior.
|
|
2756
|
+
const store = new Map<string, Entry<V>>();
|
|
2757
|
+
// De-dupe concurrent loads for the same key.
|
|
2758
|
+
const inflight = new Map<string, Promise<V>>();
|
|
2759
|
+
|
|
2760
|
+
const isFresh = (e: Entry<V>) => e.expiresAt === 0 || e.expiresAt > Date.now();
|
|
2761
|
+
|
|
2762
|
+
const evictIfNeeded = () => {
|
|
2763
|
+
if (max <= 0) return;
|
|
2764
|
+
while (store.size > max) {
|
|
2765
|
+
const oldest = store.keys().next().value;
|
|
2766
|
+
if (oldest === undefined) break;
|
|
2767
|
+
store.delete(oldest);
|
|
2768
|
+
}
|
|
2769
|
+
};
|
|
2770
|
+
|
|
2771
|
+
const cache: Cache<V> = {
|
|
2772
|
+
get(key) {
|
|
2773
|
+
const e = store.get(key);
|
|
2774
|
+
if (!e) return undefined;
|
|
2775
|
+
if (!isFresh(e)) {
|
|
2776
|
+
store.delete(key);
|
|
2777
|
+
return undefined;
|
|
2778
|
+
}
|
|
2779
|
+
// LRU touch
|
|
2780
|
+
store.delete(key);
|
|
2781
|
+
store.set(key, e);
|
|
2782
|
+
return e.value;
|
|
2783
|
+
},
|
|
2784
|
+
set(key, value, ttlMsOverride) {
|
|
2785
|
+
const t = ttlMsOverride ?? ttl;
|
|
2786
|
+
store.delete(key); // re-insert for LRU order
|
|
2787
|
+
store.set(key, { value, expiresAt: t > 0 ? Date.now() + t : 0 });
|
|
2788
|
+
evictIfNeeded();
|
|
2789
|
+
},
|
|
2790
|
+
delete(key) {
|
|
2791
|
+
return store.delete(key);
|
|
2792
|
+
},
|
|
2793
|
+
has(key) {
|
|
2794
|
+
const e = store.get(key);
|
|
2795
|
+
if (!e) return false;
|
|
2796
|
+
if (!isFresh(e)) {
|
|
2797
|
+
store.delete(key);
|
|
2798
|
+
return false;
|
|
2799
|
+
}
|
|
2800
|
+
return true;
|
|
2801
|
+
},
|
|
2802
|
+
clear() {
|
|
2803
|
+
store.clear();
|
|
2804
|
+
inflight.clear();
|
|
2805
|
+
},
|
|
2806
|
+
async wrap(key, fn, ttlMsOverride) {
|
|
2807
|
+
const cached = cache.get(key);
|
|
2808
|
+
if (cached !== undefined) return cached;
|
|
2809
|
+
const pending = inflight.get(key);
|
|
2810
|
+
if (pending) return pending;
|
|
2811
|
+
const p = (async () => {
|
|
2812
|
+
try {
|
|
2813
|
+
const v = await fn();
|
|
2814
|
+
cache.set(key, v, ttlMsOverride);
|
|
2815
|
+
return v;
|
|
2816
|
+
} finally {
|
|
2817
|
+
inflight.delete(key);
|
|
2818
|
+
}
|
|
2819
|
+
})();
|
|
2820
|
+
inflight.set(key, p);
|
|
2821
|
+
return p;
|
|
2822
|
+
},
|
|
2823
|
+
async refresh(key, fn, ttlMsOverride) {
|
|
2824
|
+
cache.delete(key);
|
|
2825
|
+
return cache.wrap(key, fn, ttlMsOverride);
|
|
2826
|
+
},
|
|
2827
|
+
get size() {
|
|
2828
|
+
return store.size;
|
|
2829
|
+
},
|
|
2830
|
+
};
|
|
2831
|
+
|
|
2832
|
+
return cache;
|
|
2833
|
+
}
|
|
2834
|
+
`,
|
|
2835
|
+
"_generators/helper/config.ts.tpl": `import * as vscode from 'vscode';
|
|
2836
|
+
|
|
2837
|
+
/**
|
|
2838
|
+
* Typed wrapper over \`vscode.workspace.getConfiguration('{{commandPrefix}}')\`.
|
|
2839
|
+
* Reads settings declared under \`contributes.configuration\` in package.json.
|
|
2840
|
+
*
|
|
2841
|
+
* Example package.json snippet:
|
|
2842
|
+
* "contributes": {
|
|
2843
|
+
* "configuration": {
|
|
2844
|
+
* "title": "{{displayName}}",
|
|
2845
|
+
* "properties": {
|
|
2846
|
+
* "{{commandPrefix}}.apiUrl": { "type": "string", "default": "" }
|
|
2847
|
+
* }
|
|
2848
|
+
* }
|
|
2849
|
+
* }
|
|
2850
|
+
*
|
|
2851
|
+
* Usage:
|
|
2852
|
+
* const url = config.get<string>('apiUrl');
|
|
2853
|
+
* await config.set('apiUrl', 'https://...');
|
|
2854
|
+
*/
|
|
2855
|
+
const SECTION = '{{commandPrefix}}';
|
|
2856
|
+
|
|
2857
|
+
export const config = {
|
|
2858
|
+
get<T>(key: string, fallback?: T): T {
|
|
2859
|
+
const v = vscode.workspace.getConfiguration(SECTION).get<T>(key);
|
|
2860
|
+
return (v === undefined ? (fallback as T) : v) as T;
|
|
2861
|
+
},
|
|
2862
|
+
set(key: string, value: unknown, target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global): Thenable<void> {
|
|
2863
|
+
return vscode.workspace.getConfiguration(SECTION).update(key, value, target);
|
|
2864
|
+
},
|
|
2865
|
+
onChange(listener: (key: string) => void): vscode.Disposable {
|
|
2866
|
+
return vscode.workspace.onDidChangeConfiguration((e) => {
|
|
2867
|
+
if (e.affectsConfiguration(SECTION)) listener(SECTION);
|
|
2868
|
+
});
|
|
2869
|
+
},
|
|
2870
|
+
};
|
|
2871
|
+
`,
|
|
2872
|
+
"_generators/helper/db.ts.tpl": `import * as vscode from 'vscode';
|
|
2873
|
+
import * as fs from 'fs';
|
|
2874
|
+
import * as path from 'path';
|
|
2875
|
+
|
|
2876
|
+
/**
|
|
2877
|
+
* Mini-ORM with pluggable providers. Ships with a filesystem JSON provider that
|
|
2878
|
+
* writes each entity to a single file under the extension's storage dir. Future
|
|
2879
|
+
* providers (sqlite, etc.) implement the same \`Provider\` interface — entity
|
|
2880
|
+
* definitions and call sites don't change.
|
|
2881
|
+
*
|
|
2882
|
+
* Usage:
|
|
2883
|
+
* const User = defineEntity<{ id: string; name: string }>('users', { primaryKey: 'id' });
|
|
2884
|
+
* const orm = createDb(context, { provider: 'storage' });
|
|
2885
|
+
* await orm(User).insert({ id: 'u1', name: 'Jairo' });
|
|
2886
|
+
* const u = await orm(User).findById('u1');
|
|
2887
|
+
*/
|
|
2888
|
+
|
|
2889
|
+
// ── Entity definition ────────────────────────────────────────────────────────
|
|
2890
|
+
|
|
2891
|
+
export interface EntityOptions<T> {
|
|
2892
|
+
/** Field used as the unique key. */
|
|
2893
|
+
primaryKey: keyof T & string;
|
|
2894
|
+
/** Optional indexes — speeds up \`findOne({ [k]: v })\` for these fields. */
|
|
2895
|
+
indexes?: (keyof T & string)[];
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2898
|
+
export interface Entity<T> {
|
|
2899
|
+
readonly name: string;
|
|
2900
|
+
readonly primaryKey: keyof T & string;
|
|
2901
|
+
readonly indexes: (keyof T & string)[];
|
|
2902
|
+
/** Phantom type carrier so \`orm(E)\` infers \`T\`. Never read. */
|
|
2903
|
+
readonly __t?: T;
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
export function defineEntity<T extends object>(
|
|
2907
|
+
name: string,
|
|
2908
|
+
opts: EntityOptions<T>,
|
|
2909
|
+
): Entity<T> {
|
|
2910
|
+
return { name, primaryKey: opts.primaryKey, indexes: opts.indexes ?? [] };
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
// ── Query types ──────────────────────────────────────────────────────────────
|
|
2914
|
+
|
|
2915
|
+
export type Where<T> = Partial<{ [K in keyof T]: T[K] | { in: T[K][] } | { neq: T[K] } }>;
|
|
2916
|
+
|
|
2917
|
+
export interface FindOptions<T> {
|
|
2918
|
+
where?: Where<T>;
|
|
2919
|
+
limit?: number;
|
|
2920
|
+
offset?: number;
|
|
2921
|
+
/** \`'field:asc'\` | \`'field:desc'\`. Default asc when only field given. */
|
|
2922
|
+
orderBy?: \`\${keyof T & string}:\${'asc' | 'desc'}\` | (keyof T & string);
|
|
2923
|
+
}
|
|
2924
|
+
|
|
2925
|
+
export interface Repository<T> {
|
|
2926
|
+
findById(id: T[keyof T]): Promise<T | null>;
|
|
2927
|
+
findOne(where: Where<T>): Promise<T | null>;
|
|
2928
|
+
findMany(opts?: FindOptions<T>): Promise<T[]>;
|
|
2929
|
+
count(opts?: { where?: Where<T> }): Promise<number>;
|
|
2930
|
+
insert(row: T): Promise<T>;
|
|
2931
|
+
upsert(row: T): Promise<T>;
|
|
2932
|
+
update(id: T[keyof T], patch: Partial<T>): Promise<T | null>;
|
|
2933
|
+
delete(id: T[keyof T]): Promise<boolean>;
|
|
2934
|
+
deleteMany(where: Where<T>): Promise<number>;
|
|
2935
|
+
clear(): Promise<void>;
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
// ── Provider interface (future-proof for sqlite/etc.) ────────────────────────
|
|
2939
|
+
|
|
2940
|
+
export interface Provider {
|
|
2941
|
+
load(entity: string): Promise<Record<string, unknown>[]>;
|
|
2942
|
+
save(entity: string, rows: Record<string, unknown>[]): Promise<void>;
|
|
2943
|
+
/** Atomic batch. Implementations may optimize. */
|
|
2944
|
+
transaction(work: (snapshot: Map<string, Record<string, unknown>[]>) => Promise<void> | void): Promise<void>;
|
|
2945
|
+
}
|
|
2946
|
+
|
|
2947
|
+
// ── Storage provider (filesystem JSON) ───────────────────────────────────────
|
|
2948
|
+
|
|
2949
|
+
class StorageProvider implements Provider {
|
|
2950
|
+
private cache = new Map<string, Record<string, unknown>[]>();
|
|
2951
|
+
|
|
2952
|
+
constructor(private readonly root: string) {
|
|
2953
|
+
fs.mkdirSync(root, { recursive: true });
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2956
|
+
private fileFor(entity: string): string {
|
|
2957
|
+
return path.join(this.root, \`\${entity}.json\`);
|
|
2958
|
+
}
|
|
2959
|
+
|
|
2960
|
+
async load(entity: string): Promise<Record<string, unknown>[]> {
|
|
2961
|
+
if (this.cache.has(entity)) return this.cache.get(entity)!;
|
|
2962
|
+
const f = this.fileFor(entity);
|
|
2963
|
+
if (!fs.existsSync(f)) {
|
|
2964
|
+
this.cache.set(entity, []);
|
|
2965
|
+
return [];
|
|
2966
|
+
}
|
|
2967
|
+
try {
|
|
2968
|
+
const rows = JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
2969
|
+
this.cache.set(entity, rows);
|
|
2970
|
+
return rows;
|
|
2971
|
+
} catch {
|
|
2972
|
+
this.cache.set(entity, []);
|
|
2973
|
+
return [];
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
async save(entity: string, rows: Record<string, unknown>[]): Promise<void> {
|
|
2978
|
+
this.cache.set(entity, rows);
|
|
2979
|
+
const f = this.fileFor(entity);
|
|
2980
|
+
const tmp = \`\${f}.tmp\`;
|
|
2981
|
+
fs.writeFileSync(tmp, JSON.stringify(rows));
|
|
2982
|
+
fs.renameSync(tmp, f); // atomic on same filesystem
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
async transaction(
|
|
2986
|
+
work: (snapshot: Map<string, Record<string, unknown>[]>) => Promise<void> | void,
|
|
2987
|
+
): Promise<void> {
|
|
2988
|
+
// Snapshot pre-tx state for rollback. Working copy is what \`work\` mutates.
|
|
2989
|
+
const backup = new Map<string, Record<string, unknown>[]>();
|
|
2990
|
+
for (const [k, v] of this.cache) backup.set(k, structuredClone(v));
|
|
2991
|
+
const working = new Map<string, Record<string, unknown>[]>();
|
|
2992
|
+
for (const [k, v] of this.cache) working.set(k, structuredClone(v));
|
|
2993
|
+
try {
|
|
2994
|
+
await work(working);
|
|
2995
|
+
for (const [entity, rows] of working) await this.save(entity, rows);
|
|
2996
|
+
} catch (err) {
|
|
2997
|
+
// Roll back in-memory cache to the pre-tx snapshot.
|
|
2998
|
+
for (const [k, v] of backup) this.cache.set(k, v);
|
|
2999
|
+
throw err;
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
|
|
3004
|
+
// ── Public DB type ───────────────────────────────────────────────────────────
|
|
3005
|
+
|
|
3006
|
+
export interface Db {
|
|
3007
|
+
<T extends object>(entity: Entity<T>): Repository<T>;
|
|
3008
|
+
transaction(work: (tx: Db) => Promise<void> | void): Promise<void>;
|
|
3009
|
+
/** Wipe a single entity. */
|
|
3010
|
+
drop(entity: Entity<unknown>): Promise<void>;
|
|
3011
|
+
/** Underlying provider — escape hatch for advanced use. */
|
|
3012
|
+
readonly provider: Provider;
|
|
3013
|
+
}
|
|
3014
|
+
|
|
3015
|
+
export interface CreateDbOptions {
|
|
3016
|
+
/** \`'storage'\` writes under \`context.storageUri/<subdir>/\`. \`'global'\` uses \`globalStorageUri\`. */
|
|
3017
|
+
provider: 'storage' | 'global';
|
|
3018
|
+
/** Override sub-directory under the chosen storage root. Default: \`db\`. */
|
|
3019
|
+
subdir?: string;
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
export function createDb(ctx: vscode.ExtensionContext, opts: CreateDbOptions): Db {
|
|
3023
|
+
// \`storageUri\` is only defined when a workspace/folder is open. \`globalStorageUri\`
|
|
3024
|
+
// is always available — fall back to it so the extension still activates with no
|
|
3025
|
+
// folder open (e.g. the Extension Development Host on first launch).
|
|
3026
|
+
const baseUri =
|
|
3027
|
+
opts.provider === 'global'
|
|
3028
|
+
? ctx.globalStorageUri
|
|
3029
|
+
: (ctx.storageUri ?? ctx.globalStorageUri);
|
|
3030
|
+
if (!baseUri) {
|
|
3031
|
+
throw new Error('createDb: no storage URI available from the extension context.');
|
|
3032
|
+
}
|
|
3033
|
+
const root = path.join(baseUri.fsPath, opts.subdir ?? 'db');
|
|
3034
|
+
const provider = new StorageProvider(root);
|
|
3035
|
+
ctx.subscriptions.push({ dispose: () => {} }); // future hook
|
|
3036
|
+
return makeDb(provider);
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
// ── Singleton accessor — \`import { db } from './db'; await db()(Users).insert(...)\` ──
|
|
3040
|
+
|
|
3041
|
+
let _db: Db | undefined;
|
|
3042
|
+
|
|
3043
|
+
/**
|
|
3044
|
+
* Default options used by \`initDb\` when called as a bootstrap hook (one-arg).
|
|
3045
|
+
* Override via the 2-arg form: \`initDb(context, { provider: 'global' })\`.
|
|
3046
|
+
*/
|
|
3047
|
+
export const dbOptions: CreateDbOptions = { provider: '{{provider}}' };
|
|
3048
|
+
|
|
3049
|
+
/**
|
|
3050
|
+
* Initialize the shared db. Call once on activate. Idempotent.
|
|
3051
|
+
*
|
|
3052
|
+
* As a bootstrap hook (recommended — \`bootstrap(registry, { onActivate: [initDb] })\`):
|
|
3053
|
+
* initDb(context)
|
|
3054
|
+
*
|
|
3055
|
+
* Direct call with custom options:
|
|
3056
|
+
* initDb(context, { provider: 'global' })
|
|
3057
|
+
*/
|
|
3058
|
+
export function initDb(ctx: vscode.ExtensionContext, opts?: CreateDbOptions): Db {
|
|
3059
|
+
if (_db) return _db;
|
|
3060
|
+
_db = createDb(ctx, opts ?? dbOptions);
|
|
3061
|
+
return _db;
|
|
3062
|
+
}
|
|
3063
|
+
|
|
3064
|
+
/** Access the shared db. Throws if \`initDb()\` wasn't called yet. */
|
|
3065
|
+
export function db(): Db {
|
|
3066
|
+
if (!_db) throw new Error('db not initialized — call initDb(context) on activate.');
|
|
3067
|
+
return _db;
|
|
3068
|
+
}
|
|
3069
|
+
|
|
3070
|
+
function makeDb(provider: Provider): Db {
|
|
3071
|
+
const repoFor = <T extends object>(entity: Entity<T>): Repository<T> => {
|
|
3072
|
+
const pk = entity.primaryKey;
|
|
3073
|
+
const load = () => provider.load(entity.name) as Promise<T[]>;
|
|
3074
|
+
const save = (rows: T[]) => provider.save(entity.name, rows as Record<string, unknown>[]);
|
|
3075
|
+
|
|
3076
|
+
return {
|
|
3077
|
+
async findById(id) {
|
|
3078
|
+
const rows = await load();
|
|
3079
|
+
return rows.find((r) => r[pk] === id) ?? null;
|
|
3080
|
+
},
|
|
3081
|
+
async findOne(where) {
|
|
3082
|
+
const rows = await load();
|
|
3083
|
+
return rows.find((r) => match(r, where)) ?? null;
|
|
3084
|
+
},
|
|
3085
|
+
async findMany(opts = {}) {
|
|
3086
|
+
let rows = await load();
|
|
3087
|
+
if (opts.where) rows = rows.filter((r) => match(r, opts.where!));
|
|
3088
|
+
if (opts.orderBy) {
|
|
3089
|
+
const [field, dir] = String(opts.orderBy).split(':');
|
|
3090
|
+
const sign = dir === 'desc' ? -1 : 1;
|
|
3091
|
+
rows = [...rows].sort((a, b) => compare(a[field as keyof T], b[field as keyof T]) * sign);
|
|
3092
|
+
}
|
|
3093
|
+
if (opts.offset) rows = rows.slice(opts.offset);
|
|
3094
|
+
if (opts.limit !== undefined) rows = rows.slice(0, opts.limit);
|
|
3095
|
+
return rows;
|
|
3096
|
+
},
|
|
3097
|
+
async count(opts = {}) {
|
|
3098
|
+
const rows = await load();
|
|
3099
|
+
return opts.where ? rows.filter((r) => match(r, opts.where!)).length : rows.length;
|
|
3100
|
+
},
|
|
3101
|
+
async insert(row) {
|
|
3102
|
+
const rows = await load();
|
|
3103
|
+
if (rows.some((r) => r[pk] === row[pk])) {
|
|
3104
|
+
throw new Error(\`\${entity.name}: duplicate \${pk}=\${String(row[pk])}\`);
|
|
3105
|
+
}
|
|
3106
|
+
rows.push(row);
|
|
3107
|
+
await save(rows);
|
|
3108
|
+
return row;
|
|
3109
|
+
},
|
|
3110
|
+
async upsert(row) {
|
|
3111
|
+
const rows = await load();
|
|
3112
|
+
const i = rows.findIndex((r) => r[pk] === row[pk]);
|
|
3113
|
+
if (i >= 0) rows[i] = row; else rows.push(row);
|
|
3114
|
+
await save(rows);
|
|
3115
|
+
return row;
|
|
3116
|
+
},
|
|
3117
|
+
async update(id, patch) {
|
|
3118
|
+
const rows = await load();
|
|
3119
|
+
const i = rows.findIndex((r) => r[pk] === id);
|
|
3120
|
+
if (i < 0) return null;
|
|
3121
|
+
rows[i] = { ...rows[i], ...patch };
|
|
3122
|
+
await save(rows);
|
|
3123
|
+
return rows[i];
|
|
3124
|
+
},
|
|
3125
|
+
async delete(id) {
|
|
3126
|
+
const rows = await load();
|
|
3127
|
+
const before = rows.length;
|
|
3128
|
+
const next = rows.filter((r) => r[pk] !== id);
|
|
3129
|
+
if (next.length === before) return false;
|
|
3130
|
+
await save(next);
|
|
3131
|
+
return true;
|
|
3132
|
+
},
|
|
3133
|
+
async deleteMany(where) {
|
|
3134
|
+
const rows = await load();
|
|
3135
|
+
const next = rows.filter((r) => !match(r, where));
|
|
3136
|
+
const removed = rows.length - next.length;
|
|
3137
|
+
if (removed > 0) await save(next);
|
|
3138
|
+
return removed;
|
|
3139
|
+
},
|
|
3140
|
+
async clear() {
|
|
3141
|
+
await save([]);
|
|
3142
|
+
},
|
|
3143
|
+
};
|
|
3144
|
+
};
|
|
3145
|
+
|
|
3146
|
+
const db: Db = Object.assign(repoFor as any, {
|
|
3147
|
+
provider,
|
|
3148
|
+
async drop(entity: Entity<unknown>) {
|
|
3149
|
+
await provider.save(entity.name, []);
|
|
3150
|
+
},
|
|
3151
|
+
async transaction(work: (tx: Db) => Promise<void> | void) {
|
|
3152
|
+
await provider.transaction(async (snapshot) => {
|
|
3153
|
+
// Build a tx-scoped Db that reads/writes the snapshot map.
|
|
3154
|
+
const txProvider: Provider = {
|
|
3155
|
+
async load(name) { return snapshot.get(name) ?? []; },
|
|
3156
|
+
async save(name, rows) { snapshot.set(name, rows); },
|
|
3157
|
+
async transaction() { throw new Error('Nested transactions are not supported'); },
|
|
3158
|
+
};
|
|
3159
|
+
await work(makeDb(txProvider));
|
|
3160
|
+
});
|
|
3161
|
+
},
|
|
3162
|
+
});
|
|
3163
|
+
|
|
3164
|
+
return db;
|
|
3165
|
+
}
|
|
3166
|
+
|
|
3167
|
+
// ── matcher ──────────────────────────────────────────────────────────────────
|
|
3168
|
+
|
|
3169
|
+
function match<T extends object>(row: T, where: Where<T>): boolean {
|
|
3170
|
+
for (const key of Object.keys(where) as (keyof T)[]) {
|
|
3171
|
+
const expected = where[key] as unknown;
|
|
3172
|
+
const actual = row[key];
|
|
3173
|
+
if (expected && typeof expected === 'object' && !Array.isArray(expected)) {
|
|
3174
|
+
if ('in' in expected) {
|
|
3175
|
+
if (!(expected as { in: unknown[] }).in.includes(actual)) return false;
|
|
3176
|
+
continue;
|
|
3177
|
+
}
|
|
3178
|
+
if ('neq' in expected) {
|
|
3179
|
+
if (actual === (expected as { neq: unknown }).neq) return false;
|
|
3180
|
+
continue;
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
if (actual !== expected) return false;
|
|
3184
|
+
}
|
|
3185
|
+
return true;
|
|
3186
|
+
}
|
|
3187
|
+
|
|
3188
|
+
function compare(a: unknown, b: unknown): number {
|
|
3189
|
+
if (a === b) return 0;
|
|
3190
|
+
if (a === null || a === undefined) return -1;
|
|
3191
|
+
if (b === null || b === undefined) return 1;
|
|
3192
|
+
return a < b ? -1 : 1;
|
|
3193
|
+
}
|
|
3194
|
+
`,
|
|
3195
|
+
"_generators/helper/notifications.ts.tpl": `import * as vscode from 'vscode';
|
|
3196
|
+
|
|
3197
|
+
/**
|
|
3198
|
+
* Concise wrappers over \`vscode.window.show*Message\`. Each accepts an optional
|
|
3199
|
+
* list of action labels and resolves to the selected label (or undefined).
|
|
3200
|
+
*
|
|
3201
|
+
* Usage:
|
|
3202
|
+
* notify.info('Saved');
|
|
3203
|
+
* const pick = await notify.warn('Discard?', 'Discard', 'Keep');
|
|
3204
|
+
* if (pick === 'Discard') ...
|
|
3205
|
+
*
|
|
3206
|
+
* For long-running tasks use \`withProgress\`:
|
|
3207
|
+
* await withProgress('Indexing…', async (report) => {
|
|
3208
|
+
* for (let i = 0; i <= 100; i += 10) {
|
|
3209
|
+
* report({ increment: 10, message: \`\${i}%\` });
|
|
3210
|
+
* await new Promise(r => setTimeout(r, 100));
|
|
3211
|
+
* }
|
|
3212
|
+
* });
|
|
3213
|
+
*/
|
|
3214
|
+
export const notify = {
|
|
3215
|
+
info(message: string, ...actions: string[]) {
|
|
3216
|
+
return vscode.window.showInformationMessage(message, ...actions);
|
|
3217
|
+
},
|
|
3218
|
+
warn(message: string, ...actions: string[]) {
|
|
3219
|
+
return vscode.window.showWarningMessage(message, ...actions);
|
|
3220
|
+
},
|
|
3221
|
+
error(message: string, ...actions: string[]) {
|
|
3222
|
+
return vscode.window.showErrorMessage(message, ...actions);
|
|
3223
|
+
},
|
|
3224
|
+
confirm(message: string, yesLabel = 'Yes', noLabel = 'No'): Thenable<boolean> {
|
|
3225
|
+
return vscode.window
|
|
3226
|
+
.showInformationMessage(message, { modal: true }, yesLabel, noLabel)
|
|
3227
|
+
.then((pick) => pick === yesLabel);
|
|
3228
|
+
},
|
|
3229
|
+
};
|
|
3230
|
+
|
|
3231
|
+
export function withProgress<T>(
|
|
3232
|
+
title: string,
|
|
3233
|
+
task: (report: (p: { message?: string; increment?: number }) => void) => Thenable<T> | T,
|
|
3234
|
+
location: vscode.ProgressLocation = vscode.ProgressLocation.Notification,
|
|
3235
|
+
): Thenable<T> {
|
|
3236
|
+
return vscode.window.withProgress({ location, title, cancellable: false }, (progress) =>
|
|
3237
|
+
Promise.resolve(task((p) => progress.report(p))),
|
|
3238
|
+
);
|
|
3239
|
+
}
|
|
3240
|
+
`,
|
|
3241
|
+
"_generators/helper/secrets.ts.tpl": `import * as vscode from 'vscode';
|
|
3242
|
+
|
|
3243
|
+
/**
|
|
3244
|
+
* Typed wrapper over \`context.secrets\` (SecretStorage backed by OS keychain).
|
|
3245
|
+
* Inject the extension context once on activate (bootstrap does this if you
|
|
3246
|
+
* import this module from your extension entry).
|
|
3247
|
+
*
|
|
3248
|
+
* Usage:
|
|
3249
|
+
* await secrets.set('githubToken', 'ghp_xxx');
|
|
3250
|
+
* const token = await secrets.get('githubToken');
|
|
3251
|
+
*/
|
|
3252
|
+
let _ctx: vscode.ExtensionContext | undefined;
|
|
3253
|
+
|
|
3254
|
+
export function initSecrets(ctx: vscode.ExtensionContext) {
|
|
3255
|
+
_ctx = ctx;
|
|
3256
|
+
}
|
|
3257
|
+
|
|
3258
|
+
function ctx(): vscode.ExtensionContext {
|
|
3259
|
+
if (!_ctx) throw new Error('Secrets helper not initialized — call initSecrets(context) on activate.');
|
|
3260
|
+
return _ctx;
|
|
3261
|
+
}
|
|
3262
|
+
|
|
3263
|
+
export const secrets = {
|
|
3264
|
+
get(key: string): Thenable<string | undefined> {
|
|
3265
|
+
return ctx().secrets.get(key);
|
|
3266
|
+
},
|
|
3267
|
+
set(key: string, value: string): Thenable<void> {
|
|
3268
|
+
return ctx().secrets.store(key, value);
|
|
3269
|
+
},
|
|
3270
|
+
delete(key: string): Thenable<void> {
|
|
3271
|
+
return ctx().secrets.delete(key);
|
|
3272
|
+
},
|
|
3273
|
+
onChange(listener: (key: string) => void): vscode.Disposable {
|
|
3274
|
+
return ctx().secrets.onDidChange((e) => listener(e.key));
|
|
3275
|
+
},
|
|
3276
|
+
};
|
|
3277
|
+
`,
|
|
3278
|
+
"_generators/helper/state.ts.tpl": `import * as vscode from 'vscode';
|
|
3279
|
+
|
|
3280
|
+
/**
|
|
3281
|
+
* Typed wrapper over \`context.{workspaceState, globalState}\`.
|
|
3282
|
+
* - workspace: scoped to the current workspace (per-project preferences)
|
|
3283
|
+
* - global: shared across all workspaces (user-wide settings, last-opened file)
|
|
3284
|
+
*
|
|
3285
|
+
* Usage:
|
|
3286
|
+
* await state.workspace.set('lastQuery', 'foo');
|
|
3287
|
+
* const q = state.workspace.get<string>('lastQuery');
|
|
3288
|
+
*/
|
|
3289
|
+
let _ctx: vscode.ExtensionContext | undefined;
|
|
3290
|
+
|
|
3291
|
+
export function initState(ctx: vscode.ExtensionContext) {
|
|
3292
|
+
_ctx = ctx;
|
|
3293
|
+
}
|
|
3294
|
+
|
|
3295
|
+
function ctx(): vscode.ExtensionContext {
|
|
3296
|
+
if (!_ctx) throw new Error('State helper not initialized — call initState(context) on activate.');
|
|
3297
|
+
return _ctx;
|
|
3298
|
+
}
|
|
3299
|
+
|
|
3300
|
+
function wrap(memento: () => vscode.Memento) {
|
|
3301
|
+
return {
|
|
3302
|
+
get<T>(key: string, fallback?: T): T | undefined {
|
|
3303
|
+
const v = memento().get<T>(key);
|
|
3304
|
+
return v === undefined ? fallback : v;
|
|
3305
|
+
},
|
|
3306
|
+
set(key: string, value: unknown): Thenable<void> {
|
|
3307
|
+
return memento().update(key, value);
|
|
3308
|
+
},
|
|
3309
|
+
delete(key: string): Thenable<void> {
|
|
3310
|
+
return memento().update(key, undefined);
|
|
3311
|
+
},
|
|
3312
|
+
keys(): readonly string[] {
|
|
3313
|
+
return memento().keys();
|
|
3314
|
+
},
|
|
3315
|
+
};
|
|
3316
|
+
}
|
|
3317
|
+
|
|
3318
|
+
export const state = {
|
|
3319
|
+
workspace: wrap(() => ctx().workspaceState),
|
|
3320
|
+
global: wrap(() => ctx().globalState),
|
|
3321
|
+
};
|
|
3322
|
+
`,
|
|
3323
|
+
"_generators/job/job.ts.tpl": `import { defineJob } from '../shared/vsceasy';
|
|
3324
|
+
|
|
3325
|
+
export default defineJob({
|
|
3326
|
+
title: '{{title}}',
|
|
3327
|
+
schedule: {{schedule}},{{minIntervalLine}}
|
|
3328
|
+
run: async (vscode, ctx) => {
|
|
3329
|
+
// TODO: implement {{name}} work
|
|
3330
|
+
console.log('[{{name}}] tick', new Date().toISOString());
|
|
3331
|
+
},
|
|
3332
|
+
});
|
|
3333
|
+
`,
|
|
3334
|
+
"_generators/menu/menu.ts.tpl": `import { defineMenu } from '../shared/vsceasy';
|
|
3335
|
+
|
|
3336
|
+
export default defineMenu({
|
|
3337
|
+
title: '{{title}}',
|
|
3338
|
+
icon: '{{icon}}',
|
|
3339
|
+
items: [
|
|
3340
|
+
{
|
|
3341
|
+
label: 'Panels',
|
|
3342
|
+
children: [
|
|
3343
|
+
// { label: 'Dashboard', panel: 'dashboard' },
|
|
3344
|
+
],
|
|
3345
|
+
},
|
|
3346
|
+
{
|
|
3347
|
+
label: 'Actions',
|
|
3348
|
+
children: [
|
|
3349
|
+
// { label: 'Hello', command: 'hello', icon: 'play' },
|
|
3350
|
+
// { label: 'Docs', url: 'https://example.com', icon: 'book' },
|
|
3351
|
+
],
|
|
3352
|
+
},
|
|
3353
|
+
],
|
|
3354
|
+
});
|
|
3355
|
+
`,
|
|
3356
|
+
"_generators/model/model.ts.tpl": `import { defineEntity, db } from '../helpers/db';
|
|
3357
|
+
|
|
3358
|
+
export interface {{Name}} {
|
|
3359
|
+
{{fieldLines}}
|
|
3360
|
+
}
|
|
3361
|
+
|
|
3362
|
+
export const {{Plural}} = defineEntity<{{Name}}>('{{collection}}', {
|
|
3363
|
+
primaryKey: '{{primaryKey}}',{{indexesLine}}
|
|
3364
|
+
});
|
|
3365
|
+
|
|
3366
|
+
/**
|
|
3367
|
+
* Typed repo accessor. Lazy — assumes \`initDb(context)\` ran on activate.
|
|
3368
|
+
*
|
|
3369
|
+
* import { {{Plural}}Repo } from '../models/{{Name}}';
|
|
3370
|
+
* await {{Plural}}Repo().insert({ ... });
|
|
3371
|
+
*/
|
|
3372
|
+
export const {{Plural}}Repo = () => db()({{Plural}});
|
|
3373
|
+
`,
|
|
3374
|
+
"_generators/panel/App.tsx.tpl": `import React from 'react';
|
|
3375
|
+
{{apiBlock}}
|
|
3376
|
+
export function App() {
|
|
3377
|
+
return (
|
|
3378
|
+
<div className="app">
|
|
3379
|
+
<h1>{{title}}</h1>
|
|
3380
|
+
<p>Edit <code>src/webview/panels/{{name}}/App.tsx</code> to start building.</p>
|
|
3381
|
+
</div>
|
|
3382
|
+
);
|
|
3383
|
+
}
|
|
3384
|
+
`,
|
|
3385
|
+
"_generators/panel/main.tsx.tpl": `import React from 'react';
|
|
3386
|
+
import { createRoot } from 'react-dom/client';
|
|
3387
|
+
import { App } from './App';
|
|
3388
|
+
import '../../styles.css';
|
|
3389
|
+
|
|
3390
|
+
createRoot(document.getElementById('root')!).render(<App />);
|
|
3391
|
+
`,
|
|
3392
|
+
"_generators/panel/panel.ts.tpl": `import { definePanel } from '../shared/vsceasy';
|
|
3393
|
+
{{apiImport}}
|
|
3394
|
+
export default definePanel{{apiGeneric}}({
|
|
3395
|
+
title: '{{title}}',{{rpcBlock}}
|
|
3396
|
+
});
|
|
3397
|
+
`,
|
|
3398
|
+
"_generators/panel/templates/dashboard/App.tsx.tpl": `import React, { useEffect, useState } from 'react';
|
|
3399
|
+
import { Button, Card } from '../../components';
|
|
3400
|
+
import '../../components/components.css';
|
|
3401
|
+
{{apiBlock}}
|
|
3402
|
+
interface Stats {
|
|
3403
|
+
total: number;
|
|
3404
|
+
active: number;
|
|
3405
|
+
updatedAt: string;
|
|
3406
|
+
}
|
|
3407
|
+
|
|
3408
|
+
export function App() {
|
|
3409
|
+
const [stats, setStats] = useState<Stats | null>(null);
|
|
3410
|
+
const [loading, setLoading] = useState(true);
|
|
3411
|
+
|
|
3412
|
+
async function refresh() {
|
|
3413
|
+
setLoading(true);
|
|
3414
|
+
try {
|
|
3415
|
+
{{statsCall}}
|
|
3416
|
+
} finally {
|
|
3417
|
+
setLoading(false);
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
useEffect(() => {
|
|
3422
|
+
void refresh();
|
|
3423
|
+
}, []);
|
|
3424
|
+
|
|
3425
|
+
return (
|
|
3426
|
+
<div className="app">
|
|
3427
|
+
<h1>{{title}}</h1>
|
|
3428
|
+
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(8rem, 1fr))', gap: '0.75rem' }}>
|
|
3429
|
+
<Card title="Total"><strong style={{ fontSize: '1.5rem' }}>{stats?.total ?? '—'}</strong></Card>
|
|
3430
|
+
<Card title="Active"><strong style={{ fontSize: '1.5rem' }}>{stats?.active ?? '—'}</strong></Card>
|
|
3431
|
+
<Card title="Updated"><span>{stats?.updatedAt ?? '—'}</span></Card>
|
|
3432
|
+
</div>
|
|
3433
|
+
<div style={{ marginTop: '0.75rem' }}>
|
|
3434
|
+
<Button variant="secondary" onClick={refresh} disabled={loading}>{loading ? 'Loading…' : 'Refresh'}</Button>
|
|
3435
|
+
</div>
|
|
3436
|
+
</div>
|
|
3437
|
+
);
|
|
3438
|
+
}
|
|
3439
|
+
`,
|
|
3440
|
+
"_generators/panel/templates/form/App.tsx.tpl": `import React, { useState } from 'react';
|
|
3441
|
+
import { Button, Input, Field, Card } from '../../components';
|
|
3442
|
+
import '../../components/components.css';
|
|
3443
|
+
{{apiBlock}}
|
|
3444
|
+
export function App() {
|
|
3445
|
+
const [name, setName] = useState('');
|
|
3446
|
+
const [email, setEmail] = useState('');
|
|
3447
|
+
const [status, setStatus] = useState<string | null>(null);
|
|
3448
|
+
const [busy, setBusy] = useState(false);
|
|
3449
|
+
|
|
3450
|
+
async function onSubmit(e: React.FormEvent) {
|
|
3451
|
+
e.preventDefault();
|
|
3452
|
+
setBusy(true);
|
|
3453
|
+
setStatus(null);
|
|
3454
|
+
try {
|
|
3455
|
+
{{submitCall}}
|
|
3456
|
+
setStatus('Saved.');
|
|
3457
|
+
setName('');
|
|
3458
|
+
setEmail('');
|
|
3459
|
+
} catch (err) {
|
|
3460
|
+
setStatus(err instanceof Error ? err.message : 'Failed.');
|
|
3461
|
+
} finally {
|
|
3462
|
+
setBusy(false);
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
return (
|
|
3467
|
+
<div className="app">
|
|
3468
|
+
<h1>{{title}}</h1>
|
|
3469
|
+
<Card title="New entry">
|
|
3470
|
+
<form onSubmit={onSubmit}>
|
|
3471
|
+
<Field label="Name" htmlFor="name">
|
|
3472
|
+
<Input id="name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Jane Doe" required />
|
|
3473
|
+
</Field>
|
|
3474
|
+
<Field label="Email" htmlFor="email">
|
|
3475
|
+
<Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="jane@acme.io" />
|
|
3476
|
+
</Field>
|
|
3477
|
+
<Button type="submit" disabled={busy}>{busy ? 'Saving…' : 'Save'}</Button>
|
|
3478
|
+
{status ? <span style={{ marginLeft: '0.75rem' }}>{status}</span> : null}
|
|
3479
|
+
</form>
|
|
3480
|
+
</Card>
|
|
3481
|
+
</div>
|
|
3482
|
+
);
|
|
3483
|
+
}
|
|
3484
|
+
`,
|
|
3485
|
+
"_generators/panel/templates/list/App.tsx.tpl": `import React, { useEffect, useState } from 'react';
|
|
3486
|
+
import { Button, List, Card } from '../../components';
|
|
3487
|
+
import '../../components/components.css';
|
|
3488
|
+
{{apiBlock}}
|
|
3489
|
+
interface Row {
|
|
3490
|
+
id: string;
|
|
3491
|
+
label: string;
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
export function App() {
|
|
3495
|
+
const [rows, setRows] = useState<Row[]>([]);
|
|
3496
|
+
const [loading, setLoading] = useState(true);
|
|
3497
|
+
|
|
3498
|
+
async function refresh() {
|
|
3499
|
+
setLoading(true);
|
|
3500
|
+
try {
|
|
3501
|
+
{{loadCall}}
|
|
3502
|
+
} finally {
|
|
3503
|
+
setLoading(false);
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3507
|
+
useEffect(() => {
|
|
3508
|
+
void refresh();
|
|
3509
|
+
}, []);
|
|
3510
|
+
|
|
3511
|
+
return (
|
|
3512
|
+
<div className="app">
|
|
3513
|
+
<h1>{{title}}</h1>
|
|
3514
|
+
<Card title="Items" actions={<Button variant="secondary" onClick={refresh} disabled={loading}>{loading ? 'Loading…' : 'Refresh'}</Button>}>
|
|
3515
|
+
<List
|
|
3516
|
+
items={rows}
|
|
3517
|
+
getKey={(r) => r.id}
|
|
3518
|
+
renderItem={(r) => r.label}
|
|
3519
|
+
empty="No items yet."
|
|
3520
|
+
/>
|
|
3521
|
+
</Card>
|
|
3522
|
+
</div>
|
|
3523
|
+
);
|
|
3524
|
+
}
|
|
3525
|
+
`,
|
|
3526
|
+
"_generators/publish/CHANGELOG.md.tpl": `# Change Log
|
|
3527
|
+
|
|
3528
|
+
All notable changes follow [Keep a Changelog](https://keepachangelog.com/).
|
|
3529
|
+
|
|
3530
|
+
## [Unreleased]
|
|
3531
|
+
|
|
3532
|
+
### Added
|
|
3533
|
+
- Initial release.
|
|
3534
|
+
`,
|
|
3535
|
+
"_generators/publish/README.md.tpl": `# {{displayName}}
|
|
3536
|
+
|
|
3537
|
+
{{description}}
|
|
3538
|
+
|
|
3539
|
+
## Features
|
|
3540
|
+
|
|
3541
|
+
- (describe what this extension does)
|
|
3542
|
+
|
|
3543
|
+
## Requirements
|
|
3544
|
+
|
|
3545
|
+
VS Code ≥ 1.80
|
|
3546
|
+
|
|
3547
|
+
## Extension Settings
|
|
3548
|
+
|
|
3549
|
+
(list your \`contributes.configuration\` entries)
|
|
3550
|
+
|
|
3551
|
+
## Known Issues
|
|
3552
|
+
|
|
3553
|
+
—
|
|
3554
|
+
|
|
3555
|
+
## Release Notes
|
|
3556
|
+
|
|
3557
|
+
See [CHANGELOG.md](./CHANGELOG.md).
|
|
3558
|
+
`,
|
|
3559
|
+
"_generators/statusBar/statusBar.ts.tpl": `import { defineStatusBar } from '../shared/vsceasy';
|
|
3560
|
+
|
|
3561
|
+
export default defineStatusBar({
|
|
3562
|
+
text: '{{text}}',{{iconLine}}{{tooltipLine}}
|
|
3563
|
+
alignment: '{{alignment}}',
|
|
3564
|
+
priority: {{priority}},{{commandLine}}{{panelLine}}
|
|
3565
|
+
});
|
|
3566
|
+
`,
|
|
3567
|
+
"_generators/subpanel/App.tsx.tpl": `import React from 'react';
|
|
3568
|
+
{{apiBlock}}
|
|
3569
|
+
export function App() {
|
|
3570
|
+
return (
|
|
3571
|
+
<div className="sidebar-view">
|
|
3572
|
+
<h2>{{title}}</h2>
|
|
3573
|
+
<p>Edit <code>src/webview/subpanels/{{name}}/App.tsx</code> to start building.</p>
|
|
3574
|
+
</div>
|
|
3575
|
+
);
|
|
3576
|
+
}
|
|
3577
|
+
`,
|
|
3578
|
+
"_generators/subpanel/main.tsx.tpl": `import React from 'react';
|
|
3579
|
+
import { createRoot } from 'react-dom/client';
|
|
3580
|
+
import { App } from './App';
|
|
3581
|
+
import '../../styles.css';
|
|
3582
|
+
|
|
3583
|
+
createRoot(document.getElementById('root')!).render(<App />);
|
|
3584
|
+
`,
|
|
3585
|
+
"_generators/subpanel/subpanel.ts.tpl": `import { defineSubpanel } from '../shared/vsceasy';
|
|
3586
|
+
{{apiImport}}
|
|
3587
|
+
export default defineSubpanel{{apiGeneric}}({
|
|
3588
|
+
title: '{{title}}',
|
|
3589
|
+
menu: '{{menu}}',{{rpcBlock}}
|
|
3590
|
+
});
|
|
3591
|
+
`,
|
|
3592
|
+
"_generators/test/_helpers.ts.tpl": `import { vi } from 'vitest';
|
|
3593
|
+
import { createRpcServer, createRpcClient } from '../shared/vsceasy/rpc';
|
|
3594
|
+
import type { Transport, Handlers, RpcClient } from '../shared/vsceasy/rpc';
|
|
3595
|
+
|
|
3596
|
+
/**
|
|
3597
|
+
* Minimal \`vscode\` namespace mock — covers the surface most extensions touch.
|
|
3598
|
+
* Extend per test by spreading or assigning new spies onto the returned object.
|
|
3599
|
+
*
|
|
3600
|
+
* const vscode = mockVscode();
|
|
3601
|
+
* vscode.window.showInformationMessage('hi');
|
|
3602
|
+
* expect(vscode.window.showInformationMessage).toHaveBeenCalledWith('hi');
|
|
3603
|
+
*/
|
|
3604
|
+
export function mockVscode() {
|
|
3605
|
+
const subscriptions: { dispose(): void }[] = [];
|
|
3606
|
+
return {
|
|
3607
|
+
window: {
|
|
3608
|
+
showInformationMessage: vi.fn(),
|
|
3609
|
+
showWarningMessage: vi.fn(),
|
|
3610
|
+
showErrorMessage: vi.fn(),
|
|
3611
|
+
showInputBox: vi.fn(),
|
|
3612
|
+
showQuickPick: vi.fn(),
|
|
3613
|
+
withProgress: vi.fn(async (_opts: any, task: any) => task({ report: vi.fn() })),
|
|
3614
|
+
createStatusBarItem: vi.fn(() => ({ show: vi.fn(), dispose: vi.fn(), text: '' })),
|
|
3615
|
+
createTreeView: vi.fn(() => ({ dispose: vi.fn() })),
|
|
3616
|
+
createWebviewPanel: vi.fn(),
|
|
3617
|
+
activeTextEditor: undefined as any,
|
|
3618
|
+
},
|
|
3619
|
+
workspace: {
|
|
3620
|
+
getConfiguration: vi.fn(() => ({ get: vi.fn(), update: vi.fn(async () => undefined) })),
|
|
3621
|
+
onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })),
|
|
3622
|
+
findFiles: vi.fn(async () => [] as any[]),
|
|
3623
|
+
workspaceFolders: [] as any[],
|
|
3624
|
+
},
|
|
3625
|
+
commands: {
|
|
3626
|
+
registerCommand: vi.fn((_id: string, _fn: any) => ({ dispose: vi.fn() })),
|
|
3627
|
+
executeCommand: vi.fn(async () => undefined),
|
|
3628
|
+
},
|
|
3629
|
+
env: {
|
|
3630
|
+
openExternal: vi.fn(async () => true),
|
|
3631
|
+
},
|
|
3632
|
+
Uri: { parse: (s: string) => ({ toString: () => s }), file: (p: string) => ({ fsPath: p, toString: () => p }) },
|
|
3633
|
+
ProgressLocation: { Notification: 15, SourceControl: 1, Window: 10 } as const,
|
|
3634
|
+
ConfigurationTarget: { Global: 1, Workspace: 2, WorkspaceFolder: 3 } as const,
|
|
3635
|
+
TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 } as const,
|
|
3636
|
+
StatusBarAlignment: { Left: 1, Right: 2 } as const,
|
|
3637
|
+
EventEmitter: class {
|
|
3638
|
+
private listeners: Array<(v: any) => void> = [];
|
|
3639
|
+
event = (l: (v: any) => void) => {
|
|
3640
|
+
this.listeners.push(l);
|
|
3641
|
+
return { dispose: () => (this.listeners = this.listeners.filter((x) => x !== l)) };
|
|
3642
|
+
};
|
|
3643
|
+
fire(v: any) {
|
|
3644
|
+
this.listeners.forEach((l) => l(v));
|
|
3645
|
+
}
|
|
3646
|
+
dispose() {
|
|
3647
|
+
this.listeners = [];
|
|
3648
|
+
}
|
|
3649
|
+
},
|
|
3650
|
+
Disposable: { from: (...d: any[]) => ({ dispose: () => d.forEach((x) => x.dispose?.()) }) },
|
|
3651
|
+
subscriptions,
|
|
3652
|
+
};
|
|
3653
|
+
}
|
|
3654
|
+
|
|
3655
|
+
export type VscodeMock = ReturnType<typeof mockVscode>;
|
|
3656
|
+
|
|
3657
|
+
/**
|
|
3658
|
+
* Minimal \`ExtensionContext\` mock — backed by in-memory Maps for state/secrets.
|
|
3659
|
+
*/
|
|
3660
|
+
export function mockContext() {
|
|
3661
|
+
const wm = new Map<string, unknown>();
|
|
3662
|
+
const gm = new Map<string, unknown>();
|
|
3663
|
+
const sm = new Map<string, string>();
|
|
3664
|
+
const memento = (m: Map<string, unknown>) => ({
|
|
3665
|
+
get: (k: string, d?: unknown) => (m.has(k) ? m.get(k) : d),
|
|
3666
|
+
update: async (k: string, v: unknown) => void (v === undefined ? m.delete(k) : m.set(k, v)),
|
|
3667
|
+
keys: () => Array.from(m.keys()),
|
|
3668
|
+
});
|
|
3669
|
+
return {
|
|
3670
|
+
subscriptions: [] as { dispose(): void }[],
|
|
3671
|
+
workspaceState: memento(wm),
|
|
3672
|
+
globalState: memento(gm),
|
|
3673
|
+
secrets: {
|
|
3674
|
+
get: async (k: string) => sm.get(k),
|
|
3675
|
+
store: async (k: string, v: string) => void sm.set(k, v),
|
|
3676
|
+
delete: async (k: string) => void sm.delete(k),
|
|
3677
|
+
onDidChange: () => ({ dispose: () => {} }),
|
|
3678
|
+
},
|
|
3679
|
+
extensionPath: '/mock',
|
|
3680
|
+
extensionUri: { fsPath: '/mock' },
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
|
|
3684
|
+
/**
|
|
3685
|
+
* Build an in-memory RPC pair (server + typed client). No webview involved.
|
|
3686
|
+
* Useful for testing your handlers end-to-end with the same types the UI sees.
|
|
3687
|
+
*
|
|
3688
|
+
* const handlers = { greet: (n: string) => \`hi \${n}\` };
|
|
3689
|
+
* const api = mockRpcPair<typeof handlers>(handlers);
|
|
3690
|
+
* expect(await api.greet('Jairo')).toBe('hi Jairo');
|
|
3691
|
+
*/
|
|
3692
|
+
export function mockRpcPair<H extends Handlers>(handlers: H): RpcClient<H> {
|
|
3693
|
+
const aListeners = new Set<(m: any) => void>();
|
|
3694
|
+
const bListeners = new Set<(m: any) => void>();
|
|
3695
|
+
const aToB: Transport = {
|
|
3696
|
+
send: (m) => bListeners.forEach((l) => l(m)),
|
|
3697
|
+
onMessage: (h) => {
|
|
3698
|
+
aListeners.add(h);
|
|
3699
|
+
return () => aListeners.delete(h);
|
|
3700
|
+
},
|
|
3701
|
+
};
|
|
3702
|
+
const bToA: Transport = {
|
|
3703
|
+
send: (m) => aListeners.forEach((l) => l(m)),
|
|
3704
|
+
onMessage: (h) => {
|
|
3705
|
+
bListeners.add(h);
|
|
3706
|
+
return () => bListeners.delete(h);
|
|
3707
|
+
},
|
|
3708
|
+
};
|
|
3709
|
+
createRpcServer<H>(bToA, handlers);
|
|
3710
|
+
return createRpcClient<H>(aToB, { callTimeoutMs: 0 });
|
|
3711
|
+
}
|
|
3712
|
+
`,
|
|
3713
|
+
"_generators/test/sample.test.ts.tpl": `import { describe, it, expect } from 'vitest';
|
|
3714
|
+
import { mockVscode, mockContext, mockRpcPair } from './_helpers';
|
|
3715
|
+
|
|
3716
|
+
describe('vscode mock', () => {
|
|
3717
|
+
it('captures notification calls', () => {
|
|
3718
|
+
const vscode = mockVscode();
|
|
3719
|
+
vscode.window.showInformationMessage('hello');
|
|
3720
|
+
expect(vscode.window.showInformationMessage).toHaveBeenCalledWith('hello');
|
|
3721
|
+
});
|
|
3722
|
+
|
|
3723
|
+
it('persists state via mock context', async () => {
|
|
3724
|
+
const ctx = mockContext();
|
|
3725
|
+
await ctx.workspaceState.update('key', 42);
|
|
3726
|
+
expect(ctx.workspaceState.get('key')).toBe(42);
|
|
3727
|
+
});
|
|
3728
|
+
});
|
|
3729
|
+
|
|
3730
|
+
describe('RPC pair', () => {
|
|
3731
|
+
it('round-trips a typed handler call', async () => {
|
|
3732
|
+
const handlers = {
|
|
3733
|
+
async greet(name: string) {
|
|
3734
|
+
return \`hi \${name}\`;
|
|
3735
|
+
},
|
|
3736
|
+
};
|
|
3737
|
+
const api = mockRpcPair<typeof handlers>(handlers);
|
|
3738
|
+
expect(await api.greet('Jairo')).toBe('hi Jairo');
|
|
3739
|
+
});
|
|
3740
|
+
|
|
3741
|
+
it('propagates handler errors', async () => {
|
|
3742
|
+
const handlers = {
|
|
3743
|
+
async boom() {
|
|
3744
|
+
throw new Error('nope');
|
|
3745
|
+
},
|
|
3746
|
+
};
|
|
3747
|
+
const api = mockRpcPair<typeof handlers>(handlers);
|
|
3748
|
+
await expect(api.boom()).rejects.toThrow('nope');
|
|
3749
|
+
});
|
|
3750
|
+
});
|
|
3751
|
+
`,
|
|
3752
|
+
"_generators/test/vitest.config.ts.tpl": `import { defineConfig } from 'vitest/config';
|
|
3753
|
+
import * as path from 'path';
|
|
3754
|
+
|
|
3755
|
+
export default defineConfig({
|
|
3756
|
+
resolve: {
|
|
3757
|
+
alias: {
|
|
3758
|
+
// \`vscode\` is only available inside the extension host. Tests stub it
|
|
3759
|
+
// with an empty module so importing any file that does \`import * as vscode\`
|
|
3760
|
+
// doesn't crash. Use \`mockVscode()\` from \`_helpers.ts\` for the surface
|
|
3761
|
+
// you actually need to assert against.
|
|
3762
|
+
vscode: path.resolve(__dirname, 'src/__tests__/__mocks__/vscode.ts'),
|
|
3763
|
+
},
|
|
3764
|
+
},
|
|
3765
|
+
test: {
|
|
3766
|
+
include: ['src/**/*.test.ts', 'src/**/*.test.tsx'],
|
|
3767
|
+
environment: 'node',
|
|
3768
|
+
globals: false,
|
|
3769
|
+
coverage: {
|
|
3770
|
+
include: ['src/**/*.{ts,tsx}'],
|
|
3771
|
+
exclude: ['src/extension/_registry.ts', 'src/webview/**', 'src/__tests__/**'],
|
|
3772
|
+
},
|
|
3773
|
+
},
|
|
3774
|
+
});
|
|
3775
|
+
`,
|
|
3776
|
+
"_generators/test/vscode.stub.ts.tpl": `/**
|
|
3777
|
+
* Auto-generated \`vscode\` module stub for vitest. Replaces the real \`vscode\`
|
|
3778
|
+
* import inside tests (the real module only exists in the extension host).
|
|
3779
|
+
*
|
|
3780
|
+
* The stub exposes the enums and class shapes the runtime touches at module
|
|
3781
|
+
* load time so files that do \`import * as vscode from 'vscode'\` don't crash
|
|
3782
|
+
* during test collection.
|
|
3783
|
+
*
|
|
3784
|
+
* To assert behaviour against \`vscode.window.X\`, use \`mockVscode()\` from
|
|
3785
|
+
* \`_helpers.ts\` and inject it into the code under test directly.
|
|
3786
|
+
*/
|
|
3787
|
+
export const TreeItemCollapsibleState = { None: 0, Collapsed: 1, Expanded: 2 } as const;
|
|
3788
|
+
export const StatusBarAlignment = { Left: 1, Right: 2 } as const;
|
|
3789
|
+
export const ConfigurationTarget = { Global: 1, Workspace: 2, WorkspaceFolder: 3 } as const;
|
|
3790
|
+
export const ProgressLocation = { SourceControl: 1, Window: 10, Notification: 15 } as const;
|
|
3791
|
+
export const ViewColumn = { Active: -1, Beside: -2, One: 1, Two: 2, Three: 3 } as const;
|
|
3792
|
+
export const ThemeIcon = class { constructor(public id: string) {} };
|
|
3793
|
+
export const ThemeColor = class { constructor(public id: string) {} };
|
|
3794
|
+
export const TreeItem = class { constructor(public label: string, public collapsibleState?: number) {} };
|
|
3795
|
+
export const MarkdownString = class {
|
|
3796
|
+
value = '';
|
|
3797
|
+
isTrusted = false;
|
|
3798
|
+
supportHtml = false;
|
|
3799
|
+
constructor(value = '') {
|
|
3800
|
+
this.value = value;
|
|
3801
|
+
}
|
|
3802
|
+
appendMarkdown(v: string) {
|
|
3803
|
+
this.value += v;
|
|
3804
|
+
return this;
|
|
3805
|
+
}
|
|
3806
|
+
};
|
|
3807
|
+
export const Uri = {
|
|
3808
|
+
parse: (s: string) => ({ toString: () => s, fsPath: s }),
|
|
3809
|
+
file: (p: string) => ({ fsPath: p, toString: () => p }),
|
|
3810
|
+
joinPath: (base: { fsPath: string }, ...segs: string[]) => ({
|
|
3811
|
+
fsPath: [base.fsPath, ...segs].join('/'),
|
|
3812
|
+
toString: () => [base.fsPath, ...segs].join('/'),
|
|
3813
|
+
}),
|
|
3814
|
+
};
|
|
3815
|
+
export const EventEmitter = class<T> {
|
|
3816
|
+
private listeners: Array<(v: T) => void> = [];
|
|
3817
|
+
event = (l: (v: T) => void) => {
|
|
3818
|
+
this.listeners.push(l);
|
|
3819
|
+
return { dispose: () => (this.listeners = this.listeners.filter((x) => x !== l)) };
|
|
3820
|
+
};
|
|
3821
|
+
fire(v: T) {
|
|
3822
|
+
this.listeners.forEach((l) => l(v));
|
|
3823
|
+
}
|
|
3824
|
+
dispose() {
|
|
3825
|
+
this.listeners = [];
|
|
3826
|
+
}
|
|
3827
|
+
};
|
|
3828
|
+
export const Disposable = {
|
|
3829
|
+
from: (...d: Array<{ dispose: () => void }>) => ({ dispose: () => d.forEach((x) => x.dispose()) }),
|
|
3830
|
+
};
|
|
3831
|
+
|
|
3832
|
+
const noop = () => {};
|
|
3833
|
+
const noopDisposable = { dispose: noop };
|
|
3834
|
+
const noopAsync = async () => undefined;
|
|
3835
|
+
const noopReg = () => noopDisposable;
|
|
3836
|
+
|
|
3837
|
+
export const window = {
|
|
3838
|
+
showInformationMessage: noopAsync,
|
|
3839
|
+
showWarningMessage: noopAsync,
|
|
3840
|
+
showErrorMessage: noopAsync,
|
|
3841
|
+
showInputBox: noopAsync,
|
|
3842
|
+
showQuickPick: noopAsync,
|
|
3843
|
+
withProgress: async (_o: unknown, task: (p: { report: () => void }) => unknown) =>
|
|
3844
|
+
task({ report: noop }),
|
|
3845
|
+
createStatusBarItem: () => ({ show: noop, hide: noop, dispose: noop, text: '' }),
|
|
3846
|
+
createTreeView: () => ({ dispose: noop }),
|
|
3847
|
+
createWebviewPanel: () => ({
|
|
3848
|
+
webview: { html: '', onDidReceiveMessage: noopReg, postMessage: noop, asWebviewUri: (u: unknown) => u },
|
|
3849
|
+
onDidDispose: noopReg,
|
|
3850
|
+
dispose: noop,
|
|
3851
|
+
}),
|
|
3852
|
+
registerWebviewViewProvider: noopReg,
|
|
3853
|
+
activeTextEditor: undefined as unknown,
|
|
3854
|
+
onDidChangeActiveTextEditor: noopReg,
|
|
3855
|
+
};
|
|
3856
|
+
|
|
3857
|
+
export const workspace = {
|
|
3858
|
+
getConfiguration: () => ({ get: noop, update: noopAsync, has: () => false, inspect: () => undefined }),
|
|
3859
|
+
onDidChangeConfiguration: noopReg,
|
|
3860
|
+
findFiles: async () => [] as unknown[],
|
|
3861
|
+
workspaceFolders: [] as unknown[],
|
|
3862
|
+
asRelativePath: (p: string) => p,
|
|
3863
|
+
};
|
|
3864
|
+
|
|
3865
|
+
export const commands = {
|
|
3866
|
+
registerCommand: noopReg,
|
|
3867
|
+
executeCommand: noopAsync,
|
|
3868
|
+
getCommands: async () => [] as string[],
|
|
3869
|
+
};
|
|
3870
|
+
|
|
3871
|
+
export const env = {
|
|
3872
|
+
openExternal: async () => true,
|
|
3873
|
+
clipboard: { writeText: noopAsync, readText: async () => '' },
|
|
3874
|
+
};
|
|
3875
|
+
|
|
3876
|
+
export const extensions = {
|
|
3877
|
+
getExtension: () => undefined,
|
|
3878
|
+
all: [] as unknown[],
|
|
3879
|
+
};
|
|
3880
|
+
|
|
3881
|
+
export const languages = {
|
|
3882
|
+
registerHoverProvider: noopReg,
|
|
3883
|
+
registerCompletionItemProvider: noopReg,
|
|
3884
|
+
};
|
|
3885
|
+
`,
|
|
3886
|
+
"_generators/treeView/treeView.ts.tpl": `import { defineTreeView, TreeNode } from '../shared/vsceasy';
|
|
3887
|
+
|
|
3888
|
+
export default defineTreeView({
|
|
3889
|
+
title: '{{title}}',
|
|
3890
|
+
menu: '{{menu}}',
|
|
3891
|
+
getChildren: async (parent, vscode, ctx) => {
|
|
3892
|
+
if (!parent) {
|
|
3893
|
+
return [
|
|
3894
|
+
{ label: 'Item 1', icon: 'file', tooltip: 'Replace with real data' },
|
|
3895
|
+
{ label: 'Group', icon: 'folder', collapsed: 'collapsed', children: [] },
|
|
3896
|
+
] as TreeNode[];
|
|
3897
|
+
}
|
|
3898
|
+
// Lazy children — return based on parent.id / parent.contextValue.
|
|
3899
|
+
return [];
|
|
3900
|
+
},
|
|
3901
|
+
});
|
|
3902
|
+
`,
|
|
3903
|
+
"react/.gitignore": `node_modules
|
|
3904
|
+
dist
|
|
3905
|
+
*.vsix
|
|
3906
|
+
.DS_Store
|
|
3907
|
+
`,
|
|
3908
|
+
"react/.vscode/launch.json": `{
|
|
3909
|
+
"version": "0.2.0",
|
|
3910
|
+
"configurations": [
|
|
3911
|
+
{
|
|
3912
|
+
"name": "Run Extension",
|
|
3913
|
+
"type": "extensionHost",
|
|
3914
|
+
"request": "launch",
|
|
3915
|
+
"args": ["--extensionDevelopmentPath=\${workspaceFolder}"],
|
|
3916
|
+
"outFiles": ["\${workspaceFolder}/dist/**/*.js"],
|
|
3917
|
+
"sourceMaps": true,
|
|
3918
|
+
"smartStep": true,
|
|
3919
|
+
"preLaunchTask": "vsceasy: build"
|
|
3920
|
+
},
|
|
3921
|
+
{
|
|
3922
|
+
"name": "Run Extension (watch / HMR)",
|
|
3923
|
+
"type": "extensionHost",
|
|
3924
|
+
"request": "launch",
|
|
3925
|
+
"args": ["--extensionDevelopmentPath=\${workspaceFolder}"],
|
|
3926
|
+
"outFiles": ["\${workspaceFolder}/dist/**/*.js"],
|
|
3927
|
+
"sourceMaps": true,
|
|
3928
|
+
"smartStep": true,
|
|
3929
|
+
"preLaunchTask": "vsceasy: dev"
|
|
3930
|
+
},
|
|
3931
|
+
{
|
|
3932
|
+
"name": "Attach to Extension Host",
|
|
3933
|
+
"type": "node",
|
|
3934
|
+
"request": "attach",
|
|
3935
|
+
"port": 9229,
|
|
3936
|
+
"skipFiles": ["<node_internals>/**"],
|
|
3937
|
+
"sourceMaps": true,
|
|
3938
|
+
"outFiles": ["\${workspaceFolder}/dist/**/*.js"]
|
|
3939
|
+
}
|
|
3940
|
+
]
|
|
3941
|
+
}
|
|
3942
|
+
`,
|
|
3943
|
+
"react/.vscode/tasks.json": `{
|
|
3944
|
+
"version": "2.0.0",
|
|
3945
|
+
"tasks": [
|
|
3946
|
+
{
|
|
3947
|
+
"label": "vsceasy: build",
|
|
3948
|
+
"type": "shell",
|
|
3949
|
+
"command": "bun run build",
|
|
3950
|
+
"presentation": { "reveal": "silent", "panel": "dedicated" },
|
|
3951
|
+
"problemMatcher": []
|
|
3952
|
+
},
|
|
3953
|
+
{
|
|
3954
|
+
"label": "vsceasy: dev",
|
|
3955
|
+
"type": "shell",
|
|
3956
|
+
"command": "bun run dev",
|
|
3957
|
+
"isBackground": true,
|
|
3958
|
+
"presentation": { "reveal": "always", "panel": "dedicated" },
|
|
3959
|
+
"group": { "kind": "build", "isDefault": true },
|
|
3960
|
+
"problemMatcher": {
|
|
3961
|
+
"owner": "esbuild-watch",
|
|
3962
|
+
"pattern": {
|
|
3963
|
+
"regexp": "^\\\\s*✘\\\\s*\\\\[ERROR\\\\]\\\\s+(.*)$",
|
|
3964
|
+
"message": 1
|
|
3965
|
+
},
|
|
3966
|
+
"background": {
|
|
3967
|
+
"activeOnStart": true,
|
|
3968
|
+
"beginsPattern": ".*build started.*|.*\\\\[watch\\\\] build started.*",
|
|
3969
|
+
"endsPattern": ".*built in.*|.*\\\\[watch\\\\] build finished.*"
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
}
|
|
3973
|
+
]
|
|
3974
|
+
}
|
|
3975
|
+
`,
|
|
3976
|
+
"react/.vscodeignore": `.vscode/**
|
|
3977
|
+
src/**
|
|
3978
|
+
scripts/**
|
|
3979
|
+
node_modules/**
|
|
3980
|
+
.gitignore
|
|
3981
|
+
tsconfig.json
|
|
3982
|
+
vite.config.ts
|
|
3983
|
+
*.map
|
|
3984
|
+
`,
|
|
3985
|
+
"react/README.md": `# {{displayName}}
|
|
3986
|
+
|
|
3987
|
+
Generated with [\`vsceasy\`](https://www.npmjs.com/package/vsceasy).
|
|
3988
|
+
|
|
3989
|
+
## Develop
|
|
3990
|
+
|
|
3991
|
+
Two ways to launch the Extension Development Host:
|
|
3992
|
+
|
|
3993
|
+
### Option A — one-shot launch (recommended for first run)
|
|
3994
|
+
|
|
3995
|
+
\`\`\`bash
|
|
3996
|
+
bun install
|
|
3997
|
+
bun run launch
|
|
3998
|
+
\`\`\`
|
|
3999
|
+
|
|
4000
|
+
Builds extension + webview once, then opens a new VS Code window with the extension loaded.
|
|
4001
|
+
Then in the dev window: Command Palette → **{{displayName}}: Open Dashboard**.
|
|
4002
|
+
|
|
4003
|
+
### Option B — watch mode + F5
|
|
4004
|
+
|
|
4005
|
+
\`\`\`bash
|
|
4006
|
+
bun install
|
|
4007
|
+
bun run dev # leave running — watches both extension + webview
|
|
4008
|
+
\`\`\`
|
|
4009
|
+
|
|
4010
|
+
Then in VS Code (this folder open):
|
|
4011
|
+
- Press <kbd>F5</kbd> → picks **Run Extension** launch config → opens Extension Development Host.
|
|
4012
|
+
- Re-press <kbd>Ctrl/Cmd+R</kbd> inside the dev host after code changes to reload.
|
|
4013
|
+
|
|
4014
|
+
> Note: \`bun run dev\` only builds — it does NOT launch VS Code. F5 (or \`bun run launch\`) does.
|
|
4015
|
+
|
|
4016
|
+
## Commands
|
|
4017
|
+
|
|
4018
|
+
- Command Palette → **{{displayName}}: Hello** → info toast
|
|
4019
|
+
- Command Palette → **{{displayName}}: Open Dashboard** → React webview
|
|
4020
|
+
|
|
4021
|
+
## Structure
|
|
4022
|
+
|
|
4023
|
+
- \`src/extension/extension.ts\` — entry, registers commands
|
|
4024
|
+
- \`src/extension/panels/DashboardPanel.ts\` — webview panel + RPC handlers
|
|
4025
|
+
- \`src/webview/App.tsx\` — React UI (typed RPC client)
|
|
4026
|
+
- \`src/shared/api.ts\` — RPC contract (types flow to both sides)
|
|
4027
|
+
- \`src/shared/rpc.ts\` — bridge implementation
|
|
4028
|
+
|
|
4029
|
+
## Package as \`.vsix\`
|
|
4030
|
+
|
|
4031
|
+
\`\`\`bash
|
|
4032
|
+
bun run build
|
|
4033
|
+
bun run package # → {{name}}-0.0.1.vsix
|
|
4034
|
+
\`\`\`
|
|
4035
|
+
`,
|
|
4036
|
+
"react/package.json": `{
|
|
4037
|
+
"name": "{{name}}",
|
|
4038
|
+
"displayName": "{{displayName}}",
|
|
4039
|
+
"description": "{{description}}",
|
|
4040
|
+
"version": "0.0.1",
|
|
4041
|
+
"publisher": "{{publisher}}",
|
|
4042
|
+
"engines": {
|
|
4043
|
+
"vscode": "^1.85.0"
|
|
4044
|
+
},
|
|
4045
|
+
"main": "./dist/extension.js",
|
|
4046
|
+
"contributes": {
|
|
4047
|
+
"commands": [
|
|
4048
|
+
{
|
|
4049
|
+
"command": "{{commandPrefix}}.hello",
|
|
4050
|
+
"title": "{{displayName}}: Hello"
|
|
4051
|
+
},
|
|
4052
|
+
{
|
|
4053
|
+
"command": "{{commandPrefix}}.openDashboard",
|
|
4054
|
+
"title": "{{displayName}}: Open Dashboard"
|
|
4055
|
+
}
|
|
4056
|
+
]
|
|
4057
|
+
},
|
|
4058
|
+
"activationEvents": [],
|
|
4059
|
+
"scripts": {
|
|
4060
|
+
"gen:scan": "bun scripts/gen.ts",
|
|
4061
|
+
"gen": "bun run gen:scan && bun run build:ext",
|
|
4062
|
+
"dev": "bun run gen:scan && concurrently -k -n ext,ui -c blue,magenta \\"bun run dev:ext\\" \\"bun run dev:ui\\"",
|
|
4063
|
+
"dev:ext": "esbuild src/extension/extension.ts --bundle --platform=node --target=node18 --external:vscode --outfile=dist/extension.js --watch --sourcemap",
|
|
4064
|
+
"dev:ui": "vite build --watch --mode development",
|
|
4065
|
+
"launch": "bun run build && code --extensionDevelopmentPath=$PWD --new-window",
|
|
4066
|
+
"build": "bun run gen:scan && bun run build:ext && bun run build:ui",
|
|
4067
|
+
"build:ext": "esbuild src/extension/extension.ts --bundle --platform=node --target=node18 --external:vscode --outfile=dist/extension.js --sourcemap",
|
|
4068
|
+
"build:ext:prod": "esbuild src/extension/extension.ts --bundle --platform=node --target=node18 --external:vscode --outfile=dist/extension.js --minify",
|
|
4069
|
+
"build:ui": "vite build",
|
|
4070
|
+
"build:prod": "bun run gen:scan && bun run build:ext:prod && bun run build:ui",
|
|
4071
|
+
"package": "bun run build:prod && vsce package --no-dependencies"
|
|
4072
|
+
},
|
|
4073
|
+
"devDependencies": {
|
|
4074
|
+
"@types/node": "^20.0.0",
|
|
4075
|
+
"@types/react": "^18.2.0",
|
|
4076
|
+
"@types/react-dom": "^18.2.0",
|
|
4077
|
+
"@types/vscode": "^1.85.0",
|
|
4078
|
+
"@vitejs/plugin-react": "^4.2.0",
|
|
4079
|
+
"@vscode/vsce": "^2.24.0",
|
|
4080
|
+
"concurrently": "^8.2.0",
|
|
4081
|
+
"esbuild": "^0.20.0",
|
|
4082
|
+
"typescript": "^5.3.0",
|
|
4083
|
+
"vite": "^5.0.0"
|
|
4084
|
+
},
|
|
4085
|
+
"dependencies": {
|
|
4086
|
+
"react": "^18.2.0",
|
|
4087
|
+
"react-dom": "^18.2.0"
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
`,
|
|
4091
|
+
"react/scripts/gen.ts": `#!/usr/bin/env bun
|
|
4092
|
+
// Scans src/panels, src/commands, and src/menus; writes src/extension/_registry.ts
|
|
4093
|
+
// and syncs package.json#contributes (commands, viewsContainers, views).
|
|
4094
|
+
|
|
4095
|
+
import * as fs from 'fs';
|
|
4096
|
+
import * as path from 'path';
|
|
4097
|
+
|
|
4098
|
+
const ROOT = process.cwd();
|
|
4099
|
+
const SRC = path.join(ROOT, 'src');
|
|
4100
|
+
const PANELS_DIR = path.join(SRC, 'panels');
|
|
4101
|
+
const COMMANDS_DIR = path.join(SRC, 'commands');
|
|
4102
|
+
const MENUS_DIR = path.join(SRC, 'menus');
|
|
4103
|
+
const STATUS_BARS_DIR = path.join(SRC, 'statusBars');
|
|
4104
|
+
const SUBPANELS_DIR = path.join(SRC, 'subpanels');
|
|
4105
|
+
const TREE_VIEWS_DIR = path.join(SRC, 'treeViews');
|
|
4106
|
+
const JOBS_DIR = path.join(SRC, 'jobs');
|
|
4107
|
+
const OUT = path.join(SRC, 'extension', '_registry.ts');
|
|
4108
|
+
const PKG_PATH = path.join(ROOT, 'package.json');
|
|
4109
|
+
|
|
4110
|
+
interface Discovered {
|
|
4111
|
+
id: string;
|
|
4112
|
+
importPath: string;
|
|
4113
|
+
}
|
|
4114
|
+
|
|
4115
|
+
function scan(dir: string, registryDir: string): Discovered[] {
|
|
4116
|
+
if (!fs.existsSync(dir)) return [];
|
|
4117
|
+
return fs
|
|
4118
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
4119
|
+
.filter((e) => e.isFile() && /\\.(ts|tsx)$/.test(e.name) && !e.name.startsWith('_'))
|
|
4120
|
+
.map((e) => {
|
|
4121
|
+
const id = e.name.replace(/\\.(ts|tsx)$/, '');
|
|
4122
|
+
const abs = path.join(dir, e.name);
|
|
4123
|
+
const rel = path.relative(registryDir, abs).replace(/\\\\/g, '/').replace(/\\.(ts|tsx)$/, '');
|
|
4124
|
+
const importPath = rel.startsWith('.') ? rel : \`./\${rel}\`;
|
|
4125
|
+
return { id, importPath };
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
4128
|
+
|
|
4129
|
+
function writeRegistry(
|
|
4130
|
+
panels: Discovered[],
|
|
4131
|
+
commands: Discovered[],
|
|
4132
|
+
menus: Discovered[],
|
|
4133
|
+
statusBars: Discovered[],
|
|
4134
|
+
subpanels: Discovered[],
|
|
4135
|
+
treeViews: Discovered[],
|
|
4136
|
+
jobs: Discovered[],
|
|
4137
|
+
prefix: string,
|
|
4138
|
+
) {
|
|
4139
|
+
const lines: string[] = [
|
|
4140
|
+
'// AUTO-GENERATED — do not edit. Run \`bun run gen\`.',
|
|
4141
|
+
\`import type { Registry } from '../shared/vsceasy';\`,
|
|
4142
|
+
...panels.map((p, i) => \`import panel\${i} from '\${p.importPath}';\`),
|
|
4143
|
+
...commands.map((c, i) => \`import command\${i} from '\${c.importPath}';\`),
|
|
4144
|
+
...menus.map((m, i) => \`import menu\${i} from '\${m.importPath}';\`),
|
|
4145
|
+
...statusBars.map((s, i) => \`import statusBar\${i} from '\${s.importPath}';\`),
|
|
4146
|
+
...subpanels.map((w, i) => \`import subpanel\${i} from '\${w.importPath}';\`),
|
|
4147
|
+
...treeViews.map((t, i) => \`import treeView\${i} from '\${t.importPath}';\`),
|
|
4148
|
+
...jobs.map((j, i) => \`import job\${i} from '\${j.importPath}';\`),
|
|
4149
|
+
'',
|
|
4150
|
+
'export const registry: Registry = {',
|
|
4151
|
+
\` prefix: \${JSON.stringify(prefix)},\`,
|
|
4152
|
+
' panels: {',
|
|
4153
|
+
...panels.map((p, i) => \` \${JSON.stringify(p.id)}: panel\${i},\`),
|
|
4154
|
+
' },',
|
|
4155
|
+
' commands: {',
|
|
4156
|
+
...commands.map((c, i) => \` \${JSON.stringify(c.id)}: command\${i},\`),
|
|
4157
|
+
' },',
|
|
4158
|
+
' menus: {',
|
|
4159
|
+
...menus.map((m, i) => \` \${JSON.stringify(m.id)}: menu\${i},\`),
|
|
4160
|
+
' },',
|
|
4161
|
+
' statusBars: {',
|
|
4162
|
+
...statusBars.map((s, i) => \` \${JSON.stringify(s.id)}: statusBar\${i},\`),
|
|
4163
|
+
' },',
|
|
4164
|
+
' subpanels: {',
|
|
4165
|
+
...subpanels.map((w, i) => \` \${JSON.stringify(w.id)}: subpanel\${i},\`),
|
|
4166
|
+
' },',
|
|
4167
|
+
' treeViews: {',
|
|
4168
|
+
...treeViews.map((t, i) => \` \${JSON.stringify(t.id)}: treeView\${i},\`),
|
|
4169
|
+
' },',
|
|
4170
|
+
' jobs: {',
|
|
4171
|
+
...jobs.map((j, i) => \` \${JSON.stringify(j.id)}: job\${i},\`),
|
|
4172
|
+
' },',
|
|
4173
|
+
'};',
|
|
4174
|
+
'',
|
|
4175
|
+
];
|
|
4176
|
+
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
|
4177
|
+
fs.writeFileSync(OUT, lines.join('\\n'));
|
|
4178
|
+
}
|
|
4179
|
+
|
|
4180
|
+
function syncPackageJson(
|
|
4181
|
+
panels: Discovered[],
|
|
4182
|
+
commands: Discovered[],
|
|
4183
|
+
menus: Discovered[],
|
|
4184
|
+
subpanels: Discovered[],
|
|
4185
|
+
treeViews: Discovered[],
|
|
4186
|
+
prefix: string,
|
|
4187
|
+
displayName: string,
|
|
4188
|
+
) {
|
|
4189
|
+
const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
|
|
4190
|
+
const contributes = (pkg.contributes ??= {});
|
|
4191
|
+
const cmds: Array<{ command: string; title: string; category?: string; enablement?: string }> = [];
|
|
4192
|
+
const keybindings: Array<{ command: string; key: string; mac?: string; when?: string }> = [];
|
|
4193
|
+
const palette: Array<{ command: string; when?: string }> = [];
|
|
4194
|
+
|
|
4195
|
+
for (const c of commands) {
|
|
4196
|
+
const def = loadDef(path.join(COMMANDS_DIR, c.id + '.ts')) ?? loadDef(path.join(COMMANDS_DIR, c.id + '.tsx'));
|
|
4197
|
+
const fullId = \`\${prefix}.\${def?.id ?? c.id}\`;
|
|
4198
|
+
cmds.push({
|
|
4199
|
+
command: fullId,
|
|
4200
|
+
title: def?.title ?? c.id,
|
|
4201
|
+
category: def?.category ?? displayName,
|
|
4202
|
+
...(def?.when ? { enablement: def.when } : {}),
|
|
4203
|
+
});
|
|
4204
|
+
if (def?.when) palette.push({ command: fullId, when: def.when });
|
|
4205
|
+
if (def?.keybindings) {
|
|
4206
|
+
for (const kb of def.keybindings) {
|
|
4207
|
+
keybindings.push({
|
|
4208
|
+
command: fullId,
|
|
4209
|
+
key: kb.key,
|
|
4210
|
+
...(kb.mac ? { mac: kb.mac } : {}),
|
|
4211
|
+
...(kb.when ? { when: kb.when } : {}),
|
|
4212
|
+
});
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
for (const p of panels) {
|
|
4217
|
+
const def = loadDef(path.join(PANELS_DIR, p.id + '.ts')) ?? loadDef(path.join(PANELS_DIR, p.id + '.tsx'));
|
|
4218
|
+
if (def?.command === false) continue;
|
|
4219
|
+
const opts = typeof def?.command === 'object' ? def!.command : {};
|
|
4220
|
+
cmds.push({
|
|
4221
|
+
command: \`\${prefix}.open\${capitalize(def?.id ?? p.id)}\`,
|
|
4222
|
+
title: (opts as any).title ?? \`Open \${def?.title ?? p.id}\`,
|
|
4223
|
+
category: (opts as any).category ?? displayName,
|
|
4224
|
+
});
|
|
4225
|
+
}
|
|
4226
|
+
|
|
4227
|
+
contributes.commands = cmds;
|
|
4228
|
+
if (keybindings.length) {
|
|
4229
|
+
contributes.keybindings = keybindings;
|
|
4230
|
+
} else {
|
|
4231
|
+
delete contributes.keybindings;
|
|
4232
|
+
}
|
|
4233
|
+
if (palette.length) {
|
|
4234
|
+
contributes.menus ??= {};
|
|
4235
|
+
contributes.menus.commandPalette = palette;
|
|
4236
|
+
} else if (contributes.menus) {
|
|
4237
|
+
delete contributes.menus.commandPalette;
|
|
4238
|
+
if (Object.keys(contributes.menus).length === 0) delete contributes.menus;
|
|
4239
|
+
}
|
|
4240
|
+
|
|
4241
|
+
// Menus → viewsContainers.activitybar + views.<containerId>
|
|
4242
|
+
const containers: Array<{ id: string; title: string; icon: string }> = [];
|
|
4243
|
+
const views: Record<string, Array<{ id: string; name: string; type?: 'webview' }>> = {};
|
|
4244
|
+
|
|
4245
|
+
// Index subpanels by menu they belong to
|
|
4246
|
+
const wvByMenu: Record<string, Array<{ id: string; name: string }>> = {};
|
|
4247
|
+
for (const w of subpanels) {
|
|
4248
|
+
const def = loadSubpanelDef(path.join(SUBPANELS_DIR, w.id + '.ts'))
|
|
4249
|
+
?? loadSubpanelDef(path.join(SUBPANELS_DIR, w.id + '.tsx'));
|
|
4250
|
+
if (!def?.menu) continue;
|
|
4251
|
+
const viewId = \`\${prefix}-\${def.menu}-\${def.id ?? w.id}\`;
|
|
4252
|
+
const name = def.title ?? w.id;
|
|
4253
|
+
(wvByMenu[def.menu] ??= []).push({ id: viewId, name });
|
|
4254
|
+
}
|
|
4255
|
+
|
|
4256
|
+
// Index tree views by their menu container
|
|
4257
|
+
const tvByMenu: Record<string, Array<{ id: string; name: string }>> = {};
|
|
4258
|
+
for (const t of treeViews) {
|
|
4259
|
+
const def = loadSubpanelDef(path.join(TREE_VIEWS_DIR, t.id + '.ts'))
|
|
4260
|
+
?? loadSubpanelDef(path.join(TREE_VIEWS_DIR, t.id + '.tsx'));
|
|
4261
|
+
if (!def?.menu) continue;
|
|
4262
|
+
const viewId = \`\${prefix}-\${def.menu}-\${def.id ?? t.id}\`;
|
|
4263
|
+
const name = def.title ?? t.id;
|
|
4264
|
+
(tvByMenu[def.menu] ??= []).push({ id: viewId, name });
|
|
4265
|
+
}
|
|
4266
|
+
|
|
4267
|
+
for (const m of menus) {
|
|
4268
|
+
const def = loadMenuDef(path.join(MENUS_DIR, m.id + '.ts')) ?? loadMenuDef(path.join(MENUS_DIR, m.id + '.tsx'));
|
|
4269
|
+
// VS Code requires viewsContainer / view ids to match /^[A-Za-z0-9_-]+$/ — no dots.
|
|
4270
|
+
const menuId = def?.id ?? m.id;
|
|
4271
|
+
const containerId = \`\${prefix}-\${menuId}\`;
|
|
4272
|
+
const title = def?.title ?? m.id;
|
|
4273
|
+
const icon = resolveIconForPkg(def?.icon);
|
|
4274
|
+
containers.push({ id: containerId, title, icon });
|
|
4275
|
+
const containerViews: Array<{ id: string; name: string; type?: 'webview' }> = [
|
|
4276
|
+
{ id: containerId, name: title }, // primary tree view
|
|
4277
|
+
];
|
|
4278
|
+
for (const v of wvByMenu[menuId] ?? []) {
|
|
4279
|
+
containerViews.push({ id: v.id, name: v.name, type: 'webview' });
|
|
4280
|
+
}
|
|
4281
|
+
for (const t of tvByMenu[menuId] ?? []) {
|
|
4282
|
+
containerViews.push({ id: t.id, name: t.name });
|
|
4283
|
+
}
|
|
4284
|
+
views[containerId] = containerViews;
|
|
4285
|
+
}
|
|
4286
|
+
if (containers.length) {
|
|
4287
|
+
(contributes.viewsContainers ??= {}).activitybar = containers;
|
|
4288
|
+
contributes.views = views;
|
|
4289
|
+
} else {
|
|
4290
|
+
delete contributes.viewsContainers?.activitybar;
|
|
4291
|
+
if (contributes.viewsContainers && Object.keys(contributes.viewsContainers).length === 0) {
|
|
4292
|
+
delete contributes.viewsContainers;
|
|
4293
|
+
}
|
|
4294
|
+
delete contributes.views;
|
|
4295
|
+
}
|
|
4296
|
+
|
|
4297
|
+
fs.writeFileSync(PKG_PATH, JSON.stringify(pkg, null, 2) + '\\n');
|
|
4298
|
+
}
|
|
4299
|
+
|
|
4300
|
+
function loadDef(file: string): {
|
|
4301
|
+
id?: string;
|
|
4302
|
+
title?: string;
|
|
4303
|
+
category?: string;
|
|
4304
|
+
command?: any;
|
|
4305
|
+
when?: string;
|
|
4306
|
+
keybindings?: Array<{ key: string; mac?: string; when?: string }>;
|
|
4307
|
+
} | null {
|
|
4308
|
+
if (!fs.existsSync(file)) return null;
|
|
4309
|
+
const src = fs.readFileSync(file, 'utf8');
|
|
4310
|
+
const grab = (key: string) => {
|
|
4311
|
+
const m = new RegExp(\`\\\\b\${key}\\\\s*:\\\\s*(['"\\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1\`).exec(src);
|
|
4312
|
+
return m?.[2];
|
|
4313
|
+
};
|
|
4314
|
+
const command =
|
|
4315
|
+
/\\bcommand\\s*:\\s*false\\b/.test(src) ? false :
|
|
4316
|
+
/\\bcommand\\s*:\\s*true\\b/.test(src) ? true :
|
|
4317
|
+
undefined;
|
|
4318
|
+
return {
|
|
4319
|
+
id: grab('id'),
|
|
4320
|
+
title: grab('title'),
|
|
4321
|
+
category: grab('category'),
|
|
4322
|
+
when: grab('when'),
|
|
4323
|
+
command,
|
|
4324
|
+
keybindings: parseKeybindings(src),
|
|
4325
|
+
};
|
|
4326
|
+
}
|
|
4327
|
+
|
|
4328
|
+
/** Extract keybinding(s) declared on a defineCommand call. Supports string, object, or array shorthand. */
|
|
4329
|
+
function parseKeybindings(src: string): Array<{ key: string; mac?: string; when?: string }> {
|
|
4330
|
+
// 1) Plain string: keybinding: 'ctrl+shift+h'
|
|
4331
|
+
const stringMatch = /\\bkeybinding\\s*:\\s*(['"\`])([^'"\`]+)\\1\\s*,?/.exec(src);
|
|
4332
|
+
if (stringMatch) return [{ key: stringMatch[2] }];
|
|
4333
|
+
|
|
4334
|
+
// 2) Single object: keybinding: { key: '...', mac?: '...', when?: '...' }
|
|
4335
|
+
const objMatch = /\\bkeybinding\\s*:\\s*\\{([^}]+)\\}/.exec(src);
|
|
4336
|
+
if (objMatch) {
|
|
4337
|
+
const obj = parseKbObject(objMatch[1]);
|
|
4338
|
+
return obj ? [obj] : [];
|
|
4339
|
+
}
|
|
4340
|
+
|
|
4341
|
+
// 3) Array shorthand: keybinding: [ 'ctrl+a', { key: 'ctrl+b', mac: 'cmd+b' } ]
|
|
4342
|
+
const arrMatch = /\\bkeybinding\\s*:\\s*\\[([\\s\\S]*?)\\]/.exec(src);
|
|
4343
|
+
if (arrMatch) {
|
|
4344
|
+
const inner = arrMatch[1];
|
|
4345
|
+
const out: Array<{ key: string; mac?: string; when?: string }> = [];
|
|
4346
|
+
const strRe = /(['"\`])([^'"\`]+)\\1/g;
|
|
4347
|
+
const objRe = /\\{([^}]+)\\}/g;
|
|
4348
|
+
let sm: RegExpExecArray | null;
|
|
4349
|
+
while ((sm = strRe.exec(inner))) out.push({ key: sm[2] });
|
|
4350
|
+
let om: RegExpExecArray | null;
|
|
4351
|
+
while ((om = objRe.exec(inner))) {
|
|
4352
|
+
const o = parseKbObject(om[1]);
|
|
4353
|
+
if (o) out.push(o);
|
|
4354
|
+
}
|
|
4355
|
+
return out;
|
|
4356
|
+
}
|
|
4357
|
+
return [];
|
|
4358
|
+
}
|
|
4359
|
+
|
|
4360
|
+
function parseKbObject(body: string): { key: string; mac?: string; when?: string } | null {
|
|
4361
|
+
const grab = (key: string) => {
|
|
4362
|
+
const m = new RegExp(\`\\\\b\${key}\\\\s*:\\\\s*(['"\\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1\`).exec(body);
|
|
4363
|
+
return m?.[2];
|
|
4364
|
+
};
|
|
4365
|
+
const key = grab('key');
|
|
4366
|
+
if (!key) return null;
|
|
4367
|
+
const mac = grab('mac');
|
|
4368
|
+
const when = grab('when');
|
|
4369
|
+
return { key, ...(mac ? { mac } : {}), ...(when ? { when } : {}) };
|
|
4370
|
+
}
|
|
4371
|
+
|
|
4372
|
+
interface MenuLoaded {
|
|
4373
|
+
id?: string;
|
|
4374
|
+
title?: string;
|
|
4375
|
+
icon?: string | { path?: string; light?: string; dark?: string };
|
|
4376
|
+
}
|
|
4377
|
+
|
|
4378
|
+
function loadMenuDef(file: string): MenuLoaded | null {
|
|
4379
|
+
if (!fs.existsSync(file)) return null;
|
|
4380
|
+
const src = fs.readFileSync(file, 'utf8');
|
|
4381
|
+
const grab = (key: string) => {
|
|
4382
|
+
const m = new RegExp(\`\\\\b\${key}\\\\s*:\\\\s*(['"\\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1\`).exec(src);
|
|
4383
|
+
return m?.[2];
|
|
4384
|
+
};
|
|
4385
|
+
let icon: MenuLoaded['icon'];
|
|
4386
|
+
const iconString = grab('icon');
|
|
4387
|
+
if (iconString !== undefined) {
|
|
4388
|
+
icon = iconString;
|
|
4389
|
+
} else {
|
|
4390
|
+
// Try object form: icon: { path: '...' } OR { light: '...', dark: '...' }
|
|
4391
|
+
const objMatch = /\\bicon\\s*:\\s*\\{([^}]+)\\}/.exec(src);
|
|
4392
|
+
if (objMatch) {
|
|
4393
|
+
const body = objMatch[1];
|
|
4394
|
+
const p = /\\bpath\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1/.exec(body);
|
|
4395
|
+
const l = /\\blight\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1/.exec(body);
|
|
4396
|
+
const d = /\\bdark\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1/.exec(body);
|
|
4397
|
+
if (p) icon = { path: p[2] };
|
|
4398
|
+
else if (l && d) icon = { light: l[2], dark: d[2] };
|
|
4399
|
+
}
|
|
4400
|
+
}
|
|
4401
|
+
return { id: grab('id'), title: grab('title'), icon };
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
interface SubpanelLoaded {
|
|
4405
|
+
id?: string;
|
|
4406
|
+
title?: string;
|
|
4407
|
+
menu?: string;
|
|
4408
|
+
}
|
|
4409
|
+
|
|
4410
|
+
function loadSubpanelDef(file: string): SubpanelLoaded | null {
|
|
4411
|
+
if (!fs.existsSync(file)) return null;
|
|
4412
|
+
const src = fs.readFileSync(file, 'utf8');
|
|
4413
|
+
const grab = (key: string) => {
|
|
4414
|
+
const m = new RegExp(\`\\\\b\${key}\\\\s*:\\\\s*(['"\\\`])((?:\\\\\\\\.|(?!\\\\1).)*)\\\\1\`).exec(src);
|
|
4415
|
+
return m?.[2];
|
|
4416
|
+
};
|
|
4417
|
+
return { id: grab('id'), title: grab('title'), menu: grab('menu') };
|
|
4418
|
+
}
|
|
4419
|
+
|
|
4420
|
+
function resolveIconForPkg(icon: MenuLoaded['icon']): string {
|
|
4421
|
+
// VS Code's viewsContainers.activitybar.icon must be a string (path to SVG or codicon ref via "$(name)").
|
|
4422
|
+
if (!icon) return '$(symbol-misc)';
|
|
4423
|
+
if (typeof icon === 'string') return \`$(\${icon})\`;
|
|
4424
|
+
if ('path' in icon && icon.path) return icon.path;
|
|
4425
|
+
if ('light' in icon && icon.light) return icon.light;
|
|
4426
|
+
return '$(symbol-misc)';
|
|
4427
|
+
}
|
|
4428
|
+
|
|
4429
|
+
function capitalize(s: string): string {
|
|
4430
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
4431
|
+
}
|
|
4432
|
+
|
|
4433
|
+
function ensurePanelHtml(panels: Discovered[]) {
|
|
4434
|
+
ensureBundleHtml(path.join(SRC, 'webview', 'panels'), panels);
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
function ensureSubpanelHtml(views: Discovered[]) {
|
|
4438
|
+
ensureBundleHtml(path.join(SRC, 'webview', 'subpanels'), views);
|
|
4439
|
+
}
|
|
4440
|
+
|
|
4441
|
+
function ensureBundleHtml(baseDir: string, entries: Discovered[]) {
|
|
4442
|
+
for (const e of entries) {
|
|
4443
|
+
const dir = path.join(baseDir, e.id);
|
|
4444
|
+
if (!fs.existsSync(dir)) continue;
|
|
4445
|
+
const htmlPath = path.join(dir, 'index.html');
|
|
4446
|
+
if (fs.existsSync(htmlPath)) continue;
|
|
4447
|
+
const mainCandidates = ['main.tsx', 'main.ts', 'index.tsx', 'index.ts'];
|
|
4448
|
+
const main = mainCandidates.find((f) => fs.existsSync(path.join(dir, f))) ?? 'main.tsx';
|
|
4449
|
+
fs.writeFileSync(
|
|
4450
|
+
htmlPath,
|
|
4451
|
+
\`<!DOCTYPE html>
|
|
4452
|
+
<html><head><meta charset="UTF-8" /></head>
|
|
4453
|
+
<body><div id="root"></div><script type="module" src="./\${main}"></script></body>
|
|
4454
|
+
</html>
|
|
4455
|
+
\`,
|
|
4456
|
+
);
|
|
4457
|
+
}
|
|
4458
|
+
}
|
|
4459
|
+
|
|
4460
|
+
function main() {
|
|
4461
|
+
const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
|
|
4462
|
+
const prefix: string =
|
|
4463
|
+
pkg.vsceasy?.commandPrefix ?? pkg.name.replace(/^@[^/]+\\//, '').replace(/[^a-zA-Z0-9]+/g, '');
|
|
4464
|
+
const displayName: string = pkg.displayName ?? pkg.name;
|
|
4465
|
+
|
|
4466
|
+
const registryDir = path.dirname(OUT);
|
|
4467
|
+
const panels = scan(PANELS_DIR, registryDir);
|
|
4468
|
+
const commands = scan(COMMANDS_DIR, registryDir);
|
|
4469
|
+
const menus = scan(MENUS_DIR, registryDir);
|
|
4470
|
+
const statusBars = scan(STATUS_BARS_DIR, registryDir);
|
|
4471
|
+
const subpanels = scan(SUBPANELS_DIR, registryDir);
|
|
4472
|
+
const treeViews = scan(TREE_VIEWS_DIR, registryDir);
|
|
4473
|
+
const jobs = scan(JOBS_DIR, registryDir);
|
|
4474
|
+
|
|
4475
|
+
writeRegistry(panels, commands, menus, statusBars, subpanels, treeViews, jobs, prefix);
|
|
4476
|
+
syncPackageJson(panels, commands, menus, subpanels, treeViews, prefix, displayName);
|
|
4477
|
+
ensurePanelHtml(panels);
|
|
4478
|
+
ensureSubpanelHtml(subpanels);
|
|
4479
|
+
|
|
4480
|
+
console.log(
|
|
4481
|
+
\`✓ vsceasy gen → \${panels.length} panel(s), \${commands.length} command(s), \${menus.length} menu(s), \${statusBars.length} statusBar(s), \${subpanels.length} subpanel(s), \${treeViews.length} treeView(s), \${jobs.length} job(s)\`,
|
|
4482
|
+
);
|
|
4483
|
+
}
|
|
4484
|
+
|
|
4485
|
+
main();
|
|
4486
|
+
`,
|
|
4487
|
+
"react/src/commands/hello.ts": `import { defineCommand } from '../shared/vsceasy';
|
|
4488
|
+
|
|
4489
|
+
export default defineCommand({
|
|
4490
|
+
title: 'Hello',
|
|
4491
|
+
run: (vscode) => vscode.window.showInformationMessage('Hello from {{displayName}}!'),
|
|
4492
|
+
});
|
|
4493
|
+
`,
|
|
4494
|
+
"react/src/extension/extension.ts": `import { bootstrap } from '../shared/vsceasy';
|
|
4495
|
+
import { registry } from './_registry';
|
|
4496
|
+
|
|
4497
|
+
export const activate = bootstrap(registry);
|
|
4498
|
+
export function deactivate() {}
|
|
4499
|
+
`,
|
|
4500
|
+
"react/src/panels/dashboard.ts": `import { definePanel } from '../shared/vsceasy';
|
|
4501
|
+
import type { DashboardApi } from '../shared/api';
|
|
4502
|
+
|
|
4503
|
+
export default definePanel<DashboardApi>({
|
|
4504
|
+
title: '{{displayName}} Dashboard',
|
|
4505
|
+
rpc: (vscode) => ({
|
|
4506
|
+
async getInfo() {
|
|
4507
|
+
return {
|
|
4508
|
+
workspace: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? null,
|
|
4509
|
+
vscodeVersion: vscode.version,
|
|
4510
|
+
};
|
|
4511
|
+
},
|
|
4512
|
+
async showMessage(text) {
|
|
4513
|
+
await vscode.window.showInformationMessage(text);
|
|
4514
|
+
},
|
|
4515
|
+
async listFiles(pattern) {
|
|
4516
|
+
const uris = await vscode.workspace.findFiles(pattern, '**/node_modules/**', 100);
|
|
4517
|
+
return uris.map((u) => vscode.workspace.asRelativePath(u));
|
|
4518
|
+
},
|
|
4519
|
+
}),
|
|
4520
|
+
});
|
|
4521
|
+
`,
|
|
4522
|
+
"react/src/shared/api.ts": `// RPC contracts — one interface per panel. Imported by both extension and webview.
|
|
4523
|
+
|
|
4524
|
+
export interface DashboardApi {
|
|
4525
|
+
getInfo(): Promise<{ workspace: string | null; vscodeVersion: string }>;
|
|
4526
|
+
showMessage(text: string): Promise<void>;
|
|
4527
|
+
listFiles(pattern: string): Promise<string[]>;
|
|
4528
|
+
}
|
|
4529
|
+
`,
|
|
4530
|
+
"react/src/shared/vsceasy/bootstrap.ts": `import * as vscode from 'vscode';
|
|
4531
|
+
import type { PanelDef, CommandDef, MenuDef, MenuItem, StatusBarDef, StatusBarMenuItem, SubpanelDef, TreeViewDef, TreeNode, JobDef, JobSchedule } from './define';
|
|
4532
|
+
import { createRpcServer, webviewTransport } from './rpc';
|
|
4533
|
+
|
|
4534
|
+
export interface Registry {
|
|
4535
|
+
panels: Record<string, PanelDef>;
|
|
4536
|
+
commands: Record<string, CommandDef>;
|
|
4537
|
+
menus?: Record<string, MenuDef>;
|
|
4538
|
+
statusBars?: Record<string, StatusBarDef>;
|
|
4539
|
+
subpanels?: Record<string, SubpanelDef>;
|
|
4540
|
+
treeViews?: Record<string, TreeViewDef>;
|
|
4541
|
+
jobs?: Record<string, JobDef>;
|
|
4542
|
+
/** Command prefix from package.json (e.g. "myExt"). */
|
|
4543
|
+
prefix: string;
|
|
4544
|
+
}
|
|
4545
|
+
|
|
4546
|
+
const openPanels = new Map<string, vscode.WebviewPanel>();
|
|
4547
|
+
|
|
4548
|
+
/**
|
|
4549
|
+
* Hook fired with the \`ExtensionContext\`. Use to wire \`initDb(context)\`,
|
|
4550
|
+
* \`initSecrets(context)\`, \`initState(context)\`, etc. Return value ignored;
|
|
4551
|
+
* may be sync or async (awaited in order).
|
|
4552
|
+
*
|
|
4553
|
+
* Signature uses \`...rest: any[]\` so any 1- or 2-arg helper (including ones
|
|
4554
|
+
* that declare a typed second parameter like \`initDb(ctx, opts?)\`) assigns
|
|
4555
|
+
* cleanly. The bootstrap runtime always passes the \`vscode\` namespace as the
|
|
4556
|
+
* second arg — helpers free to ignore it or declare their own type.
|
|
4557
|
+
*/
|
|
4558
|
+
export type ActivateHook = (
|
|
4559
|
+
context: vscode.ExtensionContext,
|
|
4560
|
+
...rest: any[]
|
|
4561
|
+
) => unknown | Promise<unknown>;
|
|
4562
|
+
|
|
4563
|
+
export interface BootstrapOptions {
|
|
4564
|
+
/**
|
|
4565
|
+
* Hooks that receive the \`ExtensionContext\` on activate, before any panel /
|
|
4566
|
+
* command / job is registered. Use to wire \`initDb(context)\`, \`initSecrets(context)\`,
|
|
4567
|
+
* \`initState(context)\`, telemetry, etc.
|
|
4568
|
+
*/
|
|
4569
|
+
onActivate?: ActivateHook[];
|
|
4570
|
+
/** Symmetric: runs in reverse on deactivate. */
|
|
4571
|
+
onDeactivate?: ActivateHook[];
|
|
4572
|
+
}
|
|
4573
|
+
|
|
4574
|
+
export function bootstrap(registry: Registry, options: BootstrapOptions = {}) {
|
|
4575
|
+
return async function activate(context: vscode.ExtensionContext) {
|
|
4576
|
+
for (const hook of options.onActivate ?? []) {
|
|
4577
|
+
await hook(context, vscode);
|
|
4578
|
+
}
|
|
4579
|
+
for (const [id, def] of Object.entries(registry.commands)) {
|
|
4580
|
+
const cmd = \`\${registry.prefix}.\${def.id ?? id}\`;
|
|
4581
|
+
context.subscriptions.push(
|
|
4582
|
+
vscode.commands.registerCommand(cmd, (...args) => def.run(vscode, context, ...args)),
|
|
4583
|
+
);
|
|
4584
|
+
}
|
|
4585
|
+
|
|
4586
|
+
for (const [id, def] of Object.entries(registry.panels)) {
|
|
4587
|
+
if (def.command !== false) {
|
|
4588
|
+
const cmd = \`\${registry.prefix}.open\${capitalize(def.id ?? id)}\`;
|
|
4589
|
+
context.subscriptions.push(
|
|
4590
|
+
vscode.commands.registerCommand(cmd, () => openPanel(context, registry.prefix, id, def)),
|
|
4591
|
+
);
|
|
4592
|
+
}
|
|
4593
|
+
}
|
|
4594
|
+
|
|
4595
|
+
if (registry.menus) {
|
|
4596
|
+
for (const [id, def] of Object.entries(registry.menus)) {
|
|
4597
|
+
registerMenu(context, registry, id, def);
|
|
4598
|
+
}
|
|
4599
|
+
}
|
|
4600
|
+
|
|
4601
|
+
if (registry.statusBars) {
|
|
4602
|
+
for (const [id, def] of Object.entries(registry.statusBars)) {
|
|
4603
|
+
registerStatusBar(context, registry, id, def);
|
|
4604
|
+
}
|
|
4605
|
+
}
|
|
4606
|
+
|
|
4607
|
+
if (registry.subpanels) {
|
|
4608
|
+
for (const [id, def] of Object.entries(registry.subpanels)) {
|
|
4609
|
+
registerSubpanel(context, registry, id, def);
|
|
4610
|
+
}
|
|
4611
|
+
}
|
|
4612
|
+
|
|
4613
|
+
if (registry.treeViews) {
|
|
4614
|
+
for (const [id, def] of Object.entries(registry.treeViews)) {
|
|
4615
|
+
registerTreeView(context, registry, id, def);
|
|
4616
|
+
}
|
|
4617
|
+
}
|
|
4618
|
+
|
|
4619
|
+
if (registry.jobs) {
|
|
4620
|
+
for (const [id, def] of Object.entries(registry.jobs)) {
|
|
4621
|
+
registerJob(context, registry, id, def);
|
|
4622
|
+
}
|
|
4623
|
+
}
|
|
4624
|
+
|
|
4625
|
+
// Register deactivate hooks as disposables — fire in reverse order on shutdown.
|
|
4626
|
+
for (const hook of [...(options.onDeactivate ?? [])].reverse()) {
|
|
4627
|
+
context.subscriptions.push({
|
|
4628
|
+
dispose: () => {
|
|
4629
|
+
void hook(context, vscode);
|
|
4630
|
+
},
|
|
4631
|
+
});
|
|
4632
|
+
}
|
|
4633
|
+
};
|
|
4634
|
+
}
|
|
4635
|
+
|
|
4636
|
+
// --- Jobs (recurring / event-triggered) ---
|
|
4637
|
+
|
|
4638
|
+
function registerJob(
|
|
4639
|
+
context: vscode.ExtensionContext,
|
|
4640
|
+
registry: Registry,
|
|
4641
|
+
id: string,
|
|
4642
|
+
def: JobDef,
|
|
4643
|
+
) {
|
|
4644
|
+
const jobId = def.id ?? id;
|
|
4645
|
+
const lastRunKey = \`vsceasy.job.\${jobId}.lastRun\`;
|
|
4646
|
+
|
|
4647
|
+
const exec = async (reason: string) => {
|
|
4648
|
+
if (def.minIntervalMs) {
|
|
4649
|
+
const last = (context.globalState.get<number>(lastRunKey) ?? 0);
|
|
4650
|
+
if (Date.now() - last < def.minIntervalMs) return;
|
|
4651
|
+
}
|
|
4652
|
+
try {
|
|
4653
|
+
await def.run(vscode, context);
|
|
4654
|
+
await context.globalState.update(lastRunKey, Date.now());
|
|
4655
|
+
} catch (err) {
|
|
4656
|
+
console.error(\`[vsceasy job:\${jobId}] (\${reason}) failed:\`, err);
|
|
4657
|
+
}
|
|
4658
|
+
};
|
|
4659
|
+
|
|
4660
|
+
const sched = def.schedule;
|
|
4661
|
+
if ('every' in sched) {
|
|
4662
|
+
const ms = parseDuration(sched.every);
|
|
4663
|
+
if (ms <= 0) throw new Error(\`Job "\${jobId}": invalid every=\${sched.every}\`);
|
|
4664
|
+
if (sched.runOnStart !== false) void exec('startup');
|
|
4665
|
+
const handle = setInterval(() => void exec('interval'), ms);
|
|
4666
|
+
context.subscriptions.push({ dispose: () => clearInterval(handle) });
|
|
4667
|
+
return;
|
|
4668
|
+
}
|
|
4669
|
+
if ('dailyAt' in sched) {
|
|
4670
|
+
const [hStr, mStr] = sched.dailyAt.split(':');
|
|
4671
|
+
const h = Number(hStr);
|
|
4672
|
+
const m = Number(mStr ?? '0');
|
|
4673
|
+
if (!Number.isFinite(h) || !Number.isFinite(m)) {
|
|
4674
|
+
throw new Error(\`Job "\${jobId}": invalid dailyAt=\${sched.dailyAt} (expected "HH:MM")\`);
|
|
4675
|
+
}
|
|
4676
|
+
let timer: NodeJS.Timeout | undefined;
|
|
4677
|
+
const scheduleNext = () => {
|
|
4678
|
+
const next = new Date();
|
|
4679
|
+
next.setHours(h, m, 0, 0);
|
|
4680
|
+
if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
|
|
4681
|
+
timer = setTimeout(async () => {
|
|
4682
|
+
await exec('dailyAt');
|
|
4683
|
+
scheduleNext();
|
|
4684
|
+
}, next.getTime() - Date.now());
|
|
4685
|
+
};
|
|
4686
|
+
scheduleNext();
|
|
4687
|
+
context.subscriptions.push({ dispose: () => { if (timer) clearTimeout(timer); } });
|
|
4688
|
+
return;
|
|
4689
|
+
}
|
|
4690
|
+
if ('on' in sched) {
|
|
4691
|
+
let sub: vscode.Disposable;
|
|
4692
|
+
switch (sched.on) {
|
|
4693
|
+
case 'startup':
|
|
4694
|
+
void exec('startup');
|
|
4695
|
+
return;
|
|
4696
|
+
case 'saveDocument':
|
|
4697
|
+
sub = vscode.workspace.onDidSaveTextDocument(() => void exec('saveDocument'));
|
|
4698
|
+
break;
|
|
4699
|
+
case 'openDocument':
|
|
4700
|
+
sub = vscode.workspace.onDidOpenTextDocument(() => void exec('openDocument'));
|
|
4701
|
+
break;
|
|
4702
|
+
case 'changeActiveEditor':
|
|
4703
|
+
sub = vscode.window.onDidChangeActiveTextEditor(() => void exec('changeActiveEditor'));
|
|
4704
|
+
break;
|
|
4705
|
+
case 'changeConfig':
|
|
4706
|
+
sub = vscode.workspace.onDidChangeConfiguration(() => void exec('changeConfig'));
|
|
4707
|
+
break;
|
|
4708
|
+
default:
|
|
4709
|
+
throw new Error(\`Job "\${jobId}": unknown on=\${(sched as { on: string }).on}\`);
|
|
4710
|
+
}
|
|
4711
|
+
context.subscriptions.push(sub);
|
|
4712
|
+
return;
|
|
4713
|
+
}
|
|
4714
|
+
if ('onFile' in sched) {
|
|
4715
|
+
const watcher = vscode.workspace.createFileSystemWatcher(sched.onFile);
|
|
4716
|
+
watcher.onDidChange(() => void exec('onFile:change'));
|
|
4717
|
+
watcher.onDidCreate(() => void exec('onFile:create'));
|
|
4718
|
+
watcher.onDidDelete(() => void exec('onFile:delete'));
|
|
4719
|
+
context.subscriptions.push(watcher);
|
|
4720
|
+
return;
|
|
4721
|
+
}
|
|
4722
|
+
}
|
|
4723
|
+
|
|
4724
|
+
const DURATION_RE = /^(\\d+)\\s*(ms|s|m|h|d)?$/;
|
|
4725
|
+
|
|
4726
|
+
function parseDuration(input: string | number): number {
|
|
4727
|
+
if (typeof input === 'number') return input;
|
|
4728
|
+
const m = DURATION_RE.exec(input.trim());
|
|
4729
|
+
if (!m) return -1;
|
|
4730
|
+
const n = Number(m[1]);
|
|
4731
|
+
switch (m[2] ?? 'ms') {
|
|
4732
|
+
case 'ms': return n;
|
|
4733
|
+
case 's': return n * 1000;
|
|
4734
|
+
case 'm': return n * 60_000;
|
|
4735
|
+
case 'h': return n * 3_600_000;
|
|
4736
|
+
case 'd': return n * 86_400_000;
|
|
4737
|
+
default: return -1;
|
|
4738
|
+
}
|
|
4739
|
+
}
|
|
4740
|
+
|
|
4741
|
+
// --- Tree Views (data-driven) ---
|
|
4742
|
+
|
|
4743
|
+
function registerTreeView(
|
|
4744
|
+
context: vscode.ExtensionContext,
|
|
4745
|
+
registry: Registry,
|
|
4746
|
+
id: string,
|
|
4747
|
+
def: TreeViewDef,
|
|
4748
|
+
) {
|
|
4749
|
+
const viewId = \`\${registry.prefix}-\${def.menu}-\${def.id ?? id}\`;
|
|
4750
|
+
const provider = new DataTreeProvider(def, context);
|
|
4751
|
+
const view = vscode.window.createTreeView(viewId, {
|
|
4752
|
+
treeDataProvider: provider,
|
|
4753
|
+
showCollapseAll: def.showCollapseAll !== false,
|
|
4754
|
+
});
|
|
4755
|
+
context.subscriptions.push(view);
|
|
4756
|
+
|
|
4757
|
+
const refreshCmd = \`\${registry.prefix}._tree.\${def.id ?? id}.refresh\`;
|
|
4758
|
+
context.subscriptions.push(
|
|
4759
|
+
vscode.commands.registerCommand(refreshCmd, () => provider.refresh()),
|
|
4760
|
+
);
|
|
4761
|
+
|
|
4762
|
+
const dispatchCmd = \`\${registry.prefix}._tree.\${def.id ?? id}.run\`;
|
|
4763
|
+
context.subscriptions.push(
|
|
4764
|
+
vscode.commands.registerCommand(dispatchCmd, async (node: TreeNode) => {
|
|
4765
|
+
if (node.run) return node.run(vscode, context);
|
|
4766
|
+
if (node.panel) {
|
|
4767
|
+
const p = registry.panels[node.panel];
|
|
4768
|
+
if (p) return openPanel(context, registry.prefix, node.panel, p);
|
|
4769
|
+
}
|
|
4770
|
+
if (node.command) {
|
|
4771
|
+
const c = registry.commands[node.command];
|
|
4772
|
+
if (c) return c.run(vscode, context);
|
|
4773
|
+
}
|
|
4774
|
+
}),
|
|
4775
|
+
);
|
|
4776
|
+
provider.setDispatchCommand(dispatchCmd);
|
|
4777
|
+
}
|
|
4778
|
+
|
|
4779
|
+
class DataTreeProvider implements vscode.TreeDataProvider<TreeNode> {
|
|
4780
|
+
private _onDidChange = new vscode.EventEmitter<TreeNode | undefined>();
|
|
4781
|
+
readonly onDidChangeTreeData = this._onDidChange.event;
|
|
4782
|
+
private dispatchCmd = '';
|
|
4783
|
+
|
|
4784
|
+
constructor(private readonly def: TreeViewDef, private readonly context: vscode.ExtensionContext) {}
|
|
4785
|
+
|
|
4786
|
+
setDispatchCommand(cmd: string) {
|
|
4787
|
+
this.dispatchCmd = cmd;
|
|
4788
|
+
}
|
|
4789
|
+
|
|
4790
|
+
refresh() {
|
|
4791
|
+
this._onDidChange.fire(undefined);
|
|
4792
|
+
}
|
|
4793
|
+
|
|
4794
|
+
getTreeItem(node: TreeNode): vscode.TreeItem {
|
|
4795
|
+
const hasChildren = !!node.children?.length;
|
|
4796
|
+
const state = hasChildren || node.children === undefined
|
|
4797
|
+
? node.collapsed === 'expanded'
|
|
4798
|
+
? vscode.TreeItemCollapsibleState.Expanded
|
|
4799
|
+
: vscode.TreeItemCollapsibleState.Collapsed
|
|
4800
|
+
: vscode.TreeItemCollapsibleState.None;
|
|
4801
|
+
const item = new vscode.TreeItem(node.label, state);
|
|
4802
|
+
item.id = node.id;
|
|
4803
|
+
item.tooltip = node.tooltip;
|
|
4804
|
+
item.description = node.description;
|
|
4805
|
+
item.contextValue = node.contextValue;
|
|
4806
|
+
item.iconPath = resolveIcon(this.context, node.icon);
|
|
4807
|
+
if (this.dispatchCmd && (node.run || node.panel || node.command)) {
|
|
4808
|
+
item.command = { command: this.dispatchCmd, title: node.label, arguments: [node] };
|
|
4809
|
+
}
|
|
4810
|
+
return item;
|
|
4811
|
+
}
|
|
4812
|
+
|
|
4813
|
+
async getChildren(node?: TreeNode): Promise<TreeNode[]> {
|
|
4814
|
+
if (node?.children) return node.children;
|
|
4815
|
+
return Promise.resolve(this.def.getChildren(node, vscode, this.context));
|
|
4816
|
+
}
|
|
4817
|
+
}
|
|
4818
|
+
|
|
4819
|
+
// --- Webview Views (sidebar inline) ---
|
|
4820
|
+
|
|
4821
|
+
function registerSubpanel(
|
|
4822
|
+
context: vscode.ExtensionContext,
|
|
4823
|
+
registry: Registry,
|
|
4824
|
+
id: string,
|
|
4825
|
+
def: SubpanelDef,
|
|
4826
|
+
) {
|
|
4827
|
+
// Must match the view id gen.ts writes into package.json#views.<container>.
|
|
4828
|
+
const viewId = \`\${registry.prefix}-\${def.menu}-\${def.id ?? id}\`;
|
|
4829
|
+
const provider: vscode.WebviewViewProvider = {
|
|
4830
|
+
resolveWebviewView(view) {
|
|
4831
|
+
view.webview.options = {
|
|
4832
|
+
enableScripts: true,
|
|
4833
|
+
localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'dist', 'webview')],
|
|
4834
|
+
};
|
|
4835
|
+
const ui = def.ui ?? \`subpanels/\${def.id ?? id}\`;
|
|
4836
|
+
view.webview.html = renderHtml(view.webview, context, ui, def.title);
|
|
4837
|
+
if (def.rpc) {
|
|
4838
|
+
const handlers = def.rpc(vscode, context);
|
|
4839
|
+
const server = createRpcServer(webviewTransport(view.webview), handlers);
|
|
4840
|
+
view.onDidDispose(() => server.dispose());
|
|
4841
|
+
}
|
|
4842
|
+
},
|
|
4843
|
+
};
|
|
4844
|
+
context.subscriptions.push(
|
|
4845
|
+
vscode.window.registerWebviewViewProvider(viewId, provider, {
|
|
4846
|
+
webviewOptions: { retainContextWhenHidden: def.retainContext ?? true },
|
|
4847
|
+
}),
|
|
4848
|
+
);
|
|
4849
|
+
}
|
|
4850
|
+
|
|
4851
|
+
// --- Status bar items ---
|
|
4852
|
+
|
|
4853
|
+
function registerStatusBar(
|
|
4854
|
+
context: vscode.ExtensionContext,
|
|
4855
|
+
registry: Registry,
|
|
4856
|
+
id: string,
|
|
4857
|
+
def: StatusBarDef,
|
|
4858
|
+
) {
|
|
4859
|
+
const alignment = def.alignment === 'right'
|
|
4860
|
+
? vscode.StatusBarAlignment.Right
|
|
4861
|
+
: vscode.StatusBarAlignment.Left;
|
|
4862
|
+
const item = vscode.window.createStatusBarItem(alignment, def.priority ?? 100);
|
|
4863
|
+
item.text = def.icon ? \`$(\${def.icon}) \${def.text}\` : def.text;
|
|
4864
|
+
|
|
4865
|
+
// Tooltip: markdown takes precedence over plain string
|
|
4866
|
+
if (def.tooltipMarkdown) {
|
|
4867
|
+
const md = new vscode.MarkdownString(def.tooltipMarkdown, true);
|
|
4868
|
+
md.supportHtml = true;
|
|
4869
|
+
md.isTrusted = true;
|
|
4870
|
+
item.tooltip = md;
|
|
4871
|
+
} else if (def.tooltip) {
|
|
4872
|
+
item.tooltip = def.tooltip;
|
|
4873
|
+
}
|
|
4874
|
+
|
|
4875
|
+
// Click behaviour priority: menu > panel > command
|
|
4876
|
+
if (def.menu && def.menu.length > 0) {
|
|
4877
|
+
const dispatchCmd = \`\${registry.prefix}._statusBar.\${id}.click\`;
|
|
4878
|
+
context.subscriptions.push(
|
|
4879
|
+
vscode.commands.registerCommand(dispatchCmd, () => openStatusBarMenu(context, registry, def.menu!)),
|
|
4880
|
+
);
|
|
4881
|
+
item.command = dispatchCmd;
|
|
4882
|
+
} else if (def.panel) {
|
|
4883
|
+
const panelDef = registry.panels[def.panel];
|
|
4884
|
+
if (panelDef) {
|
|
4885
|
+
const suffix = capitalize(panelDef.id ?? def.panel);
|
|
4886
|
+
item.command = \`\${registry.prefix}.open\${suffix}\`;
|
|
4887
|
+
} else {
|
|
4888
|
+
console.warn(\`[vsceasy] statusBar "\${id}" references unknown panel "\${def.panel}"\`);
|
|
4889
|
+
}
|
|
4890
|
+
} else if (def.command) {
|
|
4891
|
+
item.command = registry.commands[def.command]
|
|
4892
|
+
? \`\${registry.prefix}.\${registry.commands[def.command].id ?? def.command}\`
|
|
4893
|
+
: def.command;
|
|
4894
|
+
}
|
|
4895
|
+
|
|
4896
|
+
if (def.backgroundColor) {
|
|
4897
|
+
item.backgroundColor = new vscode.ThemeColor(def.backgroundColor);
|
|
4898
|
+
}
|
|
4899
|
+
item.show();
|
|
4900
|
+
context.subscriptions.push(item);
|
|
4901
|
+
}
|
|
4902
|
+
|
|
4903
|
+
async function openStatusBarMenu(
|
|
4904
|
+
context: vscode.ExtensionContext,
|
|
4905
|
+
registry: Registry,
|
|
4906
|
+
items: StatusBarMenuItem[],
|
|
4907
|
+
) {
|
|
4908
|
+
type QP = vscode.QuickPickItem & { __item: StatusBarMenuItem };
|
|
4909
|
+
const picks: QP[] = items.map((it) => ({
|
|
4910
|
+
label: it.label,
|
|
4911
|
+
description: it.description,
|
|
4912
|
+
detail: it.detail,
|
|
4913
|
+
__item: it,
|
|
4914
|
+
}));
|
|
4915
|
+
const selected = await vscode.window.showQuickPick(picks, { placeHolder: 'Choose action' });
|
|
4916
|
+
if (!selected) return;
|
|
4917
|
+
const it = selected.__item;
|
|
4918
|
+
if (it.url) {
|
|
4919
|
+
await vscode.env.openExternal(vscode.Uri.parse(it.url));
|
|
4920
|
+
return;
|
|
4921
|
+
}
|
|
4922
|
+
if (it.panel) {
|
|
4923
|
+
const panelDef = registry.panels[it.panel];
|
|
4924
|
+
if (panelDef) {
|
|
4925
|
+
const cmd = \`\${registry.prefix}.open\${capitalize(panelDef.id ?? it.panel)}\`;
|
|
4926
|
+
await vscode.commands.executeCommand(cmd);
|
|
4927
|
+
}
|
|
4928
|
+
return;
|
|
4929
|
+
}
|
|
4930
|
+
if (it.command) {
|
|
4931
|
+
const cmd = registry.commands[it.command]
|
|
4932
|
+
? \`\${registry.prefix}.\${registry.commands[it.command].id ?? it.command}\`
|
|
4933
|
+
: it.command;
|
|
4934
|
+
await vscode.commands.executeCommand(cmd);
|
|
4935
|
+
}
|
|
4936
|
+
}
|
|
4937
|
+
|
|
4938
|
+
// --- Menus ---
|
|
4939
|
+
|
|
4940
|
+
function registerMenu(
|
|
4941
|
+
context: vscode.ExtensionContext,
|
|
4942
|
+
registry: Registry,
|
|
4943
|
+
id: string,
|
|
4944
|
+
def: MenuDef,
|
|
4945
|
+
) {
|
|
4946
|
+
// Must match the id gen.ts writes into package.json#viewsContainers/views.
|
|
4947
|
+
// VS Code disallows '.' in view ids, so we use '-' as separator.
|
|
4948
|
+
const viewId = \`\${registry.prefix}-\${def.id ?? id}\`;
|
|
4949
|
+
const provider = new MenuTreeDataProvider(def.items, context);
|
|
4950
|
+
const view = vscode.window.createTreeView(viewId, {
|
|
4951
|
+
treeDataProvider: provider,
|
|
4952
|
+
showCollapseAll: true,
|
|
4953
|
+
});
|
|
4954
|
+
context.subscriptions.push(view);
|
|
4955
|
+
|
|
4956
|
+
// Single dispatch command per menu — passes the item through arguments[0] of contributes.commands.
|
|
4957
|
+
const dispatchCmd = \`\${registry.prefix}._menu.\${def.id ?? id}.run\`;
|
|
4958
|
+
context.subscriptions.push(
|
|
4959
|
+
vscode.commands.registerCommand(dispatchCmd, (item: MenuItem) =>
|
|
4960
|
+
dispatchMenuItem(context, registry, item),
|
|
4961
|
+
),
|
|
4962
|
+
);
|
|
4963
|
+
|
|
4964
|
+
provider.setDispatchCommand(dispatchCmd);
|
|
4965
|
+
}
|
|
4966
|
+
|
|
4967
|
+
async function dispatchMenuItem(
|
|
4968
|
+
context: vscode.ExtensionContext,
|
|
4969
|
+
registry: Registry,
|
|
4970
|
+
item: MenuItem,
|
|
4971
|
+
) {
|
|
4972
|
+
if (item.url) {
|
|
4973
|
+
await vscode.env.openExternal(vscode.Uri.parse(item.url));
|
|
4974
|
+
return;
|
|
4975
|
+
}
|
|
4976
|
+
if (item.panel) {
|
|
4977
|
+
const panel = registry.panels[item.panel];
|
|
4978
|
+
if (!panel) {
|
|
4979
|
+
vscode.window.showErrorMessage(\`Menu item references unknown panel: \${item.panel}\`);
|
|
4980
|
+
return;
|
|
4981
|
+
}
|
|
4982
|
+
openPanel(context, registry.prefix, item.panel, panel);
|
|
4983
|
+
return;
|
|
4984
|
+
}
|
|
4985
|
+
if (item.command) {
|
|
4986
|
+
const cmd = registry.commands[item.command];
|
|
4987
|
+
if (!cmd) {
|
|
4988
|
+
vscode.window.showErrorMessage(\`Menu item references unknown command: \${item.command}\`);
|
|
4989
|
+
return;
|
|
4990
|
+
}
|
|
4991
|
+
await cmd.run(vscode, context);
|
|
4992
|
+
return;
|
|
4993
|
+
}
|
|
4994
|
+
if (item.run) {
|
|
4995
|
+
await item.run(vscode, context);
|
|
4996
|
+
return;
|
|
4997
|
+
}
|
|
4998
|
+
}
|
|
4999
|
+
|
|
5000
|
+
class MenuTreeDataProvider implements vscode.TreeDataProvider<MenuItem> {
|
|
5001
|
+
private _onDidChange = new vscode.EventEmitter<MenuItem | undefined>();
|
|
5002
|
+
readonly onDidChangeTreeData = this._onDidChange.event;
|
|
5003
|
+
private dispatchCmd = '';
|
|
5004
|
+
|
|
5005
|
+
constructor(private readonly items: MenuItem[], private readonly context: vscode.ExtensionContext) {}
|
|
5006
|
+
|
|
5007
|
+
setDispatchCommand(cmd: string) {
|
|
5008
|
+
this.dispatchCmd = cmd;
|
|
5009
|
+
this._onDidChange.fire(undefined);
|
|
5010
|
+
}
|
|
5011
|
+
|
|
5012
|
+
getTreeItem(item: MenuItem): vscode.TreeItem {
|
|
5013
|
+
const hasChildren = !!item.children?.length;
|
|
5014
|
+
const collapsibleState = hasChildren
|
|
5015
|
+
? item.collapsed === 'collapsed'
|
|
5016
|
+
? vscode.TreeItemCollapsibleState.Collapsed
|
|
5017
|
+
: vscode.TreeItemCollapsibleState.Expanded
|
|
5018
|
+
: vscode.TreeItemCollapsibleState.None;
|
|
5019
|
+
const node = new vscode.TreeItem(item.label, collapsibleState);
|
|
5020
|
+
node.tooltip = item.description ?? item.label;
|
|
5021
|
+
node.description = item.description;
|
|
5022
|
+
node.iconPath = resolveIcon(this.context, item.icon);
|
|
5023
|
+
if (!hasChildren && this.dispatchCmd) {
|
|
5024
|
+
node.command = {
|
|
5025
|
+
command: this.dispatchCmd,
|
|
5026
|
+
title: item.label,
|
|
5027
|
+
arguments: [item],
|
|
5028
|
+
};
|
|
5029
|
+
}
|
|
5030
|
+
return node;
|
|
5031
|
+
}
|
|
5032
|
+
|
|
5033
|
+
getChildren(item?: MenuItem): MenuItem[] {
|
|
5034
|
+
if (!item) return this.items;
|
|
5035
|
+
return item.children ?? [];
|
|
5036
|
+
}
|
|
5037
|
+
}
|
|
5038
|
+
|
|
5039
|
+
function resolveIcon(
|
|
5040
|
+
context: vscode.ExtensionContext,
|
|
5041
|
+
icon: MenuItem['icon'],
|
|
5042
|
+
): vscode.TreeItem['iconPath'] {
|
|
5043
|
+
if (!icon) return undefined;
|
|
5044
|
+
if (typeof icon === 'string') return new vscode.ThemeIcon(icon);
|
|
5045
|
+
const path = require('path') as typeof import('path');
|
|
5046
|
+
const toUri = (p: string) =>
|
|
5047
|
+
path.isAbsolute(p) ? vscode.Uri.file(p) : vscode.Uri.joinPath(context.extensionUri, p);
|
|
5048
|
+
if ('path' in icon) return toUri(icon.path);
|
|
5049
|
+
return { light: toUri(icon.light), dark: toUri(icon.dark) };
|
|
5050
|
+
}
|
|
5051
|
+
|
|
5052
|
+
function openPanel(context: vscode.ExtensionContext, prefix: string, id: string, def: PanelDef) {
|
|
5053
|
+
const key = \`\${prefix}.\${def.id ?? id}\`;
|
|
5054
|
+
const existing = openPanels.get(key);
|
|
5055
|
+
const column = resolveColumn(def.column);
|
|
5056
|
+
if (existing) {
|
|
5057
|
+
existing.reveal(column);
|
|
5058
|
+
return existing;
|
|
5059
|
+
}
|
|
5060
|
+
|
|
5061
|
+
const panel = vscode.window.createWebviewPanel(
|
|
5062
|
+
key,
|
|
5063
|
+
def.title,
|
|
5064
|
+
column,
|
|
5065
|
+
{
|
|
5066
|
+
enableScripts: true,
|
|
5067
|
+
retainContextWhenHidden: def.retainContext ?? true,
|
|
5068
|
+
localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'dist', 'webview')],
|
|
5069
|
+
},
|
|
5070
|
+
);
|
|
5071
|
+
|
|
5072
|
+
const ui = def.ui ?? \`panels/\${def.id ?? id}\`;
|
|
5073
|
+
panel.webview.html = renderHtml(panel.webview, context, ui, def.title);
|
|
5074
|
+
|
|
5075
|
+
if (def.rpc) {
|
|
5076
|
+
const handlers = def.rpc(vscode, context);
|
|
5077
|
+
const server = createRpcServer(webviewTransport(panel.webview), handlers);
|
|
5078
|
+
panel.onDidDispose(() => server.dispose());
|
|
5079
|
+
}
|
|
5080
|
+
|
|
5081
|
+
openPanels.set(key, panel);
|
|
5082
|
+
panel.onDidDispose(() => openPanels.delete(key));
|
|
5083
|
+
return panel;
|
|
5084
|
+
}
|
|
5085
|
+
|
|
5086
|
+
interface ViteManifestEntry {
|
|
5087
|
+
file: string;
|
|
5088
|
+
css?: string[];
|
|
5089
|
+
assets?: string[];
|
|
5090
|
+
imports?: string[];
|
|
5091
|
+
}
|
|
5092
|
+
type ViteManifest = Record<string, ViteManifestEntry>;
|
|
5093
|
+
|
|
5094
|
+
let cachedManifest: { mtime: number; data: ViteManifest } | null = null;
|
|
5095
|
+
|
|
5096
|
+
function loadManifest(extensionUri: vscode.Uri): ViteManifest | null {
|
|
5097
|
+
const fs = require('fs') as typeof import('fs');
|
|
5098
|
+
const path = require('path') as typeof import('path');
|
|
5099
|
+
// Vite manifest can land at either \`manifest.json\` (new) or \`.vite/manifest.json\` (default).
|
|
5100
|
+
const webviewRoot = vscode.Uri.joinPath(extensionUri, 'dist', 'webview').fsPath;
|
|
5101
|
+
for (const rel of ['manifest.json', '.vite/manifest.json']) {
|
|
5102
|
+
const p = path.join(webviewRoot, rel);
|
|
5103
|
+
if (!fs.existsSync(p)) continue;
|
|
5104
|
+
const mtime = fs.statSync(p).mtimeMs;
|
|
5105
|
+
if (cachedManifest?.mtime === mtime) return cachedManifest.data;
|
|
5106
|
+
cachedManifest = { mtime, data: JSON.parse(fs.readFileSync(p, 'utf8')) };
|
|
5107
|
+
return cachedManifest.data;
|
|
5108
|
+
}
|
|
5109
|
+
return null;
|
|
5110
|
+
}
|
|
5111
|
+
|
|
5112
|
+
function resolveAssets(extensionUri: vscode.Uri, ui: string): { js: string[]; css: string[] } {
|
|
5113
|
+
const manifest = loadManifest(extensionUri);
|
|
5114
|
+
if (!manifest) {
|
|
5115
|
+
// Fallback to convention: <ui>/index.js + <ui>/index.css
|
|
5116
|
+
return { js: [\`\${ui}/index.js\`], css: [\`\${ui}/index.css\`] };
|
|
5117
|
+
}
|
|
5118
|
+
// Manifest keys for HTML entries look like \`<ui>/index.html\`.
|
|
5119
|
+
const key = \`\${ui}/index.html\`;
|
|
5120
|
+
const entry = manifest[key];
|
|
5121
|
+
if (!entry) return { js: [\`\${ui}/index.js\`], css: [] };
|
|
5122
|
+
const js = [entry.file];
|
|
5123
|
+
const css = [...(entry.css ?? [])];
|
|
5124
|
+
// Recursively pull CSS from imported chunks.
|
|
5125
|
+
const seen = new Set<string>();
|
|
5126
|
+
const walk = (imp: string) => {
|
|
5127
|
+
if (seen.has(imp)) return;
|
|
5128
|
+
seen.add(imp);
|
|
5129
|
+
const e = manifest[imp];
|
|
5130
|
+
if (!e) return;
|
|
5131
|
+
if (e.css) css.push(...e.css);
|
|
5132
|
+
e.imports?.forEach(walk);
|
|
5133
|
+
};
|
|
5134
|
+
entry.imports?.forEach(walk);
|
|
5135
|
+
return { js, css };
|
|
5136
|
+
}
|
|
5137
|
+
|
|
5138
|
+
function renderHtml(webview: vscode.Webview, context: vscode.ExtensionContext, ui: string, title: string): string {
|
|
5139
|
+
const root = vscode.Uri.joinPath(context.extensionUri, 'dist', 'webview');
|
|
5140
|
+
const { js, css } = resolveAssets(context.extensionUri, ui);
|
|
5141
|
+
const toUri = (rel: string) =>
|
|
5142
|
+
webview.asWebviewUri(vscode.Uri.joinPath(root, ...rel.split('/'))).toString();
|
|
5143
|
+
const scriptTags = js
|
|
5144
|
+
.map((f) => \`<script type="module" nonce="{{NONCE}}" src="\${toUri(f)}"></script>\`)
|
|
5145
|
+
.join('\\n ');
|
|
5146
|
+
const styleTags = css.map((f) => \`<link rel="stylesheet" href="\${toUri(f)}" />\`).join('\\n ');
|
|
5147
|
+
const nonce = Array.from({ length: 16 }, () => Math.random().toString(36)[2]).join('');
|
|
5148
|
+
const csp = [
|
|
5149
|
+
\`default-src 'none'\`,
|
|
5150
|
+
\`style-src \${webview.cspSource} 'unsafe-inline'\`,
|
|
5151
|
+
\`script-src 'nonce-\${nonce}'\`,
|
|
5152
|
+
\`img-src \${webview.cspSource} https: data:\`,
|
|
5153
|
+
\`font-src \${webview.cspSource}\`,
|
|
5154
|
+
].join('; ');
|
|
5155
|
+
|
|
5156
|
+
return \`<!DOCTYPE html>
|
|
5157
|
+
<html lang="en">
|
|
5158
|
+
<head>
|
|
5159
|
+
<meta charset="UTF-8" />
|
|
5160
|
+
<meta http-equiv="Content-Security-Policy" content="\${csp}" />
|
|
5161
|
+
\${styleTags}
|
|
5162
|
+
<title>\${escapeHtml(title)}</title>
|
|
5163
|
+
</head>
|
|
5164
|
+
<body><div id="root"></div>
|
|
5165
|
+
\${scriptTags.replace(/\\{\\{NONCE\\}\\}/g, nonce)}
|
|
5166
|
+
</body>
|
|
5167
|
+
</html>\`;
|
|
5168
|
+
}
|
|
5169
|
+
|
|
5170
|
+
function resolveColumn(c: PanelDef['column']): vscode.ViewColumn {
|
|
5171
|
+
switch (c) {
|
|
5172
|
+
case 'beside': return vscode.ViewColumn.Beside;
|
|
5173
|
+
case 'one': return vscode.ViewColumn.One;
|
|
5174
|
+
case 'two': return vscode.ViewColumn.Two;
|
|
5175
|
+
case 'three': return vscode.ViewColumn.Three;
|
|
5176
|
+
default: return vscode.window.activeTextEditor?.viewColumn ?? vscode.ViewColumn.One;
|
|
5177
|
+
}
|
|
5178
|
+
}
|
|
5179
|
+
|
|
5180
|
+
function capitalize(s: string): string {
|
|
5181
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
5182
|
+
}
|
|
5183
|
+
|
|
5184
|
+
function escapeHtml(s: string): string {
|
|
5185
|
+
return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]!));
|
|
5186
|
+
}
|
|
5187
|
+
`,
|
|
5188
|
+
"react/src/shared/vsceasy/client.ts": `// Webview-safe exports only — does NOT import 'vscode'.
|
|
5189
|
+
export {
|
|
5190
|
+
createRpcClient,
|
|
5191
|
+
vscodeApiTransport,
|
|
5192
|
+
connectWebview,
|
|
5193
|
+
webviewState,
|
|
5194
|
+
} from './rpc';
|
|
5195
|
+
export type { RpcClient, Handlers, Transport, RpcClientOptions, WebviewApi } from './rpc';
|
|
5196
|
+
`,
|
|
5197
|
+
"react/src/shared/vsceasy/codiconNames.ts": `/**
|
|
5198
|
+
* AUTO-GENERATED by scripts/genCodiconTypes.ts — do not edit.
|
|
5199
|
+
*
|
|
5200
|
+
* Curated subset of VS Code codicon names that the CLI's icon picker offers.
|
|
5201
|
+
* Used by \`MenuIcon\` for editor autocomplete. Any string is still accepted at
|
|
5202
|
+
* runtime via the \`(string & {})\` fallback in define.ts.
|
|
5203
|
+
*
|
|
5204
|
+
* Full list: https://microsoft.github.io/vscode-codicons/dist/codicon.html
|
|
5205
|
+
*/
|
|
5206
|
+
export type CodiconName =
|
|
5207
|
+
| 'account'
|
|
5208
|
+
| 'add'
|
|
5209
|
+
| 'archive'
|
|
5210
|
+
| 'beaker'
|
|
5211
|
+
| 'bell'
|
|
5212
|
+
| 'bell-dot'
|
|
5213
|
+
| 'book'
|
|
5214
|
+
| 'bookmark'
|
|
5215
|
+
| 'broadcast'
|
|
5216
|
+
| 'browser'
|
|
5217
|
+
| 'bug'
|
|
5218
|
+
| 'calendar'
|
|
5219
|
+
| 'check'
|
|
5220
|
+
| 'clock'
|
|
5221
|
+
| 'close'
|
|
5222
|
+
| 'cloud'
|
|
5223
|
+
| 'cloud-download'
|
|
5224
|
+
| 'cloud-upload'
|
|
5225
|
+
| 'code'
|
|
5226
|
+
| 'comment'
|
|
5227
|
+
| 'comment-discussion'
|
|
5228
|
+
| 'compass'
|
|
5229
|
+
| 'console'
|
|
5230
|
+
| 'dashboard'
|
|
5231
|
+
| 'database'
|
|
5232
|
+
| 'debug'
|
|
5233
|
+
| 'debug-alt'
|
|
5234
|
+
| 'debug-breakpoint'
|
|
5235
|
+
| 'debug-console'
|
|
5236
|
+
| 'debug-continue'
|
|
5237
|
+
| 'debug-disconnect'
|
|
5238
|
+
| 'debug-pause'
|
|
5239
|
+
| 'debug-restart'
|
|
5240
|
+
| 'debug-start'
|
|
5241
|
+
| 'debug-step-into'
|
|
5242
|
+
| 'debug-step-out'
|
|
5243
|
+
| 'debug-step-over'
|
|
5244
|
+
| 'debug-stop'
|
|
5245
|
+
| 'desktop-download'
|
|
5246
|
+
| 'edit'
|
|
5247
|
+
| 'error'
|
|
5248
|
+
| 'export'
|
|
5249
|
+
| 'extensions'
|
|
5250
|
+
| 'eye'
|
|
5251
|
+
| 'eye-closed'
|
|
5252
|
+
| 'file'
|
|
5253
|
+
| 'file-binary'
|
|
5254
|
+
| 'file-code'
|
|
5255
|
+
| 'file-media'
|
|
5256
|
+
| 'file-pdf'
|
|
5257
|
+
| 'file-symlink-directory'
|
|
5258
|
+
| 'file-symlink-file'
|
|
5259
|
+
| 'file-text'
|
|
5260
|
+
| 'file-zip'
|
|
5261
|
+
| 'files'
|
|
5262
|
+
| 'filter'
|
|
5263
|
+
| 'flag'
|
|
5264
|
+
| 'flame'
|
|
5265
|
+
| 'folder'
|
|
5266
|
+
| 'folder-active'
|
|
5267
|
+
| 'folder-library'
|
|
5268
|
+
| 'folder-opened'
|
|
5269
|
+
| 'gear'
|
|
5270
|
+
| 'git-branch'
|
|
5271
|
+
| 'git-commit'
|
|
5272
|
+
| 'git-compare'
|
|
5273
|
+
| 'git-fork'
|
|
5274
|
+
| 'git-merge'
|
|
5275
|
+
| 'git-pull-request'
|
|
5276
|
+
| 'github'
|
|
5277
|
+
| 'github-alt'
|
|
5278
|
+
| 'github-inverted'
|
|
5279
|
+
| 'globe'
|
|
5280
|
+
| 'graph'
|
|
5281
|
+
| 'heart'
|
|
5282
|
+
| 'history'
|
|
5283
|
+
| 'home'
|
|
5284
|
+
| 'image'
|
|
5285
|
+
| 'inbox'
|
|
5286
|
+
| 'info'
|
|
5287
|
+
| 'json'
|
|
5288
|
+
| 'key'
|
|
5289
|
+
| 'layout'
|
|
5290
|
+
| 'layout-panel'
|
|
5291
|
+
| 'layout-sidebar-left'
|
|
5292
|
+
| 'layout-sidebar-right'
|
|
5293
|
+
| 'lightbulb'
|
|
5294
|
+
| 'link'
|
|
5295
|
+
| 'link-external'
|
|
5296
|
+
| 'list-flat'
|
|
5297
|
+
| 'list-ordered'
|
|
5298
|
+
| 'list-selection'
|
|
5299
|
+
| 'list-tree'
|
|
5300
|
+
| 'list-unordered'
|
|
5301
|
+
| 'location'
|
|
5302
|
+
| 'lock'
|
|
5303
|
+
| 'mail'
|
|
5304
|
+
| 'markdown'
|
|
5305
|
+
| 'megaphone'
|
|
5306
|
+
| 'mortar-board'
|
|
5307
|
+
| 'mute'
|
|
5308
|
+
| 'new-file'
|
|
5309
|
+
| 'new-folder'
|
|
5310
|
+
| 'note'
|
|
5311
|
+
| 'notebook'
|
|
5312
|
+
| 'organization'
|
|
5313
|
+
| 'output'
|
|
5314
|
+
| 'package'
|
|
5315
|
+
| 'pencil'
|
|
5316
|
+
| 'person'
|
|
5317
|
+
| 'pin'
|
|
5318
|
+
| 'pinned'
|
|
5319
|
+
| 'play'
|
|
5320
|
+
| 'play-circle'
|
|
5321
|
+
| 'plug'
|
|
5322
|
+
| 'preferences'
|
|
5323
|
+
| 'preview'
|
|
5324
|
+
| 'pulse'
|
|
5325
|
+
| 'question'
|
|
5326
|
+
| 'record'
|
|
5327
|
+
| 'refresh'
|
|
5328
|
+
| 'remove'
|
|
5329
|
+
| 'replace'
|
|
5330
|
+
| 'repo'
|
|
5331
|
+
| 'repo-clone'
|
|
5332
|
+
| 'repo-forked'
|
|
5333
|
+
| 'repo-pull'
|
|
5334
|
+
| 'repo-push'
|
|
5335
|
+
| 'rocket'
|
|
5336
|
+
| 'save'
|
|
5337
|
+
| 'save-all'
|
|
5338
|
+
| 'search'
|
|
5339
|
+
| 'server'
|
|
5340
|
+
| 'server-environment'
|
|
5341
|
+
| 'server-process'
|
|
5342
|
+
| 'settings'
|
|
5343
|
+
| 'settings-gear'
|
|
5344
|
+
| 'shield'
|
|
5345
|
+
| 'source-control'
|
|
5346
|
+
| 'sparkle'
|
|
5347
|
+
| 'split-horizontal'
|
|
5348
|
+
| 'split-vertical'
|
|
5349
|
+
| 'star'
|
|
5350
|
+
| 'star-empty'
|
|
5351
|
+
| 'star-full'
|
|
5352
|
+
| 'stop'
|
|
5353
|
+
| 'stop-circle'
|
|
5354
|
+
| 'symbol-array'
|
|
5355
|
+
| 'symbol-boolean'
|
|
5356
|
+
| 'symbol-class'
|
|
5357
|
+
| 'symbol-color'
|
|
5358
|
+
| 'symbol-constant'
|
|
5359
|
+
| 'symbol-enum'
|
|
5360
|
+
| 'symbol-event'
|
|
5361
|
+
| 'symbol-field'
|
|
5362
|
+
| 'symbol-function'
|
|
5363
|
+
| 'symbol-interface'
|
|
5364
|
+
| 'symbol-key'
|
|
5365
|
+
| 'symbol-method'
|
|
5366
|
+
| 'symbol-misc'
|
|
5367
|
+
| 'symbol-module'
|
|
5368
|
+
| 'symbol-namespace'
|
|
5369
|
+
| 'symbol-numeric'
|
|
5370
|
+
| 'symbol-parameter'
|
|
5371
|
+
| 'symbol-property'
|
|
5372
|
+
| 'symbol-snippet'
|
|
5373
|
+
| 'symbol-string'
|
|
5374
|
+
| 'symbol-variable'
|
|
5375
|
+
| 'sync'
|
|
5376
|
+
| 'tag'
|
|
5377
|
+
| 'terminal'
|
|
5378
|
+
| 'terminal-bash'
|
|
5379
|
+
| 'terminal-cmd'
|
|
5380
|
+
| 'terminal-linux'
|
|
5381
|
+
| 'terminal-powershell'
|
|
5382
|
+
| 'tools'
|
|
5383
|
+
| 'trash'
|
|
5384
|
+
| 'unlock'
|
|
5385
|
+
| 'unmute'
|
|
5386
|
+
| 'verified'
|
|
5387
|
+
| 'video'
|
|
5388
|
+
| 'wand'
|
|
5389
|
+
| 'warning'
|
|
5390
|
+
| 'watch'
|
|
5391
|
+
| 'window'
|
|
5392
|
+
| 'zap';
|
|
5393
|
+
`,
|
|
5394
|
+
"react/src/shared/vsceasy/define.ts": `import type * as vscode from 'vscode';
|
|
5395
|
+
import type { Handlers } from './rpc';
|
|
5396
|
+
import type { CodiconName } from './codiconNames';
|
|
5397
|
+
|
|
5398
|
+
export interface PanelDef<H extends Handlers = Handlers> {
|
|
5399
|
+
/** Stable id. Default: file basename. Used as command suffix and webview key. */
|
|
5400
|
+
id?: string;
|
|
5401
|
+
/** Tab title. */
|
|
5402
|
+
title: string;
|
|
5403
|
+
/** Webview bundle name under dist/webview/<ui>/. Default: same as id. */
|
|
5404
|
+
ui?: string;
|
|
5405
|
+
/** Where to open. Default: 'active'. */
|
|
5406
|
+
column?: 'active' | 'beside' | 'one' | 'two' | 'three';
|
|
5407
|
+
/** Keep DOM alive when hidden. Default: true. */
|
|
5408
|
+
retainContext?: boolean;
|
|
5409
|
+
/** RPC handlers — receives vscode namespace + extension context. */
|
|
5410
|
+
rpc?: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext) => H;
|
|
5411
|
+
/** Optional command palette entry that opens this panel. Default: true. */
|
|
5412
|
+
command?:
|
|
5413
|
+
| boolean
|
|
5414
|
+
| { title?: string; category?: string };
|
|
5415
|
+
}
|
|
5416
|
+
|
|
5417
|
+
export interface CommandDef {
|
|
5418
|
+
/** Stable id. Default: file basename. */
|
|
5419
|
+
id?: string;
|
|
5420
|
+
/** Command palette title. */
|
|
5421
|
+
title: string;
|
|
5422
|
+
/** Optional category prefix (default: extension displayName). */
|
|
5423
|
+
category?: string;
|
|
5424
|
+
/** Handler. Receives vscode + extension context. */
|
|
5425
|
+
run: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext, ...args: unknown[]) => unknown | Promise<unknown>;
|
|
5426
|
+
/**
|
|
5427
|
+
* Keyboard shortcut. String shorthand uses the same key on every platform.
|
|
5428
|
+
* Object form supports \`mac\` override and a VS Code \`when\` clause.
|
|
5429
|
+
* Written to package.json#contributes.keybindings by \`bun run gen\`.
|
|
5430
|
+
*/
|
|
5431
|
+
keybinding?: string | KeybindingDef | (string | KeybindingDef)[];
|
|
5432
|
+
/**
|
|
5433
|
+
* VS Code \`when\` clause that controls visibility/enablement of this command
|
|
5434
|
+
* in the command palette and auto-generated menu entries. Written to
|
|
5435
|
+
* \`contributes.commands[].enablement\` and used as the default \`when\` on
|
|
5436
|
+
* the palette menu entry by \`bun run gen\`.
|
|
5437
|
+
*
|
|
5438
|
+
* Examples: \`'editorTextFocus'\`, \`'resourceLangId == typescript'\`,
|
|
5439
|
+
* \`'explorerResourceIsFolder && !virtualWorkspace'\`.
|
|
5440
|
+
* Reference: https://code.visualstudio.com/api/references/when-clause-contexts
|
|
5441
|
+
*/
|
|
5442
|
+
when?: string;
|
|
5443
|
+
}
|
|
5444
|
+
|
|
5445
|
+
export interface KeybindingDef {
|
|
5446
|
+
/** Default key combo (e.g. 'ctrl+shift+h'). */
|
|
5447
|
+
key: string;
|
|
5448
|
+
/** Override combo on macOS (e.g. 'cmd+shift+h'). */
|
|
5449
|
+
mac?: string;
|
|
5450
|
+
/** VS Code context \`when\` clause (e.g. 'editorTextFocus'). */
|
|
5451
|
+
when?: string;
|
|
5452
|
+
}
|
|
5453
|
+
|
|
5454
|
+
export function definePanel<H extends Handlers = Handlers>(def: PanelDef<H>): PanelDef<H> {
|
|
5455
|
+
return def;
|
|
5456
|
+
}
|
|
5457
|
+
|
|
5458
|
+
export function defineCommand(def: CommandDef): CommandDef {
|
|
5459
|
+
return def;
|
|
5460
|
+
}
|
|
5461
|
+
|
|
5462
|
+
// --- Menus (Activity Bar + Tree View) ---
|
|
5463
|
+
|
|
5464
|
+
export type MenuIcon =
|
|
5465
|
+
| CodiconName // known codicon (autocompletes)
|
|
5466
|
+
| (string & {}) // any codicon name (escape hatch, keeps autocomplete)
|
|
5467
|
+
| { path: string } // single SVG path relative to project root
|
|
5468
|
+
| { light: string; dark: string }; // theme-aware SVG paths
|
|
5469
|
+
|
|
5470
|
+
export type { CodiconName };
|
|
5471
|
+
|
|
5472
|
+
export interface MenuItem {
|
|
5473
|
+
/** Display label. */
|
|
5474
|
+
label: string;
|
|
5475
|
+
/** Optional icon (codicon name or asset path). */
|
|
5476
|
+
icon?: MenuIcon;
|
|
5477
|
+
/** Optional tooltip / hover description. */
|
|
5478
|
+
description?: string;
|
|
5479
|
+
/** Open a panel by id (file basename in src/panels/). */
|
|
5480
|
+
panel?: string;
|
|
5481
|
+
/** Execute a command by id (file basename in src/commands/). */
|
|
5482
|
+
command?: string;
|
|
5483
|
+
/** Open an external URL in the user's browser. */
|
|
5484
|
+
url?: string;
|
|
5485
|
+
/** Run an arbitrary handler (full vscode access). */
|
|
5486
|
+
run?: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext) => unknown | Promise<unknown>;
|
|
5487
|
+
/** Nested items — renders as a collapsible group. */
|
|
5488
|
+
children?: MenuItem[];
|
|
5489
|
+
/** Initial collapsed state for groups. Default: 'expanded'. */
|
|
5490
|
+
collapsed?: 'expanded' | 'collapsed';
|
|
5491
|
+
}
|
|
5492
|
+
|
|
5493
|
+
export interface MenuDef {
|
|
5494
|
+
/** Stable id. Default: file basename. Becomes the view container id. */
|
|
5495
|
+
id?: string;
|
|
5496
|
+
/** Title shown at the top of the sidebar panel and as the activity bar tooltip. */
|
|
5497
|
+
title: string;
|
|
5498
|
+
/** Activity bar icon. Codicon string OR SVG path(s). */
|
|
5499
|
+
icon: MenuIcon;
|
|
5500
|
+
/** Items shown in the tree view. */
|
|
5501
|
+
items: MenuItem[];
|
|
5502
|
+
}
|
|
5503
|
+
|
|
5504
|
+
export function defineMenu(def: MenuDef): MenuDef {
|
|
5505
|
+
return def;
|
|
5506
|
+
}
|
|
5507
|
+
|
|
5508
|
+
// --- Webview Views (inline sidebar sections) ---
|
|
5509
|
+
|
|
5510
|
+
export interface SubpanelDef<H extends Handlers = Handlers> {
|
|
5511
|
+
/** Stable id. Default: file basename. */
|
|
5512
|
+
id?: string;
|
|
5513
|
+
/** Section header shown in the sidebar. */
|
|
5514
|
+
title: string;
|
|
5515
|
+
/** Menu (activity bar container) this view lives in — basename in src/menus/. */
|
|
5516
|
+
menu: string;
|
|
5517
|
+
/** Webview bundle name under dist/webview/<ui>/. Default: same as id. */
|
|
5518
|
+
ui?: string;
|
|
5519
|
+
/** Keep DOM alive when hidden. Default: true. */
|
|
5520
|
+
retainContext?: boolean;
|
|
5521
|
+
/** RPC handlers — receives vscode namespace + extension context. */
|
|
5522
|
+
rpc?: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext) => H;
|
|
5523
|
+
}
|
|
5524
|
+
|
|
5525
|
+
export function defineSubpanel<H extends Handlers = Handlers>(def: SubpanelDef<H>): SubpanelDef<H> {
|
|
5526
|
+
return def;
|
|
5527
|
+
}
|
|
5528
|
+
|
|
5529
|
+
// --- Status Bar items ---
|
|
5530
|
+
|
|
5531
|
+
export interface StatusBarDef {
|
|
5532
|
+
/** Stable id. Default: file basename. */
|
|
5533
|
+
id?: string;
|
|
5534
|
+
/** Display text. May include \`$(codicon)\` syntax. */
|
|
5535
|
+
text: string;
|
|
5536
|
+
/** Tooltip on hover. */
|
|
5537
|
+
tooltip?: string;
|
|
5538
|
+
/** Optional codicon, prepended as \`$(icon) text\` when both present. */
|
|
5539
|
+
icon?: CodiconName | (string & {});
|
|
5540
|
+
/** Bar side. Default: 'left'. */
|
|
5541
|
+
alignment?: 'left' | 'right';
|
|
5542
|
+
/** Higher = leftmost on its side. Default: 100. */
|
|
5543
|
+
priority?: number;
|
|
5544
|
+
/** Command id to run on click (basename in src/commands/, or full vscode command id). */
|
|
5545
|
+
command?: string;
|
|
5546
|
+
/** Open a panel by id (basename in src/panels/). Takes precedence over \`command\` when set. */
|
|
5547
|
+
panel?: string;
|
|
5548
|
+
/** Background color theme key (e.g. 'statusBarItem.warningBackground'). */
|
|
5549
|
+
backgroundColor?: string;
|
|
5550
|
+
/**
|
|
5551
|
+
* Rich markdown tooltip (overrides \`tooltip\`). Supports command links
|
|
5552
|
+
* (\`[text](command:ext.foo)\`), codicons (\`$(rocket)\`), and HTML.
|
|
5553
|
+
* Rendered on hover. Mimics Copilot/GitLens popup style.
|
|
5554
|
+
*/
|
|
5555
|
+
tooltipMarkdown?: string;
|
|
5556
|
+
/**
|
|
5557
|
+
* Open a popup menu on click instead of running a single command/panel.
|
|
5558
|
+
* Each item runs its \`command\`, opens its \`panel\`, or opens its \`url\`.
|
|
5559
|
+
*/
|
|
5560
|
+
menu?: StatusBarMenuItem[];
|
|
5561
|
+
}
|
|
5562
|
+
|
|
5563
|
+
export interface StatusBarMenuItem {
|
|
5564
|
+
/** Display label. May include \`$(codicon)\`. */
|
|
5565
|
+
label: string;
|
|
5566
|
+
/** Inline secondary text. */
|
|
5567
|
+
description?: string;
|
|
5568
|
+
/** Detail line (smaller, below). */
|
|
5569
|
+
detail?: string;
|
|
5570
|
+
/** Command id (basename in src/commands/) or full vscode command id. */
|
|
5571
|
+
command?: string;
|
|
5572
|
+
/** Panel id (basename in src/panels/). */
|
|
5573
|
+
panel?: string;
|
|
5574
|
+
/** External URL. */
|
|
5575
|
+
url?: string;
|
|
5576
|
+
}
|
|
5577
|
+
|
|
5578
|
+
export function defineStatusBar(def: StatusBarDef): StatusBarDef {
|
|
5579
|
+
return def;
|
|
5580
|
+
}
|
|
5581
|
+
|
|
5582
|
+
// --- Tree Views (data-driven) ---
|
|
5583
|
+
|
|
5584
|
+
export interface TreeNode {
|
|
5585
|
+
/** Display label. */
|
|
5586
|
+
label: string;
|
|
5587
|
+
/** Stable id, defaults to label. Used for reveal/select. */
|
|
5588
|
+
id?: string;
|
|
5589
|
+
/** Optional icon. */
|
|
5590
|
+
icon?: MenuIcon;
|
|
5591
|
+
/** Tooltip on hover. */
|
|
5592
|
+
tooltip?: string;
|
|
5593
|
+
/** Right-aligned description text. */
|
|
5594
|
+
description?: string;
|
|
5595
|
+
/** Context value used by \`view/item/context\` menu entries. */
|
|
5596
|
+
contextValue?: string;
|
|
5597
|
+
/** Initial state when this node has children. Default: 'collapsed'. */
|
|
5598
|
+
collapsed?: 'expanded' | 'collapsed';
|
|
5599
|
+
/** Eagerly provided children. If omitted, getChildren(this) is called lazily. */
|
|
5600
|
+
children?: TreeNode[];
|
|
5601
|
+
/** Click handler — run an arbitrary callback when the node is selected. */
|
|
5602
|
+
run?: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext) => unknown | Promise<unknown>;
|
|
5603
|
+
/** Click → open a panel by id. */
|
|
5604
|
+
panel?: string;
|
|
5605
|
+
/** Click → run a command by id. */
|
|
5606
|
+
command?: string;
|
|
5607
|
+
}
|
|
5608
|
+
|
|
5609
|
+
export interface TreeViewDef {
|
|
5610
|
+
/** Stable id. Default: file basename. */
|
|
5611
|
+
id?: string;
|
|
5612
|
+
/** Sidebar section header. */
|
|
5613
|
+
title: string;
|
|
5614
|
+
/** Activity bar container id (menu basename in src/menus/). */
|
|
5615
|
+
menu: string;
|
|
5616
|
+
/** Show "Collapse All" button. Default: true. */
|
|
5617
|
+
showCollapseAll?: boolean;
|
|
5618
|
+
/** Initial / refreshed nodes. Called on mount and whenever the view is refreshed. */
|
|
5619
|
+
getChildren: (
|
|
5620
|
+
parent: TreeNode | undefined,
|
|
5621
|
+
vscode: typeof import('vscode'),
|
|
5622
|
+
ctx: vscode.ExtensionContext,
|
|
5623
|
+
) => TreeNode[] | Promise<TreeNode[]>;
|
|
5624
|
+
}
|
|
5625
|
+
|
|
5626
|
+
export function defineTreeView(def: TreeViewDef): TreeViewDef {
|
|
5627
|
+
return def;
|
|
5628
|
+
}
|
|
5629
|
+
|
|
5630
|
+
// --- Jobs (recurring / event-triggered tasks) ---
|
|
5631
|
+
|
|
5632
|
+
export type JobSchedule =
|
|
5633
|
+
/** Run every <interval>. Accepts ms number or duration string: "30s", "5m", "2h", "1d". */
|
|
5634
|
+
| { every: string | number; runOnStart?: boolean }
|
|
5635
|
+
/** Run at HH:MM local time, every day. */
|
|
5636
|
+
| { dailyAt: string }
|
|
5637
|
+
/** Run on a VS Code lifecycle event. */
|
|
5638
|
+
| { on: 'startup' | 'saveDocument' | 'openDocument' | 'changeActiveEditor' | 'changeConfig' }
|
|
5639
|
+
/** Run on filesystem changes matching a glob (relative to workspace). */
|
|
5640
|
+
| { onFile: string };
|
|
5641
|
+
|
|
5642
|
+
export interface JobDef {
|
|
5643
|
+
/** Stable id. Default: file basename. */
|
|
5644
|
+
id?: string;
|
|
5645
|
+
/** Display label (used in logs + opt. status bar). */
|
|
5646
|
+
title: string;
|
|
5647
|
+
/** When to run. */
|
|
5648
|
+
schedule: JobSchedule;
|
|
5649
|
+
/**
|
|
5650
|
+
* Skip if last successful run was less than this many ms ago. Stored in
|
|
5651
|
+
* \`context.globalState\` under \`vsceasy.job.<id>.lastRun\`. Useful for jobs
|
|
5652
|
+
* that should at most run every N hours regardless of how often the
|
|
5653
|
+
* trigger fires.
|
|
5654
|
+
*/
|
|
5655
|
+
minIntervalMs?: number;
|
|
5656
|
+
/** The actual work. Errors are caught and logged — they never crash the host. */
|
|
5657
|
+
run: (vscode: typeof import('vscode'), ctx: vscode.ExtensionContext) => unknown | Promise<unknown>;
|
|
5658
|
+
}
|
|
5659
|
+
|
|
5660
|
+
export function defineJob(def: JobDef): JobDef {
|
|
5661
|
+
return def;
|
|
5662
|
+
}
|
|
5663
|
+
`,
|
|
5664
|
+
"react/src/shared/vsceasy/index.ts": `export { definePanel, defineCommand, defineMenu, defineStatusBar, defineSubpanel, defineTreeView, defineJob } from './define';
|
|
5665
|
+
export type { PanelDef, CommandDef, MenuDef, MenuItem, MenuIcon, StatusBarDef, StatusBarMenuItem, KeybindingDef, SubpanelDef, TreeViewDef, TreeNode, JobDef, JobSchedule, CodiconName } from './define';
|
|
5666
|
+
export { bootstrap } from './bootstrap';
|
|
5667
|
+
export type { Registry, BootstrapOptions, ActivateHook } from './bootstrap';
|
|
5668
|
+
export {
|
|
5669
|
+
createRpcClient,
|
|
5670
|
+
createRpcServer,
|
|
5671
|
+
webviewTransport,
|
|
5672
|
+
vscodeApiTransport,
|
|
5673
|
+
connectWebview,
|
|
5674
|
+
webviewState,
|
|
5675
|
+
} from './rpc';
|
|
5676
|
+
export type { Transport, RpcClient, Handlers, RpcClientOptions, WebviewApi } from './rpc';
|
|
5677
|
+
`,
|
|
5678
|
+
"react/src/shared/vsceasy/rpc.ts": `// Typed RPC bridge — webview <-> extension.
|
|
5679
|
+
// Used by both sides. Transport-agnostic core + thin adapters.
|
|
5680
|
+
|
|
5681
|
+
export type RpcMessage =
|
|
5682
|
+
| { id: string; kind: 'call'; method: string; args: unknown[] }
|
|
5683
|
+
| { id: string; kind: 'result'; ok: true; value: unknown }
|
|
5684
|
+
| { id: string; kind: 'result'; ok: false; error: { message: string; stack?: string } }
|
|
5685
|
+
| { kind: 'event'; topic: string; payload: unknown };
|
|
5686
|
+
|
|
5687
|
+
export interface Transport {
|
|
5688
|
+
send(msg: RpcMessage): void;
|
|
5689
|
+
onMessage(handler: (msg: RpcMessage) => void): () => void;
|
|
5690
|
+
}
|
|
5691
|
+
|
|
5692
|
+
// --- Server (extension side) ---
|
|
5693
|
+
|
|
5694
|
+
/**
|
|
5695
|
+
* Loose constraint: an interface with method members. Using \`object\` (instead
|
|
5696
|
+
* of a Record with index signature) lets user-declared interfaces satisfy the
|
|
5697
|
+
* constraint without forcing them to declare \`[k: string]: any\`.
|
|
5698
|
+
*/
|
|
5699
|
+
export type Handlers = object;
|
|
5700
|
+
|
|
5701
|
+
export function createRpcServer<H extends Handlers>(transport: Transport, handlers: H) {
|
|
5702
|
+
const off = transport.onMessage(async (msg) => {
|
|
5703
|
+
if (msg.kind !== 'call') return;
|
|
5704
|
+
const fn = (handlers as Record<string, (...args: any[]) => any>)[msg.method];
|
|
5705
|
+
if (!fn) {
|
|
5706
|
+
transport.send({
|
|
5707
|
+
id: msg.id,
|
|
5708
|
+
kind: 'result',
|
|
5709
|
+
ok: false,
|
|
5710
|
+
error: { message: \`Unknown RPC method: \${msg.method}\` },
|
|
5711
|
+
});
|
|
5712
|
+
return;
|
|
5713
|
+
}
|
|
5714
|
+
try {
|
|
5715
|
+
const value = await fn(...msg.args);
|
|
5716
|
+
transport.send({ id: msg.id, kind: 'result', ok: true, value });
|
|
5717
|
+
} catch (err: any) {
|
|
5718
|
+
transport.send({
|
|
5719
|
+
id: msg.id,
|
|
5720
|
+
kind: 'result',
|
|
5721
|
+
ok: false,
|
|
5722
|
+
error: { message: String(err?.message ?? err), stack: err?.stack },
|
|
5723
|
+
});
|
|
5724
|
+
}
|
|
5725
|
+
});
|
|
5726
|
+
|
|
5727
|
+
return {
|
|
5728
|
+
emit(topic: string, payload: unknown) {
|
|
5729
|
+
transport.send({ kind: 'event', topic, payload });
|
|
5730
|
+
},
|
|
5731
|
+
dispose: off,
|
|
5732
|
+
};
|
|
5733
|
+
}
|
|
5734
|
+
|
|
5735
|
+
// --- Client (webview side) ---
|
|
5736
|
+
|
|
5737
|
+
export type RpcClient<H extends Handlers> = {
|
|
5738
|
+
[K in keyof H]: H[K] extends (...args: infer A) => infer R
|
|
5739
|
+
? (...args: A) => Promise<Awaited<R>>
|
|
5740
|
+
: never;
|
|
5741
|
+
} & {
|
|
5742
|
+
on(topic: string, handler: (payload: any) => void): () => void;
|
|
5743
|
+
};
|
|
5744
|
+
|
|
5745
|
+
export interface RpcClientOptions {
|
|
5746
|
+
/**
|
|
5747
|
+
* Max wait (ms) for a call's reply before rejecting with a timeout error.
|
|
5748
|
+
* Prevents hangs when the extension host reloads mid-flight during \`bun run dev\`.
|
|
5749
|
+
* Default: 15000. Set to 0 to disable.
|
|
5750
|
+
*/
|
|
5751
|
+
callTimeoutMs?: number;
|
|
5752
|
+
}
|
|
5753
|
+
|
|
5754
|
+
export function createRpcClient<H extends Handlers>(
|
|
5755
|
+
transport: Transport,
|
|
5756
|
+
opts: RpcClientOptions = {},
|
|
5757
|
+
): RpcClient<H> {
|
|
5758
|
+
const callTimeoutMs = opts.callTimeoutMs ?? 15000;
|
|
5759
|
+
const pending = new Map<string, { resolve: (v: any) => void; reject: (e: any) => void; timer?: ReturnType<typeof setTimeout> }>();
|
|
5760
|
+
const listeners = new Map<string, Set<(p: any) => void>>();
|
|
5761
|
+
|
|
5762
|
+
transport.onMessage((msg) => {
|
|
5763
|
+
if (msg.kind === 'result') {
|
|
5764
|
+
const p = pending.get(msg.id);
|
|
5765
|
+
if (!p) return;
|
|
5766
|
+
pending.delete(msg.id);
|
|
5767
|
+
if (p.timer) clearTimeout(p.timer);
|
|
5768
|
+
if (msg.ok) p.resolve(msg.value);
|
|
5769
|
+
else p.reject(Object.assign(new Error(msg.error.message), { stack: msg.error.stack }));
|
|
5770
|
+
} else if (msg.kind === 'event') {
|
|
5771
|
+
listeners.get(msg.topic)?.forEach((l) => l(msg.payload));
|
|
5772
|
+
}
|
|
5773
|
+
});
|
|
5774
|
+
|
|
5775
|
+
let counter = 0;
|
|
5776
|
+
const newId = () => \`r\${++counter}_\${Date.now()}\`;
|
|
5777
|
+
|
|
5778
|
+
const proxy = new Proxy({} as any, {
|
|
5779
|
+
get(_t, prop: string) {
|
|
5780
|
+
if (prop === 'on') {
|
|
5781
|
+
return (topic: string, handler: (p: any) => void) => {
|
|
5782
|
+
let set = listeners.get(topic);
|
|
5783
|
+
if (!set) listeners.set(topic, (set = new Set()));
|
|
5784
|
+
set.add(handler);
|
|
5785
|
+
return () => set!.delete(handler);
|
|
5786
|
+
};
|
|
5787
|
+
}
|
|
5788
|
+
return (...args: unknown[]) =>
|
|
5789
|
+
new Promise((resolve, reject) => {
|
|
5790
|
+
const id = newId();
|
|
5791
|
+
const entry: { resolve: (v: any) => void; reject: (e: any) => void; timer?: ReturnType<typeof setTimeout> } = { resolve, reject };
|
|
5792
|
+
if (callTimeoutMs > 0) {
|
|
5793
|
+
entry.timer = setTimeout(() => {
|
|
5794
|
+
if (pending.delete(id)) {
|
|
5795
|
+
reject(new Error(\`RPC \\\`\${prop}\\\` timed out after \${callTimeoutMs}ms (extension host reloaded?)\`));
|
|
5796
|
+
}
|
|
5797
|
+
}, callTimeoutMs);
|
|
5798
|
+
}
|
|
5799
|
+
pending.set(id, entry);
|
|
5800
|
+
try {
|
|
5801
|
+
transport.send({ id, kind: 'call', method: prop, args });
|
|
5802
|
+
} catch (err) {
|
|
5803
|
+
pending.delete(id);
|
|
5804
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
5805
|
+
reject(err);
|
|
5806
|
+
}
|
|
5807
|
+
});
|
|
5808
|
+
},
|
|
5809
|
+
});
|
|
5810
|
+
|
|
5811
|
+
return proxy as RpcClient<H>;
|
|
5812
|
+
}
|
|
5813
|
+
|
|
5814
|
+
// --- Transports ---
|
|
5815
|
+
|
|
5816
|
+
export function webviewTransport(webview: { postMessage(m: any): any; onDidReceiveMessage: any }): Transport {
|
|
5817
|
+
return {
|
|
5818
|
+
send: (m) => webview.postMessage(m),
|
|
5819
|
+
onMessage: (h) => {
|
|
5820
|
+
const sub = webview.onDidReceiveMessage((m: RpcMessage) => h(m));
|
|
5821
|
+
return () => sub.dispose();
|
|
5822
|
+
},
|
|
5823
|
+
};
|
|
5824
|
+
}
|
|
5825
|
+
|
|
5826
|
+
export function vscodeApiTransport(vscode: { postMessage(m: any): void }): Transport {
|
|
5827
|
+
return {
|
|
5828
|
+
send: (m) => vscode.postMessage(m),
|
|
5829
|
+
onMessage: (h) => {
|
|
5830
|
+
const listener = (e: MessageEvent) => h(e.data as RpcMessage);
|
|
5831
|
+
window.addEventListener('message', listener);
|
|
5832
|
+
return () => window.removeEventListener('message', listener);
|
|
5833
|
+
},
|
|
5834
|
+
};
|
|
5835
|
+
}
|
|
5836
|
+
|
|
5837
|
+
declare global {
|
|
5838
|
+
function acquireVsCodeApi(): WebviewApi;
|
|
5839
|
+
}
|
|
5840
|
+
|
|
5841
|
+
export interface WebviewApi {
|
|
5842
|
+
postMessage(m: any): void;
|
|
5843
|
+
getState(): unknown;
|
|
5844
|
+
setState<T>(s: T): T;
|
|
5845
|
+
}
|
|
5846
|
+
|
|
5847
|
+
let _cachedVscode: WebviewApi | null = null;
|
|
5848
|
+
function vscodeApi(): WebviewApi {
|
|
5849
|
+
// acquireVsCodeApi() may only be called once per webview lifetime.
|
|
5850
|
+
if (_cachedVscode) return _cachedVscode;
|
|
5851
|
+
return (_cachedVscode = acquireVsCodeApi());
|
|
5852
|
+
}
|
|
5853
|
+
|
|
5854
|
+
/** One-liner for webview: returns a typed RPC client. */
|
|
5855
|
+
export function connectWebview<H extends Handlers>(opts?: RpcClientOptions): RpcClient<H> {
|
|
5856
|
+
return createRpcClient<H>(vscodeApiTransport(vscodeApi()), opts);
|
|
5857
|
+
}
|
|
5858
|
+
|
|
5859
|
+
/**
|
|
5860
|
+
* Typed \`vscode.getState() / setState()\` wrapper for webviews. State survives
|
|
5861
|
+
* panel hide/show, host reloads triggered by \`retainContextWhenHidden\`, and
|
|
5862
|
+
* is the recommended way to persist scroll positions, form data, and selection.
|
|
5863
|
+
*
|
|
5864
|
+
* Usage:
|
|
5865
|
+
* const state = webviewState<{ query: string }>({ query: '' });
|
|
5866
|
+
* state.set({ query: 'foo' });
|
|
5867
|
+
* const { query } = state.get();
|
|
5868
|
+
*/
|
|
5869
|
+
export function webviewState<T>(defaults: T): {
|
|
5870
|
+
get(): T;
|
|
5871
|
+
set(next: T | ((prev: T) => T)): T;
|
|
5872
|
+
patch(partial: Partial<T>): T;
|
|
5873
|
+
} {
|
|
5874
|
+
const api = vscodeApi();
|
|
5875
|
+
const init = (): T => ({ ...defaults, ...((api.getState() as T | undefined) ?? {}) });
|
|
5876
|
+
return {
|
|
5877
|
+
get: init,
|
|
5878
|
+
set(next) {
|
|
5879
|
+
const current = init();
|
|
5880
|
+
const value = typeof next === 'function' ? (next as (p: T) => T)(current) : next;
|
|
5881
|
+
api.setState(value);
|
|
5882
|
+
return value;
|
|
5883
|
+
},
|
|
5884
|
+
patch(partial) {
|
|
5885
|
+
const current = init();
|
|
5886
|
+
const value = { ...current, ...partial };
|
|
5887
|
+
api.setState(value);
|
|
5888
|
+
return value;
|
|
5889
|
+
},
|
|
5890
|
+
};
|
|
5891
|
+
}
|
|
5892
|
+
`,
|
|
5893
|
+
"react/src/webview/panels/dashboard/App.tsx": `import React, { useEffect, useState } from 'react';
|
|
5894
|
+
import { connectWebview } from '../../../shared/vsceasy/client';
|
|
5895
|
+
import type { DashboardApi } from '../../../shared/api';
|
|
5896
|
+
|
|
5897
|
+
const api = connectWebview<DashboardApi>();
|
|
5898
|
+
|
|
5899
|
+
export function App() {
|
|
5900
|
+
const [info, setInfo] = useState<{ workspace: string | null; vscodeVersion: string } | null>(null);
|
|
5901
|
+
const [files, setFiles] = useState<string[]>([]);
|
|
5902
|
+
const [pattern, setPattern] = useState('**/*.ts');
|
|
5903
|
+
|
|
5904
|
+
useEffect(() => { api.getInfo().then(setInfo); }, []);
|
|
5905
|
+
|
|
5906
|
+
return (
|
|
5907
|
+
<div className="app">
|
|
5908
|
+
<h1>{{displayName}} Dashboard</h1>
|
|
5909
|
+
{info && (
|
|
5910
|
+
<section>
|
|
5911
|
+
<p><strong>Workspace:</strong> {info.workspace ?? '(none)'}</p>
|
|
5912
|
+
<p><strong>VS Code:</strong> {info.vscodeVersion}</p>
|
|
5913
|
+
</section>
|
|
5914
|
+
)}
|
|
5915
|
+
<section>
|
|
5916
|
+
<input value={pattern} onChange={(e) => setPattern(e.target.value)} />
|
|
5917
|
+
<button onClick={async () => setFiles(await api.listFiles(pattern))}>Find files</button>
|
|
5918
|
+
<button onClick={() => api.showMessage('Hello from the webview!')}>Toast</button>
|
|
5919
|
+
<ul>{files.map((f) => <li key={f}>{f}</li>)}</ul>
|
|
5920
|
+
</section>
|
|
5921
|
+
</div>
|
|
5922
|
+
);
|
|
5923
|
+
}
|
|
5924
|
+
`,
|
|
5925
|
+
"react/src/webview/panels/dashboard/main.tsx": `import React from 'react';
|
|
5926
|
+
import { createRoot } from 'react-dom/client';
|
|
5927
|
+
import { App } from './App';
|
|
5928
|
+
import '../../styles.css';
|
|
5929
|
+
|
|
5930
|
+
createRoot(document.getElementById('root')!).render(<App />);
|
|
5931
|
+
`,
|
|
5932
|
+
"react/src/webview/styles.css": `:root { color-scheme: light dark; }
|
|
5933
|
+
|
|
5934
|
+
body {
|
|
5935
|
+
margin: 0;
|
|
5936
|
+
padding: 1rem;
|
|
5937
|
+
font-family: var(--vscode-font-family);
|
|
5938
|
+
font-size: var(--vscode-font-size);
|
|
5939
|
+
color: var(--vscode-foreground);
|
|
5940
|
+
background: var(--vscode-editor-background);
|
|
5941
|
+
}
|
|
5942
|
+
|
|
5943
|
+
.app h1 { font-size: 1.25rem; margin: 0 0 1rem; }
|
|
5944
|
+
|
|
5945
|
+
button, input {
|
|
5946
|
+
font: inherit;
|
|
5947
|
+
color: var(--vscode-button-foreground, inherit);
|
|
5948
|
+
background: var(--vscode-button-background, transparent);
|
|
5949
|
+
border: 1px solid var(--vscode-button-border, var(--vscode-input-border, #555));
|
|
5950
|
+
padding: 0.35rem 0.75rem;
|
|
5951
|
+
border-radius: 2px;
|
|
5952
|
+
margin-right: 0.5rem;
|
|
5953
|
+
}
|
|
5954
|
+
|
|
5955
|
+
input {
|
|
5956
|
+
background: var(--vscode-input-background);
|
|
5957
|
+
color: var(--vscode-input-foreground);
|
|
5958
|
+
min-width: 16rem;
|
|
5959
|
+
}
|
|
5960
|
+
|
|
5961
|
+
button:hover { background: var(--vscode-button-hoverBackground); }
|
|
5962
|
+
|
|
5963
|
+
ul { padding-left: 1.25rem; }
|
|
5964
|
+
li { line-height: 1.6; }
|
|
5965
|
+
`,
|
|
5966
|
+
"react/tsconfig.json": `{
|
|
5967
|
+
"compilerOptions": {
|
|
5968
|
+
"target": "ES2022",
|
|
5969
|
+
"module": "ESNext",
|
|
5970
|
+
"moduleResolution": "Bundler",
|
|
5971
|
+
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
|
5972
|
+
"jsx": "react-jsx",
|
|
5973
|
+
"strict": true,
|
|
5974
|
+
"esModuleInterop": true,
|
|
5975
|
+
"skipLibCheck": true,
|
|
5976
|
+
"forceConsistentCasingInFileNames": true,
|
|
5977
|
+
"resolveJsonModule": true,
|
|
5978
|
+
"isolatedModules": true,
|
|
5979
|
+
"noEmit": true
|
|
5980
|
+
},
|
|
5981
|
+
"include": ["src"]
|
|
5982
|
+
}
|
|
5983
|
+
`,
|
|
5984
|
+
"react/vite.config.ts": `import { defineConfig } from 'vite';
|
|
5985
|
+
import react from '@vitejs/plugin-react';
|
|
5986
|
+
import * as fs from 'fs';
|
|
5987
|
+
import * as path from 'path';
|
|
5988
|
+
|
|
5989
|
+
const WEBVIEW_ROOT = path.resolve(__dirname, 'src/webview');
|
|
5990
|
+
|
|
5991
|
+
function discoverHtmlEntries(subdir: string): Record<string, string> {
|
|
5992
|
+
const dir = path.join(WEBVIEW_ROOT, subdir);
|
|
5993
|
+
if (!fs.existsSync(dir)) return {};
|
|
5994
|
+
const out: Record<string, string> = {};
|
|
5995
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
5996
|
+
if (!entry.isDirectory()) continue;
|
|
5997
|
+
const html = path.join(dir, entry.name, 'index.html');
|
|
5998
|
+
// Key includes subdir so panel \`dashboard\` and subpanel \`dashboard\` never collide.
|
|
5999
|
+
if (fs.existsSync(html)) out[\`\${subdir}/\${entry.name}\`] = html;
|
|
6000
|
+
}
|
|
6001
|
+
return out;
|
|
6002
|
+
}
|
|
6003
|
+
|
|
6004
|
+
const entries = {
|
|
6005
|
+
...discoverHtmlEntries('panels'),
|
|
6006
|
+
...discoverHtmlEntries('subpanels'),
|
|
6007
|
+
};
|
|
6008
|
+
|
|
6009
|
+
export default defineConfig({
|
|
6010
|
+
plugins: [react()],
|
|
6011
|
+
root: WEBVIEW_ROOT,
|
|
6012
|
+
build: {
|
|
6013
|
+
outDir: path.resolve(__dirname, 'dist/webview'),
|
|
6014
|
+
emptyOutDir: true,
|
|
6015
|
+
manifest: 'manifest.json',
|
|
6016
|
+
rollupOptions: {
|
|
6017
|
+
input: entries,
|
|
6018
|
+
output: {
|
|
6019
|
+
entryFileNames: '[name]/index.js',
|
|
6020
|
+
chunkFileNames: 'chunks/[name]-[hash].js',
|
|
6021
|
+
assetFileNames: 'assets/[name]-[hash].[ext]',
|
|
6022
|
+
},
|
|
6023
|
+
},
|
|
6024
|
+
},
|
|
6025
|
+
});
|
|
6026
|
+
`
|
|
6027
|
+
};
|
|
6028
|
+
});
|
|
6029
|
+
|
|
2240
6030
|
// src/lib/findProject.ts
|
|
2241
6031
|
function findProjectRoot(start = process.cwd()) {
|
|
2242
6032
|
let dir = path14.resolve(start);
|
|
@@ -2258,20 +6048,59 @@ function findProjectRoot(start = process.cwd()) {
|
|
|
2258
6048
|
dir = path14.dirname(dir);
|
|
2259
6049
|
}
|
|
2260
6050
|
}
|
|
2261
|
-
function findTemplatesRoot(fromFile = __dirname) {
|
|
2262
|
-
const
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
6051
|
+
function findTemplatesRoot(fromFile = process.argv[1] ?? __dirname) {
|
|
6052
|
+
const onDisk = findTemplatesOnDisk(fromFile);
|
|
6053
|
+
if (onDisk)
|
|
6054
|
+
return onDisk;
|
|
6055
|
+
return materializeEmbeddedTemplates();
|
|
6056
|
+
}
|
|
6057
|
+
function findTemplatesOnDisk(fromFile) {
|
|
6058
|
+
let dir = path14.dirname(path14.resolve(fromFile));
|
|
6059
|
+
const { root } = path14.parse(dir);
|
|
6060
|
+
while (true) {
|
|
6061
|
+
const candidate = path14.join(dir, "templates");
|
|
6062
|
+
if (fs14.existsSync(candidate) && fs14.statSync(candidate).isDirectory()) {
|
|
6063
|
+
try {
|
|
6064
|
+
if (fs14.readdirSync(candidate).length > 0)
|
|
6065
|
+
return candidate;
|
|
6066
|
+
} catch {}
|
|
6067
|
+
}
|
|
6068
|
+
if (dir === root)
|
|
6069
|
+
return;
|
|
6070
|
+
dir = path14.dirname(dir);
|
|
6071
|
+
}
|
|
2271
6072
|
}
|
|
2272
|
-
|
|
6073
|
+
function materializeEmbeddedTemplates() {
|
|
6074
|
+
if (materializedRoot)
|
|
6075
|
+
return materializedRoot;
|
|
6076
|
+
const keys = Object.keys(TEMPLATE_FILES);
|
|
6077
|
+
if (keys.length === 0) {
|
|
6078
|
+
throw new Error("No templates available: on-disk templates/ not found and no embedded " + "templates were bundled. This is a packaging bug — rebuild with " + "`bun run build` (runs scripts/embedTemplates.ts).");
|
|
6079
|
+
}
|
|
6080
|
+
const hash = crypto.createHash("sha1").update(`${TEMPLATES_VERSION}:${keys.length}:${keys.join("|")}`).digest("hex").slice(0, 12);
|
|
6081
|
+
const dest = path14.join(os.tmpdir(), `vsceasy-templates-${TEMPLATES_VERSION}-${hash}`);
|
|
6082
|
+
const sentinel = path14.join(dest, ".complete");
|
|
6083
|
+
if (fs14.existsSync(sentinel)) {
|
|
6084
|
+
materializedRoot = dest;
|
|
6085
|
+
return dest;
|
|
6086
|
+
}
|
|
6087
|
+
fs14.rmSync(dest, { recursive: true, force: true });
|
|
6088
|
+
fs14.mkdirSync(dest, { recursive: true });
|
|
6089
|
+
for (const rel of keys) {
|
|
6090
|
+
const abs = path14.join(dest, rel);
|
|
6091
|
+
fs14.mkdirSync(path14.dirname(abs), { recursive: true });
|
|
6092
|
+
fs14.writeFileSync(abs, TEMPLATE_FILES[rel]);
|
|
6093
|
+
}
|
|
6094
|
+
fs14.writeFileSync(sentinel, "");
|
|
6095
|
+
materializedRoot = dest;
|
|
6096
|
+
return dest;
|
|
6097
|
+
}
|
|
6098
|
+
var crypto, fs14, os, path14, __dirname = "/home/runner/work/vsceasy/vsceasy/src/lib", materializedRoot;
|
|
2273
6099
|
var init_findProject = __esm(() => {
|
|
6100
|
+
init_templatesData();
|
|
6101
|
+
crypto = __toESM(require("crypto"));
|
|
2274
6102
|
fs14 = __toESM(require("fs"));
|
|
6103
|
+
os = __toESM(require("os"));
|
|
2275
6104
|
path14 = __toESM(require("path"));
|
|
2276
6105
|
});
|
|
2277
6106
|
|