@scene-glass/devtools 0.0.0-stage → 0.1.32

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/vite.js ADDED
@@ -0,0 +1,1608 @@
1
+ // packages/devtools/src/vite/runtime-authority.ts
2
+ import { createHash } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { open, realpath, stat } from "node:fs/promises";
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ // packages/contracts/src/limits.ts
9
+ var MAX_SAFE_REVISION = Number.MAX_SAFE_INTEGER;
10
+ var SceneGlassContractError = class extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.name = "SceneGlassContractError";
15
+ this.code = code;
16
+ Object.setPrototypeOf(this, new.target.prototype);
17
+ }
18
+ };
19
+ var LIMIT_DEFAULTS = {
20
+ httpBodyBytes: 1 * 1024 * 1024,
21
+ canonicalIdentityBytes: 2048,
22
+ routeBytes: 2048,
23
+ memoBytes: 16 * 1024,
24
+ surroundingTextCodePoints: 500,
25
+ surroundingTextBytes: 4 * 1024,
26
+ locatorFieldBytes: 512,
27
+ locatorSerializedBytes: 16 * 1024,
28
+ annotationsPerPage: 1e3,
29
+ pageFileBytes: 8 * 1024 * 1024,
30
+ replayLedgerBytes: 2 * 1024 * 1024,
31
+ replayResultBytes: 64 * 1024,
32
+ pagesPerProject: 2e3,
33
+ exportScanBytes: 64 * 1024 * 1024,
34
+ exportRenderBytes: 16 * 1024 * 1024,
35
+ concurrentRequestsPerProject: 16,
36
+ concurrentRequestsGlobal: 64,
37
+ normalSessionsPerProject: 32,
38
+ normalSessionsGlobal: 128,
39
+ sessionMaxAgeMs: 30 * 60 * 1e3,
40
+ sessionIdleMs: 5 * 60 * 1e3,
41
+ diagnosticActiveRunsPerProject: 4,
42
+ diagnosticActiveRunsGlobal: 16,
43
+ diagnosticRunsPerProjectPerMinute: 5,
44
+ requestTimeoutMs: 30 * 1e3,
45
+ exportTimeoutMs: 60 * 1e3,
46
+ workRequestAnnotations: 1e3,
47
+ workRequestEvents: 32,
48
+ historyTaskCount: 32,
49
+ historyBudgetBytes: 256 * 1024 * 1024,
50
+ historyScanFiles: 2e4,
51
+ historyScanBytes: 512 * 1024 * 1024,
52
+ historyFileBytes: 16 * 1024 * 1024,
53
+ historyDiffRenderBytes: 8 * 1024 * 1024,
54
+ historyHashConcurrency: 16
55
+ };
56
+ var BUILT_IN_LIMITS = Object.freeze(LIMIT_DEFAULTS);
57
+ var GLOBAL_ONLY_LIMIT_NAMES = [
58
+ "httpBodyBytes",
59
+ "concurrentRequestsGlobal",
60
+ "normalSessionsGlobal",
61
+ "diagnosticActiveRunsGlobal",
62
+ "historyHashConcurrency"
63
+ ];
64
+ var GLOBAL_ONLY_LIMIT_NAME_SET = new Set(
65
+ GLOBAL_ONLY_LIMIT_NAMES
66
+ );
67
+ var GLOBAL_LIMIT_OVERRIDE_KEYS = Object.freeze(
68
+ Object.keys(BUILT_IN_LIMITS)
69
+ );
70
+ var PROJECT_LIMIT_OVERRIDE_KEYS = Object.freeze(
71
+ GLOBAL_LIMIT_OVERRIDE_KEYS.filter(
72
+ (key) => !GLOBAL_ONLY_LIMIT_NAME_SET.has(key)
73
+ )
74
+ );
75
+ var REPLAY_RECORD_COUNT_OVERRIDE_ALIASES = Object.freeze([
76
+ "replayRecordCount",
77
+ "replayRecordsCount",
78
+ "replayWindowSize",
79
+ "replayWindowCount",
80
+ "replayCount",
81
+ "replayCountLimit",
82
+ "recordCount",
83
+ "replayRecords"
84
+ ]);
85
+ function assertSafeRevision(value, name = "revision") {
86
+ return assertIntegerInRange(value, 0, MAX_SAFE_REVISION, name);
87
+ }
88
+ function assertIntegerInRange(value, minimum, maximum, name = "value") {
89
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum || value > maximum) {
90
+ throw new SceneGlassContractError(
91
+ "SCG_SCALAR_INVALID",
92
+ `${name} must be a safe integer from ${minimum} through ${maximum}`
93
+ );
94
+ }
95
+ return value;
96
+ }
97
+ function assertLowercaseUuidV4(value, name = "id") {
98
+ if (typeof value !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
99
+ throw new SceneGlassContractError("SCG_ID_INVALID", `${name} must be a lowercase UUID v4`);
100
+ }
101
+ return value;
102
+ }
103
+
104
+ // packages/contracts/src/annotations.ts
105
+ var SHA256_DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
106
+ var MAX_CONTEXT_SERIALIZED_BYTES = 16 * 1024;
107
+ function parseSha256Digest(value) {
108
+ if (typeof value !== "string" || !SHA256_DIGEST_PATTERN.test(value)) {
109
+ throw new SceneGlassContractError("SCG_ID_INVALID", "digest must be a lowercase sha256 digest");
110
+ }
111
+ return value;
112
+ }
113
+
114
+ // packages/contracts/src/coupon.ts
115
+ var COUPON_CAPABILITIES = Object.freeze(["measure-distance", "measure-size"]);
116
+
117
+ // packages/contracts/src/premium.ts
118
+ var PREMIUM_MEASUREMENT_NAMESPACE_V1 = "scene-glass-premium-measurement-v1";
119
+ var PREMIUM_MEASUREMENT_ABI_V1 = 1;
120
+ var MAX_PREMIUM_MODULE_BYTES = 256 * 1024;
121
+ var MAX_PREMIUM_STYLESHEET_BYTES = 64 * 1024;
122
+ var PREMIUM_MEASUREMENT_MODULE_PATH_V1 = "premium/measurement-v1.js";
123
+ var PREMIUM_MEASUREMENT_STYLESHEET_PATH_V1 = "premium/measurement-v1.css";
124
+ var PREMIUM_MODULE_MEDIA_TYPE_V1 = "application/javascript; charset=utf-8";
125
+ var PREMIUM_STYLESHEET_MEDIA_TYPE_V1 = "text/css; charset=utf-8";
126
+ var SCENE_GLASS_NATIVE_TUPLES_V1 = Object.freeze(["darwin-arm64", "darwin-x64", "linux-x64-gnu"]);
127
+ function parseSceneGlassReleaseManifestV1(value) {
128
+ const hasPredecessor = isOrdinaryRecord(value) && Object.hasOwn(value, "lifecyclePredecessor");
129
+ const hasAncestors = isOrdinaryRecord(value) && Object.hasOwn(value, "lifecycleAncestors");
130
+ const manifest = exactRecord(
131
+ value,
132
+ [
133
+ "schemaVersion",
134
+ "package",
135
+ "artifacts",
136
+ ...hasPredecessor ? ["lifecyclePredecessor"] : [],
137
+ ...hasAncestors ? ["lifecycleAncestors"] : []
138
+ ],
139
+ "release manifest"
140
+ );
141
+ if (manifest.schemaVersion !== 1) {
142
+ throw invalid("release manifest schemaVersion must be 1");
143
+ }
144
+ const releasePackage = parseReleasePackage(manifest.package);
145
+ const artifacts = parseReleaseArtifacts(manifest.artifacts);
146
+ const lifecyclePredecessor = hasPredecessor ? parseLifecyclePredecessor(manifest.lifecyclePredecessor, releasePackage.version) : void 0;
147
+ const lifecycleAncestors = hasAncestors ? parseLifecycleAncestors(manifest.lifecycleAncestors, lifecyclePredecessor) : void 0;
148
+ return Object.freeze({
149
+ schemaVersion: 1,
150
+ package: releasePackage,
151
+ artifacts,
152
+ ...lifecyclePredecessor === void 0 ? {} : { lifecyclePredecessor },
153
+ ...lifecycleAncestors === void 0 ? {} : { lifecycleAncestors }
154
+ });
155
+ }
156
+ function parseLifecycleAncestors(value, predecessor) {
157
+ if (predecessor === void 0 || !Array.isArray(value) || value.length === 0) {
158
+ throw invalid("lifecycle ancestors require a predecessor and at least one entry");
159
+ }
160
+ let successorVersion = predecessor.package.version;
161
+ const ancestors = value.map((entry, index) => {
162
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
163
+ throw invalid("lifecycle ancestors must not be sparse");
164
+ }
165
+ const ancestor = parseLifecyclePredecessor(entry, successorVersion);
166
+ successorVersion = ancestor.package.version;
167
+ return ancestor;
168
+ });
169
+ return Object.freeze(ancestors);
170
+ }
171
+ function parseReleasePackage(value) {
172
+ const packageRecord = exactRecord(value, ["name", "version"], "release package");
173
+ if (packageRecord.name !== "@scene-glass/devtools" || typeof packageRecord.version !== "string" || !isCanonicalPackageVersion(packageRecord.version)) {
174
+ throw invalid("release package identity is invalid");
175
+ }
176
+ return Object.freeze({
177
+ name: "@scene-glass/devtools",
178
+ version: packageRecord.version
179
+ });
180
+ }
181
+ function parseReleaseArtifacts(value) {
182
+ const artifacts = exactRecord(
183
+ value,
184
+ ["cli", "freeLoader", "native", "premiumMeasurement"],
185
+ "release artifacts"
186
+ );
187
+ return Object.freeze({
188
+ cli: parseArtifact(artifacts.cli, "CLI artifact"),
189
+ freeLoader: parseArtifact(artifacts.freeLoader, "free loader artifact"),
190
+ native: parseNativeArtifacts(artifacts.native),
191
+ premiumMeasurement: parsePremiumArtifact(artifacts.premiumMeasurement)
192
+ });
193
+ }
194
+ function parseLifecyclePredecessor(value, successorVersion) {
195
+ const predecessor = exactRecord(
196
+ value,
197
+ ["releaseManifestSha256", "package", "artifacts"],
198
+ "lifecycle predecessor"
199
+ );
200
+ const releasePackage = parseReleasePackage(predecessor.package);
201
+ if (comparePackageVersions(releasePackage.version, successorVersion) >= 0) {
202
+ throw invalid("lifecycle predecessor version must precede the release package version");
203
+ }
204
+ return Object.freeze({
205
+ releaseManifestSha256: parseSha256(
206
+ predecessor.releaseManifestSha256,
207
+ "lifecycle predecessor manifest"
208
+ ),
209
+ package: releasePackage,
210
+ artifacts: parseReleaseArtifacts(predecessor.artifacts)
211
+ });
212
+ }
213
+ function parseArtifact(value, label) {
214
+ const record = exactRecord(value, ["path", "sha256"], label);
215
+ return Object.freeze({
216
+ path: parsePackageArtifactPath(record.path, label),
217
+ sha256: parseSha256(record.sha256, label)
218
+ });
219
+ }
220
+ function parseNativeArtifacts(value) {
221
+ if (!Array.isArray(value) || value.length !== SCENE_GLASS_NATIVE_TUPLES_V1.length) {
222
+ throw invalid("native artifacts must contain every supported tuple");
223
+ }
224
+ const parsed = SCENE_GLASS_NATIVE_TUPLES_V1.map((tuple, index) => {
225
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
226
+ throw invalid("native artifacts must not be sparse");
227
+ }
228
+ const record = exactRecord(value[index], ["tuple", "path", "sha256"], "native artifact");
229
+ if (record.tuple !== tuple) {
230
+ throw invalid("native artifacts must use the canonical tuple order");
231
+ }
232
+ return Object.freeze({
233
+ tuple,
234
+ path: parsePackageArtifactPath(record.path, "native artifact"),
235
+ sha256: parseSha256(record.sha256, "native artifact")
236
+ });
237
+ });
238
+ return Object.freeze(parsed);
239
+ }
240
+ function parsePremiumArtifact(value) {
241
+ const record = exactRecord(
242
+ value,
243
+ ["moduleId", "namespace", "abiVersion", "module", "stylesheet"],
244
+ "premium measurement artifact"
245
+ );
246
+ if (record.moduleId !== PREMIUM_MEASUREMENT_NAMESPACE_V1 || record.namespace !== PREMIUM_MEASUREMENT_NAMESPACE_V1 || record.abiVersion !== PREMIUM_MEASUREMENT_ABI_V1) {
247
+ throw invalid("premium measurement artifact identity or ABI is invalid");
248
+ }
249
+ return Object.freeze({
250
+ moduleId: PREMIUM_MEASUREMENT_NAMESPACE_V1,
251
+ namespace: PREMIUM_MEASUREMENT_NAMESPACE_V1,
252
+ abiVersion: PREMIUM_MEASUREMENT_ABI_V1,
253
+ module: parsePremiumModuleArtifact(record.module),
254
+ stylesheet: parsePremiumStylesheetArtifact(record.stylesheet)
255
+ });
256
+ }
257
+ function parsePremiumModuleArtifact(value) {
258
+ const record = parsePremiumFileArtifact(value, "premium measurement module");
259
+ if (record.path !== PREMIUM_MEASUREMENT_MODULE_PATH_V1 || record.maxBytes !== MAX_PREMIUM_MODULE_BYTES || record.mediaType !== PREMIUM_MODULE_MEDIA_TYPE_V1) {
260
+ throw invalid("premium measurement module authority is invalid");
261
+ }
262
+ return Object.freeze({
263
+ path: PREMIUM_MEASUREMENT_MODULE_PATH_V1,
264
+ maxBytes: MAX_PREMIUM_MODULE_BYTES,
265
+ mediaType: PREMIUM_MODULE_MEDIA_TYPE_V1,
266
+ sha256: record.sha256
267
+ });
268
+ }
269
+ function parsePremiumStylesheetArtifact(value) {
270
+ const record = parsePremiumFileArtifact(value, "premium measurement stylesheet");
271
+ if (record.path !== PREMIUM_MEASUREMENT_STYLESHEET_PATH_V1 || record.maxBytes !== MAX_PREMIUM_STYLESHEET_BYTES || record.mediaType !== PREMIUM_STYLESHEET_MEDIA_TYPE_V1) {
272
+ throw invalid("premium measurement stylesheet authority is invalid");
273
+ }
274
+ return Object.freeze({
275
+ path: PREMIUM_MEASUREMENT_STYLESHEET_PATH_V1,
276
+ maxBytes: MAX_PREMIUM_STYLESHEET_BYTES,
277
+ mediaType: PREMIUM_STYLESHEET_MEDIA_TYPE_V1,
278
+ sha256: record.sha256
279
+ });
280
+ }
281
+ function parsePremiumFileArtifact(value, label) {
282
+ const record = exactRecord(value, ["path", "maxBytes", "mediaType", "sha256"], label);
283
+ const path = parsePackageArtifactPath(record.path, label);
284
+ if (typeof record.maxBytes !== "number" || !Number.isSafeInteger(record.maxBytes) || record.maxBytes < 1 || typeof record.mediaType !== "string") {
285
+ throw invalid(`${label} media type or size bound is invalid`);
286
+ }
287
+ return Object.freeze({
288
+ path,
289
+ maxBytes: record.maxBytes,
290
+ mediaType: record.mediaType,
291
+ sha256: parseSha256(record.sha256, label)
292
+ });
293
+ }
294
+ function parsePackageArtifactPath(value, label) {
295
+ if (typeof value !== "string" || value.length === 0 || value.length > 256 || value.startsWith("/") || value.endsWith("/") || value.includes("\\") || value.includes("\0") || value.includes("?") || value.includes("#")) {
296
+ throw invalid(`${label} path is not package-relative`);
297
+ }
298
+ const segments = value.split("/");
299
+ if (segments.some(
300
+ (segment) => segment.length === 0 || segment === "." || segment === ".." || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(segment)
301
+ )) {
302
+ throw invalid(`${label} path is not package-relative`);
303
+ }
304
+ return value;
305
+ }
306
+ function parseSha256(value, label) {
307
+ if (typeof value !== "string" || !/^sha256:[0-9a-f]{64}$/u.test(value)) {
308
+ throw invalid(`${label} SHA-256 is invalid`);
309
+ }
310
+ return value;
311
+ }
312
+ function isCanonicalPackageVersion(value) {
313
+ return /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/u.test(value);
314
+ }
315
+ function comparePackageVersions(left, right) {
316
+ const leftParts = left.split(".").map(Number);
317
+ const rightParts = right.split(".").map(Number);
318
+ for (let index = 0; index < 3; index += 1) {
319
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
320
+ if (difference !== 0) return difference;
321
+ }
322
+ return 0;
323
+ }
324
+ function exactRecord(value, keys, label) {
325
+ if (!isOrdinaryRecord(value)) {
326
+ throw invalid(`${label} must be an object`);
327
+ }
328
+ const actualKeys = Reflect.ownKeys(value);
329
+ if (actualKeys.length !== keys.length || actualKeys.some((key) => typeof key !== "string" || !keys.includes(key))) {
330
+ throw invalid(`${label} contains missing or unknown fields`);
331
+ }
332
+ return value;
333
+ }
334
+ function isOrdinaryRecord(value) {
335
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
336
+ return false;
337
+ }
338
+ const prototype = Object.getPrototypeOf(value);
339
+ return prototype === Object.prototype || prototype === null;
340
+ }
341
+ function invalid(message) {
342
+ return new TypeError(message);
343
+ }
344
+
345
+ // packages/contracts/src/work-contract-internal.ts
346
+ var UTC_TIMESTAMP_PATTERN = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/;
347
+ var MAX_PROJECT_RELATIVE_PATH_BYTES = BUILT_IN_LIMITS.routeBytes;
348
+ function createWorkFieldParsers(code) {
349
+ const fail = (message) => new SceneGlassContractError(code, message);
350
+ const mapped = (message, parse) => {
351
+ try {
352
+ return parse();
353
+ } catch (error) {
354
+ if (error instanceof SceneGlassContractError) {
355
+ throw fail(message);
356
+ }
357
+ throw error;
358
+ }
359
+ };
360
+ return Object.freeze({
361
+ fail,
362
+ mapped,
363
+ record: (value, name) => {
364
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
365
+ throw fail(`${name} must be an object`);
366
+ }
367
+ const prototype = Object.getPrototypeOf(value);
368
+ if (prototype !== Object.prototype && prototype !== null) {
369
+ throw fail(`${name} must be a plain object`);
370
+ }
371
+ return value;
372
+ },
373
+ field: (record, key) => Reflect.get(record, key),
374
+ exactKeys: (record, keys, name) => {
375
+ for (const key of Reflect.ownKeys(record)) {
376
+ if (typeof key !== "string" || !keys.has(key)) {
377
+ throw fail(`${name} contains an unknown field`);
378
+ }
379
+ }
380
+ for (const key of keys) {
381
+ if (!Object.prototype.hasOwnProperty.call(record, key)) {
382
+ throw fail(`${name} is missing ${key}`);
383
+ }
384
+ }
385
+ },
386
+ denseArray: (value, name) => {
387
+ if (!Array.isArray(value)) {
388
+ throw fail(`${name} must be an array`);
389
+ }
390
+ for (let index = 0; index < value.length; index += 1) {
391
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
392
+ throw fail(`${name} must not be sparse`);
393
+ }
394
+ }
395
+ return Object.freeze(Array.from(value, (entry) => entry));
396
+ },
397
+ unique: (values, name) => {
398
+ if (new Set(values).size !== values.length) {
399
+ throw fail(`${name} must not contain duplicates`);
400
+ }
401
+ },
402
+ member: (value, members, name) => {
403
+ for (const member of members) {
404
+ if (value === member) {
405
+ return member;
406
+ }
407
+ }
408
+ throw fail(`${name} is invalid`);
409
+ },
410
+ uuid: (value, name) => mapped(`${name} must be a lowercase UUID v4`, () => assertLowercaseUuidV4(value, name)),
411
+ digest: (value, name) => mapped(`${name} must be a lowercase sha256 digest`, () => parseSha256Digest(value)),
412
+ integer: (value, name) => mapped(`${name} must be a non-negative safe integer`, () => assertSafeRevision(value, name)),
413
+ flag: (value, name) => {
414
+ if (typeof value !== "boolean") {
415
+ throw fail(`${name} must be a boolean`);
416
+ }
417
+ return value;
418
+ },
419
+ text: (value, name) => {
420
+ if (typeof value !== "string") {
421
+ throw fail(`${name} must be a string`);
422
+ }
423
+ return value;
424
+ },
425
+ timestamp: (value, name) => {
426
+ if (typeof value !== "string") {
427
+ throw fail(`${name} must be an exact UTC ISO timestamp`);
428
+ }
429
+ const match = UTC_TIMESTAMP_PATTERN.exec(value);
430
+ const base = match?.[1];
431
+ const fraction = match?.[2] ?? "";
432
+ if (base === void 0) {
433
+ throw fail(`${name} must be an exact UTC ISO timestamp`);
434
+ }
435
+ const parsed = new Date(value);
436
+ const canonical = `${base}.${fraction.padEnd(3, "0")}Z`;
437
+ if (Number.isNaN(parsed.valueOf()) || parsed.toISOString() !== canonical) {
438
+ throw fail(`${name} must be an exact UTC ISO timestamp`);
439
+ }
440
+ return value;
441
+ },
442
+ schemaVersion: (value, name) => {
443
+ if (value !== 1) {
444
+ throw fail(`${name} schemaVersion must be 1`);
445
+ }
446
+ }
447
+ });
448
+ }
449
+
450
+ // packages/contracts/src/work-execution-settings.ts
451
+ var INHERITED_WORK_PROVIDER_EXECUTION_SETTINGS = Object.freeze({ model: null, reasoningEffort: null });
452
+ var fields = createWorkFieldParsers("SCG_WORK_EXECUTION_SETTINGS_INVALID");
453
+
454
+ // packages/contracts/src/work-provider-runtime.ts
455
+ var WORK_PROVIDER_RUNTIME_CODES = [
456
+ "SCG_OMO_RUNTIME_AUTHORITY_ABSENT",
457
+ "SCG_OMO_RUNTIME_UNSUPPORTED",
458
+ "SCG_OMO_RUNTIME_MISSING",
459
+ "SCG_OMO_RUNTIME_INTEGRITY"
460
+ ];
461
+ var WORK_NATIVE_PROVIDER_RUNTIME_CODES = [
462
+ "SCG_RUNTIME_AUTHORITY_ABSENT",
463
+ "SCG_RUNTIME_UNSUPPORTED",
464
+ "SCG_RUNTIME_MISSING",
465
+ "SCG_RUNTIME_INTEGRITY",
466
+ "SCG_RUNTIME_VERSION_MISMATCH",
467
+ "SCG_RUNTIME_CONVERSATION_UNQUALIFIED",
468
+ "SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED"
469
+ ];
470
+ var ALL_RUNTIME_CODES = [
471
+ ...WORK_PROVIDER_RUNTIME_CODES,
472
+ ...WORK_NATIVE_PROVIDER_RUNTIME_CODES
473
+ ];
474
+ var WORK_PROVIDER_RUNTIME_INSTALL_ACTION = "scene-glass omo install";
475
+ var WORK_NATIVE_RUNTIME_INSTALL_ACTIONS = Object.freeze({
476
+ "claude-code": "scene-glass runtime install --provider claude",
477
+ "codex-cli": "scene-glass runtime install --provider codex"
478
+ });
479
+ var WORK_PROVIDER_RUNTIME_READINESS = Object.freeze({
480
+ SCG_OMO_RUNTIME_AUTHORITY_ABSENT: "unavailable",
481
+ SCG_OMO_RUNTIME_UNSUPPORTED: "incompatible",
482
+ SCG_OMO_RUNTIME_MISSING: "missing",
483
+ SCG_OMO_RUNTIME_INTEGRITY: "unavailable",
484
+ SCG_RUNTIME_AUTHORITY_ABSENT: "unavailable",
485
+ SCG_RUNTIME_UNSUPPORTED: "incompatible",
486
+ SCG_RUNTIME_MISSING: "missing",
487
+ SCG_RUNTIME_INTEGRITY: "unavailable",
488
+ SCG_RUNTIME_VERSION_MISMATCH: "incompatible",
489
+ SCG_RUNTIME_CONVERSATION_UNQUALIFIED: "unavailable",
490
+ SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED: "unavailable"
491
+ });
492
+ var runtimeFields = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
493
+ var OMO_CODES = WORK_PROVIDER_RUNTIME_CODES;
494
+ var NATIVE_CODES = WORK_NATIVE_PROVIDER_RUNTIME_CODES;
495
+ var WORK_PROVIDER_RUNTIME_DIAGNOSTIC_SCHEMA = Object.freeze({
496
+ oneOf: [
497
+ {
498
+ type: "object",
499
+ additionalProperties: false,
500
+ required: ["code", "action"],
501
+ properties: {
502
+ code: { enum: OMO_CODES },
503
+ action: { anyOf: [{ const: WORK_PROVIDER_RUNTIME_INSTALL_ACTION }, { type: "null" }] }
504
+ }
505
+ },
506
+ {
507
+ type: "object",
508
+ additionalProperties: false,
509
+ required: ["code", "action", "provider", "version"],
510
+ properties: {
511
+ code: { enum: NATIVE_CODES },
512
+ action: {
513
+ anyOf: [
514
+ { enum: [...Object.values(WORK_NATIVE_RUNTIME_INSTALL_ACTIONS), "start-new-session"] },
515
+ { type: "null" }
516
+ ]
517
+ },
518
+ provider: { enum: ["claude-code", "codex-cli"] },
519
+ version: { anyOf: [{ type: "string" }, { type: "null" }] }
520
+ }
521
+ }
522
+ ]
523
+ });
524
+
525
+ // packages/contracts/src/work-provider-runtime-identity.ts
526
+ var fields2 = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
527
+ var VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u;
528
+ var KEYS = ["provider", "releaseVersion", "tuple", "version", "runtimeId", "binarySha256"];
529
+ var versionSchema = { type: "string", pattern: VERSION.source };
530
+ var digestSchema = { type: "string", pattern: "^(?!0{64}$)[a-f0-9]{64}$" };
531
+ var WORK_PROVIDER_RUNTIME_IDENTITY_SCHEMA = Object.freeze({
532
+ oneOf: [
533
+ {
534
+ type: "object",
535
+ additionalProperties: false,
536
+ required: [...KEYS, "nodeVersion", "senpiVersion"],
537
+ properties: {
538
+ provider: { const: "omo-native" },
539
+ releaseVersion: versionSchema,
540
+ tuple: { enum: ["darwin-arm64", "darwin-x64", "linux-x64-gnu"] },
541
+ version: versionSchema,
542
+ runtimeId: digestSchema,
543
+ binarySha256: digestSchema,
544
+ nodeVersion: versionSchema,
545
+ senpiVersion: versionSchema
546
+ }
547
+ },
548
+ {
549
+ type: "object",
550
+ additionalProperties: false,
551
+ required: KEYS,
552
+ properties: {
553
+ provider: { enum: ["claude-code", "codex-cli"] },
554
+ releaseVersion: versionSchema,
555
+ tuple: { enum: ["darwin-arm64", "darwin-x64", "linux-x64-gnu"] },
556
+ version: versionSchema,
557
+ runtimeId: digestSchema,
558
+ binarySha256: digestSchema
559
+ }
560
+ }
561
+ ]
562
+ });
563
+
564
+ // packages/contracts/src/work-provider-readiness.ts
565
+ var providerFields = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
566
+
567
+ // packages/contracts/src/work-provider-session-warnings.ts
568
+ var providerFields2 = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
569
+
570
+ // packages/contracts/src/work-provider.ts
571
+ var providerFields3 = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
572
+
573
+ // packages/contracts/src/work-provider-capabilities.ts
574
+ var fields3 = createWorkFieldParsers("SCG_WORK_CAPABILITIES_UNAVAILABLE");
575
+
576
+ // packages/contracts/src/work-history.ts
577
+ var fields4 = createWorkFieldParsers("SCG_WORK_HISTORY_INVALID");
578
+
579
+ // packages/contracts/src/work-diff.ts
580
+ var fields5 = createWorkFieldParsers("SCG_WORK_DIFF_INVALID");
581
+
582
+ // packages/contracts/src/work-request-values.ts
583
+ var WORK_TERMINAL_REQUEST_STATES = [
584
+ "completed",
585
+ "failed",
586
+ "cancelled",
587
+ "indeterminate"
588
+ ];
589
+ var WORK_PROVIDER_FAILURE_CAUSES = [
590
+ "SCG_OMO_CONVERSATION_INCOMPATIBLE",
591
+ "SCG_OMO_RUNTIME_AUTHORITY_ABSENT",
592
+ "SCG_OMO_RUNTIME_UNSUPPORTED",
593
+ "SCG_OMO_RUNTIME_MISSING",
594
+ "SCG_OMO_RUNTIME_INTEGRITY",
595
+ "SCG_RUNTIME_AUTHORITY_ABSENT",
596
+ "SCG_RUNTIME_UNSUPPORTED",
597
+ "SCG_RUNTIME_MISSING",
598
+ "SCG_RUNTIME_INTEGRITY",
599
+ "SCG_RUNTIME_VERSION_MISMATCH",
600
+ "SCG_RUNTIME_CONVERSATION_UNQUALIFIED",
601
+ "SCG_RUNTIME_LEGACY_SESSION_RESTART_REQUIRED"
602
+ ];
603
+ var WORK_ERROR_CODES = [
604
+ "SCG_WORK_REQUEST_INVALID",
605
+ "SCG_WORK_PROVIDER_INVALID",
606
+ "SCG_WORK_EXECUTION_SETTINGS_INVALID",
607
+ "SCG_WORK_CAPABILITIES_UNAVAILABLE",
608
+ "SCG_WORK_HISTORY_INVALID",
609
+ "SCG_WORK_DIFF_INVALID",
610
+ "SCG_WORK_LIMIT_EXCEEDED",
611
+ "SCG_WORK_PROVIDER_NONE",
612
+ "SCG_WORK_PROVIDER_UNREADY",
613
+ "SCG_WORK_WARNING_REQUIRED",
614
+ "SCG_WORK_GENERATION_CONFLICT",
615
+ "SCG_WORK_ACTIVE",
616
+ "SCG_WORK_STALE_PREVIEW",
617
+ "SCG_WORK_NO_ELIGIBLE",
618
+ "SCG_WORK_NOT_FOUND",
619
+ "SCG_WORK_CANCELLED",
620
+ "SCG_WORK_INDETERMINATE",
621
+ ...WORK_PROVIDER_FAILURE_CAUSES
622
+ ];
623
+
624
+ // packages/contracts/src/work-requests.ts
625
+ var TERMINAL_STATES = new Set(WORK_TERMINAL_REQUEST_STATES);
626
+ var fields6 = createWorkFieldParsers("SCG_WORK_REQUEST_INVALID");
627
+
628
+ // packages/contracts/src/work-provider-inputs.ts
629
+ var providerFields4 = createWorkFieldParsers("SCG_WORK_PROVIDER_INVALID");
630
+
631
+ // packages/devtools/src/vite/runtime-authority.ts
632
+ var DESCRIPTOR_RELATIVE_PATH = ".scg/runtime/host-descriptor.v1.json";
633
+ var LOADER_URL = "http://127.0.0.1:4175/scene-glass-loader.js";
634
+ var DESCRIPTOR_MAX_BYTES = 1024 * 1024;
635
+ var CREDENTIAL_MAX_BYTES = 8 * 1024;
636
+ var RELEASE_MANIFEST_MAX_BYTES = 64 * 1024;
637
+ var DECIMAL_IDENTITY = /^(?:0|[1-9][0-9]{0,19})$/;
638
+ var PROJECT_ID = /^[a-z0-9][a-z0-9_-]{0,127}$/;
639
+ var INSTALL_ID = /^[A-Za-z0-9_-]{1,128}$/;
640
+ var TOKEN = /^[A-Za-z0-9_-]{43}$/;
641
+ var DESCRIPTOR_KEYS = Object.freeze([
642
+ "schemaVersion",
643
+ "viteVersion",
644
+ "framework",
645
+ "frameworkVersion",
646
+ "frameworkPluginVersion",
647
+ "projectId",
648
+ "rootTemplate",
649
+ "loaderUrl",
650
+ "host",
651
+ "port",
652
+ "credentialProjectId",
653
+ "credentialKey",
654
+ "navigation",
655
+ "readinessPath",
656
+ "approvedRootIdentity",
657
+ "credentialAuthorities",
658
+ "installId"
659
+ ]);
660
+ function loadViteRuntimeAuthority(root) {
661
+ return loadViteRuntimeAuthorityWithLoader(root, LOADER_URL);
662
+ }
663
+ async function loadViteRuntimeAuthorityWithLoader(root, loaderUrl) {
664
+ const canonicalRoot = await realpath(root);
665
+ const rootStats = await stat(canonicalRoot, { bigint: true });
666
+ if (!rootStats.isDirectory() || rootStats.uid !== currentUid()) {
667
+ throw new Error("runtime root authority is invalid");
668
+ }
669
+ const descriptorBytes = await secureReadRegularFile(
670
+ join(canonicalRoot, DESCRIPTOR_RELATIVE_PATH),
671
+ DESCRIPTOR_MAX_BYTES
672
+ );
673
+ let descriptor;
674
+ try {
675
+ descriptor = parseDescriptor(descriptorBytes, identity(rootStats), loaderUrl);
676
+ } finally {
677
+ descriptorBytes.fill(0);
678
+ }
679
+ const canonicalCredentialPath = await realpath(descriptor.credentialAuthority.path);
680
+ const rootRelativeCredential = relative(canonicalRoot, canonicalCredentialPath);
681
+ if (canonicalCredentialPath !== descriptor.credentialAuthority.path || rootRelativeCredential === "" || rootRelativeCredential === ".." || rootRelativeCredential.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(rootRelativeCredential) || dirname(canonicalCredentialPath) !== canonicalRoot) {
682
+ throw new Error("credential path authority is invalid");
683
+ }
684
+ const credentialBytes = await secureReadRegularFile(
685
+ canonicalCredentialPath,
686
+ CREDENTIAL_MAX_BYTES,
687
+ descriptor.credentialAuthority
688
+ );
689
+ try {
690
+ return Object.freeze({
691
+ loaderUrl: descriptor.loaderUrl,
692
+ origin: `http://127.0.0.1:${descriptor.port}`,
693
+ projectId: descriptor.projectId,
694
+ token: parseCredentialToken(credentialBytes, descriptor)
695
+ });
696
+ } finally {
697
+ credentialBytes.fill(0);
698
+ }
699
+ }
700
+ async function loadVitePremiumArtifactAuthority(moduleUrl) {
701
+ let manifestBytes;
702
+ let moduleBytes;
703
+ let stylesheetBytes;
704
+ try {
705
+ const packageRoot = await realpath(resolve(dirname(fileURLToPath(moduleUrl)), ".."));
706
+ manifestBytes = await secureReadPackageFile(
707
+ join(packageRoot, "release-manifest.json"),
708
+ RELEASE_MANIFEST_MAX_BYTES
709
+ );
710
+ const serialized = new TextDecoder("utf-8", { fatal: true }).decode(manifestBytes);
711
+ const manifestValue = JSON.parse(serialized);
712
+ const manifest = parseSceneGlassReleaseManifestV1(manifestValue);
713
+ if (`${JSON.stringify(manifest, null, 2)}
714
+ ` !== serialized) {
715
+ throw new Error("release manifest serialization is invalid");
716
+ }
717
+ const artifact = manifest.artifacts.premiumMeasurement;
718
+ const modulePath = packageArtifactPath(packageRoot, artifact.module.path);
719
+ const stylesheetPath = packageArtifactPath(packageRoot, artifact.stylesheet.path);
720
+ moduleBytes = await secureReadPackageFile(modulePath, artifact.module.maxBytes);
721
+ stylesheetBytes = await secureReadPackageFile(stylesheetPath, artifact.stylesheet.maxBytes);
722
+ if (`sha256:${createHash("sha256").update(moduleBytes).digest("hex")}` !== artifact.module.sha256 || `sha256:${createHash("sha256").update(stylesheetBytes).digest("hex")}` !== artifact.stylesheet.sha256) {
723
+ throw new Error("premium artifact pair digest is invalid");
724
+ }
725
+ validatePremiumModuleText(moduleBytes);
726
+ validatePremiumStylesheetText(stylesheetBytes);
727
+ return Object.freeze({
728
+ artifact,
729
+ manifestDigest: `sha256:${createHash("sha256").update(manifestBytes).digest("hex")}`
730
+ });
731
+ } finally {
732
+ manifestBytes?.fill(0);
733
+ moduleBytes?.fill(0);
734
+ stylesheetBytes?.fill(0);
735
+ }
736
+ }
737
+ function probeViteRuntime(loaderUrl) {
738
+ return loaderUrl === LOADER_URL ? probeLoader(loaderUrl) : Promise.resolve(false);
739
+ }
740
+ async function probeLoader(loaderUrl) {
741
+ try {
742
+ const response = await fetch(loaderUrl, {
743
+ method: "HEAD",
744
+ cache: "no-store",
745
+ credentials: "omit",
746
+ redirect: "error",
747
+ signal: AbortSignal.timeout(1500)
748
+ });
749
+ return response.status === 200 && response.headers.get("content-type")?.toLowerCase().startsWith("application/javascript") === true;
750
+ } catch {
751
+ return false;
752
+ }
753
+ }
754
+ async function secureReadPackageFile(path, maximumBytes) {
755
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
756
+ try {
757
+ const before = await handle.stat({ bigint: true });
758
+ if (!before.isFile() || before.nlink !== 1n || before.uid !== currentUid() || (before.mode & 0o022n) !== 0n || before.size < 1n || before.size > BigInt(maximumBytes)) {
759
+ throw new Error("package artifact authority is invalid");
760
+ }
761
+ const bytes = await handle.readFile();
762
+ const after = await handle.stat({ bigint: true });
763
+ if (bytes.byteLength !== Number(before.size) || !sameIdentity(identity(before), identity(after)) || before.mode !== after.mode || before.nlink !== after.nlink || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) {
764
+ bytes.fill(0);
765
+ throw new Error("package artifact changed during secure read");
766
+ }
767
+ return bytes;
768
+ } finally {
769
+ await handle.close();
770
+ }
771
+ }
772
+ function packageArtifactPath(root, relativePath) {
773
+ const path = resolve(root, relativePath);
774
+ const fromRoot = relative(root, path);
775
+ if (fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
776
+ throw new Error("premium artifact escaped the package root");
777
+ }
778
+ return path;
779
+ }
780
+ function containsSourceMapDirective(source) {
781
+ const normalized = source.toLowerCase();
782
+ let offset = normalized.indexOf("source");
783
+ while (offset !== -1) {
784
+ if (normalized.startsWith("url=", offset + 6) || normalized.charCodeAt(offset + 6) === 109 && normalized.startsWith("appingurl", offset + 7)) {
785
+ return true;
786
+ }
787
+ offset = normalized.indexOf("source", offset + 1);
788
+ }
789
+ return false;
790
+ }
791
+ function validatePremiumModuleText(bytes) {
792
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
793
+ if (source.length === 0 || source.includes("\0") || /\bimport(?![A-Za-z0-9_$])/u.test(source) || /\bexport\b[^;]{0,1024}\bfrom\s*["']/u.test(source) || containsSourceMapDirective(source) || /(?:https?:|blob:|data:)/iu.test(source) || /scg-premium-measurement-styles|\[data-scg-premium-measurement|createElement\(["']style["']/u.test(
794
+ source
795
+ )) {
796
+ throw new Error("premium module source is invalid");
797
+ }
798
+ }
799
+ function validatePremiumStylesheetText(bytes) {
800
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
801
+ if (source.length === 0 || source.includes("\0") || source.split("\n").filter((line) => line.length > 0).length > 1 || containsSourceMapDirective(source) || /@import|url\s*\(|(?:https?:|blob:|data:)/iu.test(source) || !source.includes("[data-scg-premium-measurement=true]") || !/\.scg-meas(?:ure)-layer/u.test(source) || !/\.scg-si(?:ze)-layer/u.test(source)) {
802
+ throw new Error("premium stylesheet source is invalid");
803
+ }
804
+ }
805
+ async function secureReadRegularFile(path, maximumBytes, expectedIdentity) {
806
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
807
+ try {
808
+ const before = await handle.stat({ bigint: true });
809
+ if (!before.isFile() || before.uid !== currentUid() || (before.mode & 0o077n) !== 0n || before.size < 1n || before.size > BigInt(maximumBytes) || expectedIdentity !== void 0 && !sameIdentity(identity(before), expectedIdentity)) {
810
+ throw new Error("runtime file authority is invalid");
811
+ }
812
+ const bytes = await handle.readFile();
813
+ const after = await handle.stat({ bigint: true });
814
+ if (bytes.byteLength !== Number(before.size) || !sameIdentity(identity(before), identity(after)) || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) {
815
+ bytes.fill(0);
816
+ throw new Error("runtime file changed during secure read");
817
+ }
818
+ return bytes;
819
+ } finally {
820
+ await handle.close();
821
+ }
822
+ }
823
+ function parseDescriptor(bytes, rootIdentity, expectedLoaderUrl) {
824
+ const serialized = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
825
+ const value = JSON.parse(serialized);
826
+ const record = exactRecord2(value, DESCRIPTOR_KEYS);
827
+ if (`${JSON.stringify(record, null, 2)}
828
+ ` !== serialized) {
829
+ throw new Error("descriptor serialization is not canonical");
830
+ }
831
+ const approvedRootIdentity = parseIdentity(record.approvedRootIdentity);
832
+ const authorities = record.credentialAuthorities;
833
+ const framework = record.framework;
834
+ const frameworkVersionsValid = framework === "vue3" && isVersion(record.frameworkVersion, 3) && isVersion(record.frameworkPluginVersion, 6) || framework === "react" && isVersion(record.frameworkVersion, 19) && isVersion(record.frameworkPluginVersion, 5);
835
+ if (record.schemaVersion !== 1 || record.viteVersion !== "7.3.6" || !frameworkVersionsValid || !PROJECT_ID.test(asString(record.projectId)) || record.rootTemplate !== "index.html" || record.loaderUrl !== expectedLoaderUrl || record.host !== "127.0.0.1" || !isValidPort(record.port) || record.credentialProjectId !== record.projectId || record.credentialKey !== "SCENE_GLASS_HOST_TOKEN" || record.navigation !== "spa" || record.readinessPath !== "/__scene-glass/ready" || !sameIdentity(approvedRootIdentity, rootIdentity) || !Array.isArray(authorities) || authorities.length !== 1 || !Object.hasOwn(authorities, 0) || !INSTALL_ID.test(asString(record.installId))) {
836
+ throw new Error("descriptor authority is invalid");
837
+ }
838
+ const authorityRecord = exactRecord2(authorities[0], ["projectId", "path", "device", "inode"]);
839
+ const authorityDevice = asString(authorityRecord.device);
840
+ const authorityInode = asString(authorityRecord.inode);
841
+ const authority = Object.freeze({
842
+ projectId: asString(authorityRecord.projectId),
843
+ path: asString(authorityRecord.path),
844
+ device: authorityDevice,
845
+ inode: authorityInode
846
+ });
847
+ if (authority.projectId !== record.projectId || !isCanonicalAbsolutePath(authority.path) || !isDecimalIdentity(authorityDevice) || !isDecimalIdentity(authorityInode)) {
848
+ throw new Error("credential authority is invalid");
849
+ }
850
+ return Object.freeze({
851
+ projectId: asString(record.projectId),
852
+ loaderUrl: expectedLoaderUrl,
853
+ credentialProjectId: asString(record.credentialProjectId),
854
+ credentialKey: "SCENE_GLASS_HOST_TOKEN",
855
+ approvedRootIdentity,
856
+ credentialAuthority: authority,
857
+ port: Number(record.port)
858
+ });
859
+ }
860
+ function parseCredentialToken(bytes, descriptor) {
861
+ const prefix = `VITE_SCENE_GLASS_LOADER_URL=${descriptor.loaderUrl}
862
+ VITE_SCENE_GLASS_PROJECT_ID=${descriptor.projectId}
863
+ VITE_SCENE_GLASS_PROJECT_TOKEN=`;
864
+ const suffix = `
865
+ ${descriptor.credentialKey}=`;
866
+ const serialized = bytes.toString("ascii");
867
+ if (!serialized.startsWith(prefix) || !serialized.endsWith("\n")) {
868
+ throw new Error("credential envelope is invalid");
869
+ }
870
+ const payload = serialized.slice(prefix.length, -1);
871
+ const separator = payload.indexOf(suffix);
872
+ if (separator !== 43 || payload.indexOf(suffix, separator + 1) !== -1) {
873
+ throw new Error("credential envelope is invalid");
874
+ }
875
+ const first = payload.slice(0, separator);
876
+ const second = payload.slice(separator + suffix.length);
877
+ if (first !== second || !TOKEN.test(first) || !hasCanonicalBase64UrlTail(first)) {
878
+ throw new Error("credential token is invalid");
879
+ }
880
+ return first;
881
+ }
882
+ function hasCanonicalBase64UrlTail(value) {
883
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
884
+ const finalSextet = alphabet.indexOf(value.at(-1) ?? "");
885
+ return finalSextet >= 0 && (finalSextet & 3) === 0;
886
+ }
887
+ function exactRecord2(value, keys) {
888
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
889
+ throw new Error("runtime authority record is invalid");
890
+ }
891
+ const prototype = Object.getPrototypeOf(value);
892
+ const actualKeys = Reflect.ownKeys(value);
893
+ if (prototype !== Object.prototype && prototype !== null) {
894
+ throw new Error("runtime authority record is invalid");
895
+ }
896
+ if (actualKeys.length !== keys.length || actualKeys.some((key, index) => key !== keys[index])) {
897
+ throw new Error("runtime authority record is invalid");
898
+ }
899
+ const record = {};
900
+ for (const key of keys) {
901
+ const property = Object.getOwnPropertyDescriptor(value, key);
902
+ if (property === void 0 || property.enumerable !== true || !Object.hasOwn(property, "value")) {
903
+ throw new Error("runtime authority record is invalid");
904
+ }
905
+ const propertyValue = property.value;
906
+ record[key] = propertyValue;
907
+ }
908
+ return Object.freeze(record);
909
+ }
910
+ function parseIdentity(value) {
911
+ const record = exactRecord2(value, ["device", "inode"]);
912
+ const device = asString(record.device);
913
+ const inode = asString(record.inode);
914
+ if (!isDecimalIdentity(device) || !isDecimalIdentity(inode)) {
915
+ throw new Error("file identity is invalid");
916
+ }
917
+ return Object.freeze({ device, inode });
918
+ }
919
+ function isDecimalIdentity(value) {
920
+ return DECIMAL_IDENTITY.test(value) && BigInt(value) <= 18446744073709551615n;
921
+ }
922
+ function identity(value) {
923
+ return Object.freeze({ device: String(value.dev), inode: String(value.ino) });
924
+ }
925
+ function sameIdentity(left, right) {
926
+ return left.device === right.device && left.inode === right.inode;
927
+ }
928
+ function isVersion(value, major) {
929
+ return typeof value === "string" && new RegExp(`^${major}\\.[0-9]+\\.[0-9]+$`).test(value);
930
+ }
931
+ function isValidPort(value) {
932
+ return Number.isInteger(value) && Number(value) >= 1024 && Number(value) <= 65535 && value !== 4175;
933
+ }
934
+ function asString(value) {
935
+ return typeof value === "string" ? value : "";
936
+ }
937
+ function isCanonicalAbsolutePath(value) {
938
+ if (!isAbsolute(value) || value.includes("\0")) return false;
939
+ const segments = value.slice(1).split("/");
940
+ return !segments.some((segment) => segment === "" || segment === "." || segment === "..");
941
+ }
942
+ function currentUid() {
943
+ const getuid = process.getuid;
944
+ if (getuid === void 0) throw new Error("owner identity is unavailable");
945
+ return BigInt(getuid.call(process));
946
+ }
947
+
948
+ // packages/devtools/src/vite/plugin.ts
949
+ import { createHash as createHash2 } from "node:crypto";
950
+ var PLUGIN_NAME = "scene-glass:dev-only";
951
+ var WARNING = "[scene-glass] runtime unavailable; development injection disabled.";
952
+ var LOADER_MARKER = "data-scg-project=";
953
+ var MAX_LOADER_BYTES = 4 * 1024 * 1024;
954
+ var MAX_MCP_BYTES = 1024 * 1024;
955
+ var JAVASCRIPT_MEDIA_TYPE = "application/javascript; charset=utf-8";
956
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
957
+ var DIAGNOSTIC_SESSION_ID_PATTERN = /^diagnostic-session-[A-Za-z0-9_-]{22}$/u;
958
+ var BROWSER_SESSION_ALIAS_PREFIX = "scene-glass-vite-proxy-v1-";
959
+ var DIAGNOSTIC_ALIAS_HEADER = "x-scene-glass-diagnostic-alias";
960
+ var DIAGNOSTIC_ALIAS_PREFIX = "scene-glass-vite-diagnostic-v1-";
961
+ var DIAGNOSTIC_SESSION_ALIAS_PREFIX = "scene-glass-vite-diagnostic-session-v1-";
962
+ var DIAGNOSTIC_RUN_ID_PATTERN = /^diagnostic-[A-Za-z0-9_-]{22}$/u;
963
+ var MAX_VITE_BROWSER_SESSIONS = 32;
964
+ var SCENE_GLASS_VITE_PATHS = Object.freeze({
965
+ loader: "/@scene-glass/loader.js",
966
+ mcp: "/@scene-glass/mcp",
967
+ diagnosticRuns: "/@scene-glass/diagnostic-runs",
968
+ premiumMeasurement: "/@scene-glass/premium/measurement-v1.js",
969
+ premiumMeasurementStylesheet: "/@scene-glass/premium/measurement-v1.css"
970
+ });
971
+ function createSceneGlassPlugin(authoritySource) {
972
+ let authority;
973
+ let boundary;
974
+ let warned = false;
975
+ return {
976
+ name: PLUGIN_NAME,
977
+ apply: "serve",
978
+ async configureServer(server) {
979
+ try {
980
+ const [candidate, premiumArtifact] = await Promise.all([
981
+ authoritySource.load(server.config.root),
982
+ loadVitePremiumArtifactAuthority(authoritySource.artifactModuleUrl)
983
+ ]);
984
+ if (!await authoritySource.probe(candidate.loaderUrl)) {
985
+ warnOnce();
986
+ return;
987
+ }
988
+ authority = candidate;
989
+ boundary = createViteRuntimeBoundary(
990
+ candidate,
991
+ premiumArtifact,
992
+ authoritySource.runtimeOrigin
993
+ );
994
+ server.middlewares.use((request, response, next) => {
995
+ const activeBoundary = boundary;
996
+ if (activeBoundary?.handles(request.url) === true) {
997
+ void activeBoundary.handle(request, response).catch(() => {
998
+ if (!response.headersSent) sendEmpty(response, 503);
999
+ else response.destroy();
1000
+ });
1001
+ return;
1002
+ }
1003
+ if (isHtmlNavigation(request.url, request.headers.accept)) {
1004
+ const setHeader = response.setHeader.bind(response);
1005
+ response.setHeader = (name, value) => setHeader(name, name.toLowerCase() === "cache-control" ? "no-store" : value);
1006
+ response.setHeader("Cache-Control", "no-store");
1007
+ if (hasInitialCouponQuery(request.url)) {
1008
+ response.setHeader("Referrer-Policy", "no-referrer");
1009
+ }
1010
+ }
1011
+ next();
1012
+ });
1013
+ } catch {
1014
+ authority = void 0;
1015
+ boundary = void 0;
1016
+ warnOnce();
1017
+ }
1018
+ function warnOnce() {
1019
+ if (warned) return;
1020
+ warned = true;
1021
+ server.config.logger.warn(WARNING);
1022
+ }
1023
+ },
1024
+ transformIndexHtml(html) {
1025
+ if (authority === void 0 || alreadyInjected(html)) {
1026
+ return html;
1027
+ }
1028
+ const referrerPolicy = {
1029
+ tag: "meta",
1030
+ attrs: {
1031
+ name: "referrer",
1032
+ content: "no-referrer"
1033
+ },
1034
+ injectTo: "head-prepend"
1035
+ };
1036
+ const loader = {
1037
+ tag: "script",
1038
+ attrs: {
1039
+ src: SCENE_GLASS_VITE_PATHS.loader,
1040
+ referrerpolicy: "no-referrer",
1041
+ "data-scg-project": authority.projectId,
1042
+ "data-scg-navigation": "spa"
1043
+ },
1044
+ injectTo: "head-prepend"
1045
+ };
1046
+ return { html, tags: [referrerPolicy, loader] };
1047
+ }
1048
+ };
1049
+ }
1050
+ function createViteRuntimeBoundary(authority, premiumAuthority, runtimeOrigin) {
1051
+ const artifact = premiumAuthority.artifact;
1052
+ let activeSessionId = null;
1053
+ let activeSessionAlias = null;
1054
+ let nextSessionAlias = 0;
1055
+ let nextDiagnosticAlias = 0;
1056
+ let nextDiagnosticSessionAlias = 0;
1057
+ const sessionIds = /* @__PURE__ */ new Map();
1058
+ const diagnosticAuthorities = /* @__PURE__ */ new Map();
1059
+ const diagnosticSessions = /* @__PURE__ */ new Map();
1060
+ const projectPath = encodeURIComponent(authority.projectId);
1061
+ const upstream = Object.freeze({
1062
+ loader: authority.loaderUrl,
1063
+ mcp: `${runtimeOrigin}/mcp/v1/projects/${projectPath}`,
1064
+ diagnosticRuns: `${runtimeOrigin}/mcp/v1/projects/${projectPath}/diagnostic-runs`,
1065
+ premiumMeasurement: `${runtimeOrigin}/${artifact.module.path}`,
1066
+ premiumMeasurementStylesheet: `${runtimeOrigin}/${artifact.stylesheet.path}`
1067
+ });
1068
+ const removeDiagnosticAuthority = (diagnosticAlias) => {
1069
+ diagnosticAuthorities.delete(diagnosticAlias);
1070
+ for (const [sessionAlias, session] of diagnosticSessions) {
1071
+ if (session.diagnosticAlias === diagnosticAlias) diagnosticSessions.delete(sessionAlias);
1072
+ }
1073
+ };
1074
+ const pruneDiagnosticAuthorities = () => {
1075
+ const now = Date.now();
1076
+ for (const [diagnosticAlias, diagnosticAuthority] of diagnosticAuthorities) {
1077
+ if (diagnosticAuthority.expiresAt <= now) removeDiagnosticAuthority(diagnosticAlias);
1078
+ }
1079
+ };
1080
+ const handleMainMcp = async (request, response) => {
1081
+ const browserSession = singleHeader(request.headers["mcp-session-id"]);
1082
+ const upstreamSessionId = browserSession === void 0 ? void 0 : sessionIds.get(browserSession);
1083
+ if (browserSession !== void 0 && upstreamSessionId === void 0 || browserSession === void 0 && request.method === "DELETE" || browserSession === void 0 && sessionIds.size >= MAX_VITE_BROWSER_SESSIONS) {
1084
+ sendEmpty(response, 404);
1085
+ return;
1086
+ }
1087
+ const responseSessionAlias = browserSession ?? `${BROWSER_SESSION_ALIAS_PREFIX}${String(++nextSessionAlias)}`;
1088
+ const nextSession = await proxyJsonRequest({
1089
+ request,
1090
+ response,
1091
+ target: upstream.mcp,
1092
+ token: authority.token,
1093
+ origin: authority.origin,
1094
+ responseSessionAlias,
1095
+ ...upstreamSessionId === void 0 ? {} : { upstreamSessionId }
1096
+ });
1097
+ if (nextSession !== void 0) {
1098
+ sessionIds.set(responseSessionAlias, nextSession);
1099
+ activeSessionAlias = responseSessionAlias;
1100
+ activeSessionId = nextSession;
1101
+ }
1102
+ if (request.method === "DELETE" && browserSession !== void 0 && response.statusCode >= 200 && response.statusCode < 300) {
1103
+ sessionIds.delete(browserSession);
1104
+ if (activeSessionAlias === browserSession) {
1105
+ const fallback = [...sessionIds.entries()].at(-1);
1106
+ activeSessionAlias = fallback?.[0] ?? null;
1107
+ activeSessionId = fallback?.[1] ?? null;
1108
+ }
1109
+ }
1110
+ };
1111
+ const handleDiagnosticMcp = async (request, response, diagnosticAlias) => {
1112
+ pruneDiagnosticAuthorities();
1113
+ const diagnosticAuthority = diagnosticAuthorities.get(diagnosticAlias);
1114
+ const browserSession = singleHeader(request.headers["mcp-session-id"]);
1115
+ const diagnosticSession = browserSession === void 0 ? void 0 : diagnosticSessions.get(browserSession);
1116
+ if (diagnosticAuthority === void 0 || browserSession !== void 0 && (diagnosticSession === void 0 || diagnosticSession.diagnosticAlias !== diagnosticAlias) || browserSession === void 0 && request.method === "DELETE" || browserSession === void 0 && diagnosticSessions.size >= MAX_VITE_BROWSER_SESSIONS) {
1117
+ sendEmpty(response, 404);
1118
+ return;
1119
+ }
1120
+ const responseSessionAlias = browserSession ?? `${DIAGNOSTIC_SESSION_ALIAS_PREFIX}${String(++nextDiagnosticSessionAlias)}`;
1121
+ const nextSession = await proxyJsonRequest({
1122
+ request,
1123
+ response,
1124
+ target: upstream.mcp,
1125
+ token: diagnosticAuthority.token,
1126
+ origin: authority.origin,
1127
+ responseSessionAlias,
1128
+ ...diagnosticSession === void 0 ? {} : { upstreamSessionId: diagnosticSession.upstreamSessionId },
1129
+ upstreamSessionIdPattern: DIAGNOSTIC_SESSION_ID_PATTERN
1130
+ });
1131
+ if (nextSession !== void 0) {
1132
+ diagnosticSessions.set(
1133
+ responseSessionAlias,
1134
+ Object.freeze({ diagnosticAlias, upstreamSessionId: nextSession })
1135
+ );
1136
+ }
1137
+ if (request.method === "DELETE" && browserSession !== void 0 && response.statusCode >= 200 && response.statusCode < 300) {
1138
+ removeDiagnosticAuthority(diagnosticAlias);
1139
+ }
1140
+ };
1141
+ return Object.freeze({
1142
+ handles(url) {
1143
+ return typeof url === "string" && url.startsWith("/@scene-glass/");
1144
+ },
1145
+ async handle(request, response) {
1146
+ const path = exactRequestPath(request.url);
1147
+ if (path === void 0 || !hasBrowserAuthority(request, authority, path)) {
1148
+ sendEmpty(response, 404);
1149
+ return;
1150
+ }
1151
+ if (path === SCENE_GLASS_VITE_PATHS.loader) {
1152
+ await serveLoader(request, response, upstream.loader);
1153
+ return;
1154
+ }
1155
+ if (path === SCENE_GLASS_VITE_PATHS.mcp) {
1156
+ const rawDiagnosticAlias = request.headers[DIAGNOSTIC_ALIAS_HEADER];
1157
+ const diagnosticAlias = singleHeader(rawDiagnosticAlias);
1158
+ if (rawDiagnosticAlias !== void 0 && diagnosticAlias === void 0) {
1159
+ sendEmpty(response, 404);
1160
+ return;
1161
+ }
1162
+ if (diagnosticAlias === void 0) await handleMainMcp(request, response);
1163
+ else await handleDiagnosticMcp(request, response, diagnosticAlias);
1164
+ return;
1165
+ }
1166
+ if (path === SCENE_GLASS_VITE_PATHS.diagnosticRuns) {
1167
+ pruneDiagnosticAuthorities();
1168
+ if (diagnosticAuthorities.size >= MAX_VITE_BROWSER_SESSIONS) {
1169
+ sendEmpty(response, 429);
1170
+ return;
1171
+ }
1172
+ const diagnosticAlias = `${DIAGNOSTIC_ALIAS_PREFIX}${String(++nextDiagnosticAlias)}`;
1173
+ const issued = await issueDiagnosticRun({
1174
+ alias: diagnosticAlias,
1175
+ browserMcpEndpoint: `${authority.origin}${SCENE_GLASS_VITE_PATHS.mcp}`,
1176
+ origin: authority.origin,
1177
+ request,
1178
+ response,
1179
+ target: upstream.diagnosticRuns,
1180
+ token: authority.token,
1181
+ upstreamMcpEndpoint: upstream.mcp
1182
+ });
1183
+ if (issued !== void 0) diagnosticAuthorities.set(diagnosticAlias, issued);
1184
+ return;
1185
+ }
1186
+ if (path === SCENE_GLASS_VITE_PATHS.premiumMeasurement || path === SCENE_GLASS_VITE_PATHS.premiumMeasurementStylesheet) {
1187
+ if (request.method !== "GET" || activeSessionId === null) {
1188
+ sendEmpty(response, 404);
1189
+ return;
1190
+ }
1191
+ const moduleRequest = path === SCENE_GLASS_VITE_PATHS.premiumMeasurement;
1192
+ await servePremiumArtifact({
1193
+ artifact: moduleRequest ? artifact.module : artifact.stylesheet,
1194
+ kind: moduleRequest ? "module" : "stylesheet",
1195
+ manifestDigest: premiumAuthority.manifestDigest,
1196
+ premium: artifact,
1197
+ origin: authority.origin,
1198
+ projectId: authority.projectId,
1199
+ request,
1200
+ response,
1201
+ sessionId: activeSessionId,
1202
+ target: moduleRequest ? upstream.premiumMeasurement : upstream.premiumMeasurementStylesheet,
1203
+ token: authority.token
1204
+ });
1205
+ return;
1206
+ }
1207
+ sendEmpty(response, 404);
1208
+ }
1209
+ });
1210
+ }
1211
+ function exactRequestPath(url) {
1212
+ if (url === void 0 || url.includes("?") || url.includes("#")) return void 0;
1213
+ try {
1214
+ const parsed = new URL(url, "http://127.0.0.1");
1215
+ return parsed.pathname === url ? parsed.pathname : void 0;
1216
+ } catch {
1217
+ return void 0;
1218
+ }
1219
+ }
1220
+ function hasBrowserAuthority(request, authority, path) {
1221
+ if (singleHeader(request.headers.host) !== authority.origin.slice("http://".length) || request.headers.authorization !== void 0 || request.headers["x-scene-glass-project-id"] !== void 0 || path !== SCENE_GLASS_VITE_PATHS.mcp && request.headers[DIAGNOSTIC_ALIAS_HEADER] !== void 0) {
1222
+ return false;
1223
+ }
1224
+ if (path === SCENE_GLASS_VITE_PATHS.loader && (request.method === "GET" || request.method === "HEAD")) {
1225
+ return true;
1226
+ }
1227
+ const origin = singleHeader(request.headers.origin);
1228
+ const referer = singleHeader(request.headers.referer);
1229
+ const fetchSite = singleHeader(request.headers["sec-fetch-site"]);
1230
+ const noReferrerPremiumFetch = (path === SCENE_GLASS_VITE_PATHS.premiumMeasurement || path === SCENE_GLASS_VITE_PATHS.premiumMeasurementStylesheet) && origin === void 0 && referer === void 0 && fetchSite === "same-origin" && singleHeader(request.headers["sec-fetch-mode"]) === "cors" && singleHeader(request.headers["sec-fetch-dest"]) === "empty";
1231
+ return noReferrerPremiumFetch || (origin === authority.origin || referer?.startsWith(`${authority.origin}/`) === true) && (fetchSite === void 0 || fetchSite === "same-origin");
1232
+ }
1233
+ async function serveLoader(request, response, target) {
1234
+ if (request.method !== "GET" && request.method !== "HEAD") {
1235
+ sendEmpty(response, 405);
1236
+ return;
1237
+ }
1238
+ const controller = requestAbortController(request, response);
1239
+ const upstream = await fetch(target, {
1240
+ method: request.method,
1241
+ cache: "no-store",
1242
+ credentials: "omit",
1243
+ redirect: "error",
1244
+ signal: controller.signal
1245
+ });
1246
+ if (upstream.status !== 200 || !upstream.ok || upstream.redirected || upstream.url !== target || upstream.headers.get("content-type") !== JAVASCRIPT_MEDIA_TYPE) {
1247
+ await cancelBody(upstream);
1248
+ sendEmpty(response, 503);
1249
+ return;
1250
+ }
1251
+ const bytes = request.method === "HEAD" ? Buffer.alloc(0) : await readBoundedResponse(upstream, MAX_LOADER_BYTES, false);
1252
+ response.statusCode = 200;
1253
+ response.setHeader("cache-control", "no-store");
1254
+ response.setHeader("content-type", JAVASCRIPT_MEDIA_TYPE);
1255
+ response.setHeader("x-content-type-options", "nosniff");
1256
+ if (request.method === "HEAD") {
1257
+ response.end();
1258
+ return;
1259
+ }
1260
+ response.setHeader("content-length", String(bytes.byteLength));
1261
+ sendBytes(response, bytes);
1262
+ }
1263
+ async function proxyJsonRequest(input) {
1264
+ const method = input.request.method;
1265
+ if (method !== "POST" && method !== "DELETE") {
1266
+ sendEmpty(input.response, 405);
1267
+ return void 0;
1268
+ }
1269
+ const body = method === "POST" ? await readBoundedRequest(input.request, MAX_MCP_BYTES) : void 0;
1270
+ const requestBody = body === void 0 ? void 0 : new Uint8Array(body);
1271
+ const controller = requestAbortController(input.request, input.response);
1272
+ try {
1273
+ const headers = {
1274
+ accept: singleHeader(input.request.headers.accept) ?? "application/json",
1275
+ authorization: `Bearer ${input.token}`,
1276
+ origin: input.origin
1277
+ };
1278
+ copyRequestHeader(input.request, headers, "content-type");
1279
+ copyRequestHeader(input.request, headers, "mcp-protocol-version");
1280
+ if (input.upstreamSessionId !== void 0) {
1281
+ headers["mcp-session-id"] = input.upstreamSessionId;
1282
+ }
1283
+ const upstream = await fetch(input.target, {
1284
+ method,
1285
+ cache: "no-store",
1286
+ credentials: "omit",
1287
+ headers,
1288
+ redirect: "error",
1289
+ signal: controller.signal,
1290
+ ...requestBody === void 0 ? {} : { body: requestBody }
1291
+ });
1292
+ if (upstream.redirected || upstream.url !== input.target) {
1293
+ await cancelBody(upstream);
1294
+ sendEmpty(input.response, 502);
1295
+ return void 0;
1296
+ }
1297
+ const bytes = await readBoundedResponse(upstream, MAX_MCP_BYTES, true);
1298
+ input.response.statusCode = upstream.status;
1299
+ for (const name of ["cache-control", "content-type", "www-authenticate"]) {
1300
+ const value = upstream.headers.get(name);
1301
+ if (value !== null) input.response.setHeader(name, value);
1302
+ }
1303
+ const sessionId = upstream.headers.get("mcp-session-id");
1304
+ const validSessionId = sessionId !== null && (input.upstreamSessionIdPattern ?? SESSION_ID_PATTERN).test(sessionId) ? sessionId : void 0;
1305
+ if (input.responseSessionAlias !== void 0 && validSessionId !== void 0) {
1306
+ input.response.setHeader("mcp-session-id", input.responseSessionAlias);
1307
+ }
1308
+ sendBytes(input.response, bytes);
1309
+ return validSessionId;
1310
+ } finally {
1311
+ requestBody?.fill(0);
1312
+ body?.fill(0);
1313
+ }
1314
+ }
1315
+ async function issueDiagnosticRun(input) {
1316
+ if (input.request.method !== "POST") {
1317
+ sendEmpty(input.response, 405);
1318
+ return void 0;
1319
+ }
1320
+ const body = await readBoundedRequest(input.request, MAX_MCP_BYTES);
1321
+ const requestBody = new Uint8Array(body);
1322
+ const controller = requestAbortController(input.request, input.response);
1323
+ let responseBytes;
1324
+ try {
1325
+ const headers = {
1326
+ accept: "application/json",
1327
+ authorization: `Bearer ${input.token}`,
1328
+ origin: input.origin
1329
+ };
1330
+ copyRequestHeader(input.request, headers, "content-type");
1331
+ const upstream = await fetch(input.target, {
1332
+ method: "POST",
1333
+ cache: "no-store",
1334
+ credentials: "omit",
1335
+ headers,
1336
+ redirect: "error",
1337
+ signal: controller.signal,
1338
+ body: requestBody
1339
+ });
1340
+ if (upstream.redirected || upstream.url !== input.target) {
1341
+ await cancelBody(upstream);
1342
+ sendEmpty(input.response, 502);
1343
+ return void 0;
1344
+ }
1345
+ responseBytes = await readBoundedResponse(upstream, MAX_MCP_BYTES, true);
1346
+ if (upstream.status !== 201) {
1347
+ sendEmpty(input.response, upstream.status);
1348
+ return void 0;
1349
+ }
1350
+ if (upstream.headers.get("content-type")?.toLowerCase().startsWith("application/json") !== true || upstream.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store") !== true) {
1351
+ sendEmpty(input.response, 502);
1352
+ return void 0;
1353
+ }
1354
+ const issued = parseDiagnosticAuthorityResponse(responseBytes, input.upstreamMcpEndpoint);
1355
+ const rewritten = Buffer.from(
1356
+ JSON.stringify({
1357
+ runId: issued.runId,
1358
+ token: input.alias,
1359
+ expiresAt: issued.expiresAt,
1360
+ endpoint: input.browserMcpEndpoint
1361
+ }),
1362
+ "utf8"
1363
+ );
1364
+ input.response.statusCode = 201;
1365
+ input.response.setHeader("cache-control", "private, no-store");
1366
+ input.response.setHeader("content-length", String(rewritten.byteLength));
1367
+ input.response.setHeader("content-type", "application/json; charset=utf-8");
1368
+ input.response.setHeader("x-content-type-options", "nosniff");
1369
+ sendBytes(input.response, rewritten);
1370
+ return Object.freeze({ expiresAt: Date.parse(issued.expiresAt), token: issued.token });
1371
+ } finally {
1372
+ responseBytes?.fill(0);
1373
+ requestBody.fill(0);
1374
+ body.fill(0);
1375
+ }
1376
+ }
1377
+ function parseDiagnosticAuthorityResponse(bytes, upstreamMcpEndpoint) {
1378
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1379
+ if (!isRecord2(value)) throw new Error("diagnostic authority response is invalid");
1380
+ const record = value;
1381
+ const keys = Reflect.ownKeys(record);
1382
+ const expiresAt = typeof record.expiresAt === "string" ? record.expiresAt : "";
1383
+ const expiresAtTimestamp = Date.parse(expiresAt);
1384
+ if (keys.length !== 4 || !["runId", "token", "expiresAt", "endpoint"].every((key) => keys.includes(key)) || typeof record.runId !== "string" || !DIAGNOSTIC_RUN_ID_PATTERN.test(record.runId) || typeof record.token !== "string" || !isCanonicalBearer(record.token) || !Number.isSafeInteger(expiresAtTimestamp) || expiresAtTimestamp <= Date.now() || new Date(expiresAtTimestamp).toISOString() !== expiresAt || record.endpoint !== upstreamMcpEndpoint) {
1385
+ throw new Error("diagnostic authority response is invalid");
1386
+ }
1387
+ return Object.freeze({
1388
+ endpoint: upstreamMcpEndpoint,
1389
+ expiresAt,
1390
+ runId: record.runId,
1391
+ token: record.token
1392
+ });
1393
+ }
1394
+ function isCanonicalBearer(value) {
1395
+ if (!SESSION_ID_PATTERN.test(value)) return false;
1396
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1397
+ const finalSextet = alphabet.indexOf(value.at(-1) ?? "");
1398
+ return finalSextet >= 0 && (finalSextet & 3) === 0;
1399
+ }
1400
+ async function servePremiumArtifact(input) {
1401
+ const controller = requestAbortController(input.request, input.response);
1402
+ const upstream = await fetch(input.target, {
1403
+ cache: "no-store",
1404
+ credentials: "omit",
1405
+ headers: {
1406
+ accept: input.kind === "module" ? "application/javascript" : "text/css",
1407
+ authorization: `Bearer ${input.token}`,
1408
+ "mcp-session-id": input.sessionId,
1409
+ origin: input.origin,
1410
+ "x-scene-glass-project-id": input.projectId
1411
+ },
1412
+ redirect: "error",
1413
+ signal: controller.signal
1414
+ });
1415
+ if (!validPremiumResponse(upstream, input)) {
1416
+ await cancelBody(upstream);
1417
+ sendEmpty(input.response, 502);
1418
+ return;
1419
+ }
1420
+ const bytes = await readBoundedResponse(upstream, input.artifact.maxBytes, false);
1421
+ try {
1422
+ const declaredLength = upstream.headers.get("content-length");
1423
+ if (declaredLength !== null && declaredLength !== String(bytes.byteLength) || `sha256:${createHash2("sha256").update(bytes).digest("hex")}` !== input.artifact.sha256) {
1424
+ bytes.fill(0);
1425
+ sendEmpty(input.response, 502);
1426
+ return;
1427
+ }
1428
+ if (input.kind === "module") validatePremiumModuleText2(bytes);
1429
+ else validatePremiumStylesheetText2(bytes);
1430
+ input.response.statusCode = 200;
1431
+ input.response.setHeader("cache-control", "private, no-store");
1432
+ input.response.setHeader("content-length", String(bytes.byteLength));
1433
+ input.response.setHeader("content-type", input.artifact.mediaType);
1434
+ input.response.setHeader("x-content-type-options", "nosniff");
1435
+ input.response.setHeader("x-scene-glass-artifact-path", input.artifact.path);
1436
+ input.response.setHeader("x-scene-glass-content-sha256", input.artifact.sha256);
1437
+ input.response.setHeader("x-scene-glass-module-abi", String(input.premium.abiVersion));
1438
+ input.response.setHeader("x-scene-glass-module-id", input.premium.moduleId);
1439
+ input.response.setHeader("x-scene-glass-module-namespace", input.premium.namespace);
1440
+ input.response.setHeader("x-scene-glass-release-manifest-sha256", input.manifestDigest);
1441
+ sendBytes(input.response, bytes);
1442
+ } catch {
1443
+ bytes.fill(0);
1444
+ if (!input.response.headersSent) sendEmpty(input.response, 502);
1445
+ else input.response.destroy();
1446
+ }
1447
+ }
1448
+ function validPremiumResponse(response, input) {
1449
+ const length = response.headers.get("content-length");
1450
+ return response.status === 200 && response.ok && !response.redirected && response.url === input.target && response.headers.get("content-type") === input.artifact.mediaType && response.headers.get("x-scene-glass-artifact-path") === input.artifact.path && response.headers.get("x-scene-glass-module-id") === input.premium.moduleId && response.headers.get("x-scene-glass-module-abi") === String(input.premium.abiVersion) && response.headers.get("x-scene-glass-module-namespace") === input.premium.namespace && response.headers.get("x-scene-glass-content-sha256") === input.artifact.sha256 && response.headers.get("x-scene-glass-release-manifest-sha256") === input.manifestDigest && (length === null || /^[1-9][0-9]*$/u.test(length) && Number(length) <= input.artifact.maxBytes);
1451
+ }
1452
+ function containsSourceMapDirective2(source) {
1453
+ const normalized = source.toLowerCase();
1454
+ let offset = normalized.indexOf("source");
1455
+ while (offset !== -1) {
1456
+ if (normalized.startsWith("url=", offset + 6) || normalized.charCodeAt(offset + 6) === 109 && normalized.startsWith("appingurl", offset + 7)) {
1457
+ return true;
1458
+ }
1459
+ offset = normalized.indexOf("source", offset + 1);
1460
+ }
1461
+ return false;
1462
+ }
1463
+ function validatePremiumModuleText2(bytes) {
1464
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1465
+ if (source.length === 0 || source.includes("\0") || /\bimport(?![A-Za-z0-9_$])/u.test(source) || /\bexport\b[^;]{0,1024}\bfrom\s*["']/u.test(source) || containsSourceMapDirective2(source) || /(?:https?:|blob:|data:)/iu.test(source) || /scg-premium-measurement-styles|\[data-scg-premium-measurement|createElement\(["']style["']/u.test(
1466
+ source
1467
+ )) {
1468
+ throw new Error("premium module source is invalid");
1469
+ }
1470
+ }
1471
+ function validatePremiumStylesheetText2(bytes) {
1472
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1473
+ if (source.length === 0 || source.includes("\0") || source.split("\n").filter((line) => line.length > 0).length > 1 || containsSourceMapDirective2(source) || /@import|url\s*\(|(?:https?:|blob:|data:)/iu.test(source) || !source.includes("[data-scg-premium-measurement=true]") || !/\.scg-meas(?:ure)-layer/u.test(source) || !/\.scg-si(?:ze)-layer/u.test(source)) {
1474
+ throw new Error("premium stylesheet source is invalid");
1475
+ }
1476
+ }
1477
+ async function readBoundedRequest(request, maximum) {
1478
+ const chunks = [];
1479
+ let total = 0;
1480
+ try {
1481
+ for await (const value of request) {
1482
+ const chunk = requestChunk(value);
1483
+ chunks.push(chunk);
1484
+ total += chunk.byteLength;
1485
+ if (chunk.byteLength === 0 || total > maximum) throw new Error("request body is invalid");
1486
+ }
1487
+ if (total === 0) throw new Error("request body is empty");
1488
+ return Buffer.concat(chunks, total);
1489
+ } finally {
1490
+ for (const chunk of chunks) chunk.fill(0);
1491
+ }
1492
+ }
1493
+ function requestChunk(value) {
1494
+ if (Buffer.isBuffer(value)) return value;
1495
+ if (typeof value === "string" || value instanceof Uint8Array) return Buffer.from(value);
1496
+ throw new Error("request body is invalid");
1497
+ }
1498
+ function isRecord2(value) {
1499
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1500
+ }
1501
+ async function readBoundedResponse(response, maximum, allowEmpty) {
1502
+ if (response.body === null) {
1503
+ if (allowEmpty) return Buffer.alloc(0);
1504
+ throw new Error("response body is empty");
1505
+ }
1506
+ const reader = response.body.getReader();
1507
+ const chunks = [];
1508
+ let total = 0;
1509
+ try {
1510
+ for (; ; ) {
1511
+ const item = await reader.read();
1512
+ if (item.done) break;
1513
+ const chunk = item.value;
1514
+ chunks.push(chunk);
1515
+ total += chunk.byteLength;
1516
+ if (chunk.byteLength === 0 || total > maximum) throw new Error("response body is invalid");
1517
+ }
1518
+ if (!allowEmpty && total === 0) throw new Error("response body is empty");
1519
+ const bytes = Buffer.alloc(total);
1520
+ let offset = 0;
1521
+ for (const chunk of chunks) {
1522
+ bytes.set(chunk, offset);
1523
+ offset += chunk.byteLength;
1524
+ }
1525
+ return bytes;
1526
+ } finally {
1527
+ for (const chunk of chunks) chunk.fill(0);
1528
+ try {
1529
+ await reader.cancel();
1530
+ } catch {
1531
+ }
1532
+ reader.releaseLock();
1533
+ }
1534
+ }
1535
+ function requestAbortController(request, response) {
1536
+ const controller = new AbortController();
1537
+ request.once("aborted", () => controller.abort());
1538
+ response.once("close", () => {
1539
+ if (!response.writableEnded) controller.abort();
1540
+ });
1541
+ return controller;
1542
+ }
1543
+ function copyRequestHeader(request, target, name) {
1544
+ const value = singleHeader(request.headers[name]);
1545
+ if (value !== void 0) target[name] = value;
1546
+ }
1547
+ function singleHeader(value) {
1548
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1549
+ }
1550
+ function sendBytes(response, bytes) {
1551
+ let cleared = false;
1552
+ const clear = () => {
1553
+ if (cleared) return;
1554
+ cleared = true;
1555
+ bytes.fill(0);
1556
+ };
1557
+ response.once("close", clear);
1558
+ try {
1559
+ response.end(bytes, clear);
1560
+ } catch (error) {
1561
+ clear();
1562
+ throw error;
1563
+ }
1564
+ }
1565
+ function sendEmpty(response, status) {
1566
+ response.statusCode = status;
1567
+ response.removeHeader("content-type");
1568
+ response.setHeader("cache-control", "no-store");
1569
+ response.setHeader("content-length", "0");
1570
+ response.end();
1571
+ }
1572
+ async function cancelBody(response) {
1573
+ try {
1574
+ await response.body?.cancel();
1575
+ } catch {
1576
+ }
1577
+ }
1578
+ function alreadyInjected(html) {
1579
+ return html.includes(`src="${SCENE_GLASS_VITE_PATHS.loader}"`) && html.includes(LOADER_MARKER);
1580
+ }
1581
+ function hasInitialCouponQuery(url) {
1582
+ if (url === void 0) return false;
1583
+ try {
1584
+ return new URL(url, "http://127.0.0.1").searchParams.has("scg-coupon");
1585
+ } catch {
1586
+ return false;
1587
+ }
1588
+ }
1589
+ function isHtmlNavigation(url, accept) {
1590
+ if (url === void 0) return false;
1591
+ const pathname = url.split("?", 1)[0] ?? "";
1592
+ return accept?.toLowerCase().includes("text/html") === true || pathname === "/" || pathname.endsWith(".html");
1593
+ }
1594
+
1595
+ // packages/devtools/src/vite.ts
1596
+ var LOOPBACK_RUNTIME_ORIGIN = "http://127.0.0.1:4175";
1597
+ function sceneGlass() {
1598
+ return createSceneGlassPlugin({
1599
+ artifactModuleUrl: import.meta.url,
1600
+ load: loadViteRuntimeAuthority,
1601
+ probe: probeViteRuntime,
1602
+ runtimeOrigin: LOOPBACK_RUNTIME_ORIGIN
1603
+ });
1604
+ }
1605
+ export {
1606
+ SCENE_GLASS_VITE_PATHS,
1607
+ sceneGlass
1608
+ };