@iwsdk/vite-plugin-dev 1.2.0-rc.0 → 1.2.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash, randomUUID, randomBytes, timingSafeEqual } from 'crypto';
1
+ import { createHash, randomUUID, randomBytes, timingSafeEqual, X509Certificate } from 'crypto';
2
2
  import * as fs from 'fs';
3
3
  import { existsSync, realpathSync, readFileSync, mkdirSync, writeFileSync, renameSync, unlinkSync, linkSync, rmdirSync, rmSync, readdirSync, statSync, lstatSync as lstatSync$1 } from 'fs';
4
4
  import * as os from 'os';
@@ -23007,20 +23007,26 @@ function resolveManagedRenderMode(headless, override = process.env.IWSDK_DEV_REN
23007
23007
  return 'on-demand';
23008
23008
  }
23009
23009
  /**
23010
- * Draw `frames` fresh frames in the application frame and wait until they have
23011
- * been handed to the compositor. Apps that do not expose `requestRender`
23012
- * (non-IWSDK runtimes, older @iwsdk/core) are left alone.
23010
+ * Draw `frames` fresh frames in the application frame and wait, at most
23011
+ * `timeoutMs`, until they have been handed to the compositor. Resolves
23012
+ * `'timeout'` when they were not drawn in time, for example because an
23013
+ * uncaught error stopped the app's render loop. Apps that do not expose
23014
+ * `requestRender` (non-IWSDK runtimes, older @iwsdk/core) are left alone and
23015
+ * resolve `'unsupported'`. Rejects when the app's `requestRender` does.
23013
23016
  */
23014
23017
  async function requestApplicationRender(frame, frames = 1, timeoutMs = 10000) {
23015
- await frame.evaluate(({ frames, timeoutMs }) => {
23018
+ return frame.evaluate(({ frames, timeoutMs, }) => {
23016
23019
  const runtime = window.FRAMEWORK_MCP_RUNTIME;
23017
23020
  if (typeof runtime?.requestRender !== 'function') {
23018
- return;
23021
+ return 'unsupported';
23019
23022
  }
23023
+ let timer;
23020
23024
  return Promise.race([
23021
- runtime.requestRender(frames),
23022
- new Promise((resolve) => setTimeout(resolve, timeoutMs)),
23023
- ]);
23025
+ Promise.resolve(runtime.requestRender(frames)).then(() => 'drawn'),
23026
+ new Promise((resolve) => {
23027
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
23028
+ }),
23029
+ ]).finally(() => clearTimeout(timer));
23024
23030
  }, { frames, timeoutMs });
23025
23031
  }
23026
23032
  /**
@@ -24977,6 +24983,51 @@ async function navigateAndVerifyManagedPage({ browserAutomationEndpoint, context
24977
24983
  * This source code is licensed under the MIT license found in the
24978
24984
  * LICENSE file in the root directory of this source tree.
24979
24985
  */
