@reliantlabs/forge-web-runtime 0.6.0 → 0.8.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.
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Code } from "@connectrpc/connect";
1
+ import { Code, ConnectError } from "@connectrpc/connect";
2
2
  /**
3
3
  * FORGE_ERROR_REASON_HEADER is the Connect trailer/metadata key carrying a
4
4
  * stable, machine-readable reason code (snake_case) the backend sets for
@@ -33,15 +33,42 @@ export declare function stripServerFraming(message: string): string;
33
33
  */
34
34
  export declare function userMessage(err: unknown, fallback?: string): string;
35
35
  /**
36
- * ConnectClientError is the single typed error shape the app catches. It is
37
- * a plain Error subclass so it works with React Query, error boundaries, and
38
- * `instanceof` alike.
36
+ * codeName — the canonical wire name of a Connect code: `Code.NotFound` →
37
+ * "not_found", `Code.DeadlineExceeded` → "deadline_exceeded". The spelling
38
+ * the Connect protocol puts on the wire and in the "[code] " message prefix.
39
+ *
40
+ * (An earlier version lower-cased the enum key, which produced "notfound" —
41
+ * a name that matches nothing the server or the docs spell.)
42
+ */
43
+ export declare function codeName(code: Code): string;
44
+ /** Detail types a ConnectError carries; spelled off the base class's field. */
45
+ type ConnectErrorDetails = ConnectError["details"];
46
+ /**
47
+ * ConnectClientError is the single typed error shape the app catches.
48
+ *
49
+ * It IS a ConnectError — a subclass — so the error the runtime's
50
+ * errorNormalizeInterceptor throws still satisfies every consumer written
51
+ * against connect-es: `err instanceof ConnectError` holds, `err.code` is the
52
+ * numeric `Code`, and `metadata`, `details`, `findDetails()` and `rawMessage`
53
+ * are the original error's. What it adds is the normalized view: `codeName`,
54
+ * `status`, `retryable`, `reason` and `traceId`. An app that already branches
55
+ * on ConnectError can therefore adopt the runtime chain one call site at a
56
+ * time; nothing downgrades to `Code.Unknown` because a catch block met a type
57
+ * it did not expect.
58
+ *
59
+ * `name` stays "ConnectError". That is load-bearing: connect-es's
60
+ * `ConnectError[Symbol.hasInstance]` accepts an object whose prototype is
61
+ * exactly `ConnectError.prototype`, or one NAMED "ConnectError" with the
62
+ * right fields — a subclass instance is the second case, so any other name
63
+ * fails `instanceof ConnectError`.
64
+ *
65
+ * `message` is the server's text WITHOUT the "[code] " framing (the same as
66
+ * `rawMessage`), so it is presentable at every layer; connect-es's own
67
+ * `message` carries the prefix. Render with {@link userMessage} regardless.
39
68
  */
