@mostra/protocol 0.4.0 → 0.6.0

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.
@@ -0,0 +1,24 @@
1
+ import * as z from "zod";
2
+ //#region src/receive.d.ts
3
+ /**
4
+ * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union
5
+ * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record
6
+ * still needs every key it names); a discriminated union accepts, besides its members, an object
7
+ * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields
8
+ * rather than refuse them. Everything else (fields, types, required members, limits) is checked as
9
+ * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts
10
+ * reads exactly as `schema` reads it: a union tries its members as built before their opened
11
+ * copies, and a discriminated union's members keep their own tags.
12
+ *
13
+ * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type
14
+ * doesn't name means a newer peer. Code that branches on such a field handles the other case, and
15
+ * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on
16
+ * the absence of the one it knows means failing.
17
+ *
18
+ * ```ts
19
+ * const parsed = receivable(definition.result).safeParse(raw);
20
+ * ```
21
+ */
22
+ export declare function receivable<T>(schema: z.ZodType<T>): z.ZodType<T>;
23
+ //#endregion
24
+ //# sourceMappingURL=receive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.d.ts","names":[],"sources":["../src/receive.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAoCgB,WAAW,GAAG,QAAQ,EAAE,QAAQ,KAAK,EAAE,QAAQ"}
@@ -0,0 +1,137 @@
1
+ import * as z from "zod";
2
+ //#region src/receive.ts
3
+ /**
4
+ * Reading what a newer peer sends (HO-07, D32, #45). Within a revision a peer may add values to an
5
+ * enum and members to a union: the wire schemas' evolution rule counts both as additive
6
+ * (`tools/schemas/compat.ts`). A receiver checking such a message against the schemas it was built
7
+ * with would refuse the whole message for one value it doesn't know, so it checks it against
8
+ * {@link receivable}'s copy instead, as the Rust crate's wire types read an `Unknown` variant.
9
+ */
10
+ const opened = /* @__PURE__ */ new WeakMap();
11
+ /**
12
+ * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union
13
+ * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record
14
+ * still needs every key it names); a discriminated union accepts, besides its members, an object
15
+ * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields
16
+ * rather than refuse them. Everything else (fields, types, required members, limits) is checked as
17
+ * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts
18
+ * reads exactly as `schema` reads it: a union tries its members as built before their opened
19
+ * copies, and a discriminated union's members keep their own tags.
20
+ *
21
+ * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type
22
+ * doesn't name means a newer peer. Code that branches on such a field handles the other case, and
23
+ * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on
24
+ * the absence of the one it knows means failing.
25
+ *
26
+ * ```ts
27
+ * const parsed = receivable(definition.result).safeParse(raw);
28
+ * ```
29
+ */
30
+ function receivable(schema) {
31
+ return open(schema);
32
+ }
33
+ function open(schema) {
34
+ const known = opened.get(schema);
35
+ if (known) return known;
36
+ let result;
37
+ opened.set(schema, z.lazy(() => result ?? schema));
38
+ result = rebuild(schema);
39
+ opened.set(schema, result);
40
+ return result;
41
+ }
42
+ /** Any string, with the checks `schema` carries (an enum's `.refine`, say). */
43
+ function anyString(schema) {
44
+ const checks = defOf(schema)["checks"];
45
+ return checks?.length ? cloned(z.string(), { checks }) : z.string();
46
+ }
47
+ function defOf(schema) {
48
+ return schema._zod.def;
49
+ }
50
+ /** A copy of `schema` with some of its definition replaced; its checks and settings stay. */
51
+ function cloned(schema, changes) {
52
+ return schema.clone({
53
+ ...defOf(schema),
54
+ ...changes
55
+ });
56
+ }
57
+ /** The string values of a literal or enum node, or undefined when it has others. */
58
+ function strings(schema) {
59
+ const def = defOf(schema);
60
+ const values = def.type === "literal" ? def["values"] : def.type === "enum" ? Object.values(def["entries"]) : void 0;
61
+ return values?.every((value) => typeof value === "string") ? values : void 0;
62
+ }
63
+ function rebuild(schema) {
64
+ const def = defOf(schema);
65
+ switch (def.type) {
66
+ case "enum": return strings(schema) ? anyString(schema) : schema;
67
+ case "optional":
68
+ case "nullable":
69
+ case "readonly":
70
+ case "default":
71
+ case "prefault":
72
+ case "nonoptional":
73
+ case "catch": return cloned(schema, { innerType: open(def["innerType"]) });
74
+ case "array": return cloned(schema, { element: open(def["element"]) });
75
+ case "object": {
76
+ const shape = def["shape"];
77
+ const catchall = def["catchall"];
78
+ return cloned(schema, {
79
+ shape: Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, open(value)])),
80
+ catchall: catchall === void 0 || defOf(catchall).type === "never" ? void 0 : open(catchall)
81
+ });
82
+ }
83
+ case "record": {
84
+ const keyType = def["keyType"];
85
+ if (strings(keyType) && !def["partial"]) return cloned(schema, {
86
+ valueType: open(def["valueType"]),
87
+ mode: "loose"
88
+ });
89
+ return cloned(schema, {
90
+ keyType: open(keyType),
91
+ valueType: open(def["valueType"])
92
+ });
93
+ }
94
+ case "tuple": return cloned(schema, {
95
+ items: def["items"].map(open),
96
+ rest: def["rest"] ? open(def["rest"]) : def["rest"]
97
+ });
98
+ case "intersection": return cloned(schema, {
99
+ left: open(def["left"]),
100
+ right: open(def["right"])
101
+ });
102
+ case "pipe": return cloned(schema, { in: open(def["in"]) });
103
+ case "lazy": {
104
+ const getter = def["getter"];
105
+ return z.lazy(() => open(getter()));
106
+ }
107
+ case "union": return union(schema, def);
108
+ default: return schema;
109
+ }
110
+ }
111
+ function union(schema, def) {
112
+ const options = def["options"];
113
+ if (options.every((option) => strings(option) !== void 0)) return anyString(schema);
114
+ const anyOf = (members) => z.union([...options, ...members]);
115
+ const discriminator = def["discriminator"];
116
+ if (discriminator === void 0) return anyOf(options.map(open));
117
+ const tags = /* @__PURE__ */ new Set();
118
+ const members = [];
119
+ for (const option of options) {
120
+ const tag = defOf(option)["shape"]?.[discriminator];
121
+ const values = tag ? strings(tag) : void 0;
122
+ if (!tag || !values) return anyOf(options.map(open));
123
+ for (const value of values) tags.add(value);
124
+ const member = open(option);
125
+ const memberShape = defOf(member)["shape"];
126
+ members.push(cloned(member, { shape: {
127
+ ...memberShape,
128
+ [discriminator]: tag
129
+ } }));
130
+ }
131
+ const newer = z.looseObject({ [discriminator]: z.string().refine((value) => !tags.has(value)) });
132
+ return anyOf([...members, newer]);
133
+ }
134
+ //#endregion
135
+ export { receivable };
136
+
137
+ //# sourceMappingURL=receive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.js","names":[],"sources":["../src/receive.ts"],"sourcesContent":["/**\n * Reading what a newer peer sends (HO-07, D32, #45). Within a revision a peer may add values to an\n * enum and members to a union: the wire schemas' evolution rule counts both as additive\n * (`tools/schemas/compat.ts`). A receiver checking such a message against the schemas it was built\n * with would refuse the whole message for one value it doesn't know, so it checks it against\n * {@link receivable}'s copy instead, as the Rust crate's wire types read an `Unknown` variant.\n */\nimport * as z from \"zod\";\n\n/** A Zod node's definition, as far as {@link receivable} reads it. */\ninterface Def {\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\nconst opened = new WeakMap<z.ZodType, z.ZodType>();\n\n/**\n * `schema` as a receiver of a newer peer's messages checks it: every string enum and every union\n * of string literals accepts any string (an enum's own checks still run, and an enum-keyed record\n * still needs every key it names); a discriminated union accepts, besides its members, an object\n * whose discriminator is a string none of them has, kept whole; strict objects drop unknown fields\n * rather than refuse them. Everything else (fields, types, required members, limits) is checked as\n * before, so a message a newer peer couldn't have sent still fails, and a message `schema` accepts\n * reads exactly as `schema` reads it: a union tries its members as built before their opened\n * copies, and a discriminated union's members keep their own tags.\n *\n * The result keeps `schema`'s TypeScript type, the shape this side was built for: a value the type\n * doesn't name means a newer peer. Code that branches on such a field handles the other case, and\n * a gate (a verdict, a check, a delivery) passes only on a value it knows means passing, never on\n * the absence of the one it knows means failing.\n *\n * ```ts\n * const parsed = receivable(definition.result).safeParse(raw);\n * ```\n */\nexport function receivable<T>(schema: z.ZodType<T>): z.ZodType<T> {\n return open(schema) as z.ZodType<T>;\n}\n\nfunction open(schema: z.ZodType): z.ZodType {\n const known = opened.get(schema);\n if (known) return known;\n // A recursive schema (Zod's getter idiom) reaches itself while it is being opened: it finds this\n // stand-in, which reads the finished copy when a message is checked (Opus review of MT-01, 7).\n let result: z.ZodType | undefined;\n opened.set(\n schema,\n z.lazy(() => result ?? schema),\n );\n result = rebuild(schema);\n opened.set(schema, result);\n return result;\n}\n\n/** Any string, with the checks `schema` carries (an enum's `.refine`, say). */\nfunction anyString(schema: z.ZodType): z.ZodType {\n const checks = defOf(schema)[\"checks\"] as unknown[] | undefined;\n return checks?.length ? cloned(z.string(), { checks }) : z.string();\n}\n\nfunction defOf(schema: z.ZodType): Def {\n return (schema as unknown as { _zod: { def: Def } })._zod.def;\n}\n\n/** A copy of `schema` with some of its definition replaced; its checks and settings stay. */\nfunction cloned(schema: z.ZodType, changes: Record<string, unknown>): z.ZodType {\n return (schema as unknown as { clone(def: Def): z.ZodType }).clone({\n ...defOf(schema),\n ...changes,\n });\n}\n\n/** The string values of a literal or enum node, or undefined when it has others. */\nfunction strings(schema: z.ZodType): string[] | undefined {\n const def = defOf(schema);\n const values =\n def.type === \"literal\"\n ? (def[\"values\"] as unknown[])\n : def.type === \"enum\"\n ? Object.values(def[\"entries\"] as Record<string, unknown>)\n : undefined;\n return values?.every((value) => typeof value === \"string\") ? (values as string[]) : undefined;\n}\n\nfunction rebuild(schema: z.ZodType): z.ZodType {\n const def = defOf(schema);\n switch (def.type) {\n case \"enum\":\n return strings(schema) ? anyString(schema) : schema;\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"prefault\":\n case \"nonoptional\":\n case \"catch\":\n return cloned(schema, { innerType: open(def[\"innerType\"] as z.ZodType) });\n case \"array\":\n return cloned(schema, { element: open(def[\"element\"] as z.ZodType) });\n case \"object\": {\n const shape = def[\"shape\"] as Record<string, z.ZodType>;\n const catchall = def[\"catchall\"] as z.ZodType | undefined;\n return cloned(schema, {\n shape: Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, open(value)])),\n // A strict object (catchall `never`) would refuse a field a newer peer adds: it is dropped\n // instead. A loose object keeps passing its fields through, and a typed catchall keeps\n // checking them (GPT review of MT-01: the bridge's host context passes fields through).\n catchall:\n catchall === undefined || defOf(catchall).type === \"never\" ? undefined : open(catchall),\n });\n }\n case \"record\": {\n const keyType = def[\"keyType\"] as z.ZodType;\n // Keys from an enum: every one it names is still required, and a key a newer peer adds\n // passes through, as Zod's loose records do (Opus review of MT-01, 2).\n if (strings(keyType) && !def[\"partial\"]) {\n return cloned(schema, { valueType: open(def[\"valueType\"] as z.ZodType), mode: \"loose\" });\n }\n return cloned(schema, {\n keyType: open(keyType),\n valueType: open(def[\"valueType\"] as z.ZodType),\n });\n }\n case \"tuple\":\n return cloned(schema, {\n items: (def[\"items\"] as z.ZodType[]).map(open),\n rest: def[\"rest\"] ? open(def[\"rest\"] as z.ZodType) : def[\"rest\"],\n });\n case \"intersection\":\n return cloned(schema, {\n left: open(def[\"left\"] as z.ZodType),\n right: open(def[\"right\"] as z.ZodType),\n });\n case \"pipe\":\n return cloned(schema, { in: open(def[\"in\"] as z.ZodType) });\n case \"lazy\": {\n const getter = def[\"getter\"] as () => z.ZodType;\n return z.lazy(() => open(getter()));\n }\n case \"union\":\n return union(schema, def);\n default:\n return schema;\n }\n}\n\nfunction union(schema: z.ZodType, def: Def): z.ZodType {\n const options = def[\"options\"] as z.ZodType[];\n // A union of string literals is an enum written another way.\n if (options.every((option) => strings(option) !== undefined)) return anyString(schema);\n // The members as built come first, so whatever they accept reads as before; their opened copies\n // only take what none of them does (Opus review of MT-01, 1).\n const anyOf = (members: z.ZodType[]): z.ZodType =>\n z.union([...options, ...members] as [z.ZodType, ...z.ZodType[]]);\n const discriminator = def[\"discriminator\"] as string | undefined;\n if (discriminator === undefined) return anyOf(options.map(open));\n const tags = new Set<string>();\n const members: z.ZodType[] = [];\n for (const option of options) {\n const shape = defOf(option)[\"shape\"] as Record<string, z.ZodType> | undefined;\n const tag = shape?.[discriminator];\n const values = tag ? strings(tag) : undefined;\n // A member whose tag isn't a string literal: no newer member can be told from a broken one.\n if (!tag || !values) return anyOf(options.map(open));\n for (const value of values) tags.add(value);\n // An opened member keeps its own tag: widened, an enum tag would take every member's messages.\n const member = open(option);\n const memberShape = defOf(member)[\"shape\"] as Record<string, z.ZodType>;\n members.push(cloned(member, { shape: { ...memberShape, [discriminator]: tag } }));\n }\n const newer = z.looseObject({\n [discriminator]: z.string().refine((value) => !tags.has(value)),\n });\n return anyOf([...members, newer]);\n}\n"],"mappings":";;;;;;;;;AAeA,MAAM,yBAAS,IAAI,QAA8B;;;;;;;;;;;;;;;;;;;;AAqBjD,SAAgB,WAAc,QAAoC;CAChE,OAAO,KAAK,MAAM;AACpB;AAEA,SAAS,KAAK,QAA8B;CAC1C,MAAM,QAAQ,OAAO,IAAI,MAAM;CAC/B,IAAI,OAAO,OAAO;CAGlB,IAAI;CACJ,OAAO,IACL,QACA,EAAE,WAAW,UAAU,MAAM,CAC/B;CACA,SAAS,QAAQ,MAAM;CACvB,OAAO,IAAI,QAAQ,MAAM;CACzB,OAAO;AACT;;AAGA,SAAS,UAAU,QAA8B;CAC/C,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC;CAC7B,OAAO,QAAQ,SAAS,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO;AACpE;AAEA,SAAS,MAAM,QAAwB;CACrC,OAAQ,OAA6C,KAAK;AAC5D;;AAGA,SAAS,OAAO,QAAmB,SAA6C;CAC9E,OAAQ,OAAqD,MAAM;EACjE,GAAG,MAAM,MAAM;EACf,GAAG;CACL,CAAC;AACH;;AAGA,SAAS,QAAQ,QAAyC;CACxD,MAAM,MAAM,MAAM,MAAM;CACxB,MAAM,SACJ,IAAI,SAAS,YACR,IAAI,YACL,IAAI,SAAS,SACX,OAAO,OAAO,IAAI,UA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I,KAAK,CAAC,EAChE,CAAC;CACD,OAAO,MAAM,CAAC,GAAG,SAAS,KAAK,CAAC;AAClC"}
@@ -1,6 +1,6 @@
1
1
  import { Diagnostic } from "../diagnostics/diagnostic.js";