24986
+ /**
24987
+ * Frames an app that renders on demand draws under the profile's render hold
24988
+ * before sampling starts. Such an app may not have drawn for a long time, or
24989
+ * ever in its current view (just after entering XR, say), and its first
24990
+ * frames pay one-time costs (shader programs, texture uploads) that are not
24991
+ * the frame cost being measured. The browser keeps frames in flight, so that
24992
+ * cost can surface a frame or two later. In cold headless sessions of the VR
24993
+ * starter, one warm-up frame left a 1.6 s interval in the first profile and
24994
+ * two left a 1.5 s stall before its first sample; three kept both out.
24995
+ * Runtime publish evidence skips two frames (`warmupFrames: 2`) after its
24996
+ * readiness loop has already drawn one, so it also lets three go by.
24997
+ */
24998
+ const PROFILE_WARMUP_FRAMES = 3;
24999
+ /**
25000
+ * Longest a profile start waits for its warm-up frames: as long as runtime
25001
+ * evidence waits for a frame. An app whose render loop has stopped never
25002
+ * draws them.
25003
+ */
25004
+ const MAX_PROFILE_WARMUP_MS = 5000;
25005
+ /**
25006
+ * Shortest warm-up a profile start attempts. Drawing three frames and seeing
25007
+ * the last one presented takes four frames: 67 ms at 60 Hz for an app with
25008
+ * cheap frames, but about 0.5 s for the VR starter on SwiftShader (headless,
25009
+ * no GPU), whose frames take 117-133 ms. With less time a healthy app could
25010
+ * miss them and the timeout would blame its render loop, so the profile
25011
+ * skips the warm-up instead and says so.
25012
+ */
25013
+ const MIN_PROFILE_WARMUP_MS = 1000;
25014
+ /**
25015
+ * Active command time a profile start keeps after its warm-up, to install the
25016
+ * sampler, attach CDP and start a trace, or to undo them and restore the
25017
+ * workspace view when the start fails.
25018
+ */
25019
+ const PROFILE_START_RESERVE_MS = WORKSPACE_RESTORE_RESERVE_MS + 2500;
25020
+ /**
25021
+ * Animation frames in a row in which the app drew nothing while the profile
25022
+ * held rendering, from which the profile reports `render-loop-stopped`. Under
25023
+ * the hold the app draws every frame; entering or leaving XR skips a frame or
25024
+ * two. A longer run means its render loop stopped (one uncaught error in a
25025
+ * frame stops it), before the profile or during it, or stalled, and the
25026
+ * samples of that run are the requestAnimationFrame intervals of a page that
25027
+ * did not draw. The longest run counts, so a stall that ends before the
25028
+ * profile stops is reported too.
25029
+ */
25030
+ const RENDER_STOPPED_FRAMES = 30;
24980
25031
  const MAX_TRACE_ARTIFACT_BYTES = 100 * 1024 * 1024;
24981
25032
  const MAX_PROFILE_SAMPLES = 10000;
24982
25033
  const MAX_PROFILE_INTERRUPTIONS = 100;
@@ -25026,7 +25077,8 @@ class BrowserProfiler {
25026
25077
  const mode = request.mode ?? 'interaction';
25027
25078
  const profileId = randomUUID();
25028
25079
  const maxDurationMs = Math.min(60000, Math.max(1000, request.maxDurationMs ?? 30000));
25029
- await startProfileInFrame(frame, mode);
25080
+ const startInterruptions = await startProfileInFrame(frame, mode, Math.min(MAX_PROFILE_WARMUP_MS, this.coordinator.getRemainingActiveTimeMs() -
25081
+ PROFILE_START_RESERVE_MS));
25030
25082
  cdp = await this.context.newCDPSession(this.page);
25031
25083
  await cdp.send('Performance.enable').catch(() => { });
25032
25084
  let tracePath = null;
@@ -25069,6 +25121,9 @@ class BrowserProfiler {
25069
25121
  tracePath,
25070
25122
  visibility,
25071
25123
  };
25124
+ for (const interruption of startInterruptions) {
25125
+ this.record(profile, interruption);
25126
+ }
25072
25127
  this.activeProfile = profile;
25073
25128
  this.lastResult = null;
25074
25129
  return this.describe(profile, 'started');
@@ -25109,6 +25164,7 @@ class BrowserProfiler {
25109
25164
  environment: undefined,
25110
25165
  eventDurations: [],
25111
25166
  frameTimes: [],
25167
+ longestUndrawnRun: null,
25112
25168
  longTasks: [],
25113
25169
  marks: [],
25114
25170
  visibilityEvents: [],
@@ -25125,6 +25181,14 @@ class BrowserProfiler {
25125
25181
  this.recordError(profile, 'page-profile-unavailable', error);
25126
25182
  return emptySamples();
25127
25183
  });
25184
+ if (samples.longestUndrawnRun != null &&
25185
+ samples.longestUndrawnRun >= RENDER_STOPPED_FRAMES) {
25186
+ this.record(profile, {
25187
+ at: Date.now(),
25188
+ kind: 'render-loop-stopped',
25189
+ value: `the app drew nothing for ${samples.longestUndrawnRun} animation frames in a row while the profile held rendering`,
25190
+ });
25191
+ }
25128
25192
  const browserMetricsResponse = await profile.cdp
25129
25193
  .send('Performance.getMetrics')
25130
25194
  .catch(() => ({ metrics: [] }));
@@ -25295,24 +25359,95 @@ class BrowserProfiler {
25295
25359
  });
25296
25360
  }
25297
25361
  }
