vde-open 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { C as isValidLogicalPath, F as __toESM, P as __commonJSMin, S as hasHiddenSegment, _ as assetTypeOf, b as dirnameOfLogicalPath, d as ParseLimitError, f as analyzeDocument, l as HTML_LINK_RELAY, v as classifyLink, w as roleAllowed, x as encodeLogicalPath, y as classifyReference } from "./html-static-Ct_9qmNR.js";
2
- import { $ as boolean, A as successEnvelope, B as openParamsSchema, C as VdeError, D as ExitCode, E as isVdeError, F as htmlModeChangeParamsSchema, G as searchParamsSchema, H as renderGrantParamsSchema, I as htmlModeSchema, J as sourceStateSchema, K as sha256Schema, L as lastOpenedDocument, M as closeParamsSchema, N as documentFormatSchema, P as documentIdSchema, Q as array, R as linkOpenParamsSchema, S as validateAnswers, U as reorderParamsSchema, V as readParamsSchema, W as revisionSchema, X as LIMITS, Y as watchRuleSchema, Z as _enum, _ as feedbackWaitParamsSchema, a as uniqueTokens, at as ZodError, b as submissionSchema, c as feedbackAckParamsSchema, d as feedbackDraftParamsSchema, et as literal, f as feedbackForgetParamsSchema, g as feedbackSubmitParamsSchema, h as feedbackStatusSchema, i as codePointLength, it as string, j as assetRecordSchema, k as errorEnvelope, l as feedbackCancelParamsSchema, m as feedbackListParamsSchema, n as batchesOf, nt as record, o as answersSchema, ot as canonicalJson, p as feedbackIdParamsSchema, q as sourceKindSchema, r as partsOf, rt as strictObject, s as cancellationSchema, tt as number, u as feedbackCreateParamsSchema, v as questionnaireSchema, w as exitCodeForError, x as utf8Length, y as requestIdSchema, z as listParamsSchema } from "./search-index-ed_S_eI7.js";
2
+ import { $ as sourceStateSchema, B as htmlModeChangeParamsSchema, C as questionnaireSchema, D as validateAnswers, E as utf8Length, F as successEnvelope, G as openParamsSchema, H as lastOpenedDocument, I as assetRecordSchema, J as reorderParamsSchema, K as readParamsSchema, L as closeParamsSchema, M as ExitCode, O as VdeError, P as errorEnvelope, Q as sourceKindSchema, R as documentFormatSchema, S as feedbackWaitParamsSchema, T as submissionSchema, U as linkOpenParamsSchema, V as htmlModeSchema, W as listParamsSchema, X as searchParamsSchema, Y as revisionSchema, Z as sha256Schema, _ as feedbackForgetParamsSchema, a as uniqueTokens, at as boolean, b as feedbackStatusSchema, c as mobileLinkParamsSchema, ct as record, d as answersSchema, dt as unknown, et as watchRuleSchema, f as cancellationSchema, ft as ZodError, g as feedbackDraftParamsSchema, h as feedbackCreateParamsSchema, i as codePointLength, it as array, j as isVdeError, k as exitCodeForError, l as mobileReleaseParamsSchema, lt as strictObject, m as feedbackCancelParamsSchema, mt as canonicalJson, n as batchesOf, nt as ZodNumber, o as mobileCheckParamsSchema, ot as literal, p as feedbackAckParamsSchema, pt as _coercedNumber, q as renderGrantParamsSchema, r as partsOf, rt as _enum, s as mobileGrantParamsSchema, st as number$1, tt as LIMITS, u as viewEpochSchema, ut as string, v as feedbackIdParamsSchema, w as requestIdSchema, x as feedbackSubmitParamsSchema, y as feedbackListParamsSchema, z as documentIdSchema } from "./search-index-B0xpVDwG.js";
3
3
  import { n as scanReferences, r as extractTitle } from "./render-CY_Mrhyl.js";
4
4
  import { n as measureHeap, t as collectGarbage } from "./heap-C3qHm7SE.js";
5
5
  import { accessSync, constants, existsSync, stat, statSync, unwatchFile, watch, watchFile } from "node:fs";
@@ -28,6 +28,11 @@ import { createServer as createServer$1 } from "node:net";
28
28
  const BRIDGE_HELLO = "vde-bridge-hello";
29
29
  const BRIDGE_PORT = "vde-bridge-port";
30
30
  //#endregion
31
+ //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/coerce.js
32
+ function number(params) {
33
+ return _coercedNumber(ZodNumber, params);
34
+ }
35
+ //#endregion
31
36
  //#region ../../packages/shared/src/strict-json.ts