40
- export declare class ConnectClientError extends Error {
69
+ export declare class ConnectClientError extends ConnectError {
41
70
  /** Canonical Connect code name, e.g. "unavailable", "not_found". */
42
- readonly code: string;
43
- /** Numeric Connect code (Code enum), or undefined for non-Connect errors. */
44
- readonly connectCode?: Code;
71
+ readonly codeName: string;
45
72
  /** Approximate HTTP status, for telemetry and generic UI. */
46
73
  readonly status: number;
47
74
  /** True when a transparent retry is reasonable (transient failures). */
@@ -60,12 +87,18 @@ export declare class ConnectClientError extends Error {
60
87
  * key to every server span and log line of that request.
61
88
  */
62
89
  readonly traceId: string | null;
90
+ /**
91
+ * `status` and `retryable` default from `code`; `reason` defaults to the
92
+ * x-forge-error-reason entry in `metadata`.
93
+ */
63
94
  constructor(args: {
95
+ /** The server's message, without "[code] " framing. */
64
96
  message: string;
65
- code: string;
66
- connectCode?: Code;
67
- status: number;
68
- retryable: boolean;
97
+ code: Code;
98
+ metadata?: HeadersInit;
99
+ details?: ConnectErrorDetails;
100
+ status?: number;
101
+ retryable?: boolean;
69
102
  reason?: string | null;
70
103
  traceId?: string | null;
71
104
  cause?: unknown;
@@ -76,11 +109,8 @@ export declare class ConnectClientError extends Error {
76
109
  * working when two copies of this package end up in one bundle (see
77
110
  * {@link isConnectClientErrorShape}). Without it, normalizeError's
78
111
  * pass-through guard misses an already-normalized error from the other
79
- * copy; that error's `name` is "ConnectClientError" rather than
80
- * "ConnectError", so it misses the ConnectError branch too and is re-wrapped
81
- * through the generic Error branch — silently downgrading every error in the
82
- * app to code "unknown", status 500, no connectCode and no reason.
83
- * @connectrpc/connect does the same on ConnectError, for the same reason.
112
+ * copy and re-wraps it as a fresh error. @connectrpc/connect does the same
113
+ * on ConnectError, for the same reason.
84
114
  */
85
115
  static [Symbol.hasInstance](v: unknown): boolean;
86
116
  }
@@ -95,6 +125,8 @@ export declare function isRetryableCode(code: Code): boolean;
95
125
  * Both `instanceof` checks below match on SHAPE rather than class identity —
96
126
  * ours via ConnectClientError's Symbol.hasInstance, ConnectError's via the one
97
127
  * @connectrpc/connect ships — so neither branch is missed when a second copy
98
- * of either package lands in the bundle.
128
+ * of either package lands in the bundle. The ConnectClientError check comes
129
+ * first because every ConnectClientError is also a ConnectError.
99
130
  */
100
131
  export declare function normalizeError(err: unknown, requestTraceId?: string | null): ConnectClientError;
132
+ export {};
package/dist/errors.js CHANGED
@@ -3,8 +3,9 @@
3
3
  // Typed client errors. Connect surfaces failures as ConnectError with a
4
4
  // numeric Code; the rest of the app should reason about a stable, typed
5
5
  // shape instead of sniffing status codes at every call site. normalizeError
6
- // maps any thrown value into a ConnectClientError carrying the canonical
7
- // code name, an HTTP-ish status, a retryability verdict, and a
6
+ // maps any thrown value into a ConnectClientError — a ConnectError subclass,
7
+ // so connect-es consumers keep working — carrying the canonical code name,
8
+ // an HTTP-ish status, a retryability verdict, the backend's reason, and a
8
9
  // human-presentable message.
9
10
  import { Code, ConnectError } from "@connectrpc/connect";
10
11
  import { TRACERESPONSE_HEADER, traceIdFrom } from "./trace.js";
@@ -73,6 +74,20 @@ const HTTP_STATUS = {
73
74
  [Code.DeadlineExceeded]: 504,
74
75
  [Code.Internal]: 500,
75
76
  };
77
+ /**
78
+ * codeName — the canonical wire name of a Connect code: `Code.NotFound` →
79
+ * "not_found", `Code.DeadlineExceeded` → "deadline_exceeded". The spelling
80
+ * the Connect protocol puts on the wire and in the "[code] " message prefix.
81
+ *
82
+ * (An earlier version lower-cased the enum key, which produced "notfound" —
83
+ * a name that matches nothing the server or the docs spell.)
84
+ */
85
+ export function codeName(code) {
86
+ const key = Code[code];
87
+ if (typeof key !== "string")
88
+ return "unknown";
89
+ return key.replace(/[A-Z]/g, (c, i) => (i === 0 ? "" : "_") + c.toLowerCase());
90
+ }
76
91
  /**
77
92
  * isConnectClientErrorShape — the STRUCTURAL test behind
78
93
  * {@link ConnectClientError}'s `instanceof`.
@@ -83,6 +98,10 @@ const HTTP_STATUS = {
83
98
  * package holds two distinct ConnectClientError classes. Matching on shape
84
99
  * instead of identity is what makes the two agree: the shape is the
85
100
  * contract, the constructor is not.
101
+ *
102
+ * The shape is a ConnectError's (numeric `code`, `metadata`, `rawMessage`)
103
+ * plus the fields this class adds; `name` is "ConnectError" for the reason
104
+ * given on the class.
86
105
  */
87
106
  function isConnectClientErrorShape(v) {
88
107
  if (!(v instanceof Error))
@@ -90,22 +109,40 @@ function isConnectClientErrorShape(v) {
90
109
  if (Object.getPrototypeOf(v) === ConnectClientError.prototype)
91
110
  return true;
92
111
  const e = v;
93
- return (v.name === "ConnectClientError" &&
94
- typeof e.code === "string" &&
112
+ return (v.name === "ConnectError" &&
113
+ typeof e.code === "number" &&
114
+ typeof e.codeName === "string" &&
115
+ typeof e.rawMessage === "string" &&
95
116
  typeof e.status === "number" &&
96
117
  typeof e.retryable === "boolean" &&
97
118
  (typeof e.reason === "string" || e.reason === null));
98
119
  }
99
120
  /**
100
- * ConnectClientError is the single typed error shape the app catches. It is
101
- * a plain Error subclass so it works with React Query, error boundaries, and
102
- * `instanceof` alike.
121
+ * ConnectClientError is the single typed error shape the app catches.
122
+ *
123
+ * It IS a ConnectError — a subclass — so the error the runtime's
124
+ * errorNormalizeInterceptor throws still satisfies every consumer written
125
+ * against connect-es: `err instanceof ConnectError` holds, `err.code` is the
126
+ * numeric `Code`, and `metadata`, `details`, `findDetails()` and `rawMessage`
127
+ * are the original error's. What it adds is the normalized view: `codeName`,
128
+ * `status`, `retryable`, `reason` and `traceId`. An app that already branches
129
+ * on ConnectError can therefore adopt the runtime chain one call site at a
130
+ * time; nothing downgrades to `Code.Unknown` because a catch block met a type
131
+ * it did not expect.
132
+ *
133
+ * `name` stays "ConnectError". That is load-bearing: connect-es's
134
+ * `ConnectError[Symbol.hasInstance]` accepts an object whose prototype is
135
+ * exactly `ConnectError.prototype`, or one NAMED "ConnectError" with the
136
+ * right fields — a subclass instance is the second case, so any other name
137
+ * fails `instanceof ConnectError`.
138
+ *
139
+ * `message` is the server's text WITHOUT the "[code] " framing (the same as
140
+ * `rawMessage`), so it is presentable at every layer; connect-es's own
141
+ * `message` carries the prefix. Render with {@link userMessage} regardless.
103
142
  */
104
- export class ConnectClientError extends Error {
143
+ export class ConnectClientError extends ConnectError {
105
144
  /** Canonical Connect code name, e.g. "unavailable", "not_found". */
106
- code;
107
- /** Numeric Connect code (Code enum), or undefined for non-Connect errors. */
108
- connectCode;
145
+ codeName;
109
146
  /** Approximate HTTP status, for telemetry and generic UI. */
110
147
  status;
111
148
  /** True when a transparent retry is reasonable (transient failures). */
@@ -124,14 +161,25 @@ export class ConnectClientError extends Error {
124
161
  * key to every server span and log line of that request.
125
162
  */
126
163
  traceId;
164
+ /**
165
+ * `status` and `retryable` default from `code`; `reason` defaults to the
166
+ * x-forge-error-reason entry in `metadata`.
167
+ */
127
168
  constructor(args) {
128
- super(args.message, { cause: args.cause });
129
- this.name = "ConnectClientError";
130
- this.code = args.code;
131
- this.connectCode = args.connectCode;
132
- this.status = args.status;
133
- this.retryable = args.retryable;
134
- this.reason = args.reason ?? null;
169
+ super(args.message, args.code, args.metadata, undefined, args.cause);
170
+ // ConnectError's constructor takes only OUTGOING details (a server's);
171
+ // a client error carries the INCOMING ones it received, so they are
172
+ // assigned rather than passed. Its name, "ConnectError", is kept (above).
173
+ if (args.details)
174
+ this.details = args.details;
175
+ this.message = args.message;
176
+ this.codeName = codeName(args.code);
177
+ this.status = args.status ?? HTTP_STATUS[args.code] ?? 500;
178
+ this.retryable = args.retryable ?? isRetryableCode(args.code);
179
+ this.reason =
180
+ args.reason !== undefined
181
+ ? args.reason
182
+ : this.metadata.get(FORGE_ERROR_REASON_HEADER) || null;
135
183
  this.traceId = args.traceId ?? null;
136
184
  }
137
185
  /**
@@ -140,11 +188,8 @@ export class ConnectClientError extends Error {
140
188
  * working when two copies of this package end up in one bundle (see
141
189
  * {@link isConnectClientErrorShape}). Without it, normalizeError's
142
190
  * pass-through guard misses an already-normalized error from the other
143
- * copy; that error's `name` is "ConnectClientError" rather than
144
- * "ConnectError", so it misses the ConnectError branch too and is re-wrapped
145
- * through the generic Error branch — silently downgrading every error in the
146
- * app to code "unknown", status 500, no connectCode and no reason.
147
- * @connectrpc/connect does the same on ConnectError, for the same reason.
191
+ * copy and re-wraps it as a fresh error. @connectrpc/connect does the same
192
+ * on ConnectError, for the same reason.
148
193
  */
149
194
  static [Symbol.hasInstance](v) {
150
195
  return isConnectClientErrorShape(v);
@@ -163,7 +208,8 @@ export function isRetryableCode(code) {
163
208
  * Both `instanceof` checks below match on SHAPE rather than class identity —
164
209
  * ours via ConnectClientError's Symbol.hasInstance, ConnectError's via the one
165
210
  * @connectrpc/connect ships — so neither branch is missed when a second copy
166
- * of either package lands in the bundle.
211
+ * of either package lands in the bundle. The ConnectClientError check comes
212
+ * first because every ConnectClientError is also a ConnectError.
167
213
  */
168
214
  export function normalizeError(err, requestTraceId = null) {
169
215
  if (err instanceof ConnectClientError) {
@@ -174,12 +220,12 @@ export function normalizeError(err, requestTraceId = null) {
174
220
  // Strip the "[code] " prefix so the message is user-presentable at
175
221
  // every layer.
176
222
  message: stripServerFraming(err.rawMessage || err.message),
177
- code: Code[err.code]?.toLowerCase() ?? "unknown",
178
- connectCode: err.code,
179
- status: HTTP_STATUS[err.code] ?? 500,
180
- retryable: isRetryableCode(err.code),
181
- // Stable machine reason from backend metadata (backend owns the set).
182
- reason: err.metadata.get(FORGE_ERROR_REASON_HEADER) || null,
223
+ code: err.code,
224
+ // The original metadata and details ride along, so `findDetails()` and
225
+ // `metadata.get(...)` answer exactly as they did on the raw error. The
226
+ // reason (backend-owned) is read from that metadata by the constructor.
227
+ metadata: err.metadata,
228
+ details: err.details,
183
229
  // The server's own span when it answered; the trace this runtime asked
184
230
  // for when it did not (a proxy error, an older server).
185
231
  traceId: traceIdFrom(err.metadata.get(TRACERESPONSE_HEADER)) ?? requestTraceId,
@@ -187,6 +233,16 @@ export function normalizeError(err, requestTraceId = null) {
187
233
  });
188
234
  }
189
235
  if (err instanceof Error) {
236
+ // An aborted or timed-out fetch is a cancellation, as ConnectError.from
237
+ // reads it.
238
+ if (err.name === "AbortError" || err.name === "TimeoutError") {
239
+ return new ConnectClientError({
240
+ message: stripServerFraming(err.message),
241
+ code: Code.Canceled,
242
+ traceId: requestTraceId,
243
+ cause: err,
244
+ });
245
+ }
190
246
  // A network fault (fetch rejected: offline, DNS, CORS preflight, TLS)
191
247
  // surfaces as a TypeError — that, and only that, is a safe transparent
192
248
  // retry. A generic Error is NOT blanket-retried (blanket-retrying every
@@ -194,7 +250,7 @@ export function normalizeError(err, requestTraceId = null) {
194
250
  const networkFault = err instanceof TypeError;
195
251
  return new ConnectClientError({
196
252
  message: stripServerFraming(err.message),
197
- code: networkFault ? "unavailable" : "unknown",
253
+ code: networkFault ? Code.Unavailable : Code.Unknown,
198
254
  status: networkFault ? 503 : 500,
199
255
  retryable: networkFault,
200
256
  reason: null,
@@ -204,7 +260,7 @@ export function normalizeError(err, requestTraceId = null) {
204
260
  }
205
261
  return new ConnectClientError({
206
262
  message: typeof err === "string" ? stripServerFraming(err) : "Unknown error",
207
- code: "unknown",
263
+ code: Code.Unknown,
208
264
  status: 500,
209
265
  retryable: false,
210
266
  reason: null,
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,wEAAwE;AACxE,wEAAwE;AACxE,4EAA4E;AAC5E,yEAAyE;AACzE,+DAA+D;AAC/D,6BAA6B;AAC7B,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,EAAE,oBAAoB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S,EAAE,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC;YACpC,sEAAsE;YACtE,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAC,IAAI,IAAI;YAC3D,uEAAuE;YACvE,wDAAwD;YACxD,OAAO,EACL,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC,IAAI,cAAc;YACvE,KAAK,EAAE,GAAG;SACX,CAAC,CAAC;IACL,CAAC;IAED,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACzB,sEAAsE;QACtE,uEAAuE;QACvE,wEAAwE;QACxE,mEAAmE;QACnE,MAAM,YAAY,GAAG,GAAG,YAAY,SAAS,CAAC;QAC9C,OAAO,IAAI,kBAAkB,CAAC;YAC5B,OAAO,EAAE,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC;YACxC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS;YAC9C,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;YAChC,SAAS,EAAE,YAAY;YACvB,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,cAAc;YACvB,KAAK,EAAE,GAAG;SACX,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,kBAAkB,CAAC;QAC5B,OAAO,EACL,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe;QACrE,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,GAAG;QACX,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,GAAG;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Typed client errors. Connect surfaces failures as ConnectError with a\n// numeric Code; the rest of the app should reason about a stable, typed\n// shape instead of sniffing status codes at every call site. normalizeError\n// maps any thrown value into a ConnectClientError carrying the canonical\n// code name, an HTTP-ish status, a retryability verdict, and a\n// human-presentable message.\nimport { Code, ConnectError } from \"@connectrpc/connect\";\n\nimport { TRACERESPONSE_HEADER, traceIdFrom } from \"./trace.js\";\n\n/**\n * FORGE_ERROR_REASON_HEADER is the Connect trailer/metadata key carrying a\n * stable, machine-readable reason code (snake_case) the backend sets for\n * every error. UI/routing keys off `error.reason` instead of matching\n * human-readable message strings — the message text is display-only and\n * may change. The backend owns the setter; the frontend only reads it.\n */\nexport const FORGE_ERROR_REASON_HEADER = \"x-forge-error-reason\";\n\n/**\n * stripServerFraming removes the transport framing that must never surface\n * to a user: the leading \"[code] \" gRPC-code prefix connect-es puts on\n * `ConnectError.message`. What survives is the message the server wrote,\n * which is exactly what a user should read.\n *\n * This is the SINGLE implementation — a project never wants a different\n * answer here, and a copy frozen into a scaffold could never be corrected\n * once shipped. Idempotent: framing that has already been stripped strips\n * to itself.\n */\nexport function stripServerFraming(message: string): string {\n return message.replace(/^\\[[a-z_]+\\]\\s*/i, \"\").trim();\n}\n\n/** The copy shown when an error carries no presentable message of its own. */\nconst DEFAULT_USER_MESSAGE = \"Something went wrong. Please try again.\";\n\n/**\n * userMessage — turn any thrown value into copy fit for end users.\n *\n * `ConnectError.message` prefixes the gRPC code (\"[not_found] no such task\");\n * `rawMessage` is the server's human-readable text without that framing, and\n * stripServerFraming drops the prefix from whichever of the two is available.\n * Use this everywhere an error is SHOWN (banners, toasts) instead of\n * `err.message`.\n *\n * Pass `fallback` to override the default copy for a surface that wants its\n * own wording.\n */\nexport function userMessage(\n err: unknown,\n fallback: string = DEFAULT_USER_MESSAGE,\n): string {\n if (err instanceof ConnectError) {\n return stripServerFraming(err.rawMessage || err.message) || fallback;\n }\n if (err instanceof Error) {\n return stripServerFraming(err.message) || fallback;\n }\n return err == null ? fallback : stripServerFraming(String(err)) || fallback;\n}\n\n/** Connect codes worth a transparent transport-level retry. */\nconst RETRYABLE = new Set<Code>([\n Code.Unavailable,\n Code.DeadlineExceeded,\n Code.Aborted,\n Code.ResourceExhausted,\n]);\n\n/** Rough Connect-code → HTTP-status mapping for display/telemetry only. */\nconst HTTP_STATUS: Partial<Record<Code, number>> = {\n [Code.InvalidArgument]: 400,\n [Code.Unauthenticated]: 401,\n [Code.PermissionDenied]: 403,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.ResourceExhausted]: 429,\n [Code.Unimplemented]: 501,\n [Code.Unavailable]: 503,\n [Code.DeadlineExceeded]: 504,\n [Code.Internal]: 500,\n};\n\n/**\n * isConnectClientErrorShape — the STRUCTURAL test behind\n * {@link ConnectClientError}'s `instanceof`.\n *\n * A class object is per module instance, not per package. npm nests a\n * transitive dependency on any version conflict, and a bundler can pull one\n * package in as both ESM and CJS, so a tree holding two copies of this\n * package holds two distinct ConnectClientError classes. Matching on shape\n * instead of identity is what makes the two agree: the shape is the\n * contract, the constructor is not.\n */\nfunction isConnectClientErrorShape(v: unknown): v is ConnectClientError {\n if (!(v instanceof Error)) return false;\n if (Object.getPrototypeOf(v) === ConnectClientError.prototype) return true;\n const e = v as Partial<ConnectClientError>;\n return (\n v.name === \"ConnectClientError\" &&\n typeof e.code === \"string\" &&\n typeof e.status === \"number\" &&\n typeof e.retryable === \"boolean\" &&\n (typeof e.reason === \"string\" || e.reason === null)\n );\n}\n\n/**\n * ConnectClientError is the single typed error shape the app catches. It is\n * a plain Error subclass so it works with React Query, error boundaries, and\n * `instanceof` alike.\n */\nexport class ConnectClientError extends Error {\n /** Canonical Connect code name, e.g. \"unavailable\", \"not_found\". */\n readonly code: string;\n /** Numeric Connect code (Code enum), or undefined for non-Connect errors. */\n readonly connectCode?: Code;\n /** Approximate HTTP status, for telemetry and generic UI. */\n readonly status: number;\n /** True when a transparent retry is reasonable (transient failures). */\n readonly retryable: boolean;\n /**\n * Stable machine-readable reason code from the backend\n * (x-forge-error-reason metadata), or null. Key UI/routing off THIS,\n * never off `message` — message text is display-only.\n */\n readonly reason: string | null;\n /**\n * The trace the failed request was recorded in: the server's\n * `traceresponse` when it sent one, else the trace id of the traceparent\n * this runtime sent, else null (the request never left the browser). Put it\n * in a bug report, a toast's \"copy details\", or a support ticket — it is the\n * key to every server span and log line of that request.\n */\n readonly traceId: string | null;\n\n constructor(args: {\n message: string;\n code: string;\n connectCode?: Code;\n status: number;\n retryable: boolean;\n reason?: string | null;\n traceId?: string | null;\n cause?: unknown;\n }) {\n super(args.message, { cause: args.cause });\n this.name = \"ConnectClientError\";\n this.code = args.code;\n this.connectCode = args.connectCode;\n this.status = args.status;\n this.retryable = args.retryable;\n this.reason = args.reason ?? null;\n this.traceId = args.traceId ?? null;\n }\n\n /**\n * `instanceof` matches on SHAPE, not on class identity — so every check\n * spelled `err instanceof ConnectClientError`, here and in app code, keeps\n * working when two copies of this package end up in one bundle (see\n * {@link isConnectClientErrorShape}). Without it, normalizeError's\n * pass-through guard misses an already-normalized error from the other\n * copy; that error's `name` is \"ConnectClientError\" rather than\n * \"ConnectError\", so it misses the ConnectError branch too and is re-wrapped\n * through the generic Error branch — silently downgrading every error in the\n * app to code \"unknown\", status 500, no connectCode and no reason.\n * @connectrpc/connect does the same on ConnectError, for the same reason.\n */\n static [Symbol.hasInstance](v: unknown): boolean {\n return isConnectClientErrorShape(v);\n }\n}\n\n/** isRetryable reports whether a Connect code merits a transport retry. */\nexport function isRetryableCode(code: Code): boolean {\n return RETRYABLE.has(code);\n}\n\n/**\n * normalizeError coerces any thrown value into a ConnectClientError. Already-\n * normalized errors pass through unchanged so the interceptor chain never\n * double-wraps. `requestTraceId` is the trace id of the traceparent the\n * request carried, used when the server sent no `traceresponse`.\n *\n * Both `instanceof` checks below match on SHAPE rather than class identity —\n * ours via ConnectClientError's Symbol.hasInstance, ConnectError's via the one\n * @connectrpc/connect ships — so neither branch is missed when a second copy\n * of either package lands in the bundle.\n */\nexport function normalizeError(\n err: unknown,\n requestTraceId: string | null = null,\n): ConnectClientError {\n if (err instanceof ConnectClientError) {\n return err;\n }\n\n if (err instanceof ConnectError) {\n return new ConnectClientError({\n // Strip the \"[code] \" prefix so the message is user-presentable at\n // every layer.\n message: stripServerFraming(err.rawMessage || err.message),\n code: Code[err.code]?.toLowerCase() ?? \"unknown\",\n connectCode: err.code,\n status: HTTP_STATUS[err.code] ?? 500,\n retryable: isRetryableCode(err.code),\n // Stable machine reason from backend metadata (backend owns the set).\n reason: err.metadata.get(FORGE_ERROR_REASON_HEADER) || null,\n // The server's own span when it answered; the trace this runtime asked\n // for when it did not (a proxy error, an older server).\n traceId:\n traceIdFrom(err.metadata.get(TRACERESPONSE_HEADER)) ?? requestTraceId,\n cause: err,\n });\n }\n\n if (err instanceof Error) {\n // A network fault (fetch rejected: offline, DNS, CORS preflight, TLS)\n // surfaces as a TypeError — that, and only that, is a safe transparent\n // retry. A generic Error is NOT blanket-retried (blanket-retrying every\n // bare Error widened the blast radius to non-idempotent failures).\n const networkFault = err instanceof TypeError;\n return new ConnectClientError({\n message: stripServerFraming(err.message),\n code: networkFault ? \"unavailable\" : \"unknown\",\n status: networkFault ? 503 : 500,\n retryable: networkFault,\n reason: null,\n traceId: requestTraceId,\n cause: err,\n });\n }\n\n return new ConnectClientError({\n message:\n typeof err === \"string\" ? stripServerFraming(err) : \"Unknown error\",\n code: \"unknown\",\n status: 500,\n retryable: false,\n reason: null,\n cause: err,\n });\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,wEAAwE;AACxE,wEAAwE;AACxE,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,0EAA0E;AAC1E,6BAA6B;AAC7B,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE/D;;;;;;GAMG;AACH,MAAM,C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B,KAAK,EAAE,GAAG;aACX,CAAC,CAAC;QACL,CAAC;QACD,sEAAsE;QACtE,uEAAuE;QACvE,wEAAwE;QACxE,mEAAmE;QACnE,MAAM,YAAY,GAAG,GAAG,YAAY,SAAS,CAAC;QAC9C,OAAO,IAAI,kBAAkB,CAAC;YAC5B,OAAO,EAAE,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC;YACxC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO;YACpD,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;YAChC,SAAS,EAAE,YAAY;YACvB,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,cAAc;YACvB,KAAK,EAAE,GAAG;SACX,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,kBAAkB,CAAC;QAC5B,OAAO,EACL,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe;QACrE,IAAI,EAAE,IAAI,CAAC,OAAO;QAClB,MAAM,EAAE,GAAG;QACX,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,GAAG;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Typed client errors. Connect surfaces failures as ConnectError with a\n// numeric Code; the rest of the app should reason about a stable, typed\n// shape instead of sniffing status codes at every call site. normalizeError\n// maps any thrown value into a ConnectClientError — a ConnectError subclass,\n// so connect-es consumers keep working — carrying the canonical code name,\n// an HTTP-ish status, a retryability verdict, the backend's reason, and a\n// human-presentable message.\nimport { Code, ConnectError } from \"@connectrpc/connect\";\n\nimport { TRACERESPONSE_HEADER, traceIdFrom } from \"./trace.js\";\n\n/**\n * FORGE_ERROR_REASON_HEADER is the Connect trailer/metadata key carrying a\n * stable, machine-readable reason code (snake_case) the backend sets for\n * every error. UI/routing keys off `error.reason` instead of matching\n * human-readable message strings — the message text is display-only and\n * may change. The backend owns the setter; the frontend only reads it.\n */\nexport const FORGE_ERROR_REASON_HEADER = \"x-forge-error-reason\";\n\n/**\n * stripServerFraming removes the transport framing that must never surface\n * to a user: the leading \"[code] \" gRPC-code prefix connect-es puts on\n * `ConnectError.message`. What survives is the message the server wrote,\n * which is exactly what a user should read.\n *\n * This is the SINGLE implementation — a project never wants a different\n * answer here, and a copy frozen into a scaffold could never be corrected\n * once shipped. Idempotent: framing that has already been stripped strips\n * to itself.\n */\nexport function stripServerFraming(message: string): string {\n return message.replace(/^\\[[a-z_]+\\]\\s*/i, \"\").trim();\n}\n\n/** The copy shown when an error carries no presentable message of its own. */\nconst DEFAULT_USER_MESSAGE = \"Something went wrong. Please try again.\";\n\n/**\n * userMessage — turn any thrown value into copy fit for end users.\n *\n * `ConnectError.message` prefixes the gRPC code (\"[not_found] no such task\");\n * `rawMessage` is the server's human-readable text without that framing, and\n * stripServerFraming drops the prefix from whichever of the two is available.\n * Use this everywhere an error is SHOWN (banners, toasts) instead of\n * `err.message`.\n *\n * Pass `fallback` to override the default copy for a surface that wants its\n * own wording.\n */\nexport function userMessage(\n err: unknown,\n fallback: string = DEFAULT_USER_MESSAGE,\n): string {\n if (err instanceof ConnectError) {\n return stripServerFraming(err.rawMessage || err.message) || fallback;\n }\n if (err instanceof Error) {\n return stripServerFraming(err.message) || fallback;\n }\n return err == null ? fallback : stripServerFraming(String(err)) || fallback;\n}\n\n/** Connect codes worth a transparent transport-level retry. */\nconst RETRYABLE = new Set<Code>([\n Code.Unavailable,\n Code.DeadlineExceeded,\n Code.Aborted,\n Code.ResourceExhausted,\n]);\n\n/** Rough Connect-code → HTTP-status mapping for display/telemetry only. */\nconst HTTP_STATUS: Partial<Record<Code, number>> = {\n [Code.InvalidArgument]: 400,\n [Code.Unauthenticated]: 401,\n [Code.PermissionDenied]: 403,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.ResourceExhausted]: 429,\n [Code.Unimplemented]: 501,\n [Code.Unavailable]: 503,\n [Code.DeadlineExceeded]: 504,\n [Code.Internal]: 500,\n};\n\n/**\n * codeName — the canonical wire name of a Connect code: `Code.NotFound` →\n * \"not_found\", `Code.DeadlineExceeded` → \"deadline_exceeded\". The spelling\n * the Connect protocol puts on the wire and in the \"[code] \" message prefix.\n *\n * (An earlier version lower-cased the enum key, which produced \"notfound\" —\n * a name that matches nothing the server or the docs spell.)\n */\nexport function codeName(code: Code): string {\n const key = Code[code];\n if (typeof key !== \"string\") return \"unknown\";\n return key.replace(\n /[A-Z]/g,\n (c, i: number) => (i === 0 ? \"\" : \"_\") + c.toLowerCase(),\n );\n}\n\n/**\n * isConnectClientErrorShape — the STRUCTURAL test behind\n * {@link ConnectClientError}'s `instanceof`.\n *\n * A class object is per module instance, not per package. npm nests a\n * transitive dependency on any version conflict, and a bundler can pull one\n * package in as both ESM and CJS, so a tree holding two copies of this\n * package holds two distinct ConnectClientError classes. Matching on shape\n * instead of identity is what makes the two agree: the shape is the\n * contract, the constructor is not.\n *\n * The shape is a ConnectError's (numeric `code`, `metadata`, `rawMessage`)\n * plus the fields this class adds; `name` is \"ConnectError\" for the reason\n * given on the class.\n */\nfunction isConnectClientErrorShape(v: unknown): v is ConnectClientError {\n if (!(v instanceof Error)) return false;\n if (Object.getPrototypeOf(v) === ConnectClientError.prototype) return true;\n const e = v as Partial<ConnectClientError>;\n return (\n v.name === \"ConnectError\" &&\n typeof e.code === \"number\" &&\n typeof e.codeName === \"string\" &&\n typeof e.rawMessage === \"string\" &&\n typeof e.status === \"number\" &&\n typeof e.retryable === \"boolean\" &&\n (typeof e.reason === \"string\" || e.reason === null)\n );\n}\n\n/** Detail types a ConnectError carries; spelled off the base class's field. */\ntype ConnectErrorDetails = ConnectError[\"details\"];\n\n/**\n * ConnectClientError is the single typed error shape the app catches.\n *\n * It IS a ConnectError — a subclass — so the error the runtime's\n * errorNormalizeInterceptor throws still satisfies every consumer written\n * against connect-es: `err instanceof ConnectError` holds, `err.code` is the\n * numeric `Code`, and `metadata`, `details`, `findDetails()` and `rawMessage`\n * are the original error's. What it adds is the normalized view: `codeName`,\n * `status`, `retryable`, `reason` and `traceId`. An app that already branches\n * on ConnectError can therefore adopt the runtime chain one call site at a\n * time; nothing downgrades to `Code.Unknown` because a catch block met a type\n * it did not expect.\n *\n * `name` stays \"ConnectError\". That is load-bearing: connect-es's\n * `ConnectError[Symbol.hasInstance]` accepts an object whose prototype is\n * exactly `ConnectError.prototype`, or one NAMED \"ConnectError\" with the\n * right fields — a subclass instance is the second case, so any other name\n * fails `instanceof ConnectError`.\n *\n * `message` is the server's text WITHOUT the \"[code] \" framing (the same as\n * `rawMessage`), so it is presentable at every layer; connect-es's own\n * `message` carries the prefix. Render with {@link userMessage} regardless.\n */\nexport class ConnectClientError extends ConnectError {\n /** Canonical Connect code name, e.g. \"unavailable\", \"not_found\". */\n readonly codeName: string;\n /** Approximate HTTP status, for telemetry and generic UI. */\n readonly status: number;\n /** True when a transparent retry is reasonable (transient failures). */\n readonly retryable: boolean;\n /**\n * Stable machine-readable reason code from the backend\n * (x-forge-error-reason metadata), or null. Key UI/routing off THIS,\n * never off `message` — message text is display-only.\n */\n readonly reason: string | null;\n /**\n * The trace the failed request was recorded in: the server's\n * `traceresponse` when it sent one, else the trace id of the traceparent\n * this runtime sent, else null (the request never left the browser). Put it\n * in a bug report, a toast's \"copy details\", or a support ticket — it is the\n * key to every server span and log line of that request.\n */\n readonly traceId: string | null;\n\n /**\n * `status` and `retryable` default from `code`; `reason` defaults to the\n * x-forge-error-reason entry in `metadata`.\n */\n constructor(args: {\n /** The server's message, without \"[code] \" framing. */\n message: string;\n code: Code;\n metadata?: HeadersInit;\n details?: ConnectErrorDetails;\n status?: number;\n retryable?: boolean;\n reason?: string | null;\n traceId?: string | null;\n cause?: unknown;\n }) {\n super(args.message, args.code, args.metadata, undefined, args.cause);\n // ConnectError's constructor takes only OUTGOING details (a server's);\n // a client error carries the INCOMING ones it received, so they are\n // assigned rather than passed. Its name, \"ConnectError\", is kept (above).\n if (args.details) this.details = args.details;\n this.message = args.message;\n this.codeName = codeName(args.code);\n this.status = args.status ?? HTTP_STATUS[args.code] ?? 500;\n this.retryable = args.retryable ?? isRetryableCode(args.code);\n this.reason =\n args.reason !== undefined\n ? args.reason\n : this.metadata.get(FORGE_ERROR_REASON_HEADER) || null;\n this.traceId = args.traceId ?? null;\n }\n\n /**\n * `instanceof` matches on SHAPE, not on class identity — so every check\n * spelled `err instanceof ConnectClientError`, here and in app code, keeps\n * working when two copies of this package end up in one bundle (see\n * {@link isConnectClientErrorShape}). Without it, normalizeError's\n * pass-through guard misses an already-normalized error from the other\n * copy and re-wraps it as a fresh error. @connectrpc/connect does the same\n * on ConnectError, for the same reason.\n */\n static [Symbol.hasInstance](v: unknown): boolean {\n return isConnectClientErrorShape(v);\n }\n}\n\n/** isRetryable reports whether a Connect code merits a transport retry. */\nexport function isRetryableCode(code: Code): boolean {\n return RETRYABLE.has(code);\n}\n\n/**\n * normalizeError coerces any thrown value into a ConnectClientError. Already-\n * normalized errors pass through unchanged so the interceptor chain never\n * double-wraps. `requestTraceId` is the trace id of the traceparent the\n * request carried, used when the server sent no `traceresponse`.\n *\n * Both `instanceof` checks below match on SHAPE rather than class identity —\n * ours via ConnectClientError's Symbol.hasInstance, ConnectError's via the one\n * @connectrpc/connect ships — so neither branch is missed when a second copy\n * of either package lands in the bundle. The ConnectClientError check comes\n * first because every ConnectClientError is also a ConnectError.\n */\nexport function normalizeError(\n err: unknown,\n requestTraceId: string | null = null,\n): ConnectClientError {\n if (err instanceof ConnectClientError) {\n return err;\n }\n\n if (err instanceof ConnectError) {\n return new ConnectClientError({\n // Strip the \"[code] \" prefix so the message is user-presentable at\n // every layer.\n message: stripServerFraming(err.rawMessage || err.message),\n code: err.code,\n // The original metadata and details ride along, so `findDetails()` and\n // `metadata.get(...)` answer exactly as they did on the raw error. The\n // reason (backend-owned) is read from that metadata by the constructor.\n metadata: err.metadata,\n details: err.details,\n // The server's own span when it answered; the trace this runtime asked\n // for when it did not (a proxy error, an older server).\n traceId:\n traceIdFrom(err.metadata.get(TRACERESPONSE_HEADER)) ?? requestTraceId,\n cause: err,\n });\n }\n\n if (err instanceof Error) {\n // An aborted or timed-out fetch is a cancellation, as ConnectError.from\n // reads it.\n if (err.name === \"AbortError\" || err.name === \"TimeoutError\") {\n return new ConnectClientError({\n message: stripServerFraming(err.message),\n code: Code.Canceled,\n traceId: requestTraceId,\n cause: err,\n });\n }\n // A network fault (fetch rejected: offline, DNS, CORS preflight, TLS)\n // surfaces as a TypeError — that, and only that, is a safe transparent\n // retry. A generic Error is NOT blanket-retried (blanket-retrying every\n // bare Error widened the blast radius to non-idempotent failures).\n const networkFault = err instanceof TypeError;\n return new ConnectClientError({\n message: stripServerFraming(err.message),\n code: networkFault ? Code.Unavailable : Code.Unknown,\n status: networkFault ? 503 : 500,\n retryable: networkFault,\n reason: null,\n traceId: requestTraceId,\n cause: err,\n });\n }\n\n return new ConnectClientError({\n message:\n typeof err === \"string\" ? stripServerFraming(err) : \"Unknown error\",\n code: Code.Unknown,\n status: 500,\n retryable: false,\n reason: null,\n cause: err,\n });\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { authInterceptor, buildRuntimeInterceptors, errorNormalizeInterceptor, h
4
4
  * Typed client errors, and the backend-framing strippers every surface that
5
5
  * SHOWS an error goes through.
6
6
  */
7
- export { ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, stripServerFraming, userMessage, } from "./errors.js";
7
+ export { codeName, ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, stripServerFraming, userMessage, } from "./errors.js";
8
8
  /**
9
9
  * Mount-prefix helpers, for the URLs Next.js's router never sees — absolute
10
10
  * URLs handed to external systems that round-trip back into the app.
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ export { authInterceptor, buildRuntimeInterceptors, errorNormalizeInterceptor, h
22
22
  * Typed client errors, and the backend-framing strippers every surface that
23
23
  * SHOWS an error goes through.
24
24
  */
25
- export { ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, stripServerFraming, userMessage, } from "./errors.js";
25
+ export { codeName, ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, stripServerFraming, userMessage, } from "./errors.js";
26
26
  /**
27
27
  * Mount-prefix helpers, for the URLs Next.js's router never sees — absolute
28
28
  * URLs handed to external systems that round-trip back into the app.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,EAAE;AACF,yEAAyE;AACzE,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,4EAA4E;AAC5E,8EAA8E;AAC9E,gEAAgE;AAChE,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,4CAA4C;AAE5C,yEAAyE;AACzE,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,sEAAsE;AAEtE,mCAAmC;AACnC,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GAEjB,MAAM,mBAAmB,CAAC;AAE3B;;;GAGG;AACH,OAAO,EACL,kBAAkB,EAClB,yBAAyB,EACzB,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,WAAW,GACZ,MAAM,aAAa,CAAC;AAErB;;;;;;GAMG;AACH,OAAO,EACL,cAAc,EACd,YAAY,EACZ,iBAAiB,GAElB,MAAM,eAAe,CAAC;AAEvB;;;;;;;GAOG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,GAKhB,MAAM,YAAY,CAAC;AAEpB,qCAAqC;AACrC,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,cAAc,EACd,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAEpB,qFAAqF;AACrF,OAAO,EACL,SAAS,EACT,eAAe,EACf,UAAU,GAIX,MAAM,cAAc,CAAC;AAEtB,gFAAgF;AAChF,OAAO,EAAE,YAAY,EAA0B,MAAM,gBAAgB,CAAC;AAEtE,+EAA+E;AAC/E,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,yEAAyE;AACzE,OAAO,EACL,gBAAgB,GAMjB,MAAM,iBAAiB,CAAC;AAEzB,gEAAgE;AAChE,OAAO,EAAE,UAAU,EAAwB,MAAM,kBAAkB,CAAC;AAEpE,uFAAuF;AACvF,OAAO,EACL,QAAQ,GAIT,MAAM,eAAe,CAAC;AAEvB;;;;GAIG;AACH,OAAO,EACL,eAAe,EACf,oBAAoB,GAErB,MAAM,qBAAqB,CAAC;AAE7B,qFAAqF;AACrF,OAAO,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE3E;;;;;;GAMG;AACH,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,GAGN,MAAM,YAAY,CAAC;AAEpB;;;;;;GAMG;AACH,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,GAGpB,MAAM,aAAa,CAAC","sourcesContent":["// @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Public barrel. Import batteries from \"@reliantlabs/forge-web-runtime\".\n//\n// Everything here is MECHANISM: the transport interceptor stack, the session,\n// the error boundary, the toast queue, the <Resource> tristate ladder, W3C\n// trace propagation, client RUM. Nothing here reaches into an application —\n// app-shaped values (auth state, event subscriptions, toast markup) arrive as\n// props, so an app can restyle or replace its own files freely.\n//\n// Presentation that a project is meant to own — the component library under\n// src/components/ui, globals.css, nav, layout — deliberately stays in the\n// scaffold and is NOT part of this package.\n\n// The per-group docs below are JSDoc, not `//`, on purpose: TypeScript's\n// declaration emit preserves JSDoc and DROPS line comments, and dist/ is now\n// the whole of what this package publishes. `forge project libraries` reads\n// this inventory out of the published barrel, and a consumer's editor shows\n// it on hover — both would get symbols with no explanation otherwise.\n\n/** Transport interceptor stack. */\nexport {\n authInterceptor,\n buildRuntimeInterceptors,\n errorNormalizeInterceptor,\n headerInterceptor,\n retryInterceptor,\n traceInterceptor,\n type RuntimeInterceptorConfig,\n} from \"./interceptors.js\";\n\n/**\n * Typed client errors, and the backend-framing strippers every surface that\n * SHOWS an error goes through.\n */\nexport {\n ConnectClientError,\n FORGE_ERROR_REASON_HEADER,\n isRetryableCode,\n normalizeError,\n stripServerFraming,\n userMessage,\n} from \"./errors.js\";\n\n/**\n * Mount-prefix helpers, for the URLs Next.js's router never sees — absolute\n * URLs handed to external systems that round-trip back into the app.\n *\n * Barrel-exported rather than behind a subpath: three string functions with\n * no imports, so there is no dependency footprint for a subpath to fence off.\n */\nexport {\n createBasePath,\n joinBasePath,\n normalizeBasePath,\n type BasePathHelpers,\n} from \"./basepath.js\";\n\n/**\n * Money and basis points as integers: format minor units through Intl, and\n * parse form input back to minor units without rounding.\n *\n * The web counterpart of forge/pkg/money — an int64 count of the currency's\n * minor unit plus an ISO 4217 code, exact past 2^53. Barrel-exported for the\n * same reason as the base-path helpers: it imports nothing.\n */\nexport {\n basisPointsToInput,\n currencyMinorDigits,\n formatBasisPoints,\n formatMinorUnits,\n minorUnitsToInput,\n parseBasisPoints,\n parseMinorUnits,\n type BasisPointsOptions,\n type MoneyOptions,\n type ParseBasisPointsOptions,\n type ParseMoneyOptions,\n} from \"./money.js\";\n\n/** W3C trace-context propagation. */\nexport {\n freshTraceparent,\n injectTraceContext,\n setTraceSampled,\n traceIdFrom,\n TRACEPARENT_RE,\n TRACERESPONSE_HEADER,\n} from \"./trace.js\";\n\n/** Session: the signed-in user, derived from the app's auth state and JWT claims. */\nexport {\n decodeJwt,\n SessionProvider,\n useSession,\n type JwtClaims,\n type Session,\n type SessionAuth,\n} from \"./session.js\";\n\n/** The app-shell provider set: session + error boundary + toast host in one. */\nexport { RuntimeShell, type RuntimeShellProps } from \"./providers.js\";\n\n/** Error boundary with a designed crash fallback, for a route or a subtree. */\nexport {\n DefaultErrorFallback,\n RuntimeErrorBoundary,\n} from \"./error-boundary.js\";\n\n/** The toast queue. The app supplies the event source and the markup. */\nexport {\n RuntimeToastHost,\n type RuntimeToast,\n type RuntimeToastHostProps,\n type RuntimeToastPayload,\n type RuntimeToastSink,\n type RuntimeToastVariant,\n} from \"./toast-host.js\";\n\n/** Route guarding: render a page only to a signed-in caller. */\nexport { RouteGuard, type RouteGuardProps } from \"./route-guard.js\";\n\n/** Generic data-table container: the tristate ladder, filter and cursor pagination. */\nexport {\n Resource,\n type ResourceColumn,\n type ResourceProps,\n type ResourceStatus,\n} from \"./resource.js\";\n\n/**\n * Record a caught error with the browser telemetry SDK, when one is running.\n * A no-op otherwise, so it is safe in any catch block. The SDK itself arrives\n * through the \"/telemetry\" subpath, never the barrel.\n */\nexport {\n reportException,\n setExceptionReporter,\n type ExceptionAttributes,\n} from \"./error-reporter.js\";\n\n/** The server trace id a failed RPC's error carries (ConnectClientError.traceId). */\nexport { SERVER_TRACE_ID_ATTRIBUTE, serverTraceIdOf } from \"./trace-id.js\";\n\n/**\n * Product events, the signed-in user and the consent kill-switch for browser\n * telemetry. Like reportException these are safe to call anywhere — no-ops on\n * the server and when telemetry is off — and calls made while the SDK is still\n * loading are held and replayed. The SDK itself arrives through the\n * \"/telemetry\" subpath, never the barrel.\n */\nexport {\n disableTelemetry,\n setTelemetryUser,\n track,\n type TrackProps,\n type TrackValue,\n} from \"./track.js\";\n\n/**\n * Dev-only browser log forwarding: mirrors console output and uncaught errors\n * to the dev server, which prints them into\n * `.forge/logs/<env>/frontend_<name>.log`. No-ops unless `dev: true`, and the\n * receiving endpoint exists only in a dev server — so a production bundle\n * neither posts nor has anywhere to post to.\n */\nexport {\n DEV_LOG_ENDPOINT,\n devLoggingInstalled,\n installDevLogging,\n uninstallDevLogging,\n type DevLoggingOptions,\n type DevLogPayload,\n} from \"./devlog.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,EAAE;AACF,yEAAyE;AACzE,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,4EAA4E;AAC5E,8EAA8E;AAC9E,gEAAgE;AAChE,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,4CAA4C;AAE5C,yEAAyE;AACzE,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,sEAAsE;AAEtE,mCAAmC;AACnC,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GAEjB,MAAM,mBAAmB,CAAC;AAE3B;;;GAGG;AACH,OAAO,EACL,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,WAAW,GACZ,MAAM,aAAa,CAAC;AAErB;;;;;;GAMG;AACH,OAAO,EACL,cAAc,EACd,YAAY,EACZ,iBAAiB,GAElB,MAAM,eAAe,CAAC;AAEvB;;;;;;;GAOG;AACH,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,GAKhB,MAAM,YAAY,CAAC;AAEpB,qCAAqC;AACrC,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,cAAc,EACd,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAEpB,qFAAqF;AACrF,OAAO,EACL,SAAS,EACT,eAAe,EACf,UAAU,GAIX,MAAM,cAAc,CAAC;AAEtB,gFAAgF;AAChF,OAAO,EAAE,YAAY,EAA0B,MAAM,gBAAgB,CAAC;AAEtE,+EAA+E;AAC/E,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,yEAAyE;AACzE,OAAO,EACL,gBAAgB,GAMjB,MAAM,iBAAiB,CAAC;AAEzB,gEAAgE;AAChE,OAAO,EAAE,UAAU,EAAwB,MAAM,kBAAkB,CAAC;AAEpE,uFAAuF;AACvF,OAAO,EACL,QAAQ,GAIT,MAAM,eAAe,CAAC;AAEvB;;;;GAIG;AACH,OAAO,EACL,eAAe,EACf,oBAAoB,GAErB,MAAM,qBAAqB,CAAC;AAE7B,qFAAqF;AACrF,OAAO,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAE3E;;;;;;GAMG;AACH,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,GAGN,MAAM,YAAY,CAAC;AAEpB;;;;;;GAMG;AACH,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,GAGpB,MAAM,aAAa,CAAC","sourcesContent":["// @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Public barrel. Import batteries from \"@reliantlabs/forge-web-runtime\".\n//\n// Everything here is MECHANISM: the transport interceptor stack, the session,\n// the error boundary, the toast queue, the <Resource> tristate ladder, W3C\n// trace propagation, client RUM. Nothing here reaches into an application —\n// app-shaped values (auth state, event subscriptions, toast markup) arrive as\n// props, so an app can restyle or replace its own files freely.\n//\n// Presentation that a project is meant to own — the component library under\n// src/components/ui, globals.css, nav, layout — deliberately stays in the\n// scaffold and is NOT part of this package.\n\n// The per-group docs below are JSDoc, not `//`, on purpose: TypeScript's\n// declaration emit preserves JSDoc and DROPS line comments, and dist/ is now\n// the whole of what this package publishes. `forge project libraries` reads\n// this inventory out of the published barrel, and a consumer's editor shows\n// it on hover — both would get symbols with no explanation otherwise.\n\n/** Transport interceptor stack. */\nexport {\n authInterceptor,\n buildRuntimeInterceptors,\n errorNormalizeInterceptor,\n headerInterceptor,\n retryInterceptor,\n traceInterceptor,\n type RuntimeInterceptorConfig,\n} from \"./interceptors.js\";\n\n/**\n * Typed client errors, and the backend-framing strippers every surface that\n * SHOWS an error goes through.\n */\nexport {\n codeName,\n ConnectClientError,\n FORGE_ERROR_REASON_HEADER,\n isRetryableCode,\n normalizeError,\n stripServerFraming,\n userMessage,\n} from \"./errors.js\";\n\n/**\n * Mount-prefix helpers, for the URLs Next.js's router never sees — absolute\n * URLs handed to external systems that round-trip back into the app.\n *\n * Barrel-exported rather than behind a subpath: three string functions with\n * no imports, so there is no dependency footprint for a subpath to fence off.\n */\nexport {\n createBasePath,\n joinBasePath,\n normalizeBasePath,\n type BasePathHelpers,\n} from \"./basepath.js\";\n\n/**\n * Money and basis points as integers: format minor units through Intl, and\n * parse form input back to minor units without rounding.\n *\n * The web counterpart of forge/pkg/money — an int64 count of the currency's\n * minor unit plus an ISO 4217 code, exact past 2^53. Barrel-exported for the\n * same reason as the base-path helpers: it imports nothing.\n */\nexport {\n basisPointsToInput,\n currencyMinorDigits,\n formatBasisPoints,\n formatMinorUnits,\n minorUnitsToInput,\n parseBasisPoints,\n parseMinorUnits,\n type BasisPointsOptions,\n type MoneyOptions,\n type ParseBasisPointsOptions,\n type ParseMoneyOptions,\n} from \"./money.js\";\n\n/** W3C trace-context propagation. */\nexport {\n freshTraceparent,\n injectTraceContext,\n setTraceSampled,\n traceIdFrom,\n TRACEPARENT_RE,\n TRACERESPONSE_HEADER,\n} from \"./trace.js\";\n\n/** Session: the signed-in user, derived from the app's auth state and JWT claims. */\nexport {\n decodeJwt,\n SessionProvider,\n useSession,\n type JwtClaims,\n type Session,\n type SessionAuth,\n} from \"./session.js\";\n\n/** The app-shell provider set: session + error boundary + toast host in one. */\nexport { RuntimeShell, type RuntimeShellProps } from \"./providers.js\";\n\n/** Error boundary with a designed crash fallback, for a route or a subtree. */\nexport {\n DefaultErrorFallback,\n RuntimeErrorBoundary,\n} from \"./error-boundary.js\";\n\n/** The toast queue. The app supplies the event source and the markup. */\nexport {\n RuntimeToastHost,\n type RuntimeToast,\n type RuntimeToastHostProps,\n type RuntimeToastPayload,\n type RuntimeToastSink,\n type RuntimeToastVariant,\n} from \"./toast-host.js\";\n\n/** Route guarding: render a page only to a signed-in caller. */\nexport { RouteGuard, type RouteGuardProps } from \"./route-guard.js\";\n\n/** Generic data-table container: the tristate ladder, filter and cursor pagination. */\nexport {\n Resource,\n type ResourceColumn,\n type ResourceProps,\n type ResourceStatus,\n} from \"./resource.js\";\n\n/**\n * Record a caught error with the browser telemetry SDK, when one is running.\n * A no-op otherwise, so it is safe in any catch block. The SDK itself arrives\n * through the \"/telemetry\" subpath, never the barrel.\n */\nexport {\n reportException,\n setExceptionReporter,\n type ExceptionAttributes,\n} from \"./error-reporter.js\";\n\n/** The server trace id a failed RPC's error carries (ConnectClientError.traceId). */\nexport { SERVER_TRACE_ID_ATTRIBUTE, serverTraceIdOf } from \"./trace-id.js\";\n\n/**\n * Product events, the signed-in user and the consent kill-switch for browser\n * telemetry. Like reportException these are safe to call anywhere — no-ops on\n * the server and when telemetry is off — and calls made while the SDK is still\n * loading are held and replayed. The SDK itself arrives through the\n * \"/telemetry\" subpath, never the barrel.\n */\nexport {\n disableTelemetry,\n setTelemetryUser,\n track,\n type TrackProps,\n type TrackValue,\n} from \"./track.js\";\n\n/**\n * Dev-only browser log forwarding: mirrors console output and uncaught errors\n * to the dev server, which prints them into\n * `.forge/logs/<env>/frontend_<name>.log`. No-ops unless `dev: true`, and the\n * receiving endpoint exists only in a dev server — so a production bundle\n * neither posts nor has anywhere to post to.\n */\nexport {\n DEV_LOG_ENDPOINT,\n devLoggingInstalled,\n installDevLogging,\n uninstallDevLogging,\n type DevLoggingOptions,\n type DevLogPayload,\n} from \"./devlog.js\";\n"]}
@@ -49,5 +49,5 @@ export declare function retryInterceptor(cfg: RuntimeInterceptorConfig): Interce
49
49
  * retry owner (see the retry-ownership note at the top of this file).
50
50
  */
51
51
  export declare function buildRuntimeInterceptors(cfg?: RuntimeInterceptorConfig): Interceptor[];
52
- export { ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, } from "./errors.js";
52
+ export { codeName, ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, } from "./errors.js";
53
53
  export { freshTraceparent, injectTraceContext, setTraceSampled, traceIdFrom, TRACEPARENT_RE, TRACERESPONSE_HEADER, } from "./trace.js";
@@ -158,6 +158,6 @@ export function buildRuntimeInterceptors(cfg = {}) {
158
158
  // write a handler without the type; setTraceSampled is traceInterceptor's
159
159
  // only knob. A consumer of "@reliantlabs/forge-web-runtime/interceptors" must
160
160
  // never have to fall back to the React-typed barrel to complete the job.
161
- export { ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, } from "./errors.js";
161
+ export { codeName, ConnectClientError, FORGE_ERROR_REASON_HEADER, isRetryableCode, normalizeError, } from "./errors.js";
162
162
  export { freshTraceparent, injectTraceContext, setTraceSampled, traceIdFrom, TRACEPARENT_RE, TRACERESPONSE_HEADER, } from "./trace.js";
163
163
  //# sourceMappingURL=interceptors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"interceptors.js","sourceRoot":"","sources":["../src/interceptors.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,qEAAqE;AACrE,gFAAgF;AAChF,0EAA0E;AAC1E,wEAAwE;AACxE,2EAA2E;AAC3E,0EAA0E;AAC1E,4EAA4E;AAC5E,yEAAyE;AACzE,6DAA6D;AAC7D,+BAA+B;AAC/B,EAAE;AACF,uEAAuE;AACvE,mEAAmE;AACnE,2EAA2E;AAC3E,UAAU;AACV,EAAE;AACF,yDAAyD;AACzD,EAAE;AACF,4DAA4D;AAC5D,oDAAoD;AACpD,EAAE;AACF,sDAAsD;AACtD,6DAA6D;AAC7D,qEAAqE;AACrE,0EAA0E;AAC1E,wEAAwE;AACxE,wEAAwE;AACxE,2EAA2E;AA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;AAEzE,OAAO,EACL,kBAAkB,EAClB,yBAAyB,EACzB,eAAe,EACf,cAAc,GACf,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,cAAc,EACd,oBAAoB,GACrB,MAAM,YAAY,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// This module is also the package's SECOND ENTRY POINT, published as\n// \"@reliantlabs/forge-web-runtime/interceptors\". It is the DOM-free, React-free\n// half of the runtime: the transport layer and nothing else. Importing it\n// pulls in exactly ./errors and ./trace — no React, no @types/react, no\n// window/document. That matters for React Native, where Expo pins React 18\n// while the package's components are typed against React 19: a mobile app\n// importing the full barrel would typecheck the components it never renders\n// and fail. Everything re-exported at the bottom of this file is part of\n// this entry point's surface; keep it React-free (guarded by\n// interceptors-entry.test.ts).\n//\n// The Connect transport interceptor stack. This is the one place every\n// frontend→backend call flows through, composed once and handed to\n// createConnectTransport by the app's own connect module. Order (outermost\n// first):\n//\n// error-normalize → auth → brand headers → traceparent\n//\n// error-normalize is outermost so every caller sees a typed\n// ConnectClientError instead of a raw ConnectError.\n//\n// RETRY OWNERSHIP — read before adding a retry layer.\n// The single retry owner is the app's React Query client: it\n// structurally knows reads from writes, so it retries transient READ\n// failures and NEVER retries a mutation — no duplicate writes. Each React\n// Query retry re-runs the queryFn, which re-runs this whole interceptor\n// chain (fresh token + traceparent), so nothing is lost by not retrying\n// here. `retryInterceptor` below is therefore NOT in the default chain; it\n// stays exported (idempotency-gated) only for callers who use the raw\n// transport OUTSIDE React Query. Putting it back in the default chain would\n// stack two retry layers AND retry non-idempotent mutations — the bug this\n// split fixed.\nimport { MethodOptions_IdempotencyLevel } from \"@bufbuild/protobuf/wkt\";\n\nimport { ConnectClientError, normalizeError } from \"./errors.js\";\nimport { telemetryReady } from \"./telemetry-gate.js\";\nimport { injectTraceContext, traceIdFrom } from \"./trace.js\";\n\nimport type {\n Interceptor,\n UnaryRequest,\n StreamRequest,\n} from \"@connectrpc/connect\";\n\n/**\n * RuntimeInterceptorConfig is the seam the app wires its runtime dependencies\n * through. Everything is optional: an unconfigured chain still propagates\n * traceparent and normalizes errors.\n */\nexport interface RuntimeInterceptorConfig {\n /** Returns the current bearer token, or null when unauthenticated. */\n getToken?: () => Promise<string | null> | string | null;\n /** Returns the active brand, attached as the X-Brand header. */\n getBrand?: () => string | null | undefined;\n /** Invoked with the typed error on every failed RPC (telemetry sink). */\n onError?: (err: ConnectClientError) => void;\n /** Max transparent retries for retryable unary failures. Default 2. */\n maxRetries?: number;\n /** Base backoff in ms; grows exponentially with jitter. Default 200. */\n retryBaseMs?: number;\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/** Attaches the bearer token from the app's auth provider. */\nexport function authInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n return (next) => async (req) => {\n const token = cfg.getToken ? await cfg.getToken() : null;\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n return next(req);\n };\n}\n\n/** Attaches brand context headers when the app supplies them. */\nexport function headerInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n return (next) => async (req) => {\n const brand = cfg.getBrand?.();\n if (brand) {\n req.header.set(\"X-Brand\", brand);\n }\n return next(req);\n };\n}\n\n/**\n * Propagates a W3C traceparent so the backend (otelconnect + otelhttp) joins\n * the same distributed trace. Always emits a valid header — see trace.ts.\n *\n * While browser telemetry is still starting it waits (bounded; see\n * telemetry-gate.ts) so the call is made through the SDK's patched fetch and\n * its traceparent names a span the browser really exports.\n */\nexport function traceInterceptor(): Interceptor {\n return (next) => async (req) => {\n await telemetryReady();\n injectTraceContext(req.header);\n return next(req);\n };\n}\n\n/** Converts any thrown failure into a typed ConnectClientError. */\nexport function errorNormalizeInterceptor(\n cfg: RuntimeInterceptorConfig,\n): Interceptor {\n return (next) => async (req) => {\n try {\n return await next(req);\n } catch (err) {\n // traceInterceptor (innermost) has written the traceparent onto this\n // same request by now: the fallback when the server sent no\n // traceresponse.\n const normalized = normalizeError(\n err,\n traceIdFrom(req.header.get(\"traceparent\")),\n );\n cfg.onError?.(normalized);\n throw normalized;\n }\n };\n}\n\n/**\n * retryEligible reports whether a request is SAFE to retry transparently:\n * a no-side-effects / idempotent method (declared via proto\n * `idempotency_level`), or one carrying an explicit Idempotency-Key header.\n * A plain mutation (the default IDEMPOTENCY_UNKNOWN) is never retried, so a\n * transparent retry can't produce a duplicate write.\n */\nfunction retryEligible(req: UnaryRequest | StreamRequest): boolean {\n const level = req.method.idempotency;\n if (\n level === MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS ||\n level === MethodOptions_IdempotencyLevel.IDEMPOTENT\n ) {\n return true;\n }\n return req.header.has(\"Idempotency-Key\");\n}\n\n/**\n * Transparently retries retryable failures with exponential backoff +\n * jitter — for IDEMPOTENT requests ONLY (see retryEligible). NOT part of the\n * default chain: React Query owns retries (see the retry-ownership note at\n * the top of this file). Exported for callers using the raw transport\n * outside React Query. Streaming RPCs are never retried (a partially-\n * consumed stream can't be safely replayed).\n */\nexport function retryInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n const max = cfg.maxRetries ?? 2;\n const base = cfg.retryBaseMs ?? 200;\n return (next) => async (req) => {\n if (req.stream || !retryEligible(req)) {\n return next(req);\n }\n let attempt = 0;\n for (;;) {\n try {\n return await next(req);\n } catch (err) {\n const normalized =\n err instanceof ConnectClientError ? err : normalizeError(err);\n if (attempt >= max || !normalized.retryable) {\n throw normalized;\n }\n const backoff = base * 2 ** attempt + Math.random() * base;\n await sleep(backoff);\n attempt++;\n }\n }\n };\n}\n\n/**\n * buildRuntimeInterceptors composes the full stack in the correct order.\n * Pass the result to createConnectTransport's `interceptors` option.\n *\n * retryInterceptor is deliberately NOT included — React Query is the single\n * retry owner (see the retry-ownership note at the top of this file).\n */\nexport function buildRuntimeInterceptors(\n cfg: RuntimeInterceptorConfig = {},\n): Interceptor[] {\n return [\n errorNormalizeInterceptor(cfg),\n authInterceptor(cfg),\n headerInterceptor(cfg),\n traceInterceptor(),\n ];\n}\n\n// ── The rest of the transport-layer surface ──────────────────────────────\n//\n// These belong to this entry point because the interceptor stack's contract\n// is expressed in them: errorNormalizeInterceptor THROWS ConnectClientError\n// and RuntimeInterceptorConfig.onError RECEIVES one, so a consumer cannot\n// write a handler without the type; setTraceSampled is traceInterceptor's\n// only knob. A consumer of \"@reliantlabs/forge-web-runtime/interceptors\" must\n// never have to fall back to the React-typed barrel to complete the job.\n\nexport {\n ConnectClientError,\n FORGE_ERROR_REASON_HEADER,\n isRetryableCode,\n normalizeError,\n} from \"./errors.js\";\n\nexport {\n freshTraceparent,\n injectTraceContext,\n setTraceSampled,\n traceIdFrom,\n TRACEPARENT_RE,\n TRACERESPONSE_HEADER,\n} from \"./trace.js\";\n"]}
1
+ {"version":3,"file":"interceptors.js","sourceRoot":"","sources":["../src/interceptors.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,qEAAqE;AACrE,gFAAgF;AAChF,0EAA0E;AAC1E,wEAAwE;AACxE,2EAA2E;AAC3E,0EAA0E;AAC1E,4EAA4E;AAC5E,yEAAyE;AACzE,6DAA6D;AAC7D,+BAA+B;AAC/B,EAAE;AACF,uEAAuE;AACvE,mEAAmE;AACnE,2EAA2E;AAC3E,UAAU;AACV,EAAE;AACF,yDAAyD;AACzD,EAAE;AACF,4DAA4D;AAC5D,oDAAoD;AACpD,EAAE;AACF,sDAAsD;AACtD,6DAA6D;AAC7D,qEAAqE;AACrE,0EAA0E;AAC1E,wEAAwE;AACxE,wEAAwE;AACxE,2EAA2E;AAC3E,sEAAsE;AACtE,4EAA4E;AAC5E,2EAA2E;AAC3E,eAAe;AACf,OAAO,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAExE,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,C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ent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// This module is also the package's SECOND ENTRY POINT, published as\n// \"@reliantlabs/forge-web-runtime/interceptors\". It is the DOM-free, React-free\n// half of the runtime: the transport layer and nothing else. Importing it\n// pulls in exactly ./errors and ./trace — no React, no @types/react, no\n// window/document. That matters for React Native, where Expo pins React 18\n// while the package's components are typed against React 19: a mobile app\n// importing the full barrel would typecheck the components it never renders\n// and fail. Everything re-exported at the bottom of this file is part of\n// this entry point's surface; keep it React-free (guarded by\n// interceptors-entry.test.ts).\n//\n// The Connect transport interceptor stack. This is the one place every\n// frontend→backend call flows through, composed once and handed to\n// createConnectTransport by the app's own connect module. Order (outermost\n// first):\n//\n// error-normalize → auth → brand headers → traceparent\n//\n// error-normalize is outermost so every caller sees a typed\n// ConnectClientError instead of a raw ConnectError.\n//\n// RETRY OWNERSHIP — read before adding a retry layer.\n// The single retry owner is the app's React Query client: it\n// structurally knows reads from writes, so it retries transient READ\n// failures and NEVER retries a mutation — no duplicate writes. Each React\n// Query retry re-runs the queryFn, which re-runs this whole interceptor\n// chain (fresh token + traceparent), so nothing is lost by not retrying\n// here. `retryInterceptor` below is therefore NOT in the default chain; it\n// stays exported (idempotency-gated) only for callers who use the raw\n// transport OUTSIDE React Query. Putting it back in the default chain would\n// stack two retry layers AND retry non-idempotent mutations — the bug this\n// split fixed.\nimport { MethodOptions_IdempotencyLevel } from \"@bufbuild/protobuf/wkt\";\n\nimport { ConnectClientError, normalizeError } from \"./errors.js\";\nimport { telemetryReady } from \"./telemetry-gate.js\";\nimport { injectTraceContext, traceIdFrom } from \"./trace.js\";\n\nimport type {\n Interceptor,\n UnaryRequest,\n StreamRequest,\n} from \"@connectrpc/connect\";\n\n/**\n * RuntimeInterceptorConfig is the seam the app wires its runtime dependencies\n * through. Everything is optional: an unconfigured chain still propagates\n * traceparent and normalizes errors.\n */\nexport interface RuntimeInterceptorConfig {\n /** Returns the current bearer token, or null when unauthenticated. */\n getToken?: () => Promise<string | null> | string | null;\n /** Returns the active brand, attached as the X-Brand header. */\n getBrand?: () => string | null | undefined;\n /** Invoked with the typed error on every failed RPC (telemetry sink). */\n onError?: (err: ConnectClientError) => void;\n /** Max transparent retries for retryable unary failures. Default 2. */\n maxRetries?: number;\n /** Base backoff in ms; grows exponentially with jitter. Default 200. */\n retryBaseMs?: number;\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/** Attaches the bearer token from the app's auth provider. */\nexport function authInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n return (next) => async (req) => {\n const token = cfg.getToken ? await cfg.getToken() : null;\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n return next(req);\n };\n}\n\n/** Attaches brand context headers when the app supplies them. */\nexport function headerInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n return (next) => async (req) => {\n const brand = cfg.getBrand?.();\n if (brand) {\n req.header.set(\"X-Brand\", brand);\n }\n return next(req);\n };\n}\n\n/**\n * Propagates a W3C traceparent so the backend (otelconnect + otelhttp) joins\n * the same distributed trace. Always emits a valid header — see trace.ts.\n *\n * While browser telemetry is still starting it waits (bounded; see\n * telemetry-gate.ts) so the call is made through the SDK's patched fetch and\n * its traceparent names a span the browser really exports.\n */\nexport function traceInterceptor(): Interceptor {\n return (next) => async (req) => {\n await telemetryReady();\n injectTraceContext(req.header);\n return next(req);\n };\n}\n\n/** Converts any thrown failure into a typed ConnectClientError. */\nexport function errorNormalizeInterceptor(\n cfg: RuntimeInterceptorConfig,\n): Interceptor {\n return (next) => async (req) => {\n try {\n return await next(req);\n } catch (err) {\n // traceInterceptor (innermost) has written the traceparent onto this\n // same request by now: the fallback when the server sent no\n // traceresponse.\n const normalized = normalizeError(\n err,\n traceIdFrom(req.header.get(\"traceparent\")),\n );\n cfg.onError?.(normalized);\n throw normalized;\n }\n };\n}\n\n/**\n * retryEligible reports whether a request is SAFE to retry transparently:\n * a no-side-effects / idempotent method (declared via proto\n * `idempotency_level`), or one carrying an explicit Idempotency-Key header.\n * A plain mutation (the default IDEMPOTENCY_UNKNOWN) is never retried, so a\n * transparent retry can't produce a duplicate write.\n */\nfunction retryEligible(req: UnaryRequest | StreamRequest): boolean {\n const level = req.method.idempotency;\n if (\n level === MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS ||\n level === MethodOptions_IdempotencyLevel.IDEMPOTENT\n ) {\n return true;\n }\n return req.header.has(\"Idempotency-Key\");\n}\n\n/**\n * Transparently retries retryable failures with exponential backoff +\n * jitter — for IDEMPOTENT requests ONLY (see retryEligible). NOT part of the\n * default chain: React Query owns retries (see the retry-ownership note at\n * the top of this file). Exported for callers using the raw transport\n * outside React Query. Streaming RPCs are never retried (a partially-\n * consumed stream can't be safely replayed).\n */\nexport function retryInterceptor(cfg: RuntimeInterceptorConfig): Interceptor {\n const max = cfg.maxRetries ?? 2;\n const base = cfg.retryBaseMs ?? 200;\n return (next) => async (req) => {\n if (req.stream || !retryEligible(req)) {\n return next(req);\n }\n let attempt = 0;\n for (;;) {\n try {\n return await next(req);\n } catch (err) {\n const normalized =\n err instanceof ConnectClientError ? err : normalizeError(err);\n if (attempt >= max || !normalized.retryable) {\n throw normalized;\n }\n const backoff = base * 2 ** attempt + Math.random() * base;\n await sleep(backoff);\n attempt++;\n }\n }\n };\n}\n\n/**\n * buildRuntimeInterceptors composes the full stack in the correct order.\n * Pass the result to createConnectTransport's `interceptors` option.\n *\n * retryInterceptor is deliberately NOT included — React Query is the single\n * retry owner (see the retry-ownership note at the top of this file).\n */\nexport function buildRuntimeInterceptors(\n cfg: RuntimeInterceptorConfig = {},\n): Interceptor[] {\n return [\n errorNormalizeInterceptor(cfg),\n authInterceptor(cfg),\n headerInterceptor(cfg),\n traceInterceptor(),\n ];\n}\n\n// ── The rest of the transport-layer surface ──────────────────────────────\n//\n// These belong to this entry point because the interceptor stack's contract\n// is expressed in them: errorNormalizeInterceptor THROWS ConnectClientError\n// and RuntimeInterceptorConfig.onError RECEIVES one, so a consumer cannot\n// write a handler without the type; setTraceSampled is traceInterceptor's\n// only knob. A consumer of \"@reliantlabs/forge-web-runtime/interceptors\" must\n// never have to fall back to the React-typed barrel to complete the job.\n\nexport {\n codeName,\n ConnectClientError,\n FORGE_ERROR_REASON_HEADER,\n isRetryableCode,\n normalizeError,\n} from \"./errors.js\";\n\nexport {\n freshTraceparent,\n injectTraceContext,\n setTraceSampled,\n traceIdFrom,\n TRACEPARENT_RE,\n TRACERESPONSE_HEADER,\n} from \"./trace.js\";\n"]}
@@ -56,7 +56,7 @@ export type ServiceMutationHook<Schema extends DescMessage, Response> = (options
56
56
  * Query's default `Error`. That type is declared on the OPTIONS parameter
57
57
  * because React Query takes the result's error type from the same TError it
58
58
  * reads there, so `query.error` is a ConnectClientError at every call site
59
- * with nothing to pass. Typing it as `Error` hid `.reason`, `.code`, `.status`
59
+ * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`
60
60
  * and `.retryable`, and left `err.message.includes(...)` as the only
61
61
  * expression that compiled — the one thing the error contract forbids.
62
62
  */
@@ -79,7 +79,7 @@ export function serviceKeys(service) {
79
79
  * Query's default `Error`. That type is declared on the OPTIONS parameter
80
80
  * because React Query takes the result's error type from the same TError it
81
81
  * reads there, so `query.error` is a ConnectClientError at every call site
82
- * with nothing to pass. Typing it as `Error` hid `.reason`, `.code`, `.status`
82
+ * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`
83
83
  * and `.retryable`, and left `err.message.includes(...)` as the only
84
84
  * expression that compiled — the one thing the error contract forbids.
85
85
  */
@@ -1 +1 @@
1
- {"version":3,"file":"service-hooks.js","sourceRoot":"","sources":["../src/service-hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,yEAAyE;AACzE,gEAAgE;AAChE,EAAE;AACF,8EAA8E;AAC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CAC7B,MAA0D,EAC1D,IAA0D;IAE1D,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CACtB,QAAQ,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC;QACrB,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;QACxB,GAAG,OAAO;KACX,CAAC,CAAC;AACP,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,aAA8B,EAC9B,IAA0D;IAE1D,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAAC;YACjB,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — the\n// app-wide MutationCache in src/lib/query-client.ts is the single error-toast\n// chokepoint, and pages that render errors inline pass\n// `meta: { silenceErrorToast: true }`. It never defaults success-side UX\n// either: \"CreateOrder succeeded\" leaks RPC names into the UI, so the toast /\n// redirect / inline confirmation stays the call site's via options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use.\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: MessageInitShape<Schema>) => ServiceQueryKey;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: MessageInitShape<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method, requestKey(schema, req)] as const)\n : ([service, entityScope, method, requestKey(schema, req)] as const),\n };\n}\n\n/** A generated query hook: `useGetOrder(req, options?)`. */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n options?: Partial<UseQueryOptions<Response, ConnectClientError>>,\n) => UseQueryResult<Response, ConnectClientError>;\n\n/** A generated mutation hook: `useCreateOrder(options?)`. */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = (\n options?: Partial<\n UseMutationOptions<Response, ConnectClientError, MessageInitShape<Schema>>\n >,\n) => UseMutationResult<Response, ConnectClientError, MessageInitShape<Schema>>;\n\n/**\n * createQueryHook builds one useQuery wrapper.\n *\n * The signature it returns is the one call sites already use — `(req,\n * options?)`, with the error typed as ConnectClientError rather than React\n * Query's default `Error`. That type is declared on the OPTIONS parameter\n * because React Query takes the result's error type from the same TError it\n * reads there, so `query.error` is a ConnectClientError at every call site\n * with nothing to pass. Typing it as `Error` hid `.reason`, `.code`, `.status`\n * and `.retryable`, and left `err.message.includes(...)` as the only\n * expression that compiled — the one thing the error contract forbids.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceQueryHook<Schema, Response> {\n return (req, options) =>\n useQuery({\n queryKey: keyFor(req),\n queryFn: () => call(req),\n ...options,\n });\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return (options) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
1
+ {"version":3,"file":"service-hooks.js","sourceRoot":"","sources":["../src/service-hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,sEAAsE;AACtE,EAA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AW,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAW;KAC3E,CAAC;AACJ,CAAC;AAeD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,eAAe,CAC7B,MAA0D,EAC1D,IAA0D;IAE1D,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CACtB,QAAQ,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC;QACrB,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;QACxB,GAAG,OAAO;KACX,CAAC,CAAC;AACP,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,aAA8B,EAC9B,IAA0D;IAE1D,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAAC;YACjB,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — the\n// app-wide MutationCache in src/lib/query-client.ts is the single error-toast\n// chokepoint, and pages that render errors inline pass\n// `meta: { silenceErrorToast: true }`. It never defaults success-side UX\n// either: \"CreateOrder succeeded\" leaks RPC names into the UI, so the toast /\n// redirect / inline confirmation stays the call site's via options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use.\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: MessageInitShape<Schema>) => ServiceQueryKey;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: MessageInitShape<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method, requestKey(schema, req)] as const)\n : ([service, entityScope, method, requestKey(schema, req)] as const),\n };\n}\n\n/** A generated query hook: `useGetOrder(req, options?)`. */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n options?: Partial<UseQueryOptions<Response, ConnectClientError>>,\n) => UseQueryResult<Response, ConnectClientError>;\n\n/** A generated mutation hook: `useCreateOrder(options?)`. */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = (\n options?: Partial<\n UseMutationOptions<Response, ConnectClientError, MessageInitShape<Schema>>\n >,\n) => UseMutationResult<Response, ConnectClientError, MessageInitShape<Schema>>;\n\n/**\n * createQueryHook builds one useQuery wrapper.\n *\n * The signature it returns is the one call sites already use — `(req,\n * options?)`, with the error typed as ConnectClientError rather than React\n * Query's default `Error`. That type is declared on the OPTIONS parameter\n * because React Query takes the result's error type from the same TError it\n * reads there, so `query.error` is a ConnectClientError at every call site\n * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`\n * and `.retryable`, and left `err.message.includes(...)` as the only\n * expression that compiled — the one thing the error contract forbids.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceQueryHook<Schema, Response> {\n return (req, options) =>\n useQuery({\n queryKey: keyFor(req),\n queryFn: () => call(req),\n ...options,\n });\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return (options) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
package/dist/vite.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /**
3
+ * The environment variable `forge env up` sets on a frontend's dev server
4
+ * when the frontend's runtime config document was rendered outside its tree.
5
+ * Its value is an absolute path.
6
+ */
7
+ export declare const FORGE_RUNTIME_CONFIG_FILE_ENV = "FORGE_RUNTIME_CONFIG_FILE";
8
+ type NextFn = (err?: unknown) => void;
9
+ type Middleware = (req: IncomingMessage, res: ServerResponse, next: NextFn) => void;
10
+ /** The part of a Vite dev / preview server this plugin uses. */
11
+ export interface RuntimeConfigServer {
12
+ config: {
13
+ base: string;
14
+ logger: {
15
+ warn(msg: string): void;
16
+ };
17
+ };
18
+ middlewares: {
19
+ use(fn: Middleware): unknown;
20
+ };
21
+ watcher?: {
22
+ add(paths: string | readonly string[]): unknown;
23
+ on(event: "change", listener: (path: string) => void): unknown;
24
+ };
25
+ ws?: {
26
+ send(payload: {
27
+ type: "full-reload";
28
+ path?: string;
29
+ }): void;
30
+ };
31
+ }
32
+ export interface ForgeRuntimeConfigOptions {
33
+ /**
34
+ * The document to serve. Defaults to `process.env.FORGE_RUNTIME_CONFIG_FILE`
35
+ * as the dev server sees it. Empty or unset makes the plugin inert.
36
+ */
37
+ file?: string;
38
+ }
39
+ /** The plugin object; structurally a Vite `Plugin`. */
40
+ export interface ForgeRuntimeConfigPlugin {
41
+ name: string;
42
+ configureServer(server: RuntimeConfigServer): void;
43
+ configurePreviewServer(server: RuntimeConfigServer): void;
44
+ }
45
+ /**
46
+ * forgeRuntimeConfig serves `<base>config.js` from the file forge rendered
47
+ * for this frontend, when there is one. Add it to `plugins` in
48
+ * vite.config.ts:
49
+ *
50
+ * ```ts
51
+ * import { forgeRuntimeConfig } from "@reliantlabs/forge-web-runtime/vite";
52
+ * export default defineConfig({ plugins: [react(), forgeRuntimeConfig()] });
53
+ * ```
54
+ */
55
+ export declare function forgeRuntimeConfig(options?: ForgeRuntimeConfigOptions): ForgeRuntimeConfigPlugin;
56
+ export {};
package/dist/vite.js ADDED
@@ -0,0 +1,116 @@
1
+ // Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.
2
+ //
3
+ // forgeRuntimeConfig — a Vite plugin that serves the frontend's runtime
4
+ // config document (`config.js`, which sets `window.__FORGE_CONFIG__`) from a
5
+ // file forge rendered OUTSIDE the frontend's own tree.
6
+ //
7
+ // # Why
8
+ //
9
+ // A frontend normally carries its dev document at `public/config.js`, written
10
+ // by `forge generate` / `forge env up` in the project that owns the frontend.
11
+ // A frontend whose code lives in ANOTHER repository — a sibling checkout
12
+ // (`path: "../reliant/web"`) in dev, a source pin when building — has no
13
+ // directory forge may write into: putting one repo's rendered environment in
14
+ // another repo's working tree is a diff in someone else's `git status`. So the
15
+ // project that declares the environment renders the document to its own
16
+ // `.forge/runtime-config/<frontend>/config.js`, and `forge env up` hands the
17
+ // path to the frontend's dev server as FORGE_RUNTIME_CONFIG_FILE. This plugin
18
+ // is the dev server's half: it answers `<base>config.js` from that file.
19
+ //
20
+ // With the variable unset (the frontend's own repo runs its own dev server,
21
+ // or a build) the plugin does nothing, and `public/config.js` is served as
22
+ // before — so adding it to a vite.config.ts is safe in every mode.
23
+ //
24
+ // The file is read on EVERY request rather than once: `forge env up`
25
+ // re-renders it after identity and jobs converge, and a page reload must see
26
+ // that, not the value from when the dev server started. A change also sends
27
+ // the page a full reload, so an open tab picks it up without a click.
28
+ //
29
+ // Structural types only: this module imports nothing from `vite`, so the
30
+ // package takes no dependency on any Vite major. The plugin object is
31
+ // assignable to Vite's `Plugin` (vite.test.ts pins that).
32
+ import { readFile } from "node:fs/promises";
33
+ import { resolve } from "node:path";
34
+ /**
35
+ * The environment variable `forge env up` sets on a frontend's dev server
36
+ * when the frontend's runtime config document was rendered outside its tree.
37
+ * Its value is an absolute path.
38
+ */
39
+ export const FORGE_RUNTIME_CONFIG_FILE_ENV = "FORGE_RUNTIME_CONFIG_FILE";
40
+ /** The document's file name, which is also the path it is served at. */
41
+ const CONFIG_JS = "config.js";
42
+ /**
43
+ * configPath is the request path the document is served at under `base`.
44
+ * Vite normalizes a dev server's base to "/" or "/prefix/"; a relative base
45
+ * ("./", a build-only setting) is served from the root.
46
+ */
47
+ function configPath(base) {
48
+ const b = base.startsWith("/") ? base : "/";
49
+ return (b.endsWith("/") ? b : `${b}/`) + CONFIG_JS;
50
+ }
51
+ function requestPath(req) {
52
+ const url = req.url ?? "";
53
+ const q = url.search(/[?#]/);
54
+ return q < 0 ? url : url.slice(0, q);
55
+ }
56
+ /**
57
+ * forgeRuntimeConfig serves `<base>config.js` from the file forge rendered
58
+ * for this frontend, when there is one. Add it to `plugins` in
59
+ * vite.config.ts:
60
+ *
61
+ * ```ts
62
+ * import { forgeRuntimeConfig } from "@reliantlabs/forge-web-runtime/vite";
63
+ * export default defineConfig({ plugins: [react(), forgeRuntimeConfig()] });
64
+ * ```
65
+ */
66
+ export function forgeRuntimeConfig(options = {}) {
67
+ const raw = options.file ?? process.env[FORGE_RUNTIME_CONFIG_FILE_ENV] ?? "";
68
+ const file = raw.trim() === "" ? "" : resolve(raw.trim());
69
+ const install = (server, live) => {
70
+ if (file === "")
71
+ return;
72
+ const path = configPath(server.config.base);
73
+ server.middlewares.use((req, res, next) => {
74
+ if ((req.method !== "GET" && req.method !== "HEAD") ||
75
+ requestPath(req) !== path) {
76
+ next();
77
+ return;
78
+ }
79
+ readFile(file, "utf8").then((body) => {
80
+ res.statusCode = 200;
81
+ res.setHeader("Content-Type", "text/javascript; charset=utf-8");
82
+ // The document is per environment and re-rendered while the dev
83
+ // server runs; a cached copy is a stale environment.
84
+ res.setHeader("Cache-Control", "no-store");
85
+ res.end(req.method === "HEAD" ? undefined : body);
86
+ }, (err) => {
87
+ // Loud, not silent: the page will fall back to whatever
88
+ // public/config.js says (or to config_gen.ts's defaults), and the
89
+ // only clue is this line in the dev server's log.
90
+ server.config.logger.warn(`[forge-runtime-config] ${FORGE_RUNTIME_CONFIG_FILE_ENV}=${file} is unreadable ` +
91
+ `(${err instanceof Error ? err.message : String(err)}); ` +
92
+ `serving ${path} from the frontend's own tree instead. ` +
93
+ "Re-run `forge env up` in the project that declares this frontend.");
94
+ next();
95
+ });
96
+ });
97
+ if (live && server.watcher) {
98
+ server.watcher.add(file);
99
+ server.watcher.on("change", (changed) => {
100
+ if (resolve(changed) === file) {
101
+ server.ws?.send({ type: "full-reload", path: "*" });
102
+ }
103
+ });
104
+ }
105
+ };
106
+ return {
107
+ name: "forge-runtime-config",
108
+ configureServer(server) {
109
+ install(server, true);
110
+ },
111
+ configurePreviewServer(server) {
112
+ install(server, false);
113
+ },
114
+ };
115
+ }
116
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.js","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,wEAAwE;AACxE,6EAA6E;AAC7E,uDAAuD;AACvD,EAAE;AACF,QAAQ;AACR,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,yEAAyE;AACzE,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,wEAAwE;AACxE,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,mEAAmE;AACnE,EAAE;AACF,qEAAqE;AACrE,6EAA6E;AAC7E,4EAA4E;AAC5E,sEAAsE;AACtE,EAAE;AACF,yEAAyE;AACzE,sEAAsE;AACtE,0DAA0D;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;;;GAIG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,2BAA2B,CAAC;AAEzE,wEAAwE;AACxE,MAAM,SAAS,GAAG,WAAW,CAAC;AAsC9B;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAY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EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC;gBACtD,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC;IAEF,OAAO;QACL,IAAI,EAAE,sBAAsB;QAC5B,eAAe,CAAC,MAAM;YACpB,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACxB,CAAC;QACD,sBAAsB,CAAC,MAAM;YAC3B,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// forgeRuntimeConfig — a Vite plugin that serves the frontend's runtime\n// config document (`config.js`, which sets `window.__FORGE_CONFIG__`) from a\n// file forge rendered OUTSIDE the frontend's own tree.\n//\n// # Why\n//\n// A frontend normally carries its dev document at `public/config.js`, written\n// by `forge generate` / `forge env up` in the project that owns the frontend.\n// A frontend whose code lives in ANOTHER repository — a sibling checkout\n// (`path: \"../reliant/web\"`) in dev, a source pin when building — has no\n// directory forge may write into: putting one repo's rendered environment in\n// another repo's working tree is a diff in someone else's `git status`. So the\n// project that declares the environment renders the document to its own\n// `.forge/runtime-config/<frontend>/config.js`, and `forge env up` hands the\n// path to the frontend's dev server as FORGE_RUNTIME_CONFIG_FILE. This plugin\n// is the dev server's half: it answers `<base>config.js` from that file.\n//\n// With the variable unset (the frontend's own repo runs its own dev server,\n// or a build) the plugin does nothing, and `public/config.js` is served as\n// before — so adding it to a vite.config.ts is safe in every mode.\n//\n// The file is read on EVERY request rather than once: `forge env up`\n// re-renders it after identity and jobs converge, and a page reload must see\n// that, not the value from when the dev server started. A change also sends\n// the page a full reload, so an open tab picks it up without a click.\n//\n// Structural types only: this module imports nothing from `vite`, so the\n// package takes no dependency on any Vite major. The plugin object is\n// assignable to Vite's `Plugin` (vite.test.ts pins that).\nimport { readFile } from \"node:fs/promises\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { resolve } from \"node:path\";\n\n/**\n * The environment variable `forge env up` sets on a frontend's dev server\n * when the frontend's runtime config document was rendered outside its tree.\n * Its value is an absolute path.\n */\nexport const FORGE_RUNTIME_CONFIG_FILE_ENV = \"FORGE_RUNTIME_CONFIG_FILE\";\n\n/** The document's file name, which is also the path it is served at. */\nconst CONFIG_JS = \"config.js\";\n\ntype NextFn = (err?: unknown) => void;\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: NextFn,\n) => void;\n\n/** The part of a Vite dev / preview server this plugin uses. */\nexport interface RuntimeConfigServer {\n config: {\n base: string;\n logger: { warn(msg: string): void };\n };\n middlewares: { use(fn: Middleware): unknown };\n watcher?: {\n add(paths: string | readonly string[]): unknown;\n on(event: \"change\", listener: (path: string) => void): unknown;\n };\n ws?: { send(payload: { type: \"full-reload\"; path?: string }): void };\n}\n\nexport interface ForgeRuntimeConfigOptions {\n /**\n * The document to serve. Defaults to `process.env.FORGE_RUNTIME_CONFIG_FILE`\n * as the dev server sees it. Empty or unset makes the plugin inert.\n */\n file?: string;\n}\n\n/** The plugin object; structurally a Vite `Plugin`. */\nexport interface ForgeRuntimeConfigPlugin {\n name: string;\n configureServer(server: RuntimeConfigServer): void;\n configurePreviewServer(server: RuntimeConfigServer): void;\n}\n\n/**\n * configPath is the request path the document is served at under `base`.\n * Vite normalizes a dev server's base to \"/\" or \"/prefix/\"; a relative base\n * (\"./\", a build-only setting) is served from the root.\n */\nfunction configPath(base: string): string {\n const b = base.startsWith(\"/\") ? base : \"/\";\n return (b.endsWith(\"/\") ? b : `${b}/`) + CONFIG_JS;\n}\n\nfunction requestPath(req: IncomingMessage): string {\n const url = req.url ?? \"\";\n const q = url.search(/[?#]/);\n return q < 0 ? url : url.slice(0, q);\n}\n\n/**\n * forgeRuntimeConfig serves `<base>config.js` from the file forge rendered\n * for this frontend, when there is one. Add it to `plugins` in\n * vite.config.ts:\n *\n * ```ts\n * import { forgeRuntimeConfig } from \"@reliantlabs/forge-web-runtime/vite\";\n * export default defineConfig({ plugins: [react(), forgeRuntimeConfig()] });\n * ```\n */\nexport function forgeRuntimeConfig(\n options: ForgeRuntimeConfigOptions = {},\n): ForgeRuntimeConfigPlugin {\n const raw = options.file ?? process.env[FORGE_RUNTIME_CONFIG_FILE_ENV] ?? \"\";\n const file = raw.trim() === \"\" ? \"\" : resolve(raw.trim());\n\n const install = (server: RuntimeConfigServer, live: boolean): void => {\n if (file === \"\") return;\n const path = configPath(server.config.base);\n server.middlewares.use((req, res, next) => {\n if (\n (req.method !== \"GET\" && req.method !== \"HEAD\") ||\n requestPath(req) !== path\n ) {\n next();\n return;\n }\n readFile(file, \"utf8\").then(\n (body) => {\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"text/javascript; charset=utf-8\");\n // The document is per environment and re-rendered while the dev\n // server runs; a cached copy is a stale environment.\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(req.method === \"HEAD\" ? undefined : body);\n },\n (err: unknown) => {\n // Loud, not silent: the page will fall back to whatever\n // public/config.js says (or to config_gen.ts's defaults), and the\n // only clue is this line in the dev server's log.\n server.config.logger.warn(\n `[forge-runtime-config] ${FORGE_RUNTIME_CONFIG_FILE_ENV}=${file} is unreadable ` +\n `(${err instanceof Error ? err.message : String(err)}); ` +\n `serving ${path} from the frontend's own tree instead. ` +\n \"Re-run `forge env up` in the project that declares this frontend.\",\n );\n next();\n },\n );\n });\n if (live && server.watcher) {\n server.watcher.add(file);\n server.watcher.on(\"change\", (changed) => {\n if (resolve(changed) === file) {\n server.ws?.send({ type: \"full-reload\", path: \"*\" });\n }\n });\n }\n };\n\n return {\n name: \"forge-runtime-config\",\n configureServer(server) {\n install(server, true);\n },\n configurePreviewServer(server) {\n install(server, false);\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reliantlabs/forge-web-runtime",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "The forge frontend runtime: Connect interceptor stack, session, error boundary, toast queue, <Resource> container, W3C trace propagation and the HyperDX browser SDK wiring (errors, console, network, traces; replay off by default). The web twin of forge/pkg.",
5
5
  "license": "Apache-2.0",
6
6
  "//repository note": "REQUIRED for `npm publish --provenance`, not decoration. npm cross-checks this against the repository in the signed provenance statement and rejects the publish with a 422 if they disagree — an absent field reads as \"\" and fails that comparison. `directory` names the subdirectory this package lives in, so the provenance points at the real source. Omitting this is what made the first 0.3.1 publish fail AFTER the tarball had been signed and written to the sigstore transparency log.",
@@ -54,6 +54,10 @@
54
54
  "types": "./dist/telemetry.d.ts",
55
55
  "default": "./dist/telemetry.js"
56
56
  },
57
+ "./vite": {
58
+ "types": "./dist/vite.d.ts",
59
+ "default": "./dist/vite.js"
60
+ },
57
61
  "./package.json": "./package.json"
58
62
  },
59
63
  "scripts": {