2
2
  import "../diagnostics/spec.js";
3
- import "../diagnostics/codes/host.js";
3
+ import "../diagnostics/codes/host-core.js";
4
4
  import { JsonRpcErrorObject } from "./messages.js";
5
5
  //#region src/rpc/error.d.ts
6
6
  /** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","names":[],"sources":["../../src/rpc/error.ts"],"mappings":";;;;;;qBAUa;;WAEF;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;;;qBAoCE,iBAAiB;;WAEnB;;WAEA,YAAY;EAErB,YAAY,YAAY,YAAY;;EAQpC,iBAAiB;;;;;SAQV,gBAAgB,OAAO,oBAAoB,oBAAoB"}
1
+ {"version":3,"file":"error.d.ts","names":[],"sources":["../../src/rpc/error.ts"],"mappings":";;;;;;qBAaa;;WAEF;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;;;qBAoCE,iBAAiB;;WAEnB;;WAEA,YAAY;EAErB,YAAY,YAAY,YAAY;;EAQpC,iBAAiB;;;;;SAQV,gBAAgB,OAAO,oBAAoB,oBAAoB"}
package/dist/rpc/error.js CHANGED
@@ -1,4 +1,4 @@
1
- import { hostDiagnostics } from "../diagnostics/codes/host.js";
1
+ import { coreHostDiagnostics } from "../diagnostics/codes/host-core.js";
2
2
  import { Diagnostic } from "../diagnostics/diagnostic.js";
3
3
  import { buildDiagnostic } from "../diagnostics/spec.js";
4
4
  //#region src/rpc/error.ts
@@ -65,11 +65,11 @@ var RpcError = class RpcError extends Error {
65
65
  }
66
66
  };
67
67
  /**
68
- * Builds a HOST-area diagnostic from that area's catalog alone, so the JSON-RPC core doesn't pull
69
- * every area's text into browser bundles (D83).
68
+ * Builds one of the HOST-area diagnostics the JSON-RPC core raises, from their own catalog, so the
69
+ * core pulls neither the other areas' text nor the rest of HOST's into browser bundles (D83, #17).
70
70
  */
