@kubohiroya/turbowarp-plus-editor 0.1.0 → 0.2.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +5 -0
- package/README.md +108 -3
- package/assets/edit-button.css +19 -6
- package/config/feature-flags.js +6 -0
- package/docs/extension-loader-integration.md +83 -0
- package/package.json +39 -5
- package/scripts/yaml-editor/cli.mjs +53 -0
- package/scripts/yaml-editor/host.mjs +291 -0
- package/scripts/yaml-editor/schema.mjs +26 -0
- package/scripts/yaml-editor/vscode.mjs +174 -0
- package/site/source.json +12 -3
- package/src/extension-loader.js +56 -0
- package/src/index.js +7 -1
package/NOTICE
CHANGED
|
@@ -3,3 +3,8 @@ The original TurboWarp Plus SVG brand is adapted from kubohiroya/turbowarp-plus-
|
|
|
3
3
|
The blue colored-pencil variation identifies the TurboWarp-Plus-Editor editing action.
|
|
4
4
|
Integrated GUI builds include kubohiroya/scratch-gui and its third-party notices.
|
|
5
5
|
Library names identify independently licensed components; their licenses remain applicable.
|
|
6
|
+
|
|
7
|
+
The optional embedded-YAML editor uses the independent turbowarp-embedded-yaml package (MPL-2.0).
|
|
8
|
+
The generated yaml-editor/notices/ directory retains that package's license.
|
|
9
|
+
App-specific document validation and updates are supplied by each owning extension through its provider.
|
|
10
|
+
The local VSCode companion uses an existing Visual Studio Code installation, independently licensed by Microsoft.
|
package/README.md
CHANGED
|
@@ -53,7 +53,23 @@ HTMLページの `<head>` にスタイルシートを1回読み込み、ボタ
|
|
|
53
53
|
</a>
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
-
新しい作品用のボタンは `project_url` を省略します。英語では `lang=en` と `Edit in TurboWarp-Plus-Editor` を使います。
|
|
56
|
+
新しい作品用のボタンは `project_url` を省略します。英語では `lang=en` と `Edit in TurboWarp-Plus-Editor` を使います。
|
|
57
|
+
|
|
58
|
+
通常版はアイコンと操作名を表示します。小サイズ版は `twpe-edit-button--small` を追加し、表示文言を「編集」、`title` と `aria-label` を「TurboWarp-Plus-Editorで編集」にします(英語は `Edit` / `Edit in TurboWarp-Plus-Editor`)。`title` がホバー時のツールチップです。
|
|
59
|
+
|
|
60
|
+
```html
|
|
61
|
+
<a class="twpe-edit-button twpe-edit-button--small"
|
|
62
|
+
href="https://kubohiroya.github.io/turbowarp-plus-editor/editor.html?lang=ja"
|
|
63
|
+
title="TurboWarp-Plus-Editorで編集" aria-label="TurboWarp-Plus-Editorで編集">
|
|
64
|
+
<img src="https://kubohiroya.github.io/turbowarp-plus-editor/assets/icon.svg"
|
|
65
|
+
width="24" height="24" alt="" aria-hidden="true">
|
|
66
|
+
<span>編集</span>
|
|
67
|
+
</a>
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
両サイズとも既定はOSの配色に追従(auto)します。`<html data-theme="light">` / `dark` で固定し、`auto` または属性の削除で自動へ戻せます。JavaScriptで生成する場合は `renderEditButton({size: 'small', language: 'ja', projectURL: 'https://example.com/story.sb3'})` を使います。省略時は通常版です。
|
|
71
|
+
|
|
72
|
+
GitHub READMEは外部CSSを適用できないため、次の画像付きリンクを使用できます。
|
|
57
73
|
|
|
58
74
|
```html
|
|
59
75
|
<a href="https://kubohiroya.github.io/turbowarp-plus-editor/editor.html?lang=ja">
|
|
@@ -64,6 +80,8 @@ HTMLページの `<head>` にスタイルシートを1回読み込み、ボタ
|
|
|
64
80
|
|
|
65
81
|
既存GUIの機能フラグは変更しません。TurboWarp Plusの機能拡張一覧を試す場合は、EditorのURLへ `twPlusExtensions=1` を指定して起動します。外すか `0` へ戻して再読込すれば無効になります。ボタンに渡したこのパラメーターも保持します。
|
|
66
82
|
|
|
83
|
+
Issue #4 の拡張Loaderは、独立したLoaderコアと薄いGUI/VMアダプターで実装します。通常配信でも `twPlusExtensionLoader=1` を起動URLに明示した場合だけ、Embedded/Remoteの検証・許可UIを有効にできます(起動時固定・既定OFF)。Plus作品のPackager操作はローカル出力画面へ進み、生成時と受け取り側の初回実行時に承認を確認します。指定がない通常の起動ではLoaderを有効にしません。構成、検証、Desktopの制約、切戻しは [接続仕様](docs/extension-loader-integration.md) を参照してください。
|
|
84
|
+
|
|
67
85
|
## npmで利用する
|
|
68
86
|
|
|
69
87
|
```sh
|
|
@@ -90,14 +108,95 @@ Node.js 26を使用します。
|
|
|
90
108
|
```sh
|
|
91
109
|
npm ci
|
|
92
110
|
npm test
|
|
93
|
-
E2E_GUI_ROOT=/absolute/path/to/pinned/scratch-gui
|
|
111
|
+
E2E_GUI_ROOT=/absolute/path/to/pinned/scratch-gui \
|
|
112
|
+
TW_PLUS_PACKAGER_ROOT=/absolute/path/to/pinned/packager npm run build:pages
|
|
94
113
|
E2E_GUI_ROOT=/absolute/path/to/pinned/scratch-gui npm run test:e2e
|
|
95
114
|
```
|
|
96
115
|
|
|
97
|
-
GUIは `site/source.json` に記録したSHA
|
|
116
|
+
GUIとPackagerは `site/source.json` に記録したSHAをチェックアウトします。GUIの依存をインストールし、`node scripts/prepublish.mjs` で準備します。ビルドはGUIのSHA、実際にインストールされたdata-editorのSHA、security-dialogのバージョンが固定値と一致することを確認します。Pagesは統合検証に成功したmainから配信します。リリースのタグはnpmのバージョンと一致させます。
|
|
98
117
|
|
|
99
118
|
統合Editorの動作確認はこのリポジトリが担当します。既存の上流ライブラリの単体テストとGUIの機能フラグは維持します。新配信先の確認後、各参照先を移行し、旧data-editorのPagesを停止します。旧サイトへのリダイレクト配信は残しません。切戻しは直前のGUI固定SHA・サイト差分へのrevertと直前成果物の再配信で行います。
|
|
100
119
|
|
|
120
|
+
## 組み込み文書を編集する(0.2.0-rc.1)
|
|
121
|
+
|
|
122
|
+
[Issue #3](https://github.com/kubohiroya/turbowarp-plus-editor/issues/3)と[共通化Issue #6](https://github.com/kubohiroya/turbowarp-plus-editor/issues/6)に対応する試験公開機能です。起動時に `twPlusYamlEditor=1` を指定したEditorで有効になります。既定OFFです。Visual Studio CodeとNode.jsをインストールした環境で、ローカル補助プロセスからEditorを開きます。上流GUIやライブラリに下流依存は追加しません。原文文書の保存・文書参照・提供元登録は `@kubohiroya/turbowarp-document-data`、ハット・YAMLアイコン・共通YAMLブロックは独立した `@kubohiroya/turbowarp-embedded-yaml` に置きます。各拡張が文書を登録し、Editorは共通契約を介してVSCodeとの連携・取込・SB3保存を担当します。
|
|
123
|
+
|
|
124
|
+
紙芝居用の提供元はApp `4.0.0-rc.79` に置き、App所有の検証APIとSchemaを使用します。Editorのブラウザ用コードにはAppやそのparserを組み込みません。紙芝居では、新しい独立rootと名前付き文書を持つ作品が対象です。原文YAML・共通YAMLブロック・台本ブロックを表示・変換でき、既存の単一組み込み原文にも互換対応します。旧 `kamishibai` / `kamishibaiConfig` の作品はAppの `migrate-embedded-yaml` で別のSB3へ移行してから使用します。外部台本を開くメニューとコンパイル済みのみの作品は対象外です。
|
|
125
|
+
|
|
126
|
+
準備済みのEditorビルドに機能を加え、ローカルで起動します。`build:pages`で新たにビルドした場合は、同じ追加処理を自動で実行します。
|
|
127
|
+
|
|
128
|
+
```sh
|
|
129
|
+
npm ci --ignore-scripts
|
|
130
|
+
npm run build:yaml-tools -- /absolute/path/to/editor/build
|
|
131
|
+
npm run editor:yaml -- --site-dir /absolute/path/to/editor/build --data-dir /absolute/path/to/work-files
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
共有パッケージは公開rcへ固定しています。VSCodeとの連携には、ビルド済みEditorを配信するローカル補助プロセスが必要です。npmパッケージからも次のように起動できます。
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
npx --package=@kubohiroya/turbowarp-plus-editor@0.2.0-rc.1 turbowarp-plus-editor-yaml --site-dir /absolute/path/to/editor/build --data-dir /absolute/path/to/work-files
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
GitHub Pages上では文書の表示・変換・検証を利用できます。VSCodeを起動する操作は、上記のローカルURLで開いた場合に利用できます。
|
|
141
|
+
|
|
142
|
+
表示されたローカルURLを開くと、起動時固定の `twPlusYamlEditor=1` が有効になります。読み取り箇所は `site/yaml-editor/feature-flags.js` です。
|
|
143
|
+
|
|
144
|
+
1. 組み込み文書のSB3をEditorで開き、「embedded YAML」ハットブロックのファイルアイコンを押します。「組み込み文書」ダイアログで「VSCodeで編集」を選びます。
|
|
145
|
+
2. 開いたYAMLを編集してVSCodeで保存します。
|
|
146
|
+
3. Editorへ戻って、ダイアログ右下の「表示されている形式に変換して検証・保存」を押します。VSCodeで保存済みの作業コピーを読み、書式・アセット参照・プロジェクトの同一性を検証して、Editor内の文書と整合性情報へ反映します。
|
|
147
|
+
4. 作品ファイルを残すには、Editor標準の「ファイル」メニューまたは「コンピューターに保存する」でSB3を保存します。ダイアログの「保存」ではファイルをダウンロードしません。画像・音声の格納方式は変わりません。
|
|
148
|
+
|
|
149
|
+
ハットブロックは組み込みYAMLへの入口です。ドロップダウンにファイル名を表示し、SB3には提供元IDと文書IDの参照を持ちます。台本文字列をブロックの引数に複製しません。複数文書は同じファイル名でもIDで区別し、別文書へ移るときは、現在のダイアログを「保存」または「キャンセル」で閉じます。実際の文書取得・検証・更新は、その文書を所有する提供元に委ねます。紙芝居以外にも同じ仕組みを利用できます。今回のローカルApp実装でハットブロックを付けたSB3が対象です。旧Appで生成されたハットのないSB3へ、Editorから未知のブロックや拡張コードを自動挿入することはありません。文書の提供元が変換能力を登録すると、同じダイアログから原文ファイル・共通YAMLブロック・スキーマ専用ブロックを変換できます。
|
|
150
|
+
|
|
151
|
+
提供元は任意の `schema: {id, schema}` を文書ごとに指定できます。ローカル連携は所有者のSchemaと関連付けを作業フォルダへ保存し、YAML本文には設定用のコメントを挿入しません。Schema付き文書を初めて開くと、専用拡張領域へ公式のRed Hat YAML拡張 `redhat.vscode-yaml@2.0.0` を取得します。既存VSCodeの設定・拡張一覧は変更しません。初回取得には通信が必要です。Schemaがない文書は従来どおり所有者の検証で取り込みます。
|
|
152
|
+
|
|
153
|
+
VSCode側の補完と診断には[Red Hat YAMLのSchema関連付け](https://github.com/redhat-developer/vscode-yaml#associating-schemas)を使用します。紙芝居では生の台本を扱う編集用Schemaを供給し、取り込み時にはAppの構文・意味・アセット参照・実行データ整合性も検証します。
|
|
154
|
+
|
|
155
|
+
補助プロセスはこのローカルEditorからの認証付き操作だけを受け付けます。VSCodeには専用の作業ファイルと独立した設定領域を渡し、既存のウィンドウ・設定・拡張機能を変更しません。保存済みの作業ファイルは、接続終了やプロセス停止後も保持します。実行するコマンドや任意のローカルパスをWeb側から指定する機能はありません。
|
|
156
|
+
|
|
157
|
+
YAMLが不正な場合や別作品へ切り替えた場合は、古い内容を上書きしません。反映できなかった草稿はVSCodeの作業ファイルに保持します。右上のXと「キャンセル」は、ダイアログ内の候補を破棄してEditorを書き換えずに閉じます。作業ファイルは削除しません。台本に新しいアセット参照を追加する操作は、既存のアセット一式で検証できる範囲に限ります。
|
|
158
|
+
|
|
159
|
+
macOSの内部通信パス上限を超える保存先では、作業ファイルを移動せず、VSCode設定領域だけを短い専用ディレクトリへ自動分離します。実際の保存先は作業領域の `host.json` に記録します。
|
|
160
|
+
|
|
161
|
+
切戻しはフラグを外して再起動し、必要に応じて直前の検証済み版へ戻します。補助プロセスを停止しても作業ファイルは保持します。
|
|
162
|
+
|
|
163
|
+
関連検証:
|
|
164
|
+
|
|
165
|
+
```sh
|
|
166
|
+
npm run test:yaml
|
|
167
|
+
TWPE_CHROME_EXECUTABLE='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' npm run test:yaml:browser
|
|
168
|
+
TWPE_YAML_SITE=/absolute/path/to/editor/build \
|
|
169
|
+
TWPE_YAML_FIXTURE=/absolute/path/to/tutorial-4.0.sb3 \
|
|
170
|
+
TWPE_YAML_EVIDENCE=/absolute/path/to/evidence \
|
|
171
|
+
TWPE_CHROME_EXECUTABLE='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' \
|
|
172
|
+
npm run test:yaml:roundtrip
|
|
173
|
+
# 非紙芝居2文書fixtureも同じ環境変数で検証できます。
|
|
174
|
+
node --test test/yaml-multi-document.browser.mjs
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
自動ブラウザ回帰ではネイティブ起動だけを注入し、実GUI・実VM・実SB3で検証します。実VSCode確認には `test/vscode-edit-driver/` のテスト専用Extension Development Hostを用い、VSCode自身の文書編集・保存APIで作業YAMLを保存します。このdriverを通常の補助プロセスへインストールする必要はありません。
|
|
178
|
+
|
|
179
|
+
### 原文・共通YAMLブロック・スキーマ専用ブロック
|
|
180
|
+
|
|
181
|
+
原文ファイル、キー・配列・値・コメントを表す共通YAMLブロック、紙芝居などのスキーマ専用ブロックを、同じ文書の3つの表現として扱います。原文を意味と変換の基準とし、ブロックを編集中はその内容もEditorの編集状態へ保持します。別のブロック表現へ移るときは、現在の編集を原文へ反映した上で変換する処理を、一つの保存操作の中で行います。変換先を選ぶだけでは作品を書き換えません。初期タブは💽付きの現在の保存済み表現です。別のタブで「保存」を押すと変換確認を表示し、OKで検証・変換してEditorへ反映します。Cancelは選択を保持してダイアログへ戻ります。Xと「キャンセル」は同じ取消操作です。未反映のブロックを原文から再生成して上書きする操作は拒否します。
|
|
182
|
+
|
|
183
|
+
各タブには、その形式のプレビューを表示します。原文タブはテキスト、ブロックのタブは読み取り専用のScratchBlocksを表示し、表示だけでは作品を書き換えません。ブロックは移動・編集できず、スクロールと拡大縮小で確認できます。💽はEditor内で現在保存されている形式を表し、SB3ファイルをダウンロードしたことを表すものではありません。
|
|
184
|
+
|
|
185
|
+
共通YAMLブロックはコメントを1行ずつ、複数行の文字列を行と改行種別のブロックで扱います。標準の文字入力欄で改行が失われるのを防ぎます。未編集の原文は改行・引用符・コメントをそのまま保持します。編集した部分の出力書式は所有者とYAMLライブラリが決定します。JSONではコメントを許可しません。
|
|
186
|
+
|
|
187
|
+
- `turbowarp-yaml-json`: YAML/JSONの解析・出力、原文構文、Schema検証。
|
|
188
|
+
- `turbowarp-document-data`: 原文・Schema・文書参照・提供元登録とSB3への永続化。
|
|
189
|
+
- `turbowarp-structured-data`: 原文から実行時の値を生成する一時的な投影。原文を書き換えません。
|
|
190
|
+
- `turbowarp-embedded-yaml`: 共通ハット・共通ブロック・変換候補と適用の契約。
|
|
191
|
+
- 各App: DSL専用の検証、台本ブロック変換、実行データの再生成。
|
|
192
|
+
- TurboWarp-Plus-Editor: 操作ダイアログ、VSCode連携、取込、標準SB3保存。
|
|
193
|
+
|
|
194
|
+
非紙芝居の原文文書はYAMLとJSONを利用でき、HTML/Markdownの既存APIは維持します。下位の文書形式判定を担当する `turbowarp-named-data` にもYAML/JSONを追加します。構造化データの既存の限定Schema解釈と、文書の完全なJSON Schema検証は別の契約として維持します。
|
|
195
|
+
|
|
196
|
+
新しい文書保存・投影・表現変換は既定OFFです。対応するApp rc.79では `twPlusYamlEditor=1` によりEditorと提供元の文書操作を同じ起動条件で有効にします。各文書の変換能力は所有者が提供し、未対応の拡張へ変換機能を追加することはありません。旧ブロック台本に元のモジュールYAMLが保存されていない場合、コメント等を含む元ファイルを復元したとは扱いません。
|
|
197
|
+
|
|
198
|
+
「DSLの説明」は提供元のWebサイトを開きます。独立した検証ボタンは置かず、右下の「表示されている形式に変換して検証・保存」で表示中の形式を検証して反映します。ブロック表現を編集中のVSCode操作は、原文へ反映するまで無効になります。原文がJSONの場合、VSCode標準のJSON支援とSchema関連付けを使います。
|
|
199
|
+
|
|
101
200
|
## English
|
|
102
201
|
|
|
103
202
|
TurboWarp-Plus-Editor is an independent editor distribution by Hiroya Kubo. This downstream package builds the pinned `kubohiroya/scratch-gui` fork, verifies its library versions and integration, and deploys it to GitHub Pages. The upstream libraries do not build the GUI.
|
|
@@ -109,3 +208,9 @@ Use the landing page to create a project, open an SB3 URL, or continue to the ed
|
|
|
109
208
|
ライセンス: GPL-3.0-or-later。統合GUIと同梱物については各ライセンス・NOTICEも参照してください。
|
|
110
209
|
|
|
111
210
|
製作者: [Hiroya Kubo](https://github.com/kubohiroya)
|
|
211
|
+
|
|
212
|
+
## ブロックアイコンのプレビュー
|
|
213
|
+
|
|
214
|
+
[App rc.77のプレビュー体験サンプルを開く](https://kubohiroya.github.io/turbowarp-plus-editor/editor.html?lang=ja&twPlusBlockPreview=1&twPlusYamlEditor=1&project_url=https%3A%2F%2Fkubohiroya.github.io%2Fturbowarp-plus-editor%2Fsamples%2Fblock-preview%2Fblock-preview-rc77.sb3)と、ステージの「コード」タブが自動的に開き、先頭のsceneが表示されます。配置と動き・吹き出しの2シーンをそのまま試せます。[操作ガイド](https://kubohiroya.github.io/turbowarp-plus-editor/samples/block-preview/)・[SB3ダウンロード](https://kubohiroya.github.io/turbowarp-plus-editor/samples/block-preview/block-preview-rc77.sb3)も公開しています。正本は`site/samples/block-preview/`のYAML・SVGで、公開済みApp rc.77から`build:pages`時に再生成します。生成元・runtime・SB3のハッシュを配信`metadata.json`に記録し、Pagesの成果物チェックで照合します。
|
|
215
|
+
|
|
216
|
+
[プレビューを有効にしてEditorを開く](https://kubohiroya.github.io/turbowarp-plus-editor/?twPlusBlockPreview=1&twPlusYamlEditor=1)。既定OFFで、App rc.79の編集用runtimeとscene/actionを持つ作品が対象です。hover静止画、scene再生、アクターのドラッグ配置、moveTo/Bubbleのライブ再生に対応します。操作・既存作品の扱いは[利用案内](docs/block-icon-preview.md)を参照してください。
|
package/assets/edit-button.css
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
.twpe-edit-button {
|
|
2
|
+
color-scheme: light dark;
|
|
2
3
|
display: inline-flex;
|
|
3
4
|
align-items: center;
|
|
4
5
|
justify-content: center;
|
|
@@ -7,11 +8,11 @@
|
|
|
7
8
|
min-height: 56px;
|
|
8
9
|
max-width: 100%;
|
|
9
10
|
padding: .7em 1.1em;
|
|
10
|
-
border: 2px solid #b8ddf7;
|
|
11
|
+
border: 2px solid light-dark(#b8ddf7, #497f9e);
|
|
11
12
|
border-radius: 14px;
|
|
12
|
-
background: #e8f5ff;
|
|
13
|
-
color: #123e65;
|
|
14
|
-
font:
|
|
13
|
+
background: light-dark(#e8f5ff, #173d54);
|
|
14
|
+
color: light-dark(#123e65, #f2f2f2);
|
|
15
|
+
font: 400 1rem/1.45 system-ui, sans-serif;
|
|
15
16
|
text-align: center;
|
|
16
17
|
text-decoration: none;
|
|
17
18
|
cursor: pointer;
|
|
@@ -19,6 +20,18 @@
|
|
|
19
20
|
}
|
|
20
21
|
.twpe-edit-button img { flex: 0 0 36px; width: 36px; height: 36px; object-fit: contain; }
|
|
21
22
|
.twpe-edit-button span { overflow-wrap: anywhere; }
|
|
22
|
-
.twpe-edit-button:hover { background: #d8edff; border-color: #659cc4; color: #123e65; text-decoration: none; }
|
|
23
|
-
.twpe-edit-button:focus-visible { outline: 3px solid #145a98; outline-offset: 4px; }
|
|
23
|
+
.twpe-edit-button:hover { background: light-dark(#d8edff, #20516f); border-color: light-dark(#659cc4, #78b3d4); color: light-dark(#123e65, #f2f2f2); text-decoration: none; }
|
|
24
|
+
.twpe-edit-button:focus-visible { outline: 3px solid light-dark(#145a98, #a8d6ff); outline-offset: 4px; }
|
|
25
|
+
:root[data-theme="light"] .twpe-edit-button { color-scheme: light; }
|
|
26
|
+
:root[data-theme="dark"] .twpe-edit-button { color-scheme: dark; }
|
|
27
|
+
.twpe-edit-button--small {
|
|
28
|
+
white-space: nowrap;
|
|
29
|
+
gap: .4em;
|
|
30
|
+
min-height: 36px;
|
|
31
|
+
padding: .3em .65em;
|
|
32
|
+
border-width: 1px;
|
|
33
|
+
border-radius: 8px;
|
|
34
|
+
font-size: .875rem;
|
|
35
|
+
}
|
|
36
|
+
.twpe-edit-button--small img { flex-basis: 24px; width: 24px; height: 24px; }
|
|
24
37
|
@media (forced-colors: active) { .twpe-edit-button { border-color: ButtonText; } }
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Issue #4: Embedded / Remote拡張の統合
|
|
2
|
+
|
|
3
|
+
親仕様: https://github.com/kubohiroya/turbowarp-plus-editor/issues/4
|
|
4
|
+
|
|
5
|
+
## 実装場所と依存方向
|
|
6
|
+
|
|
7
|
+
Manifest、取得、SHA-256、認可、依存順、診断、キャッシュ、SB3保持、配布元変換は独立した `turbowarp-extension-loader` に集約した。`scratch-gui` は許可UI、VM登録、ロード/保存フック、Packagerとの受け渡しだけを担当する。Editorは固定GUIのビルド・配信と統合E2Eを所有する。
|
|
8
|
+
|
|
9
|
+
| 構成 | 固定した基点 | ローカル変更 |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| scratch-gui | `9868fa1f600a4ba60840699563b870b20d3e82ed` | `.host/scratch-gui` の薄いアダプター・UI・出力画面 |
|
|
12
|
+
| scratch-vm | `55fd9b7c9509827c9cec31482aa63f2d57ec564d` | `.host/scratch-vm-issue4` の所有サービスport(43行追加) |
|
|
13
|
+
| Packager | `c115bdf525c5f49f0fb689a21b335ccb70fc22d2` / npm `3.14.0` | ソースを改変せず、上記VMを使ってscaffoldingをビルド |
|
|
14
|
+
| data-editor | npm `0.6.0` / source `91533dbbffa9eb9d3b50be8084b85dae5184f9dc` | 共通フォーム・固定入力・プレビュー登録API |
|
|
15
|
+
| security-dialog | npm `0.3.3` | 既存UI・通常カスタム拡張の方針を維持 |
|
|
16
|
+
|
|
17
|
+
Loaderは [kubohiroya/turbowarp-extension-loader](https://github.com/kubohiroya/turbowarp-extension-loader) が所有する。GUIのpackage/lockfileはLoaderとVMをGitの完全SHAで固定する。通常配信の `site/source.json` と、統合プレビューの `site/extension-source.json` は、ともにマージ済み統合GUIを固定する。通常ビルドがLoader入りscaffolding/runtime/ローカルPackager画面を生成し、artifact gateが依存SHA・既定OFF・資産hashを検証する。既存のscratch-gui作業ツリーは変更せず専用checkoutを使う。
|
|
18
|
+
|
|
19
|
+
## 起動と信頼境界
|
|
20
|
+
|
|
21
|
+
`twPlusExtensionLoader=1` の完全一致だけで起動する。起動後のURL変更から有効化せず、作品の設定を起動フラグとして使わない。Editor公開APIの読取は `config/feature-flags.js`、GUIの接続は `startupPlusExtensionHost` が担当する。既定OFFで、既存の `twPlusExtensions` とは独立している。
|
|
22
|
+
|
|
23
|
+
ホストが静的に組み込んだLoader、UI、VM registrarを接続する。作品からLoader・認可ポリシーを取得しない。coreが検証したexact bytesと取得元をUIへ渡し、id・取得元・発行者の未検証の申告・version・digest・unsandboxed要求・capabilityを表示する。拒否・Esc・閉じる・abortは拒否となる。承認はホストセッション内で要求の全情報に束縛し、破棄時に失効する。明示的な外部ホストポリシーをUI前に適用し、拒否をユーザー操作で上書きしない。
|
|
24
|
+
|
|
25
|
+
SHA-256はバイト列の一貫性の検証であり、安全性や発行者本人性の証明ではない。RemoteはHTTPSのみ、資格情報・fragment・redirect・未証明の最終URLを拒否する。キャッシュは既定8 MiB/1時間のセッションLRUで、ヒット時にも再検証・認可する。通信不能時に異なるdigestのコードへフォールバックしない。
|
|
26
|
+
|
|
27
|
+
コアは全件を検証・認可してから登録する。認可証跡はコピーできないtransaction限定の証跡で、作品の自己申告を受け付けない。registrarはVMが提供する所有サービスportへ登録し、getInfo().idを照合してからVMブロックを登録する。失敗時は所有サービス・primitive・hat・category等を解除し、失敗したホストを再利用しない。任意の特権JSによるネットワーク・DOM等の副作用は巻き戻せない。承認後のJS評価でID不一致を検出した場合は登録を拒否する。
|
|
28
|
+
|
|
29
|
+
## SB3と保存互換性のADR
|
|
30
|
+
|
|
31
|
+
v1は `project.json.turboWarpPlus` とZIP内 `extensions/` のJSを使う。Plus固有の形式であり、標準SB3仕様ではない。Manifestには拡張ごとのsource/execution要求/digest/任意のversion等を保持する。executionと申告publisherは認可ではない。
|
|
32
|
+
|
|
33
|
+
VMは元の作品オブジェクトとZIPを保存時に作り直すため、未知フィールドや追加ZIPエントリを自動保持しない。Loader codecがロード時の文脈を保持し、GUIは `toJSON` / `_saveProjectZip` / `saveProjectSb3DontZip` からcoreの保持処理へ委譲する。標準extensionsとPlusの元URL metadata、unknown data、埋め込みバイト列を保存する。sprite単体の書出しに作品Manifestを混入しない。
|
|
34
|
+
|
|
35
|
+
ZIPはcentral directoryを展開前に検査し、重複・危険なパス・未知圧縮・ZIP64・過大サイズ等を拒否する。展開中にも実容量・CRCを照合する。Manifest無しは登録処理を呼ばず既存ロードへ委譲するが、ZIPの安全性制限は適用する。厳格な対応ZIP subset・サイズ上限はLoader READMEを正とする。
|
|
36
|
+
|
|
37
|
+
Legacy Data URLは自動で信頼済みPlus形式へ昇格しない。coreの明示移行APIでdigestとホスト承認を要求する。Embedded/Remote変換はexact bytesとlock/license/provenance metadataを保持し、Remote出力の公開用バイト列を返す。変換APIが外部へ公開することはない。
|
|
38
|
+
|
|
39
|
+
## Packagerと単一HTML
|
|
40
|
+
|
|
41
|
+
Plus作品のPackager操作は同一originの `plus-packager.html` へ進む。通常作品は従来の外部Packagerへ進む。ファイル入力または同一origin・元window照合済みpostMessageで作品を受け取る。作品が独自bootstrapや生成JSを供給することはない。
|
|
42
|
+
|
|
43
|
+
生成時はcoreの同一検証・認可APIでRemoteをEmbeddedへ変換する。外部依存が無いことの明示確認を要求し、未同梱の依存資源やlegacy custom URLが残る作品を拒否する。Packager 3.14.0へ完全なSB3をblobとして渡し、作品ロード前に信頼済みLoader/hostを起動する。JSONへ分解して埋め込みコードを失わない。
|
|
44
|
+
|
|
45
|
+
Editorと別のVMバンドルでdispatchを二重保持しないため、追加したVM portを使うscaffoldingを公式ソースから作る。runtime/scaffoldingを静的なローカルbuilderへ組み込み、生成HTMLへ全て同梱する。生成時の承認を受け取り側の承認として埋め込まず、HTMLで再確認する。CSPはconnect-src none等を指定し、実行時の外部取得に依存しない。依存資源がある拡張の自動バンドルは初期版では行わず拒否する。
|
|
46
|
+
|
|
47
|
+
## 実行環境
|
|
48
|
+
|
|
49
|
+
| 環境 | 確認した動作 |
|
|
50
|
+
|---|---|
|
|
51
|
+
| ローカル統合Editor online | Embedded/Remote、許可UI、実VMアクセス、保存・再読込 |
|
|
52
|
+
| 同Editor offline | Embedded、検証済みcache hit、cache miss拒否 |
|
|
53
|
+
| 単一HTML | 公式Packager生成、受け取り側の再承認、file URLとoffline、実ブロック実行 |
|
|
54
|
+
| TurboWarp Desktop 1.17.0 / Electron 43.8.3 | 専用プロファイルで生成HTMLを実行。標準EditorはLoader無しで自己申告JSを実行せず、未知Manifest/ZIP entriesを保存時に破棄 |
|
|
55
|
+
| 標準TurboWarp / 非対応ホスト | 事前bootstrap無しに本機構の特権を得られない。未知情報の保持は保証しない |
|
|
56
|
+
|
|
57
|
+
Desktopの本体や元のユーザープロファイルへ改変を加えていない。署名版はNode inspector fuseが無効なので、独立プロセスのrendererへChromium CDPで接続して測定した。保持対応のないエディターでの再保存は変換手段として使わない。
|
|
58
|
+
|
|
59
|
+
## 検証と再現
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
E2E_GUI_ROOT="$PWD/.host/scratch-gui-issue4" \
|
|
63
|
+
TW_PLUS_PACKAGER_ROOT="$PWD/.host/packager-issue4" \
|
|
64
|
+
NODE_OPTIONS=--max-old-space-size=6144 npm run build:pages
|
|
65
|
+
|
|
66
|
+
E2E_GUI_ROOT="$PWD/.host/scratch-gui-issue4" node test/e2e/extension-loader/prepare-packaged.mjs
|
|
67
|
+
|
|
68
|
+
E2E_GUI_ROOT="$PWD/.host/scratch-gui-issue4" npm run test:e2e:extension-loader
|
|
69
|
+
node --test .host/scratch-gui-issue4/test/unit/extension-loader/*.test.mjs
|
|
70
|
+
npm --prefix .host/turbowarp-extension-loader test
|
|
71
|
+
npm test
|
|
72
|
+
npm run test:extension-loader:desktop
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
新しい環境では `site/extension-source.json` のGUI revisionとPackager revisionを専用checkoutへ取得し、GUIで `npm ci` と `node scripts/prepublish.mjs` を実行する。LoaderとVMはGUIの固定Git依存から取得されるため、ローカルの兄弟ディレクトリやnode_modulesへの手作業パッチは不要。VMパッチはレビュー資料として `scripts/site/patches/scratch-vm-host-extension-service-port.patch` にも保持する。通常buildがscaffolding、runtime、ローカルbuilderを生成する。E2E用の単一HTMLはprepare-packaged.mjsで生成する。preview buildも同じ通常buildを呼ぶ。ソースの固定値と生成assets hashをビルドで検証し、`build-info.json.extensionIntegration` に通常配信の依存SHA・資産hash・既定OFFを記録し、プレビューのみ作業ツリー情報も追加する。
|
|
76
|
+
|
|
77
|
+
検証証跡は `test-results/extension-loader/results.json`、`.host/issue-4-artifacts/*tests.log`、`desktop-result.json` とDesktop screenshots。Embedded/Remote実行、拒否・Esc・改ざん・未知schema・信頼偽装・ID不一致、real TLSのCORS/redirect拒否、CSP、cache offline、URL/ローカルファイル、公式Bitwise/標準Pen、従来カスタム拡張の回帰を検証する。悪意あるZIP・キャッシュ汚染/失効・変換・compiler実行はcore/実VMの単体テストで検証する。
|
|
78
|
+
|
|
79
|
+
## 切戻しと公開境界
|
|
80
|
+
|
|
81
|
+
起動パラメーターを外すか0にして再起動すればOFFへ戻る。終了時はhost.disposeを待って登録を解除し、rollback/unload失敗時はVMを破棄する。Plus作品を保持非対応の状態で上書き保存しない。
|
|
82
|
+
|
|
83
|
+
通常配信は統合GUIの固定SHAへ切り替え、機能フラグは既定OFFを維持する。通常CIは既存24件と拡張15件のブラウザーE2E成功後だけ成果物を公開可能にする。公開後も固定された出所を照合して同じE2Eを実行し、単一HTMLのテストは配信されたbuilderから実際に生成したHTMLを使う。通常配信の切戻しは今回の切替コミット全体をrevertし、固定情報と対応するビルド/CI経路を一緒に以前の状態へ戻す。旧GUIへのpin変更だけでは新しいPackager資産の生成条件と一致しないため、単独では行わない。既定OFFまたはURLの0指定で拡張ロードを停止できる。検証済み成果物は通常のCI/Pages経路で再配信する。npm公開は本作業に含めない。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/turbowarp-plus-editor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-rc.2",
|
|
4
4
|
"description": "TurboWarp-Plus-Editorの配信、ブランド資産、作品を編集するボタン",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "GPL-3.0-or-later",
|
|
@@ -19,17 +19,24 @@
|
|
|
19
19
|
},
|
|
20
20
|
"exports": {
|
|
21
21
|
".": "./src/index.js",
|
|
22
|
+
"./extension-loader": "./src/extension-loader.js",
|
|
22
23
|
"./assets/icon.svg": "./assets/icon.svg",
|
|
23
24
|
"./assets/edit-button.css": "./assets/edit-button.css",
|
|
24
25
|
"./source.json": "./site/source.json"
|
|
25
26
|
},
|
|
26
27
|
"files": [
|
|
27
28
|
"src",
|
|
29
|
+
"config",
|
|
30
|
+
"docs/extension-loader-integration.md",
|
|
28
31
|
"assets",
|
|
29
32
|
"site/source.json",
|
|
30
33
|
"README.md",
|
|
31
34
|
"LICENSE",
|
|
32
|
-
"NOTICE"
|
|
35
|
+
"NOTICE",
|
|
36
|
+
"scripts/yaml-editor/cli.mjs",
|
|
37
|
+
"scripts/yaml-editor/host.mjs",
|
|
38
|
+
"scripts/yaml-editor/schema.mjs",
|
|
39
|
+
"scripts/yaml-editor/vscode.mjs"
|
|
33
40
|
],
|
|
34
41
|
"engines": {
|
|
35
42
|
"node": ">=24"
|
|
@@ -41,13 +48,40 @@
|
|
|
41
48
|
"test:e2e:block-editor": "npm run test:e2e",
|
|
42
49
|
"test:e2e:fixed-inputs": "E2E_FIXED_INPUTS=1 npm run test:e2e",
|
|
43
50
|
"test:e2e:infrastructure": "node --test test/e2e/ci-gate.test.mjs test/e2e/turbowarp/infrastructure.test.cjs",
|
|
44
|
-
"test:e2e:native": "E2E_NATIVE=1 npm run test:e2e"
|
|
51
|
+
"test:e2e:native": "E2E_NATIVE=1 npm run test:e2e",
|
|
52
|
+
"build:extension-preview": "node scripts/site/build-extension-preview.mjs",
|
|
53
|
+
"test:e2e:extension-loader": "playwright test --config test/e2e/extension-loader/playwright.config.cjs",
|
|
54
|
+
"test:extension-loader:desktop": "node test/e2e/extension-loader/desktop.cjs",
|
|
55
|
+
"build:yaml-tools": "node scripts/site/build-yaml-editor.mjs",
|
|
56
|
+
"editor:yaml": "node scripts/yaml-editor/cli.mjs",
|
|
57
|
+
"test:yaml": "node --test test/yaml-document.test.mjs test/yaml-host.test.mjs test/yaml-build.test.mjs",
|
|
58
|
+
"test:yaml:browser": "node --test test/yaml-ui.browser.mjs",
|
|
59
|
+
"test:yaml:roundtrip": "node --test test/yaml-roundtrip.browser.mjs"
|
|
45
60
|
},
|
|
46
61
|
"devDependencies": {
|
|
47
62
|
"@playwright/test": "^1.64.1",
|
|
48
|
-
"@turbowarp/jszip": "^3.12.0"
|
|
63
|
+
"@turbowarp/jszip": "^3.12.0",
|
|
64
|
+
"@turbowarp/packager": "3.14.0",
|
|
65
|
+
"@kubohiroya/turbowarp-embedded-yaml": "0.1.0-rc.2",
|
|
66
|
+
"@kubohiroya/turbowarp-extension-data-editor": "0.7.0",
|
|
67
|
+
"@kubohiroya/turbowarp-kamishibai-app": "4.0.0-rc.79",
|
|
68
|
+
"@kubohiroya/turbowarp-kamishibai-preview-app": "npm:@kubohiroya/turbowarp-kamishibai-app@4.0.0-rc.77",
|
|
69
|
+
"@kubohiroya/turbowarp-named-data": "0.8.0-rc.0",
|
|
70
|
+
"@kubohiroya/turbowarp-runtime-expression": "0.9.0",
|
|
71
|
+
"@kubohiroya/turbowarp-structured-data": "0.11.0-rc.0",
|
|
72
|
+
"@kubohiroya/turbowarp-yaml-json": "0.8.0-rc.0",
|
|
73
|
+
"ajv": "8.20.0",
|
|
74
|
+
"esbuild": "0.25.12",
|
|
75
|
+
"yaml": "2.9.1"
|
|
49
76
|
},
|
|
50
77
|
"publishConfig": {
|
|
51
|
-
"access": "public"
|
|
78
|
+
"access": "public",
|
|
79
|
+
"tag": "next"
|
|
80
|
+
},
|
|
81
|
+
"dependencies": {
|
|
82
|
+
"@kubohiroya/turbowarp-document-data": "0.5.0-rc.1"
|
|
83
|
+
},
|
|
84
|
+
"bin": {
|
|
85
|
+
"turbowarp-plus-editor-yaml": "scripts/yaml-editor/cli.mjs"
|
|
52
86
|
}
|
|
53
87
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {realpathSync} from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {startYamlEditorHost} from './host.mjs';
|
|
6
|
+
|
|
7
|
+
export function parseArguments(args) {
|
|
8
|
+
const options = {};
|
|
9
|
+
const fields = new Map([['--site-dir', 'siteDirectory'], ['--data-dir', 'dataDirectory'], ['--port', 'port']]);
|
|
10
|
+
for (let i = 0; i < args.length; i++) {
|
|
11
|
+
const field = fields.get(args[i]);
|
|
12
|
+
if (!field || options[field] !== undefined || !args[i + 1] || args[i + 1].startsWith('--')) {
|
|
13
|
+
throw new TypeError('Use --site-dir DIR [--data-dir DIR] [--port PORT].');
|
|
14
|
+
}
|
|
15
|
+
const value = args[++i];
|
|
16
|
+
if (field === 'port') {
|
|
17
|
+
if (!/^\d+$/.test(value) || Number(value) > 65535) throw new TypeError('Invalid port.');
|
|
18
|
+
options.port = Number(value);
|
|
19
|
+
} else options[field] = path.resolve(value);
|
|
20
|
+
}
|
|
21
|
+
if (!options.siteDirectory) throw new TypeError('--site-dir is required.');
|
|
22
|
+
return options;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function main(args = process.argv.slice(2)) {
|
|
26
|
+
const host = await startYamlEditorHost(parseArguments(args));
|
|
27
|
+
console.log(`TurboWarp-Plus-Editor: ${host.url}`);
|
|
28
|
+
console.log(`YAML working files are retained in: ${host.dataDirectory}`);
|
|
29
|
+
console.log(`Private VSCode profile: ${host.profileDirectory}`);
|
|
30
|
+
let stopping = false;
|
|
31
|
+
const stop = async () => {
|
|
32
|
+
if (stopping) return;
|
|
33
|
+
stopping = true;
|
|
34
|
+
await host.close();
|
|
35
|
+
process.removeListener('SIGINT', stop);
|
|
36
|
+
process.removeListener('SIGTERM', stop);
|
|
37
|
+
};
|
|
38
|
+
process.on('SIGINT', stop);
|
|
39
|
+
process.on('SIGTERM', stop);
|
|
40
|
+
return host;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isMainModule() {
|
|
44
|
+
try {
|
|
45
|
+
return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
46
|
+
} catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (isMainModule()) {
|
|
52
|
+
main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
|
53
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import {createServer} from 'node:http';
|
|
2
|
+
import {randomBytes, timingSafeEqual} from 'node:crypto';
|
|
3
|
+
import {constants, createReadStream} from 'node:fs';
|
|
4
|
+
import {lstat, mkdir, mkdtemp, open, realpath, stat, writeFile} from 'node:fs/promises';
|
|
5
|
+
import {tmpdir} from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import {pipeline} from 'node:stream/promises';
|
|
8
|
+
import {setTimeout as pause} from 'node:timers/promises';
|
|
9
|
+
import {createVSCodeProfile, launchVSCode} from './vscode.mjs';
|
|
10
|
+
import {writeSchemaWorkspace} from './schema.mjs';
|
|
11
|
+
import {normalizeSourceDocumentSchema} from '@kubohiroya/turbowarp-document-data/composition';
|
|
12
|
+
|
|
13
|
+
export const maxSourceBytes = 4 * 1024 * 1024;
|
|
14
|
+
export const apiPrefix = '/__twpe_yaml';
|
|
15
|
+
const maximumBodyBytes = maxSourceBytes * 6 + 2048;
|
|
16
|
+
const maximumSessions = 16;
|
|
17
|
+
const idPattern = /^[a-f0-9]{32}$/;
|
|
18
|
+
const loopbackAddresses = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
|
|
19
|
+
const mimeTypes = {
|
|
20
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
21
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
22
|
+
'.json': 'application/json; charset=utf-8', '.map': 'application/json',
|
|
23
|
+
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg',
|
|
24
|
+
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
|
|
25
|
+
'.ico': 'image/x-icon', '.wasm': 'application/wasm', '.woff2': 'font/woff2',
|
|
26
|
+
'.woff': 'font/woff', '.ttf': 'font/ttf', '.mp3': 'audio/mpeg', '.wav': 'audio/wav'
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function failure(status, code, message) {
|
|
30
|
+
return Object.assign(new Error(message), {status, code});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function within(root, filename) {
|
|
34
|
+
const relative = path.relative(root, filename);
|
|
35
|
+
return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function json(response, status, value) {
|
|
39
|
+
response.writeHead(status, {'content-type': 'application/json; charset=utf-8'});
|
|
40
|
+
response.end(JSON.stringify(value));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readJSON(request) {
|
|
44
|
+
if (!/^application\/json(?:\s*;|$)/i.test(request.headers['content-type'] || '')) {
|
|
45
|
+
throw failure(415, 'JSON_REQUIRED', 'Use an application/json request.');
|
|
46
|
+
}
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let bytes = 0;
|
|
49
|
+
for await (const chunk of request) {
|
|
50
|
+
bytes += chunk.length;
|
|
51
|
+
if (bytes > maximumBodyBytes) throw failure(413, 'SOURCE_TOO_LARGE', 'The YAML request is too large.');
|
|
52
|
+
chunks.push(chunk);
|
|
53
|
+
}
|
|
54
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
55
|
+
catch { throw failure(400, 'INVALID_JSON', 'The request is not valid JSON.'); }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function readSourceOnce(filename) {
|
|
59
|
+
const entry = await lstat(filename).catch(() => { throw failure(409, 'SOURCE_MISSING', 'The working YAML file is unavailable.'); });
|
|
60
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw failure(403, 'UNSAFE_SOURCE', 'The working YAML must be a regular file.');
|
|
61
|
+
let handle;
|
|
62
|
+
try {
|
|
63
|
+
handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
64
|
+
const info = await handle.stat();
|
|
65
|
+
if (!info.isFile()) throw failure(403, 'UNSAFE_SOURCE', 'The working YAML must be a regular file.');
|
|
66
|
+
if (info.size > maxSourceBytes) throw failure(413, 'SOURCE_TOO_LARGE', 'The saved YAML exceeds the size limit.');
|
|
67
|
+
const buffer = Buffer.alloc(maxSourceBytes + 1);
|
|
68
|
+
let count = 0;
|
|
69
|
+
while (count < buffer.length) {
|
|
70
|
+
const result = await handle.read(buffer, count, buffer.length - count, count);
|
|
71
|
+
if (!result.bytesRead) break;
|
|
72
|
+
count += result.bytesRead;
|
|
73
|
+
}
|
|
74
|
+
if (count > maxSourceBytes) throw failure(413, 'SOURCE_TOO_LARGE', 'The saved YAML exceeds the size limit.');
|
|
75
|
+
try { return new TextDecoder('utf-8', {fatal: true, ignoreBOM: true}).decode(buffer.subarray(0, count)); }
|
|
76
|
+
catch { throw failure(422, 'INVALID_ENCODING', 'Save the YAML as UTF-8.'); }
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.code === 'ELOOP') throw failure(403, 'UNSAFE_SOURCE', 'The working YAML must not be a symbolic link.');
|
|
79
|
+
throw error;
|
|
80
|
+
} finally { await handle?.close(); }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function readStableSource(filename) {
|
|
84
|
+
let previous = await readSourceOnce(filename);
|
|
85
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
86
|
+
await pause(15);
|
|
87
|
+
const current = await readSourceOnce(filename);
|
|
88
|
+
if (current === previous) return current;
|
|
89
|
+
previous = current;
|
|
90
|
+
}
|
|
91
|
+
throw failure(409, 'SOURCE_UNSTABLE', 'The YAML is still being saved. Try importing it again.');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function startYamlEditorHost({siteDirectory, dataDirectory, launchEditor = launchVSCode, port = 0} = {}) {
|
|
95
|
+
if (typeof siteDirectory !== 'string' || !path.isAbsolute(siteDirectory)) {
|
|
96
|
+
throw new TypeError('siteDirectory must be an absolute Editor build directory.');
|
|
97
|
+
}
|
|
98
|
+
if (typeof launchEditor !== 'function') throw new TypeError('launchEditor must be a function.');
|
|
99
|
+
if (!Number.isSafeInteger(port) || port < 0 || port > 65535) throw new TypeError('Invalid local server port.');
|
|
100
|
+
const siteRoot = await realpath(siteDirectory);
|
|
101
|
+
if (!(await stat(siteRoot)).isDirectory()) throw new TypeError('siteDirectory must be a directory.');
|
|
102
|
+
const editorFile = await realpath(path.join(siteRoot, 'editor.html'));
|
|
103
|
+
if (!within(siteRoot, editorFile) || !(await stat(editorFile)).isFile()) throw new TypeError('An Editor build with editor.html is required.');
|
|
104
|
+
let storage;
|
|
105
|
+
if (dataDirectory !== undefined) {
|
|
106
|
+
if (typeof dataDirectory !== 'string' || !path.isAbsolute(dataDirectory)) throw new TypeError('dataDirectory must be absolute.');
|
|
107
|
+
await mkdir(dataDirectory, {recursive: true, mode: 0o700});
|
|
108
|
+
if (!(await lstat(dataDirectory)).isDirectory()) throw new TypeError('dataDirectory must not be a symbolic link.');
|
|
109
|
+
const base = await realpath(dataDirectory);
|
|
110
|
+
if (within(siteRoot, base)) throw new TypeError('Working YAML files must be outside the Editor site.');
|
|
111
|
+
storage = await mkdtemp(path.join(base, 'twpe-yaml-'));
|
|
112
|
+
} else storage = await mkdtemp(path.join(tmpdir(), 'twpe-yaml-'));
|
|
113
|
+
const sessionsRoot = path.join(storage, 'sessions');
|
|
114
|
+
const profile = await createVSCodeProfile(storage);
|
|
115
|
+
await mkdir(sessionsRoot, {mode: 0o700});
|
|
116
|
+
await writeFile(path.join(storage, 'host.json'), JSON.stringify({createdAt: new Date().toISOString(), dataDirectory: storage, vscodeProfile: profile}, null, 2), {mode: 0o600, flag: 'wx'});
|
|
117
|
+
const token = randomBytes(32).toString('base64url');
|
|
118
|
+
const sessions = new Map();
|
|
119
|
+
let apiOrigin;
|
|
120
|
+
let closing = false;
|
|
121
|
+
let closePromise;
|
|
122
|
+
let pendingSessions = 0;
|
|
123
|
+
const server = createServer((request, response) => {
|
|
124
|
+
void handle(request, response).catch(error => {
|
|
125
|
+
if (response.headersSent) { response.destroy(); return; }
|
|
126
|
+
json(response, error.status || 500, {error: error.status ? error.message : 'The local YAML operation failed.', code: error.code || 'YAML_HOST_ERROR'});
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
server.requestTimeout = 15_000;
|
|
130
|
+
server.headersTimeout = 10_000;
|
|
131
|
+
|
|
132
|
+
function authorizeRequest(request) {
|
|
133
|
+
if (!loopbackAddresses.has(request.socket.remoteAddress) || request.headers.host !== new URL(apiOrigin).host) {
|
|
134
|
+
throw failure(403, 'INVALID_HOST', 'Only this loopback Editor host is accepted.');
|
|
135
|
+
}
|
|
136
|
+
if (request.headers.origin !== undefined && request.headers.origin !== apiOrigin) {
|
|
137
|
+
throw failure(403, 'INVALID_ORIGIN', 'Use the local Editor from the same origin.');
|
|
138
|
+
}
|
|
139
|
+
const fetchSite = request.headers['sec-fetch-site'];
|
|
140
|
+
if (fetchSite !== undefined && !['same-origin', 'none'].includes(fetchSite)) {
|
|
141
|
+
throw failure(403, 'INVALID_ORIGIN', 'Cross-origin requests are not accepted.');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function authorizeToken(request) {
|
|
146
|
+
const received = request.headers['x-twpe-yaml-token'];
|
|
147
|
+
if (typeof received !== 'string' || Buffer.byteLength(received) !== Buffer.byteLength(token) || !timingSafeEqual(Buffer.from(received), Buffer.from(token))) {
|
|
148
|
+
throw failure(401, 'INVALID_TOKEN', 'The local YAML session token is missing or invalid.');
|
|
149
|
+
}
|
|
150
|
+
if (['POST', 'DELETE'].includes(request.method) && request.headers.origin !== apiOrigin) {
|
|
151
|
+
throw failure(403, 'INVALID_ORIGIN', 'A same-origin request is required.');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function handleAPI(request, response, pathname) {
|
|
156
|
+
if (closing) throw failure(503, 'HOST_CLOSED', 'The local YAML host is closing.');
|
|
157
|
+
if (pathname === `${apiPrefix}/config`) {
|
|
158
|
+
if (request.method !== 'GET') throw failure(405, 'METHOD_NOT_ALLOWED', 'Use GET for configuration.');
|
|
159
|
+
json(response, 200, {available: true, token, editor: 'VSCode', maxSourceBytes});
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
authorizeToken(request);
|
|
163
|
+
if (pathname === `${apiPrefix}/sessions` && request.method === 'POST') {
|
|
164
|
+
if (sessions.size + pendingSessions >= maximumSessions) throw failure(429, 'SESSION_LIMIT', 'Close an existing YAML session first.');
|
|
165
|
+
pendingSessions++;
|
|
166
|
+
try {
|
|
167
|
+
const input = await readJSON(request);
|
|
168
|
+
if (!input || Array.isArray(input) || typeof input !== 'object' || Object.keys(input).some(key => !['source', 'sourceName', 'schema', 'format'].includes(key))) {
|
|
169
|
+
throw failure(400, 'INVALID_SESSION', 'Supply source and optional sourceName, schema and format.');
|
|
170
|
+
}
|
|
171
|
+
const format = input.format === undefined ? 'yaml' : input.format;
|
|
172
|
+
if (!['yaml', 'json'].includes(format)) throw failure(400, 'INVALID_FORMAT', 'Choose YAML or JSON.');
|
|
173
|
+
if (typeof input.source !== 'string') throw failure(400, 'INVALID_SOURCE', 'The YAML source must be a string.');
|
|
174
|
+
if (Buffer.byteLength(input.source, 'utf8') > maxSourceBytes) throw failure(413, 'SOURCE_TOO_LARGE', 'The YAML exceeds the size limit.');
|
|
175
|
+
if (input.sourceName !== undefined && (typeof input.sourceName !== 'string' || input.sourceName.length > 256 || /[/\\\x00-\x1f\x7f]/u.test(input.sourceName) || ['.', '..'].includes(input.sourceName))) {
|
|
176
|
+
throw failure(400, 'INVALID_SOURCE_NAME', 'The source name must be a plain filename.');
|
|
177
|
+
}
|
|
178
|
+
let schema;
|
|
179
|
+
try { schema = input.schema === undefined ? undefined : normalizeSourceDocumentSchema(input.schema); }
|
|
180
|
+
catch { throw failure(400, 'INVALID_SCHEMA', 'Supply a bounded inline JSON Schema object.'); }
|
|
181
|
+
const id = randomBytes(16).toString('hex');
|
|
182
|
+
const directory = path.join(sessionsRoot, id);
|
|
183
|
+
const suffix = format === 'json' ? '.json' : '.yml';
|
|
184
|
+
const suppliedName = input.sourceName || `document${suffix}`;
|
|
185
|
+
let filename = suppliedName.replace(/[<>:"|?*]/gu, '_').replace(/[. ]+$/gu, '');
|
|
186
|
+
if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(filename)) filename = `_${filename}`;
|
|
187
|
+
if (!(format === 'json' ? /\.json$/iu : /\.ya?ml$/iu).test(filename)) filename += suffix;
|
|
188
|
+
if (Buffer.byteLength(filename) > 240) throw failure(400, 'INVALID_SOURCE_NAME', 'The UTF-8 source filename is too long.');
|
|
189
|
+
const filePath = path.join(directory, filename);
|
|
190
|
+
await mkdir(directory, {mode: 0o700});
|
|
191
|
+
await writeFile(filePath, input.source, {encoding: 'utf8', mode: 0o600, flag: 'wx'});
|
|
192
|
+
const metadataDirectory = path.join(directory, '.twpe');
|
|
193
|
+
await mkdir(metadataDirectory, {mode: 0o700});
|
|
194
|
+
await writeFile(path.join(metadataDirectory, 'session.json'), JSON.stringify({id, sourceName: input.sourceName || filename, format, createdAt: new Date().toISOString(), vscodeProfile: profile.directory}), {mode: 0o600, flag: 'wx'});
|
|
195
|
+
const schemaWorkspace = await writeSchemaWorkspace(directory, schema, {format, filename});
|
|
196
|
+
const launchOptions = {...profile, format, ...(schemaWorkspace || {})};
|
|
197
|
+
const session = {filePath, source: input.source, revision: 1, launchOptions};
|
|
198
|
+
try { await launchEditor(filePath, launchOptions); }
|
|
199
|
+
catch {
|
|
200
|
+
throw failure(503, 'EDITOR_LAUNCH_FAILED', 'VSCode could not be started. Your working YAML file was retained.');
|
|
201
|
+
}
|
|
202
|
+
if (closing) throw failure(503, 'HOST_CLOSED', 'The local YAML host is closing. Your working YAML file was retained.');
|
|
203
|
+
sessions.set(id, session);
|
|
204
|
+
json(response, 201, {id, revision: session.revision, opened: true, format, ...(schemaWorkspace ? {schemaId: schemaWorkspace.schemaId} : {})});
|
|
205
|
+
} finally { pendingSessions--; }
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const id = pathname.startsWith(`${apiPrefix}/sessions/`) ? pathname.slice(`${apiPrefix}/sessions/`.length) : null;
|
|
209
|
+
if (id === null) throw failure(404, 'NOT_FOUND', 'This YAML API endpoint does not exist.');
|
|
210
|
+
if (!idPattern.test(id)) throw failure(400, 'INVALID_SESSION', 'The YAML session identifier is invalid.');
|
|
211
|
+
const session = sessions.get(id);
|
|
212
|
+
if (!session) throw failure(404, 'SESSION_NOT_FOUND', 'The YAML session is no longer active.');
|
|
213
|
+
if (request.method === 'POST') {
|
|
214
|
+
await readStableSource(session.filePath);
|
|
215
|
+
if (sessions.get(id) !== session) throw failure(404, 'SESSION_NOT_FOUND', 'The YAML session is no longer active.');
|
|
216
|
+
try { await launchEditor(session.filePath, session.launchOptions); }
|
|
217
|
+
catch { throw failure(503, 'EDITOR_LAUNCH_FAILED', 'VSCode could not be started. Your working file was retained.'); }
|
|
218
|
+
if (closing) throw failure(503, 'HOST_CLOSED', 'The local YAML host is closing. Your working file was retained.');
|
|
219
|
+
if (sessions.get(id) !== session) throw failure(404, 'SESSION_NOT_FOUND', 'The YAML session is no longer active.');
|
|
220
|
+
json(response, 200, {id, revision: session.revision, opened: true});
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (request.method === 'DELETE') {
|
|
224
|
+
sessions.delete(id);
|
|
225
|
+
json(response, 200, {id, closed: true, retained: true});
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (request.method !== 'GET') throw failure(405, 'METHOD_NOT_ALLOWED', 'Use GET, POST or DELETE for a YAML session.');
|
|
229
|
+
const source = await readStableSource(session.filePath);
|
|
230
|
+
if (sessions.get(id) !== session) throw failure(404, 'SESSION_NOT_FOUND', 'The YAML session is no longer active.');
|
|
231
|
+
if (source !== session.source) { session.source = source; session.revision++; }
|
|
232
|
+
json(response, 200, {id, source, revision: session.revision});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function handle(request, response) {
|
|
236
|
+
response.setHeader('cache-control', 'no-store');
|
|
237
|
+
response.setHeader('x-content-type-options', 'nosniff');
|
|
238
|
+
response.setHeader('referrer-policy', 'no-referrer');
|
|
239
|
+
response.setHeader('cross-origin-resource-policy', 'same-origin');
|
|
240
|
+
authorizeRequest(request);
|
|
241
|
+
let pathname;
|
|
242
|
+
try { pathname = decodeURIComponent((request.url || '/').split('?')[0]); }
|
|
243
|
+
catch { throw failure(400, 'INVALID_PATH', 'The request path is invalid.'); }
|
|
244
|
+
if (pathname.includes('\\') || pathname.includes('\0') || pathname.split('/').some(segment => segment === '..')) {
|
|
245
|
+
throw failure(403, 'INVALID_PATH', 'Parent paths are not served.');
|
|
246
|
+
}
|
|
247
|
+
if (pathname === apiPrefix || pathname.startsWith(`${apiPrefix}/`)) return handleAPI(request, response, pathname);
|
|
248
|
+
if (!['GET', 'HEAD'].includes(request.method)) throw failure(405, 'METHOD_NOT_ALLOWED', 'Use GET or HEAD for Editor files.');
|
|
249
|
+
if (pathname === '/' || pathname === '/turbowarp-plus-editor') {
|
|
250
|
+
response.writeHead(302, {location: '/turbowarp-plus-editor/editor.html?twPlusYamlEditor=1'});
|
|
251
|
+
response.end();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const prefix = '/turbowarp-plus-editor/';
|
|
255
|
+
if (!pathname.startsWith(prefix)) throw failure(404, 'NOT_FOUND', 'This local file is not available.');
|
|
256
|
+
const relative = pathname.slice(prefix.length) || 'index.html';
|
|
257
|
+
const candidate = path.resolve(siteRoot, relative);
|
|
258
|
+
if (!within(siteRoot, candidate)) throw failure(403, 'INVALID_PATH', 'The file is outside the Editor site.');
|
|
259
|
+
const filename = await realpath(candidate).catch(() => { throw failure(404, 'NOT_FOUND', 'This Editor file does not exist.'); });
|
|
260
|
+
if (!within(siteRoot, filename)) throw failure(403, 'INVALID_PATH', 'Files outside the Editor site are not served.');
|
|
261
|
+
const entry = await stat(filename);
|
|
262
|
+
if (!entry.isFile()) throw failure(404, 'NOT_FOUND', 'This Editor file does not exist.');
|
|
263
|
+
response.writeHead(200, {'content-type': mimeTypes[path.extname(filename).toLowerCase()] || 'application/octet-stream', 'content-length': entry.size});
|
|
264
|
+
if (request.method === 'HEAD') { response.end(); return; }
|
|
265
|
+
await pipeline(createReadStream(filename), response);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
await new Promise((resolve, reject) => {
|
|
269
|
+
server.once('error', reject);
|
|
270
|
+
server.listen(port, '127.0.0.1', resolve);
|
|
271
|
+
});
|
|
272
|
+
apiOrigin = `http://127.0.0.1:${server.address().port}`;
|
|
273
|
+
return Object.freeze({
|
|
274
|
+
url: `${apiOrigin}/turbowarp-plus-editor/editor.html?twPlusYamlEditor=1`,
|
|
275
|
+
apiOrigin, dataDirectory: storage,
|
|
276
|
+
profileDirectory: profile.directory,
|
|
277
|
+
userDataDirectory: profile.userDataDirectory,
|
|
278
|
+
extensionsDirectory: profile.extensionsDirectory,
|
|
279
|
+
profileSeparated: profile.separated,
|
|
280
|
+
close() {
|
|
281
|
+
if (closePromise) return closePromise;
|
|
282
|
+
closing = true;
|
|
283
|
+
sessions.clear();
|
|
284
|
+
closePromise = new Promise((resolve, reject) => {
|
|
285
|
+
server.close(error => error ? reject(error) : resolve());
|
|
286
|
+
server.closeIdleConnections?.();
|
|
287
|
+
});
|
|
288
|
+
return closePromise;
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import {mkdir, writeFile} from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {pathToFileURL} from 'node:url';
|
|
4
|
+
import {normalizeSourceDocumentSchema} from '@kubohiroya/turbowarp-document-data/composition';
|
|
5
|
+
|
|
6
|
+
/** Associate the exact owner schema without inserting a modeline into the source. */
|
|
7
|
+
export async function writeSchemaWorkspace(directory, metadata, {format = 'yaml', filename = 'story.k4.yml'} = {}) {
|
|
8
|
+
if (metadata === undefined) return null;
|
|
9
|
+
const normalized = normalizeSourceDocumentSchema(metadata);
|
|
10
|
+
const metadataDirectory = path.join(directory, '.twpe');
|
|
11
|
+
await mkdir(metadataDirectory, {recursive: true, mode: 0o700});
|
|
12
|
+
const schemaFile = path.join(metadataDirectory, 'schema.json');
|
|
13
|
+
const workspaceFile = path.join(metadataDirectory, 'editor.code-workspace');
|
|
14
|
+
await writeFile(schemaFile, JSON.stringify(normalized.schema, null, 2) + '\n', {mode: 0o600, flag: 'wx'});
|
|
15
|
+
const settings = format === 'json' ? {
|
|
16
|
+
'json.schemas': [{fileMatch: [filename], url: pathToFileURL(schemaFile).href}],
|
|
17
|
+
'json.validate.enable': true, 'files.associations': {[filename]: 'json'}
|
|
18
|
+
} : {
|
|
19
|
+
'yaml.schemas': {[pathToFileURL(schemaFile).href]: [filename]},
|
|
20
|
+
'yaml.validate': true, 'yaml.completion': true, 'yaml.hover': true,
|
|
21
|
+
'yaml.schemaStore.enable': false,
|
|
22
|
+
'files.associations': {[filename]: 'yaml'}
|
|
23
|
+
};
|
|
24
|
+
await writeFile(workspaceFile, JSON.stringify({folders: [{path: '..'}], settings}, null, 2) + '\n', {mode: 0o600, flag: 'wx'});
|
|
25
|
+
return {workspaceFile, schemaFile, schemaId: normalized.id};
|
|
26
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import {access, mkdir, mkdtemp, readdir, realpath, readFile, writeFile} from 'node:fs/promises';
|
|
2
|
+
import {constants} from 'node:fs';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {spawn} from 'node:child_process';
|
|
6
|
+
import {createConnection} from 'node:net';
|
|
7
|
+
import {setTimeout as pause} from 'node:timers/promises';
|
|
8
|
+
|
|
9
|
+
function shortSocketPath(directory) {
|
|
10
|
+
return Buffer.byteLength(path.join(directory, '1.00-main.sock')) <= 100;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function createVSCodeProfile(storage) {
|
|
14
|
+
let directory = storage;
|
|
15
|
+
if (process.platform !== 'win32' && !shortSocketPath(path.join(directory, 'u'))) {
|
|
16
|
+
const temporaryRoot = await realpath(process.platform === 'darwin' ? '/private/tmp' : '/tmp');
|
|
17
|
+
directory = await mkdtemp(path.join(temporaryRoot, 'twpe-code-'));
|
|
18
|
+
}
|
|
19
|
+
const userDataDirectory = path.join(directory, 'u');
|
|
20
|
+
const extensionsDirectory = path.join(directory, 'e');
|
|
21
|
+
await Promise.all([userDataDirectory, extensionsDirectory].map(item => mkdir(item, {mode: 0o700})));
|
|
22
|
+
const resolvedUserData = await realpath(userDataDirectory);
|
|
23
|
+
if (process.platform !== 'win32' && !shortSocketPath(resolvedUserData)) {
|
|
24
|
+
throw new Error('The private VSCode IPC path is too long.');
|
|
25
|
+
}
|
|
26
|
+
const settingsDirectory = path.join(resolvedUserData, 'User');
|
|
27
|
+
await mkdir(settingsDirectory, {mode: 0o700});
|
|
28
|
+
// Application-scoped settings belong to this private profile, never the workspace.
|
|
29
|
+
await writeFile(path.join(settingsDirectory, 'settings.json'), JSON.stringify({
|
|
30
|
+
'extensions.autoUpdate': 'off', 'telemetry.telemetryLevel': 'off',
|
|
31
|
+
'redhat.telemetry.enabled': false
|
|
32
|
+
}, null, 2) + '\n', {mode: 0o600, flag: 'wx'});
|
|
33
|
+
return {directory, userDataDirectory: resolvedUserData, extensionsDirectory: await realpath(extensionsDirectory), separated: directory !== storage};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function socketAcceptsConnections(filename) {
|
|
37
|
+
return new Promise(resolve => {
|
|
38
|
+
const socket = createConnection({path: filename});
|
|
39
|
+
let settled = false;
|
|
40
|
+
const finish = accepted => {
|
|
41
|
+
if (settled) return;
|
|
42
|
+
settled = true;
|
|
43
|
+
socket.destroy();
|
|
44
|
+
resolve(accepted);
|
|
45
|
+
};
|
|
46
|
+
socket.setTimeout(250, () => finish(false));
|
|
47
|
+
socket.once('error', () => finish(false));
|
|
48
|
+
socket.once('connect', () => finish(true));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function waitForVSCodeReady(userDataDirectory, {platform = process.platform, timeoutMs = 10_000} = {}) {
|
|
53
|
+
if (platform === 'win32') return;
|
|
54
|
+
const deadline = Date.now() + timeoutMs;
|
|
55
|
+
do {
|
|
56
|
+
const entries = await readdir(userDataDirectory).catch(() => []);
|
|
57
|
+
for (const filename of entries.filter(name => name.endsWith('-main.sock'))) {
|
|
58
|
+
if (await socketAcceptsConnections(path.join(userDataDirectory, filename))) return;
|
|
59
|
+
}
|
|
60
|
+
await pause(Math.min(100, Math.max(0, deadline - Date.now())));
|
|
61
|
+
} while (Date.now() < deadline);
|
|
62
|
+
const error = new Error('VSCode did not open its private instance after the launch request.');
|
|
63
|
+
error.code = 'VSCODE_INSTANCE_UNAVAILABLE';
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function findVSCodeExecutable() {
|
|
68
|
+
const candidates = process.platform === 'darwin' ? [
|
|
69
|
+
'/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code',
|
|
70
|
+
path.join(homedir(), 'Applications/Visual Studio Code.app/Contents/Resources/app/bin/code')
|
|
71
|
+
] : process.platform === 'win32' ? [
|
|
72
|
+
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs/Microsoft VS Code/Code.exe'),
|
|
73
|
+
process.env.ProgramFiles && path.join(process.env.ProgramFiles, 'Microsoft VS Code/Code.exe')
|
|
74
|
+
] : ['/usr/bin/code', '/usr/local/bin/code', '/snap/bin/code'];
|
|
75
|
+
if (process.platform !== 'win32') {
|
|
76
|
+
for (const directory of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
|
|
77
|
+
candidates.push(path.resolve(directory, 'code'));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const candidate of [...new Set(candidates.filter(Boolean))]) {
|
|
81
|
+
try {
|
|
82
|
+
await access(candidate, constants.X_OK);
|
|
83
|
+
return candidate;
|
|
84
|
+
} catch {}
|
|
85
|
+
}
|
|
86
|
+
const error = new Error('VSCode is unavailable. Install Visual Studio Code before opening a YAML session.');
|
|
87
|
+
error.code = 'VSCODE_UNAVAILABLE';
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const yamlExtensionId = 'redhat.vscode-yaml';
|
|
92
|
+
export const yamlExtensionVersion = '2.0.0';
|
|
93
|
+
|
|
94
|
+
function isolatedEnvironment() {
|
|
95
|
+
const env = {...process.env};
|
|
96
|
+
for (const key of Object.keys(env)) if (key.startsWith('VSCODE_')) delete env[key];
|
|
97
|
+
delete env.ELECTRON_RUN_AS_NODE;
|
|
98
|
+
return env;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Install only the pinned official YAML extension into the private profile. */
|
|
102
|
+
export async function ensureYamlSupport(profile, {findExecutable = findVSCodeExecutable, spawnProcess = spawn, timeoutMs = 120_000} = {}) {
|
|
103
|
+
const installed = async () => {
|
|
104
|
+
for (const name of await readdir(profile.extensionsDirectory)) {
|
|
105
|
+
if (!name.startsWith(`${yamlExtensionId}-${yamlExtensionVersion}`)) continue;
|
|
106
|
+
try {
|
|
107
|
+
const manifest = JSON.parse(await readFile(path.join(profile.extensionsDirectory, name, 'package.json'), 'utf8'));
|
|
108
|
+
if (manifest.publisher.toLowerCase() === 'redhat' && manifest.name === 'vscode-yaml' && manifest.version === yamlExtensionVersion) return true;
|
|
109
|
+
} catch {}
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
};
|
|
113
|
+
if (await installed()) return;
|
|
114
|
+
const executable = await findExecutable();
|
|
115
|
+
await new Promise((resolve, reject) => {
|
|
116
|
+
const child = spawnProcess(executable, ['--user-data-dir', profile.userDataDirectory,
|
|
117
|
+
'--extensions-dir', profile.extensionsDirectory, '--install-extension', `${yamlExtensionId}@${yamlExtensionVersion}`],
|
|
118
|
+
{shell: false, stdio: 'ignore', env: isolatedEnvironment()});
|
|
119
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error('The private YAML extension installation timed out.')); }, timeoutMs);
|
|
120
|
+
child.once('error', error => { clearTimeout(timer); reject(error); });
|
|
121
|
+
child.once('exit', code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error('The official YAML extension could not be installed.')); });
|
|
122
|
+
});
|
|
123
|
+
if (!await installed()) throw new Error('The pinned official YAML extension is unavailable in this private profile.');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function launchVSCode(filePath, {userDataDirectory, extensionsDirectory, workspaceFile, format = 'yaml'}, {
|
|
127
|
+
findExecutable = findVSCodeExecutable,
|
|
128
|
+
spawnProcess = spawn,
|
|
129
|
+
platform = process.platform,
|
|
130
|
+
timeoutMs = 15_000,
|
|
131
|
+
startupGraceMs = 500,
|
|
132
|
+
checkReady = waitForVSCodeReady,
|
|
133
|
+
ensureSupport = ensureYamlSupport
|
|
134
|
+
} = {}) {
|
|
135
|
+
const executable = await findExecutable();
|
|
136
|
+
await mkdir(userDataDirectory, {recursive: true, mode: 0o700});
|
|
137
|
+
await mkdir(extensionsDirectory, {recursive: true, mode: 0o700});
|
|
138
|
+
const env = isolatedEnvironment();
|
|
139
|
+
if (workspaceFile && format === 'yaml') await ensureSupport({userDataDirectory, extensionsDirectory});
|
|
140
|
+
const args = [
|
|
141
|
+
'--new-window', ...(workspaceFile ? [] : ['--disable-extensions']), '--disable-workspace-trust',
|
|
142
|
+
'--skip-welcome', '--skip-release-notes',
|
|
143
|
+
'--user-data-dir', userDataDirectory, '--extensions-dir', extensionsDirectory,
|
|
144
|
+
'--', ...(workspaceFile ? [workspaceFile] : []), filePath
|
|
145
|
+
];
|
|
146
|
+
await new Promise((resolve, reject) => {
|
|
147
|
+
const child = spawnProcess(executable, args, {shell: false, detached: true, stdio: 'ignore', env});
|
|
148
|
+
let settled = false;
|
|
149
|
+
let timer;
|
|
150
|
+
const finish = error => {
|
|
151
|
+
if (settled) return;
|
|
152
|
+
settled = true;
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
if (error) reject(error);
|
|
155
|
+
else resolve();
|
|
156
|
+
};
|
|
157
|
+
child.once('error', finish);
|
|
158
|
+
child.once('exit', (code, signal) => finish(code === 0 ? undefined : new Error(`VSCode startup failed (${signal || `exit ${code}`}).`)));
|
|
159
|
+
child.once('spawn', () => {
|
|
160
|
+
child.unref();
|
|
161
|
+
if (platform === 'win32') {
|
|
162
|
+
// The Windows GUI process can outlive the request; catch immediate startup errors.
|
|
163
|
+
timer = setTimeout(() => finish(), startupGraceMs);
|
|
164
|
+
} else {
|
|
165
|
+
// The non-waiting macOS/Linux CLI must acknowledge the launch with exit zero.
|
|
166
|
+
timer = setTimeout(() => {
|
|
167
|
+
child.kill();
|
|
168
|
+
finish(new Error('VSCode startup acknowledgement timed out.'));
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
await checkReady(userDataDirectory, {platform});
|
|
174
|
+
}
|
package/site/source.json
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"guiRepository": "kubohiroya/scratch-gui",
|
|
3
|
-
"guiRevision": "
|
|
3
|
+
"guiRevision": "3088e13ef132d26eebe9b3e9024b19130dabce51",
|
|
4
4
|
"coreRepository": "kubohiroya/turbowarp-extension-data-editor",
|
|
5
|
-
"coreRevision": "
|
|
5
|
+
"coreRevision": "d96532a91bc6046d4a3fda878425b30d6d10483e",
|
|
6
6
|
"securityPackage": "@kubohiroya/turbowarp-extension-security-dialog",
|
|
7
|
-
"securityVersion": "0.
|
|
7
|
+
"securityVersion": "0.4.0",
|
|
8
|
+
"securityRevision": "f9a5996d27789a7f4cd4ea26838ce74bda451daa",
|
|
9
|
+
"loaderRepository": "kubohiroya/turbowarp-extension-loader",
|
|
10
|
+
"loaderRevision": "9dc2689a8e2b5416687f27d1ec089b3531fd03c7",
|
|
11
|
+
"vmRepository": "kubohiroya/scratch-vm",
|
|
12
|
+
"vmRevision": "c7ed7b24a9dfbec4ec64f654dbbee2ebb17a8b06",
|
|
13
|
+
"vmBaseRevision": "55fd9b7c9509827c9cec31482aa63f2d57ec564d",
|
|
14
|
+
"packagerRepository": "TurboWarp/packager",
|
|
15
|
+
"packagerRevision": "c115bdf525c5f49f0fb689a21b335ccb70fc22d2",
|
|
16
|
+
"coreVersion": "0.7.0"
|
|
8
17
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import {readStartupFeatureFlags} from '../config/feature-flags.js';
|
|
2
|
+
|
|
3
|
+
/** Connect trusted, host-supplied modules without interpreting project policy. */
|
|
4
|
+
export async function bootstrapExtensionLoader({
|
|
5
|
+
startupSearch = '', loaderModule, integration, host, ports, loaderOptions
|
|
6
|
+
} = {}) {
|
|
7
|
+
const flags = readStartupFeatureFlags(startupSearch);
|
|
8
|
+
if (!flags.extensionLoader) {
|
|
9
|
+
return Object.freeze({enabled: false, dispose: async () => {}});
|
|
10
|
+
}
|
|
11
|
+
if (typeof loaderModule?.createExtensionLoader !== 'function' ||
|
|
12
|
+
typeof integration?.installExtensionLoader !== 'function') {
|
|
13
|
+
throw new TypeError('Trusted Loader and GUI integration modules are required');
|
|
14
|
+
}
|
|
15
|
+
const loader = loaderModule.createExtensionLoader(ports, loaderOptions);
|
|
16
|
+
let uninstall;
|
|
17
|
+
try {
|
|
18
|
+
uninstall = await integration.installExtensionLoader(host, loader);
|
|
19
|
+
if (typeof uninstall !== 'function') {
|
|
20
|
+
throw new TypeError('GUI integration must return an uninstall function');
|
|
21
|
+
}
|
|
22
|
+
} catch (error) {
|
|
23
|
+
try {
|
|
24
|
+
await loader.unload();
|
|
25
|
+
} catch (cleanupError) {
|
|
26
|
+
throw new AggregateError([error, cleanupError], 'Loader installation and cleanup failed');
|
|
27
|
+
}
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
let disposal;
|
|
31
|
+
return Object.freeze({
|
|
32
|
+
enabled: true,
|
|
33
|
+
dispose() {
|
|
34
|
+
if (!disposal) {
|
|
35
|
+
disposal = (async () => {
|
|
36
|
+
let uninstallError;
|
|
37
|
+
try {
|
|
38
|
+
await uninstall();
|
|
39
|
+
} catch (error) {
|
|
40
|
+
uninstallError = error;
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
await loader.unload();
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (uninstallError) {
|
|
46
|
+
throw new AggregateError([uninstallError, error], 'GUI teardown and Loader unload failed');
|
|
47
|
+
}
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (uninstallError) throw uninstallError;
|
|
51
|
+
})();
|
|
52
|
+
}
|
|
53
|
+
return disposal;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
package/src/index.js
CHANGED
|
@@ -22,6 +22,12 @@ const escapeHTML = value => String(value).replace(/[&<>"']/g, character => ({
|
|
|
22
22
|
}[character]));
|
|
23
23
|
|
|
24
24
|
export function renderEditButton(options = {}) {
|
|
25
|
+
const size = options.size ?? 'normal';
|
|
26
|
+
if (!['normal', 'small'].includes(size)) throw new TypeError('size must be normal or small');
|
|
27
|
+
const small = size === 'small';
|
|
25
28
|
const label = options.language === 'en' ? 'Edit in TurboWarp-Plus-Editor' : 'TurboWarp-Plus-Editorで編集';
|
|
26
|
-
|
|
29
|
+
const text = small ? (options.language === 'en' ? 'Edit' : '編集') : label;
|
|
30
|
+
const attributes = small ? ` title="${label}" aria-label="${label}"` : '';
|
|
31
|
+
const iconSize = small ? 24 : 36;
|
|
32
|
+
return `<a class="twpe-edit-button${small ? ' twpe-edit-button--small' : ''}" href="${escapeHTML(createEditorURL(options))}"${attributes}><img src="${iconURL}" width="${iconSize}" height="${iconSize}" alt="" aria-hidden="true"><span>${text}</span></a>`;
|
|
27
33
|
}
|