kintone-plugin-ide 0.3.0 → 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.
@@ -1,57 +1,57 @@
1
- // ビルド → パッケージ → インストール → テスト用アプリに反映 → 履歴
2
- import { F } from '../../config.js';
3
- import { api, apiError, downloadFile, uploadFile } from '../../kintone/api.js';
4
- import { install, addToTestApp } from '../../kintone/plugin.js';
5
- import { buildPlugin } from '../../build/build.js';
6
- import { generateKey, pack } from '../../packer/packer.js';
7
- import { dec, enc, kb } from '../../util/bytes.js';
8
- import { safeName } from '../../util/path.js';
9
-
10
- export function setupRelease(ctx) {
11
- const { state, log, appId, recordId } = ctx;
12
-
13
- async function buildOnly({ prod = ctx.settings.prod } = {}) {
14
- if (ctx.settings.typecheck) {
15
- const n = await ctx.typecheck({ quiet: true });
16
- if (n) throw new Error(`型エラーが ${n} 件あります(型チェックを OFF にすると無視してビルドできます)`);
17
- }
18
- log.info(`ビルドを始めます(${prod ? '本番' : '開発'})`);
19
- const t = performance.now();
20
- const r = await buildPlugin(state.files, log, { prod, vendor: ctx.vendorSubpath });
21
- log.ok(`ビルドしました (${Math.round(performance.now() - t)} ms)`);
22
- return r;
23
- }
24
- async function getKey() {
25
- ctx.record = await ctx.loadRecord();
26
- const f = ctx.record[F.key].value[0];
27
- if (f) return { ppk: dec.decode(await downloadFile(f.fileKey)), isNew: false };
28
- log.info('秘密鍵が無いので、新しく作ります');
29
- return { ppk: await generateKey(), isNew: true };
30
- }
31
- async function buildAndPack({ skipSave = false, prod } = {}) {
32
- if (!skipSave && state.dirty().length) await ctx.save();
33
- const { manifest, contentsZip } = await buildOnly({ prod });
34
- const { ppk, isNew } = await getKey();
35
- const { plugin, id } = await pack(contentsZip, ppk);
36
- const zipName = `${safeName(manifest.name.ja || manifest.name.en)}-${manifest.version}.zip`;
37
- const update = { [F.zip]: { value: [{ fileKey: await uploadFile(plugin, zipName, 'application/zip') }] }, [F.id]: { value: id } };
38
- if (isNew) update[F.key] = { value: [{ fileKey: await uploadFile(enc.encode(ppk), `${id}.ppk`) }] };
39
- await api('/k/v1/record.json', 'PUT', { app: appId, id: recordId, record: update });
40
- ctx.record = await ctx.loadRecord();
41
- ctx.updateStatus();
42
- log.ok(`パッケージしました: ${zipName} (${kb(plugin.length)}, ${id})`);
43
- return { plugin, id, zipName, manifest };
44
- }
45
- async function buildAndInstall(opts = {}) {
46
- const t = performance.now();
47
- const { plugin, id, zipName, manifest } = await buildAndPack(opts);
48
- const mode = await install(plugin, id, zipName, log);
49
- const testApp = ctx.testApp();
50
- if (testApp) await addToTestApp(testApp, id, log);
51
- try {
52
- await api('/k/v1/record/comment.json', 'POST', { app: appId, record: recordId, comment: { text: `v${manifest.version} を${mode}しました${testApp ? `(テスト用アプリ #${testApp} に反映)` : ''}\n${location.hostname} / ${id}` } });
53
- } catch (e) { log.warn(`コメントに履歴を残せませんでした: ${apiError(e)}`); }
54
- log.ok(`完了 (${((performance.now() - t) / 1000).toFixed(1)} 秒)${testApp ? ` /k/${testApp}/` : ''}`);
55
- }
56
- Object.assign(ctx, { buildOnly, buildAndPack, buildAndInstall });
57
- }
1
+ // ビルド → パッケージ → インストール → テスト用アプリに反映 → 履歴
2
+ import { F } from '../../config.js';
3
+ import { api, apiError, downloadFile, uploadFile } from '../../kintone/api.js';
4
+ import { install, addToTestApp } from '../../kintone/plugin.js';
5
+ import { buildPlugin } from '../../build/build.js';
6
+ import { generateKey, pack } from '../../packer/packer.js';
7
+ import { dec, enc, kb } from '../../util/bytes.js';
8
+ import { safeName } from '../../util/path.js';
9
+
10
+ export function setupRelease(ctx) {
11
+ const { state, log, appId, recordId } = ctx;
12
+
13
+ async function buildOnly({ prod = ctx.settings.prod } = {}) {
14
+ if (ctx.settings.typecheck) {
15
+ const n = await ctx.typecheck({ quiet: true });
16
+ if (n) throw new Error(`型エラーが ${n} 件あります(型チェックを OFF にすると無視してビルドできます)`);
17
+ }
18
+ log.info(`ビルドを始めます(${prod ? '本番' : '開発'})`);
19
+ const t = performance.now();
20
+ const r = await buildPlugin(state.files, log, { prod, vendor: ctx.vendorSubpath });
21
+ log.ok(`ビルドしました (${Math.round(performance.now() - t)} ms)`);
22
+ return r;
23
+ }
24
+ async function getKey() {
25
+ ctx.record = await ctx.loadRecord();
26
+ const f = ctx.record[F.key].value[0];
27
+ if (f) return { ppk: dec.decode(await downloadFile(f.fileKey)), isNew: false };
28
+ log.info('秘密鍵が無いので、新しく作ります');
29
+ return { ppk: await generateKey(), isNew: true };
30
+ }
31
+ async function buildAndPack({ skipSave = false, prod } = {}) {
32
+ if (!skipSave && state.dirty().length) await ctx.save();
33
+ const { manifest, contentsZip } = await buildOnly({ prod });
34
+ const { ppk, isNew } = await getKey();
35
+ const { plugin, id } = await pack(contentsZip, ppk);
36
+ const zipName = `${safeName(manifest.name.ja || manifest.name.en)}-${manifest.version}.zip`;
37
+ const update = { [F.zip]: { value: [{ fileKey: await uploadFile(plugin, zipName, 'application/zip') }] }, [F.id]: { value: id } };
38
+ if (isNew) update[F.key] = { value: [{ fileKey: await uploadFile(enc.encode(ppk), `${id}.ppk`) }] };
39
+ await api('/k/v1/record.json', 'PUT', { app: appId, id: recordId, record: update });
40
+ ctx.record = await ctx.loadRecord();
41
+ ctx.updateStatus();
42
+ log.ok(`パッケージしました: ${zipName} (${kb(plugin.length)}, ${id})`);
43
+ return { plugin, id, zipName, manifest };
44
+ }
45
+ async function buildAndInstall(opts = {}) {
46
+ const t = performance.now();
47
+ const { plugin, id, zipName, manifest } = await buildAndPack(opts);
48
+ const mode = await install(plugin, id, zipName, log);
49
+ const testApp = ctx.testApp();
50
+ if (testApp) await addToTestApp(testApp, id, log);
51
+ try {
52
+ await api('/k/v1/record/comment.json', 'POST', { app: appId, record: recordId, comment: { text: `v${manifest.version} を${mode}しました${testApp ? `(テスト用アプリ #${testApp} に反映)` : ''}\n${location.hostname} / ${id}` } });
53
+ } catch (e) { log.warn(`コメントに履歴を残せませんでした: ${apiError(e)}`); }
54
+ log.ok(`完了 (${((performance.now() - t) / 1000).toFixed(1)} 秒)${testApp ? ` /k/${testApp}/` : ''}`);
55
+ }
56
+ Object.assign(ctx, { buildOnly, buildAndPack, buildAndInstall });
57
+ }
@@ -1,54 +1,54 @@
1
- // 保存と、ブラウザへの下書き
2
- import { api, canInstall, uploadFile } from '../../kintone/api.js';
3
- import { kb } from '../../util/bytes.js';
4
- import { safeName } from '../../util/path.js';
5
- import { F } from '../../config.js';
6
-
7
- export function setupSave(ctx) {
8
- const { state, log, appId, recordId, draftKey } = ctx;
9
- let timer;
10
- function saveDraft() {
11
- clearTimeout(timer);
12
- timer = setTimeout(() => {
13
- try {
14
- if (state.dirty().length) localStorage.setItem(draftKey, JSON.stringify({ at: Date.now(), files: state.sourcePaths().map((p) => [p, state.files.get(p)]), dirs: [...state.dirs] }));
15
- else localStorage.removeItem(draftKey);
16
- } catch {}
17
- }, 500);
18
- }
19
- async function save() {
20
- if (ctx.settings.format) await ctx.formatFiles(state.sourcePaths());
21
- if (!(F.source in ctx.record)) throw new Error(`添付ファイルのフィールド「${F.source}」がありません(ソースの zip を保存する場所です)`);
22
- const zip = await state.toZip();
23
- const m = ctx.manifestInfo();
24
- const name = `${m ? safeName(m.name) : 'plugin'}-src.zip`;
25
- const update = { [F.source]: { value: [{ fileKey: await uploadFile(zip, name, 'application/zip') }] } };
26
- // 前の版のサブテーブルは、zip に移したら空にする
27
- const legacy = F.legacy && ctx.record[F.legacy.files];
28
- if (legacy && legacy.value.length) update[F.legacy.files] = { value: [] };
29
- await api('/k/v1/record.json', 'PUT', { app: appId, id: recordId, record: update });
30
- if (state.from === 'legacy') { log.ok('ソースをサブテーブルから zip に移しました'); state.from = 'zip'; }
31
- state.markSaved();
32
- ctx.savedOnce = true;
33
- ctx.record = await ctx.loadRecord();
34
- ctx.refreshStatus();
35
- log.ok(`保存しました: ${name} (${state.sourcePaths().length} ファイル, ${kb(zip.length)}。node_modules は入れません)`);
36
- if (ctx.settings.watch && canInstall()) await ctx.buildAndInstall({ skipSave: true });
37
- }
38
- // 前回の下書きがあれば戻す
39
- async function restoreDraft() {
40
- try {
41
- const draft = JSON.parse(localStorage.getItem(draftKey) || 'null');
42
- if (!draft || !draft.files) return;
43
- const src = state.sourcePaths();
44
- const differs = draft.files.length !== src.length || draft.files.some(([p, t]) => state.files.get(p) !== t);
45
- if (!differs || !(await ctx.confirm('保存していない下書きがあります', `${new Date(draft.at).toLocaleString()} の下書きです。戻しますか?`, { ok: '戻す' }))) return;
46
- const gone = src.filter((p) => !draft.files.some(([q]) => q === p));
47
- ctx.dropFiles(gone);
48
- ctx.addFiles(draft.files);
49
- for (const d of draft.dirs || []) if (!state.dirs.has(d)) ctx.makeFolder(d);
50
- log.ok('下書きを戻しました');
51
- } catch (e) { console.warn(e); }
52
- }
53
- Object.assign(ctx, { save, saveDraft, restoreDraft });
54
- }
1
+ // 保存と、ブラウザへの下書き
2
+ import { api, canInstall, uploadFile } from '../../kintone/api.js';
3
+ import { kb } from '../../util/bytes.js';
4
+ import { safeName } from '../../util/path.js';
5
+ import { F } from '../../config.js';
6
+
7
+ export function setupSave(ctx) {
8
+ const { state, log, appId, recordId, draftKey } = ctx;
9
+ let timer;
10
+ function saveDraft() {
11
+ clearTimeout(timer);
12
+ timer = setTimeout(() => {
13
+ try {
14
+ if (state.dirty().length) localStorage.setItem(draftKey, JSON.stringify({ at: Date.now(), files: state.sourcePaths().map((p) => [p, state.files.get(p)]), dirs: [...state.dirs] }));
15
+ else localStorage.removeItem(draftKey);
16
+ } catch {}
17
+ }, 500);
18
+ }
19
+ async function save() {
20
+ if (ctx.settings.format) await ctx.formatFiles(state.sourcePaths());
21
+ if (!(F.source in ctx.record)) throw new Error(`添付ファイルのフィールド「${F.source}」がありません(ソースの zip を保存する場所です)`);
22
+ const zip = await state.toZip();
23
+ const m = ctx.manifestInfo();
24
+ const name = `${m ? safeName(m.name) : 'plugin'}-src.zip`;
25
+ const update = { [F.source]: { value: [{ fileKey: await uploadFile(zip, name, 'application/zip') }] } };
26
+ // 前の版のサブテーブルは、zip に移したら空にする
27
+ const legacy = F.legacy && ctx.record[F.legacy.files];
28
+ if (legacy && legacy.value.length) update[F.legacy.files] = { value: [] };
29
+ await api('/k/v1/record.json', 'PUT', { app: appId, id: recordId, record: update });
30
+ if (state.from === 'legacy') { log.ok('ソースをサブテーブルから zip に移しました'); state.from = 'zip'; }
31
+ state.markSaved();
32
+ ctx.savedOnce = true;
33
+ ctx.record = await ctx.loadRecord();
34
+ ctx.refreshStatus();
35
+ log.ok(`保存しました: ${name} (${state.sourcePaths().length} ファイル, ${kb(zip.length)}。node_modules は入れません)`);
36
+ if (ctx.settings.watch && canInstall()) await ctx.buildAndInstall({ skipSave: true });
37
+ }
38
+ // 前回の下書きがあれば戻す
39
+ async function restoreDraft() {
40
+ try {
41
+ const draft = JSON.parse(localStorage.getItem(draftKey) || 'null');
42
+ if (!draft || !draft.files) return;
43
+ const src = state.sourcePaths();
44
+ const differs = draft.files.length !== src.length || draft.files.some(([p, t]) => state.files.get(p) !== t);
45
+ if (!differs || !(await ctx.confirm('保存していない下書きがあります', `${new Date(draft.at).toLocaleString()} の下書きです。戻しますか?`, { ok: '戻す' }))) return;
46
+ const gone = src.filter((p) => !draft.files.some(([q]) => q === p));
47
+ ctx.dropFiles(gone);
48
+ ctx.addFiles(draft.files);
49
+ for (const d of draft.dirs || []) if (!state.dirs.has(d)) ctx.makeFolder(d);
50
+ log.ok('下書きを戻しました');
51
+ } catch (e) { console.warn(e); }
52
+ }
53
+ Object.assign(ctx, { save, saveDraft, restoreDraft });
54
+ }
@@ -1,59 +1,59 @@
1
- // zip の取り込み・書き出し・ドラッグ&ドロップ
2
- import { zipSync, unzipSync } from 'fflate';
3
- import { unpack } from '../../packer/packer.js';
4
- import { fromBytes, toBytes } from '../../util/bytes.js';
5
- import { downloadBlob, pickFile } from '../../util/dom.js';
6
- import { dirname, normalize, safeName, isVendor } from '../../util/path.js';
7
-
8
- export function setupZip(ctx) {
9
- const { state, log, ui } = ctx;
10
-
11
- async function importZipBytes(bytes, name) {
12
- const unpacked = await unpack(bytes).catch(() => null);
13
- let entries;
14
- if (unpacked) {
15
- log.info(`${name} はプラグインです(署名 ${unpacked.verified ? 'OK' : 'NG'}, ID ${unpacked.id})。中身を取り込みます`);
16
- entries = unpacked.contents;
17
- } else entries = unzipSync(bytes);
18
- const paths = Object.keys(entries).filter((p) => !p.endsWith('/') && !p.startsWith('__MACOSX/') && !/(^|\/)\.DS_Store$/.test(p) && !/\.ppk$/.test(p));
19
- // フォルダごと固めた zip("my-plugin/manifest.json")なら、そのフォルダを根にする
20
- const mf = paths.filter((p) => /(^|\/)manifest\.json$/.test(p) && !p.includes('node_modules/')).sort((a, b) => a.length - b.length)[0];
21
- const root = mf ? mf.slice(0, -'manifest.json'.length) : '';
22
- const list = paths.filter((p) => p.startsWith(root)).map((p) => [normalize(p.slice(root.length)), entries[p]])
23
- .filter(([p]) => !isVendor(p)).map(([p, b]) => [p, fromBytes(b)]);
24
- if (!list.length) throw new Error('取り込めるファイルがありませんでした');
25
- if (state.sourcePaths().length && !(await ctx.confirm(`${list.length} 個のファイルを取り込みます`, '同じパスのファイルは上書きされます', { ok: '取り込む' }))) return;
26
- ctx.addFiles(list);
27
- ctx.preloadModels();
28
- log.ok(`${list.length} 個のファイルを取り込みました(保存すると残ります。node_modules は npm install で入れ直します)`);
29
- if (entries.PUBKEY) log.warn('秘密鍵はプラグインの zip には入っていません。同じIDのまま更新するには、元の .ppk を秘密鍵のフィールドに添付してください');
30
- if (list.some(([p]) => p === 'package.json')) await ctx.npmRestore();
31
- }
32
- async function importZip() {
33
- const file = await pickFile('.zip');
34
- if (file) await importZipBytes(new Uint8Array(await file.arrayBuffer()), file.name);
35
- }
36
- async function exportZip() {
37
- const entries = {}; for (const p of state.sourcePaths()) entries[p] = toBytes(state.files.get(p));
38
- const m = ctx.manifestInfo();
39
- const name = `${m ? safeName(m.name) : 'plugin'}-${m ? m.version : '0'}-src.zip`;
40
- downloadBlob(zipSync(entries, { level: 9 }), name);
41
- log.ok(`ソースを書き出しました: ${name}(node_modules は入れていません)`);
42
- }
43
- for (const target of [ui.editorEl, ui.treeEl]) {
44
- target.addEventListener('dragover', (e) => { if ([...e.dataTransfer.items].some((i) => i.kind === 'file')) { e.preventDefault(); ui.editorEl.classList.add('drop'); } });
45
- target.addEventListener('dragleave', () => ui.editorEl.classList.remove('drop'));
46
- target.addEventListener('drop', (e) => {
47
- const list = [...e.dataTransfer.files];
48
- const f = list[0];
49
- ui.editorEl.classList.remove('drop');
50
- if (!f) return;
51
- e.preventDefault();
52
- ctx.run(async () => {
53
- if (/\.zip$/i.test(f.name)) await importZipBytes(new Uint8Array(await f.arrayBuffer()), f.name);
54
- else await ctx.uploadFiles(ctx.current && !isVendor(ctx.current) ? dirname(ctx.current) : '', list);
55
- });
56
- }, true);
57
- }
58
- Object.assign(ctx, { importZip, exportZip });
59
- }
1
+ // zip の取り込み・書き出し・ドラッグ&ドロップ
2
+ import { zipSync, unzipSync } from 'fflate';
3
+ import { unpack } from '../../packer/packer.js';
4
+ import { fromBytes, toBytes } from '../../util/bytes.js';
5
+ import { downloadBlob, pickFile } from '../../util/dom.js';
6
+ import { dirname, normalize, safeName, isVendor } from '../../util/path.js';
7
+
8
+ export function setupZip(ctx) {
9
+ const { state, log, ui } = ctx;
10
+
11
+ async function importZipBytes(bytes, name) {
12
+ const unpacked = await unpack(bytes).catch(() => null);
13
+ let entries;
14
+ if (unpacked) {
15
+ log.info(`${name} はプラグインです(署名 ${unpacked.verified ? 'OK' : 'NG'}, ID ${unpacked.id})。中身を取り込みます`);
16
+ entries = unpacked.contents;
17
+ } else entries = unzipSync(bytes);
18
+ const paths = Object.keys(entries).filter((p) => !p.endsWith('/') && !p.startsWith('__MACOSX/') && !/(^|\/)\.DS_Store$/.test(p) && !/\.ppk$/.test(p));
19
+ // フォルダごと固めた zip("my-plugin/manifest.json")なら、そのフォルダを根にする
20
+ const mf = paths.filter((p) => /(^|\/)manifest\.json$/.test(p) && !p.includes('node_modules/')).sort((a, b) => a.length - b.length)[0];
21
+ const root = mf ? mf.slice(0, -'manifest.json'.length) : '';
22
+ const list = paths.filter((p) => p.startsWith(root)).map((p) => [normalize(p.slice(root.length)), entries[p]])
23
+ .filter(([p]) => !isVendor(p)).map(([p, b]) => [p, fromBytes(b)]);
24
+ if (!list.length) throw new Error('取り込めるファイルがありませんでした');
25
+ if (state.sourcePaths().length && !(await ctx.confirm(`${list.length} 個のファイルを取り込みます`, '同じパスのファイルは上書きされます', { ok: '取り込む' }))) return;
26
+ ctx.addFiles(list);
27
+ ctx.preloadModels();
28
+ log.ok(`${list.length} 個のファイルを取り込みました(保存すると残ります。node_modules は npm install で入れ直します)`);
29
+ if (entries.PUBKEY) log.warn('秘密鍵はプラグインの zip には入っていません。同じIDのまま更新するには、元の .ppk を秘密鍵のフィールドに添付してください');
30
+ if (list.some(([p]) => p === 'package.json')) await ctx.npmRestore();
31
+ }
32
+ async function importZip() {
33
+ const file = await pickFile('.zip');
34
+ if (file) await importZipBytes(new Uint8Array(await file.arrayBuffer()), file.name);
35
+ }
36
+ async function exportZip() {
37
+ const entries = {}; for (const p of state.sourcePaths()) entries[p] = toBytes(state.files.get(p));
38
+ const m = ctx.manifestInfo();
39
+ const name = `${m ? safeName(m.name) : 'plugin'}-${m ? m.version : '0'}-src.zip`;
40
+ downloadBlob(zipSync(entries, { level: 9 }), name);
41
+ log.ok(`ソースを書き出しました: ${name}(node_modules は入れていません)`);
42
+ }
43
+ for (const target of [ui.editorEl, ui.treeEl]) {
44
+ target.addEventListener('dragover', (e) => { if ([...e.dataTransfer.items].some((i) => i.kind === 'file')) { e.preventDefault(); ui.editorEl.classList.add('drop'); } });
45
+ target.addEventListener('dragleave', () => ui.editorEl.classList.remove('drop'));
46
+ target.addEventListener('drop', (e) => {
47
+ const list = [...e.dataTransfer.files];
48
+ const f = list[0];
49
+ ui.editorEl.classList.remove('drop');
50
+ if (!f) return;
51
+ e.preventDefault();
52
+ ctx.run(async () => {
53
+ if (/\.zip$/i.test(f.name)) await importZipBytes(new Uint8Array(await f.arrayBuffer()), f.name);
54
+ else await ctx.uploadFiles(ctx.current && !isVendor(ctx.current) ? dirname(ctx.current) : '', list);
55
+ });
56
+ }, true);
57
+ }
58
+ Object.assign(ctx, { importZip, exportZip });
59
+ }
@@ -1,96 +1,96 @@
1
- // ターミナルのコマンド
2
- import { downloadBlob } from '../util/dom.js';
3
- import { normalize } from '../util/path.js';
4
- import { saveSettings } from '../util/settings.js';
5
- import { SAMPLES } from './sample.js';
6
-
7
- export const HELP = [
8
- ['npm install <pkg>[@ver] ...', 'node_modules に入れて package.json に固定。引数なしで package.json の通りにそろえる'],
9
- ['npm install --force', 'キャッシュを使わずに全部取り直す'],
10
- ['npm uninstall <pkg>', '依存を外す'],
11
- ['npm ls / npm outdated / npm view <pkg>', '依存の一覧 / 更新の確認 / 情報'],
12
- ['build [--prod]', 'ビルドだけ(Ctrl/Cmd+B)'],
13
- ['pack', 'ビルドしてパッケージ(レコードに保存)'],
14
- ['install', '保存 → ビルド → パッケージ → インストール → 反映(Ctrl/Cmd+Enter)'],
15
- ['download', 'プラグインの zip をダウンロード'],
16
- ['check', '型チェック'],
17
- ['format [path]', 'prettier で整形(Alt+Shift+F)。引数なしで全部'],
18
- ['version <patch|minor|major|x.y.z>', 'manifest.json と package.json のバージョンを上げる'],
19
- ['grep <text|/regex/> [--all]', 'ファイルの中身を検索(Ctrl/Cmd+Shift+F)'],
20
- ['open <path>', 'ファイルを開く(Ctrl/Cmd+P でファイル名検索)'],
21
- ['touch <path> / mkdir <path>', 'ファイル / フォルダを作る'],
22
- ['upload [dir]', '画像などのファイルをアップロード(パスを指定)'],
23
- ['sample <ts|svelte|vue>', 'サンプルに入れ替える(.svelte / .vue / .scss / .less / .yaml はそのままビルドできる)'],
24
- ['diff [path] / diff off', '保存した内容と比べる'],
25
- ['import / export', 'zip を取り込む(プラグイン zip も可) / ソースを zip で書き出す'],
26
- ['testapp <id> / app', 'テスト用アプリを設定 / 開く'],
27
- ['plugin ls / plugin apps / plugin rm', 'インストール済み一覧 / 追加しているアプリ / アンインストール'],
28
- ['history', 'インストールの履歴(レコードのコメント)'],
29
- ['set <prod|typecheck|format|watch> <on|off>', '設定を切り替える(下のバーでも切り替えられる)'],
30
- ['save / clear / help', ''],
31
- ];
32
-
33
- export function setupCommands(ctx) {
34
- const { log, settings, state } = ctx;
35
- async function command(line) {
36
- const all = line.trim().match(/"[^"]*"|\S+/g)?.map((a) => a.replace(/^"|"$/g, '')) || [];
37
- const flags = all.filter((a) => a.startsWith('--'));
38
- const args = all.filter((a) => !a.startsWith('--'));
39
- const [cmd, sub, ...rest] = args;
40
- if (!cmd) return;
41
- switch (cmd) {
42
- case 'npm':
43
- if (['install', 'i', 'add', 'ci'].includes(sub)) return ctx.npmInstall(sub === 'ci' ? [] : rest, sub === 'ci' ? ['--force'] : flags);
44
- if (['uninstall', 'remove', 'rm', 'un'].includes(sub)) return ctx.npmUninstall(rest);
45
- if (['ls', 'list'].includes(sub)) return ctx.npmLs();
46
- if (sub === 'outdated') return ctx.npmOutdated();
47
- if (['view', 'info', 'show'].includes(sub)) return ctx.npmView(rest[0]);
48
- return log.error(`npm ${sub || ''} には対応していません(install / ci / uninstall / ls / outdated / view)`);
49
- case 'build': return ctx.buildOnly({ prod: flags.includes('--prod') || settings.prod });
50
- case 'pack': return ctx.buildAndPack();
51
- case 'install': return ctx.buildAndInstall();
52
- case 'download': { const r = await ctx.buildAndPack(); downloadBlob(r.plugin, r.zipName); return; }
53
- case 'check': return ctx.typecheck();
54
- case 'format': return ctx.formatFiles(sub ? [normalize(sub)] : state.sourcePaths());
55
- case 'version': return ctx.bumpVersion(sub || 'patch');
56
- case 'grep': case 'search': return ctx.grep(args.slice(1).join(' '), { all: flags.includes('--all') });
57
- case 'open': return ctx.openFile(normalize(sub || ''));
58
- case 'touch': { const p = normalize(sub || ''); if (!p) return log.warn('touch <path>'); if (!state.files.has(p)) ctx.addFiles([[p, '']]); return ctx.openFile(p); }
59
- case 'mkdir': return sub ? ctx.makeFolder(normalize(sub)) : log.warn('mkdir <path>');
60
- case 'sample': {
61
- const files = SAMPLES[sub];
62
- if (!files) return log.error(`sample ${Object.keys(SAMPLES).join(' | ')}`);
63
- const cur = state.sourcePaths();
64
- if (cur.length && !(await ctx.confirm(`${sub} のサンプルに入れ替えます`, `今のファイル(${cur.length} 個)は消えます。保存するまでレコードは変わりません`, { ok: '入れ替える', danger: true }))) return;
65
- ctx.dropFiles(cur);
66
- ctx.addFiles(Object.entries(files));
67
- ctx.preloadModels();
68
- ctx.openFile('src/desktop.ts');
69
- log.ok(`${sub} のサンプルを入れました`);
70
- return ctx.npmRestore();
71
- }
72
- case 'upload': return ctx.uploadFiles(sub ? normalize(sub) : '');
73
- case 'diff': return sub === 'off' ? ctx.closeDiff() : ctx.showDiff(sub ? normalize(sub) : ctx.current);
74
- case 'import': return ctx.importZip();
75
- case 'export': return ctx.exportZip();
76
- case 'testapp': return ctx.setTestApp(sub);
77
- case 'app': { const a = ctx.testApp(); return a ? window.open(`/k/${a}/`, '_blank') : log.warn('テスト用アプリが未設定です(testapp <id>)'); }
78
- case 'plugin':
79
- if (['ls', 'list'].includes(sub)) return ctx.pluginList();
80
- if (sub === 'apps') return ctx.pluginApps();
81
- if (['rm', 'uninstall'].includes(sub)) return ctx.pluginUninstall();
82
- return log.error('plugin ls / plugin apps / plugin rm');
83
- case 'history': return ctx.history();
84
- case 'set':
85
- if (!(sub in settings)) return log.error(`設定は ${Object.keys(settings).join(' / ')} です`);
86
- settings[sub] = rest[0] !== 'off'; saveSettings(settings); ctx.updateStatus(); return log.ok(`${sub}: ${settings[sub] ? 'ON' : 'OFF'}`);
87
- case 'save': return ctx.save();
88
- case 'clear': ctx.term.clear(); return;
89
- case 'help': case '?':
90
- for (const [c, d] of HELP) log.plain(` \x1b[36m${c.padEnd(42)}\x1b[0m ${d}`);
91
- return;
92
- default: return log.error(`知らないコマンドです: ${cmd}(help で一覧)`);
93
- }
94
- }
95
- ctx.command = command;
96
- }
1
+ // ターミナルのコマンド
2
+ import { downloadBlob } from '../util/dom.js';
3
+ import { normalize } from '../util/path.js';
4
+ import { saveSettings } from '../util/settings.js';
5
+ import { SAMPLES } from './sample.js';
6
+
7
+ export const HELP = [
8
+ ['npm install <pkg>[@ver] ...', 'node_modules に入れて package.json に固定。引数なしで package.json の通りにそろえる'],
9
+ ['npm install --force', 'キャッシュを使わずに全部取り直す'],
10
+ ['npm uninstall <pkg>', '依存を外す'],
11
+ ['npm ls / npm outdated / npm view <pkg>', '依存の一覧 / 更新の確認 / 情報'],
12
+ ['build [--prod]', 'ビルドだけ(Ctrl/Cmd+B)'],
13
+ ['pack', 'ビルドしてパッケージ(レコードに保存)'],
14
+ ['install', '保存 → ビルド → パッケージ → インストール → 反映(Ctrl/Cmd+Enter)'],
15
+ ['download', 'プラグインの zip をダウンロード'],
16
+ ['check', '型チェック'],
17
+ ['format [path]', 'prettier で整形(Alt+Shift+F)。引数なしで全部'],
18
+ ['version <patch|minor|major|x.y.z>', 'manifest.json と package.json のバージョンを上げる'],
19
+ ['grep <text|/regex/> [--all]', 'ファイルの中身を検索(Ctrl/Cmd+Shift+F)'],
20
+ ['open <path>', 'ファイルを開く(Ctrl/Cmd+P でファイル名検索)'],
21
+ ['touch <path> / mkdir <path>', 'ファイル / フォルダを作る'],
22
+ ['upload [dir]', '画像などのファイルをアップロード(パスを指定)'],
23
+ ['sample <ts|svelte|vue>', 'サンプルに入れ替える(.svelte / .vue / .scss / .less / .yaml はそのままビルドできる)'],
24
+ ['diff [path] / diff off', '保存した内容と比べる'],
25
+ ['import / export', 'zip を取り込む(プラグイン zip も可) / ソースを zip で書き出す'],
26
+ ['testapp <id> / app', 'テスト用アプリを設定 / 開く'],
27
+ ['plugin ls / plugin apps / plugin rm', 'インストール済み一覧 / 追加しているアプリ / アンインストール'],
28
+ ['history', 'インストールの履歴(レコードのコメント)'],
29
+ ['set <prod|typecheck|format|watch> <on|off>', '設定を切り替える(下のバーでも切り替えられる)'],
30
+ ['save / clear / help', ''],
31
+ ];
32
+
33
+ export function setupCommands(ctx) {
34
+ const { log, settings, state } = ctx;
35
+ async function command(line) {
36
+ const all = line.trim().match(/"[^"]*"|\S+/g)?.map((a) => a.replace(/^"|"$/g, '')) || [];
37
+ const flags = all.filter((a) => a.startsWith('--'));
38
+ const args = all.filter((a) => !a.startsWith('--'));
39
+ const [cmd, sub, ...rest] = args;
40
+ if (!cmd) return;
41
+ switch (cmd) {
42
+ case 'npm':
43
+ if (['install', 'i', 'add', 'ci'].includes(sub)) return ctx.npmInstall(sub === 'ci' ? [] : rest, sub === 'ci' ? ['--force'] : flags);
44
+ if (['uninstall', 'remove', 'rm', 'un'].includes(sub)) return ctx.npmUninstall(rest);
45
+ if (['ls', 'list'].includes(sub)) return ctx.npmLs();
46
+ if (sub === 'outdated') return ctx.npmOutdated();
47
+ if (['view', 'info', 'show'].includes(sub)) return ctx.npmView(rest[0]);
48
+ return log.error(`npm ${sub || ''} には対応していません(install / ci / uninstall / ls / outdated / view)`);
49
+ case 'build': return ctx.buildOnly({ prod: flags.includes('--prod') || settings.prod });
50
+ case 'pack': return ctx.buildAndPack();
51
+ case 'install': return ctx.buildAndInstall();
52
+ case 'download': { const r = await ctx.buildAndPack(); downloadBlob(r.plugin, r.zipName); return; }
53
+ case 'check': return ctx.typecheck();
54
+ case 'format': return ctx.formatFiles(sub ? [normalize(sub)] : state.sourcePaths());
55
+ case 'version': return ctx.bumpVersion(sub || 'patch');
56
+ case 'grep': case 'search': return ctx.grep(args.slice(1).join(' '), { all: flags.includes('--all') });
57
+ case 'open': return ctx.openFile(normalize(sub || ''));
58
+ case 'touch': { const p = normalize(sub || ''); if (!p) return log.warn('touch <path>'); if (!state.files.has(p)) ctx.addFiles([[p, '']]); return ctx.openFile(p); }
59
+ case 'mkdir': return sub ? ctx.makeFolder(normalize(sub)) : log.warn('mkdir <path>');
60
+ case 'sample': {
61
+ const files = SAMPLES[sub];
62
+ if (!files) return log.error(`sample ${Object.keys(SAMPLES).join(' | ')}`);
63
+ const cur = state.sourcePaths();
64
+ if (cur.length && !(await ctx.confirm(`${sub} のサンプルに入れ替えます`, `今のファイル(${cur.length} 個)は消えます。保存するまでレコードは変わりません`, { ok: '入れ替える', danger: true }))) return;
65
+ ctx.dropFiles(cur);
66
+ ctx.addFiles(Object.entries(files));
67
+ ctx.preloadModels();
68
+ ctx.openFile('src/desktop.ts');
69
+ log.ok(`${sub} のサンプルを入れました`);
70
+ return ctx.npmRestore();
71
+ }
72
+ case 'upload': return ctx.uploadFiles(sub ? normalize(sub) : '');
73
+ case 'diff': return sub === 'off' ? ctx.closeDiff() : ctx.showDiff(sub ? normalize(sub) : ctx.current);
74
+ case 'import': return ctx.importZip();
75
+ case 'export': return ctx.exportZip();
76
+ case 'testapp': return ctx.setTestApp(sub);
77
+ case 'app': { const a = ctx.testApp(); return a ? window.open(`/k/${a}/`, '_blank') : log.warn('テスト用アプリが未設定です(testapp <id>)'); }
78
+ case 'plugin':
79
+ if (['ls', 'list'].includes(sub)) return ctx.pluginList();
80
+ if (sub === 'apps') return ctx.pluginApps();
81
+ if (['rm', 'uninstall'].includes(sub)) return ctx.pluginUninstall();
82
+ return log.error('plugin ls / plugin apps / plugin rm');
83
+ case 'history': return ctx.history();
84
+ case 'set':
85
+ if (!(sub in settings)) return log.error(`設定は ${Object.keys(settings).join(' / ')} です`);
86
+ settings[sub] = rest[0] !== 'off'; saveSettings(settings); ctx.updateStatus(); return log.ok(`${sub}: ${settings[sub] ? 'ON' : 'OFF'}`);
87
+ case 'save': return ctx.save();
88
+ case 'clear': ctx.term.clear(); return;
89
+ case 'help': case '?':
90
+ for (const [c, d] of HELP) log.plain(` \x1b[36m${c.padEnd(42)}\x1b[0m ${d}`);
91
+ return;
92
+ default: return log.error(`知らないコマンドです: ${cmd}(help で一覧)`);
93
+ }
94
+ }
95
+ ctx.command = command;
96
+ }