25298
- async function startProfileInFrame(frame, mode) {
25362
+ /**
25363
+ * Hold rendering, warm up an on-demand app, and install the page sampler.
25364
+ * Returns interruptions for the profile to record: warm-up frames that were
25365
+ * not drawn within `warmupBudgetMs`, or a warm-up that was skipped because
25366
+ * that budget was too short or the app's render mode could not be read.
25367
+ */
25368
+ async function startProfileInFrame(frame, mode, warmupBudgetMs) {
25369
+ const interruptions = [];
25299
25370
  // A profile measures real frame cost, so draw every frame while it runs.
25300
25371
  // The hold id lives on the page next to the profile state it belongs to.
25372
+ // The same call reads the app's render mode, so the warm-up is decided on
25373
+ // the page that holds rendering. If the page goes away, the call fails and
25374
+ // so does the start.
25301
25375
  const renderHold = await acquireApplicationRenderHold(frame);
25302
- await frame.evaluate((id) => {
25376
+ const renderMode = await frame.evaluate((id) => {
25303
25377
  const runtimeWindow = window;
25304
- runtimeWindow.FRAMEWORK_MCP_RUNTIME?.releaseRenderHold?.(runtimeWindow.__IWSDK_PROFILE_RENDER_HOLD);
25378
+ const runtime = runtimeWindow.FRAMEWORK_MCP_RUNTIME;
25379
+ runtime?.releaseRenderHold?.(runtimeWindow.__IWSDK_PROFILE_RENDER_HOLD);
25305
25380
  runtimeWindow.__IWSDK_PROFILE_RENDER_HOLD = id;
25381
+ try {
25382
+ const mode = runtime?.renderMode;
25383
+ return mode === 'continuous' || mode === 'on-demand' ? mode : null;
25384
+ }
25385
+ catch (error) {
25386
+ return {
25387
+ error: error instanceof Error ? error.message : String(error),
25388
+ };
25389
+ }
25306
25390
  }, renderHold);
25391
+ if (renderMode != null && typeof renderMode === 'object') {
25392
+ // Reading the mode threw. The app may render on demand, so the samples
25393
+ // may include first-draw costs.
25394
+ interruptions.push({
25395
+ at: Date.now(),
25396
+ kind: 'render-mode-unavailable',
25397
+ value: `${PROFILE_WARMUP_FRAMES} warm-up frames skipped: could not read the app's render mode: ${renderMode.error}`,
25398
+ });
25399
+ }
25400
+ else if (renderMode === 'on-demand') {
25401
+ // Only an app that renders on demand needs warming up. One that draws
25402
+ // continuously (headed sessions, IWSDK_DEV_RENDER_MODE=continuous, apps
25403
+ // without render modes) paid its first-draw costs long ago.
25404
+ if (warmupBudgetMs < MIN_PROFILE_WARMUP_MS) {
25405
+ // Too little of the command's time is left to draw the frames. The
25406
+ // samples may include first-draw costs.
25407
+ interruptions.push({
25408
+ at: Date.now(),
25409
+ kind: 'render-warmup-skipped-budget',
25410
+ value: `${PROFILE_WARMUP_FRAMES} warm-up frames skipped: ${Math.max(0, warmupBudgetMs)}ms of the command's time was left for them`,
25411
+ });
25412
+ }
25413
+ else {
25414
+ const warmup = await requestApplicationRender(frame, PROFILE_WARMUP_FRAMES, warmupBudgetMs);
25415
+ if (warmup === 'timeout') {
25416
+ // The samples may include first-draw costs, or frames the app never
25417
+ // drew because its render loop has stopped.
25418
+ interruptions.push({
25419
+ at: Date.now(),
25420
+ kind: 'render-warmup-timeout',
25421
+ value: `${PROFILE_WARMUP_FRAMES} warm-up frames not drawn within ${warmupBudgetMs}ms`,
25422
+ });
25423
+ }
25424
+ }
25425
+ }
25307
25426
  await frame.evaluate(({ maxSamples, mode }) => {
25308
25427
  const runtimeWindow = window;
25309
25428
  runtimeWindow.__IWSDK_BROWSER_PROFILE?.observers?.forEach((observer) => observer.disconnect());
25310
25429
  if (runtimeWindow.__IWSDK_BROWSER_PROFILE?.rafId != null) {
25311
25430
  cancelAnimationFrame(runtimeWindow.__IWSDK_BROWSER_PROFILE.rafId);
25312
25431
  }
25432
+ // Count only work that starts during the profile, not the first draw
25433
+ // or the warm-up frames just before it. Observing without `buffered`
25434
+ // skips earlier entries; the check drops late reports of earlier work.
25435
+ const since = performance.now();
25436
+ const readDrawnFrames = () => {
25437
+ try {
25438
+ const count = runtimeWindow.FRAMEWORK_MCP_RUNTIME?.drawnFrames;
25439
+ return typeof count === 'number' ? count : null;
25440
+ }
25441
+ catch {
25442
+ return null;
25443
+ }
25444
+ };
25313
25445
  const state = {
25446
+ drawnFrames: readDrawnFrames(),
25314
25447
  eventDurations: [],
25448
+ framesSinceDraw: 0,
25315
25449
  frameTimes: [],
25450
+ longestUndrawnRun: 0,
25316
25451
  longTasks: [],
25317
25452
  observers: [],
25318
25453
  previousFrame: null,
@@ -25326,11 +25461,13 @@ async function startProfileInFrame(frame, mode) {
25326
25461
  }
25327
25462
  const observer = new PerformanceObserver((list) => {
25328
25463
  for (const entry of list.getEntries()) {
25329
- callback(entry);
25464
+ if (entry.startTime >= since) {
25465
+ callback(entry);
25466
+ }
25330
25467
  }
25331
25468
  });
25332
25469
  try {
25333
- observer.observe({ type, buffered: true });
25470
+ observer.observe({ type });
25334
25471
  state.observers.push(observer);
25335
25472
  }
25336
25473
  catch {
@@ -25355,6 +25492,22 @@ async function startProfileInFrame(frame, mode) {
25355
25492
  state.frameTimes.push(timestamp - state.previousFrame);
25356
25493
  }
25357
25494
  state.previousFrame = timestamp;
25495
+ // While the profile holds rendering the app draws every frame, so
25496
+ // count the frames since its drawn-frame count last moved, and keep
25497
+ // the longest such run. Counting ends when stopping releases the
25498
+ // hold.
25499
+ const drawnFrames = readDrawnFrames();
25500
+ if (drawnFrames != null &&
25501
+ runtimeWindow.__IWSDK_PROFILE_RENDER_HOLD != null) {
25502
+ if (drawnFrames === state.drawnFrames) {
25503
+ state.framesSinceDraw += 1;
25504
+ state.longestUndrawnRun = Math.max(state.longestUndrawnRun, state.framesSinceDraw);
25505
+ }
25506
+ else {
25507
+ state.drawnFrames = drawnFrames;
25508
+ state.framesSinceDraw = 0;
25509
+ }
25510
+ }
25358
25511
  state.rafId = requestAnimationFrame(sample);
25359
25512
  };
25360
25513
  state.rafId = requestAnimationFrame(sample);
@@ -25375,7 +25528,14 @@ async function startProfileInFrame(frame, mode) {
25375
25528
  performance.mark(`iwsdk-browser-profile-${mode}-start`);
25376
25529
  runtimeWindow.__IWSDK_BROWSER_PROFILE = state;
25377
25530
  }, { maxSamples: MAX_PROFILE_SAMPLES, mode });
25531
+ return interruptions;
25378
25532
  }
25533
+ /**
25534
+ * Release the profile's render hold and collect its page samples.
25535
+ * `longestUndrawnRun` is the longest run of animation frames in which the
25536
+ * app drew nothing while the profile held rendering; it is `null` when the
25537
+ * app does not report drawn frames.
25538
+ */
25379
25539
  async function stopProfileInFrame(frame) {
25380
25540
  await frame
25381
25541
  .evaluate(() => {
@@ -25404,6 +25564,7 @@ async function stopProfileInFrame(frame) {
25404
25564
  return {
25405
25565
  eventDurations: state.eventDurations,
25406
25566
  frameTimes: state.frameTimes,
25567
+ longestUndrawnRun: state.drawnFrames == null ? null : state.longestUndrawnRun,
25407
25568
  longTasks: state.longTasks,
25408
25569
  visibilityEvents: state.visibilityEvents,
25409
25570
  marks: performance
@@ -26916,6 +27077,7 @@ function matches(metadata, target) {
26916
27077
  * Reports MCP tool calls, session lifecycle, and errors through MetaVR's
26917
27078
  * DeveloperTelemetry pipeline via the `metavr xxiwsdk` subcommand.
26918
27079
  * All calls are fire-and-forget — telemetry never blocks or breaks the tool.
27080
+ * At most a few MetaVR processes run at once; further events wait their turn.
26919
27081
  *
26920
27082
  * Executes MetaVR's JavaScript entrypoint with the current Node executable.
26921
27083
  * This avoids platform shell shims and works the same way on Windows and Unix.
@@ -26930,7 +27092,60 @@ function resolveMetaVrEntrypoint() {
26930
27092
  return null;
26931
27093
  }
26932
27094
  }
26933
- function metaVrTelemetry(args, clientVersion) {
27095
+ // At most this many MetaVR processes run at once. Each event is its own
27096
+ // Node process that lives under a second; the dev server reports every MCP
27097
+ // tool call, and an agent can issue them faster than that, so without a limit
27098
+ // thousands of these processes piled up on a devserver.
27099
+ const MAX_RUNNING = 4;
27100
+ // Events waiting beyond this are dropped, so telemetry never grows without
27101
+ // bound when a caller outpaces MetaVR for a long time.
27102
+ const MAX_QUEUED = 1000;
27103
+ const queued = [];
27104
+ let running = 0;
27105
+ let exitHookInstalled = false;
27106
+ function launch(argv) {
27107
+ running++;
27108
+ let finished = false;
27109
+ const finish = () => {
27110
+ if (finished) {
27111
+ return;
27112
+ }
27113
+ finished = true;
27114
+ running--;
27115
+ drain();
27116
+ };
27117
+ try {
27118
+ const child = spawn(process.execPath, argv, {
27119
+ stdio: 'ignore',
27120
+ windowsHide: true,
27121
+ });
27122
+ child.on('error', finish);
27123
+ child.on('exit', finish);
27124
+ child.unref();
27125
+ }
27126
+ catch {
27127
+ finish();
27128
+ }
27129
+ }
27130
+ function drain() {
27131
+ while (running < MAX_RUNNING && queued.length > 0) {
27132
+ launch(queued.shift());
27133
+ }
27134
+ }
27135
+ /**
27136
+ * Starts up to MAX_RUNNING of the events still waiting and drops the rest.
27137
+ * Runs when the process exits, so a burst at the end neither floods the
27138
+ * machine nor keeps the process alive. Session and error events wait at the
27139
+ * front, so they are the ones started.
27140
+ */
27141
+ function flushQueuedTelemetry() {
27142
+ const remaining = queued.splice(0, MAX_RUNNING);
27143
+ queued.length = 0;
27144
+ for (const argv of remaining) {
27145
+ launch(argv);
27146
+ }
27147
+ }
27148
+ function metaVrTelemetry(args, clientVersion, urgent = false) {
26934
27149
  const entrypoint = resolveMetaVrEntrypoint();
26935
27150
  if (entrypoint == null) {
26936
27151
  return;
@@ -26939,12 +27154,20 @@ function metaVrTelemetry(args, clientVersion) {
26939
27154
  if (clientVersion) {
26940
27155
  globalArgs.push('--client-version', clientVersion);
26941
27156
  }
26942
- const child = spawn(process.execPath, [entrypoint, ...globalArgs, ...args], {
26943
- stdio: 'ignore',
26944
- windowsHide: true,
26945
- });
26946
- child.on('error', () => { });
26947
- child.unref();
27157
+ if (!exitHookInstalled) {
27158
+ exitHookInstalled = true;
27159
+ process.once('exit', flushQueuedTelemetry);
27160
+ }
27161
+ const argv = [entrypoint, ...globalArgs, ...args];
27162
+ if (urgent) {
27163
+ // Session boundaries and errors are rare and matter more than any one
27164
+ // tool call, so they go ahead of a backlog and are never dropped for it.
27165
+ queued.unshift(argv);
27166
+ }
27167
+ else if (queued.length < MAX_QUEUED) {
27168
+ queued.push(argv);
27169
+ }
27170
+ drain();
26948
27171
  }
26949
27172
  function reportSessionStart(sessionId, opts) {
26950
27173
  const args = ['session-start', '--session-id', sessionId];
@@ -26957,7 +27180,7 @@ function reportSessionStart(sessionId, opts) {
26957
27180
  if (opts?.port) {
26958
27181
  args.push('--port', String(opts.port));
26959
27182
  }
26960
- metaVrTelemetry(args, opts?.clientVersion);
27183
+ metaVrTelemetry(args, opts?.clientVersion, true);
26961
27184
  }
26962
27185
  function reportSessionEnd(sessionId, opts) {
26963
27186
  const args = ['session-end', '--session-id', sessionId];
@@ -26967,7 +27190,7 @@ function reportSessionEnd(sessionId, opts) {
26967
27190
  if (opts?.reason) {
26968
27191
  args.push('--reason', opts.reason);
26969
27192
  }
26970
- metaVrTelemetry(args, opts?.clientVersion);
27193
+ metaVrTelemetry(args, opts?.clientVersion, true);
26971
27194
  }
26972
27195
 
26973
27196
  /**
@@ -60109,14 +60332,7 @@ function iwsdkDev(options = {}) {
60109
60332
  const certDir = path.isAbsolute(configuredCacheDir)
60110
60333
  ? configuredCacheDir
60111
60334
  : path.resolve(projectRoot, configuredCacheDir);
60112
- const certificate = await getCertificate(certDir, httpsOptions.name ?? 'IWSDK Development', httpsOptions.domains, httpsOptions.ttlDays ?? 365);
60113
- // @vitejs/plugin-basic-ssl writes its cache asynchronously after
60114
- // returning. Complete the write before Vite starts so a rapid restart
60115
- // cannot generate a second certificate for the same project.
60116
- mkdirSync(certDir, { recursive: true });
60117
- writeFileSync(path.join(certDir, '_cert.pem'), certificate, {
60118
- mode: 0o600,
60119
- });
60335
+ const certificate = await loadDevelopmentCertificate(certDir, httpsOptions.name ?? 'IWSDK Development', httpsOptions.domains, httpsOptions.ttlDays ?? 365);
60120
60336
  userConfig.server ?? (userConfig.server = {});
60121
60337
  userConfig.server.https = {
60122
60338
  cert: certificate,
@@ -65377,6 +65593,32 @@ async function readRequestBody(request, maxBytes = Number.POSITIVE_INFINITY) {
65377
65593
  }
65378
65594
  /** @deprecated Use `iwsdkDev` instead */
65379
65595
  const injectIWER = iwsdkDev;
65596
+ /**
65597
+ * Returns the project's development certificate from `<certDir>/_cert.pem`,
65598
+ * generating and caching one when it is missing, unreadable or expired.
65599
+ *
65600
+ * `@vitejs/plugin-basic-ssl` writes its own cache without awaiting the write,
65601
+ * after `getCertificate` has returned. Pointing it at `certDir` itself let that
65602
+ * late write truncate `_cert.pem` while the next start was reading it. It now
65603
+ * generates into a subdirectory that is never read, and this function owns
65604
+ * `_cert.pem` with a synchronous write.
65605
+ */
65606
+ async function loadDevelopmentCertificate(certDir, name, domains, ttlDays) {
65607
+ const certPath = path.join(certDir, '_cert.pem');
65608
+ try {
65609
+ const cached = readFileSync(certPath, 'utf8');
65610
+ if (new Date(new X509Certificate(cached).validTo).getTime() > Date.now()) {
65611
+ return cached;
65612
+ }
65613
+ }
65614
+ catch {
65615
+ // Missing, unreadable or not a certificate: generate a new one.
65616
+ }
65617
+ const certificate = await getCertificate(path.join(certDir, '.basic-ssl'), name, domains, ttlDays);
65618
+ mkdirSync(certDir, { recursive: true });
65619
+ writeFileSync(certPath, certificate, { mode: 0o600 });
65620
+ return certificate;
65621
+ }
65380
65622
 
65381
65623
  export { injectIWER, iwsdkDev };
65382
65624
  //# sourceMappingURL=index.js.map