32
37
  var StrictJsonError = class extends Error {
33
38
  reason;
@@ -154,7 +159,7 @@ function parseStrictJson(text) {
154
159
  }
155
160
  //#endregion
156
161
  //#region package.json
157
- var version = "0.1.15";
162
+ var version = "0.1.16";
158
163
  //#endregion
159
164
  //#region src/documents/cursor.ts
160
165
  function invalidCursor(reason) {
@@ -545,7 +550,7 @@ const revisionRecordSchema = strictObject({
545
550
  revision: revisionSchema,
546
551
  format: documentFormatSchema,
547
552
  sourceSha256: sha256Schema,
548
- byteLength: number().int().nonnegative(),
553
+ byteLength: number$1().int().nonnegative(),
549
554
  parserProfileVersion: string().min(1),
550
555
  createdAt: string(),
551
556
  documentLogicalPath: string().min(1),
@@ -584,7 +589,7 @@ const feedbackRecordSchema = strictObject({
584
589
  updatedAt: string(),
585
590
  operationId: string().nullable(),
586
591
  operationDigest: sha256Schema.nullable(),
587
- draftVersion: number().int().nonnegative(),
592
+ draftVersion: number$1().int().nonnegative(),
588
593
  draftAnswers: answersSchema,
589
594
  submission: submissionSchema.nullable(),
590
595
  submissionDigest: sha256Schema.nullable(),
@@ -592,7 +597,7 @@ const feedbackRecordSchema = strictObject({
592
597
  acknowledgedAt: string().nullable()
593
598
  });
594
599
  const statePayloadSchema = strictObject({
595
- catalogVersion: number().int().nonnegative(),
600
+ catalogVersion: number$1().int().nonnegative(),
596
601
  documents: record(documentIdSchema, documentRecordSchema),
597
602
  openOrder: array(documentIdSchema),
598
603
  activeDocumentId: documentIdSchema.nullable(),
@@ -601,7 +606,7 @@ const statePayloadSchema = strictObject({
601
606
  });
602
607
  const stateFileSchema = strictObject({
603
608
  formatVersion: literal(1),
604
- storeVersion: number().int().nonnegative(),
609
+ storeVersion: number$1().int().nonnegative(),
605
610
  checksum: sha256Schema,
606
611
  payload: statePayloadSchema
607
612
  });
@@ -5052,13 +5057,22 @@ var DocumentService = class {
5052
5057
  entry: this.#requireRevision(record, revision ?? record.currentRevision)
5053
5058
  };
5054
5059
  }
5055
- async openLinked(link) {
5056
- const { documentId, href } = link;
5060
+ async #linkTarget(documentId, href) {
5057
5061
  const record = this.#requireOpen(documentId);
5058
5062
  const target = classifyLink(href);
5059
5063
  const base = target.kind !== "document" ? null : target.fromRoot || record.canonicalPath === null ? record.assetsRoot : dirname(record.canonicalPath);
5060
5064
  if (target.kind !== "document" || base === null) throw new VdeError("E_INVALID_ARGUMENT", "This link does not point to a document that can be opened.");
5061
- const canonical = await canonicalizePath(resolve(base, ...target.segments));
5065
+ return canonicalizePath(resolve(base, ...target.segments));
5066
+ }
5067
+ async openDocumentOfLink(documentId, href) {
5068
+ const canonical = await this.#linkTarget(documentId, href).catch(() => null);
5069
+ if (canonical === null) return null;
5070
+ const existing = this.#existingFile(canonical);
5071
+ return existing?.isOpen ? existing.documentId : null;
5072
+ }
5073
+ async openLinked(link) {
5074
+ const { documentId, href } = link;
5075
+ const canonical = await this.#linkTarget(documentId, href);
5062
5076
  const now = this.#now().getTime();
5063
5077
  const offered = link.confirmation === void 0 ? void 0 : this.#linkConfirmations.get(link.confirmation);
5064
5078
  if (link.confirmation !== void 0) this.#linkConfirmations.delete(link.confirmation);
@@ -7056,16 +7070,17 @@ function createRenderService(options) {
7056
7070
  snapshot
7057
7071
  };
7058
7072
  };
7059
- const liveGrant = (key) => {
7073
+ const liveGrant = (key, audience = "pc") => {
7060
7074
  const grant = grants.get(key);
7061
- if (!grant) return null;
7062
- if (!documents.state.documents[grant.documentId]?.isOpen || documents.openEpoch(grant.documentId) !== grant.openEpoch || grant.mode === "interactive" && documents.interactiveGeneration(grant.documentId) !== grant.permission) {
7075
+ if (grant?.audience !== audience) return null;
7076
+ const record = documents.state.documents[grant.documentId];
7077
+ if (!record?.isOpen || documents.openEpoch(grant.documentId) !== grant.openEpoch || grant.mode === "interactive" && documents.interactiveGeneration(grant.documentId) !== grant.permission || audience === "mobile" && (record.currentRevision !== grant.revision || options.mobile?.viewEpochOf(grant.documentId) !== grant.viewEpoch)) {
7063
7078
  grants.delete(key);
7064
7079
  return null;
7065
7080
  }
7066
7081
  return grant;
7067
7082
  };
7068
- const issue = async (params, context) => {
7083
+ const issue = async (params, context, audience = "pc", stillCurrent = () => void 0) => {
7069
7084
  const interactive = params.mode === "interactive";
7070
7085
  const permissionOf = () => {
7071
7086
  if (!interactive) return null;
@@ -7083,6 +7098,7 @@ function createRenderService(options) {
7083
7098
  if (documents.openEpoch(params.documentId) !== openEpoch) throw new VdeError("E_DOCUMENT_NOT_OPEN", "The document is not open.", { documentId: params.documentId });
7084
7099
  }
7085
7100
  const permission = permissionOf();
7101
+ stillCurrent();
7086
7102
  const { record, entry, snapshot } = prepared;
7087
7103
  if (params.requestId !== null) {
7088
7104
  const request = Object.hasOwn(store.payload.feedbackRequests, params.requestId) ? store.payload.feedbackRequests[params.requestId] : void 0;
@@ -7107,7 +7123,10 @@ function createRenderService(options) {
7107
7123
  };
7108
7124
  }
7109
7125
  const key = randomBytes(32).toString("base64url");
7126
+ const viewEpoch = audience === "mobile" ? options.mobile?.viewEpochOf(record.documentId) ?? null : null;
7110
7127
  grants.set(key, {
7128
+ audience,
7129
+ viewEpoch,
7111
7130
  documentId: record.documentId,
7112
7131
  openEpoch,
7113
7132
  revision: entry.revision,
@@ -7117,14 +7136,18 @@ function createRenderService(options) {
7117
7136
  bridge,
7118
7137
  missing: /* @__PURE__ */ new Set()
7119
7138
  });
7120
- while (grants.size > LIMITS.renderGrants) {
7121
- const oldest = grants.keys().next().value;
7122
- if (oldest === void 0) break;
7123
- grants.delete(oldest);
7139
+ let count = 0;
7140
+ for (const grant of grants.values()) if (grant.audience === audience) count += 1;
7141
+ for (const [oldKey, grant] of grants) {
7142
+ if (count <= LIMITS.renderGrants) break;
7143
+ if (grant.audience !== audience) continue;
7144
+ grants.delete(oldKey);
7145
+ count -= 1;
7124
7146
  }
7125
- const filesBaseUrl = `${options.previewOrigin()}/r/${key}/files/`;
7147
+ const filesBaseUrl = `${audience === "mobile" ? options.mobile?.previewOrigin() ?? "" : options.previewOrigin()}/r/${key}/files/`;
7126
7148
  return {
7127
7149
  grant: key,
7150
+ viewEpoch,
7128
7151
  documentId: record.documentId,
7129
7152
  revision: entry.revision,
7130
7153
  format: snapshot.format,
@@ -7158,10 +7181,11 @@ function createRenderService(options) {
7158
7181
  },
7159
7182
  async createGrant(rawParams, context) {
7160
7183
  const params = renderGrantParamsSchema.parse(rawParams);
7161
- return issue({
7184
+ const { viewEpoch: _viewEpoch, ...result } = await issue({
7162
7185
  ...params,
7163
7186
  requestId: null
7164
7187
  }, context);
7188
+ return result;
7165
7189
  },
7166
7190
  async createGrantForRequest(requestId, context) {
7167
7191
  const request = Object.hasOwn(store.payload.feedbackRequests, requestId) ? store.payload.feedbackRequests[requestId] : void 0;
@@ -7171,12 +7195,13 @@ function createRenderService(options) {
7171
7195
  status: request.status
7172
7196
  });
7173
7197
  const interactive = request.renderMode === "interactive" && documents.interactiveAllowed(request.documentId);
7174
- return issue({
7198
+ const { viewEpoch: _viewEpoch, ...result } = await issue({
7175
7199
  documentId: request.documentId,
7176
7200
  revision: request.revision,
7177
7201
  mode: interactive ? "interactive" : "static",
7178
7202
  requestId: interactive ? request.requestId : null
7179
7203
  }, context);
7204
+ return result;
7180
7205
  },
7181
7206
  bridgeOf(key) {
7182
7207
  const grant = liveGrant(key);
@@ -7189,34 +7214,50 @@ function createRenderService(options) {
7189
7214
  };
7190
7215
  },
7191
7216
  release(keys) {
7192
- let released = 0;
7193
- for (const key of keys) if (grants.delete(key)) released += 1;
7194
- return released;
7217
+ return releaseOf(keys, "pc");
7218
+ },
7219
+ releaseMobile(keys) {
7220
+ return releaseOf(keys, "mobile");
7195
7221
  },
7196
7222
  async resolve(key, logicalPath) {
7197
- const grant = liveGrant(key);
7198
- if (!grant) return null;
7199
- const file = grant.snapshot.files.get(logicalPath);
7200
- if (!file) {
7201
- if (!grant.missing.has(logicalPath) && grant.missing.size < LIMITS.renderMissingPerGrant) {
7202
- grant.missing.add(logicalPath);
7203
- options.onMissing?.(grant.documentId);
7204
- }
7205
- return null;
7206
- }
7207
- const body = file.kind === "inline" ? file.body : file.kind === "bridged" ? Buffer.concat([
7208
- file.before,
7209
- grant.bridge?.config ?? Buffer.from("null"),
7210
- file.after
7211
- ]) : await store.readBlob(file.sha256);
7212
- if (!liveGrant(key)) return null;
7223
+ return resolveOf(key, logicalPath, "pc");
7224
+ },
7225
+ async resolveMobile(key, logicalPath) {
7226
+ return resolveOf(key, logicalPath, "mobile");
7227
+ },
7228
+ checkMobile(key) {
7229
+ return liveGrant(key, "mobile") !== null;
7230
+ },
7231
+ mobileLinkOf(key, linkId) {
7232
+ const grant = liveGrant(key, "mobile");
7233
+ const link = grant?.snapshot.links.find((candidate) => candidate.linkId === linkId);
7234
+ return grant && link ? {
7235
+ documentId: grant.documentId,
7236
+ link
7237
+ } : null;
7238
+ },
7239
+ async createMobileGrant(documentId, expected) {
7240
+ const mobile = options.mobile;
7241
+ if (!mobile) throw new VdeError("E_UNKNOWN_METHOD", "The phone reader is off.");
7242
+ const stillCurrent = () => {
7243
+ const record = documents.state.documents[documentId];
7244
+ if (!record?.isOpen) throw new VdeError("E_DOCUMENT_NOT_OPEN", "The document is not open.", { documentId });
7245
+ if (record.currentRevision !== expected.revision || mobile.viewEpochOf(documentId) !== expected.viewEpoch) throw new VdeError("E_VIEW_STALE", "The document changed. Fetch the list again.");
7246
+ };
7247
+ stillCurrent();
7248
+ const interactive = documents.interactiveAllowed(documentId);
7249
+ const { bridge: _bridge, diagnostics: _diagnostics, viewEpoch, ...result } = await issue({
7250
+ documentId,
7251
+ revision: expected.revision,
7252
+ mode: interactive ? "interactive" : "static",
7253
+ requestId: null
7254
+ }, { origin: "" }, "mobile", stillCurrent).catch((error) => {
7255
+ if (error instanceof VdeError && error.code === "E_INTERACTIVE_NOT_ALLOWED") throw new VdeError("E_VIEW_STALE", "The document changed. Fetch the list again.");
7256
+ throw error;
7257
+ });
7213
7258
  return {
7214
- body,
7215
- mime: file.mime,
7216
- role: file.role,
7217
- grant: key,
7218
- mode: grant.mode,
7219
- hasDocumentLinks: file.role === "document" && grant.snapshot.links.some((link) => link.kind === "document")
7259
+ ...result,
7260
+ viewEpoch: viewEpoch ?? expected.viewEpoch
7220
7261
  };
7221
7262
  },
7222
7263
  missingOf(key) {
@@ -7237,6 +7278,80 @@ function createRenderService(options) {
7237
7278
  return link;
7238
7279
  }
7239
7280
  };
7281
+ function releaseOf(keys, audience) {
7282
+ let released = 0;
7283
+ for (const key of keys) if (grants.get(key)?.audience === audience && grants.delete(key)) released += 1;
7284
+ return released;
7285
+ }
7286
+ async function resolveOf(key, logicalPath, audience) {
7287
+ const grant = liveGrant(key, audience);
7288
+ if (!grant) return null;
7289
+ const file = grant.snapshot.files.get(logicalPath);
7290
+ if (!file) {
7291
+ if (!grant.missing.has(logicalPath) && grant.missing.size < LIMITS.renderMissingPerGrant) {
7292
+ grant.missing.add(logicalPath);
7293
+ options.onMissing?.(grant.documentId);
7294
+ }
7295
+ return null;
7296
+ }
7297
+ const body = file.kind === "inline" ? file.body : file.kind === "bridged" ? Buffer.concat([
7298
+ file.before,
7299
+ grant.bridge?.config ?? Buffer.from("null"),
7300
+ file.after
7301
+ ]) : await store.readBlob(file.sha256);
7302
+ if (!liveGrant(key, audience)) return null;
7303
+ return {
7304
+ body,
7305
+ mime: file.mime,
7306
+ role: file.role,
7307
+ grant: key,
7308
+ mode: grant.mode,
7309
+ hasDocumentLinks: file.role === "document" && grant.snapshot.links.some((link) => link.kind === "document")
7310
+ };
7311
+ }
7312
+ }
7313
+ //#endregion
7314
+ //#region src/render/view-epochs.ts
7315
+ function createViewEpochs(documents) {
7316
+ const seen = /* @__PURE__ */ new Map();
7317
+ const current = (documentId) => {
7318
+ const record = documents.state.documents[documentId];
7319
+ return {
7320
+ openEpoch: documents.openEpoch(documentId),
7321
+ revision: record?.currentRevision ?? "",
7322
+ permission: documents.interactiveGeneration(documentId)
7323
+ };
7324
+ };
7325
+ const update = (documentId) => {
7326
+ const now = current(documentId);
7327
+ const last = seen.get(documentId);
7328
+ let entry;
7329
+ if (last === void 0 || last.openEpoch !== now.openEpoch) entry = {
7330
+ ...now,
7331
+ generation: 0
7332
+ };
7333
+ else if (last.revision !== now.revision || last.permission !== now.permission) entry = {
7334
+ ...now,
7335
+ generation: last.generation + 1
7336
+ };
7337
+ else return last;
7338
+ seen.set(documentId, entry);
7339
+ return entry;
7340
+ };
7341
+ return {
7342
+ get size() {
7343
+ return seen.size;
7344
+ },
7345
+ observe() {
7346
+ const open = new Set(documents.state.openOrder);
7347
+ for (const documentId of seen.keys()) if (!open.has(documentId)) seen.delete(documentId);
7348
+ for (const documentId of open) update(documentId);
7349
+ },
7350
+ of(documentId) {
7351
+ const entry = update(documentId);
7352
+ return `${String(entry.openEpoch)}.${String(entry.generation)}`;
7353
+ }
7354
+ };
7240
7355
  }
7241
7356
  //#endregion
7242
7357
  //#region src/diagnostics/idle-collect.ts
@@ -11119,10 +11234,79 @@ function createEventQueue(options) {
11119
11234
  };
11120
11235
  }
11121
11236
  //#endregion
11237
+ //#region src/server/http/event-stream.ts
11238
+ function createEventStreams() {
11239
+ const streams = /* @__PURE__ */ new Map();
11240
+ return {
11241
+ open(c, options) {
11242
+ const response = streamSSE(c, async (stream) => {
11243
+ let closed = false;
11244
+ let wake = () => void 0;
11245
+ const done = new Promise((resolve) => {
11246
+ wake = resolve;
11247
+ });
11248
+ const finish = () => {
11249
+ closed = true;
11250
+ wake();
11251
+ };
11252
+ const queue = createEventQueue({
11253
+ writeEvent: (event) => {
11254
+ const frame = options.frame(event);
11255
+ return frame === null ? Promise.resolve() : stream.writeSSE(frame);
11256
+ },
11257
+ writeHeartbeat: () => stream.write(": heartbeat\n\n"),
11258
+ onError: finish
11259
+ });
11260
+ const drop = () => {
11261
+ queue.stop();
11262
+ finish();
11263
+ stream.abort();
11264
+ c.env.outgoing?.destroy();
11265
+ };
11266
+ streams.set(finish, queue);
11267
+ stream.onAbort(finish);
11268
+ const send = (event) => {
11269
+ if (!closed) queue.send(event);
11270
+ };
11271
+ send(options.hello);
11272
+ const unsubscribe = options.subscribe(send);
11273
+ const heartbeat = setInterval(() => {
11274
+ if (queue.stalledFor() >= (options.stallMs ?? LIMITS.sseStallMs)) {
11275
+ drop();
11276
+ return;
11277
+ }
11278
+ queue.heartbeat();
11279
+ }, options.heartbeatMs ?? LIMITS.sseHeartbeatMs);
11280
+ try {
11281
+ await done;
11282
+ } finally {
11283
+ clearInterval(heartbeat);
11284
+ unsubscribe();
11285
+ await queue.settled();
11286
+ streams.delete(finish);
11287
+ }
11288
+ });
11289
+ response.headers.set("Cache-Control", "no-store");
11290
+ return response;
11291
+ },
11292
+ stats() {
11293
+ let maxPending = 0;
11294
+ for (const queue of streams.values()) maxPending = Math.max(maxPending, queue.pending);
11295
+ return {
11296
+ streams: streams.size,
11297
+ maxPending
11298
+ };
11299
+ },
11300
+ finishAll() {
11301
+ for (const finish of streams.keys()) finish();
11302
+ }
11303
+ };
11304
+ }
11305
+ //#endregion
11122
11306
  //#region src/server/http/management.ts
11123
- const API_PREFIX = "/_/api/v1";
11124
- const STREAM_FLUSH_MS = 100;
11125
- const CLOSE_GRACE_MS$1 = 1e3;
11307
+ const API_PREFIX$1 = "/_/api/v1";
11308
+ const STREAM_FLUSH_MS$1 = 100;
11309
+ const CLOSE_GRACE_MS$2 = 1e3;
11126
11310
  const MIME_TYPES = {
11127
11311
  ".html": "text/html; charset=utf-8",
11128
11312
  ".js": "text/javascript; charset=utf-8",
@@ -11133,7 +11317,7 @@ const MIME_TYPES = {
11133
11317
  ".woff2": "font/woff2",
11134
11318
  ".map": "application/json; charset=utf-8"
11135
11319
  };
11136
- function uiCsp(previewOrigin) {
11320
+ function uiCsp$1(previewOrigin) {
11137
11321
  return [
11138
11322
  "default-src 'none'",
11139
11323
  "script-src 'self'",
@@ -11218,7 +11402,7 @@ function statusOf(code) {
11218
11402
  default: return 500;
11219
11403
  }
11220
11404
  }
11221
- function fail(c, error) {
11405
+ function fail$1(c, error) {
11222
11406
  const body = toErrorBody$1(error);
11223
11407
  return c.json(errorEnvelope(body), statusOf(body.code));
11224
11408
  }
@@ -11241,7 +11425,7 @@ async function startManagementServer(deps, options = {}) {
11241
11425
  const app = new Hono();
11242
11426
  let origin = "";
11243
11427
  let host = "";
11244
- const streams = /* @__PURE__ */ new Map();
11428
+ const streams = createEventStreams();
11245
11429
  app.use("*", async (c, next) => {
11246
11430
  await next();
11247
11431
  c.header("X-Content-Type-Options", "nosniff");
@@ -11251,28 +11435,28 @@ async function startManagementServer(deps, options = {}) {
11251
11435
  app.use("*", async (c, next) => {
11252
11436
  if (c.req.header("host") !== host) {
11253
11437
  deps.onEvent?.("http.rejected", { reason: "host" });
11254
- return fail(c, new VdeError("E_UNAUTHORIZED", "This Host is not allowed."));
11438
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This Host is not allowed."));
11255
11439
  }
11256
11440
  return next();
11257
11441
  });
11258
- app.use(`${API_PREFIX}/*`, async (c, next) => {
11442
+ app.use(`${API_PREFIX$1}/*`, async (c, next) => {
11259
11443
  const requestOrigin = c.req.header("origin");
11260
11444
  const allowed = requestOrigin === origin || deps.devOrigin !== null && requestOrigin === deps.devOrigin;
11261
11445
  if (requestOrigin !== void 0 && !allowed) {
11262
11446
  deps.onEvent?.("http.rejected", { reason: "origin" });
11263
- return fail(c, new VdeError("E_UNAUTHORIZED", "This Origin is not allowed."));
11447
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This Origin is not allowed."));
11264
11448
  }
11265
11449
  const site = c.req.header("sec-fetch-site");
11266
11450
  if (site !== void 0 && site !== "same-origin" && !(deps.devOrigin !== null && allowed)) {
11267
11451
  deps.onEvent?.("http.rejected", { reason: "fetch-site" });
11268
- return fail(c, new VdeError("E_UNAUTHORIZED", "This request is not accepted."));
11452
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This request is not accepted."));
11269
11453
  }
11270
11454
  const method = c.req.method;
11271
11455
  if (method !== "GET" && method !== "HEAD") {
11272
- if (requestOrigin === void 0) return fail(c, new VdeError("E_UNAUTHORIZED", "A request without Origin cannot make changes."));
11273
- if (Number(c.req.header("content-length") ?? "0") > 0 && !(c.req.header("content-type") ?? "").startsWith("application/json")) return fail(c, new VdeError("E_INVALID_ARGUMENT", "The body must be sent as JSON."));
11456
+ if (requestOrigin === void 0) return fail$1(c, new VdeError("E_UNAUTHORIZED", "A request without Origin cannot make changes."));
11457
+ if (Number(c.req.header("content-length") ?? "0") > 0 && !(c.req.header("content-type") ?? "").startsWith("application/json")) return fail$1(c, new VdeError("E_INVALID_ARGUMENT", "The body must be sent as JSON."));
11274
11458
  }
11275
- if (deps.isStopping()) return fail(c, new VdeError("E_DAEMON_STOPPING", "The daemon is stopping."));
11459
+ if (deps.isStopping()) return fail$1(c, new VdeError("E_DAEMON_STOPPING", "The daemon is stopping."));
11276
11460
  return next();
11277
11461
  });
11278
11462
  const api = new Hono();
@@ -11435,67 +11619,26 @@ async function startManagementServer(deps, options = {}) {
11435
11619
  confirmation: params.confirmation
11436
11620
  }));
11437
11621
  });
11438
- api.get("/events", (c) => {
11439
- const response = streamSSE(c, async (stream) => {
11440
- let closed = false;
11441
- let wake = () => void 0;
11442
- const done = new Promise((resolve) => {
11443
- wake = resolve;
11444
- });
11445
- const finish = () => {
11446
- closed = true;
11447
- wake();
11448
- };
11449
- const queue = createEventQueue({
11450
- writeEvent: (event) => stream.writeSSE({
11451
- event: event.type,
11452
- id: String(event.sequence),
11453
- data: JSON.stringify(event)
11454
- }),
11455
- writeHeartbeat: () => stream.write(": heartbeat\n\n"),
11456
- onError: finish
11457
- });
11458
- const drop = () => {
11459
- queue.stop();
11460
- finish();
11461
- stream.abort();
11462
- c.env.outgoing?.destroy();
11463
- };
11464
- streams.set(finish, queue);
11465
- stream.onAbort(finish);
11466
- const send = (event) => {
11467
- if (!closed) queue.send(event);
11468
- };
11469
- send({
11470
- type: "hello",
11471
- daemonId: deps.daemonId,
11472
- sequence: deps.events.sequence,
11473
- catalogVersion: deps.documents.state.catalogVersion
11474
- });
11475
- const unsubscribe = deps.events.subscribe(send);
11476
- const heartbeat = setInterval(() => {
11477
- if (queue.stalledFor() >= (deps.stallMs ?? LIMITS.sseStallMs)) {
11478
- drop();
11479
- return;
11480
- }
11481
- queue.heartbeat();
11482
- }, deps.heartbeatMs ?? LIMITS.sseHeartbeatMs);
11483
- try {
11484
- await done;
11485
- } finally {
11486
- clearInterval(heartbeat);
11487
- unsubscribe();
11488
- await queue.settled();
11489
- streams.delete(finish);
11490
- }
11491
- });
11492
- response.headers.set("Cache-Control", "no-store");
11493
- return response;
11494
- });
11495
- api.all("*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11496
- api.onError((error, c) => fail(c, error));
11497
- app.route(API_PREFIX, api);
11498
- app.all("/_/*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11622
+ api.get("/events", (c) => streams.open(c, {
11623
+ hello: {
11624
+ type: "hello",
11625
+ daemonId: deps.daemonId,
11626
+ sequence: deps.events.sequence,
11627
+ catalogVersion: deps.documents.state.catalogVersion
11628
+ },
11629
+ subscribe: (listener) => deps.events.subscribe(listener),
11630
+ frame: (event) => ({
11631
+ event: event.type,
11632
+ id: String(event.sequence),
11633
+ data: JSON.stringify(event)
11634
+ }),
11635
+ heartbeatMs: deps.heartbeatMs,
11636
+ stallMs: deps.stallMs
11637
+ }));
11638
+ api.all("*", (c) => fail$1(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11639
+ api.onError((error, c) => fail$1(c, error));
11640
+ app.route(API_PREFIX$1, api);
11641
+ app.all("/_/*", (c) => fail$1(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11499
11642
  app.on(["GET", "HEAD"], "*", (c) => {
11500
11643
  const asset = assets.get(c.req.path);
11501
11644
  if (!asset) {
@@ -11504,12 +11647,12 @@ async function startManagementServer(deps, options = {}) {
11504
11647
  }
11505
11648
  const headers = { "Content-Type": asset.type };
11506
11649
  if (asset.immutable) headers["Cache-Control"] = "public, max-age=31536000, immutable";
11507
- if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp(deps.previewOrigin);
11650
+ if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp$1(deps.previewOrigin);
11508
11651
  if (c.req.method === "HEAD") return c.body(null, 200, headers);
11509
11652
  return c.body(new Uint8Array(asset.body), 200, headers);
11510
11653
  });
11511
11654
  app.all("*", (c) => c.text("Method Not Allowed", 405));
11512
- app.onError((error, c) => fail(c, error));
11655
+ app.onError((error, c) => fail$1(c, error));
11513
11656
  const server = serve({
11514
11657
  fetch: app.fetch,
11515
11658
  hostname: "127.0.0.1",
@@ -11526,15 +11669,347 @@ async function startManagementServer(deps, options = {}) {
11526
11669
  port,
11527
11670
  origin,
11528
11671
  eventStreams() {
11529
- let maxPending = 0;
11530
- for (const queue of streams.values()) maxPending = Math.max(maxPending, queue.pending);
11531
- return {
11532
- streams: streams.size,
11533
- maxPending
11672
+ return streams.stats();
11673
+ },
11674
+ async close() {
11675
+ streams.finishAll();
11676
+ await new Promise((resolve) => setTimeout(resolve, STREAM_FLUSH_MS$1));
11677
+ await new Promise((resolve) => {
11678
+ server.close(() => resolve());
11679
+ server.closeIdleConnections();
11680
+ setTimeout(() => server.closeAllConnections(), CLOSE_GRACE_MS$2).unref();
11681
+ });
11682
+ }
11683
+ };
11684
+ }
11685
+ //#endregion
11686
+ //#region src/server/http/mobile.ts
11687
+ const API_PREFIX = "/_/mobile/v1";
11688
+ const STREAM_FLUSH_MS = 100;
11689
+ const CLOSE_GRACE_MS$1 = 1e3;
11690
+ const IDENTITY_HEADER = "tailscale-user-login";
11691
+ function hasExactlyOne(request, name, value) {
11692
+ const values = request.headersDistinct[name];
11693
+ return values?.length === 1 && values[0] === value;
11694
+ }
11695
+ function isConfiguredPerson(request, login) {
11696
+ return hasExactlyOne(request, IDENTITY_HEADER, login);
11697
+ }
11698
+ async function jsonBody(c) {
11699
+ if ((c.req.header("content-type") ?? "").split(";")[0]?.trim().toLowerCase() !== "application/json") throw new VdeError("E_INVALID_ARGUMENT", "JSON only.");
11700
+ try {
11701
+ return await c.req.json();
11702
+ } catch {
11703
+ throw new VdeError("E_INVALID_ARGUMENT", "Invalid JSON.");
11704
+ }
11705
+ }
11706
+ function uiCsp(previewOrigin) {
11707
+ return [
11708
+ "default-src 'none'",
11709
+ "script-src 'self'",
11710
+ "style-src 'self' 'unsafe-inline'",
11711
+ `img-src 'self' data: ${previewOrigin}`,
11712
+ "font-src 'self'",
11713
+ "connect-src 'self'",
11714
+ "worker-src 'self'",
11715
+ `frame-src ${previewOrigin}`,
11716
+ "object-src 'none'",
11717
+ "base-uri 'none'",
11718
+ "form-action 'none'",
11719
+ "frame-ancestors 'none'"
11720
+ ].join("; ");
11721
+ }
11722
+ const ERRORS = {
11723
+ E_UNAUTHORIZED: {
11724
+ status: 403,
11725
+ message: "This request is not allowed."
11726
+ },
11727
+ E_DOCUMENT_NOT_FOUND: {
11728
+ status: 404,
11729
+ message: "The document is not open."
11730
+ },
11731
+ E_DOCUMENT_NOT_OPEN: {
11732
+ status: 404,
11733
+ message: "The document is not open."
11734
+ },
11735
+ E_UNKNOWN_METHOD: {
11736
+ status: 404,
11737
+ message: "Unknown API."
11738
+ },
11739
+ E_VIEW_STALE: {
11740
+ status: 409,
11741
+ message: "The document changed. Fetch the list again."
11742
+ },
11743
+ E_CURSOR_STALE: {
11744
+ status: 409,
11745
+ message: "The list changed. Fetch it again from the start."
11746
+ },
11747
+ E_INVALID_CURSOR: {
11748
+ status: 409,
11749
+ message: "The cursor expired. Fetch again from the start."
11750
+ },
11751
+ E_REVISION_UNAVAILABLE: {
11752
+ status: 409,
11753
+ message: "The document changed. Fetch the list again."
11754
+ },
11755
+ E_INVALID_ARGUMENT: {
11756
+ status: 400,
11757
+ message: "The request is invalid."
11758
+ },
11759
+ E_UNSUPPORTED_FORMAT: {
11760
+ status: 400,
11761
+ message: "This document has no text to read here."
11762
+ },
11763
+ E_DAEMON_STOPPING: {
11764
+ status: 503,
11765
+ message: "The daemon is stopping."
11766
+ }
11767
+ };
11768
+ function fail(c, error) {
11769
+ const code = isVdeError(error) ? error.code : error instanceof ZodError ? "E_INVALID_ARGUMENT" : "E_INTERNAL";
11770
+ const known = ERRORS[code];
11771
+ return c.json(errorEnvelope({
11772
+ code: known ? code : "E_INTERNAL",
11773
+ message: known?.message ?? "An internal error occurred.",
11774
+ retryable: false,
11775
+ details: {}
11776
+ }), known?.status ?? 500);
11777
+ }
11778
+ const limitQuery = number().int().min(1).max(LIMITS.listLimitMax);
11779
+ async function startMobileServer(deps, options) {
11780
+ const assets = await loadStaticAssets(deps.webRoot);
11781
+ const { settings, documents, render, views, cursors } = deps;
11782
+ const host = `${settings.host}:${String(settings.uiPort)}`;
11783
+ const origin = `https://${host}`;
11784
+ const previewOrigin = `https://${settings.host}:${String(settings.previewPort)}`;
11785
+ const streams = createEventStreams();
11786
+ const app = new Hono();
11787
+ app.use("*", async (c, next) => {
11788
+ await next();
11789
+ c.header("X-Content-Type-Options", "nosniff");
11790
+ c.header("Referrer-Policy", "no-referrer");
11791
+ if (!c.res.headers.has("Cache-Control")) c.header("Cache-Control", "no-store");
11792
+ });
11793
+ app.use("*", async (c, next) => {
11794
+ if (!deps.isOpen()) return fail(c, new VdeError("E_DAEMON_STOPPING", "Not ready."));
11795
+ const incoming = c.env.incoming;
11796
+ if (!incoming || !hasExactlyOne(incoming, "host", host)) {
11797
+ deps.onEvent?.("mobile.rejected", { reason: "host" });
11798
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Host."));
11799
+ }
11800
+ if (!isConfiguredPerson(incoming, settings.login)) {
11801
+ deps.onEvent?.("mobile.rejected", { reason: "identity" });
11802
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Identity."));
11803
+ }
11804
+ return next();
11805
+ });
11806
+ app.use(`${API_PREFIX}/*`, async (c, next) => {
11807
+ const requestOrigin = c.req.header("origin");
11808
+ if (requestOrigin !== void 0 && requestOrigin !== origin) {
11809
+ deps.onEvent?.("mobile.rejected", { reason: "origin" });
11810
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Origin."));
11811
+ }
11812
+ const site = c.req.header("sec-fetch-site");
11813
+ if (site !== void 0 && site !== "same-origin") {
11814
+ deps.onEvent?.("mobile.rejected", { reason: "fetch-site" });
11815
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Fetch site."));
11816
+ }
11817
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {
11818
+ if (requestOrigin === void 0) return fail(c, new VdeError("E_UNAUTHORIZED", "Origin."));
11819
+ }
11820
+ if (deps.isStopping()) return fail(c, new VdeError("E_DAEMON_STOPPING", "Stopping."));
11821
+ return next();
11822
+ });
11823
+ const rowOf = (summary) => ({
11824
+ documentId: summary.documentId,
11825
+ title: summary.title,
11826
+ format: summary.format,
11827
+ openedAt: summary.openedAt,
11828
+ revision: summary.revision,
11829
+ sourceState: summary.sourceState,
11830
+ effectiveMode: summary.format === "html" ? summary.interactiveAllowed ? "interactive" : "static" : null,
11831
+ viewEpoch: views.of(summary.documentId)
11832
+ });
11833
+ const requireCurrent = (documentId, revision, viewEpoch) => {
11834
+ const record = documents.state.documents[documentId];
11835
+ if (!record?.isOpen) throw new VdeError("E_DOCUMENT_NOT_OPEN", "Not open.");
11836
+ if (record.currentRevision !== revision || views.of(documentId) !== viewEpoch) throw new VdeError("E_VIEW_STALE", "Stale.");
11837
+ return record;
11838
+ };
11839
+ const api = new Hono();
11840
+ api.get("/documents", (c) => {
11841
+ const cursor = c.req.query("cursor");
11842
+ const limit = c.req.query("limit");
11843
+ let inner;
11844
+ if (cursor !== void 0) {
11845
+ const payload = cursors.decode(cursor, "mobile-list");
11846
+ if (payload["catalogVersion"] !== documents.state.catalogVersion) throw new VdeError("E_CURSOR_STALE", "Stale.");
11847
+ inner = payload["inner"];
11848
+ }
11849
+ const result = documents.list({
11850
+ limit: limit === void 0 ? LIMITS.listLimitMax : limitQuery.parse(limit),
11851
+ ...inner === void 0 ? {} : { cursor: inner }
11852
+ });
11853
+ const data = {
11854
+ daemonId: deps.daemonId,
11855
+ catalogVersion: result.catalogVersion,
11856
+ documents: result.data.documents.map(rowOf),
11857
+ nextCursor: result.data.nextCursor === null ? null : cursors.encode({
11858
+ op: "mobile-list",
11859
+ inner: result.data.nextCursor,
11860
+ catalogVersion: result.catalogVersion
11861
+ })
11862
+ };
11863
+ return c.json(successEnvelope(data, {
11864
+ command: "mobile.documents",
11865
+ catalogVersion: result.catalogVersion
11866
+ }));
11867
+ });
11868
+ api.get("/documents/:id/content", async (c) => {
11869
+ const documentId = c.req.param("id");
11870
+ const cursor = c.req.query("cursor");
11871
+ let bound;
11872
+ if (cursor === void 0) bound = {
11873
+ revision: revisionSchema.parse(c.req.query("revision")),
11874
+ viewEpoch: viewEpochSchema.parse(c.req.query("viewEpoch")),
11875
+ inner: void 0
11876
+ };
11877
+ else {
11878
+ const payload = cursors.decode(cursor, "mobile-read");
11879
+ if (payload["documentId"] !== documentId) throw new VdeError("E_INVALID_CURSOR", "Other.");
11880
+ bound = {
11881
+ revision: payload["revision"],
11882
+ viewEpoch: payload["viewEpoch"],
11883
+ inner: payload["inner"]
11534
11884
  };
11885
+ }
11886
+ if (requireCurrent(documentId, bound.revision, bound.viewEpoch).format !== "markdown") throw new VdeError("E_UNSUPPORTED_FORMAT", "Format.");
11887
+ const read = await documents.read(bound.inner === void 0 ? {
11888
+ documentId,
11889
+ revision: bound.revision,
11890
+ maxBytes: LIMITS.readMaxBytesMax
11891
+ } : {
11892
+ documentId,
11893
+ cursor: bound.inner,
11894
+ maxBytes: LIMITS.readMaxBytesMax
11895
+ });
11896
+ requireCurrent(documentId, bound.revision, bound.viewEpoch);
11897
+ const data = {
11898
+ documentId,
11899
+ revision: read.data.revision,
11900
+ content: read.data.content ?? "",
11901
+ nextCursor: read.data.nextCursor === null ? null : cursors.encode({
11902
+ op: "mobile-read",
11903
+ documentId,
11904
+ revision: bound.revision,
11905
+ viewEpoch: bound.viewEpoch,
11906
+ inner: read.data.nextCursor
11907
+ })
11908
+ };
11909
+ return c.json(successEnvelope(data, {
11910
+ command: "mobile.content",
11911
+ catalogVersion: documents.state.catalogVersion
11912
+ }));
11913
+ });
11914
+ api.post("/documents/:id/render-grants", async (c) => {
11915
+ const expected = mobileGrantParamsSchema.parse(await jsonBody(c));
11916
+ const data = await render.createMobileGrant(c.req.param("id"), expected);
11917
+ return c.json(successEnvelope(data, {
11918
+ command: "mobile.render-grant",
11919
+ catalogVersion: documents.state.catalogVersion
11920
+ }));
11921
+ });
11922
+ api.post("/render-grants/release", async (c) => {
11923
+ const { grants } = mobileReleaseParamsSchema.parse(await jsonBody(c));
11924
+ return c.json(successEnvelope({ released: render.releaseMobile(grants) }, { command: "mobile.render-release" }));
11925
+ });
11926
+ api.post("/render-grants/check", async (c) => {
11927
+ const { grant } = mobileCheckParamsSchema.parse(await jsonBody(c));
11928
+ return c.json(successEnvelope({ valid: render.checkMobile(grant) }, { command: "mobile.render-check" }));
11929
+ });
11930
+ api.post("/links/resolve", async (c) => {
11931
+ const { grant, linkId } = mobileLinkParamsSchema.parse(await jsonBody(c));
11932
+ if (!render.checkMobile(grant)) throw new VdeError("E_VIEW_STALE", "Stale.");
11933
+ const found = render.mobileLinkOf(grant, linkId);
11934
+ const documentId = found?.link.kind === "document" ? await documents.openDocumentOfLink(found.documentId, found.link.href) : null;
11935
+ if (!render.checkMobile(grant)) throw new VdeError("E_VIEW_STALE", "Stale.");
11936
+ const data = documentId === null || !documents.state.documents[documentId]?.isOpen ? { status: "not-open" } : {
11937
+ status: "open",
11938
+ documentId
11939
+ };
11940
+ return c.json(successEnvelope(data, { command: "mobile.link-resolve" }));
11941
+ });
11942
+ const frameOf = (event) => {
11943
+ let type;
11944
+ switch (event.type) {
11945
+ case "hello":
11946
+ case "resync-required":
11947
+ case "daemon-stopping":
11948
+ type = event.type;
11949
+ break;
11950
+ case "catalog-changed":
11951
+ case "document-changed":
11952
+ case "document-status":
11953
+ type = "changed";
11954
+ break;
11955
+ default: return null;
11956
+ }
11957
+ const data = {
11958
+ type,
11959
+ daemonId: event.daemonId,
11960
+ ...type === "changed" && event.documentId !== void 0 ? { documentId: event.documentId } : {}
11961
+ };
11962
+ return {
11963
+ event: type,
11964
+ data: JSON.stringify(data)
11965
+ };
11966
+ };
11967
+ api.get("/events", (c) => streams.open(c, {
11968
+ hello: {
11969
+ type: "hello",
11970
+ daemonId: deps.daemonId,
11971
+ sequence: deps.events.sequence,
11972
+ catalogVersion: documents.state.catalogVersion
11535
11973
  },
11974
+ subscribe: (listener) => deps.events.subscribe(listener),
11975
+ frame: frameOf,
11976
+ heartbeatMs: deps.heartbeatMs,
11977
+ stallMs: deps.stallMs
11978
+ }));
11979
+ api.all("*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown.")));
11980
+ api.onError((error, c) => fail(c, error));
11981
+ app.route(API_PREFIX, api);
11982
+ app.all("/_/*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown.")));
11983
+ app.on(["GET", "HEAD"], "*", (c) => {
11984
+ const path = c.req.path;
11985
+ const asset = path === "/" ? assets.get("/mobile.html") : path.startsWith("/assets/") ? assets.get(path) : void 0;
11986
+ if (!asset) {
11987
+ if (path === "/") return c.text("The phone reader UI has not been built. Run pnpm build.", 503);
11988
+ return c.text("Not Found", 404);
11989
+ }
11990
+ const headers = { "Content-Type": asset.type };
11991
+ if (asset.immutable) headers["Cache-Control"] = "public, max-age=31536000, immutable";
11992
+ if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp(previewOrigin);
11993
+ if (c.req.method === "HEAD") return c.body(null, 200, headers);
11994
+ return c.body(new Uint8Array(asset.body), 200, headers);
11995
+ });
11996
+ app.all("*", (c) => c.text("Method Not Allowed", 405));
11997
+ app.onError((error, c) => fail(c, error));
11998
+ const server = serve({
11999
+ fetch: app.fetch,
12000
+ hostname: "127.0.0.1",
12001
+ port: options.port
12002
+ });
12003
+ await new Promise((resolve, reject) => {
12004
+ server.once("listening", resolve);
12005
+ server.once("error", reject);
12006
+ });
12007
+ const { port } = server.address();
12008
+ return {
12009
+ port,
12010
+ eventStreams: () => streams.stats(),
11536
12011
  async close() {
11537
- for (const finish of streams.keys()) finish();
12012
+ streams.finishAll();
11538
12013
  await new Promise((resolve) => setTimeout(resolve, STREAM_FLUSH_MS));
11539
12014
  await new Promise((resolve) => {
11540
12015
  server.close(() => resolve());
@@ -11610,6 +12085,9 @@ async function startPreviewServer(deps, options = {}) {
11610
12085
  };
11611
12086
  const handle = async (request, response) => {
11612
12087
  if (request.headers.host !== host) return reject(response, 404);
12088
+ if (deps.publicHost !== void 0 && request.headersDistinct["host"]?.length !== 1) return reject(response, 404);
12089
+ if (deps.isOpen && !deps.isOpen()) return reject(response, 404);
12090
+ if (deps.authorize && !deps.authorize(request)) return reject(response, 404);
11613
12091
  const method = request.method ?? "";
11614
12092
  if (method !== "GET" && method !== "HEAD") return reject(response, 405, { Allow: "GET, HEAD" });
11615
12093
  let pathname;
@@ -11621,7 +12099,7 @@ async function startPreviewServer(deps, options = {}) {
11621
12099
  const match = PREVIEW_PATH.exec(pathname);
11622
12100
  const logicalPath = match ? logicalPathOf(match[2]) : null;
11623
12101
  if (!match || logicalPath === null) return reject(response, 404);
11624
- const file = await deps.render.resolve(match[1], logicalPath);
12102
+ const file = await deps.resolve(match[1], logicalPath);
11625
12103
  if (!file) return reject(response, 404);
11626
12104
  response.writeHead(200, headersFor(file, origin, deps.frameAncestors()));
11627
12105
  response.end(method === "HEAD" ? void 0 : file.body);
@@ -11638,8 +12116,8 @@ async function startPreviewServer(deps, options = {}) {
11638
12116
  server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
11639
12117
  });
11640
12118
  const { port } = server.address();
11641
- host = `127.0.0.1:${String(port)}`;
11642
- origin = `http://${host}`;
12119
+ host = deps.publicHost ?? `127.0.0.1:${String(port)}`;
12120
+ origin = deps.publicHost === void 0 ? `http://${host}` : `https://${host}`;
11643
12121
  return {
11644
12122
  port,
11645
12123
  origin,
@@ -13796,8 +14274,8 @@ const execFileAsync = promisify(execFile);
13796
14274
  const GENERATION_DIGITS = 12;
13797
14275
  const ACQUIRE_ATTEMPTS = 8;
13798
14276
  const lockInfoSchema = strictObject({
13799
- generation: number().int().positive(),
13800
- pid: number().int().positive(),
14277
+ generation: number$1().int().positive(),
14278
+ pid: number$1().int().positive(),
13801
14279
  ownerId: string().min(1),
13802
14280
  startedAt: string(),
13803
14281
  released: boolean()
@@ -13983,6 +14461,100 @@ async function releaseLock(directory, name, ownerId) {
13983
14461
  await renameWithRetry(temp, join(directory, fileNameOf(name, current.generation)));
13984
14462
  }
13985
14463
  //#endregion
14464
+ //#region src/daemon/listener-config.ts
14465
+ const LISTENER_CONFIG_FILE = "listeners.json";
14466
+ const DEFAULT_PORTS = {
14467
+ management: 43180,
14468
+ preview: 43181,
14469
+ mobileUi: 43182,
14470
+ mobilePreview: 43183
14471
+ };
14472
+ const portSchema = number$1().int().min(1).max(65535);
14473
+ const pcConfigSchema = strictObject({
14474
+ managementPort: portSchema.optional(),
14475
+ previewPort: portSchema.optional(),
14476
+ mobile: unknown().optional()
14477
+ });
14478
+ function configError(path, reason, message) {
14479
+ return new VdeError("E_DAEMON_START_FAILED", `${message} (${path})`, {
14480
+ reason: "listener-config",
14481
+ path,
14482
+ issue: reason
14483
+ });
14484
+ }
14485
+ async function readListenerConfig(stateRoot) {
14486
+ const path = join(stateRoot, LISTENER_CONFIG_FILE);
14487
+ let text;
14488
+ try {
14489
+ text = await readFile(path, "utf8");
14490
+ } catch (error) {
14491
+ const code = error.code;
14492
+ if (code === "ENOENT") {
14493
+ if (await lstat(path).then(() => "present", (inspect) => inspect.code ?? "unreadable") === "ENOENT") return {};
14494
+ }
14495
+ throw configError(path, code ?? "unreadable", "The listener settings could not be read.");
14496
+ }
14497
+ let json;
14498
+ try {
14499
+ json = JSON.parse(text);
14500
+ } catch {
14501
+ throw configError(path, "json", "The listener settings are not valid JSON.");
14502
+ }
14503
+ const parsed = pcConfigSchema.safeParse(json);
14504
+ if (!parsed.success) {
14505
+ const issue = parsed.error.issues[0];
14506
+ const where = issue && issue.path.length > 0 ? issue.path.join(".") : "root";
14507
+ throw configError(path, `invalid:${where}`, `The listener settings are invalid at ${where}.`);
14508
+ }
14509
+ return parsed.data;
14510
+ }
14511
+ function ephemeralPortsAllowed(environment) {
14512
+ const home = environment.env["VDE_OPEN_HOME"];
14513
+ return environment.env["VDE_OPEN_TEST_EPHEMERAL_PORTS"] === "1" && home !== void 0 && home !== "" && isAbsolute(home);
14514
+ }
14515
+ function resolvePcPorts(explicit, config, ephemeral) {
14516
+ const pick = (argument, configured, fallback) => argument ?? configured ?? (ephemeral ? 0 : fallback);
14517
+ const ports = {
14518
+ management: pick(explicit.managementPort, config.managementPort, DEFAULT_PORTS.management),
14519
+ preview: pick(explicit.previewPort, config.previewPort, DEFAULT_PORTS.preview)
14520
+ };
14521
+ if (ports.management !== 0 && ports.management === ports.preview) throw new VdeError("E_DAEMON_START_FAILED", `The management and preview listeners cannot share port ${String(ports.management)}.`, {
14522
+ reason: "duplicate-port",
14523
+ port: ports.management
14524
+ });
14525
+ return ports;
14526
+ }
14527
+ const mobilePortSchema = portSchema.refine((port) => port !== 443, "must not be 443");
14528
+ const DNS_LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
14529
+ const DNS_NAME = new RegExp(`^(?=.{1,253}$)${DNS_LABEL}(?:\\.${DNS_LABEL})+$`);
14530
+ const mobileSchema = strictObject({
14531
+ host: string().transform((value) => value.toLowerCase().replace(/\.$/, "")).refine((value) => DNS_NAME.test(value), "must be a full DNS name without scheme, port, or path"),
14532
+ login: string().regex(/^[!-+\--~]{1,256}$/, "must be an ASCII login name"),
14533
+ uiPort: mobilePortSchema.default(DEFAULT_PORTS.mobileUi),
14534
+ previewPort: mobilePortSchema.default(DEFAULT_PORTS.mobilePreview)
14535
+ });
14536
+ function resolveMobileConfig(raw, pcPorts) {
14537
+ if (raw === void 0) return { state: "disabled" };
14538
+ const parsed = mobileSchema.safeParse(raw);
14539
+ if (!parsed.success) {
14540
+ const issue = parsed.error.issues[0];
14541
+ return {
14542
+ state: "error",
14543
+ reason: `invalid:${issue && issue.path.length > 0 ? `mobile.${issue.path.join(".")}` : "mobile"}`
14544
+ };
14545
+ }
14546
+ const settings = parsed.data;
14547
+ const taken = [pcPorts.management, pcPorts.preview].filter((port) => port !== 0);
14548
+ if (settings.uiPort === settings.previewPort || taken.includes(settings.uiPort) || taken.includes(settings.previewPort)) return {
14549
+ state: "error",
14550
+ reason: "duplicate-port"
14551
+ };
14552
+ return {
14553
+ state: "enabled",
14554
+ settings
14555
+ };
14556
+ }
14557
+ //#endregion
13986
14558
  //#region src/daemon/logger.ts
13987
14559
  const MAX_LOG_BYTES = 1048576;
13988
14560
  function createFileLogger(stateRoot) {
@@ -14019,8 +14591,8 @@ const START_LOCK_NAME = "start.lock";
14019
14591
  const POINTER_FILE = "runtime-pointer.json";
14020
14592
  const runtimePointerSchema = strictObject({
14021
14593
  daemonId: string().min(1),
14022
- pid: number().int().positive(),
14023
- protocolVersion: number().int(),
14594
+ pid: number$1().int().positive(),
14595
+ protocolVersion: number$1().int(),
14024
14596
  version: string(),
14025
14597
  startedAt: string(),
14026
14598
  runtimeDir: string().min(1),
@@ -14116,6 +14688,19 @@ async function requirePrivateDirectoryIfExists(path, options) {
14116
14688
  const LOCK_CHECK_INTERVAL_MS = 2e3;
14117
14689
  const SHUTDOWN_CLOSE_TIMEOUT_MS = 5e3;
14118
14690
  const diagnosticsParamsSchema = strictObject({ collectGarbage: boolean().default(false) });
14691
+ async function listenOrFail(listener, port, start) {
14692
+ try {
14693
+ return await start();
14694
+ } catch (error) {
14695
+ const cause = error?.code ?? "unknown";
14696
+ throw new VdeError("E_DAEMON_START_FAILED", `The ${listener} listener could not listen on 127.0.0.1:${String(port)} (${cause}).`, {
14697
+ reason: "listen",
14698
+ listener,
14699
+ port,
14700
+ cause
14701
+ }, { cause: error });
14702
+ }
14703
+ }
14119
14704
  async function startDaemon(options) {
14120
14705
  const { environment, version } = options;
14121
14706
  const probe = options.probe ?? systemProcessProbe;
@@ -14141,6 +14726,8 @@ async function startDaemon(options) {
14141
14726
  let ipc = null;
14142
14727
  let management = null;
14143
14728
  let preview = null;
14729
+ let mobileUi = null;
14730
+ let mobilePreview = null;
14144
14731
  let watcher = null;
14145
14732
  let parse = null;
14146
14733
  let printer = null;
@@ -14191,6 +14778,8 @@ async function startDaemon(options) {
14191
14778
  await step("management", () => management?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14192
14779
  await step("pdf", () => pdf?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14193
14780
  await step("preview", () => preview?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14781
+ await step("mobile-ui", () => mobileUi?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14782
+ await step("mobile-preview", () => mobilePreview?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14194
14783
  await step("store", () => store?.close());
14195
14784
  await step("parse", () => parse?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14196
14785
  await step("print", () => printer?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
@@ -14223,6 +14812,10 @@ async function startDaemon(options) {
14223
14812
  return stopping;
14224
14813
  };
14225
14814
  try {
14815
+ const listenerConfig = await readListenerConfig(stateRoot);
14816
+ const ephemeral = ephemeralPortsAllowed(environment);
14817
+ const ports = resolvePcPorts(options, listenerConfig, ephemeral);
14818
+ const mobileConfig = resolveMobileConfig(listenerConfig.mobile, ports);
14226
14819
  store = await StateStore.open({
14227
14820
  root: stateRoot,
14228
14821
  fs: options.fs ?? nodeStoreFs
@@ -14252,7 +14845,9 @@ async function startDaemon(options) {
14252
14845
  analyze: (format, text) => parser.analyze(format, text)
14253
14846
  });
14254
14847
  const searching = search;
14848
+ let views = null;
14255
14849
  const emit = (event) => {
14850
+ views?.observe();
14256
14851
  if (event.type !== "focus-requested" && event.type !== "feedback-changed" && event.type !== "render-diagnostics") searching.sync();
14257
14852
  events.publish(event);
14258
14853
  if (event.type === "catalog-changed") {
@@ -14269,6 +14864,8 @@ async function startDaemon(options) {
14269
14864
  scan: (kind, text) => parser.scan(kind, text),
14270
14865
  emit
14271
14866
  });
14867
+ const viewing = createViewEpochs(documents);
14868
+ views = viewing;
14272
14869
  await documents.initializeRepositories();
14273
14870
  feedback = new FeedbackService({
14274
14871
  store: openedStore,
@@ -14285,6 +14882,10 @@ async function startDaemon(options) {
14285
14882
  documents,
14286
14883
  parse: parser,
14287
14884
  previewOrigin: () => previewOrigin,
14885
+ mobile: mobileConfig.state === "enabled" ? {
14886
+ previewOrigin: () => `https://${mobileConfig.settings.host}:${String(mobileConfig.settings.previewPort)}`,
14887
+ viewEpochOf: (documentId) => viewing.of(documentId)
14888
+ } : void 0,
14288
14889
  onMissing: (documentId) => emit({
14289
14890
  type: "render-diagnostics",
14290
14891
  documentId
@@ -14301,13 +14902,13 @@ async function startDaemon(options) {
14301
14902
  onEvent: (event, fields) => logger.log(event, fields)
14302
14903
  });
14303
14904
  pdf = exporting;
14304
- preview = await startPreviewServer({
14305
- render,
14905
+ preview = await listenOrFail("preview", ports.preview, () => startPreviewServer({
14906
+ resolve: (grant, logicalPath) => render.resolve(grant, logicalPath),
14306
14907
  frameAncestors: () => [managementOrigin, devOrigin].filter((origin) => origin !== null),
14307
14908
  onEvent: (event, fields) => logger.log(event, fields)
14308
- }, options.previewPort === void 0 ? {} : { port: options.previewPort });
14909
+ }, { port: ports.preview }));
14309
14910
  previewOrigin = preview.origin;
14310
- management = await startManagementServer({
14911
+ management = await listenOrFail("management", ports.management, () => startManagementServer({
14311
14912
  daemonId,
14312
14913
  version,
14313
14914
  documents,
@@ -14321,9 +14922,72 @@ async function startDaemon(options) {
14321
14922
  devOrigin,
14322
14923
  isStopping: () => stopping !== null,
14323
14924
  onEvent: (event, fields) => logger.log(event, fields)
14324
- }, options.managementPort === void 0 ? {} : { port: options.managementPort });
14925
+ }, { port: ports.management }));
14325
14926
  managementOrigin = management.origin;
14326
14927
  const uiUrl = `${management.origin}/`;
14928
+ let mobileStatus = mobileConfig.state === "disabled" ? { state: "disabled" } : mobileConfig.state === "error" ? {
14929
+ state: "error",
14930
+ listener: null,
14931
+ port: null,
14932
+ reason: mobileConfig.reason
14933
+ } : { state: "disabled" };
14934
+ let mobileOpen = false;
14935
+ if (mobileConfig.state === "enabled") {
14936
+ const settings = mobileConfig.settings;
14937
+ const local = ephemeral ? {
14938
+ ui: 0,
14939
+ preview: 0
14940
+ } : {
14941
+ ui: settings.uiPort,
14942
+ preview: settings.previewPort
14943
+ };
14944
+ let failing = "preview";
14945
+ try {
14946
+ mobilePreview = await listenOrFail("mobile preview", local.preview, () => startPreviewServer({
14947
+ resolve: (grant, logicalPath) => render.resolveMobile(grant, logicalPath),
14948
+ frameAncestors: () => [`https://${settings.host}:${String(settings.uiPort)}`],
14949
+ publicHost: `${settings.host}:${String(settings.previewPort)}`,
14950
+ authorize: (request) => isConfiguredPerson(request, settings.login),
14951
+ isOpen: () => mobileOpen,
14952
+ onEvent: (event, fields) => logger.log(`mobile.${event}`, fields)
14953
+ }, { port: local.preview }));
14954
+ failing = "ui";
14955
+ mobileUi = await listenOrFail("mobile UI", local.ui, () => startMobileServer({
14956
+ daemonId,
14957
+ settings,
14958
+ documents,
14959
+ events,
14960
+ render,
14961
+ views: viewing,
14962
+ cursors,
14963
+ webRoot: webRootPath(),
14964
+ isStopping: () => stopping !== null,
14965
+ isOpen: () => mobileOpen,
14966
+ onEvent: (event, fields) => logger.log(event, fields)
14967
+ }, { port: local.ui }));
14968
+ mobileOpen = true;
14969
+ mobileStatus = {
14970
+ state: "ready",
14971
+ uiUrl: `https://${settings.host}:${String(settings.uiPort)}/`
14972
+ };
14973
+ } catch (error) {
14974
+ await mobileUi?.close();
14975
+ await mobilePreview?.close();
14976
+ mobileUi = null;
14977
+ mobilePreview = null;
14978
+ const cause = error instanceof VdeError && typeof error.details["cause"] === "string" ? error.details["cause"] : "unknown";
14979
+ mobileStatus = {
14980
+ state: "error",
14981
+ listener: failing,
14982
+ port: failing === "ui" ? settings.uiPort : settings.previewPort,
14983
+ reason: cause
14984
+ };
14985
+ logger.log("mobile.start-failed", {
14986
+ listener: failing,
14987
+ code: cause
14988
+ });
14989
+ }
14990
+ }
14327
14991
  watcher = createWatchService({
14328
14992
  documents,
14329
14993
  onEvent: (event, fields) => logger.log(event, fields)
@@ -14344,7 +15008,8 @@ async function startDaemon(options) {
14344
15008
  stateRoot,
14345
15009
  openDocuments: openedStore.payload.openOrder.length,
14346
15010
  catalogVersion: openedStore.payload.catalogVersion,
14347
- uiUrl
15011
+ uiUrl,
15012
+ mobile: mobileStatus
14348
15013
  },
14349
15014
  catalogVersion: openedStore.payload.catalogVersion
14350
15015
  };
@@ -14368,6 +15033,14 @@ async function startDaemon(options) {
14368
15033
  maxPending: 0
14369
15034
  },
14370
15035
  renderGrants: render.grantCount,
15036
+ mobileEventStreams: mobileUi?.eventStreams() ?? {
15037
+ streams: 0,
15038
+ maxPending: 0
15039
+ },
15040
+ ...ephemeral && mobileStatus.state === "ready" && mobileUi && mobilePreview ? { mobileBoundPorts: {
15041
+ ui: mobileUi.port,
15042
+ preview: mobilePreview.port
15043
+ } } : {},
14371
15044
  retained: {
14372
15045
  documents: documents.retainedCounts(),
14373
15046
  search: search?.retainedCounts() ?? {},
@@ -14469,4 +15142,4 @@ async function startDaemon(options) {
14469
15142
  };
14470
15143
  }
14471
15144
  //#endregion
14472
- export { decodeStateFile as C, daemonEntryPath as D, resolveStateRoot as E, referencedBlobs as O, renameWithRetry as S, resolveRuntimeLocation as T, HANDSHAKE_TIMEOUT_MS as _, DAEMON_LOCK_NAME as a, proofMatches as b, readIpcKey as c, inspectOwner as d, readCurrentLock as f, encodeFrame as g, FrameDecoder as h, requirePrivateDirectoryIfExists as i, version as k, readPointer as l, systemProcessProbe as m, ensurePrivateDirectory as n, POINTER_FILE as o, releaseLock as p, inspectPrivateDirectory as r, START_LOCK_NAME as s, startDaemon as t, acquireLock as u, computeProof as v, currentPathEnvironment as w, removeWithRetry as x, createNonce as y };
15145
+ export { resolveRuntimeLocation as A, computeProof as C, renameWithRetry as D, removeWithRetry as E, daemonEntryPath as M, referencedBlobs as N, decodeStateFile as O, version as P, HANDSHAKE_TIMEOUT_MS as S, proofMatches as T, readCurrentLock as _, DAEMON_LOCK_NAME as a, FrameDecoder as b, readIpcKey as c, LISTENER_CONFIG_FILE as d, readListenerConfig as f, inspectOwner as g, acquireLock as h, requirePrivateDirectoryIfExists as i, resolveStateRoot as j, currentPathEnvironment as k, readPointer as l, resolvePcPorts as m, ensurePrivateDirectory as n, POINTER_FILE as o, resolveMobileConfig as p, inspectPrivateDirectory as r, START_LOCK_NAME as s, startDaemon as t, DEFAULT_PORTS as u, releaseLock as v, createNonce as w, encodeFrame as x, systemProcessProbe as y };