71
71
  function hostDiagnostic(code, details, docsBase) {
72
- return buildDiagnostic(code, hostDiagnostics[code], details, docsBase);
72
+ return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);
73
73
  }
74
74
  //#endregion
75
75
  export { JSON_RPC_ERROR_CODES, RpcError, hostDiagnostic };
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../../src/rpc/error.ts"],"sourcesContent":["/**\n * Errors on a JSON-RPC connection. Every error carries a diagnostic (INTERFACES §1, §6): the\n * JSON-RPC `error.code` says which kind of failure it is, and `error.data` is the diagnostic.\n */\nimport { type HostDiagnosticCode, hostDiagnostics } from \"../diagnostics/codes/host.ts\";\nimport { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport { buildDiagnostic, type DiagnosticDetails } from \"../diagnostics/spec.ts\";\nimport type { JsonRpcErrorObject } from \"./messages.ts\";\n\n/** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */\nexport const JSON_RPC_ERROR_CODES: {\n /** The line wasn't valid JSON. */\n readonly parseError: -32700;\n /** The message wasn't a valid request, or was a batch. */\n readonly invalidRequest: -32600;\n /** The method doesn't exist on this side. */\n readonly methodNotFound: -32601;\n /** The params failed the method's schema. */\n readonly invalidParams: -32602;\n /** An unexpected failure. */\n readonly internalError: -32603;\n /** Every other diagnostic. */\n readonly diagnostic: -32000;\n} = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n diagnostic: -32000,\n};\n\nfunction codeFor(diagnostic: Diagnostic): number {\n switch (diagnostic.code) {\n case \"MOSTRA_HOST_MALFORMED\":\n return JSON_RPC_ERROR_CODES.invalidRequest;\n case \"MOSTRA_HOST_METHOD_UNKNOWN\":\n return JSON_RPC_ERROR_CODES.methodNotFound;\n case \"MOSTRA_HOST_INVALID_PARAMS\":\n return JSON_RPC_ERROR_CODES.invalidParams;\n case \"MOSTRA_HOST_INTERNAL_ERROR\":\n return JSON_RPC_ERROR_CODES.internalError;\n default:\n return JSON_RPC_ERROR_CODES.diagnostic;\n }\n}\n\n/**\n * An error that crosses a connection as a JSON-RPC error. Throw it from a request handler to\n * answer with this diagnostic; a request's promise rejects with it when the other side answers\n * with an error, the connection closes or the request times out.\n *\n * ```ts\n * throw new RpcError(\n * createDiagnostic(\"MOSTRA_HOME_MISMATCH\", { message: \"This instance serves /a, not /b.\" }),\n * );\n * ```\n */\nexport class RpcError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The diagnostic: what happened and what to do. */\n readonly diagnostic: Diagnostic;\n\n constructor(diagnostic: Diagnostic, code: number = codeFor(diagnostic)) {\n super(diagnostic.message);\n this.name = \"RpcError\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n\n /** The JSON-RPC error object for a response. */\n toErrorObject(): JsonRpcErrorObject {\n return { code: this.code, message: this.diagnostic.message, data: this.diagnostic };\n }\n\n /**\n * Reads a received error object. When its `data` isn't a diagnostic (a peer that isn't Mostra),\n * the result is a `MOSTRA_HOST_MALFORMED` diagnostic that keeps the peer's message.\n */\n static fromErrorObject(error: JsonRpcErrorObject, docsBase?: string): RpcError {\n const parsed = Diagnostic.safeParse(error.data);\n if (parsed.success) return new RpcError(parsed.data, error.code);\n return new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n {\n message: `The other side answered with error ${error.code} without a diagnostic: ${error.message.slice(0, 200)}`,\n },\n docsBase,\n ),\n error.code,\n );\n }\n}\n\n/**\n * Builds a HOST-area diagnostic from that area's catalog alone, so the JSON-RPC core doesn't pull\n * every area's text into browser bundles (D83).\n */\nexport function hostDiagnostic(\n code: HostDiagnosticCode,\n details: DiagnosticDetails,\n docsBase?: string,\n): Diagnostic {\n return buildDiagnostic(code, hostDiagnostics[code], details, docsBase);\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,uBAaT;CACF,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,YAAY;AACd;AAEA,SAAS,QAAQ,YAAgC;CAC/C,QAAQ,WAAW,MAAnB;EACE,KAAK,yBACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,SACE,OAAO,qBAAqB;CAChC;AACF;;;;;;;;;;;;AAaA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;CAElC;;CAEA;CAEA,YAAY,YAAwB,OAAe,QAAQ,UAAU,GAAG;EACtE,MAAM,WAAW,OAAO;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;;CAGA,gBAAoC;EAClC,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK,WAAW;GAAS,MAAM,KAAK;EAAW;CACpF;;;;;CAMA,OAAO,gBAAgB,OAA2B,UAA6B;EAC7E,MAAM,SAAS,WAAW,UAAU,MAAM,IAAI;EAC9C,IAAI,OAAO,SAAS,OAAO,IAAI,SAAS,OAAO,MAAM,MAAM,IAAI;EAC/D,OAAO,IAAI,SACT,eACE,yBACA,EACE,SAAS,sCAAsC,MAAM,KAAK,yBAAyB,MAAM,QAAQ,MAAM,GAAG,GAAG,IAC/G,GACA,QACF,GACA,MAAM,IACR;CACF;AACF;;;;;AAMA,SAAgB,eACd,MACA,SACA,UACY;CACZ,OAAO,gBAAgB,MAAM,gBAAgB,OAAO,SAAS,QAAQ;AACvE"}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../src/rpc/error.ts"],"sourcesContent":["/**\n * Errors on a JSON-RPC connection. Every error carries a diagnostic (INTERFACES §1, §6): the\n * JSON-RPC `error.code` says which kind of failure it is, and `error.data` is the diagnostic.\n */\nimport {\n type CoreHostDiagnosticCode,\n coreHostDiagnostics,\n} from \"../diagnostics/codes/host-core.ts\";\nimport { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport { buildDiagnostic, type DiagnosticDetails } from \"../diagnostics/spec.ts\";\nimport type { JsonRpcErrorObject } from \"./messages.ts\";\n\n/** The JSON-RPC 2.0 error codes Mostra uses (INTERFACES §6). */\nexport const JSON_RPC_ERROR_CODES: {\n /** The line wasn't valid JSON. */\n readonly parseError: -32700;\n /** The message wasn't a valid request, or was a batch. */\n readonly invalidRequest: -32600;\n /** The method doesn't exist on this side. */\n readonly methodNotFound: -32601;\n /** The params failed the method's schema. */\n readonly invalidParams: -32602;\n /** An unexpected failure. */\n readonly internalError: -32603;\n /** Every other diagnostic. */\n readonly diagnostic: -32000;\n} = {\n parseError: -32700,\n invalidRequest: -32600,\n methodNotFound: -32601,\n invalidParams: -32602,\n internalError: -32603,\n diagnostic: -32000,\n};\n\nfunction codeFor(diagnostic: Diagnostic): number {\n switch (diagnostic.code) {\n case \"MOSTRA_HOST_MALFORMED\":\n return JSON_RPC_ERROR_CODES.invalidRequest;\n case \"MOSTRA_HOST_METHOD_UNKNOWN\":\n return JSON_RPC_ERROR_CODES.methodNotFound;\n case \"MOSTRA_HOST_INVALID_PARAMS\":\n return JSON_RPC_ERROR_CODES.invalidParams;\n case \"MOSTRA_HOST_INTERNAL_ERROR\":\n return JSON_RPC_ERROR_CODES.internalError;\n default:\n return JSON_RPC_ERROR_CODES.diagnostic;\n }\n}\n\n/**\n * An error that crosses a connection as a JSON-RPC error. Throw it from a request handler to\n * answer with this diagnostic; a request's promise rejects with it when the other side answers\n * with an error, the connection closes or the request times out.\n *\n * ```ts\n * throw new RpcError(\n * createDiagnostic(\"MOSTRA_HOME_MISMATCH\", { message: \"This instance serves /a, not /b.\" }),\n * );\n * ```\n */\nexport class RpcError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The diagnostic: what happened and what to do. */\n readonly diagnostic: Diagnostic;\n\n constructor(diagnostic: Diagnostic, code: number = codeFor(diagnostic)) {\n super(diagnostic.message);\n this.name = \"RpcError\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n\n /** The JSON-RPC error object for a response. */\n toErrorObject(): JsonRpcErrorObject {\n return { code: this.code, message: this.diagnostic.message, data: this.diagnostic };\n }\n\n /**\n * Reads a received error object. When its `data` isn't a diagnostic (a peer that isn't Mostra),\n * the result is a `MOSTRA_HOST_MALFORMED` diagnostic that keeps the peer's message.\n */\n static fromErrorObject(error: JsonRpcErrorObject, docsBase?: string): RpcError {\n const parsed = Diagnostic.safeParse(error.data);\n if (parsed.success) return new RpcError(parsed.data, error.code);\n return new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n {\n message: `The other side answered with error ${error.code} without a diagnostic: ${error.message.slice(0, 200)}`,\n },\n docsBase,\n ),\n error.code,\n );\n }\n}\n\n/**\n * Builds one of the HOST-area diagnostics the JSON-RPC core raises, from their own catalog, so the\n * core pulls neither the other areas' text nor the rest of HOST's into browser bundles (D83, #17).\n */\nexport function hostDiagnostic(\n code: CoreHostDiagnosticCode,\n details: DiagnosticDetails,\n docsBase?: string,\n): Diagnostic {\n return buildDiagnostic(code, coreHostDiagnostics[code], details, docsBase);\n}\n"],"mappings":";;;;;;;;;AAaA,MAAa,uBAaT;CACF,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,YAAY;AACd;AAEA,SAAS,QAAQ,YAAgC;CAC/C,QAAQ,WAAW,MAAnB;EACE,KAAK,yBACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,KAAK,8BACH,OAAO,qBAAqB;EAC9B,SACE,OAAO,qBAAqB;CAChC;AACF;;;;;;;;;;;;AAaA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;CAElC;;CAEA;CAEA,YAAY,YAAwB,OAAe,QAAQ,UAAU,GAAG;EACtE,MAAM,WAAW,OAAO;EACxB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;;CAGA,gBAAoC;EAClC,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK,WAAW;GAAS,MAAM,KAAK;EAAW;CACpF;;;;;CAMA,OAAO,gBAAgB,OAA2B,UAA6B;EAC7E,MAAM,SAAS,WAAW,UAAU,MAAM,IAAI;EAC9C,IAAI,OAAO,SAAS,OAAO,IAAI,SAAS,OAAO,MAAM,MAAM,IAAI;EAC/D,OAAO,IAAI,SACT,eACE,yBACA,EACE,SAAS,sCAAsC,MAAM,KAAK,yBAAyB,MAAM,QAAQ,MAAM,GAAG,GAAG,IAC/G,GACA,QACF,GACA,MAAM,IACR;CACF;AACF;;;;;AAMA,SAAgB,eACd,MACA,SACA,UACY;CACZ,OAAO,gBAAgB,MAAM,oBAAoB,OAAO,SAAS,QAAQ;AAC3E"}
@@ -60,7 +60,9 @@ export declare class RpcPeer {
60
60
  request(method: string, params?: JsonRpcParams, options?: RpcRequestOptions): Promise<unknown>;
61
61
  /**
62
62
  * Calls a protocol method: validates the params before sending and the result on arrival. A
63
- * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.
63
+ * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is
64
+ * read as {@link receivable} reads it, so an enum value or union member a newer peer added
65
+ * within the revision arrives as sent (#45).
64
66
  */
65
67
  call<P, R>(definition: MethodDefinition<P, R>, params: P, options?: RpcRequestOptions): Promise<R>;
66
68
  /** Sends a notification. Does nothing once the peer is closed. */
@@ -1 +1 @@
1
- {"version":3,"file":"peer.d.ts","names":[],"sources":["../../src/rpc/peer.ts"],"mappings":";;;;;iBA0BiB;;WAEN,IAAI;;WAEJ;;;iBAIM;;;;;EAKf,KAAK,SAAS;;;;;;;EAOd,WAAW,gBAAgB,iBAAiB,SAAS;;EAErD,gBAAgB,gBAAgB;;EAEhC,iBAAiB,gBAAgB;;WAExB;;;iBAIM;;;;;WAKN;;;qBAWE;;EAMX,YAAY,SAAS;;MAKjB;;MAKA;;;;;EAQJ,YAAY;;EAkBZ,QAAQ;;;;;EAwCR,QACE,gBACA,SAAS,eACT,UAAS,oBACR;;;;;EA+BH,KAAW,GAAG,GACZ,YAAY,iBAAiB,GAAG,IAChC,QAAQ,GACR,UAAS,oBACR,QAAQ;;EAcX,OAAO,gBAAgB,SAAS;;;;;EAWhC,MAAM,aAAa;;;;;;;wBA4GL,YAAY,GAAG,GAC7B,YAAY,iBAAiB,GAAG,IAChC,iBACA,oBACC"}
1
+ {"version":3,"file":"peer.d.ts","names":[],"sources":["../../src/rpc/peer.ts"],"mappings":";;;;;iBA2BiB;;WAEN,IAAI;;WAEJ;;;iBAIM;;;;;EAKf,KAAK,SAAS;;;;;;;EAOd,WAAW,gBAAgB,iBAAiB,SAAS;;EAErD,gBAAgB,gBAAgB;;EAEhC,iBAAiB,gBAAgB;;WAExB;;;iBAIM;;;;;WAKN;;;qBAWE;;EAMX,YAAY,SAAS;;MAKjB;;MAKA;;;;;EAQJ,YAAY;;EAkBZ,QAAQ;;;;;EAwCR,QACE,gBACA,SAAS,eACT,UAAS,oBACR;;;;;;;EAiCH,KAAW,GAAG,GACZ,YAAY,iBAAiB,GAAG,IAChC,QAAQ,GACR,UAAS,oBACR,QAAQ;;EAcX,OAAO,gBAAgB,SAAS;;;;;EAWhC,MAAM,aAAa;;;;;;;wBA4GL,YAAY,GAAG,GAC7B,YAAY,iBAAiB,GAAG,IAChC,iBACA,oBACC"}
package/dist/rpc/peer.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { JSON_RPC_ERROR_CODES, RpcError, hostDiagnostic } from "./error.js";
2
2
  import { classifyMessage } from "./messages.js";
3
+ import { receivable } from "../receive.js";
3
4
  //#region src/rpc/peer.ts
4
5
  /** One end of a JSON-RPC 2.0 connection. */
5
6
  var RpcPeer = class {
@@ -89,12 +90,14 @@ var RpcPeer = class {
89
90
  }
90
91
  /**
91
92
  * Calls a protocol method: validates the params before sending and the result on arrival. A
92
- * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.
93
+ * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is
94
+ * read as {@link receivable} reads it, so an enum value or union member a newer peer added
95
+ * within the revision arrives as sent (#45).
93
96
  */
94
97
  async call(definition, params, options = {}) {
95
98
  const checked = parseParams(definition, params, this.#options.docsBase);
96
99
  const raw = await this.request(definition.method, checked, options);
97
- const parsed = definition.result.safeParse(raw);
100
+ const parsed = receivable(definition.result).safeParse(raw);
98
101
  if (parsed.success) return parsed.data;
99
102
  throw new RpcError(this.#diagnostic("MOSTRA_HOST_MALFORMED", `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`));
100
103
  }
@@ -1 +1 @@
1
- {"version":3,"file":"peer.js","names":[],"sources":["../../src/rpc/peer.ts"],"sourcesContent":["/**\n * One end of a JSON-RPC 2.0 connection (D83): it matches responses to requests, dispatches\n * incoming requests and notifications, and turns every failure into a diagnostic. It has no I/O.\n * The transport hands it parsed messages (or raw lines) and sends what it gives back, so the same\n * peer serves stdio, Unix sockets, Node IPC and `postMessage`.\n *\n * ```ts\n * const peer = new RpcPeer({\n * send: (message) => socket.write(encodeLine(message)),\n * onRequest: (method, params) => handlers[method](params),\n * });\n * splitter.push(chunk).forEach((line) => peer.receiveLine(line));\n * const result = await peer.call(mostraInitializeMethod, params);\n * ```\n */\nimport type { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport type { MethodDefinition } from \"../method.ts\";\nimport { hostDiagnostic, JSON_RPC_ERROR_CODES, RpcError } from \"./error.ts\";\nimport {\n classifyMessage,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcParams,\n} from \"./messages.ts\";\n\n/** What a request handler learns about the request besides its params. */\nexport interface RpcRequestContext {\n /** The request's ID. */\n readonly id: JsonRpcId;\n /** The method name. */\n readonly method: string;\n}\n\n/** Options for {@link RpcPeer}. */\nexport interface RpcPeerOptions {\n /**\n * Sends one message. The transport serializes it (`encodeLine` for newline-delimited streams).\n * Throwing means the transport is gone: the peer closes.\n */\n send(message: JsonRpcMessage): void;\n /**\n * Answers an incoming request. Return the result, or throw an {@link RpcError} to answer with\n * its diagnostic. Any other exception is answered with `MOSTRA_HOST_INTERNAL_ERROR`, without\n * its details, and reported to `onInternalError`. Without a handler, every request is answered\n * with `MOSTRA_HOST_METHOD_UNKNOWN`.\n */\n onRequest?(method: string, params: unknown, context: RpcRequestContext): unknown;\n /** Receives an incoming notification. Exceptions are reported to `onInternalError`. */\n onNotification?(method: string, params: unknown): void;\n /** Reports an unexpected exception from a handler, for logging. */\n onInternalError?(error: unknown, method: string): void;\n /** The docs base URL for diagnostics the peer creates. Default `DEFAULT_DOCS_BASE`. */\n readonly docsBase?: string;\n}\n\n/** Options for one outgoing request. */\nexport interface RpcRequestOptions {\n /**\n * Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. A late response is\n * ignored. Default: no timeout (FAILURE_MODEL §9).\n */\n readonly timeoutMs?: number;\n}\n\ninterface Pending {\n readonly method: string;\n resolve(result: unknown): void;\n reject(error: RpcError): void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** One end of a JSON-RPC 2.0 connection. */\nexport class RpcPeer {\n readonly #options: RpcPeerOptions;\n readonly #pending = new Map<JsonRpcId, Pending>();\n #nextId = 1;\n #closed: Diagnostic | undefined;\n\n constructor(options: RpcPeerOptions) {\n this.#options = options;\n }\n\n /** Whether the peer has closed. A closed peer sends nothing and rejects new requests. */\n get closed(): boolean {\n return this.#closed !== undefined;\n }\n\n /** How many outgoing requests are waiting for a response. */\n get pendingRequests(): number {\n return this.#pending.size;\n }\n\n /**\n * Receives one line of a newline-delimited stream. Blank lines are skipped; a line that isn't\n * JSON is answered with a parse error (-32700).\n */\n receiveLine(line: string): void {\n if (line.trim() === \"\") return;\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n this.#reply(null, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", \"A line wasn't valid JSON.\"),\n JSON_RPC_ERROR_CODES.parseError,\n ),\n });\n return;\n }\n this.receive(value);\n }\n\n /** Receives one parsed message. */\n receive(value: unknown): void {\n if (this.#closed) return;\n const classified = classifyMessage(value);\n switch (classified.kind) {\n case \"request\":\n this.#handleRequest(\n classified.message.id,\n classified.message.method,\n classified.message.params,\n );\n return;\n case \"notification\":\n this.#handleNotification(classified.message.method, classified.message.params);\n return;\n case \"success\":\n this.#settle(classified.message.id, (pending) =>\n pending.resolve(classified.message.result),\n );\n return;\n case \"failure\": {\n const { id, error } = classified.message;\n if (id !== null) {\n this.#settle(id, (pending) =>\n pending.reject(RpcError.fromErrorObject(error, this.#options.docsBase)),\n );\n }\n return;\n }\n case \"invalid\":\n this.#reply(classified.id, {\n rpc: new RpcError(this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", classified.reason)),\n });\n return;\n }\n }\n\n /**\n * Sends a request and resolves with its result, or rejects with an {@link RpcError}: the\n * other side's diagnostic, `MOSTRA_HOST_TIMEOUT` or `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\n request(\n method: string,\n params?: JsonRpcParams,\n options: RpcRequestOptions = {},\n ): Promise<unknown> {\n if (this.#closed) return Promise.reject(new RpcError(this.#closed));\n const id = this.#nextId++;\n return new Promise<unknown>((resolve, reject) => {\n const pending: Pending = { method, resolve, reject };\n if (options.timeoutMs !== undefined) {\n pending.timer = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_TIMEOUT\",\n `No response to ${method} within ${options.timeoutMs} ms.`,\n ),\n ),\n );\n }, options.timeoutMs);\n }\n this.#pending.set(id, pending);\n this.#send(\n params === undefined\n ? { jsonrpc: \"2.0\", id, method }\n : { jsonrpc: \"2.0\", id, method, params },\n );\n });\n }\n\n /**\n * Calls a protocol method: validates the params before sending and the result on arrival. A\n * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`.\n */\n async call<P, R>(\n definition: MethodDefinition<P, R>,\n params: P,\n options: RpcRequestOptions = {},\n ): Promise<R> {\n const checked = parseParams(definition, params, this.#options.docsBase);\n const raw = await this.request(definition.method, checked as JsonRpcParams, options);\n const parsed = definition.result.safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`,\n ),\n );\n }\n\n /** Sends a notification. Does nothing once the peer is closed. */\n notify(method: string, params?: JsonRpcParams): void {\n if (this.#closed) return;\n this.#send(\n params === undefined ? { jsonrpc: \"2.0\", method } : { jsonrpc: \"2.0\", method, params },\n );\n }\n\n /**\n * Closes the peer: every waiting request rejects with `diagnostic` (by default\n * `MOSTRA_HOST_CONNECTION_CLOSED`), and later messages are ignored. Idempotent.\n */\n close(diagnostic?: Diagnostic): void {\n if (this.#closed) return;\n const reason =\n diagnostic ??\n this.#diagnostic(\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"The connection closed before a response arrived.\",\n );\n this.#closed = reason;\n const pending = [...this.#pending.values()];\n this.#pending.clear();\n for (const entry of pending) {\n if (entry.timer !== undefined) clearTimeout(entry.timer);\n entry.reject(new RpcError(reason));\n }\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): void {\n const handler = this.#options.onRequest;\n if (!handler) {\n this.#reply(id, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", `This side serves no method ${method}.`),\n ),\n });\n return;\n }\n let outcome: unknown;\n try {\n outcome = handler(method, params, { id, method });\n } catch (error) {\n this.#reply(id, { rpc: this.#asRpcError(error, method) });\n return;\n }\n Promise.resolve(outcome).then(\n (result) => this.#reply(id, { result: result === undefined ? null : result }),\n (error: unknown) => this.#reply(id, { rpc: this.#asRpcError(error, method) }),\n );\n }\n\n #handleNotification(method: string, params: unknown): void {\n try {\n this.#options.onNotification?.(method, params);\n } catch (error) {\n this.#options.onInternalError?.(error, method);\n }\n }\n\n #asRpcError(error: unknown, method: string): RpcError {\n if (error instanceof RpcError) return error;\n this.#options.onInternalError?.(error, method);\n return new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", `${method} failed unexpectedly.`),\n );\n }\n\n #settle(id: JsonRpcId, action: (pending: Pending) => void): void {\n const pending = this.#pending.get(id);\n if (!pending) return;\n this.#pending.delete(id);\n if (pending.timer !== undefined) clearTimeout(pending.timer);\n action(pending);\n }\n\n #reply(id: JsonRpcId | null, outcome: { result: unknown } | { rpc: RpcError }): void {\n if (this.#closed) return;\n if (\"rpc\" in outcome) {\n this.#send({ jsonrpc: \"2.0\", id, error: outcome.rpc.toErrorObject() });\n } else if (id !== null) {\n this.#send({ jsonrpc: \"2.0\", id, result: outcome.result });\n }\n }\n\n #send(message: JsonRpcMessage): void {\n try {\n this.#options.send(message);\n } catch {\n this.close();\n }\n }\n\n #diagnostic(\n code:\n | \"MOSTRA_HOST_MALFORMED\"\n | \"MOSTRA_HOST_METHOD_UNKNOWN\"\n | \"MOSTRA_HOST_INTERNAL_ERROR\"\n | \"MOSTRA_HOST_TIMEOUT\"\n | \"MOSTRA_HOST_CONNECTION_CLOSED\",\n message: string,\n ): Diagnostic {\n return hostDiagnostic(code, { message }, this.#options.docsBase);\n }\n}\n\nfunction describeIssue(\n issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[],\n): string {\n const [first] = issues;\n if (!first) return \"unknown problem\";\n const path = first.path.map(String).join(\".\");\n return `${path === \"\" ? \"(root)\" : path}: ${first.message}`;\n}\n\n/**\n * Validates a method's params against its schema and returns the parsed value. Throws an\n * {@link RpcError} with `MOSTRA_HOST_INVALID_PARAMS` naming the first problem; the message\n * describes types and paths, never the values sent.\n */\nexport function parseParams<P, R>(\n definition: MethodDefinition<P, R>,\n params: unknown,\n docsBase?: string,\n): P {\n const parsed = definition.params.safeParse(params ?? {});\n if (parsed.success) return parsed.data;\n throw new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_INVALID_PARAMS\",\n { message: `Invalid params for ${definition.method}: ${describeIssue(parsed.error.issues)}` },\n docsBase,\n ),\n );\n}\n"],"mappings":";;;;AAwEA,IAAa,UAAb,MAAqB;CACnB;CACA,2BAAoB,IAAI,IAAwB;CAChD,UAAU;CACV;CAEA,YAAY,SAAyB;EACnC,KAAK,WAAW;CAClB;;CAGA,IAAI,SAAkB;EACpB,OAAO,KAAK,YAAY,KAAA;CAC1B;;CAGA,IAAI,kBAA0B;EAC5B,OAAO,KAAK,SAAS;CACvB;;;;;CAMA,YAAY,MAAoB;EAC9B,IAAI,KAAK,KAAK,MAAM,IAAI;EACxB,IAAI;EACJ,IAAI;GACF,QAAQ,KAAK,MAAM,IAAI;EACzB,QAAQ;GACN,KAAK,OAAO,MAAM,EAChB,KAAK,IAAI,SACP,KAAK,YAAY,yBAAyB,2BAA2B,GACrE,qBAAqB,UACvB,EACF,CAAC;GACD;EACF;EACA,KAAK,QAAQ,KAAK;CACpB;;CAGA,QAAQ,OAAsB;EAC5B,IAAI,KAAK,SAAS;EAClB,MAAM,aAAa,gBAAgB,KAAK;EACxC,QAAQ,WAAW,MAAnB;GACE,KAAK;IACH,KAAK,eACH,WAAW,QAAQ,IACnB,WAAW,QAAQ,QACnB,WAAW,QAAQ,MACrB;IACA;GACF,KAAK;IACH,KAAK,oBAAoB,WAAW,QAAQ,QAAQ,WAAW,QAAQ,MAAM;IAC7E;GACF,KAAK;IACH,KAAK,QAAQ,WAAW,QAAQ,KAAK,YACnC,QAAQ,QAAQ,WAAW,QAAQ,MAAM,CAC3C;IACA;GACF,KAAK,WAAW;IACd,MAAM,EAAE,IAAI,UAAU,WAAW;IACjC,IAAI,OAAO,MACT,KAAK,QAAQ,KAAK,YAChB,QAAQ,OAAO,SAAS,gBAAgB,OAAO,KAAK,SAAS,QAAQ,CAAC,CACxE;IAEF;GACF;GACA,KAAK;IACH,KAAK,OAAO,WAAW,IAAI,EACzB,KAAK,IAAI,SAAS,KAAK,YAAY,yBA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AAI,EAAE;EACpC,IAAI,CAAC,SAAS;EACd,KAAK,SAAS,OAAO,EAAE;EACvB,IAAI,QAAQ,UAAU,KAAA,GAAW,aAAa,QAAQ,KAAK;EAC3D,OAAO,OAAO;CAChB;CAEA,OAAO,IAAsB,SAAwD;EACnF,IAAI,KAAK,SAAS;EAClB,IAAI,SAAS,SACX,KAAK,MAAM;GAAE,SAAS;GAAO;GAAI,OAAO,QAAQ,IAAI,cAAc;EAAE,CAAC;OAChE,IAAI,OAAO,MAChB,KAAK,MAAM;GAAE,SAAS;GAAO;GAAI,QAAQ,QAAQ;EAAO,CAAC;CAE7D;CAEA,MAAM,SAA+B;EACnC,IAAI;GACF,KAAK,SAAS,KAAK,OAAO;EAC5B,QAAQ;GACN,KAAK,MAAM;EACb;CACF;CAEA,YACE,MAMA,SACY;EACZ,OAAO,eAAe,MAAM,EAAE,QAAQ,GAAG,KAAK,SAAS,QAAQ;CACjE;AACF;AAEA,SAAS,cACP,QACQ;CACR,MAAM,CAAC,SAAS;CAChB,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,KAAK,GAAG;CAC5C,OAAO,GAAG,SAAS,KAAK,WAAW,KAAK,IAAI,MAAM;AACpD;;;;;;AAOA,SAAgB,YACd,YACA,QACA,UACG;CACH,MAAM,SAAS,WAAW,OAAO,UAAU,UAAU,CAAC,CAAC;CACvD,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,MAAM,IAAI,SACR,eACE,8BACA,EAAE,SAAS,sBAAsB,WAAW,OAAO,IAAI,cAAc,OAAO,MAAM,MAAM,IAAI,GAC5F,QACF,CACF;AACF"}
1
+ {"version":3,"file":"peer.js","names":[],"sources":["../../src/rpc/peer.ts"],"sourcesContent":["/**\n * One end of a JSON-RPC 2.0 connection (D83): it matches responses to requests, dispatches\n * incoming requests and notifications, and turns every failure into a diagnostic. It has no I/O.\n * The transport hands it parsed messages (or raw lines) and sends what it gives back, so the same\n * peer serves stdio, Unix sockets, Node IPC and `postMessage`.\n *\n * ```ts\n * const peer = new RpcPeer({\n * send: (message) => socket.write(encodeLine(message)),\n * onRequest: (method, params) => handlers[method](params),\n * });\n * splitter.push(chunk).forEach((line) => peer.receiveLine(line));\n * const result = await peer.call(mostraInitializeMethod, params);\n * ```\n */\nimport type { Diagnostic } from \"../diagnostics/diagnostic.ts\";\nimport type { MethodDefinition } from \"../method.ts\";\nimport { receivable } from \"../receive.ts\";\nimport { hostDiagnostic, JSON_RPC_ERROR_CODES, RpcError } from \"./error.ts\";\nimport {\n classifyMessage,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcParams,\n} from \"./messages.ts\";\n\n/** What a request handler learns about the request besides its params. */\nexport interface RpcRequestContext {\n /** The request's ID. */\n readonly id: JsonRpcId;\n /** The method name. */\n readonly method: string;\n}\n\n/** Options for {@link RpcPeer}. */\nexport interface RpcPeerOptions {\n /**\n * Sends one message. The transport serializes it (`encodeLine` for newline-delimited streams).\n * Throwing means the transport is gone: the peer closes.\n */\n send(message: JsonRpcMessage): void;\n /**\n * Answers an incoming request. Return the result, or throw an {@link RpcError} to answer with\n * its diagnostic. Any other exception is answered with `MOSTRA_HOST_INTERNAL_ERROR`, without\n * its details, and reported to `onInternalError`. Without a handler, every request is answered\n * with `MOSTRA_HOST_METHOD_UNKNOWN`.\n */\n onRequest?(method: string, params: unknown, context: RpcRequestContext): unknown;\n /** Receives an incoming notification. Exceptions are reported to `onInternalError`. */\n onNotification?(method: string, params: unknown): void;\n /** Reports an unexpected exception from a handler, for logging. */\n onInternalError?(error: unknown, method: string): void;\n /** The docs base URL for diagnostics the peer creates. Default `DEFAULT_DOCS_BASE`. */\n readonly docsBase?: string;\n}\n\n/** Options for one outgoing request. */\nexport interface RpcRequestOptions {\n /**\n * Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. A late response is\n * ignored. Default: no timeout (FAILURE_MODEL §9).\n */\n readonly timeoutMs?: number;\n}\n\ninterface Pending {\n readonly method: string;\n resolve(result: unknown): void;\n reject(error: RpcError): void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** One end of a JSON-RPC 2.0 connection. */\nexport class RpcPeer {\n readonly #options: RpcPeerOptions;\n readonly #pending = new Map<JsonRpcId, Pending>();\n #nextId = 1;\n #closed: Diagnostic | undefined;\n\n constructor(options: RpcPeerOptions) {\n this.#options = options;\n }\n\n /** Whether the peer has closed. A closed peer sends nothing and rejects new requests. */\n get closed(): boolean {\n return this.#closed !== undefined;\n }\n\n /** How many outgoing requests are waiting for a response. */\n get pendingRequests(): number {\n return this.#pending.size;\n }\n\n /**\n * Receives one line of a newline-delimited stream. Blank lines are skipped; a line that isn't\n * JSON is answered with a parse error (-32700).\n */\n receiveLine(line: string): void {\n if (line.trim() === \"\") return;\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n this.#reply(null, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", \"A line wasn't valid JSON.\"),\n JSON_RPC_ERROR_CODES.parseError,\n ),\n });\n return;\n }\n this.receive(value);\n }\n\n /** Receives one parsed message. */\n receive(value: unknown): void {\n if (this.#closed) return;\n const classified = classifyMessage(value);\n switch (classified.kind) {\n case \"request\":\n this.#handleRequest(\n classified.message.id,\n classified.message.method,\n classified.message.params,\n );\n return;\n case \"notification\":\n this.#handleNotification(classified.message.method, classified.message.params);\n return;\n case \"success\":\n this.#settle(classified.message.id, (pending) =>\n pending.resolve(classified.message.result),\n );\n return;\n case \"failure\": {\n const { id, error } = classified.message;\n if (id !== null) {\n this.#settle(id, (pending) =>\n pending.reject(RpcError.fromErrorObject(error, this.#options.docsBase)),\n );\n }\n return;\n }\n case \"invalid\":\n this.#reply(classified.id, {\n rpc: new RpcError(this.#diagnostic(\"MOSTRA_HOST_MALFORMED\", classified.reason)),\n });\n return;\n }\n }\n\n /**\n * Sends a request and resolves with its result, or rejects with an {@link RpcError}: the\n * other side's diagnostic, `MOSTRA_HOST_TIMEOUT` or `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\n request(\n method: string,\n params?: JsonRpcParams,\n options: RpcRequestOptions = {},\n ): Promise<unknown> {\n if (this.#closed) return Promise.reject(new RpcError(this.#closed));\n const id = this.#nextId++;\n return new Promise<unknown>((resolve, reject) => {\n const pending: Pending = { method, resolve, reject };\n if (options.timeoutMs !== undefined) {\n pending.timer = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_TIMEOUT\",\n `No response to ${method} within ${options.timeoutMs} ms.`,\n ),\n ),\n );\n }, options.timeoutMs);\n }\n this.#pending.set(id, pending);\n this.#send(\n params === undefined\n ? { jsonrpc: \"2.0\", id, method }\n : { jsonrpc: \"2.0\", id, method, params },\n );\n });\n }\n\n /**\n * Calls a protocol method: validates the params before sending and the result on arrival. A\n * result that fails the method's schema rejects with `MOSTRA_HOST_MALFORMED`. The result is\n * read as {@link receivable} reads it, so an enum value or union member a newer peer added\n * within the revision arrives as sent (#45).\n */\n async call<P, R>(\n definition: MethodDefinition<P, R>,\n params: P,\n options: RpcRequestOptions = {},\n ): Promise<R> {\n const checked = parseParams(definition, params, this.#options.docsBase);\n const raw = await this.request(definition.method, checked as JsonRpcParams, options);\n const parsed = receivable(definition.result).safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new RpcError(\n this.#diagnostic(\n \"MOSTRA_HOST_MALFORMED\",\n `The result of ${definition.method} doesn't match its schema: ${describeIssue(parsed.error.issues)}`,\n ),\n );\n }\n\n /** Sends a notification. Does nothing once the peer is closed. */\n notify(method: string, params?: JsonRpcParams): void {\n if (this.#closed) return;\n this.#send(\n params === undefined ? { jsonrpc: \"2.0\", method } : { jsonrpc: \"2.0\", method, params },\n );\n }\n\n /**\n * Closes the peer: every waiting request rejects with `diagnostic` (by default\n * `MOSTRA_HOST_CONNECTION_CLOSED`), and later messages are ignored. Idempotent.\n */\n close(diagnostic?: Diagnostic): void {\n if (this.#closed) return;\n const reason =\n diagnostic ??\n this.#diagnostic(\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"The connection closed before a response arrived.\",\n );\n this.#closed = reason;\n const pending = [...this.#pending.values()];\n this.#pending.clear();\n for (const entry of pending) {\n if (entry.timer !== undefined) clearTimeout(entry.timer);\n entry.reject(new RpcError(reason));\n }\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): void {\n const handler = this.#options.onRequest;\n if (!handler) {\n this.#reply(id, {\n rpc: new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", `This side serves no method ${method}.`),\n ),\n });\n return;\n }\n let outcome: unknown;\n try {\n outcome = handler(method, params, { id, method });\n } catch (error) {\n this.#reply(id, { rpc: this.#asRpcError(error, method) });\n return;\n }\n Promise.resolve(outcome).then(\n (result) => this.#reply(id, { result: result === undefined ? null : result }),\n (error: unknown) => this.#reply(id, { rpc: this.#asRpcError(error, method) }),\n );\n }\n\n #handleNotification(method: string, params: unknown): void {\n try {\n this.#options.onNotification?.(method, params);\n } catch (error) {\n this.#options.onInternalError?.(error, method);\n }\n }\n\n #asRpcError(error: unknown, method: string): RpcError {\n if (error instanceof RpcError) return error;\n this.#options.onInternalError?.(error, method);\n return new RpcError(\n this.#diagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", `${method} failed unexpectedly.`),\n );\n }\n\n #settle(id: JsonRpcId, action: (pending: Pending) => void): void {\n const pending = this.#pending.get(id);\n if (!pending) return;\n this.#pending.delete(id);\n if (pending.timer !== undefined) clearTimeout(pending.timer);\n action(pending);\n }\n\n #reply(id: JsonRpcId | null, outcome: { result: unknown } | { rpc: RpcError }): void {\n if (this.#closed) return;\n if (\"rpc\" in outcome) {\n this.#send({ jsonrpc: \"2.0\", id, error: outcome.rpc.toErrorObject() });\n } else if (id !== null) {\n this.#send({ jsonrpc: \"2.0\", id, result: outcome.result });\n }\n }\n\n #send(message: JsonRpcMessage): void {\n try {\n this.#options.send(message);\n } catch {\n this.close();\n }\n }\n\n #diagnostic(\n code:\n | \"MOSTRA_HOST_MALFORMED\"\n | \"MOSTRA_HOST_METHOD_UNKNOWN\"\n | \"MOSTRA_HOST_INTERNAL_ERROR\"\n | \"MOSTRA_HOST_TIMEOUT\"\n | \"MOSTRA_HOST_CONNECTION_CLOSED\",\n message: string,\n ): Diagnostic {\n return hostDiagnostic(code, { message }, this.#options.docsBase);\n }\n}\n\nfunction describeIssue(\n issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[],\n): string {\n const [first] = issues;\n if (!first) return \"unknown problem\";\n const path = first.path.map(String).join(\".\");\n return `${path === \"\" ? \"(root)\" : path}: ${first.message}`;\n}\n\n/**\n * Validates a method's params against its schema and returns the parsed value. Throws an\n * {@link RpcError} with `MOSTRA_HOST_INVALID_PARAMS` naming the first problem; the message\n * describes types and paths, never the values sent.\n */\nexport function parseParams<P, R>(\n definition: MethodDefinition<P, R>,\n params: unknown,\n docsBase?: string,\n): P {\n const parsed = definition.params.safeParse(params ?? {});\n if (parsed.success) return parsed.data;\n throw new RpcError(\n hostDiagnostic(\n \"MOSTRA_HOST_INVALID_PARAMS\",\n { message: `Invalid params for ${definition.method}: ${describeIssue(parsed.error.issues)}` },\n docsBase,\n ),\n );\n}\n"],"mappings":";;;;;AAyEA,IAAa,UAAb,MAAqB;CACnB;CACA,2BAAoB,IAAI,IAAwB;CAChD,UAAU;CACV;CAEA,YAAY,SAAyB;EACnC,KAAK,WAAW;CAClB;;CAGA,IAAI,SAAkB;EACpB,OAAO,KAAK,YAAY,KAAA;CAC1B;;CAGA,IAAI,kBAA0B;EAC5B,OAAO,KAAK,SAAS;CACvB;;;;;CAMA,YAAY,MAAoB;EAC9B,IAAI,KAAK,KAAK,MAAM,IAAI;EACxB,IAAI;EACJ,IAAI;GACF,QAAQ,KAAK,MAAM,IAAI;EACzB,QAAQ;GACN,KAAK,OAAO,MAAM,EAChB,KAAK,IAAI,SACP,KAAK,YAAY,yBAAyB,2BAA2B,GACrE,qBAAqB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MAAM,EAAE,QAAQ,GAAG,KAAK,SAAS,QAAQ;CACjE;AACF;AAEA,SAAS,cACP,QACQ;CACR,MAAM,CAAC,SAAS;CAChB,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,KAAK,GAAG;CAC5C,OAAO,GAAG,SAAS,KAAK,WAAW,KAAK,IAAI,MAAM;AACpD;;;;;;AAOA,SAAgB,YACd,YACA,QACA,UACG;CACH,MAAM,SAAS,WAAW,OAAO,UAAU,UAAU,CAAC,CAAC;CACvD,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,MAAM,IAAI,SACR,eACE,8BACA,EAAE,SAAS,sBAAsB,WAAW,OAAO,IAAI,cAAc,OAAO,MAAM,MAAM,IAAI,GAC5F,QACF,CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/protocol",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Mostra's shared protocol vocabulary: IDs, dated revisions and diagnostics, with Zod schemas and generated JSON Schema.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -43,7 +43,7 @@
43
43
  "provenance": true
44
44
  },
