@cms.ai/brand_brain 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1741 @@
1
+ //#region ../../node_modules/.pnpm/@orpc+shared@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/shared/dist/index.mjs
2
+ function resolveMaybeOptionalOptions(rest) {
3
+ return rest[0] ?? {};
4
+ }
5
+ function toArray(value) {
6
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
7
+ }
8
+ const ORPC_NAME = "orpc";
9
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
10
+ const ORPC_SHARED_PACKAGE_VERSION = "1.14.0";
11
+ var AbortError = class extends Error {
12
+ constructor(...rest) {
13
+ super(...rest);
14
+ this.name = "AbortError";
15
+ }
16
+ };
17
+ function once(fn) {
18
+ let cached;
19
+ return () => {
20
+ if (cached) return cached.result;
21
+ const result = fn();
22
+ cached = { result };
23
+ return result;
24
+ };
25
+ }
26
+ function sequential(fn) {
27
+ let lastOperationPromise = Promise.resolve();
28
+ return (...args) => {
29
+ return lastOperationPromise = lastOperationPromise.catch(() => {}).then(() => {
30
+ return fn(...args);
31
+ });
32
+ };
33
+ }
34
+ const SPAN_ERROR_STATUS = 2;
35
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
36
+ function getGlobalOtelConfig() {
37
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
38
+ }
39
+ function startSpan(name, options = {}, context) {
40
+ return (getGlobalOtelConfig()?.tracer)?.startSpan(name, options, context);
41
+ }
42
+ function setSpanError(span, error, options = {}) {
43
+ if (!span) return;
44
+ const exception = toOtelException(error);
45
+ span.recordException(exception);
46
+ if (!options.signal?.aborted || options.signal.reason !== error) span.setStatus({
47
+ code: SPAN_ERROR_STATUS,
48
+ message: exception.message
49
+ });
50
+ }
51
+ function toOtelException(error) {
52
+ if (error instanceof Error) {
53
+ const exception = {
54
+ message: error.message,
55
+ name: error.name,
56
+ stack: error.stack
57
+ };
58
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) exception.code = error.code;
59
+ return exception;
60
+ }
61
+ return { message: String(error) };
62
+ }
63
+ async function runWithSpan({ name, context, ...options }, fn) {
64
+ const tracer = getGlobalOtelConfig()?.tracer;
65
+ if (!tracer) return fn();
66
+ const callback = async (span) => {
67
+ try {
68
+ return await fn(span);
69
+ } catch (e) {
70
+ setSpanError(span, e, options);
71
+ throw e;
72
+ } finally {
73
+ span.end();
74
+ }
75
+ };
76
+ if (context) return tracer.startActiveSpan(name, options, context, callback);
77
+ else return tracer.startActiveSpan(name, options, callback);
78
+ }
79
+ async function runInSpanContext(span, fn) {
80
+ const otelConfig = getGlobalOtelConfig();
81
+ if (!span || !otelConfig) return fn();
82
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
83
+ return otelConfig.context.with(ctx, fn);
84
+ }
85
+ function isAsyncIteratorObject(maybe) {
86
+ if (!maybe || typeof maybe !== "object") return false;
87
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
88
+ }
89
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? Symbol.for("asyncDispose");
90
+ var AsyncIteratorClass = class {
91
+ #isDone = false;
92
+ #isExecuteComplete = false;
93
+ #cleanup;
94
+ #next;
95
+ constructor(next, cleanup) {
96
+ this.#cleanup = cleanup;
97
+ this.#next = sequential(async () => {
98
+ if (this.#isDone) return {
99
+ done: true,
100
+ value: void 0
101
+ };
102
+ try {
103
+ const result = await next();
104
+ if (result.done) this.#isDone = true;
105
+ return result;
106
+ } catch (err) {
107
+ this.#isDone = true;
108
+ throw err;
109
+ } finally {
110
+ if (this.#isDone && !this.#isExecuteComplete) {
111
+ this.#isExecuteComplete = true;
112
+ await this.#cleanup("next");
113
+ }
114
+ }
115
+ });
116
+ }
117
+ next() {
118
+ return this.#next();
119
+ }
120
+ async return(value) {
121
+ this.#isDone = true;
122
+ if (!this.#isExecuteComplete) {
123
+ this.#isExecuteComplete = true;
124
+ await this.#cleanup("return");
125
+ }
126
+ return {
127
+ done: true,
128
+ value
129
+ };
130
+ }
131
+ async throw(err) {
132
+ this.#isDone = true;
133
+ if (!this.#isExecuteComplete) {
134
+ this.#isExecuteComplete = true;
135
+ await this.#cleanup("throw");
136
+ }
137
+ throw err;
138
+ }
139
+ /**
140
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
141
+ */
142
+ async [asyncDisposeSymbol]() {
143
+ this.#isDone = true;
144
+ if (!this.#isExecuteComplete) {
145
+ this.#isExecuteComplete = true;
146
+ await this.#cleanup("dispose");
147
+ }
148
+ }
149
+ [Symbol.asyncIterator]() {
150
+ return this;
151
+ }
152
+ };
153
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
154
+ let span;
155
+ return new AsyncIteratorClass(async () => {
156
+ span ??= startSpan(name);
157
+ try {
158
+ const result = await runInSpanContext(span, () => iterator.next());
159
+ span?.addEvent(result.done ? "completed" : "yielded");
160
+ return result;
161
+ } catch (err) {
162
+ setSpanError(span, err, options);
163
+ throw err;
164
+ }
165
+ }, async (reason) => {
166
+ try {
167
+ if (reason !== "next") await runInSpanContext(span, () => iterator.return?.());
168
+ } catch (err) {
169
+ setSpanError(span, err, options);
170
+ throw err;
171
+ } finally {
172
+ span?.end();
173
+ }
174
+ });
175
+ }
176
+ function intercept(interceptors, options, main) {
177
+ const next = (options2, index) => {
178
+ const interceptor = interceptors[index];
179
+ if (!interceptor) return main(options2);
180
+ return interceptor({
181
+ ...options2,
182
+ next: (newOptions = options2) => next(newOptions, index + 1)
183
+ });
184
+ };
185
+ return next(options, 0);
186
+ }
187
+ function parseEmptyableJSON(text) {
188
+ if (!text) return;
189
+ return JSON.parse(text);
190
+ }
191
+ function stringifyJSON(value) {
192
+ return JSON.stringify(value);
193
+ }
194
+ function getConstructor(value) {
195
+ if (!isTypescriptObject(value)) return null;
196
+ return Object.getPrototypeOf(value)?.constructor;
197
+ }
198
+ function isObject(value) {
199
+ if (!value || typeof value !== "object") return false;
200
+ const proto = Object.getPrototypeOf(value);
201
+ return proto === Object.prototype || !proto || !proto.constructor;
202
+ }
203
+ function isTypescriptObject(value) {
204
+ return !!value && (typeof value === "object" || typeof value === "function");
205
+ }
206
+ function value(value2, ...args) {
207
+ if (typeof value2 === "function") return value2(...args);
208
+ return value2;
209
+ }
210
+ function preventNativeAwait(target) {
211
+ return new Proxy(target, { get(target2, prop, receiver) {
212
+ const value2 = Reflect.get(target2, prop, receiver);
213
+ if (prop !== "then" || typeof value2 !== "function") return value2;
214
+ return new Proxy(value2, { apply(targetFn, thisArg, args) {
215
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) return Reflect.apply(targetFn, thisArg, args);
216
+ let shouldOmit = true;
217
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, { get: (target3, prop2, receiver2) => {
218
+ if (shouldOmit && prop2 === "then") {
219
+ shouldOmit = false;
220
+ return;
221
+ }
222
+ return Reflect.get(target3, prop2, receiver2);
223
+ } })));
224
+ } });
225
+ } });
226
+ }
227
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
228
+ function isNativeFunction(fn) {
229
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
230
+ }
231
+ function tryDecodeURIComponent(value) {
232
+ try {
233
+ return decodeURIComponent(value);
234
+ } catch {
235
+ return value;
236
+ }
237
+ }
238
+ //#endregion
239
+ //#region ../../node_modules/.pnpm/@orpc+client@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/client/dist/shared/client.KWZYf6QD.mjs
240
+ const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
241
+ const ORPC_CLIENT_PACKAGE_VERSION = "1.14.0";
242
+ const COMMON_ORPC_ERROR_DEFS = {
243
+ BAD_REQUEST: {
244
+ status: 400,
245
+ message: "Bad Request"
246
+ },
247
+ UNAUTHORIZED: {
248
+ status: 401,
249
+ message: "Unauthorized"
250
+ },
251
+ FORBIDDEN: {
252
+ status: 403,
253
+ message: "Forbidden"
254
+ },
255
+ NOT_FOUND: {
256
+ status: 404,
257
+ message: "Not Found"
258
+ },
259
+ METHOD_NOT_SUPPORTED: {
260
+ status: 405,
261
+ message: "Method Not Supported"
262
+ },
263
+ NOT_ACCEPTABLE: {
264
+ status: 406,
265
+ message: "Not Acceptable"
266
+ },
267
+ TIMEOUT: {
268
+ status: 408,
269
+ message: "Request Timeout"
270
+ },
271
+ CONFLICT: {
272
+ status: 409,
273
+ message: "Conflict"
274
+ },
275
+ PRECONDITION_FAILED: {
276
+ status: 412,
277
+ message: "Precondition Failed"
278
+ },
279
+ PAYLOAD_TOO_LARGE: {
280
+ status: 413,
281
+ message: "Payload Too Large"
282
+ },
283
+ UNSUPPORTED_MEDIA_TYPE: {
284
+ status: 415,
285
+ message: "Unsupported Media Type"
286
+ },
287
+ UNPROCESSABLE_CONTENT: {
288
+ status: 422,
289
+ message: "Unprocessable Content"
290
+ },
291
+ TOO_MANY_REQUESTS: {
292
+ status: 429,
293
+ message: "Too Many Requests"
294
+ },
295
+ CLIENT_CLOSED_REQUEST: {
296
+ status: 499,
297
+ message: "Client Closed Request"
298
+ },
299
+ INTERNAL_SERVER_ERROR: {
300
+ status: 500,
301
+ message: "Internal Server Error"
302
+ },
303
+ NOT_IMPLEMENTED: {
304
+ status: 501,
305
+ message: "Not Implemented"
306
+ },
307
+ BAD_GATEWAY: {
308
+ status: 502,
309
+ message: "Bad Gateway"
310
+ },
311
+ SERVICE_UNAVAILABLE: {
312
+ status: 503,
313
+ message: "Service Unavailable"
314
+ },
315
+ GATEWAY_TIMEOUT: {
316
+ status: 504,
317
+ message: "Gateway Timeout"
318
+ }
319
+ };
320
+ function fallbackORPCErrorStatus(code, status) {
321
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
322
+ }
323
+ function fallbackORPCErrorMessage(code, message) {
324
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
325
+ }
326
+ const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
327
+ globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet();
328
+ const globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
329
+ var ORPCError = class extends Error {
330
+ defined;
331
+ code;
332
+ status;
333
+ data;
334
+ constructor(code, ...rest) {
335
+ const options = resolveMaybeOptionalOptions(rest);
336
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) throw new Error("[ORPCError] Invalid error status code.");
337
+ const message = fallbackORPCErrorMessage(code, options.message);
338
+ super(message, options);
339
+ this.code = code;
340
+ this.status = fallbackORPCErrorStatus(code, options.status);
341
+ this.defined = options.defined ?? false;
342
+ this.data = options.data;
343
+ }
344
+ toJSON() {
345
+ return {
346
+ defined: this.defined,
347
+ code: this.code,
348
+ status: this.status,
349
+ message: this.message,
350
+ data: this.data
351
+ };
352
+ }
353
+ /**
354
+ * Workaround for Next.js where different contexts use separate
355
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
356
+ * `instanceof` checks across contexts.
357
+ *
358
+ * This is particularly problematic with "Optimized SSR", where orpc-client
359
+ * executes in one context but is invoked from another. When an error is thrown
360
+ * in the execution context, `instanceof ORPCError` checks fail in the
361
+ * invocation context due to separate class constructors.
362
+ *
363
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
364
+ */
365
+ static [Symbol.hasInstance](instance) {
366
+ if (globalORPCErrorConstructors.has(this)) {
367
+ const constructor = getConstructor(instance);
368
+ if (constructor && globalORPCErrorConstructors.has(constructor)) return true;
369
+ }
370
+ return super[Symbol.hasInstance](instance);
371
+ }
372
+ };
373
+ globalORPCErrorConstructors.add(ORPCError);
374
+ function toORPCError(error) {
375
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
376
+ message: "Internal server error",
377
+ cause: error
378
+ });
379
+ }
380
+ function isORPCErrorStatus(status) {
381
+ return status < 200 || status >= 400;
382
+ }
383
+ function isORPCErrorJson(json) {
384
+ if (!isObject(json)) return false;
385
+ const validKeys = [
386
+ "defined",
387
+ "code",
388
+ "status",
389
+ "message",
390
+ "data"
391
+ ];
392
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) return false;
393
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
394
+ }
395
+ function createORPCErrorFromJson(json, options = {}) {
396
+ return new ORPCError(json.code, {
397
+ ...options,
398
+ ...json
399
+ });
400
+ }
401
+ //#endregion
402
+ //#region ../../node_modules/.pnpm/@orpc+standard-server@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/standard-server/dist/index.mjs
403
+ var EventEncoderError = class extends TypeError {};
404
+ var EventDecoderError = class extends TypeError {};
405
+ var ErrorEvent = class extends Error {
406
+ data;
407
+ constructor(options) {
408
+ super(options?.message ?? "An error event was received", options);
409
+ this.data = options?.data;
410
+ }
411
+ };
412
+ function decodeEventMessage(encoded) {
413
+ const lines = encoded.replace(/\n+$/, "").split(/\n/);
414
+ const message = {
415
+ data: void 0,
416
+ event: void 0,
417
+ id: void 0,
418
+ retry: void 0,
419
+ comments: []
420
+ };
421
+ for (const line of lines) {
422
+ const index = line.indexOf(":");
423
+ const key = index === -1 ? line : line.slice(0, index);
424
+ const value = index === -1 ? "" : line.slice(index + 1).replace(/^\s/, "");
425
+ if (index === 0) message.comments.push(value);
426
+ else if (key === "data") {
427
+ message.data ??= "";
428
+ message.data += `${value}
429
+ `;
430
+ } else if (key === "event") message.event = value;
431
+ else if (key === "id") message.id = value;
432
+ else if (key === "retry") {
433
+ const maybeInteger = Number.parseInt(value);
434
+ if (Number.isInteger(maybeInteger) && maybeInteger >= 0 && maybeInteger.toString() === value) message.retry = maybeInteger;
435
+ }
436
+ }
437
+ message.data = message.data?.replace(/\n$/, "");
438
+ return message;
439
+ }
440
+ var EventDecoder = class {
441
+ constructor(options = {}) {
442
+ this.options = options;
443
+ }
444
+ incomplete = "";
445
+ feed(chunk) {
446
+ this.incomplete += chunk;
447
+ const lastCompleteIndex = this.incomplete.lastIndexOf("\n\n");
448
+ if (lastCompleteIndex === -1) return;
449
+ const completes = this.incomplete.slice(0, lastCompleteIndex).split(/\n\n/);
450
+ this.incomplete = this.incomplete.slice(lastCompleteIndex + 2);
451
+ for (const encoded of completes) {
452
+ const message = decodeEventMessage(`${encoded}
453
+
454
+ `);
455
+ if (this.options.onEvent) this.options.onEvent(message);
456
+ }
457
+ }
458
+ end() {
459
+ if (this.incomplete) throw new EventDecoderError("Event Iterator ended before complete");
460
+ }
461
+ };
462
+ var EventDecoderStream = class extends TransformStream {
463
+ constructor() {
464
+ let decoder;
465
+ super({
466
+ start(controller) {
467
+ decoder = new EventDecoder({ onEvent: (event) => {
468
+ controller.enqueue(event);
469
+ } });
470
+ },
471
+ transform(chunk) {
472
+ decoder.feed(chunk);
473
+ },
474
+ flush() {
475
+ decoder.end();
476
+ }
477
+ });
478
+ }
479
+ };
480
+ function assertEventId(id) {
481
+ if (id.includes("\n")) throw new EventEncoderError("Event's id must not contain a newline character");
482
+ }
483
+ function assertEventName(event) {
484
+ if (event.includes("\n")) throw new EventEncoderError("Event's event must not contain a newline character");
485
+ }
486
+ function assertEventRetry(retry) {
487
+ if (!Number.isInteger(retry) || retry < 0) throw new EventEncoderError("Event's retry must be a integer and >= 0");
488
+ }
489
+ function assertEventComment(comment) {
490
+ if (comment.includes("\n")) throw new EventEncoderError("Event's comment must not contain a newline character");
491
+ }
492
+ function encodeEventData(data) {
493
+ const lines = data?.split(/\n/) ?? [];
494
+ let output = "";
495
+ for (const line of lines) output += `data: ${line}
496
+ `;
497
+ return output;
498
+ }
499
+ function encodeEventComments(comments) {
500
+ let output = "";
501
+ for (const comment of comments ?? []) {
502
+ assertEventComment(comment);
503
+ output += `: ${comment}
504
+ `;
505
+ }
506
+ return output;
507
+ }
508
+ function encodeEventMessage(message) {
509
+ let output = "";
510
+ output += encodeEventComments(message.comments);
511
+ if (message.event !== void 0) {
512
+ assertEventName(message.event);
513
+ output += `event: ${message.event}
514
+ `;
515
+ }
516
+ if (message.retry !== void 0) {
517
+ assertEventRetry(message.retry);
518
+ output += `retry: ${message.retry}
519
+ `;
520
+ }
521
+ if (message.id !== void 0) {
522
+ assertEventId(message.id);
523
+ output += `id: ${message.id}
524
+ `;
525
+ }
526
+ output += encodeEventData(message.data);
527
+ output += "\n";
528
+ return output;
529
+ }
530
+ const EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
531
+ function withEventMeta(container, meta) {
532
+ if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) return container;
533
+ if (meta.id !== void 0) assertEventId(meta.id);
534
+ if (meta.retry !== void 0) assertEventRetry(meta.retry);
535
+ if (meta.comments !== void 0) for (const comment of meta.comments) assertEventComment(comment);
536
+ return new Proxy(container, { get(target, prop, receiver) {
537
+ if (prop === EVENT_SOURCE_META_SYMBOL) return meta;
538
+ return Reflect.get(target, prop, receiver);
539
+ } });
540
+ }
541
+ function getEventMeta(container) {
542
+ return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
543
+ }
544
+ function generateContentDisposition(filename, disposition = "inline") {
545
+ return `${disposition}; filename="${filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "\\\"")}"; filename*=utf-8''${encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)))}`;
546
+ }
547
+ function getFilenameFromContentDisposition(contentDisposition) {
548
+ const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
549
+ if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") return tryDecodeURIComponent(encodedFilenameStarMatch[2]);
550
+ const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
551
+ if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") return encodedFilenameMatch[1].replace(/\\"/g, "\"");
552
+ }
553
+ function mergeStandardHeaders(a, b) {
554
+ const merged = { ...a };
555
+ for (const key in b) if (Array.isArray(b[key])) merged[key] = [...toArray(merged[key]), ...b[key]];
556
+ else if (b[key] !== void 0) if (Array.isArray(merged[key])) merged[key] = [...merged[key], b[key]];
557
+ else if (merged[key] !== void 0) merged[key] = [merged[key], b[key]];
558
+ else merged[key] = b[key];
559
+ return merged;
560
+ }
561
+ //#endregion
562
+ //#region ../../node_modules/.pnpm/@orpc+client@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs
563
+ function mapEventIterator(iterator, maps) {
564
+ const mapError = async (error) => {
565
+ let mappedError = await maps.error(error);
566
+ if (mappedError !== error) {
567
+ const meta = getEventMeta(error);
568
+ if (meta && isTypescriptObject(mappedError)) mappedError = withEventMeta(mappedError, meta);
569
+ }
570
+ return mappedError;
571
+ };
572
+ return new AsyncIteratorClass(async () => {
573
+ const { done, value } = await (async () => {
574
+ try {
575
+ return await iterator.next();
576
+ } catch (error) {
577
+ throw await mapError(error);
578
+ }
579
+ })();
580
+ let mappedValue = await maps.value(value, done);
581
+ if (mappedValue !== value) {
582
+ const meta = getEventMeta(value);
583
+ if (meta && isTypescriptObject(mappedValue)) mappedValue = withEventMeta(mappedValue, meta);
584
+ }
585
+ return {
586
+ done,
587
+ value: mappedValue
588
+ };
589
+ }, async () => {
590
+ try {
591
+ await iterator.return?.();
592
+ } catch (error) {
593
+ throw await mapError(error);
594
+ }
595
+ });
596
+ }
597
+ //#endregion
598
+ //#region ../../node_modules/.pnpm/@orpc+client@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/client/dist/index.mjs
599
+ function resolveFriendlyClientOptions(options) {
600
+ return {
601
+ ...options,
602
+ context: options.context ?? {}
603
+ };
604
+ }
605
+ function createORPCClient(link, options = {}) {
606
+ const path = options.path ?? [];
607
+ const procedureClient = async (...[input, options2 = {}]) => {
608
+ return await link.call(path, input, resolveFriendlyClientOptions(options2));
609
+ };
610
+ return preventNativeAwait(new Proxy(procedureClient, { get(target, key) {
611
+ if (typeof key !== "string") return Reflect.get(target, key);
612
+ return createORPCClient(link, {
613
+ ...options,
614
+ path: [...path, key]
615
+ });
616
+ } }));
617
+ }
618
+ //#endregion
619
+ //#region ../../node_modules/.pnpm/@orpc+standard-server-fetch@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/standard-server-fetch/dist/index.mjs
620
+ function toEventIterator(stream, options = {}) {
621
+ const reader = (stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream()))?.getReader();
622
+ let span;
623
+ let isCancelled = false;
624
+ return new AsyncIteratorClass(async () => {
625
+ span ??= startSpan("consume_event_iterator_stream");
626
+ try {
627
+ while (true) {
628
+ if (reader === void 0) return {
629
+ done: true,
630
+ value: void 0
631
+ };
632
+ const { done, value } = await runInSpanContext(span, () => reader.read());
633
+ if (done) {
634
+ if (isCancelled) throw new AbortError("Stream was cancelled");
635
+ return {
636
+ done: true,
637
+ value: void 0
638
+ };
639
+ }
640
+ switch (value.event) {
641
+ case "message": {
642
+ let message = parseEmptyableJSON(value.data);
643
+ if (isTypescriptObject(message)) message = withEventMeta(message, value);
644
+ span?.addEvent("message");
645
+ return {
646
+ done: false,
647
+ value: message
648
+ };
649
+ }
650
+ case "error": {
651
+ let error = new ErrorEvent({ data: parseEmptyableJSON(value.data) });
652
+ error = withEventMeta(error, value);
653
+ span?.addEvent("error");
654
+ throw error;
655
+ }
656
+ case "done": {
657
+ let done2 = parseEmptyableJSON(value.data);
658
+ if (isTypescriptObject(done2)) done2 = withEventMeta(done2, value);
659
+ span?.addEvent("done");
660
+ return {
661
+ done: true,
662
+ value: done2
663
+ };
664
+ }
665
+ default: span?.addEvent("maybe_keepalive");
666
+ }
667
+ }
668
+ } catch (e) {
669
+ if (!(e instanceof ErrorEvent)) setSpanError(span, e, options);
670
+ throw e;
671
+ }
672
+ }, async (reason) => {
673
+ try {
674
+ if (reason !== "next") {
675
+ isCancelled = true;
676
+ span?.addEvent("cancelled");
677
+ }
678
+ await runInSpanContext(span, () => reader?.cancel());
679
+ } catch (e) {
680
+ setSpanError(span, e, options);
681
+ throw e;
682
+ } finally {
683
+ span?.end();
684
+ }
685
+ });
686
+ }
687
+ function toEventStream(iterator, options = {}) {
688
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
689
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
690
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
691
+ const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
692
+ const initialComment = options.eventIteratorInitialComment ?? "";
693
+ let cancelled = false;
694
+ let timeout;
695
+ let span;
696
+ return new ReadableStream({
697
+ start(controller) {
698
+ span = startSpan("stream_event_iterator");
699
+ if (initialCommentEnabled) controller.enqueue(encodeEventMessage({ comments: [initialComment] }));
700
+ },
701
+ async pull(controller) {
702
+ try {
703
+ if (keepAliveEnabled) timeout = setInterval(() => {
704
+ controller.enqueue(encodeEventMessage({ comments: [keepAliveComment] }));
705
+ span?.addEvent("keepalive");
706
+ }, keepAliveInterval);
707
+ const value = await runInSpanContext(span, () => iterator.next());
708
+ clearInterval(timeout);
709
+ if (cancelled) return;
710
+ const meta = getEventMeta(value.value);
711
+ if (!value.done || value.value !== void 0 || meta !== void 0) {
712
+ const event = value.done ? "done" : "message";
713
+ controller.enqueue(encodeEventMessage({
714
+ ...meta,
715
+ event,
716
+ data: stringifyJSON(value.value)
717
+ }));
718
+ span?.addEvent(event);
719
+ }
720
+ if (value.done) {
721
+ controller.close();
722
+ span?.end();
723
+ }
724
+ } catch (err) {
725
+ clearInterval(timeout);
726
+ if (cancelled) return;
727
+ if (err instanceof ErrorEvent) {
728
+ controller.enqueue(encodeEventMessage({
729
+ ...getEventMeta(err),
730
+ event: "error",
731
+ data: stringifyJSON(err.data)
732
+ }));
733
+ span?.addEvent("error");
734
+ controller.close();
735
+ } else {
736
+ setSpanError(span, err);
737
+ controller.error(err);
738
+ }
739
+ span?.end();
740
+ }
741
+ },
742
+ async cancel() {
743
+ try {
744
+ cancelled = true;
745
+ clearInterval(timeout);
746
+ span?.addEvent("cancelled");
747
+ await runInSpanContext(span, () => iterator.return?.());
748
+ } catch (e) {
749
+ setSpanError(span, e);
750
+ throw e;
751
+ } finally {
752
+ span?.end();
753
+ }
754
+ }
755
+ }).pipeThrough(new TextEncoderStream());
756
+ }
757
+ function toStandardBody(re, options = {}) {
758
+ return runWithSpan({
759
+ name: "parse_standard_body",
760
+ signal: options.signal
761
+ }, async () => {
762
+ const contentDisposition = re.headers.get("content-disposition");
763
+ if (typeof contentDisposition === "string") {
764
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
765
+ const blob2 = await re.blob();
766
+ return new File([blob2], fileName, { type: blob2.type });
767
+ }
768
+ const contentType = re.headers.get("content-type");
769
+ if (!contentType || contentType.startsWith("application/json")) return parseEmptyableJSON(await re.text());
770
+ if (contentType.startsWith("multipart/form-data")) return await re.formData();
771
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
772
+ const text = await re.text();
773
+ return new URLSearchParams(text);
774
+ }
775
+ if (contentType.startsWith("text/event-stream")) return toEventIterator(re.body, options);
776
+ if (contentType.startsWith("text/plain")) return await re.text();
777
+ const blob = await re.blob();
778
+ return new File([blob], "blob", { type: blob.type });
779
+ });
780
+ }
781
+ function toFetchBody(body, headers, options = {}) {
782
+ if (body instanceof ReadableStream) return body;
783
+ const currentContentDisposition = headers.get("content-disposition");
784
+ headers.delete("content-type");
785
+ headers.delete("content-disposition");
786
+ if (body === void 0) return;
787
+ if (body instanceof Blob) {
788
+ headers.set("content-type", body.type);
789
+ headers.set("content-length", body.size.toString());
790
+ headers.set("content-disposition", currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob"));
791
+ return body;
792
+ }
793
+ if (body instanceof FormData) return body;
794
+ if (body instanceof URLSearchParams) return body;
795
+ if (isAsyncIteratorObject(body)) {
796
+ headers.set("content-type", "text/event-stream");
797
+ return toEventStream(body, options);
798
+ }
799
+ headers.set("content-type", "application/json");
800
+ return stringifyJSON(body);
801
+ }
802
+ function toStandardHeaders$1(headers, standardHeaders = {}) {
803
+ headers.forEach((value, key) => {
804
+ if (Array.isArray(standardHeaders[key])) standardHeaders[key].push(value);
805
+ else if (standardHeaders[key] !== void 0) standardHeaders[key] = [standardHeaders[key], value];
806
+ else standardHeaders[key] = value;
807
+ });
808
+ return standardHeaders;
809
+ }
810
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
811
+ for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
812
+ else if (value !== void 0) fetchHeaders.append(key, value);
813
+ return fetchHeaders;
814
+ }
815
+ function toFetchRequest(request, options = {}) {
816
+ const headers = toFetchHeaders(request.headers);
817
+ const body = toFetchBody(request.body, headers, options);
818
+ return new Request(request.url, {
819
+ signal: request.signal,
820
+ method: request.method,
821
+ headers,
822
+ body
823
+ });
824
+ }
825
+ function toStandardLazyResponse(response, options = {}) {
826
+ return {
827
+ body: once(() => toStandardBody(response, options)),
828
+ status: response.status,
829
+ get headers() {
830
+ const headers = toStandardHeaders$1(response.headers);
831
+ Object.defineProperty(this, "headers", {
832
+ value: headers,
833
+ writable: true
834
+ });
835
+ return headers;
836
+ },
837
+ set headers(value) {
838
+ Object.defineProperty(this, "headers", {
839
+ value,
840
+ writable: true
841
+ });
842
+ }
843
+ };
844
+ }
845
+ //#endregion
846
+ //#region ../../node_modules/.pnpm/@orpc+client@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/client/dist/shared/client.DrB9nq_G.mjs
847
+ var CompositeStandardLinkPlugin = class {
848
+ plugins;
849
+ constructor(plugins = []) {
850
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
851
+ }
852
+ init(options) {
853
+ for (const plugin of this.plugins) plugin.init?.(options);
854
+ }
855
+ };
856
+ var StandardLink = class {
857
+ constructor(codec, sender, options = {}) {
858
+ this.codec = codec;
859
+ this.sender = sender;
860
+ new CompositeStandardLinkPlugin(options.plugins).init(options);
861
+ this.interceptors = toArray(options.interceptors);
862
+ this.clientInterceptors = toArray(options.clientInterceptors);
863
+ }
864
+ interceptors;
865
+ clientInterceptors;
866
+ call(path, input, options) {
867
+ return runWithSpan({
868
+ name: `${ORPC_NAME}.${path.join("/")}`,
869
+ signal: options.signal
870
+ }, (span) => {
871
+ span?.setAttribute("rpc.system", ORPC_NAME);
872
+ span?.setAttribute("rpc.method", path.join("."));
873
+ if (isAsyncIteratorObject(input)) input = asyncIteratorWithSpan({
874
+ name: "consume_event_iterator_input",
875
+ signal: options.signal
876
+ }, input);
877
+ return intercept(this.interceptors, {
878
+ ...options,
879
+ path,
880
+ input
881
+ }, async ({ path: path2, input: input2, ...options2 }) => {
882
+ const otelConfig = getGlobalOtelConfig();
883
+ let otelContext;
884
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
885
+ if (currentSpan && otelConfig) otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
886
+ const request = await runWithSpan({
887
+ name: "encode_request",
888
+ context: otelContext
889
+ }, () => this.codec.encode(path2, input2, options2));
890
+ const response = await intercept(this.clientInterceptors, {
891
+ ...options2,
892
+ input: input2,
893
+ path: path2,
894
+ request
895
+ }, ({ input: input3, path: path3, request: request2, ...options3 }) => {
896
+ return runWithSpan({
897
+ name: "send_request",
898
+ signal: options3.signal,
899
+ context: otelContext
900
+ }, () => this.sender.call(request2, options3, path3, input3));
901
+ });
902
+ const output = await runWithSpan({
903
+ name: "decode_response",
904
+ context: otelContext
905
+ }, () => this.codec.decode(response, options2, path2, input2));
906
+ if (isAsyncIteratorObject(output)) return asyncIteratorWithSpan({
907
+ name: "consume_event_iterator_output",
908
+ signal: options2.signal
909
+ }, output);
910
+ return output;
911
+ });
912
+ });
913
+ }
914
+ };
915
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
916
+ BIGINT: 0,
917
+ DATE: 1,
918
+ NAN: 2,
919
+ UNDEFINED: 3,
920
+ URL: 4,
921
+ REGEXP: 5,
922
+ SET: 6,
923
+ MAP: 7
924
+ };
925
+ var StandardRPCJsonSerializer = class {
926
+ customSerializers;
927
+ constructor(options = {}) {
928
+ this.customSerializers = options.customJsonSerializers ?? [];
929
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) throw new Error("Custom serializer type must be unique.");
930
+ }
931
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
932
+ for (const custom of this.customSerializers) if (custom.condition(data)) {
933
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
934
+ meta.push([custom.type, ...segments]);
935
+ return result;
936
+ }
937
+ if (data instanceof Blob) {
938
+ maps.push(segments);
939
+ blobs.push(data);
940
+ return [
941
+ data,
942
+ meta,
943
+ maps,
944
+ blobs
945
+ ];
946
+ }
947
+ if (typeof data === "bigint") {
948
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
949
+ return [
950
+ data.toString(),
951
+ meta,
952
+ maps,
953
+ blobs
954
+ ];
955
+ }
956
+ if (data instanceof Date) {
957
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
958
+ if (Number.isNaN(data.getTime())) return [
959
+ null,
960
+ meta,
961
+ maps,
962
+ blobs
963
+ ];
964
+ return [
965
+ data.toISOString(),
966
+ meta,
967
+ maps,
968
+ blobs
969
+ ];
970
+ }
971
+ if (Number.isNaN(data)) {
972
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
973
+ return [
974
+ null,
975
+ meta,
976
+ maps,
977
+ blobs
978
+ ];
979
+ }
980
+ if (data instanceof URL) {
981
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
982
+ return [
983
+ data.toString(),
984
+ meta,
985
+ maps,
986
+ blobs
987
+ ];
988
+ }
989
+ if (data instanceof RegExp) {
990
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
991
+ return [
992
+ data.toString(),
993
+ meta,
994
+ maps,
995
+ blobs
996
+ ];
997
+ }
998
+ if (data instanceof Set) {
999
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
1000
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
1001
+ return result;
1002
+ }
1003
+ if (data instanceof Map) {
1004
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
1005
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
1006
+ return result;
1007
+ }
1008
+ if (Array.isArray(data)) return [
1009
+ data.map((v, i) => {
1010
+ if (v === void 0) {
1011
+ meta.push([
1012
+ STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED,
1013
+ ...segments,
1014
+ i
1015
+ ]);
1016
+ return null;
1017
+ }
1018
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
1019
+ }),
1020
+ meta,
1021
+ maps,
1022
+ blobs
1023
+ ];
1024
+ if (isObject(data)) {
1025
+ const json = {};
1026
+ for (const k in data) {
1027
+ if (k === "toJSON" && typeof data[k] === "function") continue;
1028
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
1029
+ }
1030
+ return [
1031
+ json,
1032
+ meta,
1033
+ maps,
1034
+ blobs
1035
+ ];
1036
+ }
1037
+ return [
1038
+ data,
1039
+ meta,
1040
+ maps,
1041
+ blobs
1042
+ ];
1043
+ }
1044
+ deserialize(json, meta, maps, getBlob) {
1045
+ const ref = { data: json };
1046
+ if (maps && getBlob) maps.forEach((segments, i) => {
1047
+ let currentRef = ref;
1048
+ let preSegment = "data";
1049
+ segments.forEach((segment) => {
1050
+ currentRef = currentRef[preSegment];
1051
+ preSegment = segment;
1052
+ if (!Object.hasOwn(currentRef, preSegment)) throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${preSegment}`);
1053
+ });
1054
+ currentRef[preSegment] = getBlob(i);
1055
+ });
1056
+ for (const item of meta) {
1057
+ const type = item[0];
1058
+ let currentRef = ref;
1059
+ let preSegment = "data";
1060
+ for (let i = 1; i < item.length; i++) {
1061
+ currentRef = currentRef[preSegment];
1062
+ preSegment = item[i];
1063
+ if (!Object.hasOwn(currentRef, preSegment)) throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${preSegment}`);
1064
+ }
1065
+ for (const custom of this.customSerializers) if (custom.type === type) {
1066
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
1067
+ break;
1068
+ }
1069
+ switch (type) {
1070
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
1071
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
1072
+ break;
1073
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
1074
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
1075
+ break;
1076
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
1077
+ currentRef[preSegment] = NaN;
1078
+ break;
1079
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
1080
+ currentRef[preSegment] = void 0;
1081
+ break;
1082
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
1083
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
1084
+ break;
1085
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
1086
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
1087
+ currentRef[preSegment] = new RegExp(pattern, flags);
1088
+ break;
1089
+ }
1090
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
1091
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
1092
+ break;
1093
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
1094
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
1095
+ break;
1096
+ }
1097
+ }
1098
+ return ref.data;
1099
+ }
1100
+ };
1101
+ function toHttpPath(path) {
1102
+ return `/${path.map(encodeURIComponent).join("/")}`;
1103
+ }
1104
+ function toStandardHeaders(headers) {
1105
+ if (typeof headers.forEach === "function") return toStandardHeaders$1(headers);
1106
+ return headers;
1107
+ }
1108
+ function getMalformedResponseErrorCode(status) {
1109
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
1110
+ }
1111
+ var StandardRPCLinkCodec = class {
1112
+ constructor(serializer, options) {
1113
+ this.serializer = serializer;
1114
+ this.baseUrl = options.url;
1115
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
1116
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
1117
+ this.expectedMethod = options.method ?? this.fallbackMethod;
1118
+ this.headers = options.headers ?? {};
1119
+ }
1120
+ baseUrl;
1121
+ maxUrlLength;
1122
+ fallbackMethod;
1123
+ expectedMethod;
1124
+ headers;
1125
+ async encode(path, input, options) {
1126
+ let headers = toStandardHeaders(await value(this.headers, options, path, input));
1127
+ if (options.lastEventId !== void 0) headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
1128
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
1129
+ const baseUrl = await value(this.baseUrl, options, path, input);
1130
+ const url = new URL(baseUrl);
1131
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
1132
+ const serialized = this.serializer.serialize(input);
1133
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
1134
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
1135
+ const getUrl = new URL(url);
1136
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
1137
+ if (getUrl.toString().length <= maxUrlLength) return {
1138
+ body: void 0,
1139
+ method: expectedMethod,
1140
+ headers,
1141
+ url: getUrl,
1142
+ signal: options.signal
1143
+ };
1144
+ }
1145
+ return {
1146
+ url,
1147
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
1148
+ headers,
1149
+ body: serialized,
1150
+ signal: options.signal
1151
+ };
1152
+ }
1153
+ async decode(response) {
1154
+ const isOk = !isORPCErrorStatus(response.status);
1155
+ const deserialized = await (async () => {
1156
+ let isBodyOk = false;
1157
+ try {
1158
+ const body = await response.body();
1159
+ isBodyOk = true;
1160
+ return this.serializer.deserialize(body);
1161
+ } catch (error) {
1162
+ if (!isBodyOk) throw new Error("Cannot parse response body, please check the response body and content-type.", { cause: error });
1163
+ throw new Error("Invalid RPC response format.", { cause: error });
1164
+ }
1165
+ })();
1166
+ if (!isOk) {
1167
+ if (isORPCErrorJson(deserialized)) throw createORPCErrorFromJson(deserialized);
1168
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
1169
+ status: response.status,
1170
+ data: {
1171
+ ...response,
1172
+ body: deserialized
1173
+ }
1174
+ });
1175
+ }
1176
+ return deserialized;
1177
+ }
1178
+ };
1179
+ var StandardRPCSerializer = class {
1180
+ constructor(jsonSerializer) {
1181
+ this.jsonSerializer = jsonSerializer;
1182
+ }
1183
+ serialize(data) {
1184
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1185
+ value: async (value) => this.#serialize(value, false),
1186
+ error: async (e) => {
1187
+ return new ErrorEvent({
1188
+ data: this.#serialize(toORPCError(e).toJSON(), false),
1189
+ cause: e
1190
+ });
1191
+ }
1192
+ });
1193
+ return this.#serialize(data, true);
1194
+ }
1195
+ #serialize(data, enableFormData) {
1196
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
1197
+ const meta = meta_.length === 0 ? void 0 : meta_;
1198
+ if (!enableFormData || blobs.length === 0) return {
1199
+ json,
1200
+ meta
1201
+ };
1202
+ const form = new FormData();
1203
+ form.set("data", stringifyJSON({
1204
+ json,
1205
+ meta,
1206
+ maps
1207
+ }));
1208
+ blobs.forEach((blob, i) => {
1209
+ form.set(i.toString(), blob);
1210
+ });
1211
+ return form;
1212
+ }
1213
+ deserialize(data) {
1214
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1215
+ value: async (value) => this.#deserialize(value),
1216
+ error: async (e) => {
1217
+ if (!(e instanceof ErrorEvent)) return e;
1218
+ const deserialized = this.#deserialize(e.data);
1219
+ if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: e });
1220
+ return new ErrorEvent({
1221
+ data: deserialized,
1222
+ cause: e
1223
+ });
1224
+ }
1225
+ });
1226
+ return this.#deserialize(data);
1227
+ }
1228
+ #deserialize(data) {
1229
+ if (data === void 0) return;
1230
+ if (!(data instanceof FormData)) return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
1231
+ const serialized = JSON.parse(data.get("data"));
1232
+ return this.jsonSerializer.deserialize(serialized.json, serialized.meta ?? [], serialized.maps, (i) => data.get(i.toString()));
1233
+ }
1234
+ };
1235
+ var StandardRPCLink = class extends StandardLink {
1236
+ constructor(linkClient, options) {
1237
+ const linkCodec = new StandardRPCLinkCodec(new StandardRPCSerializer(new StandardRPCJsonSerializer(options)), options);
1238
+ super(linkCodec, linkClient, options);
1239
+ }
1240
+ };
1241
+ //#endregion
1242
+ //#region ../../node_modules/.pnpm/@orpc+client@1.14.0_@opentelemetry+api@1.9.0/node_modules/@orpc/client/dist/adapters/fetch/index.mjs
1243
+ var CompositeLinkFetchPlugin = class extends CompositeStandardLinkPlugin {
1244
+ initRuntimeAdapter(options) {
1245
+ for (const plugin of this.plugins) plugin.initRuntimeAdapter?.(options);
1246
+ }
1247
+ };
1248
+ var LinkFetchClient = class {
1249
+ fetch;
1250
+ toFetchRequestOptions;
1251
+ adapterInterceptors;
1252
+ constructor(options) {
1253
+ new CompositeLinkFetchPlugin(options.plugins).initRuntimeAdapter(options);
1254
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1255
+ this.toFetchRequestOptions = options;
1256
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
1257
+ }
1258
+ async call(standardRequest, options, path, input) {
1259
+ const request = toFetchRequest(standardRequest, this.toFetchRequestOptions);
1260
+ return toStandardLazyResponse(await intercept(this.adapterInterceptors, {
1261
+ ...options,
1262
+ request,
1263
+ path,
1264
+ input,
1265
+ init: { redirect: "manual" }
1266
+ }, ({ request: request2, path: path2, input: input2, init, ...options2 }) => this.fetch(request2, init, options2, path2, input2)), { signal: request.signal });
1267
+ }
1268
+ };
1269
+ var RPCLink = class extends StandardRPCLink {
1270
+ constructor(options) {
1271
+ const linkClient = new LinkFetchClient(options);
1272
+ super(linkClient, options);
1273
+ }
1274
+ };
1275
+ //#endregion
1276
+ //#region ../orpc/src/shared/client.ts
1277
+ function createLink(options) {
1278
+ return new RPCLink({
1279
+ url: options.baseUrl,
1280
+ headers: async () => {
1281
+ const baseHeaders = { "Content-Type": "application/json" };
1282
+ const customHeaders = typeof options.headers === "function" ? await options.headers() : options.headers;
1283
+ if (customHeaders) Object.assign(baseHeaders, customHeaders);
1284
+ if (options.getAuthToken) {
1285
+ const token = await options.getAuthToken();
1286
+ if (token) baseHeaders["Cookie"] = `tourial-session=${token}`;
1287
+ }
1288
+ return baseHeaders;
1289
+ },
1290
+ fetch: options.fetch || options.onResponse ? async (request, init) => {
1291
+ const response = await (options.fetch || globalThis.fetch)(request, init);
1292
+ if (options.onResponse) await options.onResponse(response);
1293
+ return response;
1294
+ } : void 0
1295
+ });
1296
+ }
1297
+ //#endregion
1298
+ //#region ../orpc/src/live/client.ts
1299
+ /**
1300
+ * Create an HTTP client for calling live oRPC API endpoints
1301
+ */
1302
+ function createLiveHttpClient(options) {
1303
+ return createORPCClient(createLink(options));
1304
+ }
1305
+ //#endregion
1306
+ //#region src/api.ts
1307
+ /**
1308
+ * Normalize a branded-host origin into the `/api/v3` base the live API is served
1309
+ * under. Accepts a bare origin ("https://guide.acme.com") or a URL that already
1310
+ * ends with `/api/v3`.
1311
+ */
1312
+ function toApiBaseUrl(baseUrl) {
1313
+ const trimmed = baseUrl.replace(/\/+$/, "");
1314
+ return trimmed.endsWith("/api/v3") ? trimmed : `${trimmed}/api/v3`;
1315
+ }
1316
+ /**
1317
+ * Wrap a fetch implementation so every request carries the visitor cookies.
1318
+ * This is the load-bearing piece: the branded host is same-site with the
1319
+ * customer's page, so `credentials: "include"` lets the existing
1320
+ * `navless-live-*` cookies attach in every browser.
1321
+ */
1322
+ function withCredentials(fetchImpl) {
1323
+ return (input, init) => fetchImpl(input, {
1324
+ ...init,
1325
+ credentials: "include"
1326
+ });
1327
+ }
1328
+ /** Build the typed live oRPC client, reusing @navless/orpc's client factory. */
1329
+ function createApiClient(apiBaseUrl, fetchImpl) {
1330
+ return createLiveHttpClient({
1331
+ baseUrl: apiBaseUrl,
1332
+ fetch: withCredentials(fetchImpl)
1333
+ });
1334
+ }
1335
+ //#endregion
1336
+ //#region src/analytics.ts
1337
+ const UTM_KEYS = [
1338
+ "utm_source",
1339
+ "utm_medium",
1340
+ "utm_campaign",
1341
+ "utm_term",
1342
+ "utm_content"
1343
+ ];
1344
+ const INTEGRATION_COOKIE_KEYS = ["hubspotutk", "_mkto_trk"];
1345
+ /** Pull UTM attribution params out of a `location.search` string. */
1346
+ function extractUTMParams(search) {
1347
+ const params = new URLSearchParams(search);
1348
+ const result = {};
1349
+ for (const key of UTM_KEYS) {
1350
+ const value = params.get(key);
1351
+ if (value) result[key] = value;
1352
+ }
1353
+ return result;
1354
+ }
1355
+ /**
1356
+ * Pull first-party integration cookies (HubSpot, Marketo) out of a
1357
+ * `document.cookie` string so they can be forwarded for CRM stitching.
1358
+ */
1359
+ function extractIntegrationCookies(cookieString) {
1360
+ const cookies = {};
1361
+ for (const key of INTEGRATION_COOKIE_KEYS) {
1362
+ const match = cookieString.match(new RegExp(`(?:^|;\\s*)${key}=([^;]*)`));
1363
+ if (match?.[1]) cookies[key] = decodeURIComponent(match[1]);
1364
+ }
1365
+ return cookies;
1366
+ }
1367
+ /** Read `document.cookie`, swallowing the SecurityError thrown in opaque origins. */
1368
+ function safeCookieString() {
1369
+ if (typeof document === "undefined") return "";
1370
+ try {
1371
+ return document.cookie;
1372
+ } catch {
1373
+ return "";
1374
+ }
1375
+ }
1376
+ //#endregion
1377
+ //#region src/types.ts
1378
+ /** AG-UI protocol frame types written by the guide SSE stream. */
1379
+ const SSEMessageType = {
1380
+ RunStarted: "RUN_STARTED",
1381
+ RunFinished: "RUN_FINISHED",
1382
+ RunError: "RUN_ERROR",
1383
+ TextMessageStart: "TEXT_MESSAGE_START",
1384
+ TextMessageContent: "TEXT_MESSAGE_CONTENT",
1385
+ TextMessageEnd: "TEXT_MESSAGE_END",
1386
+ Custom: "CUSTOM"
1387
+ };
1388
+ /** The `name` on `CUSTOM` guide events (skill payloads). */
1389
+ const GuideEvent = {
1390
+ SkillStart: "skill_start",
1391
+ SkillContent: "skill_content",
1392
+ SkillDocuments: "skill_documents",
1393
+ SkillRecommendations: "skill_recommendations",
1394
+ SkillCTAs: "skill_ctas",
1395
+ SkillDiagnoseHeader: "skill_diagnose_header",
1396
+ SkillDiagnoseQuestion: "skill_diagnose_question",
1397
+ SkillPlaylistItems: "skill_playlist_items",
1398
+ SkillPlaylistHeader: "skill_playlist_header",
1399
+ SkillPlaylistRationale: "skill_playlist_rationale",
1400
+ SkillHowToOutline: "skill_howto_outline",
1401
+ SkillHowToSteps: "skill_howto_steps",
1402
+ SkillBusinessCaseChooser: "skill_businesscase_chooser",
1403
+ SkillBusinessCaseDelta: "skill_businesscase_delta",
1404
+ SkillSolutionDesignHeader: "skill_solutiondesign_header",
1405
+ SkillSolutionDesignDiagram: "skill_solutiondesign_diagram",
1406
+ SkillEnd: "skill_end",
1407
+ SkillError: "skill_error",
1408
+ SkillGate: "skill_gate",
1409
+ InputSuggestions: "input_suggestions"
1410
+ };
1411
+ /** The guide skill types. `answer` is always on; the rest are enabled per-guide. */
1412
+ const SkillResponseType = {
1413
+ Answer: "answer",
1414
+ HowTo: "howto",
1415
+ Diagnose: "diagnose",
1416
+ Recommend: "recommend",
1417
+ Playlist: "playlist",
1418
+ BusinessCase: "businesscase",
1419
+ SolutionDesign: "solutiondesign"
1420
+ };
1421
+ /** Consent tiers. `essential` is always granted server-side. */
1422
+ const ConsentTier = {
1423
+ Essential: "essential",
1424
+ Functional: "functional",
1425
+ Analytical: "analytical"
1426
+ };
1427
+ /** Analytics events fired by the SDK bootstrap. */
1428
+ const EmbedTrackingEvent = {
1429
+ EmbedLoaded: "embed_loaded",
1430
+ EmbedPageView: "embed_page_view",
1431
+ EmbedTriggerClicked: "embed_trigger_clicked",
1432
+ EmbedSideTabClicked: "embed_side_tab_clicked",
1433
+ EmbedSideTabDismissed: "embed_side_tab_dismissed"
1434
+ };
1435
+ //#endregion
1436
+ //#region src/chat-stream.ts
1437
+ const DATA_PREFIX = "data:";
1438
+ const DONE_SENTINEL = "[DONE]";
1439
+ /**
1440
+ * Stream a guide chat turn. POSTs the conversation to the SSE route
1441
+ * (`/api/v3/guide/conversation`) and yields normalized {@link GuideStreamEvent}s
1442
+ * until the server writes `data: [DONE]`. This is the one endpoint that is not
1443
+ * part of the typed oRPC router, so it is spoken by hand here.
1444
+ */
1445
+ async function* streamConversation(params) {
1446
+ const { apiBaseUrl, guideId, messages, forcedSkill, fetchImpl, signal } = params;
1447
+ const body = {
1448
+ guideId,
1449
+ messages: messages.map((m) => ({
1450
+ role: m.role,
1451
+ content: m.content
1452
+ }))
1453
+ };
1454
+ if (forcedSkill) body.forcedSkill = forcedSkill;
1455
+ const response = await fetchImpl(`${apiBaseUrl}/guide/conversation`, {
1456
+ method: "POST",
1457
+ headers: { "Content-Type": "application/json" },
1458
+ credentials: "include",
1459
+ body: JSON.stringify(body),
1460
+ signal
1461
+ });
1462
+ if (!response.ok || !response.body) throw new Error(`[brand_brain] Conversation request failed with status ${response.status}`);
1463
+ const reader = response.body.getReader();
1464
+ const decoder = new TextDecoder();
1465
+ let buffer = "";
1466
+ try {
1467
+ for (;;) {
1468
+ const { done, value } = await reader.read();
1469
+ if (done) break;
1470
+ buffer += decoder.decode(value, { stream: true });
1471
+ let separatorIndex = buffer.indexOf("\n\n");
1472
+ while (separatorIndex !== -1) {
1473
+ const rawEvent = buffer.slice(0, separatorIndex);
1474
+ buffer = buffer.slice(separatorIndex + 2);
1475
+ separatorIndex = buffer.indexOf("\n\n");
1476
+ const dataLine = rawEvent.split("\n").find((line) => line.startsWith(DATA_PREFIX));
1477
+ if (!dataLine) continue;
1478
+ const data = dataLine.slice(5).trim();
1479
+ if (data === DONE_SENTINEL) return;
1480
+ const mapped = mapFrame(JSON.parse(data));
1481
+ if (mapped) yield mapped;
1482
+ }
1483
+ }
1484
+ } finally {
1485
+ reader.releaseLock();
1486
+ }
1487
+ }
1488
+ function mapFrame(frame) {
1489
+ switch (frame.type) {
1490
+ case SSEMessageType.RunStarted: return {
1491
+ type: "run-started",
1492
+ runId: frame.runId ?? ""
1493
+ };
1494
+ case SSEMessageType.RunFinished: return {
1495
+ type: "run-finished",
1496
+ finishReason: frame.finishReason
1497
+ };
1498
+ case SSEMessageType.RunError: return {
1499
+ type: "error",
1500
+ message: frame.error?.message ?? "Unknown error",
1501
+ code: frame.error?.code
1502
+ };
1503
+ case SSEMessageType.TextMessageStart: return {
1504
+ type: "message-start",
1505
+ messageId: frame.messageId ?? "",
1506
+ role: frame.role ?? "assistant"
1507
+ };
1508
+ case SSEMessageType.TextMessageContent: return {
1509
+ type: "text",
1510
+ messageId: frame.messageId ?? "",
1511
+ delta: frame.delta ?? ""
1512
+ };
1513
+ case SSEMessageType.TextMessageEnd: return {
1514
+ type: "message-end",
1515
+ messageId: frame.messageId ?? ""
1516
+ };
1517
+ case SSEMessageType.Custom: return mapCustomFrame(frame);
1518
+ default: return null;
1519
+ }
1520
+ }
1521
+ function mapCustomFrame(frame) {
1522
+ if (!frame.name) return null;
1523
+ const value = frame.value ?? {};
1524
+ if (frame.name === GuideEvent.SkillGate) return {
1525
+ type: "gate",
1526
+ skill: value.skill,
1527
+ prompt: value.prompt,
1528
+ skillInstanceId: value.skillInstanceId
1529
+ };
1530
+ if (frame.name === GuideEvent.SkillError) return {
1531
+ type: "error",
1532
+ message: value.message ?? "Skill error",
1533
+ code: value.errorType
1534
+ };
1535
+ return {
1536
+ type: "skill",
1537
+ name: frame.name,
1538
+ value
1539
+ };
1540
+ }
1541
+ //#endregion
1542
+ //#region src/GuideClient.ts
1543
+ function resolveDomain(config) {
1544
+ if (config.domain) return config.domain;
1545
+ if (typeof window !== "undefined") return window.location.hostname;
1546
+ throw new Error("[brand_brain] `domain` is required when running without a browser `window`.");
1547
+ }
1548
+ /**
1549
+ * The client returned by {@link initGuide}. Holds the resolved guide, the
1550
+ * credentialed live API client, and the in-memory conversation history. Every
1551
+ * method reuses an existing public endpoint — the SDK adds no server surface.
1552
+ */
1553
+ var GuideClient = class GuideClient {
1554
+ #api;
1555
+ constructor(params) {
1556
+ this.history = [];
1557
+ this.conversations = {
1558
+ getOrCreate: () => this.#api.conversations.getOrCreate({
1559
+ guideId: this.guide.id,
1560
+ accountId: this.guide.accountId
1561
+ }),
1562
+ list: () => this.#api.conversations.list({
1563
+ guideId: this.guide.id,
1564
+ accountId: this.guide.accountId
1565
+ }),
1566
+ get: (conversationId, options) => this.#api.conversations.get({
1567
+ conversationId,
1568
+ accountId: this.guide.accountId,
1569
+ ...options
1570
+ }),
1571
+ delete: (conversationId) => this.#api.conversations.delete({
1572
+ conversationId,
1573
+ accountId: this.guide.accountId
1574
+ })
1575
+ };
1576
+ this.skills = {
1577
+ listHistory: () => this.#api.skillInstances.listHistory({
1578
+ accountId: this.guide.accountId,
1579
+ guideId: this.guide.id
1580
+ }),
1581
+ get: (skillInstanceId) => this.#api.skillInstances.get({ skillInstanceId }),
1582
+ update: (skillInstanceId, data) => this.#api.skillInstances.update({
1583
+ skillInstanceId,
1584
+ data
1585
+ }),
1586
+ selectDraft: (draftId) => this.#api.skillInstances.selectDraft({ draftId }),
1587
+ markShared: (skillInstanceId) => this.#api.skillInstances.markShared({ skillInstanceId }),
1588
+ importShared: (sourceSkillInstanceId) => this.#api.skillInstances.importShared({
1589
+ sourceSkillInstanceId,
1590
+ accountId: this.guide.accountId
1591
+ })
1592
+ };
1593
+ this.guide = params.guide;
1594
+ this.apiBaseUrl = params.apiBaseUrl;
1595
+ this.domain = params.domain;
1596
+ this.fetchImpl = params.fetchImpl;
1597
+ this.#api = createApiClient(this.apiBaseUrl, this.fetchImpl);
1598
+ }
1599
+ static async init(config) {
1600
+ const fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
1601
+ const apiBaseUrl = toApiBaseUrl(config.baseUrl);
1602
+ const domain = resolveDomain(config);
1603
+ const guide = await createApiClient(apiBaseUrl, fetchImpl).guides.resolve({
1604
+ domain,
1605
+ slug: config.slug
1606
+ });
1607
+ const client = new GuideClient({
1608
+ guide,
1609
+ apiBaseUrl,
1610
+ domain,
1611
+ fetchImpl
1612
+ });
1613
+ await client.applyInitialConsent(config.consent ?? "auto", guide.gdprEnabled);
1614
+ if (config.trackLoad ?? true) client.trackLoad();
1615
+ return client;
1616
+ }
1617
+ /** The account this guide belongs to (used implicitly by history calls). */
1618
+ get accountId() {
1619
+ return this.guide.accountId;
1620
+ }
1621
+ /** The in-memory conversation history accumulated by {@link ask}. */
1622
+ get messages() {
1623
+ return this.history;
1624
+ }
1625
+ /**
1626
+ * Send a message and stream the reply. Yields text deltas for the chat bubble
1627
+ * plus every structured skill event; the full 7-skill surface flows through
1628
+ * one stream. The user + assistant turns are appended to {@link messages}.
1629
+ */
1630
+ async *ask(message, options = {}) {
1631
+ this.history.push({
1632
+ id: crypto.randomUUID(),
1633
+ role: "user",
1634
+ content: message
1635
+ });
1636
+ let assistant = null;
1637
+ for await (const event of streamConversation({
1638
+ apiBaseUrl: this.apiBaseUrl,
1639
+ guideId: this.guide.id,
1640
+ messages: this.history,
1641
+ forcedSkill: options.forcedSkill,
1642
+ fetchImpl: this.fetchImpl,
1643
+ signal: options.signal
1644
+ })) {
1645
+ if (event.type === "message-start") {
1646
+ assistant = {
1647
+ id: event.messageId || crypto.randomUUID(),
1648
+ role: "assistant",
1649
+ content: ""
1650
+ };
1651
+ this.history.push(assistant);
1652
+ } else if (event.type === "text" && assistant) assistant.content += event.delta;
1653
+ yield event;
1654
+ }
1655
+ }
1656
+ /** Clear the in-memory conversation history (server-side history is unaffected). */
1657
+ reset() {
1658
+ this.history.length = 0;
1659
+ }
1660
+ /** Grant consent tiers. `essential` is always forced true server-side. */
1661
+ async setConsent(levels) {
1662
+ await this.#api.visitors.setConsent({
1663
+ domain: this.domain,
1664
+ consent: levels
1665
+ });
1666
+ }
1667
+ /** Read the current visitor's tracking + consent + email status. */
1668
+ getStatus() {
1669
+ return this.#api.visitors.getVisitorStatus();
1670
+ }
1671
+ /** Capture a lead email (sends a magic link when verification is required). */
1672
+ submitGate(email, options = {}) {
1673
+ return this.#api.visitors.submitGate({
1674
+ email,
1675
+ domain: this.domain,
1676
+ guideId: this.guide.id,
1677
+ ...options
1678
+ });
1679
+ }
1680
+ /**
1681
+ * Fire an analytics event. Fire-and-forget — never throws into the host page.
1682
+ * Uses a raw request (the same shape the embed script posts) so it stays
1683
+ * decoupled from the typed client's event enum.
1684
+ */
1685
+ track(eventType, properties) {
1686
+ this.fetchImpl(`${this.apiBaseUrl}/events/track`, {
1687
+ method: "POST",
1688
+ headers: { "Content-Type": "application/json" },
1689
+ credentials: "include",
1690
+ body: JSON.stringify({ json: {
1691
+ domain: this.domain,
1692
+ guideId: this.guide.id,
1693
+ eventType,
1694
+ properties: properties ?? {}
1695
+ } })
1696
+ }).catch(() => {});
1697
+ }
1698
+ /** Fire the initial `embed_loaded` (with attribution) + first page view. */
1699
+ trackLoad() {
1700
+ const search = typeof window !== "undefined" ? window.location.search : "";
1701
+ const parentUrl = typeof window !== "undefined" ? window.location.href : void 0;
1702
+ const referrer = typeof document !== "undefined" ? document.referrer : void 0;
1703
+ this.track(EmbedTrackingEvent.EmbedLoaded, {
1704
+ referrer,
1705
+ parentUrl,
1706
+ utmParams: extractUTMParams(search),
1707
+ integrationCookies: extractIntegrationCookies(safeCookieString())
1708
+ });
1709
+ this.trackPageView();
1710
+ }
1711
+ /** Record a page view (call on client-side route changes in an SPA). */
1712
+ trackPageView(url) {
1713
+ const pageUrl = url ?? (typeof window !== "undefined" ? window.location.href : void 0);
1714
+ this.track(EmbedTrackingEvent.EmbedPageView, { pageUrl });
1715
+ }
1716
+ /** End the current visit (best to call on `pagehide`). */
1717
+ async endSession() {
1718
+ await this.#api.sessions.endSession();
1719
+ }
1720
+ async applyInitialConsent(consent, gdprEnabled) {
1721
+ if (consent === false) return;
1722
+ try {
1723
+ if (consent === "auto") {
1724
+ if (!gdprEnabled) await this.setConsent({
1725
+ functional: true,
1726
+ analytical: true
1727
+ });
1728
+ return;
1729
+ }
1730
+ await this.setConsent(consent);
1731
+ } catch {}
1732
+ }
1733
+ };
1734
+ /** Bootstrap a guide session and return a ready-to-use {@link GuideClient}. */
1735
+ async function initGuide(config) {
1736
+ return GuideClient.init(config);
1737
+ }
1738
+ //#endregion
1739
+ export { ConsentTier, EmbedTrackingEvent, GuideClient, GuideEvent, SSEMessageType, SkillResponseType, initGuide };
1740
+
1741
+ //# sourceMappingURL=index.mjs.map