kintone-plugin-ide 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ // ファイルツリー(@pierre/trees)と、ファイル・フォルダの操作
2
+ import { NODE_MODULES } from '../config.js';
3
+ import { loadTrees } from '../deps.js';
4
+ import { el } from '../util/dom.js';
5
+ import { fromBytes, kb } from '../util/bytes.js';
6
+ import { dirname, normalize, isVendor } from '../util/path.js';
7
+ import { TREE_CSS } from './css.js';
8
+ import { workspaceFS } from './workspace-fs.js';
9
+
10
+ export async function setupTree(ctx) {
11
+ const { log, ui } = ctx;
12
+ const { files, saved, dirs } = ctx.state;
13
+ const { FileTree } = await loadTrees();
14
+ const treePaths = () => [...files.keys(), ...[...dirs].map((d) => d + '/')].sort();
15
+
16
+ // ---- 右クリック / ⋯ のメニュー ----
17
+ // ツリーの中(行の右端)に出すと、右のエディタの下に潜ってしまうので、IDE の一番上に出す
18
+ let portal = null;
19
+ const closePortal = () => { portal?.remove(); portal = null; };
20
+ function menu(item, c) {
21
+ closePortal();
22
+ const m = el('div', { className: 'kpi-menu' });
23
+ m.dataset.fileTreeContextMenuRoot = 'true';
24
+ const isDir = item.kind === 'directory';
25
+ const path = normalize(item.path);
26
+ const vendor = isVendor(path);
27
+ const add = (label, fn, disabled = false) => {
28
+ const b = el('button', { textContent: label, disabled });
29
+ b.onclick = () => { c.close({ restoreFocus: false }); closePortal(); fn(); };
30
+ m.append(b);
31
+ };
32
+ const dir = isDir ? path : dirname(path);
33
+ add('新しいファイル', () => newFile(dir), vendor);
34
+ add('新しいフォルダ', () => newFolder(dir), vendor);
35
+ add('ファイルをアップロード…', () => uploadFiles(dir), vendor);
36
+ m.append(el('hr'));
37
+ add('名前を変更', () => tree.startRenaming(item.path), vendor);
38
+ add('複製', () => duplicate(path, isDir), vendor);
39
+ if (!isDir) {
40
+ m.append(el('hr'));
41
+ add('保存した内容と比べる', () => ctx.showDiff(path), vendor);
42
+ add('整形(prettier)', () => ctx.run(() => ctx.formatFiles([path])), vendor);
43
+ }
44
+ add('パスをコピー', () => navigator.clipboard.writeText(path));
45
+ m.append(el('hr'));
46
+ if (vendor) {
47
+ const rest = path.slice(NODE_MODULES.length).split('/');
48
+ const pkg = rest[0] && (rest[0].startsWith('@') ? rest.slice(0, 2).join('/') : rest[0]);
49
+ add(pkg ? `npm uninstall ${pkg}` : 'npm uninstall', () => ctx.run(() => ctx.command(`npm uninstall ${pkg}`)), !pkg);
50
+ }
51
+ else add('削除', () => removePath(path, isDir));
52
+
53
+ ui.root.append(m);
54
+ const r = c.anchorRect;
55
+ const w = m.offsetWidth, h = m.offsetHeight;
56
+ m.style.left = `${Math.max(4, Math.min(r.left, innerWidth - w - 8))}px`;
57
+ m.style.top = `${r.bottom + h + 8 > innerHeight ? Math.max(4, r.top - h) : r.bottom}px`;
58
+ portal = m;
59
+ return el('span'); // ツリーに渡すのは空の印だけ
60
+ }
61
+
62
+ const vendorGuard = (paths) => !paths.some((p) => isVendor(normalize(p)));
63
+ const tree = new FileTree({
64
+ paths: treePaths(),
65
+ initialExpansion: 'open',
66
+ flattenEmptyDirectories: false, // node_modules/dayjs のように1行にまとめない
67
+ search: true,
68
+ renaming: { canRename: ({ path }) => !isVendor(normalize(path)) },
69
+ dragAndDrop: {
70
+ canDrag: vendorGuard,
71
+ canDrop: ({ target }) => !JSON.stringify(target ?? '').includes(NODE_MODULES),
72
+ },
73
+ composition: {
74
+ contextMenu: { enabled: true, triggerMode: 'both', buttonVisibility: 'when-needed', render: menu, onClose: closePortal },
75
+ },
76
+ onSelectionChange: (paths) => { const p = paths[0] && normalize(paths[0]); if (p && files.has(p)) ctx.openFile(p); },
77
+ unsafeCSS: TREE_CSS,
78
+ });
79
+ // 名前の変更もドラッグ&ドロップでの移動も、ツリーの "move" を受けて反映する
80
+ tree.onMutation('move', ({ from, to }) => {
81
+ const f = normalize(from), t = normalize(to);
82
+ const isFolder = from.endsWith('/') || dirs.has(f) || (!files.has(f) && [...files.keys()].some((k) => k.startsWith(f + '/')));
83
+ movePath(f, t, isFolder);
84
+ });
85
+ tree.render({ containerWrapper: ui.treeEl });
86
+ const collapse = (p) => { try { (tree.getItem(p + '/') || tree.getItem(p))?.collapse(); } catch {} };
87
+ collapse('node_modules');
88
+
89
+ // ---- 変更の印(git status の見た目を借りる) ----
90
+ let lastStatus = [];
91
+ let syncTimer;
92
+ function refreshStatus() {
93
+ const set = [];
94
+ for (const p of files.keys()) {
95
+ if (isVendor(p)) continue;
96
+ if (!saved.has(p)) set.push({ path: p, status: 'added' });
97
+ else if (files.get(p) !== saved.get(p)) set.push({ path: p, status: 'modified' });
98
+ }
99
+ if ([...files.keys()].some(isVendor)) set.push({ path: NODE_MODULES, status: 'ignored' });
100
+ const remove = lastStatus.map((s) => s.path).filter((p) => !set.some((s) => s.path === p));
101
+ tree.applyGitStatusPatch({ set, remove });
102
+ lastStatus = set;
103
+ ctx.updateStatus();
104
+ ctx.saveDraft?.();
105
+ clearTimeout(syncTimer); syncTimer = setTimeout(() => workspaceFS.sync(), 400); // 言語サービスに知らせる
106
+ }
107
+
108
+ // ---- 操作 ----
109
+ const has = (p) => files.has(p) || dirs.has(p) || [...files.keys()].some((k) => k.startsWith(p + '/'));
110
+ // 入力欄のチェック(空・node_modules・同じ名前)
111
+ const checkPath = (kind) => (v) => {
112
+ const p = normalize(v);
113
+ if (!p) return '名前を入れてください';
114
+ if (isVendor(p)) return 'node_modules の中には作れません(npm install を使ってください)';
115
+ if (/[\\:*?"<>|]/.test(p)) return '使えない文字が入っています';
116
+ if (kind === 'file' && v.endsWith('/')) return null; // 末尾が / ならフォルダとして作る
117
+ if (files.has(p)) return `${p} はもうあります`;
118
+ if (kind === 'folder' && has(p)) return `${p}/ はもうあります`;
119
+ return null;
120
+ };
121
+ // "src/" + "new-file.ts" の、ファイル名の部分だけを選んだ状態で出す
122
+ const nameRange = (prefix, name) => [prefix.length, prefix.length + name.replace(/\.[^.]*$/, '').length];
123
+ async function newFile(dir) {
124
+ const prefix = dir ? `${dir}/` : '';
125
+ const v = await ctx.ask({ title: '新しいファイル', message: 'フォルダは / で区切ります。末尾を / にするとフォルダを作ります', value: prefix + 'new-file.ts', select: nameRange(prefix, 'new-file.ts'), validate: checkPath('file'), ok: '作る' });
126
+ if (v == null) return;
127
+ if (v.endsWith('/')) { makeFolder(normalize(v)); return; }
128
+ const p = normalize(v);
129
+ addFiles([[p, '']]);
130
+ ctx.openFile(p);
131
+ }
132
+ async function newFolder(dir) {
133
+ const prefix = dir ? `${dir}/` : '';
134
+ const v = await ctx.ask({ title: '新しいフォルダ', value: prefix + 'new-folder', select: [prefix.length, prefix.length + 10], validate: checkPath('folder'), ok: '作る' });
135
+ if (v != null) makeFolder(normalize(v));
136
+ }
137
+ function makeFolder(p) {
138
+ if (!p || has(p)) return;
139
+ dirs.add(p);
140
+ tree.add(p + '/');
141
+ refreshStatus();
142
+ log.ok(`${p}/ を作りました`);
143
+ }
144
+ // 画像などをアップロード。1つならパスを、複数なら置き場所のフォルダを聞く
145
+ async function uploadFiles(dir, picked) {
146
+ const list = picked || await new Promise((resolve) => {
147
+ const input = el('input', { type: 'file', multiple: true });
148
+ input.onchange = () => resolve([...input.files]);
149
+ input.click();
150
+ });
151
+ if (!list.length) return;
152
+ const prefix = dir ? `${dir}/` : '';
153
+ let targets;
154
+ if (list.length === 1) {
155
+ const v = await ctx.ask({ title: `${list[0].name} をアップロード`, message: `置く場所(パス)を指定してください(${kb(list[0].size)})`, value: prefix + list[0].name, select: nameRange(prefix, list[0].name), validate: (x) => (normalize(x) ? (isVendor(normalize(x)) ? 'node_modules の中には置けません' : null) : 'パスを入れてください'), ok: 'アップロード' });
156
+ if (v == null) return;
157
+ targets = [[normalize(v), list[0]]];
158
+ } else {
159
+ const v = await ctx.ask({ title: `${list.length} 個のファイルをアップロード`, message: list.map((f) => f.name).join('\n'), value: dir || 'image', validate: (x) => (isVendor(normalize(x)) ? 'node_modules の中には置けません' : null), ok: 'アップロード' });
160
+ if (v == null) return;
161
+ targets = list.map((f) => [normalize(`${normalize(v)}/${f.name}`), f]);
162
+ }
163
+ const exists = targets.filter(([p]) => files.has(p)).map(([p]) => p);
164
+ if (exists.length && !(await ctx.confirm('上書きします', exists.join('\n'), { ok: '上書きする', danger: true }))) return;
165
+ const entries = [];
166
+ for (const [p, f] of targets) entries.push([p, fromBytes(new Uint8Array(await f.arrayBuffer()))]);
167
+ addFiles(entries);
168
+ for (const [p, f] of targets) log.ok(`${p} を追加しました (${kb(f.size)})`);
169
+ if (targets.length === 1) ctx.openFile(targets[0][0]);
170
+ }
171
+ function addFiles(entries, { collapseNew = false } = {}) {
172
+ const added = [];
173
+ for (const [p, text] of entries) {
174
+ if (!files.has(p)) added.push(p);
175
+ files.set(p, text);
176
+ const m = ctx.models?.get(p); if (m && m.getValue() !== text) m.setValue(text);
177
+ }
178
+ if (added.length) tree.batch(added.map((path) => ({ type: 'add', path })));
179
+ for (const d of [...dirs]) if (added.some((p) => p.startsWith(d + '/'))) dirs.delete(d);
180
+ if (collapseNew) collapse('node_modules');
181
+ refreshStatus();
182
+ }
183
+ // ファイルを消す(確認なし。node_modules の入れ替えなどに使う)
184
+ function dropFiles(paths) {
185
+ for (const f of paths) { files.delete(f); ctx.disposeModel?.(f); }
186
+ const gone = paths.filter((p) => !files.has(p));
187
+ if (gone.length) tree.batch(gone.map((path) => ({ type: 'remove', path })));
188
+ if (gone.includes(ctx.current)) ctx.closeEditor();
189
+ refreshStatus();
190
+ }
191
+ function duplicate(p, isDir) {
192
+ const targets = isDir ? [...files.keys()].filter((f) => f.startsWith(p + '/')) : [p];
193
+ const copyName = isDir ? `${p}-copy` : p.replace(/(\.[^./]+)?$/, '-copy$1');
194
+ if (isDir && !targets.length) { makeFolder(copyName); return; }
195
+ addFiles(targets.map((f) => [isDir ? copyName + f.slice(p.length) : copyName, files.get(f)]));
196
+ }
197
+ async function removePath(p, isFolder) {
198
+ const targets = isFolder ? [...files.keys()].filter((f) => f.startsWith(p + '/')) : [p];
199
+ const emptyDirs = isFolder ? [...dirs].filter((d) => d === p || d.startsWith(p + '/')) : [];
200
+ if (!targets.length && !emptyDirs.length) return;
201
+ if (targets.length && !(await ctx.confirm(`${targets.length} 個のファイルを削除します`, `保存するまでレコードには反映されません\n\n${targets.slice(0, 30).join('\n')}${targets.length > 30 ? '\n…' : ''}`, { ok: '削除', danger: true }))) return;
202
+ for (const f of targets) { files.delete(f); ctx.disposeModel(f); }
203
+ for (const d of emptyDirs) dirs.delete(d);
204
+ tree.remove(isFolder ? p + '/' : p, { recursive: isFolder });
205
+ if (targets.includes(ctx.current)) ctx.closeEditor();
206
+ refreshStatus();
207
+ }
208
+ function movePath(from, to, isFolder) {
209
+ if (isFolder) {
210
+ const moves = [...files.keys()].filter((f) => f.startsWith(from + '/')).map((f) => [f, to + f.slice(from.length)]);
211
+ for (const d of [...dirs]) if (d === from || d.startsWith(from + '/')) { dirs.delete(d); dirs.add(to + d.slice(from.length)); }
212
+ for (const [a, b] of moves) moveFile(a, b);
213
+ } else moveFile(from, to);
214
+ refreshStatus();
215
+ }
216
+ function moveFile(a, b) {
217
+ if (!files.has(a)) return;
218
+ files.set(b, files.get(a)); files.delete(a);
219
+ ctx.disposeModel(a);
220
+ if (ctx.current === a) { ctx.current = null; ctx.openFile(b); }
221
+ }
222
+
223
+ Object.assign(ctx, { tree, refreshStatus, newFile, newFolder, makeFolder, uploadFiles, addFiles, dropFiles, removePath, closeMenu: closePortal });
224
+ }
@@ -0,0 +1,173 @@
1
+ // modern-monaco の言語サービスに見せるファイルシステム。
2
+ // 中身は IDE の files(Map)そのもの。加えて、ファイルに無ければ次の2つを「あることに」する:
3
+ // tsconfig.json … kintone の型(@kintone/dts-gen)を読む設定
4
+ // index.html … import map。npm の依存(esm.sh の型)と、拡張子を省いた相対 import("./lib/banner")の解決
5
+ // modern-monaco は import に拡張子が要るので、拡張子なしの import は import map の scopes で .ts に向ける。
6
+ import { CONFIG } from '../config.js';
7
+ import { readPackageJson } from '../npm/registry.js';
8
+ import { toBytes, enc, isBinary } from '../util/bytes.js';
9
+ import { dirname, normalize } from '../util/path.js';
10
+
11
+ const FILE = 1, DIR = 2;
12
+ class NotFound extends Error { constructor(p) { super(`見つかりません: ${p}`); this.FS_ERROR = 'NOT_FOUND'; this.name = 'NotFoundError'; } }
13
+ const strip = (f) => normalize(String(f).replace(/^file:\/\/\//, '').replace(/[?#].*$/, ''));
14
+ // 型が `declare module 'svelte' { ... }` の形で配られているパッケージ。
15
+ // import map で URL に向けると「モジュールではない」と言われるので、型ファイルを丸ごと環境の型に足す
16
+ // (esm.sh はこの形の型を書き換えて壊すので、jsDelivr からそのまま取る)
17
+ const AMBIENT_TYPES = { svelte: (range) => `https://cdn.jsdelivr.net/npm/svelte@${encodeURIComponent(range)}/types/index.d.ts` };
18
+ const SCRIPT = /\.(m?tsx?|m?jsx?)$/;
19
+ const EXTS = ['.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs', '.d.ts', '/index.ts', '/index.tsx', '/index.js'];
20
+
21
+ export const DEFAULT_TSCONFIG = JSON.stringify({
22
+ compilerOptions: { target: 'ES2020', strict: true, types: [CONFIG.CDN.kintoneDts, 'kintone-plugin-ide-env'] },
23
+ }, null, 2) + '\n';
24
+
25
+ function importMap(files) {
26
+ const imports = {};
27
+ let deps = {};
28
+ try { deps = readPackageJson(files).dependencies; } catch {}
29
+ for (const [name, range] of Object.entries(deps)) {
30
+ if (AMBIENT_TYPES[name]) continue;
31
+ imports[name] = `${CONFIG.CDN.npm}/${name}@${range}`;
32
+ imports[`${name}/`] = `${CONFIG.CDN.npm}/${name}@${range}/`;
33
+ }
34
+ const scopes = {};
35
+ for (const [p, text] of files) {
36
+ if (!SCRIPT.test(p) || p.startsWith('node_modules/') || isBinary(text)) continue;
37
+ const map = {};
38
+ for (const m of text.matchAll(/(?:from\s*|import\s*\(?\s*)['"](\.{1,2}\/[^'"]+)['"]/g)) {
39
+ const spec = m[1];
40
+ if (/\.(m?[tj]sx?|json|css)$/.test(spec)) continue;
41
+ const base = normalize(`${dirname(p)}/${spec}`);
42
+ const hit = EXTS.map((e) => base + e).find((c) => files.has(c));
43
+ if (hit) map[spec] = `/${hit}`;
44
+ }
45
+ if (Object.keys(map).length) scopes[`/${p}`] = map;
46
+ }
47
+ return { imports, scopes };
48
+ }
49
+ // .svelte / .vue などを TS から import できるようにする型と、Svelte 5 のルーン(.svelte.ts 用)
50
+ export const ENV_DTS = `// kintone Plugin IDE が用意する型(仮のファイル)
51
+ declare module '*.svelte' { const component: any; export default component; }
52
+ declare module '*.vue' { const component: any; export default component; }
53
+ declare module '*.yaml' { const data: any; export default data; }
54
+ declare module '*.yml' { const data: any; export default data; }
55
+ declare module '*.css'; declare module '*.scss'; declare module '*.sass'; declare module '*.less';
56
+ declare function $state<T>(initial: T): T;
57
+ declare function $state<T>(): T | undefined;
58
+ declare namespace $state { function raw<T>(initial: T): T; function snapshot<T>(value: T): T; }
59
+ declare function $derived<T>(expression: T): T;
60
+ declare namespace $derived { function by<T>(fn: () => T): T; }
61
+ declare function $effect(fn: () => void | (() => void)): void;
62
+ declare namespace $effect { function pre(fn: () => void | (() => void)): void; function root(fn: () => void | (() => void)): () => void; function tracking(): boolean; }
63
+ declare function $props(): any;
64
+ declare function $bindable<T>(fallback?: T): T;
65
+ declare function $inspect(...values: any[]): { with(fn: (type: 'init' | 'update', ...values: any[]) => void): void };
66
+ declare function $host<T extends HTMLElement = HTMLElement>(): T;
67
+ `;
68
+ const indexHtml = (files) => `<!-- kintone Plugin IDE が作る仮のファイル(言語サービス用) -->\n<script type="importmap">\n${JSON.stringify(importMap(files), null, 2)}\n</script>\n`;
69
+
70
+ class MapFS {
71
+ files = new Map();
72
+ dirs = new Set();
73
+ watchers = new Set();
74
+ onWrite = null;
75
+ last = {};
76
+ ambient = new Map(); // "svelte@^5" → 型ファイルの中身
77
+ attach(files, dirs, onWrite) { this.files = files; this.dirs = dirs; this.onWrite = onWrite; this.last = {}; this.ambient = new Map(); this.sync(); }
78
+ // package.json の依存に合わせて、まとめて配られている型を取ってくる
79
+ loadAmbient() {
80
+ let deps = {};
81
+ try { deps = readPackageJson(this.files).dependencies; } catch {}
82
+ for (const [name, url] of Object.entries(AMBIENT_TYPES)) {
83
+ const key = deps[name] && `${name}@${deps[name]}`;
84
+ if (!key || this.ambient.has(key)) continue;
85
+ for (const k of this.ambient.keys()) if (k.startsWith(name + '@')) this.ambient.delete(k);
86
+ this.ambient.set(key, '');
87
+ fetch(url(deps[name])).then((r) => (r.ok ? r.text() : '')).then((t) => {
88
+ if (!t || this.ambient.get(key) !== '') return;
89
+ this.ambient.set(key, `\n// ---- ${key} ----\n${t.replace(/^\/\/\/ <reference types=.*$/gm, '')}`);
90
+ this.emit('modify', 'kintone-plugin-ide-env.d.ts');
91
+ this.emit('modify', 'tsconfig.json'); // 型の読み直し
92
+ }).catch(() => {});
93
+ }
94
+ }
95
+ virtual(p) {
96
+ if (p === 'tsconfig.json' && !this.files.has(p)) return DEFAULT_TSCONFIG;
97
+ if (p === 'index.html' && !this.files.has(p)) return indexHtml(this.files);
98
+ if (p === 'kintone-plugin-ide-env.d.ts') {
99
+ const extra = [...this.ambient.values()].filter(Boolean);
100
+ // svelte の型が来たら、こちらの仮の '*.svelte' は外す(本物が同じものを持っている)
101
+ const base = extra.some((t) => t.includes("declare module '*.svelte'")) ? ENV_DTS.replace(/^declare module '\*\.svelte'.*\n/m, '') : ENV_DTS;
102
+ return base + extra.join('\n');
103
+ }
104
+ return undefined;
105
+ }
106
+ text(p) {
107
+ const v = this.virtual(p);
108
+ if (v !== undefined) return v;
109
+ if (!this.files.has(p)) throw new NotFound(p);
110
+ return this.files.get(p);
111
+ }
112
+ isDir(p) { return p === '' || this.dirs.has(p) || [...this.files.keys()].some((f) => f.startsWith(p + '/')); }
113
+ async readFile(f) { const t = this.text(strip(f)); return isBinary(t) ? toBytes(t) : enc.encode(t); }
114
+ async readTextFile(f) { const t = this.text(strip(f)); if (isBinary(t)) throw new Error('バイナリです'); return t; }
115
+ async stat(f) {
116
+ const p = strip(f);
117
+ const isFile = this.files.has(p) || this.virtual(p) !== undefined;
118
+ if (!isFile && !this.isDir(p)) throw new NotFound(p);
119
+ const size = isFile ? this.text(p).length : 0;
120
+ return { type: isFile ? FILE : DIR, ctime: 0, mtime: Date.now(), version: 1, size };
121
+ }
122
+ async readDirectory(f) {
123
+ const p = strip(f), prefix = p ? p + '/' : '';
124
+ const out = new Map();
125
+ for (const k of [...this.files.keys(), ...[...this.dirs].map((d) => d + '/x')]) {
126
+ if (!k.startsWith(prefix)) continue;
127
+ const [head, ...rest] = k.slice(prefix.length).split('/');
128
+ if (head) out.set(head, rest.length ? DIR : FILE);
129
+ }
130
+ return [...out];
131
+ }
132
+ async writeFile(f, content, context) {
133
+ const p = strip(f);
134
+ const text = typeof content === 'string' ? content : new TextDecoder().decode(content);
135
+ const created = !this.files.has(p);
136
+ this.files.set(p, text);
137
+ this.onWrite?.(p);
138
+ this.emit(created ? 'create' : 'modify', p, context);
139
+ }
140
+ async createDirectory(f) { this.dirs.add(strip(f)); }
141
+ async delete(f) { const p = strip(f); this.files.delete(p); this.emit('remove', p); }
142
+ async rename(a, b) { const t = this.text(strip(a)); this.files.delete(strip(a)); this.files.set(strip(b), t); this.emit('remove', strip(a)); this.emit('create', strip(b)); }
143
+ async copy(a, b) { this.files.set(strip(b), this.text(strip(a))); this.emit('create', strip(b)); }
144
+ watch(f, a, b) {
145
+ const handle = typeof a === 'function' ? a : b;
146
+ const w = { path: strip(f), recursive: !!(a && a.recursive), handle };
147
+ this.watchers.add(w);
148
+ return () => this.watchers.delete(w);
149
+ }
150
+ emit(kind, p, context) {
151
+ for (const w of this.watchers) {
152
+ if (w.path === p || (w.recursive && (w.path === '' || p.startsWith(w.path + '/')))) {
153
+ try { w.handle(kind, `file:///${p}`, FILE, context); } catch (e) { console.warn(e); }
154
+ }
155
+ }
156
+ }
157
+ // IDE 側でファイルが変わった時に呼ぶ。仮のファイルが変わっていれば言語サービスに知らせる
158
+ sync() {
159
+ this.loadAmbient();
160
+ for (const p of ['tsconfig.json', 'index.html']) {
161
+ let t; try { t = this.text(p); } catch { t = ''; }
162
+ if (this.last[p] !== undefined && this.last[p] !== t) this.emit('modify', p);
163
+ this.last[p] = t;
164
+ }
165
+ const keys = new Set(this.files.keys());
166
+ if (this.last.keys) {
167
+ for (const k of keys) if (!this.last.keys.has(k)) this.emit('create', k);
168
+ for (const k of this.last.keys) if (!keys.has(k)) this.emit('remove', k);
169
+ }
170
+ this.last.keys = keys;
171
+ }
172
+ }
173
+ export const workspaceFS = new MapFS();
package/src/index.js ADDED
@@ -0,0 +1,48 @@
1
+ /*
2
+ * kintone Plugin IDE ― kintone のレコードを、そのままプラグインの開発環境にする
3
+ * 1レコード = 1プラグイン。ソースは添付ファイルのフィールドに zip で持つ。
4
+ *
5
+ * 使い方(アプリの「JavaScript / CSSでカスタマイズ」に入れる数行):
6
+ * (async () => {
7
+ * const { setup } = await import('https://esm.sh/kintone-plugin-ide@0.3.1');
8
+ * setup({ installHosts: ['example.cybozu.com'] });
9
+ * })();
10
+ */
11
+ import { CONFIG, configure } from './config.js';
12
+ import { openIDE } from './ide/index.js';
13
+ import { el } from './util/dom.js';
14
+
15
+ export { CONFIG, configure, openIDE };
16
+ // 画面を使わない部品(自分のツールから使える)
17
+ export { buildPlugin, sourceList, readManifest } from './build/build.js';
18
+ export { generateKey, pack, unpack, idFromSpki } from './packer/packer.js';
19
+ export { install, addToTestApp, deployApp } from './kintone/plugin.js';
20
+
21
+ const open = () => openIDE().catch((e) => { console.error(e); alert('IDEを開けませんでした\n' + e.message); });
22
+
23
+ // 詳細画面のヘッダーに「IDEで開く」を出す。URL に ide=1 があれば自動で開く
24
+ function attach() {
25
+ const space = kintone.app.record.getHeaderMenuSpaceElement();
26
+ if (space && !space.querySelector('.kpi-open')) {
27
+ const b = el('button', { className: 'kpi-open kintoneplugin-button-normal', textContent: 'IDEで開く' });
28
+ b.onclick = open;
29
+ space.append(b);
30
+ }
31
+ if (/[?&#]ide=1\b/.test(location.href) && !document.querySelector('.kpi-root')) setTimeout(open, 0);
32
+ }
33
+
34
+ let registered = false;
35
+ /**
36
+ * @param {import('../types/index.d.ts').SetupOptions} [options]
37
+ */
38
+ export function setup(options = {}) {
39
+ configure(options);
40
+ window.__openKintonePluginIDE = openIDE;
41
+ if (!registered) {
42
+ registered = true;
43
+ kintone.events.on('app.record.detail.show', (event) => { attach(); return event; });
44
+ }
45
+ // CDN から読むと、詳細画面の表示イベントが先に終わっていることがある。その場合はここで出す
46
+ try { if (kintone.app.record.getId()) attach(); } catch {}
47
+ return { open: openIDE, config: CONFIG };
48
+ }
@@ -0,0 +1,24 @@
1
+ import { CONFIG } from '../config.js';
2
+
3
+ export const apiUrl = (p) => kintone.api.url(p, true);
4
+ export const api = (p, method, body) => kintone.api(apiUrl(p), method, body);
5
+ export const apiError = (e) => {
6
+ const code = e && (e.code || (e.error && e.error.code));
7
+ const msg = (e && (e.message || (e.error && e.error.message))) || String(e);
8
+ return code === 'CB_NO02' ? 'kintoneシステム管理者の権限がありません' : code ? `${msg} (${code})` : msg;
9
+ };
10
+ export const canInstall = () => CONFIG.INSTALL_HOSTS.includes(location.hostname);
11
+
12
+ export async function downloadFile(fileKey) {
13
+ const res = await fetch(`${apiUrl('/k/v1/file.json')}?fileKey=${encodeURIComponent(fileKey)}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
14
+ if (!res.ok) throw new Error(`ファイルの取得に失敗しました (${res.status})`);
15
+ return new Uint8Array(await res.arrayBuffer());
16
+ }
17
+ export async function uploadFile(bytes, name, type = 'application/octet-stream') {
18
+ const form = new FormData();
19
+ form.append('__REQUEST_TOKEN__', kintone.getRequestToken());
20
+ form.append('file', new Blob([bytes], { type }), name);
21
+ const res = await fetch(apiUrl('/k/v1/file.json'), { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' }, body: form });
22
+ if (!res.ok) throw new Error(`アップロードに失敗しました (${res.status})`);
23
+ return (await res.json()).fileKey;
24
+ }
@@ -0,0 +1,37 @@
1
+ // プラグインのインストール・テスト用アプリへの反映
2
+ import { api, apiError, canInstall, uploadFile } from './api.js';
3
+
4
+ export async function install(plugin, id, zipName, log) {
5
+ if (!canInstall()) throw new Error(`${location.hostname} は INSTALL_HOSTS に入っていないので、インストールしません`);
6
+ let installed;
7
+ try { installed = (await api('/k/v1/plugins.json', 'GET', { ids: [id] })).plugins.some((p) => p.id === id); } catch (e) { throw new Error(apiError(e)); }
8
+ const fileKey = await uploadFile(plugin, zipName, 'application/zip');
9
+ try {
10
+ const r = await api('/k/v1/plugin.json', installed ? 'PUT' : 'POST', installed ? { id, fileKey } : { fileKey });
11
+ log.ok(`プラグインを${installed ? '更新' : '読み込み'}しました (v${r.version})`);
12
+ return installed ? '更新' : '読み込み';
13
+ } catch (e) { throw new Error(`プラグインの${installed ? '更新' : '読み込み'}に失敗しました: ${apiError(e)}`); }
14
+ }
15
+
16
+ export async function deployApp(app) {
17
+ await api('/k/v1/preview/app/deploy.json', 'POST', { apps: [{ app }] });
18
+ for (let i = 0; i < 90; i++) {
19
+ await new Promise((r) => setTimeout(r, 1000));
20
+ const st = (await api('/k/v1/preview/app/deploy.json', 'GET', { apps: [app] })).apps[0].status;
21
+ if (st === 'SUCCESS') return;
22
+ if (st !== 'PROCESSING') throw new Error(`反映の状態: ${st}`);
23
+ }
24
+ throw new Error('反映が終わりませんでした');
25
+ }
26
+
27
+ export async function addToTestApp(app, id, log) {
28
+ try {
29
+ const { plugins } = await api('/k/v1/preview/app/plugins.json', 'GET', { app });
30
+ if (!plugins.some((p) => p.id === id)) {
31
+ await api('/k/v1/preview/app/plugins.json', 'POST', { app, ids: [id] });
32
+ log.info(`アプリ ${app} にプラグインを追加しました`);
33
+ }
34
+ await deployApp(app);
35
+ log.ok(`テスト用アプリに反映しました /k/${app}/`);
36
+ } catch (e) { throw new Error(`テスト用アプリ(${app})への反映に失敗しました: ${apiError(e)}`); }
37
+ }
@@ -0,0 +1,32 @@
1
+ import { CONFIG } from '../config.js';
2
+
3
+ // "@scope/name/sub/path" → { name: "@scope/name", sub: "/sub/path" }
4
+ export function parseSpecifier(spec) {
5
+ const parts = spec.split('/');
6
+ const n = spec.startsWith('@') ? 2 : 1;
7
+ return { name: parts.slice(0, n).join('/'), sub: parts.length > n ? '/' + parts.slice(n).join('/') : '' };
8
+ }
9
+ // "dayjs@^1.11" / "@kintone/rest-api-client" → { name, range }
10
+ export function parseInstallArg(arg) {
11
+ const at = arg.lastIndexOf('@');
12
+ return at > 0 ? { name: arg.slice(0, at), range: arg.slice(at + 1) } : { name: arg, range: '' };
13
+ }
14
+ export function readPackageJson(files) {
15
+ if (!files.has('package.json')) return { name: 'kintone-plugin', private: true, dependencies: {} };
16
+ try { const j = JSON.parse(files.get('package.json')); j.dependencies ??= {}; return j; } catch (e) { throw new Error('package.json がJSONとして読めません: ' + e.message); }
17
+ }
18
+ export async function registryInfo(name, tag = 'latest') {
19
+ const res = await fetch(`${CONFIG.CDN.registry}/${name.replace('/', '%2f')}/${encodeURIComponent(tag)}`);
20
+ if (res.status === 404) throw new Error(`npm に ${name}${tag !== 'latest' ? '@' + tag : ''} が見つかりません`);
21
+ if (!res.ok) throw new Error(`npm registry: ${res.status}`);
22
+ return res.json();
23
+ }
24
+ // dist-tag か完全なバージョンなら registry に聞いて "^x.y.z" にする。範囲指定(^1.2 など)はそのまま
25
+ export async function resolveRange(name, range) {
26
+ if (range && /[\^~><=*x| ]/.test(range)) return range;
27
+ const { version } = await registryInfo(name, range || 'latest');
28
+ return range ? version : `^${version}`;
29
+ }
30
+ // shared: 依存を抱え込まない版(esm.sh が分けたモジュールを URL で共有する)
31
+ export const npmUrl = (name, range, sub = '', { shared = false } = {}) =>
32
+ `${CONFIG.CDN.npm}/${name}${range ? '@' + range : ''}${sub}${/\.css$/.test(sub) ? '' : shared ? '?target=es2020' : '?target=es2020&bundle'}`;
@@ -0,0 +1,69 @@
1
+ // npm のパッケージを esm.sh から取ってきて、1ファイルの ES モジュールにして node_modules/ に置く。
2
+ // node_modules/<name>/package.json { name, version, module: "index.mjs" }
3
+ // node_modules/<name>/index.mjs 本体(依存も全部入り)
4
+ // node_modules/<name>/<sub>.mjs "dayjs/plugin/utc" のようなサブパス(使った時に取ってくる)
5
+ // 取ってきたものは IndexedDB に name@version 単位でキャッシュするので、2回目からは通信しない。
6
+ import { NODE_MODULES, SHARED_RUNTIMES } from '../config.js';
7
+ import { loadEsbuild } from '../deps.js';
8
+ import { httpPlugin } from '../build/http-plugin.js';
9
+ import { idbGet, idbSet } from '../util/idb.js';
10
+ import { npmUrl } from './registry.js';
11
+
12
+ export const pkgDir = (name) => `${NODE_MODULES}${name}/`;
13
+ export const subFile = (name, sub) => `${pkgDir(name)}${sub.slice(1)}${/\.(css|mjs|js)$/.test(sub) ? '' : '.mjs'}`;
14
+
15
+ // range("^1.11.0")を esm.sh に解決させて、実際のバージョンを知る
16
+ async function exactVersion(name, range) {
17
+ const res = await fetch(npmUrl(name, range));
18
+ if (!res.ok) throw new Error(`${name}@${range || 'latest'} を取得できません (${res.status})`);
19
+ const text = await res.text();
20
+ const m = text.match(new RegExp(`/${name.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}@([^/]+)/`));
21
+ return m ? m[1] : range;
22
+ }
23
+
24
+ async function bundle(url, log) {
25
+ const es = await loadEsbuild();
26
+ const r = await es.build({
27
+ entryPoints: [url], bundle: true, write: false, format: 'esm', target: 'es2020',
28
+ logLevel: 'silent', legalComments: 'inline', plugins: [httpPlugin(log)],
29
+ });
30
+ return r.outputFiles[0].text;
31
+ }
32
+
33
+ // → [[path, text], ...]
34
+ export async function fetchPackage(name, range, log, { force = false } = {}) {
35
+ const version = await exactVersion(name, range);
36
+ if (SHARED_RUNTIMES.test(name)) {
37
+ // 印だけ置く。中身はビルドの時に esm.sh から分割されたまま読み、ブラウザにキャッシュする
38
+ return { version, entries: [[`${pkgDir(name)}package.json`, JSON.stringify({ name, version, _range: range, _from: `esm.sh/${name}@${version}`, _note: 'ランタイムを共有するパッケージなので、ここには置かずビルド時に esm.sh から読みます' }, null, 2) + '\n']] };
39
+ }
40
+ const key = `npm:${name}@${version}`;
41
+ let main = force ? undefined : await idbGet(key);
42
+ if (main === undefined) {
43
+ log.info(`${name}@${version} を取得しています...`);
44
+ main = await bundle(npmUrl(name, version), log);
45
+ await idbSet(key, main);
46
+ }
47
+ return {
48
+ version,
49
+ entries: [
50
+ [`${pkgDir(name)}package.json`, JSON.stringify({ name, version, type: 'module', module: 'index.mjs', _range: range, _from: `esm.sh/${name}@${version}` }, null, 2) + '\n'],
51
+ [`${pkgDir(name)}index.mjs`, main],
52
+ ],
53
+ };
54
+ }
55
+
56
+ export async function fetchSubpath(name, version, sub, log) {
57
+ const key = `npm:${name}@${version}${sub}`;
58
+ let text = await idbGet(key);
59
+ if (text === undefined) {
60
+ log.info(`${name}${sub} を取得しています...`);
61
+ if (/\.css$/.test(sub)) {
62
+ const res = await fetch(npmUrl(name, version, sub));
63
+ if (!res.ok) throw new Error(`${name}${sub} を取得できません (${res.status})`);
64
+ text = await res.text();
65
+ } else text = await bundle(npmUrl(name, version, sub), log);
66
+ await idbSet(key, text);
67
+ }
68
+ return [subFile(name, sub), text];
69
+ }