45
45
  "dependencies": {
46
- "zod": "4.6.5"
46
+ "zod": "4.6.6"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@mostra/tools": "0.0.0",
@@ -75,7 +75,7 @@
75
75
  "ignore": [
76
76
  "zod"
77
77
  ],
78
- "limit": "6 kB"
78
+ "limit": "5 kB"
79
79
  },
80
80
  {
81
81
  "name": "@mostra/protocol IDs alone (zod excluded)",
@@ -93,7 +93,7 @@
93
93
  "ignore": [
94
94
  "zod"
95
95
  ],
96
- "limit": "8.75 kB"
96
+ "limit": "7.5 kB"
97
97
  },
98
98
  {
99
99
  "name": "@mostra/protocol server-function serializer (D54)",
@@ -1011,7 +1011,7 @@
1011
1011
  "properties": {
1012
1012
  "file": {
1013
1013
  "type": "string",
1014
- "pattern": "^mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\\.tar\\.gz$"
1014
+ "pattern": "^(?:mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\\.tar\\.gz$|mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-win32-(arm64|x64)\\.tar\\.gz$)"
1015
1015
  },
1016
1016
  "sha256": {
1017
1017
  "$ref": "#/definitions/Sha256"
@@ -1286,7 +1286,9 @@
1286
1286
  "darwin-arm64",
1287
1287
  "darwin-x64",
1288
1288
  "linux-x64",
1289
- "linux-arm64"
1289
+ "linux-arm64",
1290
+ "win32-x64",
1291
+ "win32-arm64"
1290
1292
  ]
1291
1293
  },
1292
1294
  "BundleSetup": {
@@ -1320,6 +1322,10 @@
1320
1322
  },
1321
1323
  "at": {
1322
1324
  "type": "string"
1325
+ },
1326
+ "root": {
1327
+ "type": "string",
1328
+ "minLength": 1
1323
1329
  }
1324
1330
  },
