kintone-plugin-ide 0.3.0 → 0.4.0

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,173 +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();
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 CHANGED
@@ -1,48 +1,49 @@
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.0');
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
- }
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.4.0');
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, packFiles, unpack, idFromSpki, publicKeyFromPpk } from 'kintone-plugin-web-signer';
19
+ export { browserPlugin } from 'esbuild-plugin-browser';
20
+ export { install, addToTestApp, deployApp } from './kintone/plugin.js';
21
+
22
+ const open = () => openIDE().catch((e) => { console.error(e); alert('IDEを開けませんでした\n' + e.message); });
23
+
24
+ // 詳細画面のヘッダーに「IDEで開く」を出す。URL に ide=1 があれば自動で開く
25
+ function attach() {
26
+ const space = kintone.app.record.getHeaderMenuSpaceElement();
27
+ if (space && !space.querySelector('.kpi-open')) {
28
+ const b = el('button', { className: 'kpi-open kintoneplugin-button-normal', textContent: 'IDEで開く' });
29
+ b.onclick = open;
30
+ space.append(b);
31
+ }
32
+ if (/[?&#]ide=1\b/.test(location.href) && !document.querySelector('.kpi-root')) setTimeout(open, 0);
33
+ }
34
+
35
+ let registered = false;
36
+ /**
37
+ * @param {import('../types/index.d.ts').SetupOptions} [options]
38
+ */
39
+ export function setup(options = {}) {
40
+ configure(options);
41
+ window.__openKintonePluginIDE = openIDE;
42
+ if (!registered) {
43
+ registered = true;
44
+ kintone.events.on('app.record.detail.show', (event) => { attach(); return event; });
45
+ }
46
+ // CDN から読むと、詳細画面の表示イベントが先に終わっていることがある。その場合はここで出す
47
+ try { if (kintone.app.record.getId()) attach(); } catch {}
48
+ return { open: openIDE, config: CONFIG };
49
+ }
@@ -1,24 +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
- }
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
+ }
@@ -1,37 +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
- }
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
+ }