@iwsdk/cli 0.5.3 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -1
- package/bin/iwsdk.js +1 -1
- package/dist/browser-lease.d.ts +14 -0
- package/dist/browser-lease.d.ts.map +1 -0
- package/dist/cli-types.d.ts +1 -1
- package/dist/cli-types.d.ts.map +1 -1
- package/dist/cli.js +2811 -485
- package/dist/cli.js.map +1 -1
- package/dist/commands/browser.d.ts +14 -0
- package/dist/commands/browser.d.ts.map +1 -0
- package/dist/commands/dev.d.ts +6 -2
- package/dist/commands/dev.d.ts.map +1 -1
- package/dist/commands/runtime.d.ts.map +1 -1
- package/dist/commands/status.d.ts.map +1 -1
- package/dist/contract.js +481 -30
- package/dist/contract.js.map +1 -1
- package/dist/help.d.ts +1 -0
- package/dist/help.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2813 -487
- package/dist/index.js.map +1 -1
- package/dist/mcp-stdio.d.ts.map +1 -1
- package/dist/runtime-contract.d.ts +70 -1
- package/dist/runtime-contract.d.ts.map +1 -1
- package/dist/runtime-files.d.ts +19 -0
- package/dist/runtime-files.d.ts.map +1 -0
- package/dist/runtime-files.js +318 -0
- package/dist/runtime-files.js.map +1 -0
- package/dist/runtime-owner.d.ts +50 -0
- package/dist/runtime-owner.d.ts.map +1 -0
- package/dist/runtime-owner.js +539 -0
- package/dist/runtime-owner.js.map +1 -0
- package/dist/runtime-state.d.ts +20 -18
- package/dist/runtime-state.d.ts.map +1 -1
- package/dist/runtime-transport.d.ts.map +1 -1
- package/dist/screenshot-output.d.ts +13 -0
- package/dist/screenshot-output.d.ts.map +1 -0
- package/guidance/AGENTS.md +96 -37
- package/package.json +16 -2
package/dist/index.js
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
import { existsSync, realpathSync, readFileSync, openSync, closeSync } from 'fs';
|
|
2
|
-
import {
|
|
2
|
+
import { mkdir, mkdtemp, writeFile, readdir, rename, unlink, rmdir, rm, readFile, copyFile } from 'fs/promises';
|
|
3
3
|
import path from 'path';
|
|
4
|
-
import require$$7, { fileURLToPath } from 'url';
|
|
5
|
-
import { spawn } from 'child_process';
|
|
4
|
+
import require$$7, { fileURLToPath, pathToFileURL } from 'url';
|
|
5
|
+
import { execFileSync, spawn } from 'child_process';
|
|
6
|
+
import require$$1, { randomUUID, createHash as createHash$2 } from 'crypto';
|
|
7
|
+
import require$$3$1, { createConnection } from 'net';
|
|
8
|
+
import { createRequire } from 'module';
|
|
6
9
|
import require$$0$3 from 'events';
|
|
7
10
|
import require$$1$1 from 'https';
|
|
8
11
|
import require$$2$1 from 'http';
|
|
9
|
-
import require$$3$1 from 'net';
|
|
10
12
|
import require$$4 from 'tls';
|
|
11
|
-
import require$$1 from 'crypto';
|
|
12
13
|
import require$$0$2 from 'stream';
|
|
13
14
|
import require$$0 from 'zlib';
|
|
14
15
|
import require$$0$1 from 'buffer';
|
|
15
16
|
import require$$2 from 'util';
|
|
16
17
|
import process$2 from 'node:process';
|
|
17
|
-
import {
|
|
18
|
+
import { randomUUID as randomUUID$1 } from 'node:crypto';
|
|
18
19
|
import os from 'os';
|
|
19
20
|
|
|
20
21
|
/**
|
|
@@ -150,9 +151,25 @@ var mcpSurfaceMarkers = {
|
|
|
150
151
|
*/
|
|
151
152
|
const DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS = 30_000;
|
|
152
153
|
const UI_RENDER_PREVIEW_TIMEOUT_MS = 60_000;
|
|
154
|
+
const ASSET_RENDER_PREVIEW_TIMEOUT_MS = 120_000;
|
|
155
|
+
const BROWSER_RUNTIME_COMMAND_TIMEOUT_MS = 60_000;
|
|
156
|
+
const BROWSER_RUNTIME_METHODS = new Set([
|
|
157
|
+
'browser_interact',
|
|
158
|
+
'browser_profile',
|
|
159
|
+
'browser_snapshot',
|
|
160
|
+
'get_console_logs',
|
|
161
|
+
'reload_page',
|
|
162
|
+
'screenshot',
|
|
163
|
+
]);
|
|
153
164
|
function getDefaultRuntimeCommandTimeoutMs(method) {
|
|
154
|
-
|
|
155
|
-
|
|
165
|
+
if (method === 'asset_render_preview') {
|
|
166
|
+
return ASSET_RENDER_PREVIEW_TIMEOUT_MS;
|
|
167
|
+
}
|
|
168
|
+
if (method === 'ui_render_preview') {
|
|
169
|
+
return UI_RENDER_PREVIEW_TIMEOUT_MS;
|
|
170
|
+
}
|
|
171
|
+
return BROWSER_RUNTIME_METHODS.has(method)
|
|
172
|
+
? BROWSER_RUNTIME_COMMAND_TIMEOUT_MS
|
|
156
173
|
: DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS;
|
|
157
174
|
}
|
|
158
175
|
function describeValue(value) {
|
|
@@ -232,10 +249,13 @@ function assertSchemaValue(value, schema, path) {
|
|
|
232
249
|
throw new Error(`${path} must be at most ${schema.maximum}`);
|
|
233
250
|
}
|
|
234
251
|
}
|
|
235
|
-
if (typeof value === 'string'
|
|
236
|
-
schema.
|
|
237
|
-
|
|
238
|
-
|
|
252
|
+
if (typeof value === 'string') {
|
|
253
|
+
if (schema.maxLength != null && value.length > schema.maxLength) {
|
|
254
|
+
throw new Error(`${path} allows at most ${schema.maxLength} characters`);
|
|
255
|
+
}
|
|
256
|
+
if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
|
|
257
|
+
throw new Error(`${path} must match ${schema.pattern}`);
|
|
258
|
+
}
|
|
239
259
|
}
|
|
240
260
|
if (Array.isArray(value)) {
|
|
241
261
|
if (schema.minItems != null && value.length < schema.minItems) {
|
|
@@ -279,6 +299,8 @@ const IWSDK_RUNTIME_LAUNCH_PATH = '.iwsdk/runtime/launch.json';
|
|
|
279
299
|
const IWSDK_RUNTIME_STATE_SCHEMA_VERSION = 2;
|
|
280
300
|
const IWSDK_RUNTIME_BROWSER_READY_SCHEMA_VERSION = 2;
|
|
281
301
|
const INTERNAL_BROWSER_PROBE_METHOD = '__iwsdk_browser_probe';
|
|
302
|
+
const INTERNAL_RUNTIME_SHUTDOWN_METHOD = '__iwsdk_runtime_shutdown';
|
|
303
|
+
const INTERNAL_RUNTIME_LAUNCH_CLAIM_ENV = 'IWSDK_DEV_LAUNCH_CLAIM_ID';
|
|
282
304
|
function hasRuntimeBrowserCommandReadyContract(session) {
|
|
283
305
|
if (!session?.browser) {
|
|
284
306
|
return false;
|
|
@@ -1001,14 +1023,234 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1001
1023
|
// =============================================================================
|
|
1002
1024
|
{
|
|
1003
1025
|
name: 'browser_screenshot',
|
|
1004
|
-
description: 'Capture the
|
|
1026
|
+
description: 'Capture the current application in the managed browser, persist the image locally, and return screenshotPath with capture metadata. The application surface is resolved automatically.',
|
|
1005
1027
|
inputSchema: {
|
|
1006
1028
|
type: 'object',
|
|
1007
|
-
properties: {
|
|
1029
|
+
properties: {
|
|
1030
|
+
format: {
|
|
1031
|
+
type: 'string',
|
|
1032
|
+
enum: ['png', 'jpeg'],
|
|
1033
|
+
description: 'Image format. Defaults to png.',
|
|
1034
|
+
},
|
|
1035
|
+
quality: {
|
|
1036
|
+
type: 'number',
|
|
1037
|
+
minimum: 20,
|
|
1038
|
+
maximum: 100,
|
|
1039
|
+
description: 'JPEG quality. Ignored for PNG.',
|
|
1040
|
+
},
|
|
1041
|
+
fullPage: {
|
|
1042
|
+
type: 'boolean',
|
|
1043
|
+
description: 'Capture the full application document when it fits the bounded 32-megapixel and 64-tile limits.',
|
|
1044
|
+
},
|
|
1045
|
+
ref: {
|
|
1046
|
+
type: 'string',
|
|
1047
|
+
description: 'Capture one fully visible element ref returned by browser_snapshot. Targets larger than the application viewport are rejected as non-retryable.',
|
|
1048
|
+
},
|
|
1049
|
+
},
|
|
1008
1050
|
required: [],
|
|
1009
1051
|
additionalProperties: false,
|
|
1010
1052
|
},
|
|
1011
1053
|
},
|
|
1054
|
+
{
|
|
1055
|
+
name: 'browser_snapshot',
|
|
1056
|
+
description: 'Inspect the current application as a compact accessibility-first list of interactive elements and canvas regions. Use returned refs with browser_interact.',
|
|
1057
|
+
inputSchema: {
|
|
1058
|
+
type: 'object',
|
|
1059
|
+
additionalProperties: false,
|
|
1060
|
+
properties: {
|
|
1061
|
+
maxNodes: {
|
|
1062
|
+
type: 'integer',
|
|
1063
|
+
minimum: 1,
|
|
1064
|
+
maximum: 1000,
|
|
1065
|
+
description: 'Maximum returned elements. Defaults to 200.',
|
|
1066
|
+
},
|
|
1067
|
+
maxTextLength: {
|
|
1068
|
+
type: 'integer',
|
|
1069
|
+
minimum: 16,
|
|
1070
|
+
maximum: 1000,
|
|
1071
|
+
description: 'Maximum text/name length per element. Defaults to 200.',
|
|
1072
|
+
},
|
|
1073
|
+
rootRef: {
|
|
1074
|
+
type: 'string',
|
|
1075
|
+
description: 'Optional existing ref used as the snapshot root.',
|
|
1076
|
+
},
|
|
1077
|
+
},
|
|
1078
|
+
},
|
|
1079
|
+
},
|
|
1080
|
+
{
|
|
1081
|
+
name: 'browser_interact',
|
|
1082
|
+
description: 'Perform up to 10 trusted Playwright actions against the current application. Prefer refs from browser_snapshot; use coordinates for canvas input. Hold keys within one batch with keyDown, wait, and keyUp; keyDown and keyUp focus an optional ref or locator, and any held keys are released when the batch ends. This tool does not navigate to arbitrary URLs.',
|
|
1083
|
+
inputSchema: {
|
|
1084
|
+
type: 'object',
|
|
1085
|
+
additionalProperties: false,
|
|
1086
|
+
properties: {
|
|
1087
|
+
timeoutMs: {
|
|
1088
|
+
type: 'integer',
|
|
1089
|
+
minimum: 100,
|
|
1090
|
+
maximum: 12000,
|
|
1091
|
+
description: 'Total timeout budget for the complete batch. Defaults to 10000 and is capped at 12000 so workspace restoration completes before the host command deadline.',
|
|
1092
|
+
},
|
|
1093
|
+
steps: {
|
|
1094
|
+
type: 'array',
|
|
1095
|
+
minItems: 1,
|
|
1096
|
+
maxItems: 10,
|
|
1097
|
+
items: {
|
|
1098
|
+
type: 'object',
|
|
1099
|
+
additionalProperties: false,
|
|
1100
|
+
properties: {
|
|
1101
|
+
action: {
|
|
1102
|
+
type: 'string',
|
|
1103
|
+
enum: [
|
|
1104
|
+
'click',
|
|
1105
|
+
'doubleClick',
|
|
1106
|
+
'hover',
|
|
1107
|
+
'pointerMove',
|
|
1108
|
+
'pointerDown',
|
|
1109
|
+
'pointerUp',
|
|
1110
|
+
'wheel',
|
|
1111
|
+
'fill',
|
|
1112
|
+
'type',
|
|
1113
|
+
'clear',
|
|
1114
|
+
'press',
|
|
1115
|
+
'keyDown',
|
|
1116
|
+
'keyUp',
|
|
1117
|
+
'check',
|
|
1118
|
+
'uncheck',
|
|
1119
|
+
'select',
|
|
1120
|
+
'scroll',
|
|
1121
|
+
'drag',
|
|
1122
|
+
'wait',
|
|
1123
|
+
],
|
|
1124
|
+
},
|
|
1125
|
+
ref: { type: 'string' },
|
|
1126
|
+
targetRef: { type: 'string' },
|
|
1127
|
+
locator: {
|
|
1128
|
+
type: 'object',
|
|
1129
|
+
additionalProperties: false,
|
|
1130
|
+
properties: {
|
|
1131
|
+
role: { type: 'string' },
|
|
1132
|
+
name: { type: 'string' },
|
|
1133
|
+
testId: { type: 'string' },
|
|
1134
|
+
text: { type: 'string' },
|
|
1135
|
+
},
|
|
1136
|
+
},
|
|
1137
|
+
targetLocator: {
|
|
1138
|
+
type: 'object',
|
|
1139
|
+
additionalProperties: false,
|
|
1140
|
+
properties: {
|
|
1141
|
+
role: { type: 'string' },
|
|
1142
|
+
name: { type: 'string' },
|
|
1143
|
+
testId: { type: 'string' },
|
|
1144
|
+
text: { type: 'string' },
|
|
1145
|
+
},
|
|
1146
|
+
},
|
|
1147
|
+
point: {
|
|
1148
|
+
type: 'object',
|
|
1149
|
+
additionalProperties: false,
|
|
1150
|
+
properties: {
|
|
1151
|
+
x: { type: 'number' },
|
|
1152
|
+
y: { type: 'number' },
|
|
1153
|
+
canvasRef: { type: 'string' },
|
|
1154
|
+
},
|
|
1155
|
+
required: ['x', 'y'],
|
|
1156
|
+
},
|
|
1157
|
+
targetPoint: {
|
|
1158
|
+
type: 'object',
|
|
1159
|
+
additionalProperties: false,
|
|
1160
|
+
properties: {
|
|
1161
|
+
x: { type: 'number' },
|
|
1162
|
+
y: { type: 'number' },
|
|
1163
|
+
canvasRef: { type: 'string' },
|
|
1164
|
+
},
|
|
1165
|
+
required: ['x', 'y'],
|
|
1166
|
+
},
|
|
1167
|
+
button: {
|
|
1168
|
+
type: 'string',
|
|
1169
|
+
enum: ['left', 'middle', 'right'],
|
|
1170
|
+
},
|
|
1171
|
+
key: {
|
|
1172
|
+
type: 'string',
|
|
1173
|
+
maxLength: 100,
|
|
1174
|
+
description: 'Keyboard key for press, keyDown, or keyUp. Keys held by keyDown are scoped to this batch and released automatically at the end.',
|
|
1175
|
+
},
|
|
1176
|
+
durationMs: {
|
|
1177
|
+
type: 'integer',
|
|
1178
|
+
minimum: 0,
|
|
1179
|
+
maximum: 12000,
|
|
1180
|
+
description: 'For wait, pause for this duration within the batch timeout.',
|
|
1181
|
+
},
|
|
1182
|
+
value: { type: 'string' },
|
|
1183
|
+
values: { type: 'array', items: { type: 'string' } },
|
|
1184
|
+
text: { type: 'string' },
|
|
1185
|
+
path: {
|
|
1186
|
+
type: 'string',
|
|
1187
|
+
description: 'For wait, the expected application pathname, search, and hash.',
|
|
1188
|
+
},
|
|
1189
|
+
loadState: {
|
|
1190
|
+
type: 'string',
|
|
1191
|
+
enum: ['domcontentloaded', 'load', 'networkidle'],
|
|
1192
|
+
description: 'For wait, the application load state to await.',
|
|
1193
|
+
},
|
|
1194
|
+
state: {
|
|
1195
|
+
type: 'string',
|
|
1196
|
+
enum: [
|
|
1197
|
+
'attached',
|
|
1198
|
+
'checked',
|
|
1199
|
+
'detached',
|
|
1200
|
+
'disabled',
|
|
1201
|
+
'editable',
|
|
1202
|
+
'enabled',
|
|
1203
|
+
'focused',
|
|
1204
|
+
'hidden',
|
|
1205
|
+
'unchecked',
|
|
1206
|
+
'visible',
|
|
1207
|
+
],
|
|
1208
|
+
},
|
|
1209
|
+
deltaX: { type: 'number' },
|
|
1210
|
+
deltaY: { type: 'number' },
|
|
1211
|
+
timeoutMs: {
|
|
1212
|
+
type: 'integer',
|
|
1213
|
+
minimum: 100,
|
|
1214
|
+
maximum: 12000,
|
|
1215
|
+
},
|
|
1216
|
+
},
|
|
1217
|
+
required: ['action'],
|
|
1218
|
+
},
|
|
1219
|
+
},
|
|
1220
|
+
},
|
|
1221
|
+
required: ['steps'],
|
|
1222
|
+
},
|
|
1223
|
+
},
|
|
1224
|
+
{
|
|
1225
|
+
name: 'browser_profile',
|
|
1226
|
+
description: 'Start, stop, or inspect a bounded uncalibrated desktop-browser performance profile for the current application.',
|
|
1227
|
+
inputSchema: {
|
|
1228
|
+
type: 'object',
|
|
1229
|
+
additionalProperties: false,
|
|
1230
|
+
properties: {
|
|
1231
|
+
action: {
|
|
1232
|
+
type: 'string',
|
|
1233
|
+
enum: ['start', 'status', 'stop'],
|
|
1234
|
+
},
|
|
1235
|
+
mode: {
|
|
1236
|
+
type: 'string',
|
|
1237
|
+
enum: ['interaction', 'rendering', 'trace'],
|
|
1238
|
+
description: 'Profile mode used when action is start.',
|
|
1239
|
+
},
|
|
1240
|
+
maxDurationMs: {
|
|
1241
|
+
type: 'integer',
|
|
1242
|
+
minimum: 1000,
|
|
1243
|
+
maximum: 60000,
|
|
1244
|
+
description: 'Safety auto-stop duration. Defaults to 30000.',
|
|
1245
|
+
},
|
|
1246
|
+
profileId: {
|
|
1247
|
+
type: 'string',
|
|
1248
|
+
description: 'Optional profile ID precondition for stop.',
|
|
1249
|
+
},
|
|
1250
|
+
},
|
|
1251
|
+
required: ['action'],
|
|
1252
|
+
},
|
|
1253
|
+
},
|
|
1012
1254
|
// =============================================================================
|
|
1013
1255
|
// Device State
|
|
1014
1256
|
// =============================================================================
|
|
@@ -1127,19 +1369,21 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1127
1369
|
properties: {
|
|
1128
1370
|
count: {
|
|
1129
1371
|
type: 'number',
|
|
1130
|
-
|
|
1372
|
+
minimum: 1,
|
|
1373
|
+
maximum: 200,
|
|
1374
|
+
description: 'Maximum number of logs to return (most recent N). Defaults to 100 and is capped at 200.',
|
|
1131
1375
|
},
|
|
1132
1376
|
level: {
|
|
1133
1377
|
oneOf: [
|
|
1134
1378
|
{
|
|
1135
1379
|
type: 'string',
|
|
1136
|
-
enum: ['log', 'info', 'warn', 'error', 'debug'],
|
|
1380
|
+
enum: ['log', 'info', 'warn', 'error', 'debug', 'trace'],
|
|
1137
1381
|
},
|
|
1138
1382
|
{
|
|
1139
1383
|
type: 'array',
|
|
1140
1384
|
items: {
|
|
1141
1385
|
type: 'string',
|
|
1142
|
-
enum: ['log', 'info', 'warn', 'error', 'debug'],
|
|
1386
|
+
enum: ['log', 'info', 'warn', 'error', 'debug', 'trace'],
|
|
1143
1387
|
},
|
|
1144
1388
|
},
|
|
1145
1389
|
],
|
|
@@ -1236,7 +1480,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1236
1480
|
},
|
|
1237
1481
|
{
|
|
1238
1482
|
name: 'scene_render_file',
|
|
1239
|
-
description: 'Validate, compose, and render an IWSDK scene JSON file without opening it in the live editor. Invalid files return structured diagnostics and no PNG; valid files return
|
|
1483
|
+
description: 'Validate, compose, and render an IWSDK scene JSON file without opening it in the live editor. Invalid files return structured diagnostics and no PNG; valid files persist the PNG locally and return screenshotPath with hashes and render metadata.',
|
|
1240
1484
|
inputSchema: {
|
|
1241
1485
|
type: 'object',
|
|
1242
1486
|
additionalProperties: false,
|
|
@@ -1252,8 +1496,16 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1252
1496
|
type: 'string',
|
|
1253
1497
|
description: 'Stable id of an exact camera declared in document.authoring.views. Use this, not view, for names such as "hero".',
|
|
1254
1498
|
},
|
|
1255
|
-
width: {
|
|
1256
|
-
|
|
1499
|
+
width: {
|
|
1500
|
+
type: 'number',
|
|
1501
|
+
minimum: 1,
|
|
1502
|
+
description: 'Render width in pixels. For agent-loop review use 512 or smaller; use 384 or smaller when verifying a correction.',
|
|
1503
|
+
},
|
|
1504
|
+
height: {
|
|
1505
|
+
type: 'number',
|
|
1506
|
+
minimum: 1,
|
|
1507
|
+
description: 'Render height in pixels. For agent-loop review use 512 or smaller; use 384 or smaller when verifying a correction.',
|
|
1508
|
+
},
|
|
1257
1509
|
},
|
|
1258
1510
|
required: ['path'],
|
|
1259
1511
|
},
|
|
@@ -1735,7 +1987,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1735
1987
|
},
|
|
1736
1988
|
{
|
|
1737
1989
|
name: 'scene_screenshot',
|
|
1738
|
-
description: 'Capture a native scene editor screenshot. Supports exact saved authoring viewId cameras, current/top/front/back/left/right/quarter/orbit views, and explicit perspective/orthographic poses.',
|
|
1990
|
+
description: 'Capture a native scene editor screenshot, persist the PNG locally, and return screenshotPath. Supports exact saved authoring viewId cameras, current/top/front/back/left/right/quarter/orbit views, and explicit perspective/orthographic poses.',
|
|
1739
1991
|
inputSchema: {
|
|
1740
1992
|
type: 'object',
|
|
1741
1993
|
properties: {
|
|
@@ -1760,6 +2012,57 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1760
2012
|
},
|
|
1761
2013
|
},
|
|
1762
2014
|
},
|
|
2015
|
+
{
|
|
2016
|
+
name: 'asset_render_preview',
|
|
2017
|
+
description: 'Render an isolated manifest model as one labelled multi-view contact sheet without changing the open scene. Supports authored materials or a neutral clay pass, optional framing around one named subtree, persists the PNG locally, and returns screenshotPath with deterministic geometry diagnostics. UIKitML assets must use ui_render_preview.',
|
|
2018
|
+
inputSchema: {
|
|
2019
|
+
type: 'object',
|
|
2020
|
+
additionalProperties: false,
|
|
2021
|
+
properties: {
|
|
2022
|
+
assetId: {
|
|
2023
|
+
type: 'string',
|
|
2024
|
+
description: 'Renderable glTF or Object3D manifest asset id. UIKitML assets are rejected with guidance to use ui_render_preview.',
|
|
2025
|
+
},
|
|
2026
|
+
views: {
|
|
2027
|
+
type: 'array',
|
|
2028
|
+
minItems: 1,
|
|
2029
|
+
maxItems: 6,
|
|
2030
|
+
items: {
|
|
2031
|
+
type: 'string',
|
|
2032
|
+
enum: ['front', 'back', 'left', 'right', 'top', 'quarter'],
|
|
2033
|
+
},
|
|
2034
|
+
description: 'Ordered contact-sheet views. Defaults to front, back, right, top, and quarter.',
|
|
2035
|
+
},
|
|
2036
|
+
mode: {
|
|
2037
|
+
type: 'string',
|
|
2038
|
+
enum: ['material', 'clay'],
|
|
2039
|
+
description: 'Use authored materials or a fixed neutral clay material. Defaults to material.',
|
|
2040
|
+
},
|
|
2041
|
+
focus: {
|
|
2042
|
+
type: 'string',
|
|
2043
|
+
maxLength: 512,
|
|
2044
|
+
description: 'Optional exact object name or slash-separated named hierarchy path to frame. The full asset remains visible for attachment context.',
|
|
2045
|
+
},
|
|
2046
|
+
width: {
|
|
2047
|
+
type: 'number',
|
|
2048
|
+
minimum: 320,
|
|
2049
|
+
maximum: 2048,
|
|
2050
|
+
description: 'Composite contact-sheet width in pixels. Defaults to 640. Keep agent-loop previews at 640 or smaller; use focus rather than more pixels for detail review.',
|
|
2051
|
+
},
|
|
2052
|
+
height: {
|
|
2053
|
+
type: 'number',
|
|
2054
|
+
minimum: 240,
|
|
2055
|
+
maximum: 2048,
|
|
2056
|
+
description: 'Composite contact-sheet height in pixels. Defaults to 480. Keep agent-loop previews at 480 or smaller; use focus rather than more pixels for detail review.',
|
|
2057
|
+
},
|
|
2058
|
+
background: {
|
|
2059
|
+
type: 'string',
|
|
2060
|
+
description: 'Three.js-compatible background color. Defaults to #202226.',
|
|
2061
|
+
},
|
|
2062
|
+
},
|
|
2063
|
+
required: ['assetId'],
|
|
2064
|
+
},
|
|
2065
|
+
},
|
|
1763
2066
|
{
|
|
1764
2067
|
name: 'ui_list_assets',
|
|
1765
2068
|
description: 'List UIKitML assets available in the project asset manifest. Use a returned asset id with ui_render_preview or a PanelUI component config.',
|
|
@@ -1776,7 +2079,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1776
2079
|
},
|
|
1777
2080
|
{
|
|
1778
2081
|
name: 'ui_render_preview',
|
|
1779
|
-
description: 'Render one UIKitML asset from the project asset manifest in isolation against a plain background. Use this to inspect panel layout without the surrounding scene.',
|
|
2082
|
+
description: 'Render one UIKitML asset from the project asset manifest in isolation against a plain background, persist the PNG locally, and return screenshotPath. Use this to inspect panel layout without the surrounding scene.',
|
|
1780
2083
|
inputSchema: {
|
|
1781
2084
|
type: 'object',
|
|
1782
2085
|
additionalProperties: false,
|
|
@@ -1805,6 +2108,45 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
1805
2108
|
required: ['assetId'],
|
|
1806
2109
|
},
|
|
1807
2110
|
},
|
|
2111
|
+
{
|
|
2112
|
+
name: 'ui_inspect',
|
|
2113
|
+
description: 'Inspect live UIKitML elements owned by one ECS panel entity. Omit selector to list stable-ID elements, or use #id, .class, and descendant selectors for focused inspection. Returns bounded current text, state, layout, and selected computed properties without interacting with the UI; documents over 10,000 objects fail explicitly. Requires FRAMEWORK_MCP_RUNTIME.',
|
|
2114
|
+
inputSchema: {
|
|
2115
|
+
type: 'object',
|
|
2116
|
+
additionalProperties: false,
|
|
2117
|
+
properties: {
|
|
2118
|
+
entityIndex: {
|
|
2119
|
+
type: 'integer',
|
|
2120
|
+
minimum: 0,
|
|
2121
|
+
description: 'Panel entity index from ecs_find_entities or scene_get_runtime_hierarchy.',
|
|
2122
|
+
},
|
|
2123
|
+
selector: {
|
|
2124
|
+
type: 'string',
|
|
2125
|
+
maxLength: 512,
|
|
2126
|
+
description: 'Optional #id, .class, or descendant selector with at most 16 parts. Omit to list every stable-ID element in document order.',
|
|
2127
|
+
},
|
|
2128
|
+
properties: {
|
|
2129
|
+
type: 'array',
|
|
2130
|
+
minItems: 1,
|
|
2131
|
+
maxItems: 20,
|
|
2132
|
+
items: {
|
|
2133
|
+
type: 'string',
|
|
2134
|
+
maxLength: 64,
|
|
2135
|
+
pattern: '^[A-Za-z][A-Za-z0-9]*$',
|
|
2136
|
+
description: 'Camel-case UIKit property name.',
|
|
2137
|
+
},
|
|
2138
|
+
description: 'Optional computed UIKit property names to return. Defaults to common text, value, state, display, and pointer-event properties.',
|
|
2139
|
+
},
|
|
2140
|
+
limit: {
|
|
2141
|
+
type: 'integer',
|
|
2142
|
+
minimum: 1,
|
|
2143
|
+
maximum: 50,
|
|
2144
|
+
description: 'Maximum returned elements. Defaults to 50.',
|
|
2145
|
+
},
|
|
2146
|
+
},
|
|
2147
|
+
required: ['entityIndex'],
|
|
2148
|
+
},
|
|
2149
|
+
},
|
|
1808
2150
|
{
|
|
1809
2151
|
name: 'scene_compare_screenshots',
|
|
1810
2152
|
description: 'Capture two native scene editor screenshots and report byte identity. This is not a perceptual image comparison.',
|
|
@@ -2473,7 +2815,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
2473
2815
|
},
|
|
2474
2816
|
{
|
|
2475
2817
|
name: 'ecs_snapshot',
|
|
2476
|
-
description: 'Capture a snapshot of all ECS entity/component state.
|
|
2818
|
+
description: 'Capture a snapshot of all ECS entity/component state. Retains 2 snapshots by default; set capacity (2-20) to keep a larger rolling window. Use with ecs_diff to compare. Requires FRAMEWORK_MCP_RUNTIME.',
|
|
2477
2819
|
inputSchema: {
|
|
2478
2820
|
type: 'object',
|
|
2479
2821
|
properties: {
|
|
@@ -2481,6 +2823,10 @@ const ALL_RUNTIME_MCP_TOOLS = [
|
|
|
2481
2823
|
type: 'string',
|
|
2482
2824
|
description: 'Label for this snapshot (default: auto-generated). Use to reference in ecs_diff.',
|
|
2483
2825
|
},
|
|
2826
|
+
capacity: {
|
|
2827
|
+
type: 'number',
|
|
2828
|
+
description: 'Rolling snapshot capacity for this runtime (integer 2-20). Omit to keep the current capacity; defaults to 2.',
|
|
2829
|
+
},
|
|
2484
2830
|
},
|
|
2485
2831
|
},
|
|
2486
2832
|
},
|
|
@@ -2543,20 +2889,79 @@ const EXPECTED_TAB_SCHEMA = {
|
|
|
2543
2889
|
},
|
|
2544
2890
|
required: ['id', 'generation'],
|
|
2545
2891
|
};
|
|
2892
|
+
const RUNTIME_TARGET_SCHEMA = {
|
|
2893
|
+
type: 'object',
|
|
2894
|
+
additionalProperties: false,
|
|
2895
|
+
description: 'Execution destination. Omit for the managed browser. Physical devices require headsetId, pageId and tabGeneration from runtime_list_targets.',
|
|
2896
|
+
properties: {
|
|
2897
|
+
deviceClass: { type: 'string', enum: ['managed', 'physical'] },
|
|
2898
|
+
headsetId: { type: 'string' },
|
|
2899
|
+
pageId: { type: 'string' },
|
|
2900
|
+
tabGeneration: { type: 'integer', minimum: 1 },
|
|
2901
|
+
browserEpoch: { type: 'integer', minimum: 1 },
|
|
2902
|
+
sessionId: { type: 'string' },
|
|
2903
|
+
},
|
|
2904
|
+
required: ['deviceClass'],
|
|
2905
|
+
};
|
|
2906
|
+
const CONTROL_TOOLS = [
|
|
2907
|
+
{
|
|
2908
|
+
name: 'runtime_pair_headset',
|
|
2909
|
+
description: 'Associate an exact headset identifier (adb serial) with this dev session. Open the returned bootstrap URL on that device, then discover its page using runtime_list_targets.',
|
|
2910
|
+
inputSchema: {
|
|
2911
|
+
type: 'object',
|
|
2912
|
+
properties: { headsetId: { type: 'string' } },
|
|
2913
|
+
required: ['headsetId'],
|
|
2914
|
+
},
|
|
2915
|
+
},
|
|
2916
|
+
{
|
|
2917
|
+
name: 'runtime_get_status',
|
|
2918
|
+
description: 'Read live runtime ownership and managed browser lifecycle. Does not launch or recover a browser.',
|
|
2919
|
+
inputSchema: { type: 'object', properties: {} },
|
|
2920
|
+
},
|
|
2921
|
+
{
|
|
2922
|
+
name: 'runtime_list_targets',
|
|
2923
|
+
description: 'Discover connected targets, exact identities, readiness and supported methods. Physical targets must be explicitly selected.',
|
|
2924
|
+
inputSchema: { type: 'object', properties: {} },
|
|
2925
|
+
},
|
|
2926
|
+
{
|
|
2927
|
+
name: 'runtime_wait',
|
|
2928
|
+
description: 'Wait for a lifecycle revision change, without causing recovery. Returns a current snapshot on timeout.',
|
|
2929
|
+
inputSchema: {
|
|
2930
|
+
type: 'object',
|
|
2931
|
+
properties: {
|
|
2932
|
+
afterRevision: { type: 'integer', minimum: 0 },
|
|
2933
|
+
timeoutMs: { type: 'integer', minimum: 0, maximum: 25000 },
|
|
2934
|
+
},
|
|
2935
|
+
},
|
|
2936
|
+
},
|
|
2937
|
+
{
|
|
2938
|
+
name: 'runtime_recover',
|
|
2939
|
+
description: 'Explicitly retry launching the managed browser after failures. Does not replay previous commands or reset live page state.',
|
|
2940
|
+
inputSchema: { type: 'object', properties: {} },
|
|
2941
|
+
},
|
|
2942
|
+
];
|
|
2546
2943
|
function withExpectedTabPrecondition(schema) {
|
|
2547
2944
|
return {
|
|
2548
2945
|
...schema,
|
|
2549
2946
|
properties: {
|
|
2550
2947
|
...(schema.properties ?? {}),
|
|
2551
2948
|
expectedTab: EXPECTED_TAB_SCHEMA,
|
|
2949
|
+
runtimeTarget: RUNTIME_TARGET_SCHEMA,
|
|
2552
2950
|
},
|
|
2553
2951
|
};
|
|
2554
2952
|
}
|
|
2555
|
-
const RUNTIME_MCP_TOOLS =
|
|
2953
|
+
const RUNTIME_MCP_TOOLS = [
|
|
2954
|
+
...ALL_RUNTIME_MCP_TOOLS,
|
|
2955
|
+
...CONTROL_TOOLS,
|
|
2956
|
+
]
|
|
2957
|
+
.filter((tool) => (!tool.name.startsWith('scene_') ||
|
|
2556
2958
|
PUBLIC_SCENE_MCP_TOOL_NAME_SET.has(tool.name)) &&
|
|
2557
|
-
!REMOVED_WORKSPACE_MCP_TOOL_NAME_SET.has(tool.name))
|
|
2959
|
+
!REMOVED_WORKSPACE_MCP_TOOL_NAME_SET.has(tool.name))
|
|
2960
|
+
.map((tool) => ({
|
|
2558
2961
|
...tool,
|
|
2559
|
-
inputSchema:
|
|
2962
|
+
inputSchema: CONTROL_TOOLS.some((control) => control.name === tool.name)
|
|
2963
|
+
? tool.inputSchema
|
|
2964
|
+
: withExpectedTabPrecondition(tool.inputSchema),
|
|
2560
2965
|
}));
|
|
2561
2966
|
const RUNTIME_TOOL_TO_METHOD = {
|
|
2562
2967
|
xr_get_session_status: 'get_session_status',
|
|
@@ -2576,6 +2981,9 @@ const RUNTIME_TOOL_TO_METHOD = {
|
|
|
2576
2981
|
xr_get_device_state: 'get_device_state',
|
|
2577
2982
|
xr_set_device_state: 'set_device_state',
|
|
2578
2983
|
browser_screenshot: 'screenshot',
|
|
2984
|
+
browser_snapshot: 'browser_snapshot',
|
|
2985
|
+
browser_interact: 'browser_interact',
|
|
2986
|
+
browser_profile: 'browser_profile',
|
|
2579
2987
|
browser_get_console_logs: 'get_console_logs',
|
|
2580
2988
|
browser_reload_page: 'reload_page',
|
|
2581
2989
|
scene_get_render_stats: 'get_render_stats',
|
|
@@ -2598,6 +3006,9 @@ const ALL_RUNTIME_CLI_PATHS = {
|
|
|
2598
3006
|
xr_get_gamepad_state: ['xr', 'get-gamepad-state'],
|
|
2599
3007
|
xr_set_gamepad_state: ['xr', 'set-gamepad-state'],
|
|
2600
3008
|
browser_screenshot: ['browser', 'screenshot'],
|
|
3009
|
+
browser_snapshot: ['browser', 'snapshot'],
|
|
3010
|
+
browser_interact: ['browser', 'interact'],
|
|
3011
|
+
browser_profile: ['browser', 'profile'],
|
|
2601
3012
|
xr_get_device_state: ['xr', 'get-device-state'],
|
|
2602
3013
|
xr_set_device_state: ['xr', 'set-device-state'],
|
|
2603
3014
|
browser_get_console_logs: ['browser', 'logs'],
|
|
@@ -2637,8 +3048,10 @@ const ALL_RUNTIME_CLI_PATHS = {
|
|
|
2637
3048
|
scene_get_logs: ['scene', 'logs'],
|
|
2638
3049
|
scene_set_camera: ['scene', 'set-camera'],
|
|
2639
3050
|
scene_screenshot: ['scene', 'screenshot'],
|
|
3051
|
+
asset_render_preview: ['asset', 'render-preview'],
|
|
2640
3052
|
ui_list_assets: ['ui', 'assets'],
|
|
2641
3053
|
ui_render_preview: ['ui', 'render-preview'],
|
|
3054
|
+
ui_inspect: ['ui', 'inspect'],
|
|
2642
3055
|
scene_compare_screenshots: ['scene', 'compare-screenshots'],
|
|
2643
3056
|
scene_begin_review: ['scene', 'begin-review'],
|
|
2644
3057
|
scene_set_review_lens: ['scene', 'set-review-lens'],
|
|
@@ -2678,6 +3091,7 @@ const SCENE_EDITOR_MCP_TOOL_NAMES = [
|
|
|
2678
3091
|
'scene_screenshot',
|
|
2679
3092
|
'scene_set_preview_visibility',
|
|
2680
3093
|
'scene_measure_image_regions',
|
|
3094
|
+
'asset_render_preview',
|
|
2681
3095
|
'ui_list_assets',
|
|
2682
3096
|
'ui_render_preview',
|
|
2683
3097
|
];
|
|
@@ -2696,9 +3110,27 @@ const EDITOR_TARGET_MCP_TOOL_NAME_SET = new Set([
|
|
|
2696
3110
|
...REVIEW_EVIDENCE_MCP_TOOL_NAMES,
|
|
2697
3111
|
...WORKSPACE_MCP_TOOL_NAMES,
|
|
2698
3112
|
]);
|
|
2699
|
-
const
|
|
3113
|
+
const HOST_BROWSER_MCP_TOOL_NAME_SET = new Set([
|
|
3114
|
+
'browser_screenshot',
|
|
3115
|
+
'browser_snapshot',
|
|
3116
|
+
'browser_interact',
|
|
3117
|
+
'browser_profile',
|
|
3118
|
+
'browser_get_console_logs',
|
|
3119
|
+
'browser_reload_page',
|
|
3120
|
+
]);
|
|
3121
|
+
const APP_TARGET_MCP_TOOL_NAME_SET = new Set([
|
|
3122
|
+
...HOST_BROWSER_MCP_TOOL_NAME_SET,
|
|
3123
|
+
'ui_inspect',
|
|
3124
|
+
]);
|
|
2700
3125
|
const RUNTIME_OPERATIONS = RUNTIME_MCP_TOOLS.map((tool) => {
|
|
2701
|
-
const cliPath = RUNTIME_CLI_PATHS[tool.name]
|
|
3126
|
+
const cliPath = RUNTIME_CLI_PATHS[tool.name] ??
|
|
3127
|
+
{
|
|
3128
|
+
runtime_get_status: ['runtime', 'status'],
|
|
3129
|
+
runtime_list_targets: ['runtime', 'targets'],
|
|
3130
|
+
runtime_wait: ['runtime', 'wait'],
|
|
3131
|
+
runtime_recover: ['runtime', 'recover'],
|
|
3132
|
+
runtime_pair_headset: ['runtime', 'pair-headset'],
|
|
3133
|
+
}[tool.name];
|
|
2702
3134
|
const target = EDITOR_TARGET_MCP_TOOL_NAME_SET.has(tool.name)
|
|
2703
3135
|
? { role: 'editor' }
|
|
2704
3136
|
: APP_TARGET_MCP_TOOL_NAME_SET.has(tool.name)
|
|
@@ -2712,6 +3144,14 @@ const RUNTIME_OPERATIONS = RUNTIME_MCP_TOOLS.map((tool) => {
|
|
|
2712
3144
|
mcpName: tool.name,
|
|
2713
3145
|
wsMethod: RUNTIME_TOOL_TO_METHOD[tool.name] ?? tool.name,
|
|
2714
3146
|
...(target ? { target } : {}),
|
|
3147
|
+
execution: tool.name.startsWith('runtime_')
|
|
3148
|
+
? 'server'
|
|
3149
|
+
: HOST_BROWSER_MCP_TOOL_NAME_SET.has(tool.name)
|
|
3150
|
+
? 'host'
|
|
3151
|
+
: 'runtime',
|
|
3152
|
+
physical: !EDITOR_TARGET_MCP_TOOL_NAME_SET.has(tool.name) &&
|
|
3153
|
+
(!HOST_BROWSER_MCP_TOOL_NAME_SET.has(tool.name) ||
|
|
3154
|
+
tool.name === 'browser_reload_page'),
|
|
2715
3155
|
description: tool.description,
|
|
2716
3156
|
inputSchema: tool.inputSchema,
|
|
2717
3157
|
};
|
|
@@ -2739,24 +3179,36 @@ function resolveRuntimeOperationRequest(operation, params) {
|
|
|
2739
3179
|
expectedTab.generation < 1)) {
|
|
2740
3180
|
throw new Error(`${operation.mcpName}.expectedTab requires the { id, generation } object returned as result._tab`);
|
|
2741
3181
|
}
|
|
2742
|
-
if (operation.mcpName === 'browser_screenshot' &&
|
|
2743
|
-
paramsRecord != null &&
|
|
2744
|
-
Object.keys(paramsRecord).some((key) => key !== 'expectedTab')) {
|
|
2745
|
-
throw new Error('browser_screenshot does not accept parameters; it always captures the application runtime');
|
|
2746
|
-
}
|
|
2747
3182
|
assertSchemaValue(params, operation.inputSchema, operation.mcpName);
|
|
2748
3183
|
const commandParams = paramsRecord == null
|
|
2749
3184
|
? params
|
|
2750
|
-
: Object.fromEntries(Object.entries(paramsRecord).filter(([key]) => key !== 'expectedTab'));
|
|
3185
|
+
: Object.fromEntries(Object.entries(paramsRecord).filter(([key]) => key !== 'expectedTab' && key !== 'runtimeTarget'));
|
|
3186
|
+
const selection = paramsRecord?.runtimeTarget;
|
|
3187
|
+
if (selection?.deviceClass === 'physical' &&
|
|
3188
|
+
(!selection.headsetId ||
|
|
3189
|
+
!selection.pageId ||
|
|
3190
|
+
!Number.isInteger(selection.tabGeneration))) {
|
|
3191
|
+
throw new Error('Physical runtimeTarget requires headsetId, pageId and tabGeneration from runtime_list_targets.');
|
|
3192
|
+
}
|
|
3193
|
+
if (selection &&
|
|
3194
|
+
isRecord$6(expectedTab) &&
|
|
3195
|
+
((selection.pageId != null && selection.pageId !== expectedTab.id) ||
|
|
3196
|
+
(selection.tabGeneration != null &&
|
|
3197
|
+
selection.tabGeneration !== expectedTab.generation))) {
|
|
3198
|
+
throw new Error('runtimeTarget and expectedTab must identify the same page generation.');
|
|
3199
|
+
}
|
|
2751
3200
|
const target = isRecord$6(expectedTab) &&
|
|
2752
3201
|
typeof expectedTab.id === 'string' &&
|
|
2753
3202
|
typeof expectedTab.generation === 'number'
|
|
2754
3203
|
? {
|
|
2755
3204
|
...(operation.target ?? {}),
|
|
3205
|
+
...selection,
|
|
2756
3206
|
pageId: expectedTab.id,
|
|
2757
3207
|
tabGeneration: expectedTab.generation,
|
|
2758
3208
|
}
|
|
2759
|
-
:
|
|
3209
|
+
: selection
|
|
3210
|
+
? { ...operation.target, ...selection }
|
|
3211
|
+
: operation.target;
|
|
2760
3212
|
return { params: commandParams, target };
|
|
2761
3213
|
}
|
|
2762
3214
|
function isRecord$6(value) {
|
|
@@ -2769,70 +3221,470 @@ function isRecord$6(value) {
|
|
|
2769
3221
|
* This source code is licensed under the MIT license found in the
|
|
2770
3222
|
* LICENSE file in the root directory of this source tree.
|
|
2771
3223
|
*/
|
|
2772
|
-
const
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
const
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
3224
|
+
const LOCK_TIMEOUT_MS = 5_000;
|
|
3225
|
+
const mutationQueues = new Map();
|
|
3226
|
+
async function renameRuntimeFile(tempPath, filePath) {
|
|
3227
|
+
for (let attempt = 0;; attempt += 1) {
|
|
3228
|
+
try {
|
|
3229
|
+
await rename(tempPath, filePath);
|
|
3230
|
+
return;
|
|
3231
|
+
}
|
|
3232
|
+
catch (error) {
|
|
3233
|
+
const code = error.code;
|
|
3234
|
+
if (process.platform !== 'win32' ||
|
|
3235
|
+
attempt >= 4 ||
|
|
3236
|
+
!['EACCES', 'EBUSY', 'EPERM'].includes(code ?? '')) {
|
|
3237
|
+
throw error;
|
|
3238
|
+
}
|
|
3239
|
+
await new Promise((resolve) => setTimeout(resolve, 25 * 2 ** attempt));
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
function normalizeWorkspaceRoot(workspaceRoot) {
|
|
3244
|
+
const resolved = path.resolve(workspaceRoot);
|
|
2787
3245
|
try {
|
|
2788
|
-
|
|
2789
|
-
|
|
3246
|
+
return existsSync(resolved) ? realpathSync.native(resolved) : resolved;
|
|
3247
|
+
}
|
|
3248
|
+
catch {
|
|
3249
|
+
return resolved;
|
|
3250
|
+
}
|
|
3251
|
+
}
|
|
3252
|
+
function getRuntimeFilePath(workspaceRoot, relativePath) {
|
|
3253
|
+
return path.join(normalizeWorkspaceRoot(workspaceRoot), relativePath);
|
|
3254
|
+
}
|
|
3255
|
+
async function readRuntimeJson(filePath) {
|
|
3256
|
+
try {
|
|
3257
|
+
return JSON.parse(await readFile(filePath, 'utf8'));
|
|
2790
3258
|
}
|
|
2791
3259
|
catch {
|
|
2792
3260
|
return null;
|
|
2793
3261
|
}
|
|
2794
3262
|
}
|
|
2795
|
-
function
|
|
2796
|
-
|
|
3263
|
+
async function writeRuntimeJson(filePath, value) {
|
|
3264
|
+
await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
3265
|
+
const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
3266
|
+
try {
|
|
3267
|
+
await writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
|
|
3268
|
+
encoding: 'utf8',
|
|
3269
|
+
flag: 'wx',
|
|
3270
|
+
mode: 0o600,
|
|
3271
|
+
});
|
|
3272
|
+
await renameRuntimeFile(tempPath, filePath);
|
|
3273
|
+
}
|
|
3274
|
+
finally {
|
|
3275
|
+
await rm(tempPath, { force: true }).catch(() => { });
|
|
3276
|
+
}
|
|
3277
|
+
}
|
|
3278
|
+
async function removeRuntimeFile(filePath) {
|
|
3279
|
+
await rm(filePath, { force: true }).catch(() => { });
|
|
3280
|
+
}
|
|
3281
|
+
function isRuntimeProcessAlive(pid) {
|
|
3282
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
2797
3283
|
return false;
|
|
2798
3284
|
}
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
3285
|
+
try {
|
|
3286
|
+
process.kill(pid, 0);
|
|
3287
|
+
return true;
|
|
3288
|
+
}
|
|
3289
|
+
catch (error) {
|
|
3290
|
+
return error.code === 'EPERM';
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
function getRuntimeFileLockPath(filePath) {
|
|
3294
|
+
return `${filePath}.lock`;
|
|
2805
3295
|
}
|
|
2806
|
-
async function
|
|
3296
|
+
async function removeOrphanedTempFiles(filePath) {
|
|
3297
|
+
const directory = path.dirname(filePath);
|
|
3298
|
+
const prefix = `${path.basename(filePath)}.`;
|
|
3299
|
+
let entries;
|
|
2807
3300
|
try {
|
|
2808
|
-
|
|
2809
|
-
return JSON.parse(raw);
|
|
3301
|
+
entries = await readdir(directory);
|
|
2810
3302
|
}
|
|
2811
3303
|
catch {
|
|
3304
|
+
return;
|
|
3305
|
+
}
|
|
3306
|
+
await Promise.all(entries
|
|
3307
|
+
.filter((entry) => entry.startsWith(prefix) && entry.endsWith('.tmp'))
|
|
3308
|
+
.map((entry) => rm(path.join(directory, entry), { force: true }).catch(() => { })));
|
|
3309
|
+
}
|
|
3310
|
+
const processStarts = new Map();
|
|
3311
|
+
/** OS process birth identity distinguishes a live owner from a reused PID. */
|
|
3312
|
+
function getRuntimeProcessStart(pid) {
|
|
3313
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
2812
3314
|
return null;
|
|
2813
3315
|
}
|
|
3316
|
+
const cached = processStarts.get(pid);
|
|
3317
|
+
if (pid === process.pid && cached) {
|
|
3318
|
+
return cached;
|
|
3319
|
+
}
|
|
3320
|
+
let value = null;
|
|
3321
|
+
try {
|
|
3322
|
+
if (process.platform === 'linux') {
|
|
3323
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
3324
|
+
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
|
3325
|
+
value = `${boot}:${stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]}`;
|
|
3326
|
+
}
|
|
3327
|
+
else if (process.platform === 'win32') {
|
|
3328
|
+
value =
|
|
3329
|
+
execFileSync('powershell.exe', [
|
|
3330
|
+
'-NoProfile',
|
|
3331
|
+
'-NonInteractive',
|
|
3332
|
+
'-Command',
|
|
3333
|
+
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`,
|
|
3334
|
+
], {
|
|
3335
|
+
encoding: 'utf8',
|
|
3336
|
+
timeout: 1500,
|
|
3337
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
3338
|
+
}).trim() || null;
|
|
3339
|
+
}
|
|
3340
|
+
else {
|
|
3341
|
+
value =
|
|
3342
|
+
execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
|
|
3343
|
+
encoding: 'utf8',
|
|
3344
|
+
timeout: 1500,
|
|
3345
|
+
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
|
3346
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
3347
|
+
}).trim() || null;
|
|
3348
|
+
}
|
|
3349
|
+
}
|
|
3350
|
+
catch { }
|
|
3351
|
+
// A transient Windows/ps failure must remain retryable. Only a positive
|
|
3352
|
+
// identity is stable enough to cache for the lifetime of this process.
|
|
3353
|
+
if (pid === process.pid && value != null) {
|
|
3354
|
+
processStarts.set(pid, value);
|
|
3355
|
+
}
|
|
3356
|
+
return value;
|
|
2814
3357
|
}
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
3358
|
+
const liveLockOwners = new Map();
|
|
3359
|
+
function ownerIsDead(owner) {
|
|
3360
|
+
if (!isRuntimeProcessAlive(owner.pid)) {
|
|
3361
|
+
return true;
|
|
3362
|
+
}
|
|
3363
|
+
if (owner.processStart) {
|
|
3364
|
+
const key = `${owner.pid}:${owner.processStart}:${owner.lockId ?? 'legacy'}`;
|
|
3365
|
+
if ((liveLockOwners.get(key) ?? 0) > Date.now()) {
|
|
3366
|
+
return false;
|
|
3367
|
+
}
|
|
3368
|
+
const current = getRuntimeProcessStart(owner.pid);
|
|
3369
|
+
if (current != null && current !== owner.processStart) {
|
|
3370
|
+
return true;
|
|
3371
|
+
}
|
|
3372
|
+
// Especially on Windows, avoid a synchronous OS query on every 25ms
|
|
3373
|
+
// contention poll. PID death is still checked immediately above; cached
|
|
3374
|
+
// liveness only delays reclamation and can never steal a live lock.
|
|
3375
|
+
if (liveLockOwners.size >= 128) {
|
|
3376
|
+
liveLockOwners.clear();
|
|
3377
|
+
}
|
|
3378
|
+
liveLockOwners.set(key, Date.now() + 1000);
|
|
3379
|
+
}
|
|
3380
|
+
return false;
|
|
2818
3381
|
}
|
|
2819
|
-
async function
|
|
2820
|
-
|
|
3382
|
+
async function reclaimFileLock(lockPath) {
|
|
3383
|
+
let entries;
|
|
3384
|
+
try {
|
|
3385
|
+
entries = await readdir(lockPath);
|
|
3386
|
+
}
|
|
3387
|
+
catch {
|
|
3388
|
+
return;
|
|
3389
|
+
}
|
|
3390
|
+
if (entries.length === 1 &&
|
|
3391
|
+
(entries[0] === 'owner.json' ||
|
|
3392
|
+
/^owner-[a-f0-9-]+\.json$/u.test(entries[0]))) {
|
|
3393
|
+
const ownerPath = path.join(lockPath, entries[0]);
|
|
3394
|
+
const owner = await readRuntimeJson(ownerPath);
|
|
3395
|
+
if (!owner ||
|
|
3396
|
+
!Number.isInteger(owner.pid) ||
|
|
3397
|
+
owner.pid <= 0 ||
|
|
3398
|
+
!ownerIsDead(owner)) {
|
|
3399
|
+
return;
|
|
3400
|
+
}
|
|
3401
|
+
// A successor has a different filename. A delayed reclaimer cannot remove
|
|
3402
|
+
// its owner file, and rmdir cannot remove a populated successor directory.
|
|
3403
|
+
await unlink(ownerPath).catch(() => { });
|
|
3404
|
+
}
|
|
3405
|
+
else if (entries.length !== 0) {
|
|
3406
|
+
return;
|
|
3407
|
+
}
|
|
3408
|
+
await rmdir(lockPath).catch(() => { });
|
|
2821
3409
|
}
|
|
2822
|
-
function
|
|
2823
|
-
|
|
3410
|
+
function newLockOwner() {
|
|
3411
|
+
return {
|
|
3412
|
+
acquiredAt: Date.now(),
|
|
3413
|
+
pid: process.pid,
|
|
3414
|
+
lockId: randomUUID(),
|
|
3415
|
+
processStart: getRuntimeProcessStart(process.pid),
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
async function acquireRuntimeFileLock(filePath) {
|
|
3419
|
+
const lockPath = getRuntimeFileLockPath(filePath);
|
|
3420
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
3421
|
+
await mkdir(path.dirname(lockPath), { recursive: true });
|
|
3422
|
+
const owner = newLockOwner();
|
|
3423
|
+
const filename = `owner-${owner.lockId}.json`;
|
|
3424
|
+
const prepared = await mkdtemp(`${lockPath}.prepared-`);
|
|
2824
3425
|
try {
|
|
2825
|
-
|
|
3426
|
+
await writeFile(path.join(prepared, filename), JSON.stringify(owner), {
|
|
3427
|
+
mode: 0o600,
|
|
3428
|
+
});
|
|
3429
|
+
while (true) {
|
|
3430
|
+
// Respect a live recovery guard left by an older CLI. New writers do not
|
|
3431
|
+
// need a recovery guard, so its own crash cannot create another lock layer.
|
|
3432
|
+
await reclaimFileLock(`${lockPath}.recovery`);
|
|
3433
|
+
let recoveryExists = false;
|
|
3434
|
+
try {
|
|
3435
|
+
await readdir(`${lockPath}.recovery`);
|
|
3436
|
+
recoveryExists = true;
|
|
3437
|
+
}
|
|
3438
|
+
catch { }
|
|
3439
|
+
try {
|
|
3440
|
+
if (recoveryExists) {
|
|
3441
|
+
throw Object.assign(new Error('Legacy recovery in progress'), {
|
|
3442
|
+
code: 'EEXIST',
|
|
3443
|
+
});
|
|
3444
|
+
}
|
|
3445
|
+
await rename(prepared, lockPath);
|
|
3446
|
+
await removeOrphanedTempFiles(filePath);
|
|
3447
|
+
return async () => {
|
|
3448
|
+
await unlink(path.join(lockPath, filename)).catch(() => { });
|
|
3449
|
+
await rmdir(lockPath).catch(() => { });
|
|
3450
|
+
};
|
|
3451
|
+
}
|
|
3452
|
+
catch (error) {
|
|
3453
|
+
if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code ?? '')) {
|
|
3454
|
+
throw error;
|
|
3455
|
+
}
|
|
3456
|
+
}
|
|
3457
|
+
if (!recoveryExists) {
|
|
3458
|
+
await reclaimFileLock(lockPath);
|
|
3459
|
+
}
|
|
3460
|
+
if (Date.now() >= deadline) {
|
|
3461
|
+
throw new Error(`Timed out acquiring runtime state lock ${lockPath}. Inspect its owner and stop the owning process before removing an unreadable legacy lock or recovery guard.`);
|
|
3462
|
+
}
|
|
3463
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
finally {
|
|
3467
|
+
await rm(prepared, { recursive: true, force: true });
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
async function withRuntimeFileLock(filePath, operation) {
|
|
3471
|
+
const previous = mutationQueues.get(filePath) ?? Promise.resolve();
|
|
3472
|
+
const next = previous
|
|
3473
|
+
.catch(() => { })
|
|
3474
|
+
.then(async () => {
|
|
3475
|
+
const release = await acquireRuntimeFileLock(filePath);
|
|
3476
|
+
try {
|
|
3477
|
+
return await operation();
|
|
3478
|
+
}
|
|
3479
|
+
finally {
|
|
3480
|
+
await release().catch(() => { });
|
|
3481
|
+
}
|
|
3482
|
+
});
|
|
3483
|
+
mutationQueues.set(filePath, next);
|
|
3484
|
+
try {
|
|
3485
|
+
return await next;
|
|
3486
|
+
}
|
|
3487
|
+
finally {
|
|
3488
|
+
if (mutationQueues.get(filePath) === next) {
|
|
3489
|
+
mutationQueues.delete(filePath);
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/**
|
|
3495
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
3496
|
+
*
|
|
3497
|
+
* This source code is licensed under the MIT license found in the
|
|
3498
|
+
* LICENSE file in the root directory of this source tree.
|
|
3499
|
+
*/
|
|
3500
|
+
class RuntimeOwnerError extends Error {
|
|
3501
|
+
constructor(message, owner, code = 'runtime_owner_conflict') {
|
|
3502
|
+
super(message);
|
|
3503
|
+
this.owner = owner;
|
|
3504
|
+
this.code = code;
|
|
3505
|
+
this.name = 'RuntimeOwnerError';
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
function runtimeOwnerRecordPath(workspaceRoot) {
|
|
3509
|
+
return path.join(normalizeWorkspaceRoot(workspaceRoot), '.iwsdk/runtime/owner.json');
|
|
3510
|
+
}
|
|
3511
|
+
function sameRuntimeOwner(expected, actual) {
|
|
3512
|
+
return (expected.sessionId === actual.sessionId &&
|
|
3513
|
+
expected.pid === actual.pid &&
|
|
3514
|
+
expected.workspaceRoot === actual.workspaceRoot &&
|
|
3515
|
+
expected.endpoint === actual.endpoint &&
|
|
3516
|
+
expected.processStart != null &&
|
|
3517
|
+
expected.processStart === actual.processStart);
|
|
3518
|
+
}
|
|
3519
|
+
function runtimeOwnerEndpoint(workspaceRoot) {
|
|
3520
|
+
const key = createHash$2('sha256')
|
|
3521
|
+
.update(normalizeWorkspaceRoot(workspaceRoot))
|
|
3522
|
+
.digest('hex')
|
|
3523
|
+
.slice(0, 32);
|
|
3524
|
+
// Short enough for macOS sockaddr_un even with a long project path.
|
|
3525
|
+
return process.platform === 'win32'
|
|
3526
|
+
? `\\\\.\\pipe\\iwsdk-${key}`
|
|
3527
|
+
: path.join('/tmp', `iwsdk-${process.getuid?.() ?? 'user'}`, `${key}.sock`);
|
|
3528
|
+
}
|
|
3529
|
+
/** A timeout is uncertainty; only ENOENT/ECONNREFUSED proves absence. */
|
|
3530
|
+
function inspectRuntimeOwner(endpoint) {
|
|
3531
|
+
return new Promise((resolve) => {
|
|
3532
|
+
const socket = createConnection(endpoint);
|
|
3533
|
+
let data = '';
|
|
3534
|
+
const finish = (result) => {
|
|
3535
|
+
socket.destroy();
|
|
3536
|
+
resolve(result);
|
|
3537
|
+
};
|
|
3538
|
+
socket.setTimeout(750, () => finish({ state: 'unknown', reason: 'Owner probe timed out' }));
|
|
3539
|
+
socket.on('error', (error) => finish(['ENOENT', 'ECONNREFUSED'].includes(error.code ?? '')
|
|
3540
|
+
? { state: 'absent' }
|
|
3541
|
+
: { state: 'unknown', reason: error.message }));
|
|
3542
|
+
socket.on('data', (chunk) => {
|
|
3543
|
+
data += chunk.toString();
|
|
3544
|
+
if (data.length > 4096) {
|
|
3545
|
+
return finish({ state: 'unknown', reason: 'Invalid owner response' });
|
|
3546
|
+
}
|
|
3547
|
+
if (!data.includes('\n')) {
|
|
3548
|
+
return;
|
|
3549
|
+
}
|
|
3550
|
+
try {
|
|
3551
|
+
const owner = JSON.parse(data);
|
|
3552
|
+
if (typeof owner.sessionId !== 'string' ||
|
|
3553
|
+
typeof owner.workspaceRoot !== 'string' ||
|
|
3554
|
+
owner.endpoint !== endpoint ||
|
|
3555
|
+
!Number.isInteger(owner.pid) ||
|
|
3556
|
+
owner.pid <= 0) {
|
|
3557
|
+
throw new Error('Invalid identity');
|
|
3558
|
+
}
|
|
3559
|
+
finish({ state: 'live', owner });
|
|
3560
|
+
}
|
|
3561
|
+
catch {
|
|
3562
|
+
finish({ state: 'unknown', reason: 'Invalid owner identity' });
|
|
3563
|
+
}
|
|
3564
|
+
});
|
|
3565
|
+
socket.on('end', () => finish({ state: 'unknown', reason: 'Owner closed without an identity' }));
|
|
3566
|
+
});
|
|
3567
|
+
}
|
|
3568
|
+
/** Stop only the runtime whose live endpoint was positively verified. */
|
|
3569
|
+
async function stopRuntimeOwner(owner, requestShutdown, timing = {}) {
|
|
3570
|
+
const recordPath = runtimeOwnerRecordPath(owner.workspaceRoot);
|
|
3571
|
+
const sameOwner = (value) => sameRuntimeOwner(owner, value);
|
|
3572
|
+
const initial = await inspectRuntimeOwner(owner.endpoint);
|
|
3573
|
+
const recorded = await readRuntimeJson(recordPath);
|
|
3574
|
+
if (initial.state !== 'live' ||
|
|
3575
|
+
!sameOwner(initial.owner) ||
|
|
3576
|
+
recorded == null ||
|
|
3577
|
+
!sameOwner(recorded)) {
|
|
3578
|
+
throw new RuntimeOwnerError(`Runtime ownership could not be verified at ${owner.endpoint}; refusing PID-only termination.`, owner, 'runtime_owner_unverified');
|
|
3579
|
+
}
|
|
3580
|
+
const stopped = async (duration) => {
|
|
3581
|
+
const deadline = Date.now() + duration;
|
|
3582
|
+
do {
|
|
3583
|
+
const observation = await inspectRuntimeOwner(owner.endpoint);
|
|
3584
|
+
if (observation.state === 'live' && !sameOwner(observation.owner)) {
|
|
3585
|
+
return true;
|
|
3586
|
+
}
|
|
3587
|
+
if (observation.state === 'absent') {
|
|
3588
|
+
if (!isRuntimeProcessAlive(owner.pid)) {
|
|
3589
|
+
return true;
|
|
3590
|
+
}
|
|
3591
|
+
const processStart = getRuntimeProcessStart(owner.pid);
|
|
3592
|
+
if (processStart != null && processStart !== owner.processStart) {
|
|
3593
|
+
return true;
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
3597
|
+
} while (Date.now() < deadline);
|
|
3598
|
+
return false;
|
|
3599
|
+
};
|
|
3600
|
+
const accepted = await requestShutdown();
|
|
3601
|
+
// An acknowledgement can be lost after the runtime accepted shutdown. Give
|
|
3602
|
+
// even an unacknowledged owner time to finish cleanup before using signals.
|
|
3603
|
+
if (await stopped(timing.graceMs ?? (accepted ? 35000 : 5000))) {
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
for (const signal of ['SIGTERM', 'SIGKILL']) {
|
|
3607
|
+
const observation = await inspectRuntimeOwner(owner.endpoint);
|
|
3608
|
+
if (observation.state === 'absent') {
|
|
3609
|
+
return;
|
|
3610
|
+
}
|
|
3611
|
+
if (observation.state === 'live' && !sameOwner(observation.owner)) {
|
|
3612
|
+
return;
|
|
3613
|
+
}
|
|
3614
|
+
const currentRecord = await readRuntimeJson(recordPath);
|
|
3615
|
+
if (currentRecord == null || !sameOwner(currentRecord)) {
|
|
3616
|
+
throw new RuntimeOwnerError(`Runtime ownership record changed at ${recordPath}; refusing PID-only termination.`, owner, 'runtime_owner_unverified');
|
|
3617
|
+
}
|
|
3618
|
+
// The endpoint proves workspace ownership, but it is not sufficient
|
|
3619
|
+
// authority to signal an arbitrary PID (notably for Windows named pipes).
|
|
3620
|
+
// Require the independently recorded process-birth identity immediately
|
|
3621
|
+
// before every destructive signal so PID reuse or endpoint squatting can
|
|
3622
|
+
// only cause a fail-closed refusal.
|
|
3623
|
+
const identityMatches = owner.processStart != null &&
|
|
3624
|
+
getRuntimeProcessStart(owner.pid) === owner.processStart;
|
|
3625
|
+
if (!identityMatches || owner.pid === process.pid) {
|
|
3626
|
+
throw new RuntimeOwnerError(`Runtime ${owner.sessionId} did not stop, and its process identity cannot be safely signalled. Inspect ${owner.endpoint}.`, owner, 'runtime_owner_unverified');
|
|
3627
|
+
}
|
|
3628
|
+
try {
|
|
3629
|
+
process.kill(owner.pid, signal);
|
|
3630
|
+
}
|
|
3631
|
+
catch (error) {
|
|
3632
|
+
if (error.code !== 'ESRCH') {
|
|
3633
|
+
throw error;
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
if (await stopped(timing.signalMs ?? 5000)) {
|
|
3637
|
+
return;
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
3640
|
+
throw new RuntimeOwnerError(`Runtime ${owner.sessionId} is still present or unresponsive at ${owner.endpoint}; shutdown is not confirmed.`, owner, 'runtime_owner_shutdown_failed');
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
/**
|
|
3644
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
3645
|
+
*
|
|
3646
|
+
* This source code is licensed under the MIT license found in the
|
|
3647
|
+
* LICENSE file in the root directory of this source tree.
|
|
3648
|
+
*/
|
|
3649
|
+
const VITE_CONFIG_NAMES = [
|
|
3650
|
+
'vite.config.ts',
|
|
3651
|
+
'vite.config.js',
|
|
3652
|
+
'vite.config.mts',
|
|
3653
|
+
'vite.config.mjs',
|
|
3654
|
+
'vite.config.cts',
|
|
3655
|
+
'vite.config.cjs',
|
|
3656
|
+
];
|
|
3657
|
+
const IWSDK_PROJECT_CONFIG_NAME = 'iwsdk.config.json';
|
|
3658
|
+
const IWSDK_APP_PACKAGE_NAMES = [
|
|
3659
|
+
'@iwsdk/cli',
|
|
3660
|
+
'@iwsdk/core',
|
|
3661
|
+
'@iwsdk/vite-plugin-dev',
|
|
3662
|
+
];
|
|
3663
|
+
function readPackageManifest$1(dirPath) {
|
|
3664
|
+
try {
|
|
3665
|
+
const raw = readFileSync(path.join(dirPath, 'package.json'), 'utf8');
|
|
3666
|
+
return JSON.parse(raw);
|
|
2826
3667
|
}
|
|
2827
3668
|
catch {
|
|
2828
|
-
return
|
|
3669
|
+
return null;
|
|
3670
|
+
}
|
|
3671
|
+
}
|
|
3672
|
+
function hasIwsdkDependency(manifest) {
|
|
3673
|
+
if (!manifest) {
|
|
3674
|
+
return false;
|
|
2829
3675
|
}
|
|
3676
|
+
const dependencyBuckets = [
|
|
3677
|
+
manifest.dependencies,
|
|
3678
|
+
manifest.devDependencies,
|
|
3679
|
+
manifest.peerDependencies,
|
|
3680
|
+
];
|
|
3681
|
+
return dependencyBuckets.some((dependencies) => IWSDK_APP_PACKAGE_NAMES.some((packageName) => typeof dependencies?.[packageName] === 'string'));
|
|
2830
3682
|
}
|
|
2831
3683
|
function getRuntimeSessionFilePath(workspaceRoot) {
|
|
2832
|
-
return
|
|
3684
|
+
return getRuntimeFilePath(workspaceRoot, IWSDK_RUNTIME_SESSION_PATH);
|
|
2833
3685
|
}
|
|
2834
3686
|
function getRuntimeLaunchFilePath(workspaceRoot) {
|
|
2835
|
-
return
|
|
3687
|
+
return getRuntimeFilePath(workspaceRoot, IWSDK_RUNTIME_LAUNCH_PATH);
|
|
2836
3688
|
}
|
|
2837
3689
|
function getRuntimeLogsDir(workspaceRoot) {
|
|
2838
3690
|
return path.join(normalizeWorkspaceRoot(workspaceRoot), IWSDK_RUNTIME_LOGS_DIR);
|
|
@@ -2842,18 +3694,7 @@ async function ensureRuntimeLogsDir(workspaceRoot) {
|
|
|
2842
3694
|
await mkdir(logsDir, { recursive: true });
|
|
2843
3695
|
return logsDir;
|
|
2844
3696
|
}
|
|
2845
|
-
|
|
2846
|
-
if (!Number.isInteger(pid) || pid <= 0) {
|
|
2847
|
-
return false;
|
|
2848
|
-
}
|
|
2849
|
-
try {
|
|
2850
|
-
process.kill(pid, 0);
|
|
2851
|
-
return true;
|
|
2852
|
-
}
|
|
2853
|
-
catch {
|
|
2854
|
-
return false;
|
|
2855
|
-
}
|
|
2856
|
-
}
|
|
3697
|
+
const isProcessAlive = isRuntimeProcessAlive;
|
|
2857
3698
|
function isIwsdkAppRoot(dirPath) {
|
|
2858
3699
|
const normalizedDir = normalizeWorkspaceRoot(dirPath);
|
|
2859
3700
|
if (!existsSync(path.join(normalizedDir, 'package.json'))) {
|
|
@@ -2879,52 +3720,135 @@ function findNearestIwsdkAppRoot(startDir = process.cwd()) {
|
|
|
2879
3720
|
current = parent;
|
|
2880
3721
|
}
|
|
2881
3722
|
}
|
|
2882
|
-
async function unregisterRuntimeSession(workspaceRoot) {
|
|
2883
|
-
await removeIfExists(getRuntimeSessionFilePath(workspaceRoot));
|
|
2884
|
-
}
|
|
2885
3723
|
async function getRuntimeSession(workspaceRoot) {
|
|
2886
3724
|
const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
|
|
2887
|
-
const
|
|
3725
|
+
const filePath = getRuntimeSessionFilePath(normalizedWorkspaceRoot);
|
|
3726
|
+
const session = await withRuntimeFileLock(filePath, () => readRuntimeJson(filePath));
|
|
2888
3727
|
if (!session) {
|
|
2889
3728
|
return null;
|
|
2890
3729
|
}
|
|
2891
|
-
if (
|
|
2892
|
-
|
|
2893
|
-
|
|
3730
|
+
if (isProcessAlive(session.pid) && session.browser?.lifecycle) {
|
|
3731
|
+
const endpoint = runtimeOwnerEndpoint(normalizedWorkspaceRoot);
|
|
3732
|
+
const observation = await inspectRuntimeOwner(endpoint);
|
|
3733
|
+
if (observation.state === 'unknown') {
|
|
3734
|
+
throw new Error(`Runtime ownership is unknown at ${endpoint}: ${observation.reason}. Inspect the runtime process before retrying; no PID-only action was taken.`);
|
|
3735
|
+
}
|
|
3736
|
+
if (observation.state === 'live') {
|
|
3737
|
+
if (observation.owner.sessionId === session.sessionId &&
|
|
3738
|
+
observation.owner.pid === session.pid &&
|
|
3739
|
+
observation.owner.workspaceRoot === normalizedWorkspaceRoot) {
|
|
3740
|
+
return session;
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
else if (session.processStart != null) {
|
|
3744
|
+
const birth = getRuntimeProcessStart(session.pid);
|
|
3745
|
+
if (birth == null || birth === session.processStart) {
|
|
3746
|
+
throw new Error(`Runtime ${session.sessionId} (pid ${session.pid}) has lost its owner endpoint at ${endpoint}, but its process may still be alive. Stop that dev process before retrying.`);
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
2894
3749
|
}
|
|
2895
|
-
|
|
3750
|
+
else if (isProcessAlive(session.pid)) {
|
|
3751
|
+
return session;
|
|
3752
|
+
}
|
|
3753
|
+
// Never hold the file lock across IPC: a runtime publishing state may need
|
|
3754
|
+
// that lock before it can respond, especially with slower Windows probes.
|
|
3755
|
+
return withRuntimeFileLock(filePath, async () => {
|
|
3756
|
+
const current = await readRuntimeJson(filePath);
|
|
3757
|
+
if (current?.sessionId === session.sessionId &&
|
|
3758
|
+
current.pid === session.pid &&
|
|
3759
|
+
current.processStart === session.processStart) {
|
|
3760
|
+
await removeRuntimeFile(filePath);
|
|
3761
|
+
}
|
|
3762
|
+
return null;
|
|
3763
|
+
});
|
|
2896
3764
|
}
|
|
2897
|
-
|
|
3765
|
+
function createLaunchMetadata(input, createdAt = new Date().toISOString()) {
|
|
2898
3766
|
const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
|
|
2899
|
-
|
|
3767
|
+
return {
|
|
2900
3768
|
schemaVersion: IWSDK_RUNTIME_STATE_SCHEMA_VERSION,
|
|
3769
|
+
...(input.claimId == null ? {} : { claimId: input.claimId }),
|
|
3770
|
+
...(input.phase == null ? {} : { phase: input.phase }),
|
|
2901
3771
|
workspaceRoot,
|
|
2902
3772
|
pid: input.pid,
|
|
3773
|
+
processStart: getRuntimeProcessStart(input.pid),
|
|
3774
|
+
...(input.launcherPid == null ? {} : { launcherPid: input.launcherPid }),
|
|
3775
|
+
...(input.processGroupId == null
|
|
3776
|
+
? {}
|
|
3777
|
+
: { processGroupId: input.processGroupId }),
|
|
2903
3778
|
command: input.command,
|
|
2904
3779
|
args: input.args ?? [],
|
|
2905
3780
|
logPath: input.logPath ?? null,
|
|
2906
3781
|
scriptName: input.scriptName ?? 'dev:runtime',
|
|
2907
3782
|
port: input.port ?? null,
|
|
2908
3783
|
openBrowser: input.openBrowser ?? false,
|
|
2909
|
-
createdAt
|
|
3784
|
+
createdAt,
|
|
2910
3785
|
};
|
|
2911
|
-
await writeJsonFile(getRuntimeLaunchFilePath(workspaceRoot), metadata);
|
|
2912
|
-
return metadata;
|
|
2913
3786
|
}
|
|
2914
|
-
async function
|
|
2915
|
-
|
|
3787
|
+
async function claimLaunchMetadata(input) {
|
|
3788
|
+
const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
|
|
3789
|
+
const filePath = getRuntimeLaunchFilePath(workspaceRoot);
|
|
3790
|
+
const metadata = createLaunchMetadata({
|
|
3791
|
+
...input,
|
|
3792
|
+
phase: 'starting',
|
|
3793
|
+
workspaceRoot,
|
|
3794
|
+
});
|
|
3795
|
+
return withRuntimeFileLock(filePath, async () => {
|
|
3796
|
+
const existing = await readRuntimeJson(filePath);
|
|
3797
|
+
if (existing != null && isLaunchProcessAlive(existing)) {
|
|
3798
|
+
return { acquired: false, metadata: existing };
|
|
3799
|
+
}
|
|
3800
|
+
await writeRuntimeJson(filePath, metadata);
|
|
3801
|
+
return { acquired: true, metadata };
|
|
3802
|
+
});
|
|
3803
|
+
}
|
|
3804
|
+
async function setLaunchMetadata(input, expectedClaimId) {
|
|
3805
|
+
const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
|
|
3806
|
+
const filePath = getRuntimeLaunchFilePath(workspaceRoot);
|
|
3807
|
+
return withRuntimeFileLock(filePath, async () => {
|
|
3808
|
+
const existing = await readRuntimeJson(filePath);
|
|
3809
|
+
if (expectedClaimId != null && existing?.claimId !== expectedClaimId) {
|
|
3810
|
+
return null;
|
|
3811
|
+
}
|
|
3812
|
+
const metadata = createLaunchMetadata({ ...input, workspaceRoot }, existing != null && existing.claimId === input.claimId
|
|
3813
|
+
? existing.createdAt
|
|
3814
|
+
: new Date().toISOString());
|
|
3815
|
+
await writeRuntimeJson(filePath, metadata);
|
|
3816
|
+
return metadata;
|
|
3817
|
+
});
|
|
3818
|
+
}
|
|
3819
|
+
async function clearLaunchMetadata(workspaceRoot, expectedClaimId, expectedPhase) {
|
|
3820
|
+
const filePath = getRuntimeLaunchFilePath(workspaceRoot);
|
|
3821
|
+
return withRuntimeFileLock(filePath, async () => {
|
|
3822
|
+
const existing = await readRuntimeJson(filePath);
|
|
3823
|
+
if ((expectedClaimId == null || existing?.claimId === expectedClaimId) &&
|
|
3824
|
+
(expectedPhase == null || existing?.phase === expectedPhase)) {
|
|
3825
|
+
await removeRuntimeFile(filePath);
|
|
3826
|
+
return true;
|
|
3827
|
+
}
|
|
3828
|
+
return false;
|
|
3829
|
+
});
|
|
2916
3830
|
}
|
|
2917
3831
|
async function getLaunchMetadata(workspaceRoot) {
|
|
2918
3832
|
const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
|
|
2919
|
-
const
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
3833
|
+
const filePath = getRuntimeLaunchFilePath(normalizedWorkspaceRoot);
|
|
3834
|
+
return withRuntimeFileLock(filePath, async () => {
|
|
3835
|
+
const metadata = await readRuntimeJson(filePath);
|
|
3836
|
+
if (!metadata) {
|
|
3837
|
+
return null;
|
|
3838
|
+
}
|
|
3839
|
+
if (!isLaunchProcessAlive(metadata)) {
|
|
3840
|
+
await removeRuntimeFile(filePath);
|
|
3841
|
+
return null;
|
|
3842
|
+
}
|
|
3843
|
+
return metadata;
|
|
3844
|
+
});
|
|
3845
|
+
}
|
|
3846
|
+
function isLaunchProcessAlive(metadata) {
|
|
2923
3847
|
if (!isProcessAlive(metadata.pid)) {
|
|
2924
|
-
|
|
2925
|
-
return null;
|
|
3848
|
+
return false;
|
|
2926
3849
|
}
|
|
2927
|
-
|
|
3850
|
+
const birth = metadata.processStart == null ? null : getRuntimeProcessStart(metadata.pid);
|
|
3851
|
+
return birth == null || birth === metadata.processStart;
|
|
2928
3852
|
}
|
|
2929
3853
|
async function getWorkspaceRuntimeState(workspaceRoot) {
|
|
2930
3854
|
const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
|
|
@@ -2945,6 +3869,12 @@ async function getWorkspaceRuntimeState(workspaceRoot) {
|
|
|
2945
3869
|
launch,
|
|
2946
3870
|
};
|
|
2947
3871
|
}
|
|
3872
|
+
function getRuntimeUrls(session) {
|
|
3873
|
+
return {
|
|
3874
|
+
local: session?.localUrl ?? null,
|
|
3875
|
+
network: session?.networkUrls ?? [],
|
|
3876
|
+
};
|
|
3877
|
+
}
|
|
2948
3878
|
function formatMissingRuntimeMessage(workspaceRoot) {
|
|
2949
3879
|
return `No running IWSDK runtime found for ${workspaceRoot}. Start the dev server with "iwsdk dev up".`;
|
|
2950
3880
|
}
|
|
@@ -8106,6 +9036,102 @@ const { Duplex } = require$$0$2;
|
|
|
8106
9036
|
const { createHash } = require$$1;
|
|
8107
9037
|
const { CLOSE_TIMEOUT, GUID, kWebSocket } = constants;
|
|
8108
9038
|
|
|
9039
|
+
/**
|
|
9040
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
9041
|
+
*
|
|
9042
|
+
* This source code is licensed under the MIT license found in the
|
|
9043
|
+
* LICENSE file in the root directory of this source tree.
|
|
9044
|
+
*/
|
|
9045
|
+
/** Keep a command connection open for the complete secondary-CDP operation. */
|
|
9046
|
+
async function acquireBrowserLease(session, timeoutMs) {
|
|
9047
|
+
const id = randomUUID();
|
|
9048
|
+
const protocol = session.localUrl.startsWith('https:') ? 'wss' : 'ws';
|
|
9049
|
+
const ws = new WebSocket$1(`${protocol}://127.0.0.1:${session.port}/__iwer_mcp`, { rejectUnauthorized: false });
|
|
9050
|
+
let granted = false;
|
|
9051
|
+
let released = false;
|
|
9052
|
+
let closed = false;
|
|
9053
|
+
let rejectLost;
|
|
9054
|
+
const lost = new Promise((_resolve, reject) => {
|
|
9055
|
+
rejectLost = reject;
|
|
9056
|
+
});
|
|
9057
|
+
// A connection can die between granting and the caller's Promise.race.
|
|
9058
|
+
void lost.catch(() => { });
|
|
9059
|
+
const release = () => {
|
|
9060
|
+
if (closed) {
|
|
9061
|
+
return;
|
|
9062
|
+
}
|
|
9063
|
+
closed = true;
|
|
9064
|
+
released = true;
|
|
9065
|
+
if (granted && ws.readyState === WebSocket$1.OPEN) {
|
|
9066
|
+
ws.send(JSON.stringify({ id, method: '__iwsdk_browser_lease_release' }));
|
|
9067
|
+
}
|
|
9068
|
+
ws.close();
|
|
9069
|
+
};
|
|
9070
|
+
// Closing without a release is deliberate: the runtime treats the lost
|
|
9071
|
+
// lease as an uncertain command outcome and retires the owned browser before
|
|
9072
|
+
// admitting another command. This prevents a rejected or timed-out runner
|
|
9073
|
+
// from continuing CDP work concurrently with a later command.
|
|
9074
|
+
const abandon = () => {
|
|
9075
|
+
if (closed) {
|
|
9076
|
+
return;
|
|
9077
|
+
}
|
|
9078
|
+
closed = true;
|
|
9079
|
+
ws.close();
|
|
9080
|
+
};
|
|
9081
|
+
try {
|
|
9082
|
+
await new Promise((resolve, reject) => {
|
|
9083
|
+
const timer = setTimeout(() => {
|
|
9084
|
+
reject(new Error('Timed out acquiring the managed browser lease.'));
|
|
9085
|
+
ws.close();
|
|
9086
|
+
}, 20000);
|
|
9087
|
+
const failed = (error) => {
|
|
9088
|
+
clearTimeout(timer);
|
|
9089
|
+
if (granted && !released) {
|
|
9090
|
+
rejectLost(error);
|
|
9091
|
+
}
|
|
9092
|
+
else if (!granted) {
|
|
9093
|
+
reject(error);
|
|
9094
|
+
}
|
|
9095
|
+
};
|
|
9096
|
+
ws.on('error', failed);
|
|
9097
|
+
ws.on('close', () => failed(new Error('Managed browser lease was lost. The script outcome is unknown.')));
|
|
9098
|
+
ws.on('open', () => ws.send(JSON.stringify({
|
|
9099
|
+
id,
|
|
9100
|
+
method: '__iwsdk_browser_lease',
|
|
9101
|
+
expectedSessionId: session.sessionId,
|
|
9102
|
+
params: {
|
|
9103
|
+
browserEpoch: session.browser?.lifecycle?.browserEpoch,
|
|
9104
|
+
targetId: session.browserAutomation?.targetId,
|
|
9105
|
+
timeoutMs,
|
|
9106
|
+
},
|
|
9107
|
+
})));
|
|
9108
|
+
ws.on('message', (raw) => {
|
|
9109
|
+
try {
|
|
9110
|
+
const response = JSON.parse(raw.toString());
|
|
9111
|
+
if (response.id !== id) {
|
|
9112
|
+
return;
|
|
9113
|
+
}
|
|
9114
|
+
clearTimeout(timer);
|
|
9115
|
+
if (response.error) {
|
|
9116
|
+
failed(new Error(response.error.message));
|
|
9117
|
+
return;
|
|
9118
|
+
}
|
|
9119
|
+
granted = true;
|
|
9120
|
+
resolve();
|
|
9121
|
+
}
|
|
9122
|
+
catch (error) {
|
|
9123
|
+
failed(error);
|
|
9124
|
+
}
|
|
9125
|
+
});
|
|
9126
|
+
});
|
|
9127
|
+
return { abandon, release, lost };
|
|
9128
|
+
}
|
|
9129
|
+
catch (error) {
|
|
9130
|
+
release();
|
|
9131
|
+
throw error;
|
|
9132
|
+
}
|
|
9133
|
+
}
|
|
9134
|
+
|
|
8109
9135
|
/**
|
|
8110
9136
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
8111
9137
|
*
|
|
@@ -8162,6 +9188,26 @@ function getProtocolOrder(runtimeSession) {
|
|
|
8162
9188
|
function isRecord$2(value) {
|
|
8163
9189
|
return value != null && typeof value === 'object' && !Array.isArray(value);
|
|
8164
9190
|
}
|
|
9191
|
+
const PERMISSION_FAILURE = /permission|not permitted|denied|sandbox|eacces|eperm/i;
|
|
9192
|
+
function isTransportFailure(normalized) {
|
|
9193
|
+
return (normalized.includes('socket hang up') ||
|
|
9194
|
+
normalized.includes('closed before response') ||
|
|
9195
|
+
normalized.includes('request timeout') ||
|
|
9196
|
+
normalized.includes('econnreset') ||
|
|
9197
|
+
normalized.includes('econnrefused'));
|
|
9198
|
+
}
|
|
9199
|
+
/** A headset's failures are its own; managed browser state never explains them. */
|
|
9200
|
+
function inferPhysicalIssueCause(message, explicitCause) {
|
|
9201
|
+
if (explicitCause) {
|
|
9202
|
+
return explicitCause;
|
|
9203
|
+
}
|
|
9204
|
+
if (PERMISSION_FAILURE.test(message)) {
|
|
9205
|
+
return 'permission_denied';
|
|
9206
|
+
}
|
|
9207
|
+
return isTransportFailure(message.toLowerCase())
|
|
9208
|
+
? 'connection_lost'
|
|
9209
|
+
: undefined;
|
|
9210
|
+
}
|
|
8165
9211
|
function inferRuntimeIssueCause(message, browser, explicitCause) {
|
|
8166
9212
|
if (explicitCause) {
|
|
8167
9213
|
return explicitCause;
|
|
@@ -8187,14 +9233,10 @@ function inferRuntimeIssueCause(message, browser, explicitCause) {
|
|
|
8187
9233
|
normalized.includes('relaunch')) {
|
|
8188
9234
|
return 'browser_relaunched';
|
|
8189
9235
|
}
|
|
8190
|
-
if (
|
|
9236
|
+
if (PERMISSION_FAILURE.test(normalized)) {
|
|
8191
9237
|
return 'permission_denied';
|
|
8192
9238
|
}
|
|
8193
|
-
if (normalized
|
|
8194
|
-
normalized.includes('closed before response') ||
|
|
8195
|
-
normalized.includes('request timeout') ||
|
|
8196
|
-
normalized.includes('econnreset') ||
|
|
8197
|
-
normalized.includes('econnrefused')) {
|
|
9239
|
+
if (isTransportFailure(normalized)) {
|
|
8198
9240
|
if (browser &&
|
|
8199
9241
|
!isRuntimeBrowserCommandReady({
|
|
8200
9242
|
schemaVersion: 1,
|
|
@@ -8206,14 +9248,19 @@ function inferRuntimeIssueCause(message, browser, explicitCause) {
|
|
|
8206
9248
|
}
|
|
8207
9249
|
return undefined;
|
|
8208
9250
|
}
|
|
8209
|
-
async function trySendRuntimeCommand(protocol, port, method, params, target,
|
|
9251
|
+
async function trySendRuntimeCommand(protocol, port, method, params, target, deadline, connectDeadline, browser, expectedSessionId) {
|
|
9252
|
+
const inferCause = (message, explicitCause) => target?.deviceClass === 'physical'
|
|
9253
|
+
? inferPhysicalIssueCause(message, explicitCause)
|
|
9254
|
+
: inferRuntimeIssueCause(message, browser, explicitCause);
|
|
8210
9255
|
return new Promise((resolve, reject) => {
|
|
9256
|
+
const timeoutMs = Math.max(Math.min(deadline, connectDeadline) - Date.now(), 1);
|
|
8211
9257
|
const requestId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
8212
9258
|
const wsUrl = `${protocol}://127.0.0.1:${port}/__iwer_mcp`;
|
|
8213
9259
|
const ws = new WebSocket$1(wsUrl, {
|
|
8214
9260
|
rejectUnauthorized: false,
|
|
8215
9261
|
});
|
|
8216
9262
|
let settled = false;
|
|
9263
|
+
let dispatched = false;
|
|
8217
9264
|
const finish = (callback) => {
|
|
8218
9265
|
if (settled) {
|
|
8219
9266
|
return;
|
|
@@ -8243,7 +9290,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8243
9290
|
})
|
|
8244
9291
|
: false,
|
|
8245
9292
|
});
|
|
8246
|
-
const
|
|
9293
|
+
const onTimeout = () => {
|
|
8247
9294
|
const message = `Request timeout for ${method}`;
|
|
8248
9295
|
traceTransport('timeout', {
|
|
8249
9296
|
method,
|
|
@@ -8253,12 +9300,30 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8253
9300
|
});
|
|
8254
9301
|
closeSocket();
|
|
8255
9302
|
finish(() => reject(new RuntimeCommandTransportError(message, {
|
|
8256
|
-
issueCause:
|
|
9303
|
+
issueCause: inferCause(message),
|
|
8257
9304
|
browser,
|
|
9305
|
+
details: {
|
|
9306
|
+
outcome: dispatched ? 'outcome_unknown' : 'not_executed',
|
|
9307
|
+
},
|
|
8258
9308
|
})));
|
|
8259
|
-
}
|
|
9309
|
+
};
|
|
9310
|
+
// Until the socket opens, only the connection budget applies; a probe that
|
|
9311
|
+
// times out has dispatched nothing and may fall back to another protocol.
|
|
9312
|
+
let timeout = setTimeout(onTimeout, timeoutMs);
|
|
8260
9313
|
ws.on('open', () => {
|
|
9314
|
+
// Once open, the command gets its whole original deadline, and the relay
|
|
9315
|
+
// settles against that same absolute deadline, so admission time and a
|
|
9316
|
+
// WSS probe never extend or shorten the caller's budget. An open that
|
|
9317
|
+
// lands after the deadline dispatches nothing.
|
|
9318
|
+
clearTimeout(timeout);
|
|
9319
|
+
if (deadline <= Date.now()) {
|
|
9320
|
+
onTimeout();
|
|
9321
|
+
return;
|
|
9322
|
+
}
|
|
9323
|
+
timeout = setTimeout(onTimeout, deadline - Date.now());
|
|
8261
9324
|
const payload = JSON.stringify({
|
|
9325
|
+
deadline,
|
|
9326
|
+
expectedSessionId,
|
|
8262
9327
|
id: requestId,
|
|
8263
9328
|
method,
|
|
8264
9329
|
params: params ?? {},
|
|
@@ -8270,6 +9335,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8270
9335
|
protocol,
|
|
8271
9336
|
port,
|
|
8272
9337
|
});
|
|
9338
|
+
dispatched = true;
|
|
8273
9339
|
ws.send(payload, (error) => {
|
|
8274
9340
|
if (!error) {
|
|
8275
9341
|
traceTransport('send', {
|
|
@@ -8288,8 +9354,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8288
9354
|
});
|
|
8289
9355
|
closeSocket();
|
|
8290
9356
|
finish(() => reject(new RuntimeCommandTransportError(error.message, {
|
|
8291
|
-
issueCause:
|
|
9357
|
+
issueCause: inferCause(error.message),
|
|
8292
9358
|
browser,
|
|
9359
|
+
details: {
|
|
9360
|
+
outcome: dispatched ? 'outcome_unknown' : 'not_executed',
|
|
9361
|
+
},
|
|
8293
9362
|
})));
|
|
8294
9363
|
});
|
|
8295
9364
|
});
|
|
@@ -8324,7 +9393,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8324
9393
|
cause: explicitCause ?? null,
|
|
8325
9394
|
});
|
|
8326
9395
|
finish(() => reject(new RuntimeCommandExecutionError(message, {
|
|
8327
|
-
issueCause:
|
|
9396
|
+
issueCause: inferCause(message, explicitCause),
|
|
8328
9397
|
browser,
|
|
8329
9398
|
details,
|
|
8330
9399
|
})));
|
|
@@ -8347,8 +9416,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8347
9416
|
});
|
|
8348
9417
|
closeSocket();
|
|
8349
9418
|
finish(() => reject(new RuntimeCommandTransportError(message, {
|
|
8350
|
-
issueCause:
|
|
9419
|
+
issueCause: inferCause(message),
|
|
8351
9420
|
browser,
|
|
9421
|
+
details: {
|
|
9422
|
+
outcome: dispatched ? 'outcome_unknown' : 'not_executed',
|
|
9423
|
+
},
|
|
8352
9424
|
})));
|
|
8353
9425
|
}
|
|
8354
9426
|
});
|
|
@@ -8361,8 +9433,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8361
9433
|
});
|
|
8362
9434
|
closeSocket();
|
|
8363
9435
|
finish(() => reject(new RuntimeCommandTransportError(error.message, {
|
|
8364
|
-
issueCause:
|
|
9436
|
+
issueCause: inferCause(error.message),
|
|
8365
9437
|
browser,
|
|
9438
|
+
details: {
|
|
9439
|
+
outcome: dispatched ? 'outcome_unknown' : 'not_executed',
|
|
9440
|
+
},
|
|
8366
9441
|
})));
|
|
8367
9442
|
});
|
|
8368
9443
|
ws.on('close', (code, reasonBuffer) => {
|
|
@@ -8384,30 +9459,37 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
|
|
|
8384
9459
|
? `Connection closed before response for ${method}: ${reason}`
|
|
8385
9460
|
: `Connection closed before response for ${method} (code ${code})`;
|
|
8386
9461
|
finish(() => reject(new RuntimeCommandTransportError(message, {
|
|
8387
|
-
issueCause:
|
|
9462
|
+
issueCause: inferCause(message),
|
|
8388
9463
|
browser,
|
|
9464
|
+
details: {
|
|
9465
|
+
outcome: dispatched ? 'outcome_unknown' : 'not_executed',
|
|
9466
|
+
},
|
|
8389
9467
|
})));
|
|
8390
9468
|
});
|
|
8391
9469
|
});
|
|
8392
9470
|
}
|
|
8393
9471
|
async function sendRuntimeCommandBeforeDeadline(options, deadline) {
|
|
8394
9472
|
const { method, params, port, runtimeSession, target } = options;
|
|
8395
|
-
|
|
9473
|
+
// Managed browser state describes the host browser only, never a headset.
|
|
9474
|
+
const browser = target?.deviceClass === 'physical' ? undefined : runtimeSession?.browser;
|
|
8396
9475
|
const protocolOrder = getProtocolOrder(runtimeSession);
|
|
8397
9476
|
const firstProtocol = protocolOrder[0];
|
|
8398
9477
|
const fallbackProtocol = protocolOrder[1];
|
|
8399
9478
|
const remainingAtStart = Math.max(deadline - Date.now(), 1);
|
|
8400
|
-
|
|
8401
|
-
|
|
8402
|
-
|
|
9479
|
+
// An unknown scheme probes WSS briefly; the budget covers connecting only.
|
|
9480
|
+
const connectDeadline = fallbackProtocol && firstProtocol === 'wss'
|
|
9481
|
+
? Date.now() + FAST_WSS_FALLBACK_TIMEOUT_MS
|
|
9482
|
+
: deadline;
|
|
8403
9483
|
try {
|
|
8404
|
-
return await trySendRuntimeCommand(firstProtocol, port, method, params, target,
|
|
9484
|
+
return await trySendRuntimeCommand(firstProtocol, port, method, params, target, deadline, connectDeadline, browser, runtimeSession?.sessionId);
|
|
8405
9485
|
}
|
|
8406
9486
|
catch (error) {
|
|
8407
9487
|
if (!(error instanceof RuntimeCommandTransportError)) {
|
|
8408
9488
|
throw error;
|
|
8409
9489
|
}
|
|
8410
|
-
if (
|
|
9490
|
+
if (error.details?.outcome === 'outcome_unknown' ||
|
|
9491
|
+
!fallbackProtocol ||
|
|
9492
|
+
fallbackProtocol === firstProtocol) {
|
|
8411
9493
|
throw error;
|
|
8412
9494
|
}
|
|
8413
9495
|
const remainingMs = Math.max(deadline - Date.now(), 1);
|
|
@@ -8426,7 +9508,7 @@ async function sendRuntimeCommandBeforeDeadline(options, deadline) {
|
|
|
8426
9508
|
})
|
|
8427
9509
|
: false,
|
|
8428
9510
|
});
|
|
8429
|
-
return trySendRuntimeCommand(fallbackProtocol, port, method, params, target,
|
|
9511
|
+
return trySendRuntimeCommand(fallbackProtocol, port, method, params, target, deadline, deadline, browser, runtimeSession?.sessionId);
|
|
8430
9512
|
}
|
|
8431
9513
|
}
|
|
8432
9514
|
function sceneOpenReadinessRequest(method, params, response, previousSceneSessionId) {
|
|
@@ -8576,13 +9658,6 @@ async function confirmOpenedSceneReady(options, response, deadline, previousScen
|
|
|
8576
9658
|
});
|
|
8577
9659
|
}
|
|
8578
9660
|
async function sendRuntimeCommand({ port, method, params, target, timeoutMs = getDefaultRuntimeCommandTimeoutMs(method), runtimeSession, }) {
|
|
8579
|
-
if (runtimeSession?.browser?.status === 'not_launched') {
|
|
8580
|
-
throw new RuntimeCommandExecutionError(runtimeSession.browser.lastError?.message ??
|
|
8581
|
-
'No managed browser was launched. Run "iwsdk dev restart --open" to enable browser, scene, and runtime tools.', {
|
|
8582
|
-
issueCause: 'browser_not_launched',
|
|
8583
|
-
browser: runtimeSession.browser,
|
|
8584
|
-
});
|
|
8585
|
-
}
|
|
8586
9661
|
const deadline = Date.now() + Math.max(timeoutMs, 1);
|
|
8587
9662
|
const options = { method, params, port, runtimeSession, target };
|
|
8588
9663
|
const previousSceneSessionId = await captureSceneOpenSessionBaseline(options, deadline);
|
|
@@ -8590,6 +9665,355 @@ async function sendRuntimeCommand({ port, method, params, target, timeoutMs = ge
|
|
|
8590
9665
|
return confirmOpenedSceneReady(options, response, deadline, previousSceneSessionId);
|
|
8591
9666
|
}
|
|
8592
9667
|
|
|
9668
|
+
/**
|
|
9669
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
9670
|
+
*
|
|
9671
|
+
* This source code is licensed under the MIT license found in the
|
|
9672
|
+
* LICENSE file in the root directory of this source tree.
|
|
9673
|
+
*/
|
|
9674
|
+
const MAX_RUNNER_RESULT_BYTES = 1024 * 1024;
|
|
9675
|
+
async function getPageTargetId(context, page) {
|
|
9676
|
+
const cdp = await context.newCDPSession(page);
|
|
9677
|
+
try {
|
|
9678
|
+
const response = await cdp.send('Target.getTargetInfo');
|
|
9679
|
+
const targetId = response?.targetInfo?.targetId;
|
|
9680
|
+
return typeof targetId === 'string' ? targetId : '';
|
|
9681
|
+
}
|
|
9682
|
+
finally {
|
|
9683
|
+
await cdp.detach().catch(() => { });
|
|
9684
|
+
}
|
|
9685
|
+
}
|
|
9686
|
+
async function selectManagedBrowserPage(browser, managedOrigin, expectedTargetId) {
|
|
9687
|
+
const originCandidates = browser
|
|
9688
|
+
.contexts()
|
|
9689
|
+
.flatMap((candidateContext) => candidateContext.pages().map((candidatePage) => ({
|
|
9690
|
+
context: candidateContext,
|
|
9691
|
+
page: candidatePage,
|
|
9692
|
+
})))
|
|
9693
|
+
.filter(({ page: candidatePage }) => {
|
|
9694
|
+
try {
|
|
9695
|
+
return new URL(candidatePage.url()).origin === managedOrigin;
|
|
9696
|
+
}
|
|
9697
|
+
catch {
|
|
9698
|
+
return false;
|
|
9699
|
+
}
|
|
9700
|
+
});
|
|
9701
|
+
const managedCandidates = [];
|
|
9702
|
+
for (const candidate of originCandidates) {
|
|
9703
|
+
const opener = typeof candidate.page.opener === 'function'
|
|
9704
|
+
? await candidate.page.opener().catch(() => null)
|
|
9705
|
+
: null;
|
|
9706
|
+
if (opener != null) {
|
|
9707
|
+
continue;
|
|
9708
|
+
}
|
|
9709
|
+
const [targetId, marked] = await Promise.all([
|
|
9710
|
+
getPageTargetId(candidate.context, candidate.page).catch(() => ''),
|
|
9711
|
+
candidate.page
|
|
9712
|
+
.evaluate(() => globalThis.__IWSDK_MANAGED_BROWSER_TARGET === true)
|
|
9713
|
+
.catch(() => false),
|
|
9714
|
+
]);
|
|
9715
|
+
if (targetId === expectedTargetId && marked) {
|
|
9716
|
+
managedCandidates.push(candidate);
|
|
9717
|
+
}
|
|
9718
|
+
}
|
|
9719
|
+
if (managedCandidates.length !== 1) {
|
|
9720
|
+
throw new Error(`Expected exactly one verified managed application page; found ${managedCandidates.length}`);
|
|
9721
|
+
}
|
|
9722
|
+
return managedCandidates[0];
|
|
9723
|
+
}
|
|
9724
|
+
function validateAutomationEndpoint(endpoint) {
|
|
9725
|
+
let parsed;
|
|
9726
|
+
try {
|
|
9727
|
+
parsed = new URL(endpoint);
|
|
9728
|
+
}
|
|
9729
|
+
catch {
|
|
9730
|
+
throw new Error('Managed browser automation endpoint is invalid');
|
|
9731
|
+
}
|
|
9732
|
+
const loopbackHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
9733
|
+
if (parsed.protocol !== 'http:' ||
|
|
9734
|
+
!loopbackHosts.has(parsed.hostname) ||
|
|
9735
|
+
parsed.username !== '' ||
|
|
9736
|
+
parsed.password !== '' ||
|
|
9737
|
+
parsed.search !== '' ||
|
|
9738
|
+
parsed.hash !== '') {
|
|
9739
|
+
throw new Error('Managed browser automation endpoint must use loopback HTTP');
|
|
9740
|
+
}
|
|
9741
|
+
return parsed.href;
|
|
9742
|
+
}
|
|
9743
|
+
async function withTimeout(operation, timeoutMs, onTimeout) {
|
|
9744
|
+
let timer = null;
|
|
9745
|
+
return Promise.race([
|
|
9746
|
+
operation,
|
|
9747
|
+
new Promise((_, reject) => {
|
|
9748
|
+
timer = setTimeout(() => {
|
|
9749
|
+
onTimeout();
|
|
9750
|
+
reject(new Error(`browser run timed out after ${timeoutMs}ms`));
|
|
9751
|
+
}, timeoutMs);
|
|
9752
|
+
}),
|
|
9753
|
+
]).finally(() => {
|
|
9754
|
+
if (timer != null) {
|
|
9755
|
+
clearTimeout(timer);
|
|
9756
|
+
}
|
|
9757
|
+
});
|
|
9758
|
+
}
|
|
9759
|
+
const DESTRUCTIVE_CDP_METHODS = new Set([
|
|
9760
|
+
'Browser.close',
|
|
9761
|
+
'Page.close',
|
|
9762
|
+
'Target.closeTarget',
|
|
9763
|
+
'Target.disposeBrowserContext',
|
|
9764
|
+
]);
|
|
9765
|
+
function protectCdpOwnership(cdp) {
|
|
9766
|
+
const send = cdp.send.bind(cdp);
|
|
9767
|
+
cdp.send = async (method, params) => {
|
|
9768
|
+
if (DESTRUCTIVE_CDP_METHODS.has(method)) {
|
|
9769
|
+
throw new Error(`Direct CDP method ${method} is blocked for IWSDK-owned browser resources`);
|
|
9770
|
+
}
|
|
9771
|
+
return send(method, params);
|
|
9772
|
+
};
|
|
9773
|
+
}
|
|
9774
|
+
function protectManagedOwnership(browser, context, page, cdp) {
|
|
9775
|
+
const deny = () => {
|
|
9776
|
+
throw new Error('The managed browser, context, and application page are owned by IWSDK; direct close operations are blocked in browser run scripts.');
|
|
9777
|
+
};
|
|
9778
|
+
browser.close = deny;
|
|
9779
|
+
context.close = deny;
|
|
9780
|
+
page.close = deny;
|
|
9781
|
+
protectCdpOwnership(cdp);
|
|
9782
|
+
const newContextCdp = context.newCDPSession?.bind(context);
|
|
9783
|
+
if (newContextCdp) {
|
|
9784
|
+
context.newCDPSession = async (...args) => {
|
|
9785
|
+
const session = await newContextCdp(...args);
|
|
9786
|
+
protectCdpOwnership(session);
|
|
9787
|
+
return session;
|
|
9788
|
+
};
|
|
9789
|
+
}
|
|
9790
|
+
const newBrowserCdp = browser.newBrowserCDPSession?.bind(browser);
|
|
9791
|
+
if (newBrowserCdp) {
|
|
9792
|
+
browser.newBrowserCDPSession = async (...args) => {
|
|
9793
|
+
const session = await newBrowserCdp(...args);
|
|
9794
|
+
protectCdpOwnership(session);
|
|
9795
|
+
return session;
|
|
9796
|
+
};
|
|
9797
|
+
}
|
|
9798
|
+
}
|
|
9799
|
+
function serializeRunnerResult(value) {
|
|
9800
|
+
if (value === undefined) {
|
|
9801
|
+
return null;
|
|
9802
|
+
}
|
|
9803
|
+
let serialized;
|
|
9804
|
+
try {
|
|
9805
|
+
serialized = JSON.stringify(value);
|
|
9806
|
+
}
|
|
9807
|
+
catch {
|
|
9808
|
+
throw new Error('browser run result must be JSON-serializable');
|
|
9809
|
+
}
|
|
9810
|
+
if (serialized == null) {
|
|
9811
|
+
throw new Error('browser run result must be JSON-serializable');
|
|
9812
|
+
}
|
|
9813
|
+
if (Buffer.byteLength(serialized, 'utf8') > MAX_RUNNER_RESULT_BYTES) {
|
|
9814
|
+
throw new Error(`browser run result exceeds ${MAX_RUNNER_RESULT_BYTES} bytes`);
|
|
9815
|
+
}
|
|
9816
|
+
return JSON.parse(serialized);
|
|
9817
|
+
}
|
|
9818
|
+
async function handleBrowserRun(scriptArgument, options, io) {
|
|
9819
|
+
if (!scriptArgument) {
|
|
9820
|
+
throw new Error('Usage: iwsdk browser run <workspace-script.mjs>');
|
|
9821
|
+
}
|
|
9822
|
+
const workspaceRoot = await resolveWorkspaceRoot({
|
|
9823
|
+
cwd: io.cwd,
|
|
9824
|
+
workspace: typeof options.workspace === 'string' ? options.workspace : undefined,
|
|
9825
|
+
requireRunning: true,
|
|
9826
|
+
});
|
|
9827
|
+
const requestedScriptPath = path.resolve(io.cwd, scriptArgument);
|
|
9828
|
+
const requestedDirectory = path.dirname(requestedScriptPath);
|
|
9829
|
+
// Workspace discovery canonicalizes directory aliases (for example macOS
|
|
9830
|
+
// /var -> /private/var). Compare paths in the same namespace, while leaving
|
|
9831
|
+
// a symlink on the script itself for the separate containment check below.
|
|
9832
|
+
const scriptPath = path.join(existsSync(requestedDirectory)
|
|
9833
|
+
? realpathSync.native(requestedDirectory)
|
|
9834
|
+
: requestedDirectory, path.basename(requestedScriptPath));
|
|
9835
|
+
const relativeScriptPath = path.relative(workspaceRoot, scriptPath);
|
|
9836
|
+
if (relativeScriptPath === '..' ||
|
|
9837
|
+
relativeScriptPath.startsWith(`..${path.sep}`) ||
|
|
9838
|
+
path.isAbsolute(relativeScriptPath)) {
|
|
9839
|
+
throw new Error('browser run script must stay inside the IWSDK workspace');
|
|
9840
|
+
}
|
|
9841
|
+
if (!existsSync(scriptPath)) {
|
|
9842
|
+
throw new Error(`browser run script does not exist: ${relativeScriptPath}`);
|
|
9843
|
+
}
|
|
9844
|
+
const realWorkspaceRoot = realpathSync(workspaceRoot);
|
|
9845
|
+
const realScriptPath = realpathSync(scriptPath);
|
|
9846
|
+
const realRelativeScriptPath = path.relative(realWorkspaceRoot, realScriptPath);
|
|
9847
|
+
if (realRelativeScriptPath === '..' ||
|
|
9848
|
+
realRelativeScriptPath.startsWith(`..${path.sep}`) ||
|
|
9849
|
+
path.isAbsolute(realRelativeScriptPath)) {
|
|
9850
|
+
throw new Error('browser run script symlinks must stay inside the IWSDK workspace');
|
|
9851
|
+
}
|
|
9852
|
+
const session = await getRuntimeSession(workspaceRoot);
|
|
9853
|
+
if (!session) {
|
|
9854
|
+
throw new Error('Managed browser runtime session is unavailable');
|
|
9855
|
+
}
|
|
9856
|
+
const automation = session.browserAutomation;
|
|
9857
|
+
const automationConfigured = automation?.configured ?? automation?.enabled ?? false;
|
|
9858
|
+
if (!automationConfigured) {
|
|
9859
|
+
throw new Error('Managed browser automation is disabled. Start with "iwsdk dev up --allow-browser-automation" or restart with "iwsdk dev restart --allow-browser-automation".');
|
|
9860
|
+
}
|
|
9861
|
+
const endpoint = automation?.endpoint;
|
|
9862
|
+
const expectedTargetId = automation?.targetId;
|
|
9863
|
+
if (!automation?.enabled || !endpoint || !expectedTargetId) {
|
|
9864
|
+
throw new Error('Managed browser automation is configured, but the managed browser is not running. Retry after the browser relaunches or restart the dev session.');
|
|
9865
|
+
}
|
|
9866
|
+
if (automation.protocol !== 'cdp') {
|
|
9867
|
+
throw new Error('Managed browser automation protocol is unsupported');
|
|
9868
|
+
}
|
|
9869
|
+
const automationEndpoint = validateAutomationEndpoint(endpoint);
|
|
9870
|
+
const timeoutMs = parseIntegerOption(options.timeout, '--timeout', 60_000);
|
|
9871
|
+
const requireFromWorkspace = createRequire(path.join(workspaceRoot, 'package.json'));
|
|
9872
|
+
let playwright;
|
|
9873
|
+
try {
|
|
9874
|
+
playwright = requireFromWorkspace('playwright');
|
|
9875
|
+
}
|
|
9876
|
+
catch {
|
|
9877
|
+
try {
|
|
9878
|
+
let requireFromPlugin;
|
|
9879
|
+
try {
|
|
9880
|
+
const pluginEntry = requireFromWorkspace.resolve('@iwsdk/vite-plugin-dev');
|
|
9881
|
+
requireFromPlugin = createRequire(pluginEntry);
|
|
9882
|
+
}
|
|
9883
|
+
catch {
|
|
9884
|
+
// The package exports only an ESM entry, so CommonJS resolution can
|
|
9885
|
+
// reject the package root even though the dependency is installed.
|
|
9886
|
+
requireFromPlugin = createRequire(path.join(workspaceRoot, 'node_modules', '@iwsdk', 'vite-plugin-dev', 'package.json'));
|
|
9887
|
+
}
|
|
9888
|
+
playwright = requireFromPlugin('playwright');
|
|
9889
|
+
}
|
|
9890
|
+
catch {
|
|
9891
|
+
throw new Error('The workspace does not expose Playwright through @iwsdk/vite-plugin-dev. Reinstall the IWSDK development dependencies.');
|
|
9892
|
+
}
|
|
9893
|
+
}
|
|
9894
|
+
if (session.browser?.lifecycle && timeoutMs > 110000) {
|
|
9895
|
+
throw new Error('Managed browser scripts are limited to 110000ms per lease.');
|
|
9896
|
+
}
|
|
9897
|
+
const browser = await playwright.chromium.connectOverCDP(automationEndpoint, {
|
|
9898
|
+
timeout: Math.min(timeoutMs, 30_000),
|
|
9899
|
+
});
|
|
9900
|
+
// For a connectOverCDP browser, Playwright's close implementation disconnects
|
|
9901
|
+
// the secondary CDP transport. Capture it before scripts receive protected
|
|
9902
|
+
// wrappers; closing the shared client connection can tear down the owner.
|
|
9903
|
+
const disconnectBrowser = browser.close.bind(browser);
|
|
9904
|
+
let lease = null;
|
|
9905
|
+
try {
|
|
9906
|
+
// Connecting is read-only. Acquire exclusive ownership immediately after
|
|
9907
|
+
// connection so the complete lease budget remains available to the script.
|
|
9908
|
+
lease = session.browser?.lifecycle
|
|
9909
|
+
? await acquireBrowserLease(session, timeoutMs + 5000)
|
|
9910
|
+
: null;
|
|
9911
|
+
}
|
|
9912
|
+
catch (error) {
|
|
9913
|
+
await disconnectBrowser().catch(() => { });
|
|
9914
|
+
throw error;
|
|
9915
|
+
}
|
|
9916
|
+
let cdp = null;
|
|
9917
|
+
const cleanup = {
|
|
9918
|
+
detachCdp: null,
|
|
9919
|
+
};
|
|
9920
|
+
const abortController = new AbortController();
|
|
9921
|
+
let runnerSettled = false;
|
|
9922
|
+
try {
|
|
9923
|
+
const runnerOperation = (async () => {
|
|
9924
|
+
try {
|
|
9925
|
+
const managedOrigin = new URL(session.localUrl).origin;
|
|
9926
|
+
const selected = await selectManagedBrowserPage(browser, managedOrigin, expectedTargetId);
|
|
9927
|
+
const { context, page } = selected;
|
|
9928
|
+
const pageUrl = new URL(page.url());
|
|
9929
|
+
// Keep this small DOM-boundary resolver local to the CLI runner. The
|
|
9930
|
+
// plugin's resolver owns a live Playwright Page and is intentionally
|
|
9931
|
+
// private; exporting it would couple the CLI to plugin internals while
|
|
9932
|
+
// still requiring separate serialization across the CDP connection.
|
|
9933
|
+
const workspacePath = pageUrl.pathname === '/__iwsdk/workspace' ||
|
|
9934
|
+
pageUrl.pathname.startsWith('/__iwsdk/workspace/');
|
|
9935
|
+
const workspaceDataset = workspacePath
|
|
9936
|
+
? false
|
|
9937
|
+
: await page.evaluate(() => globalThis.document.documentElement.dataset
|
|
9938
|
+
.iwsdkWorkspaceView != null);
|
|
9939
|
+
const hasWorkspaceMarker = workspacePath || workspaceDataset;
|
|
9940
|
+
const frameElement = hasWorkspaceMarker
|
|
9941
|
+
? await page.$('#workspace-runtime-frame')
|
|
9942
|
+
: null;
|
|
9943
|
+
const frame = await frameElement?.contentFrame();
|
|
9944
|
+
if (hasWorkspaceMarker && !frame) {
|
|
9945
|
+
throw new Error('IWSDK workspace application frame is unavailable');
|
|
9946
|
+
}
|
|
9947
|
+
cdp = await context.newCDPSession(page);
|
|
9948
|
+
cleanup.detachCdp = cdp.detach.bind(cdp);
|
|
9949
|
+
protectManagedOwnership(browser, context, page, cdp);
|
|
9950
|
+
const moduleUrl = `${pathToFileURL(realScriptPath).href}?iwsdk_run=${randomUUID()}`;
|
|
9951
|
+
const scriptModule = (await import(moduleUrl));
|
|
9952
|
+
const run = scriptModule.default ?? scriptModule.run;
|
|
9953
|
+
if (typeof run !== 'function') {
|
|
9954
|
+
throw new Error('browser run script must export a default async function or named run function');
|
|
9955
|
+
}
|
|
9956
|
+
const result = await run({
|
|
9957
|
+
browser,
|
|
9958
|
+
cdp,
|
|
9959
|
+
context,
|
|
9960
|
+
frame: frame ?? page.mainFrame(),
|
|
9961
|
+
page,
|
|
9962
|
+
signal: abortController.signal,
|
|
9963
|
+
workspaceRoot,
|
|
9964
|
+
});
|
|
9965
|
+
return createSuccess({
|
|
9966
|
+
operation: 'browser.run',
|
|
9967
|
+
result: serializeRunnerResult(result),
|
|
9968
|
+
script: realRelativeScriptPath.split(path.sep).join('/'),
|
|
9969
|
+
workspaceRoot,
|
|
9970
|
+
});
|
|
9971
|
+
}
|
|
9972
|
+
finally {
|
|
9973
|
+
// A settled script (success or rejection) no longer owns awaited CDP
|
|
9974
|
+
// work and may release normally. A timeout or lost lease leaves this
|
|
9975
|
+
// false until the abandoned operation actually settles, so the server
|
|
9976
|
+
// retires the browser instead of admitting overlapping commands.
|
|
9977
|
+
runnerSettled = true;
|
|
9978
|
+
}
|
|
9979
|
+
})();
|
|
9980
|
+
const execution = withTimeout(runnerOperation, timeoutMs, () => abortController.abort());
|
|
9981
|
+
try {
|
|
9982
|
+
return await (lease ? Promise.race([execution, lease.lost]) : execution);
|
|
9983
|
+
}
|
|
9984
|
+
catch (error) {
|
|
9985
|
+
abortController.abort();
|
|
9986
|
+
if (error instanceof RuntimeCommandExecutionError) {
|
|
9987
|
+
throw error;
|
|
9988
|
+
}
|
|
9989
|
+
throw new RuntimeCommandExecutionError(error instanceof Error ? error.message : String(error), {
|
|
9990
|
+
details: {
|
|
9991
|
+
code: 'browser_run_failed',
|
|
9992
|
+
outcome: 'outcome_unknown',
|
|
9993
|
+
},
|
|
9994
|
+
});
|
|
9995
|
+
}
|
|
9996
|
+
}
|
|
9997
|
+
finally {
|
|
9998
|
+
if (cleanup.detachCdp != null) {
|
|
9999
|
+
try {
|
|
10000
|
+
await cleanup.detachCdp();
|
|
10001
|
+
}
|
|
10002
|
+
catch { }
|
|
10003
|
+
}
|
|
10004
|
+
try {
|
|
10005
|
+
await disconnectBrowser();
|
|
10006
|
+
}
|
|
10007
|
+
catch { }
|
|
10008
|
+
if (runnerSettled) {
|
|
10009
|
+
lease?.release();
|
|
10010
|
+
}
|
|
10011
|
+
else {
|
|
10012
|
+
lease?.abandon();
|
|
10013
|
+
}
|
|
10014
|
+
}
|
|
10015
|
+
}
|
|
10016
|
+
|
|
8593
10017
|
/**
|
|
8594
10018
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
8595
10019
|
*
|
|
@@ -8624,6 +10048,7 @@ async function handleStatus(options, io) {
|
|
|
8624
10048
|
]);
|
|
8625
10049
|
return createSuccess({
|
|
8626
10050
|
workspaceRoot,
|
|
10051
|
+
runtimeUrls: getRuntimeUrls(state.session),
|
|
8627
10052
|
state,
|
|
8628
10053
|
adapters,
|
|
8629
10054
|
});
|
|
@@ -8636,9 +10061,11 @@ async function handleStatus(options, io) {
|
|
|
8636
10061
|
* LICENSE file in the root directory of this source tree.
|
|
8637
10062
|
*/
|
|
8638
10063
|
const DEV_SESSION_ENV_NAMES = {
|
|
10064
|
+
allowBrowserAutomation: 'IWSDK_DEV_ALLOW_BROWSER_AUTOMATION',
|
|
8639
10065
|
aiMode: 'IWSDK_DEV_AI_MODE',
|
|
8640
10066
|
headless: 'IWSDK_DEV_HEADLESS',
|
|
8641
10067
|
open: 'IWSDK_DEV_OPEN',
|
|
10068
|
+
nativeXRControl: 'IWSDK_DEV_NATIVE_XR_CONTROL',
|
|
8642
10069
|
screenshotHeight: 'IWSDK_DEV_SCREENSHOT_HEIGHT',
|
|
8643
10070
|
screenshotWidth: 'IWSDK_DEV_SCREENSHOT_WIDTH',
|
|
8644
10071
|
};
|
|
@@ -8661,6 +10088,14 @@ function describeChildExit(exit) {
|
|
|
8661
10088
|
}
|
|
8662
10089
|
return 'Dev server exited abnormally';
|
|
8663
10090
|
}
|
|
10091
|
+
/** Names the port a fail-closed startup could not bind, from its launch log. */
|
|
10092
|
+
async function describeStartupExit(logPath) {
|
|
10093
|
+
const log = logPath ? await readFile(logPath, 'utf8').catch(() => '') : '';
|
|
10094
|
+
const port = /Port (\d+) is already in use/.exec(log.slice(-16384))?.[1];
|
|
10095
|
+
return port
|
|
10096
|
+
? `Port ${port} is already in use. The runtime keeps its configured port instead of moving; stop the process using it or change server.port.`
|
|
10097
|
+
: 'Dev server exited before registering a runtime session';
|
|
10098
|
+
}
|
|
8664
10099
|
function sleep(ms) {
|
|
8665
10100
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8666
10101
|
}
|
|
@@ -8802,6 +10237,8 @@ function resolveDevSessionOptions(options) {
|
|
|
8802
10237
|
const headedRequested = readBooleanFlag(options.headed, '--headed');
|
|
8803
10238
|
const openRequested = readBooleanFlag(options.open, '--open');
|
|
8804
10239
|
const noOpenRequested = readBooleanFlag(options.noOpen, '--no-open');
|
|
10240
|
+
const allowBrowserAutomation = readBooleanFlag(options.allowBrowserAutomation, '--allow-browser-automation');
|
|
10241
|
+
const nativeXRControl = readBooleanFlag(options.nativeXrControl, '--native-xr-control');
|
|
8805
10242
|
if (headlessRequested && headedRequested) {
|
|
8806
10243
|
throw new Error('--headless and --headed cannot be used together');
|
|
8807
10244
|
}
|
|
@@ -8817,9 +10254,11 @@ function resolveDevSessionOptions(options) {
|
|
|
8817
10254
|
const screenshotWidth = parseOptionalPositiveIntegerOption(options.screenshotWidth, '--screenshot-width');
|
|
8818
10255
|
const screenshotHeight = parseOptionalPositiveIntegerOption(options.screenshotHeight, '--screenshot-height');
|
|
8819
10256
|
return {
|
|
10257
|
+
allowBrowserAutomation,
|
|
8820
10258
|
...(aiMode == null ? {} : { aiMode }),
|
|
8821
10259
|
headless: headlessRequested || aiMode === 'agent',
|
|
8822
10260
|
open: !noOpenRequested,
|
|
10261
|
+
nativeXRControl,
|
|
8823
10262
|
...(screenshotWidth == null ? {} : { screenshotWidth }),
|
|
8824
10263
|
...(screenshotHeight == null ? {} : { screenshotHeight }),
|
|
8825
10264
|
};
|
|
@@ -8833,6 +10272,8 @@ function buildDevRuntimeEnvironment(options, baseEnvironment = process.env) {
|
|
|
8833
10272
|
}
|
|
8834
10273
|
environment[DEV_SESSION_ENV_NAMES.headless] = String(session.headless);
|
|
8835
10274
|
environment[DEV_SESSION_ENV_NAMES.open] = String(session.open);
|
|
10275
|
+
environment[DEV_SESSION_ENV_NAMES.allowBrowserAutomation] = String(session.allowBrowserAutomation);
|
|
10276
|
+
environment[DEV_SESSION_ENV_NAMES.nativeXRControl] = String(session.nativeXRControl);
|
|
8836
10277
|
if (session.aiMode != null) {
|
|
8837
10278
|
environment[DEV_SESSION_ENV_NAMES.aiMode] = session.aiMode;
|
|
8838
10279
|
}
|
|
@@ -8866,14 +10307,28 @@ async function ensureLogPath(workspaceRoot) {
|
|
|
8866
10307
|
const logsDir = await ensureRuntimeLogsDir(workspaceRoot);
|
|
8867
10308
|
return path.join(logsDir, `dev-${Date.now()}.log`);
|
|
8868
10309
|
}
|
|
8869
|
-
async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit) {
|
|
10310
|
+
async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit, attachingToOwner) {
|
|
8870
10311
|
const deadline = Date.now() + timeoutMs;
|
|
8871
10312
|
let lastSession = null;
|
|
8872
10313
|
let lastBrowserIssue;
|
|
8873
10314
|
while (Date.now() < deadline) {
|
|
8874
10315
|
const session = await getRuntimeSession(workspaceRoot);
|
|
10316
|
+
if (!session &&
|
|
10317
|
+
attachingToOwner != null &&
|
|
10318
|
+
(await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot))).state ===
|
|
10319
|
+
'absent') {
|
|
10320
|
+
throw new Error('The runtime stopped while this command was attaching. Retry iwsdk dev up to start a new runtime.');
|
|
10321
|
+
}
|
|
8875
10322
|
if (session) {
|
|
8876
10323
|
lastSession = session;
|
|
10324
|
+
if (session.browser?.lifecycle) {
|
|
10325
|
+
return {
|
|
10326
|
+
session,
|
|
10327
|
+
exit: null,
|
|
10328
|
+
browserReady: isRuntimeBrowserCommandReady(session),
|
|
10329
|
+
browserIssue: session.browser.lastError,
|
|
10330
|
+
};
|
|
10331
|
+
}
|
|
8877
10332
|
if (!session.browser || isRuntimeBrowserCommandReady(session)) {
|
|
8878
10333
|
return { session, exit: null, browserReady: true };
|
|
8879
10334
|
}
|
|
@@ -8953,6 +10408,45 @@ async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit) {
|
|
|
8953
10408
|
: undefined),
|
|
8954
10409
|
};
|
|
8955
10410
|
}
|
|
10411
|
+
async function attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io, attachingToOwner) {
|
|
10412
|
+
const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs, undefined, attachingToOwner);
|
|
10413
|
+
const launch = await getLaunchMetadata(workspaceRoot);
|
|
10414
|
+
if (!waitResult.session) {
|
|
10415
|
+
const owner = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
|
|
10416
|
+
if (owner.state === 'live') {
|
|
10417
|
+
return createFailure(`Runtime ${owner.owner.sessionId} owns the workspace but has not registered a session; it may be starting or finishing cleanup. Retry shortly, or stop it with iwsdk dev down. No second runtime was started.`, 'runtime_owner_unregistered', { workspaceRoot, owner: owner.owner });
|
|
10418
|
+
}
|
|
10419
|
+
return createFailure(launch == null
|
|
10420
|
+
? formatMissingRuntimeMessage(workspaceRoot)
|
|
10421
|
+
: `Dev server did not register a runtime session within ${timeoutMs}ms`, launch == null ? 'dev_up_missing_runtime' : 'dev_up_timeout', { workspaceRoot, launch });
|
|
10422
|
+
}
|
|
10423
|
+
if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
|
|
10424
|
+
await openUrl(waitResult.session.localUrl);
|
|
10425
|
+
}
|
|
10426
|
+
const adapters = await readAdapterStatus(workspaceRoot);
|
|
10427
|
+
if (foreground) {
|
|
10428
|
+
io.stdout.write(`[IWSDK] Runtime already running at ${waitResult.session.localUrl}\n`);
|
|
10429
|
+
io.stdout.write(waitResult.browserReady
|
|
10430
|
+
? '[IWSDK] Managed browser command path is ready.\n'
|
|
10431
|
+
: `[IWSDK] Managed browser command path is not ready${waitResult.browserIssue?.cause ? ` (${waitResult.browserIssue.cause})` : ''}. ${waitResult.session.browser?.lifecycle?.nextAction ?? 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.'}\n`);
|
|
10432
|
+
return null;
|
|
10433
|
+
}
|
|
10434
|
+
return createSuccess({
|
|
10435
|
+
action: 'attached',
|
|
10436
|
+
workspaceRoot,
|
|
10437
|
+
session: waitResult.session,
|
|
10438
|
+
launch,
|
|
10439
|
+
adapters,
|
|
10440
|
+
browserCommandReady: waitResult.browserReady,
|
|
10441
|
+
...(waitResult.browserReady
|
|
10442
|
+
? {}
|
|
10443
|
+
: {
|
|
10444
|
+
browserIssue: waitResult.browserIssue ?? null,
|
|
10445
|
+
browserNextAction: waitResult.session.browser?.lifecycle?.nextAction ??
|
|
10446
|
+
'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.',
|
|
10447
|
+
}),
|
|
10448
|
+
});
|
|
10449
|
+
}
|
|
8956
10450
|
function waitForChildExit(child) {
|
|
8957
10451
|
return new Promise((resolve) => {
|
|
8958
10452
|
child.once('error', () => {
|
|
@@ -8988,46 +10482,154 @@ async function openUrl(url) {
|
|
|
8988
10482
|
child.unref();
|
|
8989
10483
|
});
|
|
8990
10484
|
}
|
|
8991
|
-
async function
|
|
8992
|
-
|
|
8993
|
-
|
|
8994
|
-
|
|
8995
|
-
|
|
8996
|
-
|
|
8997
|
-
|
|
8998
|
-
|
|
8999
|
-
|
|
10485
|
+
async function terminateWindowsProcessTree(pid, force) {
|
|
10486
|
+
await new Promise((resolve) => {
|
|
10487
|
+
const child = spawn('taskkill', ['/pid', String(pid), '/T', ...(force ? ['/F'] : [])], { stdio: 'ignore', windowsHide: true });
|
|
10488
|
+
let settled = false;
|
|
10489
|
+
const finish = () => {
|
|
10490
|
+
if (settled) {
|
|
10491
|
+
return;
|
|
10492
|
+
}
|
|
10493
|
+
settled = true;
|
|
10494
|
+
clearTimeout(timeout);
|
|
10495
|
+
resolve();
|
|
9000
10496
|
};
|
|
10497
|
+
const timeout = setTimeout(() => {
|
|
10498
|
+
child.kill();
|
|
10499
|
+
finish();
|
|
10500
|
+
}, 5_000);
|
|
10501
|
+
child.once('error', finish);
|
|
10502
|
+
child.once('close', finish);
|
|
10503
|
+
});
|
|
10504
|
+
}
|
|
10505
|
+
function isPosixProcessGroupAlive(processGroupId) {
|
|
10506
|
+
try {
|
|
10507
|
+
process.kill(-processGroupId, 0);
|
|
10508
|
+
return true;
|
|
10509
|
+
}
|
|
10510
|
+
catch (error) {
|
|
10511
|
+
return error.code !== 'ESRCH';
|
|
9001
10512
|
}
|
|
9002
|
-
|
|
10513
|
+
}
|
|
10514
|
+
async function waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, timeoutMs) {
|
|
10515
|
+
const deadline = Date.now() + timeoutMs;
|
|
10516
|
+
do {
|
|
10517
|
+
if (process.platform === 'win32'
|
|
10518
|
+
? child.exitCode != null || child.signalCode != null
|
|
10519
|
+
: processGroupId != null
|
|
10520
|
+
? !isPosixProcessGroupAlive(processGroupId)
|
|
10521
|
+
: child.exitCode != null || child.signalCode != null) {
|
|
10522
|
+
return true;
|
|
10523
|
+
}
|
|
10524
|
+
await Promise.race([childExitPromise, sleep(50)]);
|
|
10525
|
+
} while (Date.now() < deadline);
|
|
10526
|
+
return process.platform === 'win32'
|
|
10527
|
+
? child.exitCode != null || child.signalCode != null
|
|
10528
|
+
: processGroupId != null
|
|
10529
|
+
? !isPosixProcessGroupAlive(processGroupId)
|
|
10530
|
+
: child.exitCode != null || child.signalCode != null;
|
|
10531
|
+
}
|
|
10532
|
+
async function terminateSpawnedDevProcess(child, childExitPromise, processGroupId) {
|
|
10533
|
+
if (typeof child.pid !== 'number') {
|
|
10534
|
+
return true;
|
|
10535
|
+
}
|
|
10536
|
+
if (process.platform === 'win32') {
|
|
10537
|
+
await terminateWindowsProcessTree(child.pid, false);
|
|
10538
|
+
}
|
|
10539
|
+
else if (processGroupId != null) {
|
|
9003
10540
|
try {
|
|
9004
|
-
process.kill(
|
|
10541
|
+
process.kill(-processGroupId, 'SIGTERM');
|
|
10542
|
+
}
|
|
10543
|
+
catch (error) {
|
|
10544
|
+
if (error.code === 'ESRCH') {
|
|
10545
|
+
return true;
|
|
10546
|
+
}
|
|
9005
10547
|
}
|
|
9006
|
-
catch { }
|
|
9007
10548
|
}
|
|
9008
|
-
|
|
9009
|
-
|
|
9010
|
-
|
|
9011
|
-
|
|
9012
|
-
|
|
10549
|
+
else {
|
|
10550
|
+
child.kill('SIGTERM');
|
|
10551
|
+
}
|
|
10552
|
+
if (await waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, 2_000)) {
|
|
10553
|
+
return true;
|
|
10554
|
+
}
|
|
10555
|
+
if (process.platform === 'win32') {
|
|
10556
|
+
await terminateWindowsProcessTree(child.pid, true);
|
|
10557
|
+
}
|
|
10558
|
+
else if (processGroupId != null) {
|
|
10559
|
+
try {
|
|
10560
|
+
process.kill(-processGroupId, 'SIGKILL');
|
|
10561
|
+
}
|
|
10562
|
+
catch (error) {
|
|
10563
|
+
if (error.code === 'ESRCH') {
|
|
10564
|
+
return true;
|
|
10565
|
+
}
|
|
10566
|
+
}
|
|
10567
|
+
}
|
|
10568
|
+
else {
|
|
10569
|
+
child.kill('SIGKILL');
|
|
10570
|
+
}
|
|
10571
|
+
return waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, 2_000);
|
|
10572
|
+
}
|
|
10573
|
+
async function requestRuntimeShutdown(session, claimId) {
|
|
10574
|
+
if (session == null || (claimId == null && !session.browser?.lifecycle)) {
|
|
10575
|
+
return false;
|
|
10576
|
+
}
|
|
10577
|
+
try {
|
|
10578
|
+
await sendRuntimeCommand({
|
|
10579
|
+
port: session.port,
|
|
10580
|
+
method: INTERNAL_RUNTIME_SHUTDOWN_METHOD,
|
|
10581
|
+
params: { claimId, sessionId: session.sessionId },
|
|
10582
|
+
timeoutMs: 3_000,
|
|
10583
|
+
runtimeSession: session,
|
|
10584
|
+
});
|
|
10585
|
+
return true;
|
|
10586
|
+
}
|
|
10587
|
+
catch {
|
|
10588
|
+
return false;
|
|
10589
|
+
}
|
|
10590
|
+
}
|
|
10591
|
+
async function terminateRuntimeWorkspace(workspaceRoot) {
|
|
10592
|
+
let state = await getWorkspaceRuntimeState(workspaceRoot);
|
|
10593
|
+
const launchClaimId = state.launch?.claimId;
|
|
10594
|
+
const observation = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
|
|
10595
|
+
if (observation.state === 'unknown') {
|
|
10596
|
+
throw new Error(`Runtime ownership is unknown: ${observation.reason}. Inspect the dev process before retrying; no PID-only termination was attempted.`);
|
|
10597
|
+
}
|
|
10598
|
+
if (observation.state === 'live') {
|
|
10599
|
+
const owner = observation.owner;
|
|
10600
|
+
const session = state.session;
|
|
10601
|
+
if (owner.workspaceRoot !== workspaceRoot ||
|
|
10602
|
+
(session != null &&
|
|
10603
|
+
(owner.sessionId !== session.sessionId || owner.pid !== session.pid))) {
|
|
10604
|
+
throw new Error('The runtime owner changed during shutdown. Retry iwsdk dev down.');
|
|
10605
|
+
}
|
|
10606
|
+
// Startup and incomplete browser cleanup can retain the owner without a
|
|
10607
|
+
// session record. The verified IPC identity still authorizes stopping it.
|
|
10608
|
+
await stopRuntimeOwner(owner, () => requestRuntimeShutdown(session, launchClaimId));
|
|
10609
|
+
if (launchClaimId) {
|
|
10610
|
+
await clearLaunchMetadata(workspaceRoot, launchClaimId);
|
|
10611
|
+
}
|
|
10612
|
+
return { stopped: true, workspaceRoot, sessionId: owner.sessionId };
|
|
10613
|
+
}
|
|
10614
|
+
if (state.session == null &&
|
|
10615
|
+
state.launch?.phase === 'starting' &&
|
|
10616
|
+
launchClaimId != null) {
|
|
10617
|
+
const cancelled = await clearLaunchMetadata(workspaceRoot, launchClaimId, 'starting');
|
|
10618
|
+
if (cancelled) {
|
|
9013
10619
|
return {
|
|
9014
10620
|
stopped: true,
|
|
9015
10621
|
workspaceRoot,
|
|
10622
|
+
cancelledStartup: true,
|
|
9016
10623
|
};
|
|
9017
10624
|
}
|
|
9018
|
-
await
|
|
10625
|
+
state = await getWorkspaceRuntimeState(workspaceRoot);
|
|
9019
10626
|
}
|
|
9020
|
-
|
|
9021
|
-
|
|
9022
|
-
process.kill(pid, 'SIGKILL');
|
|
9023
|
-
}
|
|
9024
|
-
catch { }
|
|
10627
|
+
if (state.session != null || state.launch != null) {
|
|
10628
|
+
throw new Error('A live legacy runtime has no verifiable owner endpoint. Stop that dev process from its original terminal; no PID-only termination was attempted.');
|
|
9025
10629
|
}
|
|
9026
|
-
await clearLaunchMetadata(workspaceRoot);
|
|
9027
10630
|
return {
|
|
9028
|
-
stopped:
|
|
10631
|
+
stopped: false,
|
|
9029
10632
|
workspaceRoot,
|
|
9030
|
-
forced: true,
|
|
9031
10633
|
};
|
|
9032
10634
|
}
|
|
9033
10635
|
async function handleDevUp(options, io) {
|
|
@@ -9040,56 +10642,59 @@ async function handleDevUp(options, io) {
|
|
|
9040
10642
|
const timeoutMs = parseIntegerOption(options.timeout, '--timeout', 60000);
|
|
9041
10643
|
const foreground = isForegroundLaunch(options);
|
|
9042
10644
|
const openBrowser = devSessionOptions.open;
|
|
9043
|
-
const existingSession = await
|
|
9044
|
-
|
|
9045
|
-
|
|
9046
|
-
|
|
9047
|
-
|
|
9048
|
-
|
|
9049
|
-
|
|
9050
|
-
|
|
9051
|
-
|
|
9052
|
-
|
|
9053
|
-
if (!waitResult.browserReady) {
|
|
9054
|
-
return createFailure(waitResult.browserIssue?.message ??
|
|
9055
|
-
`Managed browser did not become ready within ${timeoutMs}ms`, 'dev_browser_not_ready', {
|
|
9056
|
-
workspaceRoot,
|
|
9057
|
-
logPath: launch?.logPath ?? null,
|
|
9058
|
-
scriptName: launch?.scriptName,
|
|
9059
|
-
session: waitResult.session,
|
|
9060
|
-
browser: waitResult.session.browser ?? null,
|
|
9061
|
-
cause: waitResult.browserIssue?.cause,
|
|
9062
|
-
});
|
|
9063
|
-
}
|
|
9064
|
-
if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
|
|
9065
|
-
await openUrl(waitResult.session.localUrl);
|
|
9066
|
-
}
|
|
9067
|
-
const adapters = await readAdapterStatus(workspaceRoot);
|
|
9068
|
-
if (foreground) {
|
|
9069
|
-
io.stdout.write(`[IWSDK] Runtime already running at ${waitResult.session.localUrl}\n`);
|
|
9070
|
-
return null;
|
|
9071
|
-
}
|
|
9072
|
-
return createSuccess({
|
|
9073
|
-
action: 'attached',
|
|
9074
|
-
workspaceRoot,
|
|
9075
|
-
session: waitResult.session,
|
|
9076
|
-
launch,
|
|
9077
|
-
adapters,
|
|
9078
|
-
});
|
|
10645
|
+
const [existingSession, existingLaunch] = await Promise.all([
|
|
10646
|
+
getRuntimeSession(workspaceRoot),
|
|
10647
|
+
getLaunchMetadata(workspaceRoot),
|
|
10648
|
+
]);
|
|
10649
|
+
const observation = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
|
|
10650
|
+
if (observation.state === 'unknown') {
|
|
10651
|
+
throw new Error(`Runtime ownership is unknown: ${observation.reason}. Inspect the dev process before retrying; no second runtime was started.`);
|
|
10652
|
+
}
|
|
10653
|
+
if (existingSession || existingLaunch || observation.state === 'live') {
|
|
10654
|
+
return attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io, observation.state === 'live' ? observation.owner.sessionId : undefined);
|
|
9079
10655
|
}
|
|
9080
10656
|
const packageManager = await detectPackageManager(workspaceRoot);
|
|
9081
10657
|
const scriptName = await resolveDevRuntimeScript(workspaceRoot);
|
|
9082
10658
|
const logPath = foreground ? null : await ensureLogPath(workspaceRoot);
|
|
9083
|
-
const stdoutFd = logPath ? openSync(logPath, 'a') : -1;
|
|
9084
10659
|
const spawnArgs = getRunScriptArgs(packageManager, scriptName);
|
|
9085
|
-
const
|
|
9086
|
-
|
|
9087
|
-
|
|
9088
|
-
|
|
9089
|
-
|
|
9090
|
-
|
|
9091
|
-
|
|
10660
|
+
const claimId = randomUUID();
|
|
10661
|
+
const claim = await claimLaunchMetadata({
|
|
10662
|
+
claimId,
|
|
10663
|
+
workspaceRoot,
|
|
10664
|
+
pid: process.pid,
|
|
10665
|
+
command: packageManager,
|
|
10666
|
+
args: spawnArgs,
|
|
10667
|
+
logPath,
|
|
10668
|
+
scriptName,
|
|
10669
|
+
port: null,
|
|
10670
|
+
openBrowser,
|
|
9092
10671
|
});
|
|
10672
|
+
if (!claim.acquired) {
|
|
10673
|
+
return attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io);
|
|
10674
|
+
}
|
|
10675
|
+
const stdoutFd = logPath ? openSync(logPath, 'a') : -1;
|
|
10676
|
+
const childEnvironment = buildDevRuntimeEnvironment(options);
|
|
10677
|
+
childEnvironment[INTERNAL_RUNTIME_LAUNCH_CLAIM_ENV] = claimId;
|
|
10678
|
+
let child;
|
|
10679
|
+
try {
|
|
10680
|
+
child = spawn(packageManager, spawnArgs, {
|
|
10681
|
+
cwd: workspaceRoot,
|
|
10682
|
+
// A separate POSIX process group lets the CLI forward Ctrl-C to the
|
|
10683
|
+
// package manager and every descendant without signaling itself.
|
|
10684
|
+
detached: process.platform !== 'win32' || !foreground,
|
|
10685
|
+
stdio: foreground ? 'inherit' : ['ignore', stdoutFd, stdoutFd],
|
|
10686
|
+
env: childEnvironment,
|
|
10687
|
+
// npm/pnpm/yarn are .cmd shims on Windows; Node cannot spawn them without a shell.
|
|
10688
|
+
shell: process.platform === 'win32',
|
|
10689
|
+
});
|
|
10690
|
+
}
|
|
10691
|
+
catch (error) {
|
|
10692
|
+
if (stdoutFd >= 0) {
|
|
10693
|
+
closeSync(stdoutFd);
|
|
10694
|
+
}
|
|
10695
|
+
await clearLaunchMetadata(workspaceRoot, claimId);
|
|
10696
|
+
throw error;
|
|
10697
|
+
}
|
|
9093
10698
|
const childExitPromise = waitForChildExit(child);
|
|
9094
10699
|
let childExit = null;
|
|
9095
10700
|
void childExitPromise.then((result) => {
|
|
@@ -9100,85 +10705,184 @@ async function handleDevUp(options, io) {
|
|
|
9100
10705
|
child.unref();
|
|
9101
10706
|
}
|
|
9102
10707
|
if (typeof child.pid !== 'number') {
|
|
10708
|
+
await clearLaunchMetadata(workspaceRoot, claimId);
|
|
9103
10709
|
throw new Error('Failed to start the dev process');
|
|
9104
10710
|
}
|
|
9105
|
-
|
|
10711
|
+
const processGroupId = process.platform !== 'win32' ? child.pid : undefined;
|
|
10712
|
+
const claimedLaunch = await setLaunchMetadata({
|
|
10713
|
+
claimId,
|
|
10714
|
+
phase: 'running',
|
|
9106
10715
|
workspaceRoot,
|
|
9107
10716
|
pid: child.pid,
|
|
10717
|
+
launcherPid: child.pid,
|
|
10718
|
+
processGroupId,
|
|
9108
10719
|
command: packageManager,
|
|
9109
10720
|
args: spawnArgs,
|
|
9110
10721
|
logPath,
|
|
9111
10722
|
scriptName,
|
|
9112
10723
|
port: null,
|
|
9113
10724
|
openBrowser,
|
|
9114
|
-
});
|
|
9115
|
-
|
|
9116
|
-
|
|
9117
|
-
|
|
9118
|
-
|
|
9119
|
-
|
|
10725
|
+
}, claimId);
|
|
10726
|
+
if (claimedLaunch == null) {
|
|
10727
|
+
if (process.platform === 'win32') {
|
|
10728
|
+
await terminateWindowsProcessTree(child.pid, true);
|
|
10729
|
+
}
|
|
10730
|
+
else if (processGroupId != null) {
|
|
10731
|
+
try {
|
|
10732
|
+
process.kill(-processGroupId, 'SIGTERM');
|
|
10733
|
+
}
|
|
10734
|
+
catch { }
|
|
10735
|
+
}
|
|
10736
|
+
else {
|
|
10737
|
+
child.kill('SIGTERM');
|
|
10738
|
+
}
|
|
10739
|
+
throw new Error('Lost ownership of the IWSDK dev startup claim');
|
|
10740
|
+
}
|
|
10741
|
+
let receivedForegroundSignal = null;
|
|
10742
|
+
let foregroundSignalExitCode = null;
|
|
10743
|
+
let foregroundSignalCount = 0;
|
|
10744
|
+
const handleForegroundSignal = (signal) => {
|
|
10745
|
+
foregroundSignalCount += 1;
|
|
10746
|
+
receivedForegroundSignal = signal;
|
|
10747
|
+
foregroundSignalExitCode =
|
|
10748
|
+
signal === 'SIGINT' ? 130 : signal === 'SIGHUP' ? 129 : 143;
|
|
10749
|
+
if (child.exitCode == null && child.signalCode == null) {
|
|
10750
|
+
if (process.platform === 'win32' && child.pid != null) {
|
|
10751
|
+
if (foregroundSignalCount > 1) {
|
|
10752
|
+
void terminateWindowsProcessTree(child.pid, true);
|
|
10753
|
+
}
|
|
10754
|
+
else {
|
|
10755
|
+
void getRuntimeSession(workspaceRoot)
|
|
10756
|
+
.then((session) => requestRuntimeShutdown(session, claimId))
|
|
10757
|
+
.catch(() => { });
|
|
10758
|
+
}
|
|
10759
|
+
}
|
|
10760
|
+
else {
|
|
10761
|
+
try {
|
|
10762
|
+
process.kill(-child.pid, foregroundSignalCount > 1 ? 'SIGKILL' : signal);
|
|
10763
|
+
}
|
|
10764
|
+
catch { }
|
|
10765
|
+
}
|
|
10766
|
+
}
|
|
10767
|
+
};
|
|
10768
|
+
const removeForegroundSignalHandlers = () => {
|
|
10769
|
+
if (!foreground) {
|
|
10770
|
+
return;
|
|
10771
|
+
}
|
|
10772
|
+
process.off('SIGINT', handleForegroundSignal);
|
|
10773
|
+
process.off('SIGHUP', handleForegroundSignal);
|
|
10774
|
+
process.off('SIGTERM', handleForegroundSignal);
|
|
10775
|
+
};
|
|
10776
|
+
if (foreground) {
|
|
10777
|
+
process.on('SIGINT', handleForegroundSignal);
|
|
10778
|
+
process.on('SIGHUP', handleForegroundSignal);
|
|
10779
|
+
process.on('SIGTERM', handleForegroundSignal);
|
|
10780
|
+
}
|
|
10781
|
+
try {
|
|
10782
|
+
const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs, () => childExit);
|
|
10783
|
+
// Ctrl-C can arrive while browser readiness is still being probed. The
|
|
10784
|
+
// resulting transport disconnect is expected shutdown, not startup
|
|
10785
|
+
// failure, so let the finally block finish bounded process cleanup.
|
|
10786
|
+
if (foreground && receivedForegroundSignal != null) {
|
|
10787
|
+
return foregroundSignalExitCode ?? 1;
|
|
10788
|
+
}
|
|
10789
|
+
if (!waitResult.session) {
|
|
10790
|
+
if (waitResult.exit) {
|
|
10791
|
+
await clearLaunchMetadata(workspaceRoot, claimId);
|
|
10792
|
+
return createFailure(await describeStartupExit(logPath), 'dev_up_exit', {
|
|
10793
|
+
workspaceRoot,
|
|
10794
|
+
logPath,
|
|
10795
|
+
exitCode: waitResult.exit.exitCode,
|
|
10796
|
+
signal: waitResult.exit.signal,
|
|
10797
|
+
scriptName,
|
|
10798
|
+
});
|
|
10799
|
+
}
|
|
10800
|
+
const cleanupConfirmed = await terminateSpawnedDevProcess(child, childExitPromise, processGroupId);
|
|
10801
|
+
if (cleanupConfirmed) {
|
|
10802
|
+
await clearLaunchMetadata(workspaceRoot, claimId);
|
|
10803
|
+
}
|
|
10804
|
+
return createFailure(cleanupConfirmed
|
|
10805
|
+
? `Dev server did not register a runtime session within ${timeoutMs}ms and the timed-out process was stopped`
|
|
10806
|
+
: `Dev server did not register a runtime session within ${timeoutMs}ms, and process cleanup could not be confirmed. Run "iwsdk dev down" before retrying.`, 'dev_up_timeout', {
|
|
9120
10807
|
workspaceRoot,
|
|
9121
10808
|
logPath,
|
|
9122
|
-
exitCode: waitResult.exit.exitCode,
|
|
9123
|
-
signal: waitResult.exit.signal,
|
|
9124
10809
|
scriptName,
|
|
10810
|
+
launcherPid: child.pid,
|
|
10811
|
+
processGroupId,
|
|
10812
|
+
cleanupConfirmed,
|
|
9125
10813
|
});
|
|
9126
10814
|
}
|
|
9127
|
-
|
|
10815
|
+
await setLaunchMetadata({
|
|
10816
|
+
claimId,
|
|
9128
10817
|
workspaceRoot,
|
|
10818
|
+
pid: waitResult.session.pid,
|
|
10819
|
+
launcherPid: child.pid,
|
|
10820
|
+
processGroupId,
|
|
10821
|
+
command: packageManager,
|
|
10822
|
+
args: spawnArgs,
|
|
9129
10823
|
logPath,
|
|
9130
10824
|
scriptName,
|
|
9131
|
-
|
|
9132
|
-
|
|
9133
|
-
|
|
9134
|
-
workspaceRoot
|
|
9135
|
-
|
|
9136
|
-
|
|
9137
|
-
|
|
9138
|
-
|
|
9139
|
-
|
|
9140
|
-
|
|
9141
|
-
|
|
9142
|
-
|
|
9143
|
-
|
|
9144
|
-
|
|
9145
|
-
|
|
10825
|
+
port: waitResult.session.port,
|
|
10826
|
+
openBrowser,
|
|
10827
|
+
}, claimId);
|
|
10828
|
+
const launch = await getLaunchMetadata(workspaceRoot);
|
|
10829
|
+
const adapters = await readAdapterStatus(workspaceRoot);
|
|
10830
|
+
if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
|
|
10831
|
+
await openUrl(waitResult.session.localUrl);
|
|
10832
|
+
}
|
|
10833
|
+
if (foreground) {
|
|
10834
|
+
io.stdout.write(`[IWSDK] Runtime ready at ${waitResult.session.localUrl}\n`);
|
|
10835
|
+
io.stdout.write(waitResult.browserReady
|
|
10836
|
+
? '[IWSDK] Managed browser command path is ready.\n'
|
|
10837
|
+
: `[IWSDK] Managed browser command path is not ready${waitResult.browserIssue?.cause ? ` (${waitResult.browserIssue.cause})` : ''}. ${waitResult.session.browser?.lifecycle?.nextAction ?? 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.'}\n`);
|
|
10838
|
+
const exit = await childExitPromise;
|
|
10839
|
+
if (receivedForegroundSignal != null) {
|
|
10840
|
+
await clearLaunchMetadata(workspaceRoot, claimId).catch(() => { });
|
|
10841
|
+
return foregroundSignalExitCode ?? 1;
|
|
10842
|
+
}
|
|
10843
|
+
await clearLaunchMetadata(workspaceRoot, claimId);
|
|
10844
|
+
if (isAbnormalChildExit(exit) &&
|
|
10845
|
+
!(await wasWorkspaceStoppedExternally(workspaceRoot))) {
|
|
10846
|
+
return createFailure(describeChildExit(exit), 'dev_up_exit', {
|
|
10847
|
+
workspaceRoot,
|
|
10848
|
+
session: waitResult.session,
|
|
10849
|
+
exitCode: exit.exitCode,
|
|
10850
|
+
signal: exit.signal,
|
|
10851
|
+
scriptName,
|
|
10852
|
+
});
|
|
10853
|
+
}
|
|
10854
|
+
return null;
|
|
10855
|
+
}
|
|
10856
|
+
return createSuccess({
|
|
10857
|
+
action: 'started',
|
|
9146
10858
|
workspaceRoot,
|
|
9147
|
-
logPath,
|
|
9148
|
-
scriptName,
|
|
9149
10859
|
session: waitResult.session,
|
|
9150
|
-
|
|
9151
|
-
|
|
10860
|
+
launch,
|
|
10861
|
+
logPath,
|
|
10862
|
+
adapters,
|
|
10863
|
+
browserCommandReady: waitResult.browserReady,
|
|
10864
|
+
...(waitResult.browserReady
|
|
10865
|
+
? {}
|
|
10866
|
+
: {
|
|
10867
|
+
browserIssue: waitResult.browserIssue ?? null,
|
|
10868
|
+
browserNextAction: waitResult.session.browser?.lifecycle?.nextAction ??
|
|
10869
|
+
'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.',
|
|
10870
|
+
}),
|
|
9152
10871
|
});
|
|
9153
10872
|
}
|
|
9154
|
-
|
|
9155
|
-
|
|
9156
|
-
|
|
9157
|
-
|
|
9158
|
-
|
|
9159
|
-
|
|
9160
|
-
|
|
9161
|
-
|
|
9162
|
-
|
|
9163
|
-
|
|
9164
|
-
|
|
9165
|
-
workspaceRoot,
|
|
9166
|
-
session: waitResult.session,
|
|
9167
|
-
exitCode: exit.exitCode,
|
|
9168
|
-
signal: exit.signal,
|
|
9169
|
-
scriptName,
|
|
9170
|
-
});
|
|
10873
|
+
finally {
|
|
10874
|
+
removeForegroundSignalHandlers();
|
|
10875
|
+
if (foreground && child.exitCode == null && child.signalCode == null) {
|
|
10876
|
+
if (process.platform === 'win32' && child.pid != null) {
|
|
10877
|
+
const session = await getRuntimeSession(workspaceRoot).catch(() => null);
|
|
10878
|
+
await requestRuntimeShutdown(session, claimId);
|
|
10879
|
+
}
|
|
10880
|
+
await terminateSpawnedDevProcess(child, childExitPromise, processGroupId);
|
|
10881
|
+
}
|
|
10882
|
+
if (foreground && (child.exitCode != null || child.signalCode != null)) {
|
|
10883
|
+
await clearLaunchMetadata(workspaceRoot, claimId).catch(() => { });
|
|
9171
10884
|
}
|
|
9172
|
-
return null;
|
|
9173
10885
|
}
|
|
9174
|
-
return createSuccess({
|
|
9175
|
-
action: 'started',
|
|
9176
|
-
workspaceRoot,
|
|
9177
|
-
session: waitResult.session,
|
|
9178
|
-
launch,
|
|
9179
|
-
logPath,
|
|
9180
|
-
adapters,
|
|
9181
|
-
});
|
|
9182
10886
|
}
|
|
9183
10887
|
async function handleDevDown(options, io) {
|
|
9184
10888
|
const workspaceRoot = await resolveWorkspaceRoot({
|
|
@@ -20926,6 +22630,9 @@ const isUUID$1 = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[
|
|
|
20926
22630
|
/** @type {(value: string) => boolean} */
|
|
20927
22631
|
const isIPv4$1 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
|
|
20928
22632
|
|
|
22633
|
+
/** @type {(value: string) => boolean} */
|
|
22634
|
+
const isPort = RegExp.prototype.test.bind(/^\d*$/u);
|
|
22635
|
+
|
|
20929
22636
|
/** @type {(value: string) => boolean} */
|
|
20930
22637
|
const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
|
|
20931
22638
|
|
|
@@ -20933,45 +22640,45 @@ const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
|
|
|
20933
22640
|
const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
|
|
20934
22641
|
|
|
20935
22642
|
/** @type {(value: string) => boolean} */
|
|
20936
|
-
const isPathCharacter = RegExp.prototype.test.bind(/^[
|
|
22643
|
+
const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
|
|
20937
22644
|
|
|
20938
|
-
/**
|
|
20939
|
-
|
|
20940
|
-
* @returns {string}
|
|
20941
|
-
*/
|
|
20942
|
-
function stringArrayToHexStripped (input) {
|
|
20943
|
-
let acc = '';
|
|
20944
|
-
let code = 0;
|
|
20945
|
-
let i = 0;
|
|
22645
|
+
/** @type {(value: string) => boolean} */
|
|
22646
|
+
const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
|
|
20946
22647
|
|
|
20947
|
-
|
|
20948
|
-
|
|
20949
|
-
if (code === 48) {
|
|
20950
|
-
continue
|
|
20951
|
-
}
|
|
20952
|
-
if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
|
|
20953
|
-
return ''
|
|
20954
|
-
}
|
|
20955
|
-
acc += input[i];
|
|
20956
|
-
break
|
|
20957
|
-
}
|
|
22648
|
+
/** @type {(value: string) => boolean} */
|
|
22649
|
+
const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
|
|
20958
22650
|
|
|
20959
|
-
|
|
20960
|
-
|
|
20961
|
-
|
|
20962
|
-
|
|
20963
|
-
|
|
20964
|
-
acc += input[i];
|
|
22651
|
+
const BYTE_HEX = new Array(256);
|
|
22652
|
+
{
|
|
22653
|
+
const HEX_DIGITS = '0123456789ABCDEF';
|
|
22654
|
+
for (let i = 0; i < 256; i++) {
|
|
22655
|
+
BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF];
|
|
20965
22656
|
}
|
|
20966
|
-
|
|
22657
|
+
}
|
|
22658
|
+
function percentEncodeNonAscii (cp) {
|
|
22659
|
+
if (cp < 0x800) {
|
|
22660
|
+
return BYTE_HEX[0xC0 | (cp >> 6)] +
|
|
22661
|
+
BYTE_HEX[0x80 | (cp & 0x3F)]
|
|
22662
|
+
}
|
|
22663
|
+
if (cp < 0x10000) {
|
|
22664
|
+
return BYTE_HEX[0xE0 | (cp >> 12)] +
|
|
22665
|
+
BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
|
|
22666
|
+
BYTE_HEX[0x80 | (cp & 0x3F)]
|
|
22667
|
+
}
|
|
22668
|
+
return BYTE_HEX[0xF0 | (cp >> 18)] +
|
|
22669
|
+
BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +
|
|
22670
|
+
BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
|
|
22671
|
+
BYTE_HEX[0x80 | (cp & 0x3F)]
|
|
20967
22672
|
}
|
|
20968
22673
|
|
|
20969
|
-
/**
|
|
20970
|
-
|
|
20971
|
-
|
|
20972
|
-
|
|
20973
|
-
|
|
20974
|
-
|
|
22674
|
+
/** @type {(value: string) => boolean} */
|
|
22675
|
+
const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
|
|
22676
|
+
|
|
22677
|
+
/** @type {(value: string) => boolean} */
|
|
22678
|
+
const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
|
|
22679
|
+
|
|
22680
|
+
/** @type {(value: string) => boolean} */
|
|
22681
|
+
const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
|
|
20975
22682
|
|
|
20976
22683
|
/**
|
|
20977
22684
|
* @param {string} value
|
|
@@ -20980,88 +22687,104 @@ function stringArrayToHexStripped (input) {
|
|
|
20980
22687
|
const nonSimpleDomain$1 = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
|
|
20981
22688
|
|
|
20982
22689
|
/**
|
|
20983
|
-
* @param {
|
|
22690
|
+
* @param {string} zone
|
|
20984
22691
|
* @returns {boolean}
|
|
20985
22692
|
*/
|
|
20986
|
-
function
|
|
20987
|
-
|
|
22693
|
+
function isZoneIdentifier (zone) {
|
|
22694
|
+
if (zone.length === 0) return false
|
|
22695
|
+
|
|
22696
|
+
for (let i = 0; i < zone.length; i++) {
|
|
22697
|
+
if (isZoneCharacter(zone[i])) continue
|
|
22698
|
+
if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
|
|
22699
|
+
i += 2;
|
|
22700
|
+
continue
|
|
22701
|
+
}
|
|
22702
|
+
return false
|
|
22703
|
+
}
|
|
22704
|
+
|
|
20988
22705
|
return true
|
|
20989
22706
|
}
|
|
20990
22707
|
|
|
20991
22708
|
/**
|
|
20992
|
-
*
|
|
20993
|
-
*
|
|
20994
|
-
*
|
|
20995
|
-
* @
|
|
22709
|
+
* Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a
|
|
22710
|
+
* single zero hextet is left uncompressed. On ties the leftmost run wins.
|
|
22711
|
+
*
|
|
22712
|
+
* @param {string[]} hextets
|
|
22713
|
+
* @returns {string}
|
|
20996
22714
|
*/
|
|
20997
|
-
function
|
|
20998
|
-
|
|
20999
|
-
|
|
21000
|
-
|
|
21001
|
-
|
|
22715
|
+
function compressIPv6ZeroRun (hextets) {
|
|
22716
|
+
let bestStart = -1;
|
|
22717
|
+
let bestLength = 0;
|
|
22718
|
+
let runStart = -1;
|
|
22719
|
+
let runLength = 0;
|
|
22720
|
+
for (let i = 0; i < hextets.length; i++) {
|
|
22721
|
+
if (hextets[i] === '0') {
|
|
22722
|
+
if (runStart === -1) runStart = i;
|
|
22723
|
+
runLength++;
|
|
22724
|
+
if (runLength > bestLength) {
|
|
22725
|
+
bestLength = runLength;
|
|
22726
|
+
bestStart = runStart;
|
|
22727
|
+
}
|
|
21002
22728
|
} else {
|
|
21003
|
-
|
|
21004
|
-
|
|
22729
|
+
runStart = -1;
|
|
22730
|
+
runLength = 0;
|
|
21005
22731
|
}
|
|
21006
|
-
buffer.length = 0;
|
|
21007
22732
|
}
|
|
21008
|
-
|
|
22733
|
+
|
|
22734
|
+
if (bestLength < 2) return hextets.join(':')
|
|
22735
|
+
|
|
22736
|
+
const head = hextets.slice(0, bestStart).join(':');
|
|
22737
|
+
const tail = hextets.slice(bestStart + bestLength).join(':');
|
|
22738
|
+
return head + '::' + tail
|
|
21009
22739
|
}
|
|
21010
22740
|
|
|
21011
22741
|
/**
|
|
22742
|
+
* Validates an IPv6 address against the alternatives in RFC 3986 section
|
|
22743
|
+
* 3.2.2 and returns the same address with leading hextet zeroes removed.
|
|
22744
|
+
* An embedded IPv4 address counts as two hextets and is only valid at the end.
|
|
22745
|
+
*
|
|
21012
22746
|
* @param {string} input
|
|
21013
|
-
* @returns {
|
|
22747
|
+
* @returns {string|undefined}
|
|
21014
22748
|
*/
|
|
21015
|
-
function
|
|
21016
|
-
|
|
21017
|
-
|
|
21018
|
-
/** @type {Array<string>} */
|
|
21019
|
-
const address = [];
|
|
21020
|
-
/** @type {Array<string>} */
|
|
21021
|
-
const buffer = [];
|
|
21022
|
-
let endipv6Encountered = false;
|
|
21023
|
-
let endIpv6 = false;
|
|
22749
|
+
function normalizeIPv6Address (input) {
|
|
22750
|
+
const compression = input.indexOf('::');
|
|
22751
|
+
if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined
|
|
21024
22752
|
|
|
21025
|
-
|
|
22753
|
+
const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':');
|
|
22754
|
+
const right = compression === -1 ? [] : input.slice(compression + 2).split(':');
|
|
22755
|
+
if (compression !== -1) {
|
|
22756
|
+
if (left.length === 1 && left[0] === '') left.length = 0;
|
|
22757
|
+
if (right.length === 1 && right[0] === '') right.length = 0;
|
|
22758
|
+
}
|
|
21026
22759
|
|
|
21027
|
-
|
|
21028
|
-
|
|
21029
|
-
|
|
21030
|
-
|
|
21031
|
-
|
|
21032
|
-
|
|
21033
|
-
|
|
21034
|
-
if (
|
|
21035
|
-
|
|
21036
|
-
// not valid
|
|
21037
|
-
output.error = true;
|
|
21038
|
-
break
|
|
21039
|
-
}
|
|
21040
|
-
if (i > 0 && input[i - 1] === ':') {
|
|
21041
|
-
endipv6Encountered = true;
|
|
21042
|
-
}
|
|
21043
|
-
address.push(':');
|
|
21044
|
-
continue
|
|
21045
|
-
} else if (cursor === '%') {
|
|
21046
|
-
if (!consume(buffer, address, output)) { break }
|
|
21047
|
-
// switch to zone detection
|
|
21048
|
-
consume = consumeIsZone;
|
|
21049
|
-
} else {
|
|
21050
|
-
buffer.push(cursor);
|
|
22760
|
+
const parts = left.concat(right);
|
|
22761
|
+
let hextetCount = 0;
|
|
22762
|
+
for (let i = 0; i < parts.length; i++) {
|
|
22763
|
+
const part = parts[i];
|
|
22764
|
+
if (part === '') return undefined
|
|
22765
|
+
|
|
22766
|
+
if (part.indexOf('.') !== -1) {
|
|
22767
|
+
if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4$1(part)) return undefined
|
|
22768
|
+
hextetCount += 2;
|
|
21051
22769
|
continue
|
|
21052
22770
|
}
|
|
22771
|
+
|
|
22772
|
+
if (!isHextet(part)) return undefined
|
|
22773
|
+
parts[i] = parseInt(part, 16).toString(16);
|
|
22774
|
+
hextetCount++;
|
|
21053
22775
|
}
|
|
21054
|
-
|
|
21055
|
-
|
|
21056
|
-
|
|
21057
|
-
|
|
21058
|
-
address.push(buffer.join(''));
|
|
21059
|
-
} else {
|
|
21060
|
-
address.push(stringArrayToHexStripped(buffer));
|
|
21061
|
-
}
|
|
22776
|
+
|
|
22777
|
+
if (compression === -1) {
|
|
22778
|
+
if (hextetCount !== 8) return undefined
|
|
22779
|
+
return compressIPv6ZeroRun(parts)
|
|
21062
22780
|
}
|
|
21063
|
-
|
|
21064
|
-
|
|
22781
|
+
if (hextetCount >= 8) return undefined
|
|
22782
|
+
|
|
22783
|
+
// expand "::" then re-compress the longest run for a canonical result
|
|
22784
|
+
const expanded = parts.slice(0, left.length);
|
|
22785
|
+
for (let i = hextetCount; i < 8; i++) expanded.push('0');
|
|
22786
|
+
for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
|
|
22787
|
+
return compressIPv6ZeroRun(expanded)
|
|
21065
22788
|
}
|
|
21066
22789
|
|
|
21067
22790
|
/**
|
|
@@ -21069,26 +22792,49 @@ function getIPV6 (input) {
|
|
|
21069
22792
|
* @property {string} host - The normalized host.
|
|
21070
22793
|
* @property {string} [escapedHost] - The escaped host.
|
|
21071
22794
|
* @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
|
|
22795
|
+
* @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.
|
|
22796
|
+
* @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.
|
|
21072
22797
|
*/
|
|
21073
22798
|
|
|
21074
22799
|
/**
|
|
22800
|
+
* Validates and normalizes a bracketed IP literal. Raw zone separators remain
|
|
22801
|
+
* accepted for backwards compatibility, while encoded separators and zone
|
|
22802
|
+
* contents follow RFC 6874.
|
|
22803
|
+
*
|
|
21075
22804
|
* @param {string} host
|
|
21076
22805
|
* @returns {NormalizeIPv6Result}
|
|
21077
22806
|
*/
|
|
21078
22807
|
function normalizeIPv6$1 (host) {
|
|
21079
|
-
|
|
21080
|
-
const
|
|
22808
|
+
const bracketed = host[0] === '[' && host[host.length - 1] === ']';
|
|
22809
|
+
const hasBracket = host[0] === '[' || host[host.length - 1] === ']';
|
|
22810
|
+
if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }
|
|
22811
|
+
|
|
22812
|
+
let input = bracketed ? host.slice(1, -1) : host;
|
|
22813
|
+
if (bracketed && isIPvFuture(input)) {
|
|
22814
|
+
input = input.toLowerCase();
|
|
22815
|
+
return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }
|
|
22816
|
+
}
|
|
22817
|
+
|
|
22818
|
+
if (findToken(input, ':') < 2) {
|
|
22819
|
+
return { host, isIPV6: false, error: bracketed }
|
|
22820
|
+
}
|
|
21081
22821
|
|
|
21082
|
-
|
|
21083
|
-
|
|
21084
|
-
|
|
21085
|
-
|
|
21086
|
-
|
|
21087
|
-
|
|
21088
|
-
|
|
21089
|
-
|
|
21090
|
-
|
|
21091
|
-
|
|
22822
|
+
let zoneIdentifier = '';
|
|
22823
|
+
const zoneSeparator = input.indexOf('%');
|
|
22824
|
+
if (zoneSeparator !== -1) {
|
|
22825
|
+
const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1;
|
|
22826
|
+
zoneIdentifier = input.slice(zoneSeparator + separatorLength);
|
|
22827
|
+
if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }
|
|
22828
|
+
input = input.slice(0, zoneSeparator);
|
|
22829
|
+
}
|
|
22830
|
+
|
|
22831
|
+
const address = normalizeIPv6Address(input);
|
|
22832
|
+
if (address === undefined) return { host, isIPV6: false, error: true }
|
|
22833
|
+
|
|
22834
|
+
return {
|
|
22835
|
+
host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),
|
|
22836
|
+
escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),
|
|
22837
|
+
isIPV6: true
|
|
21092
22838
|
}
|
|
21093
22839
|
}
|
|
21094
22840
|
|
|
@@ -21214,7 +22960,7 @@ function reescapeHostDelimiters$1 (host, isIP) {
|
|
|
21214
22960
|
|
|
21215
22961
|
/**
|
|
21216
22962
|
* Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.
|
|
21217
|
-
* Reserved delimiters such as `%2F`
|
|
22963
|
+
* Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.
|
|
21218
22964
|
*
|
|
21219
22965
|
* @param {string} input
|
|
21220
22966
|
* @param {boolean} [decodeUnreserved=false]
|
|
@@ -21263,7 +23009,8 @@ function normalizePathEncoding$1 (input) {
|
|
|
21263
23009
|
let output = '';
|
|
21264
23010
|
|
|
21265
23011
|
for (let i = 0; i < input.length; i++) {
|
|
21266
|
-
|
|
23012
|
+
const ch = input[i];
|
|
23013
|
+
if (ch === '%' && i + 2 < input.length) {
|
|
21267
23014
|
const hex = input.slice(i + 1, i + 3);
|
|
21268
23015
|
if (isHexPair(hex)) {
|
|
21269
23016
|
const normalizedHex = hex.toUpperCase();
|
|
@@ -21280,10 +23027,25 @@ function normalizePathEncoding$1 (input) {
|
|
|
21280
23027
|
}
|
|
21281
23028
|
}
|
|
21282
23029
|
|
|
21283
|
-
if (isPathCharacter(
|
|
21284
|
-
output +=
|
|
23030
|
+
if (isPathCharacter(ch)) {
|
|
23031
|
+
output += ch;
|
|
21285
23032
|
} else {
|
|
21286
|
-
|
|
23033
|
+
const code = input.charCodeAt(i);
|
|
23034
|
+
if (code < 0x80) {
|
|
23035
|
+
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
|
|
23036
|
+
} else if (code < 0xD800 || code > 0xDFFF) {
|
|
23037
|
+
output += percentEncodeNonAscii(code);
|
|
23038
|
+
} else if (code <= 0xDBFF && i + 1 < input.length) {
|
|
23039
|
+
const low = input.charCodeAt(i + 1);
|
|
23040
|
+
if (low >= 0xDC00 && low <= 0xDFFF) {
|
|
23041
|
+
output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
|
|
23042
|
+
i++;
|
|
23043
|
+
} else {
|
|
23044
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23045
|
+
}
|
|
23046
|
+
} else {
|
|
23047
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23048
|
+
}
|
|
21287
23049
|
}
|
|
21288
23050
|
}
|
|
21289
23051
|
|
|
@@ -21291,16 +23053,73 @@ function normalizePathEncoding$1 (input) {
|
|
|
21291
23053
|
}
|
|
21292
23054
|
|
|
21293
23055
|
/**
|
|
21294
|
-
*
|
|
23056
|
+
* Serializes a path without rewriting reserved data. Raw RFC 3986 path
|
|
23057
|
+
* characters remain literal, valid escapes are preserved and uppercased, and
|
|
23058
|
+
* everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the
|
|
23059
|
+
* first segment must be escaped so the result cannot be parsed as a scheme.
|
|
21295
23060
|
*
|
|
21296
23061
|
* @param {string} input
|
|
23062
|
+
* @param {boolean} [pathNoScheme=false]
|
|
21297
23063
|
* @returns {string}
|
|
21298
23064
|
*/
|
|
21299
|
-
function
|
|
23065
|
+
function serializePathEncoding$1 (input, pathNoScheme = false) {
|
|
21300
23066
|
let output = '';
|
|
23067
|
+
let firstSegment = pathNoScheme && input[0] !== '/';
|
|
21301
23068
|
|
|
21302
23069
|
for (let i = 0; i < input.length; i++) {
|
|
21303
|
-
|
|
23070
|
+
const ch = input[i];
|
|
23071
|
+
if (ch === '%' && i + 2 < input.length) {
|
|
23072
|
+
const hex = input.slice(i + 1, i + 3);
|
|
23073
|
+
if (isHexPair(hex)) {
|
|
23074
|
+
output += '%' + hex.toUpperCase();
|
|
23075
|
+
i += 2;
|
|
23076
|
+
continue
|
|
23077
|
+
}
|
|
23078
|
+
}
|
|
23079
|
+
|
|
23080
|
+
if (ch === '/') {
|
|
23081
|
+
firstSegment = false;
|
|
23082
|
+
}
|
|
23083
|
+
|
|
23084
|
+
if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {
|
|
23085
|
+
output += ch;
|
|
23086
|
+
} else {
|
|
23087
|
+
const code = input.charCodeAt(i);
|
|
23088
|
+
if (code < 0x80) {
|
|
23089
|
+
output += BYTE_HEX[code];
|
|
23090
|
+
} else if (code < 0xD800 || code > 0xDFFF) {
|
|
23091
|
+
output += percentEncodeNonAscii(code);
|
|
23092
|
+
} else if (code <= 0xDBFF && i + 1 < input.length) {
|
|
23093
|
+
const low = input.charCodeAt(i + 1);
|
|
23094
|
+
if (low >= 0xDC00 && low <= 0xDFFF) {
|
|
23095
|
+
output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
|
|
23096
|
+
i++;
|
|
23097
|
+
} else {
|
|
23098
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23099
|
+
}
|
|
23100
|
+
} else {
|
|
23101
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23102
|
+
}
|
|
23103
|
+
}
|
|
23104
|
+
}
|
|
23105
|
+
|
|
23106
|
+
return output
|
|
23107
|
+
}
|
|
23108
|
+
|
|
23109
|
+
/**
|
|
23110
|
+
* Percent-encodes a URI component using its RFC 3986 literal character set.
|
|
23111
|
+
* Existing valid escapes are preserved and normalized to uppercase hex.
|
|
23112
|
+
*
|
|
23113
|
+
* @param {string} input
|
|
23114
|
+
* @param {(value: string) => boolean} isAllowed
|
|
23115
|
+
* @returns {string}
|
|
23116
|
+
*/
|
|
23117
|
+
function encodeComponent (input, isAllowed) {
|
|
23118
|
+
let output = '';
|
|
23119
|
+
|
|
23120
|
+
for (let i = 0; i < input.length; i++) {
|
|
23121
|
+
const ch = input[i];
|
|
23122
|
+
if (ch === '%' && i + 2 < input.length) {
|
|
21304
23123
|
const hex = input.slice(i + 1, i + 3);
|
|
21305
23124
|
if (isHexPair(hex)) {
|
|
21306
23125
|
output += '%' + hex.toUpperCase();
|
|
@@ -21309,7 +23128,125 @@ function escapePreservingEscapes$1 (input) {
|
|
|
21309
23128
|
}
|
|
21310
23129
|
}
|
|
21311
23130
|
|
|
21312
|
-
|
|
23131
|
+
if (isAllowed(ch)) {
|
|
23132
|
+
output += ch;
|
|
23133
|
+
} else {
|
|
23134
|
+
const code = input.charCodeAt(i);
|
|
23135
|
+
if (code < 0x80) {
|
|
23136
|
+
output += BYTE_HEX[code];
|
|
23137
|
+
} else if (code < 0xD800 || code > 0xDFFF) {
|
|
23138
|
+
output += percentEncodeNonAscii(code);
|
|
23139
|
+
} else if (code <= 0xDBFF && i + 1 < input.length) {
|
|
23140
|
+
const low = input.charCodeAt(i + 1);
|
|
23141
|
+
if (low >= 0xDC00 && low <= 0xDFFF) {
|
|
23142
|
+
output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
|
|
23143
|
+
i++;
|
|
23144
|
+
} else {
|
|
23145
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23146
|
+
}
|
|
23147
|
+
} else {
|
|
23148
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23149
|
+
}
|
|
23150
|
+
}
|
|
23151
|
+
}
|
|
23152
|
+
|
|
23153
|
+
return output
|
|
23154
|
+
}
|
|
23155
|
+
|
|
23156
|
+
/**
|
|
23157
|
+
* Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.
|
|
23158
|
+
* In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.
|
|
23159
|
+
*
|
|
23160
|
+
* @param {string} input
|
|
23161
|
+
* @returns {string}
|
|
23162
|
+
*/
|
|
23163
|
+
function encodeUserinfo (input) {
|
|
23164
|
+
return encodeComponent(input, isUserinfoCharacter)
|
|
23165
|
+
}
|
|
23166
|
+
|
|
23167
|
+
/**
|
|
23168
|
+
* Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be
|
|
23169
|
+
* escaped because it would otherwise begin the fragment component.
|
|
23170
|
+
*
|
|
23171
|
+
* @param {string} input
|
|
23172
|
+
* @returns {string}
|
|
23173
|
+
*/
|
|
23174
|
+
function encodeQuery$1 (input) {
|
|
23175
|
+
return encodeComponent(input, isQueryFragmentCharacter)
|
|
23176
|
+
}
|
|
23177
|
+
|
|
23178
|
+
/**
|
|
23179
|
+
* Encodes fragment data using the RFC 3986 §3.5 grammar.
|
|
23180
|
+
*
|
|
23181
|
+
* @param {string} input
|
|
23182
|
+
* @returns {string}
|
|
23183
|
+
*/
|
|
23184
|
+
function encodeFragment$1 (input) {
|
|
23185
|
+
return encodeComponent(input, isQueryFragmentCharacter)
|
|
23186
|
+
}
|
|
23187
|
+
|
|
23188
|
+
function isEscapeSafe (cp) {
|
|
23189
|
+
return (
|
|
23190
|
+
(cp >= 0x30 && cp <= 0x39) ||
|
|
23191
|
+
(cp >= 0x41 && cp <= 0x5A) ||
|
|
23192
|
+
(cp >= 0x61 && cp <= 0x7A) ||
|
|
23193
|
+
cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||
|
|
23194
|
+
cp === 0x2F || cp === 0x40 || cp === 0x5F
|
|
23195
|
+
)
|
|
23196
|
+
}
|
|
23197
|
+
|
|
23198
|
+
/**
|
|
23199
|
+
* Normalizes the percent-encoding of a query or fragment component.
|
|
23200
|
+
*
|
|
23201
|
+
* Like `normalizePathEncoding`, but uses the query/fragment character set
|
|
23202
|
+
* (which additionally allows `?`) and decodes `.` since it has no dot-segment
|
|
23203
|
+
* meaning outside of a path.
|
|
23204
|
+
*
|
|
23205
|
+
* @param {string} input
|
|
23206
|
+
* @returns {string}
|
|
23207
|
+
*/
|
|
23208
|
+
function normalizeQueryFragmentEncoding$1 (input) {
|
|
23209
|
+
let output = '';
|
|
23210
|
+
|
|
23211
|
+
for (let i = 0; i < input.length; i++) {
|
|
23212
|
+
const ch = input[i];
|
|
23213
|
+
if (ch === '%' && i + 2 < input.length) {
|
|
23214
|
+
const hex = input.slice(i + 1, i + 3);
|
|
23215
|
+
if (isHexPair(hex)) {
|
|
23216
|
+
const normalizedHex = hex.toUpperCase();
|
|
23217
|
+
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
23218
|
+
|
|
23219
|
+
if (isUnreserved(decoded)) {
|
|
23220
|
+
output += decoded;
|
|
23221
|
+
} else {
|
|
23222
|
+
output += '%' + normalizedHex;
|
|
23223
|
+
}
|
|
23224
|
+
|
|
23225
|
+
i += 2;
|
|
23226
|
+
continue
|
|
23227
|
+
}
|
|
23228
|
+
}
|
|
23229
|
+
|
|
23230
|
+
if (isQueryFragmentCharacter(ch)) {
|
|
23231
|
+
output += ch;
|
|
23232
|
+
} else {
|
|
23233
|
+
const code = input.charCodeAt(i);
|
|
23234
|
+
if (code < 0x80) {
|
|
23235
|
+
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
|
|
23236
|
+
} else if (code < 0xD800 || code > 0xDFFF) {
|
|
23237
|
+
output += percentEncodeNonAscii(code);
|
|
23238
|
+
} else if (code <= 0xDBFF && i + 1 < input.length) {
|
|
23239
|
+
const low = input.charCodeAt(i + 1);
|
|
23240
|
+
if (low >= 0xDC00 && low <= 0xDFFF) {
|
|
23241
|
+
output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
|
|
23242
|
+
i++;
|
|
23243
|
+
} else {
|
|
23244
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23245
|
+
}
|
|
23246
|
+
} else {
|
|
23247
|
+
output += percentEncodeNonAscii(0xFFFD);
|
|
23248
|
+
}
|
|
23249
|
+
}
|
|
21313
23250
|
}
|
|
21314
23251
|
|
|
21315
23252
|
return output
|
|
@@ -21323,15 +23260,21 @@ function recomposeAuthority$1 (component) {
|
|
|
21323
23260
|
const uriTokens = [];
|
|
21324
23261
|
|
|
21325
23262
|
if (component.userinfo !== undefined) {
|
|
21326
|
-
uriTokens.push(component.userinfo);
|
|
23263
|
+
uriTokens.push(encodeUserinfo(component.userinfo));
|
|
21327
23264
|
uriTokens.push('@');
|
|
21328
23265
|
}
|
|
21329
23266
|
|
|
21330
23267
|
if (component.host !== undefined) {
|
|
21331
|
-
let host =
|
|
23268
|
+
let host = component.host;
|
|
21332
23269
|
if (!isIPv4$1(host)) {
|
|
21333
|
-
|
|
21334
|
-
if (ipV6res.isIPV6
|
|
23270
|
+
let ipV6res = normalizeIPv6$1(host);
|
|
23271
|
+
if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
|
|
23272
|
+
// Decode only unreserved bytes, once. In particular, keep %25 encoded
|
|
23273
|
+
// so it cannot introduce a second escape during recomposition.
|
|
23274
|
+
host = normalizePercentEncoding$1(host, true);
|
|
23275
|
+
ipV6res = normalizeIPv6$1(host);
|
|
23276
|
+
}
|
|
23277
|
+
if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
|
|
21335
23278
|
host = `[${ipV6res.escapedHost}]`;
|
|
21336
23279
|
} else {
|
|
21337
23280
|
host = reescapeHostDelimiters$1(host, false);
|
|
@@ -21341,8 +23284,12 @@ function recomposeAuthority$1 (component) {
|
|
|
21341
23284
|
}
|
|
21342
23285
|
|
|
21343
23286
|
if (typeof component.port === 'number' || typeof component.port === 'string') {
|
|
23287
|
+
const port = String(component.port);
|
|
23288
|
+
if (!isPort(port)) {
|
|
23289
|
+
throw new TypeError('URI port is malformed.')
|
|
23290
|
+
}
|
|
21344
23291
|
uriTokens.push(':');
|
|
21345
|
-
uriTokens.push(
|
|
23292
|
+
uriTokens.push(port);
|
|
21346
23293
|
}
|
|
21347
23294
|
|
|
21348
23295
|
return uriTokens.length ? uriTokens.join('') : undefined
|
|
@@ -21353,14 +23300,17 @@ var utils = {
|
|
|
21353
23300
|
reescapeHostDelimiters: reescapeHostDelimiters$1,
|
|
21354
23301
|
normalizePercentEncoding: normalizePercentEncoding$1,
|
|
21355
23302
|
normalizePathEncoding: normalizePathEncoding$1,
|
|
21356
|
-
|
|
23303
|
+
serializePathEncoding: serializePathEncoding$1,
|
|
23304
|
+
normalizeQueryFragmentEncoding: normalizeQueryFragmentEncoding$1,
|
|
23305
|
+
encodeQuery: encodeQuery$1,
|
|
23306
|
+
encodeFragment: encodeFragment$1,
|
|
21357
23307
|
removeDotSegments: removeDotSegments$1,
|
|
21358
23308
|
isIPv4: isIPv4$1,
|
|
21359
23309
|
isUUID: isUUID$1,
|
|
21360
23310
|
normalizeIPv6: normalizeIPv6$1};
|
|
21361
23311
|
|
|
21362
23312
|
const { isUUID } = utils;
|
|
21363
|
-
const URN_REG =
|
|
23313
|
+
const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
|
|
21364
23314
|
|
|
21365
23315
|
/**
|
|
21366
23316
|
* @callback SchemeFn
|
|
@@ -21459,9 +23409,14 @@ function wsSerialize (wsComponent) {
|
|
|
21459
23409
|
|
|
21460
23410
|
// reconstruct path from resource name
|
|
21461
23411
|
if (wsComponent.resourceName) {
|
|
21462
|
-
const
|
|
23412
|
+
const queryIndex = wsComponent.resourceName.indexOf('?');
|
|
23413
|
+
const path = queryIndex === -1
|
|
23414
|
+
? wsComponent.resourceName
|
|
23415
|
+
: wsComponent.resourceName.slice(0, queryIndex);
|
|
21463
23416
|
wsComponent.path = (path && path !== '/' ? path : undefined);
|
|
21464
|
-
wsComponent.query =
|
|
23417
|
+
wsComponent.query = queryIndex === -1
|
|
23418
|
+
? undefined
|
|
23419
|
+
: wsComponent.resourceName.slice(queryIndex + 1);
|
|
21465
23420
|
wsComponent.resourceName = undefined;
|
|
21466
23421
|
}
|
|
21467
23422
|
|
|
@@ -21478,7 +23433,7 @@ function urnParse (urnComponent, options) {
|
|
|
21478
23433
|
return urnComponent
|
|
21479
23434
|
}
|
|
21480
23435
|
const matches = urnComponent.path.match(URN_REG);
|
|
21481
|
-
if (matches) {
|
|
23436
|
+
if (matches && matches[0] === urnComponent.path) {
|
|
21482
23437
|
const scheme = options.scheme || urnComponent.scheme || 'urn';
|
|
21483
23438
|
urnComponent.nid = matches[1].toLowerCase();
|
|
21484
23439
|
urnComponent.nss = matches[2];
|
|
@@ -21610,9 +23565,24 @@ var schemes = {
|
|
|
21610
23565
|
getSchemeHandler: getSchemeHandler$1,
|
|
21611
23566
|
};
|
|
21612
23567
|
|
|
21613
|
-
const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding,
|
|
23568
|
+
const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = utils;
|
|
21614
23569
|
const { SCHEMES, getSchemeHandler } = schemes;
|
|
21615
23570
|
|
|
23571
|
+
const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
|
|
23572
|
+
const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.';
|
|
23573
|
+
|
|
23574
|
+
/**
|
|
23575
|
+
* @param {string} scheme
|
|
23576
|
+
* @returns {string}
|
|
23577
|
+
*/
|
|
23578
|
+
function decodeValidScheme (scheme) {
|
|
23579
|
+
const decodedScheme = unescape(String(scheme));
|
|
23580
|
+
if (!VALID_SCHEME.test(decodedScheme)) {
|
|
23581
|
+
throw new TypeError(MALFORMED_SCHEME_ERROR)
|
|
23582
|
+
}
|
|
23583
|
+
return decodedScheme
|
|
23584
|
+
}
|
|
23585
|
+
|
|
21616
23586
|
/**
|
|
21617
23587
|
* @template {import('./types/index').URIComponent|string} T
|
|
21618
23588
|
* @param {T} uri
|
|
@@ -21636,7 +23606,50 @@ function normalize (uri, options) {
|
|
|
21636
23606
|
*/
|
|
21637
23607
|
function resolve (baseURI, relativeURI, options) {
|
|
21638
23608
|
const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' };
|
|
21639
|
-
const
|
|
23609
|
+
const {
|
|
23610
|
+
parsed: baseParsed,
|
|
23611
|
+
malformedAuthorityOrPort: baseMalformed,
|
|
23612
|
+
malformedPercentEncoding: baseMalformedPercentEncoding,
|
|
23613
|
+
malformedSchemeSpecific: baseMalformedSchemeSpecific,
|
|
23614
|
+
malformedHost: baseMalformedHost,
|
|
23615
|
+
malformedScheme: baseMalformedScheme
|
|
23616
|
+
} = parseWithStatus(baseURI, schemelessOptions);
|
|
23617
|
+
const {
|
|
23618
|
+
parsed: relativeParsed,
|
|
23619
|
+
malformedAuthorityOrPort: relativeMalformed,
|
|
23620
|
+
malformedPercentEncoding: relativeMalformedPercentEncoding,
|
|
23621
|
+
malformedSchemeSpecific: relativeMalformedSchemeSpecific,
|
|
23622
|
+
malformedHost: relativeMalformedHost,
|
|
23623
|
+
malformedScheme: relativeMalformedScheme
|
|
23624
|
+
} = parseWithStatus(relativeURI, schemelessOptions);
|
|
23625
|
+
if (
|
|
23626
|
+
baseMalformed ||
|
|
23627
|
+
relativeMalformed ||
|
|
23628
|
+
baseMalformedPercentEncoding ||
|
|
23629
|
+
relativeMalformedPercentEncoding ||
|
|
23630
|
+
baseMalformedSchemeSpecific ||
|
|
23631
|
+
relativeMalformedSchemeSpecific ||
|
|
23632
|
+
baseMalformedHost ||
|
|
23633
|
+
relativeMalformedHost ||
|
|
23634
|
+
baseMalformedScheme ||
|
|
23635
|
+
relativeMalformedScheme
|
|
23636
|
+
) {
|
|
23637
|
+
throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
|
|
23638
|
+
}
|
|
23639
|
+
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
|
|
23640
|
+
const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme);
|
|
23641
|
+
const resolvedHost = resolved.host;
|
|
23642
|
+
const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&
|
|
23643
|
+
(isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
|
|
23644
|
+
canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
|
|
23645
|
+
// Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname
|
|
23646
|
+
// parser can reject them even though fast-uri preserves them safely as RFC
|
|
23647
|
+
// 3986 data. A raw non-ASCII host must still fail closed if conversion fails.
|
|
23648
|
+
const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&
|
|
23649
|
+
!/\P{ASCII}/u.test(resolvedHost);
|
|
23650
|
+
if (resolved.error && !encodedASCIIHost) {
|
|
23651
|
+
throw new Error(resolved.error)
|
|
23652
|
+
}
|
|
21640
23653
|
schemelessOptions.skipEscape = true;
|
|
21641
23654
|
return serialize(resolved, schemelessOptions)
|
|
21642
23655
|
}
|
|
@@ -21719,7 +23732,7 @@ function equal$2 (uriA, uriB, options) {
|
|
|
21719
23732
|
const normalizedA = normalizeComparableURI(uriA, options);
|
|
21720
23733
|
const normalizedB = normalizeComparableURI(uriB, options);
|
|
21721
23734
|
|
|
21722
|
-
return normalizedA !== undefined && normalizedB !== undefined && normalizedA
|
|
23735
|
+
return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB
|
|
21723
23736
|
}
|
|
21724
23737
|
|
|
21725
23738
|
/**
|
|
@@ -21747,25 +23760,30 @@ function serialize (cmpts, opts) {
|
|
|
21747
23760
|
const options = Object.assign({}, opts);
|
|
21748
23761
|
const uriTokens = [];
|
|
21749
23762
|
|
|
23763
|
+
if (component.scheme) {
|
|
23764
|
+
component.scheme = decodeValidScheme(component.scheme);
|
|
23765
|
+
}
|
|
23766
|
+
|
|
21750
23767
|
// find scheme handler
|
|
21751
23768
|
const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
|
|
21752
23769
|
|
|
21753
23770
|
// perform scheme specific serialization
|
|
21754
23771
|
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
|
|
21755
23772
|
|
|
23773
|
+
const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined;
|
|
23774
|
+
const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority;
|
|
23775
|
+
|
|
21756
23776
|
if (component.path !== undefined) {
|
|
21757
23777
|
if (!options.skipEscape) {
|
|
21758
|
-
component.path =
|
|
21759
|
-
|
|
21760
|
-
if (component.scheme !== undefined) {
|
|
21761
|
-
component.path = component.path.split('%3A').join(':');
|
|
21762
|
-
}
|
|
23778
|
+
component.path = serializePathEncoding(component.path, pathNoScheme);
|
|
21763
23779
|
} else {
|
|
21764
23780
|
component.path = normalizePercentEncoding(component.path);
|
|
21765
23781
|
}
|
|
21766
23782
|
}
|
|
21767
23783
|
|
|
21768
23784
|
if (options.reference !== 'suffix' && component.scheme) {
|
|
23785
|
+
// Scheme handlers may replace the scheme during serialization.
|
|
23786
|
+
component.scheme = decodeValidScheme(component.scheme);
|
|
21769
23787
|
uriTokens.push(component.scheme, ':');
|
|
21770
23788
|
}
|
|
21771
23789
|
|
|
@@ -21788,6 +23806,13 @@ function serialize (cmpts, opts) {
|
|
|
21788
23806
|
s = removeDotSegments(s);
|
|
21789
23807
|
}
|
|
21790
23808
|
|
|
23809
|
+
// Dot-segment removal can expose a colon that was not originally in the
|
|
23810
|
+
// first segment (for example, "./a:b"). Reapply path-noscheme encoding so
|
|
23811
|
+
// the serialized relative reference cannot be reparsed as a URI scheme.
|
|
23812
|
+
if (pathNoScheme) {
|
|
23813
|
+
s = serializePathEncoding(s, true);
|
|
23814
|
+
}
|
|
23815
|
+
|
|
21791
23816
|
if (
|
|
21792
23817
|
authority === undefined &&
|
|
21793
23818
|
s[0] === '/' &&
|
|
@@ -21801,11 +23826,11 @@ function serialize (cmpts, opts) {
|
|
|
21801
23826
|
}
|
|
21802
23827
|
|
|
21803
23828
|
if (component.query !== undefined) {
|
|
21804
|
-
uriTokens.push('?', component.query);
|
|
23829
|
+
uriTokens.push('?', encodeQuery(component.query));
|
|
21805
23830
|
}
|
|
21806
23831
|
|
|
21807
23832
|
if (component.fragment !== undefined) {
|
|
21808
|
-
uriTokens.push('#', component.fragment);
|
|
23833
|
+
uriTokens.push('#', encodeFragment(component.fragment));
|
|
21809
23834
|
}
|
|
21810
23835
|
return uriTokens.join('')
|
|
21811
23836
|
}
|
|
@@ -21816,6 +23841,15 @@ const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:
|
|
|
21816
23841
|
// with or without a scheme prefix, for the literal-backslash rejection below.
|
|
21817
23842
|
const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
|
|
21818
23843
|
|
|
23844
|
+
// Captures the leading authority-introducer region after an optional scheme: a
|
|
23845
|
+
// run of forward slashes, backslashes, and the characters the WHATWG URL parser
|
|
23846
|
+
// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
|
|
23847
|
+
// is exactly "//". Node treats "\" as "/" on special schemes and strips those
|
|
23848
|
+
// characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
|
|
23849
|
+
// "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
|
|
23850
|
+
// the path group (host confusion / SSRF / redirect bypass).
|
|
23851
|
+
const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
|
|
23852
|
+
|
|
21819
23853
|
/**
|
|
21820
23854
|
* @param {import('./types/index').URIComponent} parsed
|
|
21821
23855
|
* @param {RegExpMatchArray} matches
|
|
@@ -21833,10 +23867,86 @@ function getParseError (parsed, matches) {
|
|
|
21833
23867
|
return undefined
|
|
21834
23868
|
}
|
|
21835
23869
|
|
|
23870
|
+
/**
|
|
23871
|
+
* Checks percent syntax without decoding the represented octets. RFC 3986
|
|
23872
|
+
* percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
|
|
23873
|
+
* though they are not independently valid UTF-8.
|
|
23874
|
+
*
|
|
23875
|
+
* @param {string|undefined} component
|
|
23876
|
+
* @returns {boolean}
|
|
23877
|
+
*/
|
|
23878
|
+
function hasMalformedPercentEncoding (component) {
|
|
23879
|
+
if (component === undefined) return false
|
|
23880
|
+
|
|
23881
|
+
let percent = component.indexOf('%');
|
|
23882
|
+
while (percent !== -1) {
|
|
23883
|
+
if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
|
|
23884
|
+
return true
|
|
23885
|
+
}
|
|
23886
|
+
percent = component.indexOf('%', percent + 3);
|
|
23887
|
+
}
|
|
23888
|
+
|
|
23889
|
+
return false
|
|
23890
|
+
}
|
|
23891
|
+
|
|
23892
|
+
/**
|
|
23893
|
+
* Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
|
|
23894
|
+
* An unterminated `[` is not a literal, so it must still be validated as a
|
|
23895
|
+
* reg-name instead of being waved through as an IP.
|
|
23896
|
+
*
|
|
23897
|
+
* @param {string} host
|
|
23898
|
+
* @returns {boolean}
|
|
23899
|
+
*/
|
|
23900
|
+
function isIPLiteral (host) {
|
|
23901
|
+
return host[0] === '[' && host[host.length - 1] === ']'
|
|
23902
|
+
}
|
|
23903
|
+
|
|
23904
|
+
/**
|
|
23905
|
+
* @param {RegExpMatchArray} matches
|
|
23906
|
+
* @returns {boolean}
|
|
23907
|
+
*/
|
|
23908
|
+
function hasMalformedComponentPercentEncoding (matches) {
|
|
23909
|
+
// Bracketed IP literals use a raw "%" as the zone separator for historical
|
|
23910
|
+
// compatibility. Their parsing is intentionally left to normalizeIPv6.
|
|
23911
|
+
const host = matches[4];
|
|
23912
|
+
return hasMalformedPercentEncoding(matches[3]) ||
|
|
23913
|
+
(host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||
|
|
23914
|
+
hasMalformedPercentEncoding(matches[6]) ||
|
|
23915
|
+
hasMalformedPercentEncoding(matches[7]) ||
|
|
23916
|
+
hasMalformedPercentEncoding(matches[8])
|
|
23917
|
+
}
|
|
23918
|
+
|
|
23919
|
+
/**
|
|
23920
|
+
* @param {import('./types/index').URIComponent} parsed
|
|
23921
|
+
* @param {import('./types/index').Options} options
|
|
23922
|
+
* @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
|
|
23923
|
+
* @param {boolean} isIP
|
|
23924
|
+
* @returns {boolean} whether host conversion failed
|
|
23925
|
+
*/
|
|
23926
|
+
function canonicalizeHost (parsed, options, schemeHandler, isIP) {
|
|
23927
|
+
if (
|
|
23928
|
+
!options.unicodeSupport &&
|
|
23929
|
+
(!schemeHandler || !schemeHandler.unicodeSupport) &&
|
|
23930
|
+
parsed.host &&
|
|
23931
|
+
!isIPLiteral(parsed.host) &&
|
|
23932
|
+
(options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
|
|
23933
|
+
isIP === false &&
|
|
23934
|
+
nonSimpleDomain(parsed.host)
|
|
23935
|
+
) {
|
|
23936
|
+
try {
|
|
23937
|
+
parsed.host = new URL('http://' + parsed.host).hostname;
|
|
23938
|
+
} catch (e) {
|
|
23939
|
+
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
|
|
23940
|
+
return true
|
|
23941
|
+
}
|
|
23942
|
+
}
|
|
23943
|
+
return false
|
|
23944
|
+
}
|
|
23945
|
+
|
|
21836
23946
|
/**
|
|
21837
23947
|
* @param {string} uri
|
|
21838
23948
|
* @param {import('./types/index').Options} [opts]
|
|
21839
|
-
* @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }}
|
|
23949
|
+
* @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
|
|
21840
23950
|
*/
|
|
21841
23951
|
function parseWithStatus (uri, opts) {
|
|
21842
23952
|
const options = Object.assign({}, opts);
|
|
@@ -21852,6 +23962,11 @@ function parseWithStatus (uri, opts) {
|
|
|
21852
23962
|
};
|
|
21853
23963
|
|
|
21854
23964
|
let malformedAuthorityOrPort = false;
|
|
23965
|
+
let malformedPercentEncoding = false;
|
|
23966
|
+
let malformedSchemeSpecific = false;
|
|
23967
|
+
let malformedHost = false;
|
|
23968
|
+
let malformedIPLiteral = false;
|
|
23969
|
+
let malformedScheme = false;
|
|
21855
23970
|
|
|
21856
23971
|
let isIP = false;
|
|
21857
23972
|
if (options.reference === 'suffix') {
|
|
@@ -21875,6 +23990,28 @@ function parseWithStatus (uri, opts) {
|
|
|
21875
23990
|
malformedAuthorityOrPort = true;
|
|
21876
23991
|
}
|
|
21877
23992
|
|
|
23993
|
+
// Reject a malformed or whitespace-smuggled authority introducer. fast-uri
|
|
23994
|
+
// only recognizes a literal "//"; anything else in the leading separator run
|
|
23995
|
+
// (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
|
|
23996
|
+
// Node strips) means the authority fast-uri parses differs from the one Node's
|
|
23997
|
+
// URL resolves. Reject rather than rewrite, mirroring the literal-backslash
|
|
23998
|
+
// guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
|
|
23999
|
+
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
|
|
24000
|
+
if (introducerMatch !== null) {
|
|
24001
|
+
const region = introducerMatch[1];
|
|
24002
|
+
const normalizedRegion = region.replace(/[\t\n\r]/g, '');
|
|
24003
|
+
// Two or more leading separators introduce an authority.
|
|
24004
|
+
if (normalizedRegion.length >= 2) {
|
|
24005
|
+
if (normalizedRegion.slice(0, 2) !== '//') {
|
|
24006
|
+
parsed.error = parsed.error || 'URI authority must not contain a literal backslash.';
|
|
24007
|
+
malformedAuthorityOrPort = true;
|
|
24008
|
+
} else if (region.length !== normalizedRegion.length) {
|
|
24009
|
+
parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.';
|
|
24010
|
+
malformedAuthorityOrPort = true;
|
|
24011
|
+
}
|
|
24012
|
+
}
|
|
24013
|
+
}
|
|
24014
|
+
|
|
21878
24015
|
const matches = uri.match(URI_PARSE);
|
|
21879
24016
|
|
|
21880
24017
|
if (matches) {
|
|
@@ -21887,6 +24024,21 @@ function parseWithStatus (uri, opts) {
|
|
|
21887
24024
|
parsed.query = matches[7];
|
|
21888
24025
|
parsed.fragment = matches[8];
|
|
21889
24026
|
|
|
24027
|
+
if (parsed.scheme !== undefined) {
|
|
24028
|
+
const decodedScheme = unescape(parsed.scheme);
|
|
24029
|
+
if (VALID_SCHEME.test(decodedScheme)) {
|
|
24030
|
+
parsed.scheme = decodedScheme.toLowerCase();
|
|
24031
|
+
} else {
|
|
24032
|
+
parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
|
|
24033
|
+
malformedScheme = true;
|
|
24034
|
+
}
|
|
24035
|
+
}
|
|
24036
|
+
|
|
24037
|
+
malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
|
|
24038
|
+
if (malformedPercentEncoding) {
|
|
24039
|
+
parsed.error = parsed.error || 'URI contains malformed percent-encoding.';
|
|
24040
|
+
}
|
|
24041
|
+
|
|
21890
24042
|
// fix port number
|
|
21891
24043
|
if (isNaN(parsed.port)) {
|
|
21892
24044
|
parsed.port = matches[5];
|
|
@@ -21901,9 +24053,17 @@ function parseWithStatus (uri, opts) {
|
|
|
21901
24053
|
if (parsed.host) {
|
|
21902
24054
|
const ipv4result = isIPv4(parsed.host);
|
|
21903
24055
|
if (ipv4result === false) {
|
|
24056
|
+
const bracketedIPLiteral = isIPLiteral(parsed.host);
|
|
24057
|
+
const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1;
|
|
21904
24058
|
const ipv6result = normalizeIPv6(parsed.host);
|
|
21905
|
-
|
|
21906
|
-
|
|
24059
|
+
isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
|
|
24060
|
+
malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
|
|
24061
|
+
parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
|
|
24062
|
+
|
|
24063
|
+
if (malformedIPLiteral) {
|
|
24064
|
+
parsed.error = parsed.error || 'URI host is malformed.';
|
|
24065
|
+
malformedAuthorityOrPort = true;
|
|
24066
|
+
}
|
|
21907
24067
|
} else {
|
|
21908
24068
|
isIP = true;
|
|
21909
24069
|
}
|
|
@@ -21926,49 +24086,44 @@ function parseWithStatus (uri, opts) {
|
|
|
21926
24086
|
// find scheme handler
|
|
21927
24087
|
const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
|
|
21928
24088
|
|
|
21929
|
-
//
|
|
21930
|
-
if (!
|
|
21931
|
-
|
|
21932
|
-
|
|
21933
|
-
|
|
21934
|
-
|
|
21935
|
-
|
|
21936
|
-
|
|
21937
|
-
|
|
21938
|
-
|
|
24089
|
+
// convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts
|
|
24090
|
+
if (!malformedIPLiteral) {
|
|
24091
|
+
malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
|
|
24092
|
+
}
|
|
24093
|
+
|
|
24094
|
+
if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) {
|
|
24095
|
+
let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
|
|
24096
|
+
if (!isIP) {
|
|
24097
|
+
// Fold reg-name case after decoding unreserved octets. The second
|
|
24098
|
+
// pass only restores uppercase hex in escapes that remain encoded.
|
|
24099
|
+
host = normalizePercentEncoding(host.toLowerCase());
|
|
21939
24100
|
}
|
|
21940
|
-
|
|
24101
|
+
parsed.host = reescapeHostDelimiters(host, isIP);
|
|
21941
24102
|
}
|
|
21942
24103
|
|
|
21943
24104
|
if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
|
|
21944
|
-
if (uri.indexOf('%') !== -1) {
|
|
21945
|
-
if (parsed.scheme !== undefined) {
|
|
21946
|
-
parsed.scheme = unescape(parsed.scheme);
|
|
21947
|
-
}
|
|
21948
|
-
if (parsed.host !== undefined) {
|
|
21949
|
-
parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
|
|
21950
|
-
}
|
|
21951
|
-
}
|
|
21952
24105
|
if (parsed.path) {
|
|
21953
24106
|
parsed.path = normalizePathEncoding(parsed.path);
|
|
21954
24107
|
}
|
|
24108
|
+
if (parsed.query) {
|
|
24109
|
+
parsed.query = normalizeQueryFragmentEncoding(parsed.query);
|
|
24110
|
+
}
|
|
21955
24111
|
if (parsed.fragment) {
|
|
21956
|
-
|
|
21957
|
-
parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
|
|
21958
|
-
} catch {
|
|
21959
|
-
parsed.error = parsed.error || 'URI malformed';
|
|
21960
|
-
}
|
|
24112
|
+
parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
|
|
21961
24113
|
}
|
|
21962
24114
|
}
|
|
21963
24115
|
|
|
21964
24116
|
// perform scheme specific parsing
|
|
21965
24117
|
if (schemeHandler && schemeHandler.parse) {
|
|
21966
24118
|
schemeHandler.parse(parsed, options);
|
|
24119
|
+
if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {
|
|
24120
|
+
malformedSchemeSpecific = true;
|
|
24121
|
+
}
|
|
21967
24122
|
}
|
|
21968
24123
|
} else {
|
|
21969
24124
|
parsed.error = parsed.error || 'URI can not be parsed.';
|
|
21970
24125
|
}
|
|
21971
|
-
return { parsed, malformedAuthorityOrPort }
|
|
24126
|
+
return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }
|
|
21972
24127
|
}
|
|
21973
24128
|
|
|
21974
24129
|
/**
|
|
@@ -21992,13 +24147,17 @@ function normalizeString (uri, opts) {
|
|
|
21992
24147
|
/**
|
|
21993
24148
|
* @param {string} uri
|
|
21994
24149
|
* @param {import('./types/index').Options} [opts]
|
|
21995
|
-
* @returns {{ normalized: string, malformedAuthorityOrPort: boolean }}
|
|
24150
|
+
* @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
|
|
21996
24151
|
*/
|
|
21997
24152
|
function normalizeStringWithStatus (uri, opts) {
|
|
21998
|
-
const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
|
|
24153
|
+
const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
|
|
21999
24154
|
return {
|
|
22000
|
-
normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
|
|
22001
|
-
malformedAuthorityOrPort
|
|
24155
|
+
normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
|
|
24156
|
+
malformedAuthorityOrPort,
|
|
24157
|
+
malformedPercentEncoding,
|
|
24158
|
+
malformedSchemeSpecific,
|
|
24159
|
+
malformedHost,
|
|
24160
|
+
malformedScheme
|
|
22002
24161
|
}
|
|
22003
24162
|
}
|
|
22004
24163
|
|
|
@@ -22008,14 +24167,18 @@ function normalizeStringWithStatus (uri, opts) {
|
|
|
22008
24167
|
* @returns {string|undefined}
|
|
22009
24168
|
*/
|
|
22010
24169
|
function normalizeComparableURI (uri, opts) {
|
|
22011
|
-
if (typeof uri
|
|
22012
|
-
|
|
22013
|
-
return malformedAuthorityOrPort ? undefined : normalized
|
|
24170
|
+
if (typeof uri !== 'string' && typeof uri !== 'object') {
|
|
24171
|
+
return undefined
|
|
22014
24172
|
}
|
|
22015
24173
|
|
|
22016
|
-
|
|
22017
|
-
|
|
24174
|
+
let value;
|
|
24175
|
+
try {
|
|
24176
|
+
value = typeof uri === 'string' ? uri : serialize(uri, opts);
|
|
24177
|
+
} catch {
|
|
24178
|
+
return undefined
|
|
22018
24179
|
}
|
|
24180
|
+
const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
|
|
24181
|
+
return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized
|
|
22019
24182
|
}
|
|
22020
24183
|
|
|
22021
24184
|
const fastUri = {
|
|
@@ -25979,6 +28142,27 @@ function reportToolCall(toolName, success, durationMs, error, sessionId, clientV
|
|
|
25979
28142
|
metaVrTelemetry(args, clientVersion);
|
|
25980
28143
|
}
|
|
25981
28144
|
|
|
28145
|
+
/**
|
|
28146
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
28147
|
+
*
|
|
28148
|
+
* This source code is licensed under the MIT license found in the
|
|
28149
|
+
* LICENSE file in the root directory of this source tree.
|
|
28150
|
+
*/
|
|
28151
|
+
function isScreenshotResult(value) {
|
|
28152
|
+
return (typeof value === 'object' &&
|
|
28153
|
+
value !== null &&
|
|
28154
|
+
!Array.isArray(value) &&
|
|
28155
|
+
typeof value.imageData === 'string');
|
|
28156
|
+
}
|
|
28157
|
+
async function saveScreenshot(result, requestedPath) {
|
|
28158
|
+
const extension = result.mimeType === 'image/jpeg' ? 'jpg' : 'png';
|
|
28159
|
+
const outputPath = requestedPath ??
|
|
28160
|
+
path.join(os.tmpdir(), `iwsdk-screenshot-${randomUUID$1()}.${extension}`);
|
|
28161
|
+
await mkdir(path.dirname(outputPath), { recursive: true });
|
|
28162
|
+
await writeFile(outputPath, Buffer.from(result.imageData, 'base64'), requestedPath == null ? { flag: 'wx' } : undefined);
|
|
28163
|
+
return outputPath;
|
|
28164
|
+
}
|
|
28165
|
+
|
|
25982
28166
|
/**
|
|
25983
28167
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
25984
28168
|
*
|
|
@@ -25988,6 +28172,73 @@ function reportToolCall(toolName, success, durationMs, error, sessionId, clientV
|
|
|
25988
28172
|
function isRecord$1(value) {
|
|
25989
28173
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
25990
28174
|
}
|
|
28175
|
+
const MAX_ASSET_PREVIEW_MCP_NAMED_PARTS = 40;
|
|
28176
|
+
const MAX_ASSET_PREVIEW_MCP_WARNINGS = 24;
|
|
28177
|
+
const MAX_ASSET_PREVIEW_MCP_WARNINGS_PER_CODE = 3;
|
|
28178
|
+
function compactAssetPreviewMetadata(metadata) {
|
|
28179
|
+
if (!isRecord$1(metadata.diagnostics)) {
|
|
28180
|
+
return metadata;
|
|
28181
|
+
}
|
|
28182
|
+
const diagnostics = metadata.diagnostics;
|
|
28183
|
+
const namedPartRecords = Array.isArray(diagnostics.namedParts)
|
|
28184
|
+
? diagnostics.namedParts.filter(isRecord$1)
|
|
28185
|
+
: null;
|
|
28186
|
+
const namedParts = (namedPartRecords ?? [])
|
|
28187
|
+
.slice(0, MAX_ASSET_PREVIEW_MCP_NAMED_PARTS)
|
|
28188
|
+
.map((part) => ({
|
|
28189
|
+
...(typeof part.name === 'string' ? { name: part.name } : {}),
|
|
28190
|
+
...(typeof part.path === 'string' ? { path: part.path } : {}),
|
|
28191
|
+
...(typeof part.type === 'string' ? { type: part.type } : {}),
|
|
28192
|
+
}));
|
|
28193
|
+
const namedPartCount = typeof diagnostics.namedPartCount === 'number'
|
|
28194
|
+
? diagnostics.namedPartCount
|
|
28195
|
+
: namedPartRecords?.length;
|
|
28196
|
+
const warningRecords = Array.isArray(diagnostics.warnings)
|
|
28197
|
+
? diagnostics.warnings.filter(isRecord$1)
|
|
28198
|
+
: null;
|
|
28199
|
+
const warningCodeCounts = new Map();
|
|
28200
|
+
const warningSampleCounts = new Map();
|
|
28201
|
+
const warnings = [];
|
|
28202
|
+
for (const warning of warningRecords ?? []) {
|
|
28203
|
+
const code = typeof warning.code === 'string' ? warning.code : 'unknown_warning';
|
|
28204
|
+
warningCodeCounts.set(code, (warningCodeCounts.get(code) ?? 0) + 1);
|
|
28205
|
+
const sampledForCode = warningSampleCounts.get(code) ?? 0;
|
|
28206
|
+
if (warnings.length >= MAX_ASSET_PREVIEW_MCP_WARNINGS ||
|
|
28207
|
+
sampledForCode >= MAX_ASSET_PREVIEW_MCP_WARNINGS_PER_CODE) {
|
|
28208
|
+
continue;
|
|
28209
|
+
}
|
|
28210
|
+
warningSampleCounts.set(code, sampledForCode + 1);
|
|
28211
|
+
warnings.push({
|
|
28212
|
+
code,
|
|
28213
|
+
...(typeof warning.message === 'string'
|
|
28214
|
+
? { message: warning.message }
|
|
28215
|
+
: {}),
|
|
28216
|
+
...(typeof warning.path === 'string' ? { path: warning.path } : {}),
|
|
28217
|
+
});
|
|
28218
|
+
}
|
|
28219
|
+
return {
|
|
28220
|
+
...metadata,
|
|
28221
|
+
diagnostics: {
|
|
28222
|
+
...diagnostics,
|
|
28223
|
+
...(namedPartRecords == null
|
|
28224
|
+
? {}
|
|
28225
|
+
: {
|
|
28226
|
+
namedPartsTruncated: diagnostics.namedPartsTruncated === true ||
|
|
28227
|
+
(namedPartCount ?? namedPartRecords.length) > namedParts.length,
|
|
28228
|
+
namedPartCount: namedPartCount ?? namedPartRecords.length,
|
|
28229
|
+
namedParts,
|
|
28230
|
+
}),
|
|
28231
|
+
...(warningRecords == null
|
|
28232
|
+
? {}
|
|
28233
|
+
: {
|
|
28234
|
+
warningCodeCounts: Object.fromEntries(warningCodeCounts),
|
|
28235
|
+
warningCount: warningRecords.length,
|
|
28236
|
+
warnings,
|
|
28237
|
+
warningsTruncated: warningRecords.length > warnings.length,
|
|
28238
|
+
}),
|
|
28239
|
+
},
|
|
28240
|
+
};
|
|
28241
|
+
}
|
|
25991
28242
|
function createTabMetadataText(tabId, tabGeneration) {
|
|
25992
28243
|
return {
|
|
25993
28244
|
type: 'text',
|
|
@@ -26139,7 +28390,9 @@ async function startRuntimeMcpStdioServer({ serverName = 'iwsdk', version = '1.0
|
|
|
26139
28390
|
runtimeSession: session,
|
|
26140
28391
|
});
|
|
26141
28392
|
reportToolCall(name, true, Date.now() - startTime, undefined, session.sessionId, version);
|
|
26142
|
-
|
|
28393
|
+
// Managed browser status would misdescribe a headset's session.
|
|
28394
|
+
const normalizedResponse = name === 'xr_get_session_status' &&
|
|
28395
|
+
command.target?.deviceClass !== 'physical'
|
|
26143
28396
|
? {
|
|
26144
28397
|
...rawResponse,
|
|
26145
28398
|
result: withBrowserStatus$1(rawResponse.result ?? rawResponse, session),
|
|
@@ -26149,27 +28402,49 @@ async function startRuntimeMcpStdioServer({ serverName = 'iwsdk', version = '1.0
|
|
|
26149
28402
|
if ((name === 'browser_screenshot' ||
|
|
26150
28403
|
name === 'scene_screenshot' ||
|
|
26151
28404
|
name === 'scene_render_file' ||
|
|
28405
|
+
name === 'asset_render_preview' ||
|
|
26152
28406
|
name === 'ui_render_preview') &&
|
|
28407
|
+
isScreenshotResult(result)) {
|
|
28408
|
+
const screenshotPath = await saveScreenshot(result);
|
|
28409
|
+
const { imageData: _imageData, ...metadata } = result;
|
|
28410
|
+
const responseMetadata = name === 'asset_render_preview'
|
|
28411
|
+
? compactAssetPreviewMetadata(metadata)
|
|
28412
|
+
: metadata;
|
|
28413
|
+
return tabTracker.processResponse({
|
|
28414
|
+
...normalizedResponse,
|
|
28415
|
+
result: { ...responseMetadata, screenshotPath },
|
|
28416
|
+
});
|
|
28417
|
+
}
|
|
28418
|
+
if (name === 'browser_interact' &&
|
|
26153
28419
|
isRecord$1(result) &&
|
|
26154
|
-
|
|
26155
|
-
|
|
26156
|
-
|
|
26157
|
-
|
|
26158
|
-
|
|
26159
|
-
|
|
28420
|
+
isRecord$1(result.failure) &&
|
|
28421
|
+
isRecord$1(result.failure.screenshot) &&
|
|
28422
|
+
typeof result.failure.screenshot.imageData === 'string') {
|
|
28423
|
+
const screenshot = result.failure.screenshot;
|
|
28424
|
+
const mimeType = typeof screenshot.mimeType === 'string'
|
|
28425
|
+
? screenshot.mimeType
|
|
28426
|
+
: 'image/png';
|
|
28427
|
+
const sanitizedResult = {
|
|
28428
|
+
...result,
|
|
28429
|
+
failure: {
|
|
28430
|
+
...result.failure,
|
|
28431
|
+
screenshot: {
|
|
28432
|
+
captured: true,
|
|
28433
|
+
mimeType,
|
|
28434
|
+
},
|
|
28435
|
+
},
|
|
26160
28436
|
};
|
|
26161
|
-
|
|
26162
|
-
|
|
26163
|
-
|
|
26164
|
-
|
|
26165
|
-
|
|
26166
|
-
|
|
26167
|
-
|
|
26168
|
-
|
|
26169
|
-
|
|
26170
|
-
|
|
28437
|
+
const content = [
|
|
28438
|
+
{ type: 'text', text: JSON.stringify(sanitizedResult, null, 2) },
|
|
28439
|
+
{
|
|
28440
|
+
type: 'image',
|
|
28441
|
+
data: screenshot.imageData,
|
|
28442
|
+
mimeType,
|
|
28443
|
+
},
|
|
28444
|
+
];
|
|
28445
|
+
if (normalizedResponse._tabId != null) {
|
|
28446
|
+
content.push(createTabMetadataText(normalizedResponse._tabId, normalizedResponse._tabGeneration));
|
|
26171
28447
|
}
|
|
26172
|
-
const content = [image];
|
|
26173
28448
|
return { content };
|
|
26174
28449
|
}
|
|
26175
28450
|
return tabTracker.processResponse(normalizedResponse);
|
|
@@ -26442,6 +28717,7 @@ function resolveRuntimeParams(operationName, options) {
|
|
|
26442
28717
|
if (operationName === 'browser_screenshot' ||
|
|
26443
28718
|
operationName === 'scene_screenshot' ||
|
|
26444
28719
|
operationName === 'scene_render_file' ||
|
|
28720
|
+
operationName === 'asset_render_preview' ||
|
|
26445
28721
|
operationName === 'ui_render_preview') {
|
|
26446
28722
|
allowed.add('outputFile');
|
|
26447
28723
|
}
|
|
@@ -26465,12 +28741,6 @@ function resolveRuntimeParams(operationName, options) {
|
|
|
26465
28741
|
function isRecord(value) {
|
|
26466
28742
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
26467
28743
|
}
|
|
26468
|
-
function isScreenshotResult(value) {
|
|
26469
|
-
return isRecord(value) && typeof value.imageData === 'string';
|
|
26470
|
-
}
|
|
26471
|
-
function isBrowserRelaunchedResult(value) {
|
|
26472
|
-
return isRecord(value) && value.status === 'browser_relaunched';
|
|
26473
|
-
}
|
|
26474
28744
|
function withBrowserStatus(result, session) {
|
|
26475
28745
|
const browser = session.browser ?? null;
|
|
26476
28746
|
const browserConnected = Boolean(session.browser?.connected);
|
|
@@ -26490,13 +28760,26 @@ function withBrowserStatus(result, session) {
|
|
|
26490
28760
|
browserCommandReady,
|
|
26491
28761
|
};
|
|
26492
28762
|
}
|
|
26493
|
-
async function
|
|
26494
|
-
|
|
26495
|
-
|
|
26496
|
-
|
|
26497
|
-
|
|
26498
|
-
|
|
26499
|
-
|
|
28763
|
+
async function normalizeInteractionFailureScreenshot(result) {
|
|
28764
|
+
if (!isRecord(result) || !isRecord(result.failure)) {
|
|
28765
|
+
return result;
|
|
28766
|
+
}
|
|
28767
|
+
const screenshot = result.failure.screenshot;
|
|
28768
|
+
if (!isScreenshotResult(screenshot)) {
|
|
28769
|
+
return result;
|
|
28770
|
+
}
|
|
28771
|
+
const screenshotPath = await saveScreenshot(screenshot);
|
|
28772
|
+
return {
|
|
28773
|
+
...result,
|
|
28774
|
+
failure: {
|
|
28775
|
+
...result.failure,
|
|
28776
|
+
screenshot: {
|
|
28777
|
+
captured: true,
|
|
28778
|
+
mimeType: screenshot.mimeType ?? 'image/png',
|
|
28779
|
+
screenshotPath,
|
|
28780
|
+
},
|
|
28781
|
+
},
|
|
28782
|
+
};
|
|
26500
28783
|
}
|
|
26501
28784
|
async function handleRuntimeOperation(domain, action, options, io) {
|
|
26502
28785
|
const operation = action
|
|
@@ -26528,10 +28811,6 @@ async function handleRuntimeOperation(domain, action, options, io) {
|
|
|
26528
28811
|
let rawResult;
|
|
26529
28812
|
try {
|
|
26530
28813
|
rawResult = await sendRuntimeCommand(sendOptions);
|
|
26531
|
-
if (operation.mcpName === 'browser_screenshot' &&
|
|
26532
|
-
isBrowserRelaunchedResult(rawResult.result ?? rawResult)) {
|
|
26533
|
-
rawResult = await sendRuntimeCommand(sendOptions);
|
|
26534
|
-
}
|
|
26535
28814
|
}
|
|
26536
28815
|
catch (error) {
|
|
26537
28816
|
if (operation.mcpName === 'xr_accept_session' &&
|
|
@@ -26540,12 +28819,18 @@ async function handleRuntimeOperation(domain, action, options, io) {
|
|
|
26540
28819
|
}
|
|
26541
28820
|
throw error;
|
|
26542
28821
|
}
|
|
26543
|
-
|
|
28822
|
+
// Managed browser status would misdescribe a headset's session.
|
|
28823
|
+
let result = operation.mcpName === 'xr_get_session_status' &&
|
|
28824
|
+
command.target?.deviceClass !== 'physical'
|
|
26544
28825
|
? withBrowserStatus(rawResult.result ?? rawResult, session)
|
|
26545
28826
|
: (rawResult.result ?? rawResult);
|
|
28827
|
+
if (operation.mcpName === 'browser_interact') {
|
|
28828
|
+
result = await normalizeInteractionFailureScreenshot(result);
|
|
28829
|
+
}
|
|
26546
28830
|
const isScreenshotOperation = operation.mcpName === 'browser_screenshot' ||
|
|
26547
28831
|
operation.mcpName === 'scene_screenshot' ||
|
|
26548
28832
|
operation.mcpName === 'scene_render_file' ||
|
|
28833
|
+
operation.mcpName === 'asset_render_preview' ||
|
|
26549
28834
|
operation.mcpName === 'ui_render_preview';
|
|
26550
28835
|
const hasExplicitScreenshotPath = typeof options.outputFile === 'string';
|
|
26551
28836
|
if (options.outputFile === true) {
|
|
@@ -26553,23 +28838,15 @@ async function handleRuntimeOperation(domain, action, options, io) {
|
|
|
26553
28838
|
}
|
|
26554
28839
|
// An explicit output path is an instruction to persist the PNG. Honor it
|
|
26555
28840
|
// even when --raw is also present, instead of silently printing base64 and
|
|
26556
|
-
// ignoring the requested file.
|
|
26557
28841
|
if (isScreenshotOperation &&
|
|
26558
28842
|
isScreenshotResult(result) &&
|
|
26559
28843
|
(hasExplicitScreenshotPath || !options.raw)) {
|
|
26560
|
-
const screenshotPath = await saveScreenshot(result, options.outputFile);
|
|
26561
|
-
|
|
26562
|
-
const { imageData: _imageData, ...metadata } = result;
|
|
26563
|
-
return createSuccess({
|
|
26564
|
-
workspaceRoot,
|
|
26565
|
-
operation: operation.id,
|
|
26566
|
-
result: metadata,
|
|
26567
|
-
screenshotPath,
|
|
26568
|
-
});
|
|
26569
|
-
}
|
|
28844
|
+
const screenshotPath = await saveScreenshot(result, typeof options.outputFile === 'string' ? options.outputFile : undefined);
|
|
28845
|
+
const { imageData: _imageData, ...metadata } = result;
|
|
26570
28846
|
return createSuccess({
|
|
26571
28847
|
workspaceRoot,
|
|
26572
28848
|
operation: operation.id,
|
|
28849
|
+
...(Object.keys(metadata).length > 0 ? { result: metadata } : {}),
|
|
26573
28850
|
screenshotPath,
|
|
26574
28851
|
});
|
|
26575
28852
|
}
|
|
@@ -26615,6 +28892,12 @@ function formatSchemaPropertyLines(propertyPath, schema, required, indent = 2) {
|
|
|
26615
28892
|
lines.push(...formatSchemaPropertyLines(`${propertyPath}.${name}`, nestedSchema, nestedRequired.has(name), indent + 2));
|
|
26616
28893
|
}
|
|
26617
28894
|
}
|
|
28895
|
+
if (schema.items?.properties) {
|
|
28896
|
+
const itemRequired = new Set(schema.items.required ?? []);
|
|
28897
|
+
for (const [name, itemSchema] of Object.entries(schema.items.properties)) {
|
|
28898
|
+
lines.push(...formatSchemaPropertyLines(`${propertyPath}[].${name}`, itemSchema, itemRequired.has(name), indent + 2));
|
|
28899
|
+
}
|
|
28900
|
+
}
|
|
26618
28901
|
if (schema.items?.enum?.length) {
|
|
26619
28902
|
lines.push(`${prefix} item values: ${schema.items.enum.join(', ')}`);
|
|
26620
28903
|
}
|
|
@@ -26655,6 +28938,7 @@ function buildRuntimeCommandHelp(domain, action) {
|
|
|
26655
28938
|
const writesScreenshot = operation.mcpName === 'browser_screenshot' ||
|
|
26656
28939
|
operation.mcpName === 'scene_screenshot' ||
|
|
26657
28940
|
operation.mcpName === 'scene_render_file' ||
|
|
28941
|
+
operation.mcpName === 'asset_render_preview' ||
|
|
26658
28942
|
operation.mcpName === 'ui_render_preview';
|
|
26659
28943
|
const lines = [
|
|
26660
28944
|
`Usage: iwsdk ${domain} ${action} [--input-json <json>] [--timeout <ms>] [--raw]${writesScreenshot ? ' [--output-file <path>]' : ''}`,
|
|
@@ -26693,11 +28977,15 @@ function buildRuntimeDomainHelp(domain) {
|
|
|
26693
28977
|
if (operations.length === 0) {
|
|
26694
28978
|
return [`Unknown command group "${domain}".`];
|
|
26695
28979
|
}
|
|
28980
|
+
const actions = operations.map((operation) => ` ${operation.action.padEnd(24)} ${operation.description}`);
|
|
28981
|
+
if (domain === 'browser') {
|
|
28982
|
+
actions.push(` ${'run'.padEnd(24)} Run trusted workspace Playwright code against the existing managed browser (requires explicit dev-server opt-in).`);
|
|
28983
|
+
}
|
|
26696
28984
|
return [
|
|
26697
28985
|
`Usage: iwsdk ${domain} <action>`,
|
|
26698
28986
|
'',
|
|
26699
28987
|
'Actions:',
|
|
26700
|
-
...
|
|
28988
|
+
...actions,
|
|
26701
28989
|
'',
|
|
26702
28990
|
`Run "iwsdk ${domain} <action> --help" for parameters.`,
|
|
26703
28991
|
];
|
|
@@ -26710,6 +28998,21 @@ function buildMcpInspectHelp() {
|
|
|
26710
28998
|
' --tool <mcpName> Show description and input schema for one runtime tool',
|
|
26711
28999
|
];
|
|
26712
29000
|
}
|
|
29001
|
+
function buildBrowserRunHelp() {
|
|
29002
|
+
return [
|
|
29003
|
+
'Usage: iwsdk browser run <workspace-script.mjs> [--timeout <ms>] [--workspace <path>]',
|
|
29004
|
+
'',
|
|
29005
|
+
'Run trusted local Playwright code against the existing managed Chromium session.',
|
|
29006
|
+
'Start the dev server with --allow-browser-automation first.',
|
|
29007
|
+
'The script must stay inside the workspace and export a default function or named run function.',
|
|
29008
|
+
'It receives { browser, context, page, frame, cdp, workspaceRoot }.',
|
|
29009
|
+
'IWSDK owns the managed browser, context, and page; destructive close operations are blocked.',
|
|
29010
|
+
'',
|
|
29011
|
+
'Options:',
|
|
29012
|
+
' --timeout <ms> Script timeout. Defaults to 60000.',
|
|
29013
|
+
' --workspace <path> Resolve a running IWSDK workspace explicitly.',
|
|
29014
|
+
];
|
|
29015
|
+
}
|
|
26713
29016
|
function buildReferenceCommandHelp(action) {
|
|
26714
29017
|
if (action === 'status') {
|
|
26715
29018
|
return [
|
|
@@ -26779,8 +29082,10 @@ function buildDevCommandHelp(action) {
|
|
|
26779
29082
|
' --headed Launch the managed browser headed (default)',
|
|
26780
29083
|
' --open Open the managed browser on startup (default)',
|
|
26781
29084
|
' --no-open Do not open the managed browser on startup',
|
|
29085
|
+
' --native-xr-control Control native Quest WebXR through ADB-reversed localhost',
|
|
26782
29086
|
' --screenshot-width <pixels> Positive screenshot width; default behavior is 800px',
|
|
26783
29087
|
' --screenshot-height <pixels> Positive screenshot height; default behavior is 800px',
|
|
29088
|
+
' --allow-browser-automation Enable the local same-session Playwright runner',
|
|
26784
29089
|
' --foreground Keep the package-manager process attached',
|
|
26785
29090
|
' --timeout <milliseconds> Runtime readiness timeout (default: 60000)',
|
|
26786
29091
|
' --workspace <path> Select an IWSDK application explicitly',
|
|
@@ -26805,12 +29110,14 @@ function usageLines() {
|
|
|
26805
29110
|
'Commands:',
|
|
26806
29111
|
' status',
|
|
26807
29112
|
' dev up|restart [--ai-mode <mode>] [--headed|--headless] [--open|--no-open]',
|
|
29113
|
+
' runtime status|targets|wait|recover|pair-headset',
|
|
26808
29114
|
' dev down|logs|open|status',
|
|
26809
29115
|
' adapter sync|status|prune|prompt',
|
|
26810
29116
|
' reference status|warmup|inspect|search|relationship|api|file|components|systems|dependents|examples',
|
|
26811
29117
|
' mcp stdio|inspect [--tool <mcpName>]',
|
|
26812
29118
|
' xr <action>',
|
|
26813
|
-
' browser <action>',
|
|
29119
|
+
' browser <action>|run <script>',
|
|
29120
|
+
' asset <action>',
|
|
26814
29121
|
' scene <action>',
|
|
26815
29122
|
' ui <action>',
|
|
26816
29123
|
' ecs <action>',
|
|
@@ -26828,7 +29135,7 @@ async function runCli(argv, io = {}) {
|
|
|
26828
29135
|
const stderr = io.stderr ?? process.stderr;
|
|
26829
29136
|
const cwd = io.cwd ?? process.cwd();
|
|
26830
29137
|
const parsed = parseArgv(argv);
|
|
26831
|
-
const [command, subcommand] = parsed.positionals;
|
|
29138
|
+
const [command, subcommand, argument] = parsed.positionals;
|
|
26832
29139
|
const context = { stdout, stderr, cwd };
|
|
26833
29140
|
try {
|
|
26834
29141
|
let result;
|
|
@@ -26851,9 +29158,15 @@ async function runCli(argv, io = {}) {
|
|
|
26851
29158
|
}
|
|
26852
29159
|
if (command === 'xr' ||
|
|
26853
29160
|
command === 'browser' ||
|
|
29161
|
+
command === 'asset' ||
|
|
26854
29162
|
command === 'scene' ||
|
|
26855
29163
|
command === 'ui' ||
|
|
26856
|
-
command === 'ecs'
|
|
29164
|
+
command === 'ecs' ||
|
|
29165
|
+
command === 'runtime') {
|
|
29166
|
+
if (command === 'browser' && subcommand === 'run') {
|
|
29167
|
+
stdout.write(`${buildBrowserRunHelp().join('\n')}\n`);
|
|
29168
|
+
return 0;
|
|
29169
|
+
}
|
|
26857
29170
|
stdout.write(`${(subcommand
|
|
26858
29171
|
? buildRuntimeCommandHelp(command, subcommand)
|
|
26859
29172
|
: buildRuntimeDomainHelp(command)).join('\n')}\n`);
|
|
@@ -26934,9 +29247,15 @@ async function runCli(argv, io = {}) {
|
|
|
26934
29247
|
throw new Error('Usage: iwsdk mcp stdio|inspect');
|
|
26935
29248
|
case 'xr':
|
|
26936
29249
|
case 'browser':
|
|
29250
|
+
case 'asset':
|
|
26937
29251
|
case 'scene':
|
|
26938
29252
|
case 'ui':
|
|
26939
29253
|
case 'ecs':
|
|
29254
|
+
case 'runtime':
|
|
29255
|
+
if (command === 'browser' && subcommand === 'run') {
|
|
29256
|
+
result = await handleBrowserRun(argument, parsed.options, context);
|
|
29257
|
+
break;
|
|
29258
|
+
}
|
|
26940
29259
|
if (!subcommand) {
|
|
26941
29260
|
throw new Error(buildRuntimeDomainHelp(command).join('\n'));
|
|
26942
29261
|
}
|
|
@@ -26945,6 +29264,9 @@ async function runCli(argv, io = {}) {
|
|
|
26945
29264
|
default:
|
|
26946
29265
|
throw new Error(`Unknown command: ${command}`);
|
|
26947
29266
|
}
|
|
29267
|
+
if (typeof result === 'number') {
|
|
29268
|
+
return result;
|
|
29269
|
+
}
|
|
26948
29270
|
if (result) {
|
|
26949
29271
|
if (isCliRawOutput(result)) {
|
|
26950
29272
|
writeJson(stdout, result.value);
|
|
@@ -26965,7 +29287,11 @@ async function runCli(argv, io = {}) {
|
|
|
26965
29287
|
cause: error.issueCause,
|
|
26966
29288
|
browser: error.browser ?? null,
|
|
26967
29289
|
})
|
|
26968
|
-
:
|
|
29290
|
+
: error instanceof RuntimeOwnerError
|
|
29291
|
+
? createFailure(error.message, error.code, {
|
|
29292
|
+
owner: error.owner,
|
|
29293
|
+
})
|
|
29294
|
+
: createFailure(error instanceof Error ? error.message : String(error));
|
|
26969
29295
|
writeJson(stderr, failure);
|
|
26970
29296
|
return 1;
|
|
26971
29297
|
}
|