1325
1331
  "required": [
@@ -979,7 +979,7 @@
979
979
  "properties": {
980
980
  "file": {
981
981
  "type": "string",
982
- "pattern": "^mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\\.tar\\.gz$"
982
+ "pattern": "^(?:mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\\.tar\\.gz$|mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-win32-(arm64|x64)\\.tar\\.gz$)"
983
983
  },
984
984
  "sha256": {
985
985
  "$ref": "#/$defs/Sha256"
@@ -1254,7 +1254,9 @@
1254
1254
  "darwin-arm64",
1255
1255
  "darwin-x64",
1256
1256
  "linux-x64",
1257
- "linux-arm64"
1257
+ "linux-arm64",
1258
+ "win32-x64",
1259
+ "win32-arm64"
1258
1260
  ]
1259
1261
  },
1260
1262
  "BundleSetup": {
@@ -1288,6 +1290,10 @@
1288
1290
  },
1289
1291
  "at": {
1290
1292
  "type": "string"
1293
+ },
1294
+ "root": {
1295
+ "type": "string",
1296
+ "minLength": 1
1291
1297
  }
1292
1298
  },
1293
1299
  "required": [
package/src/bundle.ts CHANGED
@@ -11,18 +11,29 @@
11
11
  * files.json BundleFiles: every other file and link of the archive with its SHA-256
12
12
  * node/ the official Node.js distribution for the platform
13
13
  * lib/node_modules/ Mostra's packages (cli, runtime, worker, verify, shell, sdk, warm) and theirs
14
- * bin/ the mostra, mostra-runtime and mostra-setup launchers
14
+ * bin/ the mostra, mostra-runtime and mostra-setup launchers (POSIX scripts, or on
15
+ * Windows `.exe` launchers beside the helpers mostra-win and mostra-win-service)
15
16
  * ```
16
17
  *
18
+ * A Windows archive holds no links: an ordinary Windows user can't create symbolic links, so its
19
+ * `files.json` lists the links, each to a directory inside the bundle, and setup makes each one a
20
+ * junction at the bundle's real path (D153).
21
+ *
17
22
  * The verify browser isn't in the archive: setup downloads the pinned revision through the
18
23
  * bundle's own Playwright and checks every file against `BundleInfo.browser.files` (D142).
19
24
  */
20
25
  import * as z from "zod";
21
26
  import { wireRegistry } from "./wire-registry.ts";
22
27
 
23
- /** The platforms v1 ships a bundle for (D35; Windows follows in v1.1, D120). */
24
- export const BUNDLE_PLATFORMS: readonly ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64"] =
25
- ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64"];
28
+ /** The platforms v1 ships a bundle for (D35, D146): macOS, glibc Linux and Windows. */
29
+ export const BUNDLE_PLATFORMS: readonly [
30
+ "darwin-arm64",
31
+ "darwin-x64",
32
+ "linux-x64",
33
+ "linux-arm64",
34
+ "win32-x64",
35
+ "win32-arm64",
36
+ ] = ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "win32-x64", "win32-arm64"];
26
37
 
27
38
  /** One platform a bundle is built for: `<os>-<arch>` as Node names them. */
28
39
  export type BundlePlatform = (typeof BUNDLE_PLATFORMS)[number];
@@ -33,6 +44,11 @@ export const BUNDLE_NAME = "mostra-runtime-bundle";
33
44
  /** The marker setup writes at a bundle's root once its files and its browser are verified. */
34
45
  export const BUNDLE_SETUP_MARKER = ".mostra-setup.json";
35
46
 
47
+ /** Whether a platform's bundle is a Windows one, whose links setup makes as junctions (D153). */
48
+ export function isWindowsBundle(platform: BundlePlatform): boolean {
49
+ return platform.startsWith("win32-");
50
+ }
51
+
36
52
  /** The archive a release attaches for a version and platform. */
37
53
  export function bundleAssetName(version: string, platform: BundlePlatform): string {
38
54
  return `mostra-${version}-${platform}.tar.gz`;
@@ -79,7 +95,10 @@ export const BundleFileEntry: z.ZodType<BundleFileEntry> = z
79
95
  })
80
96
  .register(wireRegistry, { id: "BundleFileEntry" });
81
97
 
82
- /** One symbolic link of a bundle. Its target is relative and resolves inside the bundle. */
98
+ /**
99
+ * One symbolic link of a bundle. Its target is relative and resolves inside the bundle. In a
100
+ * Windows bundle every link names a directory, and setup makes it a junction (D153).
101
+ */
83
102
  export interface BundleLinkEntry {
84
103
  /** The link itself, relative to the bundle's root. */
85
104
  readonly path: string;
@@ -199,7 +218,10 @@ export const BundleAsset: z.ZodType<BundleAsset> = z
199
218
  // (Opus review finding 8), and `BundlePins` checks it names its release and platform.
200
219
  file: z
201
220
  .string()
202
- .regex(/^mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\.tar\.gz$/),
221
+ // Widened for Windows as the schema gate can prove: the old pattern is one alternative.
222
+ .regex(
223
+ /^(?:mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-(darwin|linux)-(arm64|x64)\.tar\.gz$|mostra-[0-9A-Za-z][0-9A-Za-z.+-]*-win32-(arm64|x64)\.tar\.gz$)/,
224
+ ),
203
225
  sha256,
204
226
  size: z.int().positive(),
205
227
  unpackedSize: z.int().positive(),
@@ -249,6 +271,12 @@ export interface BundleSetup {
249
271
  readonly browser: { readonly revision: string };
250
272
  /** When setup finished (RFC 3339). */
251
273
  readonly at: string;
274
+ /**
275
+ * The bundle's real path when setup ran. A Windows bundle's junctions name their targets by
276
+ * absolute path, so a Windows bundle whose marker names another root (it was moved or copied)
277
+ * is set up again, which makes its junctions afresh (D153). Absent in markers before WP-W3.
278
+ */
279
+ readonly root?: string;
252
280
  }
253
281
 
254
282
  /** The setup marker's schema. */
@@ -260,5 +288,6 @@ export const BundleSetup: z.ZodType<BundleSetup> = z
260
288
  files: sha256,
261
289
  browser: z.object({ revision: z.string().min(1) }),
262
290
  at: z.string(),
291
+ root: z.string().min(1).exactOptional(),
263
292
  })
264
293
  .register(wireRegistry, { id: "BundleSetup" });