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,168 +0,0 @@
1
- // esbuild に渡す前に変換するファイル(コンパイラは使う時に CDN から読む)
2
- // .svelte Svelte 5 のコンポーネント(CSS は JS に入れて実行時に差し込む)
3
- // .svelte.ts/.svelte.js Svelte 5 のルーン入りモジュール
4
- // .vue Vue 3 の SFC(<script setup> / TS / scoped CSS / <style lang="scss">)
5
- // .scss / .sass / .less CSS に
6
- // .yaml / .yml export default のオブジェクトに
7
- // svelte と vue のコンパイラは、package.json に書いたランタイムと同じバージョンを使う。
8
- import { dirname, normalize } from '../util/path.js';
9
- import { isBinary } from '../util/bytes.js';
10
-
11
- export const TRANSFORM_EXT = /\.(svelte|svelte\.[jt]s|vue|s[ac]ss|less|ya?ml)$/;
12
-
13
- const lineCol = (text, offset) => {
14
- const before = text.slice(0, offset).split('\n');
15
- return { line: before.length, column: before[before.length - 1].length };
16
- };
17
- const fail = (path, message, loc) => ({ errors: [{ text: message, location: loc ? { file: path, line: loc.line, column: loc.column ?? 0 } : { file: path } }] });
18
- const injectCss = (css, id) => css.trim()
19
- ? `\n;(()=>{if(typeof document==='undefined'||document.getElementById(${JSON.stringify(id)}))return;const s=document.createElement('style');s.id=${JSON.stringify(id)};s.textContent=${JSON.stringify(css)};document.head.appendChild(s)})();\n`
20
- : '';
21
- const hashId = (s) => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; return h.toString(36); };
22
-
23
- /**
24
- * @param {object} o
25
- * @param {Map<string,string>} o.files
26
- * @param {(name:string, range?:string)=>Promise<any>} o.load コンパイラを読む(deps.js の loadCompiler)
27
- * @param {object} o.esbuild esbuild(TS を剥がすのに使う)
28
- * @param {Record<string,string>} o.deps package.json の dependencies
29
- */
30
- export function createTransformer({ files, log, prod, load, esbuild, deps }) {
31
- const need = (name) => {
32
- if (!deps[name]) throw new Error(`${name} が package.json にありません。npm install ${name} してください(ランタイムとコンパイラのバージョンをそろえるため)`);
33
- return deps[name];
34
- };
35
-
36
- // ---- Sass ----
37
- async function compileSass(path, text) {
38
- const sass = await load('sass');
39
- const toUrl = (p) => new URL(`file:///${p}`);
40
- const candidates = (p) => {
41
- const d = dirname(p), b = p.split('/').pop();
42
- const bases = /\.(s[ac]ss|css)$/.test(b) ? [p] : [`${p}.scss`, `${p}.sass`, `${p}.css`, `${d ? d + '/' : ''}_${b}.scss`, `${d ? d + '/' : ''}_${b}.sass`, `${p}/index.scss`, `${p}/_index.scss`];
43
- return bases.map(normalize);
44
- };
45
- const importer = {
46
- canonicalize(url, ctx) {
47
- const base = ctx && ctx.containingUrl ? ctx.containingUrl.pathname.slice(1) : path;
48
- const raw = url.startsWith('file:///') ? url.slice(8) : normalize(`${dirname(base)}/${url}`);
49
- const hit = candidates(raw).find((c) => files.has(c));
50
- return hit ? toUrl(hit) : null;
51
- },
52
- load(u) {
53
- const p = decodeURIComponent(u.pathname.slice(1));
54
- return { contents: files.get(p), syntax: p.endsWith('.sass') ? 'indented' : p.endsWith('.css') ? 'css' : 'scss' };
55
- },
56
- };
57
- try {
58
- const r = sass.compileString(text, { url: toUrl(path), syntax: path.endsWith('.sass') ? 'indented' : 'scss', importers: [importer], style: prod ? 'compressed' : 'expanded', silenceDeprecations: ['import'] });
59
- return r.css;
60
- } catch (e) {
61
- const s = e.span;
62
- throw Object.assign(new Error(e.sassMessage || e.message), { loc: s ? { line: s.start.line + 1, column: s.start.column } : null, file: s && s.url ? s.url.pathname.slice(1) : path });
63
- }
64
- }
65
-
66
- // ---- Less ----
67
- async function compileLess(path, text) {
68
- const mod = await load('less');
69
- const less = mod.default || mod;
70
- const vfs = {
71
- install(lessObj, pm) {
72
- class VfsFileManager extends lessObj.FileManager {
73
- supports() { return true; }
74
- supportsSync() { return false; }
75
- loadFile(filename, currentDirectory) {
76
- const base = normalize(`${currentDirectory || dirname(path)}/${filename}`);
77
- const hit = [base, `${base}.less`, `${base}.css`].find((c) => files.has(c));
78
- return hit ? Promise.resolve({ contents: files.get(hit), filename: hit }) : Promise.reject({ type: 'File', message: `ファイルが見つかりません: ${filename}` });
79
- }
80
- }
81
- pm.addFileManager(new VfsFileManager());
82
- },
83
- };
84
- try {
85
- return (await less.render(text, { filename: path, plugins: [vfs], compress: prod })).css;
86
- } catch (e) {
87
- throw Object.assign(new Error(e.message), { loc: e.line ? { line: e.line, column: e.column || 0 } : null, file: e.filename || path });
88
- }
89
- }
90
-
91
- // ---- Svelte ----
92
- async function compileSvelte(path, text) {
93
- const svelte = await load('svelte', need('svelte'));
94
- const warn = (w) => log.warn(`${path}${w.start ? `:${w.start.line}:${w.start.column + 1}` : ''} ${w.message}`);
95
- try {
96
- if (/\.svelte\.[jt]s$/.test(path)) {
97
- const js = path.endsWith('.ts') ? (await esbuild.transform(text, { loader: 'ts', sourcefile: path })).code : text;
98
- const r = svelte.compileModule(js, { filename: path, generate: 'client', dev: !prod });
99
- r.warnings.forEach(warn);
100
- return { contents: r.js.code, loader: 'js' };
101
- }
102
- const r = svelte.compile(text, { filename: path, generate: 'client', dev: !prod, css: 'injected' });
103
- r.warnings.forEach(warn);
104
- return { contents: r.js.code, loader: 'js' };
105
- } catch (e) {
106
- throw Object.assign(new Error(e.message), { loc: e.start ? { line: e.start.line, column: e.start.column } : null });
107
- }
108
- }
109
-
110
- // ---- Vue ----
111
- async function compileVue(path, text) {
112
- const sfc = await load('vue', need('vue'));
113
- const { descriptor, errors } = sfc.parse(text, { filename: path });
114
- if (errors.length) {
115
- const e = errors[0];
116
- throw Object.assign(new Error(e.message), { loc: e.loc ? { line: e.loc.start.line, column: e.loc.start.column - 1 } : null });
117
- }
118
- const id = hashId(path);
119
- const scoped = descriptor.styles.some((s) => s.scoped);
120
- let code = '', lang = 'js';
121
- if (descriptor.script || descriptor.scriptSetup) {
122
- const s = sfc.compileScript(descriptor, { id, inlineTemplate: true, isProd: prod, genDefaultAs: '__sfc__', templateOptions: { compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } } });
123
- code = s.content;
124
- lang = /tsx?/.test((descriptor.scriptSetup || descriptor.script).lang || '') ? 'ts' : 'js';
125
- } else code = 'const __sfc__ = {};';
126
- if (descriptor.template && !descriptor.scriptSetup) {
127
- const t = sfc.compileTemplate({ source: descriptor.template.content, filename: path, id, scoped, isProd: prod, compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } });
128
- if (t.errors.length) throw new Error(String(t.errors[0].message || t.errors[0]));
129
- code += `\n${t.code.replace(/\nexport (function|const) (render|ssrRender)/, '\n$1 $2')}\n__sfc__.render = render;`;
130
- }
131
- if (scoped) code += `\n__sfc__.__scopeId = "data-v-${id}";`;
132
- let css = '';
133
- for (const st of descriptor.styles) {
134
- let source = st.content;
135
- if (/^s[ac]ss$/.test(st.lang || '')) source = await compileSass(`${path}.${st.lang}`, source);
136
- else if (st.lang === 'less') source = await compileLess(`${path}.less`, source);
137
- const r = sfc.compileStyle({ source, filename: path, id: `data-v-${id}`, scoped: st.scoped, isProd: prod });
138
- if (r.errors.length) throw new Error(String(r.errors[0].message || r.errors[0]));
139
- css += r.code + '\n';
140
- }
141
- code += injectCss(css, `vue-${id}`);
142
- code += '\nexport default __sfc__;\n';
143
- return { contents: code, loader: lang };
144
- }
145
-
146
- // ---- YAML ----
147
- async function compileYaml(path, text) {
148
- const yaml = await load('yaml');
149
- try { return { contents: `export default ${JSON.stringify((yaml.load || yaml.default.load)(text))};`, loader: 'js' }; }
150
- catch (e) { throw Object.assign(new Error(e.reason || e.message), { loc: e.mark ? { line: e.mark.line + 1, column: e.mark.column } : null }); }
151
- }
152
-
153
- /** @returns {Promise<{contents:string, loader:string, resolveDir:string}|{errors:any[]}|null>} */
154
- return async function transform(path, text) {
155
- if (!TRANSFORM_EXT.test(path) || isBinary(text)) return null;
156
- try {
157
- let r;
158
- if (/\.svelte(\.[jt]s)?$/.test(path)) r = await compileSvelte(path, text);
159
- else if (path.endsWith('.vue')) r = await compileVue(path, text);
160
- else if (/\.s[ac]ss$/.test(path)) r = { contents: await compileSass(path, text), loader: 'css' };
161
- else if (path.endsWith('.less')) r = { contents: await compileLess(path, text), loader: 'css' };
162
- else r = await compileYaml(path, text);
163
- return { ...r, resolveDir: '/' + dirname(path) };
164
- } catch (e) {
165
- return fail(e.file || path, e.message.split('\n')[0], e.loc);
166
- }
167
- };
168
- }
@@ -1,60 +0,0 @@
1
- // esbuild: IDE の中のファイル(Map)を読む。npm のパッケージは node_modules/ から
2
- import { dirname, ext, normalize } from '../util/path.js';
3
- import { isBinary, toBytes } from '../util/bytes.js';
4
- import { parseSpecifier, readPackageJson, npmUrl } from '../npm/registry.js';
5
- import { pkgDir, subFile } from '../npm/vendor.js';
6
- import { httpPlugin } from './http-plugin.js';
7
- import { SHARED_RUNTIMES } from '../config.js';
8
-
9
- const LOADERS = { ts: 'ts', mts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', jsx: 'jsx', json: 'json', css: 'css', svg: 'text', html: 'text', txt: 'text', md: 'text' };
10
- const EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json', '.css', '.svelte.ts', '.svelte.js', '/index.ts', '/index.tsx', '/index.js'];
11
-
12
- /**
13
- * @param {Map<string,string>} files
14
- * @param {{ vendor?: (name: string, sub: string) => Promise<string|null>, transform?: Function }} opts
15
- * vendor: node_modules に無いものを取ってきて置き、そのパスを返す(IDE から渡す)
16
- * transform: .svelte / .vue などを変換する(transformers.js)
17
- */
18
- export function vfsPlugin(files, log, { vendor, transform } = {}) {
19
- const deps = readPackageJson(files).dependencies;
20
- const warned = new Set();
21
- const http = httpPlugin(log);
22
- return {
23
- name: 'kintone-vfs',
24
- setup(b) {
25
- http.setup(b);
26
- b.onResolve({ filter: /^(\.{0,2}\/|[^@\w])/ }, (a) => {
27
- if (a.namespace === 'http') return undefined;
28
- const base = normalize(a.path.startsWith('/') ? a.path : `${dirname(a.importer)}/${a.path}`);
29
- for (const e of EXTS) if (files.has(base + e)) return { path: base + e, namespace: 'vfs' };
30
- // ESM の書き方("./foo.js" と書いて foo.ts を指す)
31
- const ts = base.replace(/\.js$/, '.ts');
32
- if (ts !== base && files.has(ts)) return { path: ts, namespace: 'vfs' };
33
- return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
34
- });
35
- b.onResolve({ filter: /^[@\w]/ }, async (a) => {
36
- if (a.kind === 'entry-point') return { path: normalize(a.path), namespace: 'vfs' };
37
- if (a.namespace === 'http') return undefined;
38
- const { name, sub } = parseSpecifier(a.path);
39
- if (!deps[name]) {
40
- if (!warned.has(name)) { warned.add(name); log.warn(`${name} が package.json にありません(最新版を CDN から直接使います)。npm install ${name} で node_modules に入ります`); }
41
- return { path: npmUrl(name, '', sub), namespace: 'http' };
42
- }
43
- if (SHARED_RUNTIMES.test(name)) return { path: npmUrl(name, deps[name], sub, { shared: true }), namespace: 'http' };
44
- const target = sub ? subFile(name, sub) : `${pkgDir(name)}index.mjs`;
45
- if (files.has(target)) return { path: target, namespace: 'vfs' };
46
- const got = vendor && (await vendor(name, sub));
47
- if (got) return { path: got, namespace: 'vfs' };
48
- return { path: npmUrl(name, deps[name], sub), namespace: 'http' };
49
- });
50
- b.onLoad({ filter: /.*/, namespace: 'vfs' }, async (a) => {
51
- if (!files.has(a.path)) return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
52
- const text = files.get(a.path);
53
- const t = transform && (await transform(a.path, text));
54
- if (t) return t;
55
- if (isBinary(text)) return { contents: toBytes(text), loader: 'dataurl' };
56
- return { contents: text, loader: LOADERS[ext(a.path)] || 'text', resolveDir: '/' + dirname(a.path) };
57
- });
58
- },
59
- };
60
- }
@@ -1,50 +0,0 @@
1
- // パッケージング(Web Crypto + fflate)― 公式パッカーとバイト単位で一致することを確認済み
2
- import { zipSync, unzipSync } from 'fflate';
3
- import { b64, unb64 } from '../util/bytes.js';
4
-
5
- const ALG = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-1' };
6
- const RSA_ALG = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]);
7
- const derLen = (n) => (n < 128 ? [n] : n < 256 ? [0x81, n] : [0x82, n >> 8, n & 255]);
8
- const cat = (...a) => { const o = new Uint8Array(a.reduce((s, x) => s + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; };
9
- const pemBody = (pem) => unb64(pem.replace(/-----[^-]+-----|\s/g, ''));
10
- const toPem = (der, label) => `-----BEGIN ${label}-----\n${b64(der).match(/.{1,64}/g).join('\n')}\n-----END ${label}-----\n`;
11
- // .ppk は PKCS#1。Web Crypto は PKCS#8 しか読めないので包む / 剥がす
12
- const p1to8 = (p1) => {
13
- const body = cat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALG, cat(new Uint8Array([0x04, ...derLen(p1.length)]), p1));
14
- return cat(new Uint8Array([0x30, ...derLen(body.length)]), body);
15
- };
16
- const p8to1 = (p8) => {
17
- let i = 0;
18
- const len = () => { let l = p8[i++]; if (l & 0x80) { const n = l & 0x7f; l = 0; for (let k = 0; k < n; k++) l = (l << 8) | p8[i++]; } return l; };
19
- const skip = () => { i++; const l = len(); i += l; };
20
- i++; len(); skip(); skip(); i++; const l = len();
21
- return p8.slice(i, i + l);
22
- };
23
-
24
- export async function generateKey() {
25
- const kp = await crypto.subtle.generateKey({ ...ALG, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) }, true, ['sign', 'verify']);
26
- return toPem(p8to1(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))), 'RSA PRIVATE KEY');
27
- }
28
- export async function idFromSpki(spki) {
29
- const hex = [...new Uint8Array(await crypto.subtle.digest('SHA-256', spki))].map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 32);
30
- return hex.replace(/[0-9a-f]/g, (c) => 'abcdefghijklmnop'['0123456789abcdef'.indexOf(c)]);
31
- }
32
- export async function pack(contentsZip, ppk) {
33
- const key = await crypto.subtle.importKey('pkcs8', p1to8(pemBody(ppk)), ALG, true, ['sign']);
34
- const signature = new Uint8Array(await crypto.subtle.sign(ALG, key, contentsZip));
35
- const jwk = await crypto.subtle.exportKey('jwk', key);
36
- const pub = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS1', ext: true }, ALG, true, ['verify']);
37
- const spki = new Uint8Array(await crypto.subtle.exportKey('spki', pub));
38
- return { id: await idFromSpki(spki), plugin: zipSync({ 'contents.zip': contentsZip, PUBKEY: spki, SIGNATURE: signature }) };
39
- }
40
- // プラグインzip の署名を検証して中身を取り出す(import 用)。プラグインでなければ null
41
- export async function unpack(pluginZip) {
42
- const outer = unzipSync(pluginZip);
43
- if (!outer['contents.zip']) return null;
44
- let verified = false;
45
- if (outer.PUBKEY && outer.SIGNATURE) {
46
- const pub = await crypto.subtle.importKey('spki', outer.PUBKEY, ALG, false, ['verify']);
47
- verified = await crypto.subtle.verify(ALG, pub, outer.SIGNATURE, outer['contents.zip']);
48
- }
49
- return { contents: unzipSync(outer['contents.zip']), verified, id: outer.PUBKEY ? await idFromSpki(outer.PUBKEY) : null };
50
- }