storybook
Version:
Storybook: Develop, document, and test UI components in isolation
2,488 lines • 85.3 kB
JavaScript
import CJS_COMPAT_NODE_URL_qjinduibsyq from 'node:url';
import CJS_COMPAT_NODE_PATH_qjinduibsyq from 'node:path';
import CJS_COMPAT_NODE_MODULE_qjinduibsyq from "node:module";
var __filename = CJS_COMPAT_NODE_URL_qjinduibsyq.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_qjinduibsyq.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_qjinduibsyq.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
nanoid
} from "./chunk-2J2NU66Q.js";
import {
deserializeError,
serializeError
} from "./chunk-6WZPWJR4.js";
import {
OpenServiceAsyncSchemaError,
OpenServiceInternalServiceError,
OpenServiceInvalidStaticPathError,
OpenServiceLoadedDrainExceededError,
OpenServiceMissingChannelError,
OpenServiceMissingServiceError,
OpenServiceOperationNameCollisionError,
OpenServiceRemoteCommandConfigDriftError,
OpenServiceRemoteCommandDisconnectedError,
OpenServiceRemoteCommandUnhandledError,
OpenServiceUnimplementedOperationError,
OpenServiceValidationError
} from "./chunk-DW727PJG.js";
// src/channels/main.ts
var isMulti = (args) => args.transports !== void 0, generateRandomId = () => Math.random().toString(16).slice(2), Channel = class {
constructor(input = {}) {
this.sender = generateRandomId();
this.events = {};
this.data = {};
this.transports = [];
this.isAsync = input.async || !1, isMulti(input) ? (this.transports = input.transports || [], this.transports.forEach((t2) => {
t2.setHandler((event) => this.handleEvent(event));
})) : this.transports = input.transport ? [input.transport] : [], this.transports.forEach((t2) => {
t2.setHandler((event) => this.handleEvent(event));
});
}
get hasTransport() {
return this.transports.length > 0;
}
addListener(eventName, listener) {
this.events[eventName] = this.events[eventName] || [], this.events[eventName].push(listener);
}
emit(eventName, ...args) {
let event = { type: eventName, args, from: this.sender }, options = {};
args.length >= 1 && args[0] && args[0].options && (options = args[0].options);
let handler = () => {
this.transports.forEach((t2) => {
t2.send(event, options);
}), this.handleEvent(event);
};
this.isAsync ? setImmediate(handler) : handler();
}
last(eventName) {
return this.data[eventName];
}
eventNames() {
return Object.keys(this.events);
}
listenerCount(eventName) {
let listeners = this.listeners(eventName);
return listeners ? listeners.length : 0;
}
listeners(eventName) {
return this.events[eventName] || void 0;
}
once(eventName, listener) {
let onceListener = this.onceListener(eventName, listener);
this.addListener(eventName, onceListener);
}
removeAllListeners(eventName) {
eventName ? this.events[eventName] && delete this.events[eventName] : this.events = {};
}
removeListener(eventName, listener) {
let listeners = this.listeners(eventName);
listeners && (this.events[eventName] = listeners.filter((l3) => l3 !== listener));
}
on(eventName, listener) {
this.addListener(eventName, listener);
}
off(eventName, listener) {
this.removeListener(eventName, listener);
}
handleEvent(event) {
let listeners = this.listeners(event.type);
listeners && listeners.length && listeners.forEach((fn) => {
fn.apply(event, event.args);
}), this.data[event.type] = event.args;
}
onceListener(eventName, listener) {
let onceListener = (...args) => (this.removeListener(eventName, onceListener), listener(...args));
return onceListener;
}
};
// src/channels/channel-slot.ts
var channel;
function syncGlobalSlot(next) {
globalThis.__STORYBOOK_ADDONS_CHANNEL__ = next;
}
function getChannel() {
let fromGlobal = globalThis.__STORYBOOK_ADDONS_CHANNEL__;
return fromGlobal && (channel = fromGlobal), channel ?? null;
}
function setChannel(next) {
channel = next ?? void 0, syncGlobalSlot(channel);
}
function installNoopChannel() {
setChannel(new Channel({}));
}
function ensureChannel() {
getChannel() || installNoopChannel();
}
typeof window > "u" && ensureChannel();
// ../../node_modules/valibot/dist/index.mjs
var store$4, DEFAULT_CONFIG = {
lang: void 0,
message: void 0,
abortEarly: void 0,
abortPipeEarly: void 0
};
function getGlobalConfig(config$1) {
return !config$1 && !store$4 ? DEFAULT_CONFIG : {
lang: config$1?.lang ?? store$4?.lang,
message: config$1?.message,
abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
};
}
var store$3;
function getGlobalMessage(lang) {
return store$3?.get(lang);
}
var store$2;
function getSchemaMessage(lang) {
return store$2?.get(lang);
}
var store$1;
function getSpecificMessage(reference, lang) {
return store$1?.get(reference)?.get(lang);
}
function _stringify(input) {
let type = typeof input;
return type === "string" ? `"${input}"` : type === "number" || type === "bigint" || type === "boolean" ? `${input}` : type === "object" || type === "function" ? (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null" : type;
}
function _addIssue(context, label, dataset, config$1, other) {
let input = other && "input" in other ? other.input : dataset.value, expected = other?.expected ?? context.expects ?? null, received = other?.received ?? _stringify(input), issue = {
kind: context.kind,
type: context.type,
input,
expected,
received,
message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
requirement: context.requirement,
path: other?.path,
issues: other?.issues,
lang: config$1.lang,
abortEarly: config$1.abortEarly,
abortPipeEarly: config$1.abortPipeEarly
}, isSchema = context.kind === "schema", message$1 = other?.message ?? context.message ?? getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? getSchemaMessage(issue.lang) : null) ?? config$1.message ?? getGlobalMessage(issue.lang);
message$1 !== void 0 && (issue.message = typeof message$1 == "function" ? message$1(issue) : message$1), isSchema && (dataset.typed = !1), dataset.issues ? dataset.issues.push(issue) : dataset.issues = [issue];
}
var _standardCache = /* @__PURE__ */ new WeakMap();
function _getStandardProps(context) {
let cached = _standardCache.get(context);
return cached || (cached = {
version: 1,
vendor: "valibot",
validate(value$1) {
return context["~run"]({ value: value$1 }, getGlobalConfig());
}
}, _standardCache.set(context, cached)), cached;
}
function _isValidObjectKey(object$1, key) {
return Object.prototype.hasOwnProperty.call(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
}
function _joinExpects(values$1, separator) {
let list = [...new Set(values$1)];
return list.length > 1 ? `(${list.join(` ${separator} `)})` : list[0] ?? "never";
}
function getDotPath(issue) {
if (issue.path) {
let key = "";
for (let item of issue.path) if (typeof item.key == "string" || typeof item.key == "number") key ? key += `.${item.key}` : key += item.key;
else return null;
return key;
}
return null;
}
var EMOJI_REGEX = new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$", "u");
function description(description_) {
return {
kind: "metadata",
type: "description",
reference: description,
description: description_
};
}
function integer(message$1) {
return {
kind: "validation",
type: "integer",
reference: integer,
async: !1,
expects: null,
requirement: Number.isInteger,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && !this.requirement(dataset.value) && _addIssue(this, "integer", dataset, config$1), dataset;
}
};
}
function maxValue(requirement, message$1) {
return {
kind: "validation",
type: "max_value",
reference: maxValue,
async: !1,
expects: `<=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`,
requirement,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && !(dataset.value <= this.requirement) && _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) }), dataset;
}
};
}
function minLength(requirement, message$1) {
return {
kind: "validation",
type: "min_length",
reference: minLength,
async: !1,
expects: `>=${requirement}`,
requirement,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && dataset.value.length < this.requirement && _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` }), dataset;
}
};
}
function minValue(requirement, message$1) {
return {
kind: "validation",
type: "min_value",
reference: minValue,
async: !1,
expects: `>=${requirement instanceof Date ? requirement.toJSON() : _stringify(requirement)}`,
requirement,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && !(dataset.value >= this.requirement) && _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : _stringify(dataset.value) }), dataset;
}
};
}
function regex(requirement, message$1) {
return {
kind: "validation",
type: "regex",
reference: regex,
async: !1,
expects: `${requirement}`,
requirement,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && !this.requirement.test(dataset.value) && _addIssue(this, "format", dataset, config$1), dataset;
}
};
}
function safeInteger(message$1) {
return {
kind: "validation",
type: "safe_integer",
reference: safeInteger,
async: !1,
expects: null,
requirement: Number.isSafeInteger,
message: message$1,
"~run"(dataset, config$1) {
return dataset.typed && !this.requirement(dataset.value) && _addIssue(this, "safe integer", dataset, config$1), dataset;
}
};
}
function transform(operation) {
return {
kind: "transformation",
type: "transform",
reference: transform,
async: !1,
operation,
"~run"(dataset) {
return dataset.value = this.operation(dataset.value), dataset;
}
};
}
function trim() {
return {
kind: "transformation",
type: "trim",
reference: trim,
async: !1,
"~run"(dataset) {
return dataset.value = dataset.value.trim(), dataset;
}
};
}
var ABORT_EARLY_CONFIG = { abortEarly: !0 };
function getFallback(schema, dataset, config$1) {
return typeof schema.fallback == "function" ? schema.fallback(dataset, config$1) : schema.fallback;
}
function getDefault(schema, dataset, config$1) {
return typeof schema.default == "function" ? schema.default(dataset, config$1) : schema.default;
}
function any() {
return {
kind: "schema",
type: "any",
reference: any,
expects: "any",
async: !1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset) {
return dataset.typed = !0, dataset;
}
};
}
function array(item, message$1) {
return {
kind: "schema",
type: "array",
reference: array,
expects: "Array",
async: !1,
item,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let input = dataset.value;
if (Array.isArray(input)) {
dataset.typed = !0, dataset.value = [];
for (let key = 0; key < input.length; key++) {
let value$1 = input[key], itemDataset = this.item["~run"]({ value: value$1 }, config$1);
if (itemDataset.issues) {
let pathItem = {
type: "array",
origin: "value",
input,
key,
value: value$1
};
for (let issue of itemDataset.issues)
issue.path ? issue.path.unshift(pathItem) : issue.path = [pathItem], dataset.issues?.push(issue);
if (dataset.issues || (dataset.issues = itemDataset.issues), config$1.abortEarly) {
dataset.typed = !1;
break;
}
}
itemDataset.typed || (dataset.typed = !1), dataset.value.push(itemDataset.value);
}
} else _addIssue(this, "type", dataset, config$1);
return dataset;
}
};
}
function boolean(message$1) {
return {
kind: "schema",
type: "boolean",
reference: boolean,
expects: "boolean",
async: !1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return typeof dataset.value == "boolean" ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function custom(check$1, message$1) {
return {
kind: "schema",
type: "custom",
reference: custom,
expects: "unknown",
async: !1,
check: check$1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return this.check(dataset.value) ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function lazy(getter) {
return {
kind: "schema",
type: "lazy",
reference: lazy,
expects: "unknown",
async: !1,
getter,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return this.getter(dataset.value)["~run"](dataset, config$1);
}
};
}
function literal(literal_, message$1) {
return {
kind: "schema",
type: "literal",
reference: literal,
expects: _stringify(literal_),
async: !1,
literal: literal_,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return dataset.value === this.literal ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function looseObject(entries$1, message$1) {
return {
kind: "schema",
type: "loose_object",
reference: looseObject,
expects: "Object",
async: !1,
entries: entries$1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let input = dataset.value;
if (input && typeof input == "object") {
dataset.typed = !0, dataset.value = {};
for (let key in this.entries) {
let valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
let value$1 = key in input ? input[key] : getDefault(valueSchema), valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
if (valueDataset.issues) {
let pathItem = {
type: "object",
origin: "value",
input,
key,
value: value$1
};
for (let issue of valueDataset.issues)
issue.path ? issue.path.unshift(pathItem) : issue.path = [pathItem], dataset.issues?.push(issue);
if (dataset.issues || (dataset.issues = valueDataset.issues), config$1.abortEarly) {
dataset.typed = !1;
break;
}
}
valueDataset.typed || (dataset.typed = !1), dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) dataset.value[key] = getFallback(valueSchema);
else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish" && (_addIssue(this, "key", dataset, config$1, {
input: void 0,
expected: `"${key}"`,
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
}), config$1.abortEarly))
break;
}
if (!dataset.issues || !config$1.abortEarly)
for (let key in input) _isValidObjectKey(input, key) && !(key in this.entries) && (dataset.value[key] = input[key]);
} else _addIssue(this, "type", dataset, config$1);
return dataset;
}
};
}
function nullable(wrapped, default_) {
return {
kind: "schema",
type: "nullable",
reference: nullable,
expects: `(${wrapped.expects} | null)`,
async: !1,
wrapped,
default: default_,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return dataset.value === null && (this.default !== void 0 && (dataset.value = getDefault(this, dataset, config$1)), dataset.value === null) ? (dataset.typed = !0, dataset) : this.wrapped["~run"](dataset, config$1);
}
};
}
function number(message$1) {
return {
kind: "schema",
type: "number",
reference: number,
expects: "number",
async: !1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return typeof dataset.value == "number" && !isNaN(dataset.value) ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function object(entries$1, message$1) {
return {
kind: "schema",
type: "object",
reference: object,
expects: "Object",
async: !1,
entries: entries$1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let input = dataset.value;
if (input && typeof input == "object") {
dataset.typed = !0, dataset.value = {};
for (let key in this.entries) {
let valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
let value$1 = key in input ? input[key] : getDefault(valueSchema), valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
if (valueDataset.issues) {
let pathItem = {
type: "object",
origin: "value",
input,
key,
value: value$1
};
for (let issue of valueDataset.issues)
issue.path ? issue.path.unshift(pathItem) : issue.path = [pathItem], dataset.issues?.push(issue);
if (dataset.issues || (dataset.issues = valueDataset.issues), config$1.abortEarly) {
dataset.typed = !1;
break;
}
}
valueDataset.typed || (dataset.typed = !1), dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) dataset.value[key] = getFallback(valueSchema);
else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish" && (_addIssue(this, "key", dataset, config$1, {
input: void 0,
expected: `"${key}"`,
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
}), config$1.abortEarly))
break;
}
} else _addIssue(this, "type", dataset, config$1);
return dataset;
}
};
}
function optional(wrapped, default_) {
return {
kind: "schema",
type: "optional",
reference: optional,
expects: `(${wrapped.expects} | undefined)`,
async: !1,
wrapped,
default: default_,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return dataset.value === void 0 && (this.default !== void 0 && (dataset.value = getDefault(this, dataset, config$1)), dataset.value === void 0) ? (dataset.typed = !0, dataset) : this.wrapped["~run"](dataset, config$1);
}
};
}
function picklist(options, message$1) {
return {
kind: "schema",
type: "picklist",
reference: picklist,
expects: _joinExpects(options.map(_stringify), "|"),
async: !1,
options,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return this.options.includes(dataset.value) ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function record(key, value$1, message$1) {
return {
kind: "schema",
type: "record",
reference: record,
expects: "Object",
async: !1,
key,
value: value$1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let input = dataset.value;
if (input && typeof input == "object") {
dataset.typed = !0, dataset.value = {};
for (let entryKey in input) if (_isValidObjectKey(input, entryKey)) {
let entryValue = input[entryKey], keyDataset = this.key["~run"]({ value: entryKey }, config$1);
if (keyDataset.issues) {
let pathItem = {
type: "object",
origin: "key",
input,
key: entryKey,
value: entryValue
};
for (let issue of keyDataset.issues)
issue.path = [pathItem], dataset.issues?.push(issue);
if (dataset.issues || (dataset.issues = keyDataset.issues), config$1.abortEarly) {
dataset.typed = !1;
break;
}
}
let valueDataset = this.value["~run"]({ value: entryValue }, config$1);
if (valueDataset.issues) {
let pathItem = {
type: "object",
origin: "value",
input,
key: entryKey,
value: entryValue
};
for (let issue of valueDataset.issues)
issue.path ? issue.path.unshift(pathItem) : issue.path = [pathItem], dataset.issues?.push(issue);
if (dataset.issues || (dataset.issues = valueDataset.issues), config$1.abortEarly) {
dataset.typed = !1;
break;
}
}
(!keyDataset.typed || !valueDataset.typed) && (dataset.typed = !1), keyDataset.typed && (dataset.value[keyDataset.value] = valueDataset.value);
}
} else _addIssue(this, "type", dataset, config$1);
return dataset;
}
};
}
function string(message$1) {
return {
kind: "schema",
type: "string",
reference: string,
expects: "string",
async: !1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return typeof dataset.value == "string" ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function undefined_(message$1) {
return {
kind: "schema",
type: "undefined",
reference: undefined_,
expects: "undefined",
async: !1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return dataset.value === void 0 ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function _subIssues(datasets) {
let issues;
if (datasets) for (let dataset of datasets) if (issues) for (let issue of dataset.issues) issues.push(issue);
else issues = dataset.issues;
return issues;
}
function union(options, message$1) {
return {
kind: "schema",
type: "union",
reference: union,
expects: _joinExpects(options.map((option) => option.expects), "|"),
async: !1,
options,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let validDataset, typedDatasets, untypedDatasets;
for (let schema of this.options) {
let optionDataset = schema["~run"]({ value: dataset.value }, config$1);
if (optionDataset.typed) if (optionDataset.issues) typedDatasets ? typedDatasets.push(optionDataset) : typedDatasets = [optionDataset];
else {
validDataset = optionDataset;
break;
}
else untypedDatasets ? untypedDatasets.push(optionDataset) : untypedDatasets = [optionDataset];
}
if (validDataset) return validDataset;
if (typedDatasets) {
if (typedDatasets.length === 1) return typedDatasets[0];
_addIssue(this, "type", dataset, config$1, { issues: _subIssues(typedDatasets) }), dataset.typed = !0;
} else {
if (untypedDatasets?.length === 1) return untypedDatasets[0];
_addIssue(this, "type", dataset, config$1, { issues: _subIssues(untypedDatasets) });
}
return dataset;
}
};
}
function unknown() {
return {
kind: "schema",
type: "unknown",
reference: unknown,
expects: "unknown",
async: !1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset) {
return dataset.typed = !0, dataset;
}
};
}
function variant(key, options, message$1) {
return {
kind: "schema",
type: "variant",
reference: variant,
expects: "Object",
async: !1,
key,
options,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
let input = dataset.value;
if (input && typeof input == "object") {
let outputDataset, maxDiscriminatorPriority = 0, invalidDiscriminatorKey = this.key, expectedDiscriminators = [], parseOptions = (variant$1, allKeys) => {
for (let schema of variant$1.options) {
if (schema.type === "variant") parseOptions(schema, new Set(allKeys).add(schema.key));
else {
let keysAreValid = !0, currentPriority = 0;
for (let currentKey of allKeys) {
let discriminatorSchema = schema.entries[currentKey];
if (currentKey in input ? discriminatorSchema["~run"]({
typed: !1,
value: input[currentKey]
}, ABORT_EARLY_CONFIG).issues : discriminatorSchema.type !== "exact_optional" && discriminatorSchema.type !== "optional" && discriminatorSchema.type !== "nullish") {
keysAreValid = !1, invalidDiscriminatorKey !== currentKey && (maxDiscriminatorPriority < currentPriority || maxDiscriminatorPriority === currentPriority && currentKey in input && !(invalidDiscriminatorKey in input)) && (maxDiscriminatorPriority = currentPriority, invalidDiscriminatorKey = currentKey, expectedDiscriminators = []), invalidDiscriminatorKey === currentKey && expectedDiscriminators.push(schema.entries[currentKey].expects);
break;
}
currentPriority++;
}
if (keysAreValid) {
let optionDataset = schema["~run"]({ value: input }, config$1);
(!outputDataset || !outputDataset.typed && optionDataset.typed) && (outputDataset = optionDataset);
}
}
if (outputDataset && !outputDataset.issues) break;
}
};
if (parseOptions(this, /* @__PURE__ */ new Set([this.key])), outputDataset) return outputDataset;
_addIssue(this, "type", dataset, config$1, {
input: input[invalidDiscriminatorKey],
expected: _joinExpects(expectedDiscriminators, "|"),
path: [{
type: "object",
origin: "value",
input,
key: invalidDiscriminatorKey,
value: input[invalidDiscriminatorKey]
}]
});
} else _addIssue(this, "type", dataset, config$1);
return dataset;
}
};
}
function void_(message$1) {
return {
kind: "schema",
type: "void",
reference: void_,
expects: "void",
async: !1,
message: message$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return dataset.value === void 0 ? dataset.typed = !0 : _addIssue(this, "type", dataset, config$1), dataset;
}
};
}
function message(schema, message_) {
return {
...schema,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
return schema["~run"](dataset, {
...config$1,
message: message_
});
}
};
}
function pipe(...pipe$1) {
return {
...pipe$1[0],
pipe: pipe$1,
get "~standard"() {
return _getStandardProps(this);
},
"~run"(dataset, config$1) {
for (let item of pipe$1) if (item.kind !== "metadata") {
if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
dataset.typed = !1;
break;
}
(!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) && (dataset = item["~run"](dataset, config$1));
}
return dataset;
}
};
}
function safeParse(schema, input, config$1) {
let dataset = schema["~run"]({ value: input }, getGlobalConfig(config$1));
return {
typed: dataset.typed,
success: !dataset.issues,
output: dataset.value,
issues: dataset.issues
};
}
function summarize(issues) {
let summary = "";
for (let issue of issues) {
summary && (summary += `
`), summary += `\xD7 ${issue.message}`;
let dotPath = getDotPath(issue);
dotPath && (summary += `
\u2192 at ${dotPath}`);
}
return summary;
}
// src/shared/open-service/service-channel.ts
var SERVICE_SYNC_START = "services:sync-start", SERVICE_SYNC_START_REPLY = "services:sync-start-reply", SERVICE_PATCHES = "services:patches", SERVICE_COMMAND_INVOKE = "services:command-invoke", SERVICE_COMMAND_ACK = "services:command-ack", SERVICE_COMMAND_RESULT = "services:command-result", SERVICE_COMMAND_ERROR = "services:command-error", SERVICE_COMMAND_UNHANDLED = "services:command-unhandled", stateSnapshotSchema = custom(
(value) => typeof value == "object" && value !== null && !Array.isArray(value)
), syncStartSchema = object({
serviceId: string(),
clientId: string()
}), stampedSnapshotSchema = object({
serviceId: string(),
state: stateSnapshotSchema,
version: pipe(number(), safeInteger(), minValue(0)),
clientId: string()
}), commandInvokeSchema = object({
serviceId: string(),
commandName: string(),
input: optional(unknown()),
callId: string(),
clientId: string()
}), commandAckSchema = object({
serviceId: string(),
callId: string(),
clientId: string()
}), commandUnhandledSchema = object({
serviceId: string(),
callId: string(),
clientId: string()
}), commandResultSchema = object({
serviceId: string(),
callId: string(),
result: optional(unknown()),
clientId: string()
}), commandErrorSchema = object({
serviceId: string(),
callId: string(),
error: custom(
(value) => typeof value == "object" && value !== null && !Array.isArray(value)
),
clientId: string()
});
function generateClientId() {
return nanoid();
}
// ../../node_modules/@preact/signals-core/dist/signals-core.mjs
var i = /* @__PURE__ */ Symbol.for("preact-signals");
function t() {
if (e > 1) {
e--;
return;
}
let i2, t2 = !1;
for ((function() {
let i3 = r;
for (r = void 0; i3 !== void 0; )
i3.S.v === i3.v && (i3.S.i = i3.i), i3 = i3.o;
})(); s !== void 0; ) {
let n3 = s;
for (s = void 0, u++; n3 !== void 0; ) {
let o3 = n3.u;
if (n3.u = void 0, n3.f &= -3, !(8 & n3.f) && w(n3)) try {
n3.c();
} catch (n4) {
t2 || (i2 = n4, t2 = !0);
}
n3 = o3;
}
}
if (u = 0, e--, t2) throw i2;
}
function n(i2) {
if (e > 0) return i2();
d = ++c, e++;
try {
return i2();
} finally {
t();
}
}
var o, s;
function h(i2) {
let t2 = o;
o = void 0;
try {
return i2();
} finally {
o = t2;
}
}
var r, f, e = 0, u = 0, c = 0, d = 0, v = 0;
function l(i2) {
if (o === void 0) return;
let t2 = i2.n;
if (t2 === void 0 || t2.t !== o)
return t2 = { i: 0, S: i2, p: o.s, n: void 0, t: o, e: void 0, x: void 0, r: t2 }, o.s !== void 0 && (o.s.n = t2), o.s = t2, i2.n = t2, 32 & o.f && i2.S(t2), t2;
if (t2.i === -1)
return t2.i = 0, t2.n !== void 0 && (t2.n.p = t2.p, t2.p !== void 0 && (t2.p.n = t2.n), t2.p = o.s, t2.n = void 0, o.s.n = t2, o.s = t2), t2;
}
function y(i2, t2) {
this.v = i2, this.i = 0, this.n = void 0, this.t = void 0, this.l = 0, this.W = t2?.watched, this.Z = t2?.unwatched, this.name = t2?.name;
}
y.prototype.brand = i;
y.prototype.h = function() {
return !0;
};
y.prototype.S = function(i2) {
let t2 = this.t;
t2 !== i2 && i2.e === void 0 && (i2.x = t2, this.t = i2, t2 !== void 0 ? t2.e = i2 : h(() => {
var i3;
(i3 = this.W) == null || i3.call(this);
}));
};
y.prototype.U = function(i2) {
if (this.t !== void 0) {
let t2 = i2.e, n3 = i2.x;
t2 !== void 0 && (t2.x = n3, i2.e = void 0), n3 !== void 0 && (n3.e = t2, i2.x = void 0), i2 === this.t && (this.t = n3, n3 === void 0 && h(() => {
var i3;
(i3 = this.Z) == null || i3.call(this);
}));
}
};
y.prototype.subscribe = function(i2) {
return j(() => {
let t2 = this.value, n3 = o;
o = void 0;
try {
i2(t2);
} finally {
o = n3;
}
}, { name: "sub" });
};
y.prototype.valueOf = function() {
return this.value;
};
y.prototype.toString = function() {
return this.value + "";
};
y.prototype.toJSON = function() {
return this.value;
};
y.prototype.peek = function() {
return h(() => this.value);
};
Object.defineProperty(y.prototype, "value", { get() {
let i2 = l(this);
return i2 !== void 0 && (i2.i = this.i), this.v;
}, set(i2) {
if (i2 !== this.v) {
if (u > 100) throw new Error("Cycle detected");
(function(i3) {
e !== 0 && u === 0 && i3.l !== d && (i3.l = d, r = { S: i3, v: i3.v, i: i3.i, o: r });
})(this), this.v = i2, this.i++, v++, e++;
try {
for (let i3 = this.t; i3 !== void 0; i3 = i3.x) i3.t.N();
} finally {
t();
}
}
} });
function a(i2, t2) {
return new y(i2, t2);
}
function w(i2) {
for (let t2 = i2.s; t2 !== void 0; t2 = t2.n) if (t2.S.i !== t2.i || !t2.S.h() || t2.S.i !== t2.i) return !0;
return !1;
}
function _(i2) {
for (let t2 = i2.s; t2 !== void 0; t2 = t2.n) {
let n3 = t2.S.n;
if (n3 !== void 0 && (t2.r = n3), t2.S.n = t2, t2.i = -1, t2.n === void 0) {
i2.s = t2;
break;
}
}
}
function b(i2) {
let t2, n3 = i2.s;
for (; n3 !== void 0; ) {
let i3 = n3.p;
n3.i === -1 ? (n3.S.U(n3), i3 !== void 0 && (i3.n = n3.n), n3.n !== void 0 && (n3.n.p = i3)) : t2 = n3, n3.S.n = n3.r, n3.r !== void 0 && (n3.r = void 0), n3 = i3;
}
i2.s = t2;
}
function p(i2, t2) {
y.call(this, void 0), this.x = i2, this.s = void 0, this.g = v - 1, this.f = 4, this.W = t2?.watched, this.Z = t2?.unwatched, this.name = t2?.name;
}
p.prototype = new y();
p.prototype.h = function() {
if (this.f &= -3, 1 & this.f) return !1;
if ((36 & this.f) == 32 || (this.f &= -5, this.g === v)) return !0;
if (this.g = v, this.f |= 1, this.i > 0 && !w(this))
return this.f &= -2, !0;
let i2 = o;
try {
_(this), o = this;
let i3 = this.x();
(16 & this.f || this.v !== i3 || this.i === 0) && (this.v = i3, this.f &= -17, this.i++);
} catch (i3) {
this.v = i3, this.f |= 16, this.i++;
}
return o = i2, b(this), this.f &= -2, !0;
};
p.prototype.S = function(i2) {
if (this.t === void 0) {
this.f |= 36;
for (let i3 = this.s; i3 !== void 0; i3 = i3.n) i3.S.S(i3);
}
y.prototype.S.call(this, i2);
};
p.prototype.U = function(i2) {
if (this.t !== void 0 && (y.prototype.U.call(this, i2), this.t === void 0)) {
this.f &= -33;
for (let i3 = this.s; i3 !== void 0; i3 = i3.n) i3.S.U(i3);
}
};
p.prototype.N = function() {
if (!(2 & this.f)) {
this.f |= 6;
for (let i2 = this.t; i2 !== void 0; i2 = i2.x) i2.t.N();
}
};
Object.defineProperty(p.prototype, "value", { get() {
if (1 & this.f) throw new Error("Cycle detected");
let i2 = l(this);
if (this.h(), i2 !== void 0 && (i2.i = this.i), 16 & this.f) throw this.v;
return this.v;
} });
function g(i2, t2) {
return new p(i2, t2);
}
function S(i2) {
let n3 = i2.m;
if (i2.m = void 0, typeof n3 == "function") {
e++;
let s3 = o;
o = void 0;
try {
n3();
} catch (t2) {
throw i2.f &= -2, i2.f |= 8, m(i2), t2;
} finally {
o = s3, t();
}
}
}
function m(i2) {
for (let t2 = i2.s; t2 !== void 0; t2 = t2.n) t2.S.U(t2);
i2.x = void 0, i2.s = void 0, S(i2);
}
function x(i2) {
if (o !== this) throw new Error("Out-of-order effect");
b(this), o = i2, this.f &= -2, 8 & this.f && m(this), t();
}
function E(i2, t2) {
this.x = i2, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t2?.name, f && f.push(this);
}
E.prototype.c = function() {
let i2 = this.S();
try {
if (8 & this.f || this.x === void 0) return;
let t2 = this.x();
typeof t2 == "function" && (this.m = t2);
} finally {
i2();
}
};
E.prototype.S = function() {
if (1 & this.f) throw new Error("Cycle detected");
this.f |= 1, this.f &= -9, S(this), _(this), e++;
let i2 = o;
return o = this, x.bind(this, i2);
};
E.prototype.N = function() {
2 & this.f || (this.f |= 2, this.u = s, s = this);
};
E.prototype.d = function() {
this.f |= 8, 1 & this.f || m(this);
};
E.prototype.dispose = function() {
this.d();
};
function j(i2, t2) {
let n3 = new E(i2, t2);
try {
n3.c();
} catch (i3) {
throw n3.d(), i3;
}
let o3 = n3.d.bind(n3);
return o3[Symbol.dispose] = o3, o3;
}
// ../../node_modules/deepsignal/core/dist/deepsignal-core.mjs
var n2 = /* @__PURE__ */ new WeakMap(), s2 = /* @__PURE__ */ new WeakMap(), a2 = /* @__PURE__ */ new WeakMap(), o2 = /* @__PURE__ */ new WeakSet(), l2 = /* @__PURE__ */ new WeakMap(), c2 = /^\$/, f2 = Object.getOwnPropertyDescriptor, g2 = !1, u2 = (e2) => {
if (!R(e2)) throw new Error("This object can't be observed.");
return s2.has(e2) || s2.set(e2, p2(e2, v2)), s2.get(e2);
};
var p2 = (e2, t2) => {
let r2 = new Proxy(e2, t2);
return o2.add(r2), r2;
}, y2 = () => {
throw new Error("Don't mutate the signals directly.");
}, w2 = (e2) => (o3, l3, u3) => {
var i2;
if (g2) return Reflect.get(o3, l3, u3);
let h2 = e2 || l3[0] === "$";
if (!e2 && h2 && Array.isArray(o3)) {
if (l3 === "$") return a2.has(o3) || a2.set(o3, p2(o3, d2)), a2.get(o3);
h2 = l3 === "$length";
}
n2.has(u3) || n2.set(u3, /* @__PURE__ */ new Map());
let y3 = n2.get(u3), w3 = h2 ? l3.replace(c2, "") : l3;
if (y3.has(w3) || typeof ((i2 = f2(o3, w3)) == null ? void 0 : i2.get) != "function") {
let e3 = Reflect.get(o3, w3, u3);
if (h2 && typeof e3 == "function") return;
if (typeof w3 == "symbol" && b2.has(w3)) return e3;
y3.has(w3) || (R(e3) && (s2.has(e3) || s2.set(e3, p2(e3, v2)), e3 = s2.get(e3)), y3.set(w3, a(e3)));
} else y3.set(w3, g(() => Reflect.get(o3, w3, u3)));
return h2 ? y3.get(w3) : y3.get(w3).value;
}, v2 = { get: w2(!1), set(r2, a3, o3, g3) {
var u3;
if (typeof ((u3 = f2(r2, a3)) == null ? void 0 : u3.set) == "function") return Reflect.set(r2, a3, o3, g3);
n2.has(g3) || n2.set(g3, /* @__PURE__ */ new Map());
let i2 = n2.get(g3);
if (a3[0] === "$") {
o3 instanceof y || y2();
let t2 = a3.replace(c2, "");
return i2.set(t2, o3), Reflect.set(r2, t2, o3.peek(), g3);
}
{
let e2 = o3;
R(o3) && (s2.has(o3) || s2.set(o3, p2(o3, v2)), e2 = s2.get(o3));
let n3 = !(a3 in r2), c3 = Reflect.set(r2, a3, o3, g3);
return i2.has(a3) ? i2.get(a3).value = e2 : i2.set(a3, a(e2)), n3 && l2.has(r2) && l2.get(r2).value++, Array.isArray(r2) && i2.has("length") && (i2.get("length").value = r2.length), c3;
}
}, deleteProperty(e2, t2) {
t2[0] === "$" && y2();
let r2 = n2.get(s2.get(e2)), a3 = Reflect.deleteProperty(e2, t2);
return r2 && r2.has(t2) && (r2.get(t2).value = void 0), l2.has(e2) && l2.get(e2).value++, a3;
}, ownKeys: (e2) => (l2.has(e2) || l2.set(e2, a(0)), l2._ = l2.get(e2).value, Reflect.ownKeys(e2)) }, d2 = { get: w2(!0), set: y2, deleteProperty: y2 }, b2 = new Set(Object.getOwnPropertyNames(Symbol).map((e2) => Symbol[e2]).filter((e2) => typeof e2 == "symbol")), m2 = /* @__PURE__ */ new Set([Object, Array]), R = (e2) => typeof e2 == "object" && e2 !== null && m2.has(e2.constructor) && !o2.has(e2);
// ../../node_modules/es-toolkit/dist/predicate/isPlainObject.mjs
function isPlainObject(value) {
if (!value || typeof value != "object")
return !1;
let proto = Object.getPrototypeOf(value);
return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null ? Object.prototype.toString.call(value) === "[object Object]" : !1;
}
// ../../node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs
function getSymbols(object2) {
return Object.getOwnPropertySymbols(object2).filter((symbol) => Object.prototype.propertyIsEnumerable.call(object2, symbol));
}
// ../../node_modules/es-toolkit/dist/compat/_internal/getTag.mjs
function getTag(value) {
return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value);
}
// ../../node_modules/es-toolkit/dist/compat/_internal/tags.mjs
var regexpTag = "[object RegExp]", stringTag = "[object String]", numberTag = "[object Number]", booleanTag = "[object Boolean]", argumentsTag = "[object Arguments]", symbolTag = "[object Symbol]", dateTag = "[object Date]", mapTag = "[object Map]", setTag = "[object Set]", arrayTag = "[object Array]", functionTag = "[object Function]", arrayBufferTag = "[object ArrayBuffer]", objectTag = "[object Object]", errorTag = "[object Error]", dataViewTag = "[object DataView]", uint8ArrayTag = "[object Uint8Array]", uint8ClampedArrayTag = "[object Uint8ClampedArray]", uint16ArrayTag = "[object Uint16Array]", uint32ArrayTag = "[object Uint32Array]", bigUint64ArrayTag = "[object BigUint64Array]", int8ArrayTag = "[object Int8Array]", int16ArrayTag = "[object Int16Array]", int32ArrayTag = "[object Int32Array]", bigInt64ArrayTag = "[object BigInt64Array]", float32ArrayTag = "[object Float32Array]", float64ArrayTag = "[object Float64Array]";
// ../../node_modules/es-toolkit/dist/compat/util/eq.mjs
function eq(value, other) {
return value === other || Number.isNaN(value) && Number.isNaN(other);
}
// ../../node_modules/es-toolkit/dist/predicate/isEqualWith.mjs
function isEqualWith(a3, b3, areValuesEqual) {
return isEqualWithImpl(a3, b3, void 0, void 0, void 0, void 0, areValuesEqual);
}
function isEqualWithImpl(a3, b3, property, aParent, bParent, stack, areValuesEqual) {
let result = areValuesEqual(a3, b3, property, aParent, bParent, stack);
if (result !== void 0)
return result;
if (typeof a3 == typeof b3)
switch (typeof a3) {
case "bigint":
case "string":
case "boolean":
case "symbol":
case "undefined":
return a3 === b3;
case "number":
return a3 === b3 || Object.is(a3, b3);
case "function":
return a3 === b3;
case "object":
return areObjectsEqual(a3, b3, stack, areValuesEqual);
}
return areObjectsEqual(a3, b3, stack, areValuesEqual);
}
function areObjectsEqual(a3, b3, stack, areValuesEqual) {
if (Object.is(a3, b3))
return !0;
let aTag = getTag(a3), bTag = getTag(b3);
if (aTag === argumentsTag && (aTag = objectTag), bTag === argumentsTag && (bTag = objectTag), aTag !== bTag)
return !1;
switch (aTag) {
case stringTag:
return a3.toString() === b3.toString();
case numberTag: {
let x2 = a3.valueOf(), y3 = b3.valueOf();
return eq(x2, y3);
}
case booleanTag:
case dateTag:
case symbolTag:
return Object.is(a3.valueOf(), b3.valueOf());
case regexpTag:
return a3.source === b3.source && a3.flags === b3.flags;
case functionTag:
return a3 === b3;
}
stack = stack ?? /* @__PURE__ */ new Map();
let aStack = stack.get(a3), bStack = stack.get(b3);
if (aStack != null && bStack != null)
return aStack === b3;
stack.set(a3, b3), stack.set(b3, a3);
try {
switch (aTag) {
case mapTag: {
if (a3.size !== b3.size)
return !1;
for (let [key, value] of a3.entries())
if (!b3.has(key) || !isEqualWithImpl(value, b3.get(key), key, a3, b3, stack, areValuesEqual))
return !1;
return !0;
}
case setTag: {
if (a3.size !== b3.size)
return !1;
let aValues = Array.from(a3.values()), bValues = Array.from(b3.values());
for (let i2 = 0; i2 < aValues.length; i2++) {
let aValue = aValues[i2], index = bValues.findIndex((bValue) => isEqualWithImpl(aValue, bValue, void 0, a3, b3, stack, areValuesEqual));
if (index === -1)
return !1;
bValues.splice(index, 1);
}
return !0;
}
case arrayTag:
case uint8ArrayTag:
case uint8ClampedArrayTag:
case uint16ArrayTag:
case uint32ArrayTag:
case bigUint64ArrayTag:
case int8ArrayTag:
case int16ArrayTag:
case int32ArrayTag:
case bigInt64ArrayTag:
case float32ArrayTag:
case float64ArrayTag: {
if (typeof Buffer < "u" && Buffer.isBuffer(a3) !== Buffer.isBuffer(b3) || a3.length !== b3.length)
return !1;
for (let i2 = 0; i2 < a3.length; i2++)
if (!isEqualWithImpl(a3[i2], b3[i2], i2, a3, b3, stack, areValuesEqual))
return !1;
return !0;
}
case arrayBufferTag:
return a3.byteLength !== b3.byteLength ? !1 : areObjectsEqual(new Uint8Array(a3), new Uint8Array(b3), stack, areValuesEqual);
case dataViewTag:
return a3.byteLength !== b3.byteLength || a3.byteOffset !== b3.byteOffset ? !1 : areObjectsEqual(new Uint8Array(a3), new Uint8Array(b3), stack, areValuesEqual);
case errorTag:
return a3.name === b3.name && a3.message === b3.message;
case objectTag: {
if (!(areObjectsEqual(a3.constructor, b3.constructor, stack, areValuesEqual) || isPlainObject(a3) && isPlainObject(b3)))
return !1;
let aKeys = [...Object.keys(a3), ...getSymbols(a3)], bKeys = [...Object.keys(b3), ...getSymbols(b3)];
if (aKeys.length !== bKeys.length)
return !1;
for (let i2 = 0; i2 < aKeys.length; i2++) {
let propKey = aKeys[i2], aProp = a3[propKey];
if (!Object.hasOwn(b3, propKey))
return !1;
let bProp = b3[propKey];
if (!isEqualWithImpl(aProp, bProp, propKey, a3, b3, stack, areValuesEqual))
return !1;
}
return !0;
}
default:
return !1;
}
} finally {
stack.delete(a3), stack.delete(b3);
}
}
// ../../node_modules/es-toolkit/dist/function/noop.mjs
function noop() {
}
// ../../node_modules/es-toolkit/dist/predicate/isEqual.mjs
function isEqual(a3, b3) {
return isEqualWith(a3, b3, noop);
}
// ../../node_modules/es-toolkit/dist/predicate/isPrimitive.mjs
function isPrimitive(value) {
return value == null || typeof value != "object" && typeof value != "function";
}
// ../../node_modules/es-toolkit/dist/predicate/isTypedArray.mjs
function isTypedArray(x2) {
return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}
// src/shared/open-service/query-state.ts
function buildQueryState(data, lifecycle) {
let isPending = lifecycle.status === "pending", isLoading = lifecycle.loadStatus === "loading";
return {
data,
error: lifecycle.error,
status: lifecycle.status,
loadStatus: lifecycle.loadStatus,
isPending,
isSuccess: lifecycle.status === "success",
isError: lifecycle.status === "error",
isLoading,
isInitialLoading: isPending && isLoading && data === void 0,
isRefreshing: isLoading && !isPending
};
}
function toError(value) {
return value instanceof Error ? value : new Error(String(value));
}
// src/shared/open-service/service-validation.ts
function rethrowAsync(error) {
queueMicrotask(() => {
throw error;
});
}
async function validateSchema(schema, value, meta) {
let validationResult = await schema["~standard"].validate(value);
if (validationResult.issues)
throw new OpenServiceValidationError({ ...meta, issues: validationResult.issues });
return validationResult.value;
}
function validateSchemaSync(schema, value, meta) {
let validationResult = schema["~standard"].validate(value);
if (validationResult instanceof Promise)
throw new OpenServiceAsyncSchemaError({
kind: meta.kind,
serviceId: meta.serviceId,
name: meta.name,
phase: meta.phase
});
if (validationResult.issues)
throw new OpenServiceValidationError({ ...meta, issues: validationResult.issues });
return validationResult.value;
}
// src/shared/open-service/query-runtime.ts
var MAX_DRAIN_ITERATIONS = 32, inFlightLoads = /* @__PURE__ */ new Map(), nextRuntimeSequence = 0, nextRuntimeId = () => String(nextRuntimeSequence += 1), activeHandlerLoadSession, EMPTY_SET = /* @__PURE__ */ new Set();
function stableHash(value) {
let encode = (raw) => {
if (raw === void 0)
return { __t: "undefined" };
if (raw === null || typeof raw != "object")
return raw;
if (Array.isArray(raw))
return raw.map(encode);
let sorted = {};
for (let k of Object.keys(raw).sort())
sorted[k] = encode(raw[k]);
return { __t: "object", value: sorted };
};
return JSON.stringify(encode(value));
}
function makeInFlightKey(runtimeId, loadKey) {
return `${runtimeId}::${loadKey}`;
}
function makeLoadKey(serviceId, queryName, validatedInput) {
return `${serviceId}::${queryName}::${stableHash(validatedInput)}`;
}
function surfaceRejections(settlements) {
let rejections = settlements.filter((s3) => s3.status === "rejected");
if (rejections.length === 0)
return;
let [first, ...rest] = rejections.map((r2) => r2.reason);
if (rest.length > 0 && first instanceof Error && Reflect.get(first, "cause") === void 0)
try {
Reflect.set(first, "cause", { aggregated: rest });
} catch {
}
throw first;
}
async function drainCollector(collector, settledKeys, serviceId, queryName) {
let iterations = 0;
for (; collector.size > 0; ) {
if (iterations++ > MAX_DRAIN_ITERATIONS)
throw new OpenServiceLoadedDrainExceededError({
serviceId,
name: queryName,
iterations: MAX_DRAIN_ITERATIONS
});
let pending = [...collector];
collector.clear();
let settlements = await Promise.allSettled(pending.map((entry) => entry.promise));
if (settledKeys)
for (let entry of pending)
settledKeys.add(entry.key);
surfaceRejections(settlements);
}
}
function detachSnapshot(value) {
return value === null || typeof value != "object" ? value : JSON.parse(JSON.stringify(value));
}
function validateQueryInput(refs, queryName, queryDef, input) {
return validateSchemaSync(queryDef.input, input, {
kind: "query",
serviceId: refs.serviceId,
name: queryName,
phase: "input"
});
}
function validateQueryOutput(refs, queryName, queryDef, output) {
return validateSchemaSync(queryDef.output, output, {
kind: "query",
serviceId: refs.serviceId,
name: queryName,
phase: "output"
});
}
function runHandlerSync(refs, queryName, queryDef, validatedInput, selfQueries, getService2) {
if (!queryDef.handler)
throw new OpenServiceUnimplementedOperationError({
kind: "query",
serviceId: refs.serviceId,
name: queryName
});
let handlerCtx = { self: {
get state() {
return refs.state;
},
queries: selfQueries
}, getService: getService2 };
return queryDef.handler(validatedInput, handlerCtx);
}
function createQueryGet(refs, queryName, queryDef, selfQueries, fireLoad) {
return function(input) {
let validatedInput = validateQueryInput(
refs,
queryName,
queryDef,
arguments.length === 0 ? void 0 : input
);
return queryDef.load && fireLoad?.(validatedInput), validateQueryOutput(
refs,
queryName,
queryDef,
runHandlerSync(
refs,
queryName,
queryDef,
validatedInput,
selfQueries,
refs.registryApi.getService
)
);
};
}
function triggerLoad(refs, queryName, queryDef, validatedInput, loadKey, parentAncestorChain) {
let inFlightKey = makeInFlightKey(refs.runtimeId, loadKey), existing = inFlightLoads.get(inFlightKey);
if (existing)
return existing;
let extendedChain = new Set(parentAncestorChain);
extendedChain.add(loadKey);
let promise = Promise.resolve().then(() => runLoadBody(refs, queryName, queryDef, validatedInput, extendedChain)).finally(() => {
inFlightLoads.get(inFlightKey) === promise && inFlightLoads.delete(inFlightKey);
});
return inFlightLoads.set(inFlightKey, promise), promise;
}
async function runLoadBody(refs, queryName, queryDef, validatedInput, ancestorChain) {
if (!queryDef.load)
return;
let collector = /* @__PURE__ */ new Set(), wrappedQueries = buildLoadWrappedQueries(refs, ancestorChain, collector), loadCtx = { self: {
get state() {
return refs.state;
},
queries: wrappedQueries,
commands: refs.getLoadCommands()
}, getService: refs.registryApi.getService };
await Promise.resolve(queryDef.load(validatedInput, loadCtx)), await drainCollector(collector, void 0, refs.serviceId, queryName);
}
async function runReactiveLoad(refs, queryName, queryDef, validatedInput, isCurrent) {
if (!queryDef.load)
return;
let loadCtx = { self: {
get state() {
return refs.state;
},
// Reactive-load reads must keep dependency loads warm. `.get()` on a default query is a pure
// read and never fires a load, so the body sees fire-and-forget wrappers instead: reading a
// dependency triggers its load (deduped while in flight) without awaiting a drain.
queries: refs.reactiveLoadQueries,
commands: refs.buildGatedCommands(isCurrent)
}, getService: refs.registryApi.getService };
await Promise.resolve(queryDef.load(validatedInput, loadCtx));
}
function buildReactiveLoadQueries(refs) {
let wrappedQueries = {};
for (let [name, queryDef] of refs.queryDefinitions) {
let defaultQuery = refs.defaultQueries[name], get = createQueryGet(refs, name, queryDef, wrappedQueries, (validatedInput) => {
let loadKey = makeLoadKey(refs.serviceId, name, validatedInput);
triggerLoad(refs, name, queryDef, validatedInput, loadKey, EMPTY_SET).catch(rethrowAsync);
});
wrappedQueries[name] = {
get,
loaded: defaultQuery.loaded,
subscribe: defaultQuery.subscribe
};
}
return wrappedQueries;
}
function buildLoadWrappedQueries(refs, ancestorChain, collector) {
let wrappedQueries = {};
for (let [name, queryDef] of refs.queryDefinitions) {
let defaultQuery = refs.defaultQueries[name], wrapped = {
get: createQueryGet(refs, name, queryDef, wrappedQueries, (validatedInput) => {
let loadKey = makeLoadKey(refs.serviceId, name, validatedInput), promise = triggerLoad(refs, name, queryDef, validatedInput, loadKey, ancestorChain);
ancestorChain.has(loadKey) || collector.add({ key: loadKey, promise });
}),
loaded(input) {
return runLoaded(
refs,
name,
queryDef,
arguments.length === 0 ? void 0 : input,
ancestorChain
);
},
subscribe: defaultQuery.subscribe
};
wrappedQueries[name] = wrapped;
}
return wrappedQueries;
}
async function runLoaded(refs, queryName, queryDef, rawInput, parentAncestorChain = EMPTY_SET) {
let validatedInput = validateQueryInput(refs, queryName, queryDef, rawInput), loadKey = makeLoadKey(refs.serviceId, queryName, validatedInput), ancestorChain = new Set(parentAncestorChain);
ancestorChain.add(loadKey);
let session = {
ancestorChain,
collector: /* @__PURE__ */ new Set(),
settledKeys: /* @__PURE__ */ new Set()
};
if (queryDef.load && !parentAncestorChain.has(loadKey)) {
let promise = triggerLoad(
refs,
queryName,
queryDef,
validatedInput,
loadKey,
parentAncestorChain
);
session.collector.add({ key: loadKey, promise });
}
let iterations = 0, hasMoreWork = !0;
for (; hasMoreWork; ) {
if (iterations++ > MAX_DRAIN_ITERATIONS)
throw new OpenServiceLoadedDrainExceededError({
serviceId: refs.serviceId,
name: queryName,
iterations: MAX_DRAIN_ITERATIONS
});
for (; session.collector.size > 0; ) {
let pending = [...session.collector];
session.collector.clear();
let settlements = await Promise.allSettled(pending.map((entry) => entry.promise));
for (let entry of pending)
session.settledKeys.add(entry.key);
surfaceRejections(settlements);
}
let previousSession2 = activeHandlerLoadSession;
activeHandlerLoadSession = session;
try {
runHandlerSync(
refs,
queryName,
queryDef,
validatedInput,
refs.defaultQueries,
refs.registryApi.getService
);
} catch {
} finally {
activeHandlerLoadSession = previousSession2;
}
hasMoreWork = session.collector.size > 0;
}
let previousSession = activeHandlerLoadSession;
activeHandlerLoadSession = session;
try {
return validateQueryOutput(
refs,
queryName,
queryDef,
runHandlerSync(
refs,
queryName,
queryDef,
validatedInput,
refs.defaultQueries,
refs.registryApi.getService
)
);
} finally {
activeHandlerLoadSession = previousSession;
}
}
function createDefaultQuery(refs, queryName, queryDef) {
let resolveInput = (input, argsLength) => argsLength === 0 ? void 0 : input;
return {
get: createQueryGet(refs, queryName, queryDef, refs.defaultQueries, (validatedInput) => {
let session = activeHandlerLoadSession;
if (!session)
return;
let loadKey = makeLoadKey(refs.serviceId, queryName, validatedInput);
if (!session.ancestorChain.has(loadKey) && !session.settledKeys.has(loadKey)) {
let promise = triggerLoad(
refs,
queryName,
queryDef,
validatedInput,
loadKey,
session.ancestorChain
);
session.collector.add({ key: loadKey, promise });
}
}),
loaded(input) {
return runLoaded(refs, queryName, queryDef, resolveInput(input, arguments.length));
},
subscribe: ((...args) => {
if (args.length === 1 && typeof args[0] == "function")
return subscribeToQuery(
refs,
queryName,
queryDef,
void 0,
void 0,
args[0]
);
if (args.length === 2 && typeof args[0] == "function" && typeof args[1] == "function")
return subscribeToQuery(
refs,
queryName,
queryDef,
void 0,
args[0],
args[1]
);
let [input, selectorOrCallback, maybeCallback] = args;
return subscribeToQuery(
refs,
queryName,
queryDef,
input,
maybeCallback ? selectorOrCallback : void 0,
maybeCallback ?? selectorOrCallback
);
})
};
}
function subscribeToQuery(refs, queryName, queryDef, rawInput, selector, callback) {
let active = !0, validatedInput;
try {
validatedInput = validateQueryInput(refs, queryName, queryDef, rawInput);
} catch (error) {
return callback(
buildQueryState(void 0, { status: "error", error: toError(error), loadStatus: "idle" })
), () => {
active = !1;
};
}
let lifecycle = a({
status: queryDef.load ? "pending" : "success",
error: void 0,
loadStatus: "idle"
}), loadTeardown;
if (queryDef.load) {
let epoch = 0;
loadTeardown = j(() => {
let myEpoch = ++epoch, isCurrent = () => myEpoch === epoch, previous = h(() => lifecycle.value);
lifecycle.value = {
status: previous.status,
error: previous.error,
loadStatus: "loading"
}, runReactiveLoad(refs, queryName, queryDef, validatedInput, isCurrent).then(
() => {
isCurrent() && (lifecycle.value = { status: "success", error: void 0, loadStatus: "idle" });
},
(error) => {
isCurrent() && (lifecycle.value = { status: "error", error: toError(error), loadStatus: "idle" });
}
);
});
}
let comp = g(() => {
let output = runHandlerSync(
refs,
queryName,
queryDef,
validatedInput,
refs.defaultQueries,
refs.registryApi.getService
);
if (selector) {
let validated = h(() => validateQueryOutput(refs, queryName, queryDef, output));
return selector(output), detachSnapshot(selector(validated));
}
return detachSnapshot(validateQueryOutput(refs, queryName, queryDef, output));
}), hasEmitted = !1, lastEmitted, lastData, teardown = j(() => {
let life = lifecycle.value, data, status = life.status, error = life.error;
try {
data = comp.value, lastData = data;
} catch (handlerError) {
data = lastData, status = "error", error = toError(handlerError);
}
if (!active)
return;
let state = buildQueryState(data, { status, error, loadStatus: life.loadStatus });
hasEmitted && isEqual(state, lastEmitted) || (hasEmitted = !0, lastEmitted = state, callback(state));
});
return () => {
active = !1, teardown(), loadTeardown?.();
};
}
function buildQueries(refs) {
let result = {};
for (let [name, queryDef] of refs.queryDefinitions)
result[name] = createDefaultQuery(refs, name, queryDef);
return result;
}
// src/shared/open-service/service-sync.ts
function isNewer(incoming, local) {
return incoming.version !== local.version ? incoming.version > local.version : incoming.clientId > local.clientId;
}
var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function isPlainObject2(value) {
return typeof value == "object" && value !== null && !Array.isArray(value);
}
function applyStatePatch(target, source, options) {
if (!options.preserveMissingKeys)
for (let key of Object.keys(target))
FORBIDDEN_KEYS.has(key) || Object.prototype.hasOwnProperty.call(source, key) || delete target[key];
for (let key of Object.keys(source)) {
if (FORBIDDEN_KEYS.has(key))
continue;
let sourceValue = source[key], tarvalue = target[key];
isPlainObject2(sourceValue) && isPlainObject2(tarvalue) ? applyStatePatch(tarvalue, sourceValue, options) : tarvalue !== sourceValue && (target[key] = sourceValue);
}
}
function createSnapshotReconciler(options) {
let { setState, initialStamp } = options, localStamp = initialStamp;
return {
get stamp() {
return localStamp;
},
advanceLocal(clientId) {
return localStamp = { version: localStamp.version + 1, clientId }, localStamp;
},
tryAdopt(incoming, state) {
return isNewer(incoming, localStamp) ? (localStamp = { version: incoming.version, clientId: incoming.clientId }, setState((current) => applyStatePatch(current, state, { preserveMissingKeys: !1 })), !0) : !1;
}
};
}
// src/shared/open-service/service-runtime.ts
function normalizeStaticStoragePath(serviceId, name, rawPath) {
let segments = rawPath.replaceAll("\\", "/").split("/").filter((segment) => segment.length > 0 && segment !== ".");
if (segments.length === 0 || segments.some((segment) => segment === ".."))
throw new OpenServiceInvalidStaticPathError({ serviceId, name, path: rawPath });
return segments.join("/");
}
function resolveStaticPath(serviceId, name, queryDef, input) {
let rawPath = queryDef.staticPath(input), relativePath = normalizeStaticStoragePath(serviceId, name, rawPath);
return `${serviceId}/${relativePath}`;
}
function createCommandSelf(state) {
return {
get state() {
return state;
},
setState(mutate) {
n(() => {
mutate(state);
});
},
queries: {},
commands: {}
};
}
function buildCommands(serviceId, commands, createCommandCtx) {
return Object.fromEntries(
Object.entries(commands).map(([name, def]) => [
name,
async (input) => {
if (!def.handler)
throw new OpenServiceUnimplementedOperationError({
kind: "command",
serviceId,
name
});
let validatedInput = await validateSchema(def.input, input, {
kind: "command",
serviceId,
name,
phase: "input"
}), output = await def.handler(validatedInput, createCommandCtx());
return validateSchema(def.output, output, {
kind: "command",
serviceId,
name,
phase: "output"
});
}
])
);
}
function buildQueryDefinitionsWithStaticLoader(serviceId, queries, staticLoader, setState) {
return new Map(
Object.entries(queries).map(([name, queryDef]) => {
if (!queryDef.staticPath)
return [name, queryDef];
let { staticPath } = queryDef;
return [
name,
{
...queryDef,
load: async (input) => {
let logicalPath = resolveStaticPath(serviceId, name, { staticPath }, input), snapshot = await staticLoader(logicalPath, {
serviceId,
queryName: name,
input
});
setState((state) => {
applyStatePatch(state, snapshot, {
preserveMissingKeys: !0
});
});
}
}
];
})
);
}
function createServiceRuntime(def, runtimeOptions, initialState = def.initialState) {
let rawState = initialState, state = u2(rawState), getStateSnapshot = () => structuredClone(rawState), commandSelf = createCommandSelf(state), { registryApi, staticLoader } = runtimeOptions, createCommandCtx = () => ({
self: commandSelf,
getService: registryApi.getService
}), commands = buildCommands(def.id, def.commands, createCommandCtx);
commandSelf.commands = commands;
let loadCommands = commands, remoteCommandNames = /* @__PURE__ */ new Set(), queryDefinitions = staticLoader ? buildQueryDefinitionsWithStaticLoader(
def.id,
def.queries,
staticLoader,
commandSelf.setState
) : new Map(
Object.entries(def.queries)
), defaultQueries = {}, reactiveLoadQueries = {}, buildGatedCommands = (isCurrent) => {
let gatedSelf = {
get state() {
return state;
},
setState(mutate) {
isCurrent() && n(() => {
mutate(state);
});
},
queries: defaultQueries,
commands: {}
}, gated = buildCommands(def.id, def.commands, () => ({
self: gatedSelf,
getService: registryApi.getService
}));
return gatedSelf.commands = gated, remoteCommandNames.size === 0 ? gated : Object.fromEntries(
Object.keys(def.commands).map((name) => [
name,
remoteCommandNames.has(name) ? loadCommands[name] : gated[name]
])
);
}, runtimeId = nextRuntimeId(), refs = {
serviceId: def.id,
runtimeId,
commandSelf,
state,
registryApi,
queryDefinitions,
defaultQueries,
reactiveLoadQueries,
getLoadCommands: () => loadCommands,
buildGatedCommands
}, builtQueries = buildQueries(refs);
for (let [name, query] of Object.entries(builtQueries))
defaultQueries[name] = query;
for (let [name, query] of Object.entries(buildReactiveLoadQueries(refs)))
reactiveLoadQueries[name] = query;
commandSelf.queries = defaultQueries;
let queries = defaultQueries, queryCtx = { self: {
get state() {
return state;
},
queries: defaultQueries
}, getService: registryApi.getService }, loadCtxForStatic = {
self: {
get state() {
return state;
},
queries: defaultQueries,
commands
},
getService: registryApi.getService
};
return {
getStateSnapshot,
commandSelf,
queryCtx,
loadCtxForStatic,
commands,
queries,
runLoadOnce: async (queryName, validatedInput) => {
let queryDef = queryDefinitions.get(queryName);
if (!queryDef || !queryDef.load)
return;
let loadKey = makeLoadKey(def.id, queryName, validatedInput), ancestorChain = /* @__PURE__ */ new Set([loadKey]), inFlightKey = makeInFlightKey(runtimeId, loadKey), promise = Promise.resolve().then(() => runLoadBody(refs, queryName, queryDef, validatedInput, ancestorChain)).finally(() => {
inFlightLoads.get(inFlightKey) === promise && inFlightLoads.delete(inFlightKey);
});
inFlightLoads.set(inFlightKey, promise), await promise;
},
attachChannelCommands: (channelCommands, implementedCommandNames) => {
loadCommands = channelCommands, remoteCommandNames.clear();
for (let name of Object.keys(def.commands))
implementedCommandNames.has(name) || remoteCommandNames.add(name);
}
};
}
// src/shared/open-service/service-transport.ts
var REMOTE_COMMAND_ACK_TIMEOUT_MS = 300;
function wrapCommandsForBroadcast(commands, context) {
let { serviceId, ownClientId, reconciler, getSnapshot, channel: channel2 } = context;
return Object.fromEntries(
Object.entries(commands).map(([name, cmd]) => [
name,
async (input) => {
let result = await cmd(input), stamp = reconciler.advanceLocal(ownClientId);
return channel2.emit(SERVICE_PATCHES, {
serviceId,
state: getSnapshot(),
version: stamp.version,
clientId: stamp.clientId
}), result;
}
])
);
}
function connectRuntimeToChannel(context) {
let { serviceId, ownClientId, reconciler, getSnapshot, channel: channel2, relay } = context, emitSyncStart = () => {
channel2.emit(SERVICE_SYNC_START, {
serviceId,
clientId: ownClientId
});
}, relayAdopted = () => {
channel2.emit(SERVICE_PATCHES, {
serviceId,
state: getSnapshot(),
version: reconciler.stamp.version,
clientId: reconciler.stamp.clientId
});
}, adoptPeerSnapshot = (snapshot) => {
let adopted = reconciler.tryAdopt(
{ version: snapshot.version, clientId: snapshot.clientId },
snapshot.state
);
return adopted && relay && relayAdopted(), adopted;
}, onSyncStart = (payload) => {
let request = safeParse(syncStartSchema, payload);
!request.success || request.output.serviceId !== serviceId || request.output.clientId === ownClientId || channel2.emit(SERVICE_SYNC_START_REPLY, {
serviceId,
state: getSnapshot(),
version: reconciler.stamp.version,
clientId: reconciler.stamp.clientId
});
}, onSyncStartReply = (payload) => {
let snapshot = safeParse(stampedSnapshotSchema, payload);
!snapshot.success || snapshot.output.serviceId !== serviceId || adoptPeerSnapshot(snapshot.output);
}, onPatches = (payload) => {
let snapshot = safeParse(stampedSnapshotSchema, payload);
!snapshot.success || snapshot.output.serviceId !== serviceId || adoptPeerSnapshot(snapshot.output);
};
return channel2.on(SERVICE_SYNC_START, onSyncStart), channel2.on(SERVICE_SYNC_START_REPLY, onSyncStartReply), channel2.on(SERVICE_PATCHES, onPatches), emitSyncStart(), relay && reconciler.stamp.version > 0 && relayAdopted(), () => {
channel2.off(SERVICE_SYNC_START, onSyncStart), channel2.off(SERVICE_SYNC_START_REPLY, onSyncStartReply), channel2.off(SERVICE_PATCHES, onPatches);
};
}
function connectCommandTransport(context) {
let {
serviceId,
ownClientId,
channel: channel2,
localCommands,
implementedCommandNames,
commandNames,
delegated
} = context, dispatchesLocally = (commandName) => !delegated && implementedCommandNames.has(commandName), pending = /* @__PURE__ */ new Map(), settle = (callId, apply) => {
let entry = pending.get(callId);
entry && (pending.delete(callId), clearTimeout(entry.noAckTimer), apply(entry));
}, onInvoke = (payload) => {
let parsed = safeParse(commandInvokeSchema, payload);
if (!parsed.success || parsed.output.serviceId !== serviceId)
return;
let invoke = parsed.output;
if (!dispatchesLocally(invoke.commandName)) {
!delegated && invoke.clientId !== ownClientId && channel2.emit(SERVICE_COMMAND_UNHANDLED, {
serviceId,
callId: invoke.callId,
clientId: ownClientId
});
return;
}
channel2.emit(SERVICE_COMMAND_ACK, {
serviceId,
callId: invoke.callId,
clientId: ownClientId
}), setTimeout(() => {
Promise.resolve().then(() => localCommands[invoke.commandName](invoke.input)).then(
(result) => {
channel2.emit(SERVICE_COMMAND_RESULT, {
serviceId,
callId: invoke.callId,
result,
clientId: ownClientId
});
},
(error) => {
channel2.emit(SERVICE_COMMAND_ERROR, {
serviceId,
callId: invoke.callId,
error: serializeError(error),
clientId: ownClientId
});
}
);
}, 0);
}, onResult = (payload) => {
let result = safeParse(commandResultSchema, payload);
!result.success || result.output.serviceId !== serviceId || settle(result.output.callId, (entry) => entry.resolve(result.output.result));
}, onError = (payload) => {
let failure = safeParse(commandErrorSchema, payload);
!failure.success || failure.output.serviceId !== serviceId || settle(failure.output.callId, (entry) => entry.reject(deserializeError(failure.output.error)));
}, onAck = (payload) => {
let ack = safeParse(commandAckSchema, payload);
if (!ack.success || ack.output.serviceId !== serviceId)
return;
let entry = pending.get(ack.output.callId);
entry && clearTimeout(entry.noAckTimer);
}, onUnhandled = (payload) => {
let report = safeParse(commandUnhandledSchema, payload);
!report.success || report.output.serviceId !== serviceId || !delegated || settle(
report.output.callId,
(entry) => entry.reject(
new OpenServiceRemoteCommandConfigDriftError({
serviceId,
commandName: entry.commandName
})
)
);
};
channel2.on(SERVICE_COMMAND_INVOKE, onInvoke), channel2.on(SERVICE_COMMAND_RESULT, onResult), channel2.on(SERVICE_COMMAND_ERROR, onError), channel2.on(SERVICE_COMMAND_ACK, onAck), channel2.on(SERVICE_COMMAND_UNHANDLED, onUnhandled);
let requestRemote = (commandName, input) => {
let callId = generateClientId();
return new Promise((resolve, reject) => {
let noAckTimer = setTimeout(() => {
settle(
callId,
(entry) => entry.reject(
new OpenServiceRemoteCommandUnhandledError({
serviceId,
commandName: entry.commandName,
delegated
})
)
);
}, REMOTE_COMMAND_ACK_TIMEOUT_MS);
pending.set(callId, { commandName, resolve, reject, noAckTimer }), channel2.emit(SERVICE_COMMAND_INVOKE, {
serviceId,
commandName,
input,
callId,
clientId: ownClientId
});
});
}, commands = {};
for (let name of commandNames)
commands[name] = dispatchesLocally(name) ? localCommands[name] : (input) => requestRemote(name, input);
return {
commands,
disconnect: () => {
channel2.off(SERVICE_COMMAND_INVOKE, onInvoke), channel2.off(SERVICE_COMMAND_RESULT, onResult), channel2.off(SERVICE_COMMAND_ERROR, onError), channel2.off(SERVICE_COMMAND_ACK, onAck), channel2.off(SERVICE_COMMAND_UNHANDLED, onUnhandled);
for (let [, entry] of pending)
clearTimeout(entry.noAckTimer), entry.reject(new OpenServiceRemoteCommandDisconnectedError({ serviceId }));
pending.clear();
}
};
}
function connectUnknownServiceReporter(context) {
let { channel: channel2, isServiceRegistered, isDelegated } = context, ownClientId = generateClientId(), onInvoke = (payload) => {
let parsed = safeParse(commandInvokeSchema, payload);
!parsed.success || isDelegated() || isServiceRegistered(parsed.output.serviceId) || channel2.emit(SERVICE_COMMAND_UNHANDLED, {
serviceId: parsed.output.serviceId,
callId: parsed.output.callId,
clientId: ownClientId
});
};
return channel2.on(SERVICE_COMMAND_INVOKE, onInvoke), () => {
channel2.off(SERVICE_COMMAND_INVOKE, onInvoke);
};
}
function connectServiceToChannel(context) {
let {
serviceId,
ownClientId,
reconciler,
getSnapshot,
channel: channel2,
relay,
commands,
implementedCommandNames,
commandNames,
delegated,
runtime
} = context, broadcastCommands = wrapCommandsForBroadcast(commands, {
serviceId,
ownClientId,
reconciler,
getSnapshot,
channel: channel2
}), commandTransport = connectCommandTransport({
serviceId,
ownClientId,
channel: channel2,
localCommands: broadcastCommands,
implementedCommandNames,
commandNames,
delegated
}), disconnectSync = connectRuntimeToChannel({
serviceId,
ownClientId,
reconciler,
getSnapshot,
channel: channel2,
relay
});
return runtime.attachChannelCommands(
commandTransport.commands,
delegated ? /* @__PURE__ */ new Set() : implementedCommandNames
), {
commands: commandTransport.commands,
disconnect: () => {
disconnectSync(), commandTransport.disconnect();
}
};
}
// src/shared/open-service/service-registry.ts
var REGISTRY_SYMBOL = /* @__PURE__ */ Symbol.for("storybook.open-service.registry");
function getInventory() {
let registryGlobal = globalThis;
return registryGlobal[REGISTRY_SYMBOL] ??= {
entries: /* @__PURE__ */ new Map(),
delegatedMode: !1,
everRegisteredIds: /* @__PURE__ */ new Set()
}, registryGlobal[REGISTRY_SYMBOL];
}
function getRegistry() {
return getInventory().entries;
}
function setDelegatedMode(enabled) {
getInventory().delegatedMode = enabled;
}
function isDelegatedMode() {
return getInventory().delegatedMode;
}
function ensureUnknownServiceReporter(channel2) {
let inventory = getInventory();
inventory.unknownServiceReporter?.channel !== channel2 && (inventory.unknownServiceReporter?.disconnect(), inventory.unknownServiceReporter = {
channel: channel2,
disconnect: connectUnknownServiceReporter({
channel: channel2,
isServiceRegistered: (serviceId) => inventory.everRegisteredIds.has(serviceId),
isDelegated: () => inventory.delegatedMode
})
});
}
function assertUniqueOperationNames(definition) {
let duplicateName = Object.keys(definition.queries).find(
(name) => Object.hasOwn(definition.commands, name)
);
if (duplicateName)
throw new OpenServiceOperationNameCollisionError({
serviceId: definition.id,
operationName: duplicateName
});
}
function describeDefinition(definition) {
return {
id: definition.id,
description: definition.description,
queries: Object.fromEntries(
Object.entries(definition.queries).filter(([, query]) => !query.internal).map(([name, query]) => [
name,
{
name,
description: query.description,
input: query.input,
output: query.output,
...query.staticPath ? { staticPath: !0 } : {}
}
])
),
commands: Object.fromEntries(
Object.entries(definition.commands).filter(([, command]) => !command.internal).map(([name, command]) => [
name,
{
name,
description: command.description,
input: command.input,
output: command.output
}
])
)
};
}
function summarizeDescriptor(descriptor) {
return {
id: descriptor.id,
description: descriptor.description,
queryNames: Object.keys(descriptor.queries),
commandNames: Object.keys(descriptor.commands)
};
}
function applyRegistration(definition, registration) {
return registration ? {
...definition,
queries: Object.fromEntries(
Object.entries(definition.queries).map(([name, query]) => {
let override = registration.queries?.[name];
return [
name,
override && "staticInputs" in override ? { ...query, staticInputs: override.staticInputs } : query
];
})
),
commands: Object.fromEntries(
Object.entries(definition.commands).map(([name, command]) => {
let override = registration.commands?.[name];
return [
name,
override && "handler" in override ? { ...command, handler: override.handler } : command
];
})
)
} : definition;
}
var serviceRegistryApi = {
listServices,
describeService,
getService
};
function registerService(definition, registration, { relay = !1, staticLoader } = {}) {
assertUniqueOperationNames(definition);
let registry = getRegistry(), existingEntry = registry.get(definition.id);
if (existingEntry)
return existingEntry.instance;
let ownClientId = generateClientId(), resolvedDefinition = applyRegistration(definition, registration), runtime = createServiceRuntime(
resolvedDefinition,
{ registryApi: serviceRegistryApi, staticLoader },
structuredClone(resolvedDefinition.initialState)
), reconciler = createSnapshotReconciler({
setState: (mutate) => runtime.commandSelf.setState((state) => mutate(state)),
initialStamp: { version: 0, clientId: ownClientId }
}), getSnapshot = () => runtime.getStateSnapshot(), descriptor = describeDefinition(resolvedDefinition), channel2 = getChannel();
if (!channel2)
throw new OpenServiceMissingChannelError({ serviceId: definition.id });
getInventory().everRegisteredIds.add(definition.id), ensureUnknownServiceReporter(channel2);
let implementedCommandNames = new Set(
Object.entries(resolvedDefinition.commands).filter(([, command]) => typeof command.handler == "function").map(([name]) => name)
), { commands, disconnect } = connectServiceToChannel({
serviceId: definition.id,
ownClientId,
reconciler,
getSnapshot,
channel: channel2,
relay: isDelegatedMode() ? !1 : relay,
commands: runtime.commands,
implementedCommandNames,
commandNames: Object.keys(resolvedDefinition.commands),
delegated: isDelegatedMode(),
runtime
}), instance = {
queries: runtime.queries,
commands,
...serviceRegistryApi
};
return registry.set(definition.id, {
definition: resolvedDefinition,
instance,
descriptor,
summary: summarizeDescriptor(descriptor),
disconnect
}), instance;
}
function getRegisteredServices() {
return Array.from(getRegistry().values(), ({ definition }) => definition);
}
async function listServices() {
return Array.from(getRegistry().values()).filter(({ definition }) => !definition.internal).map(({ summary }) => summary);
}
async function describeService(serviceId) {
let entry = getRegistry().get(serviceId);
if (!entry)
throw new OpenServiceMissingServiceError({ serviceId });
return entry.descriptor;
}
function getService(serviceId, options) {
let entry = getRegistry().get(serviceId);
if (!entry)
throw new OpenServiceMissingServiceError({ serviceId });
if (entry.definition.internal && !options?.internal)
throw new OpenServiceInternalServiceError({ serviceId });
return entry.instance;
}
function clearRegistry() {
let inventory = getInventory();
for (let entry of inventory.entries.values())
entry.disconnect();
inventory.entries.clear(), inventory.delegatedMode = !1, inventory.everRegisteredIds.clear(), inventory.unknownServiceReporter?.disconnect(), inventory.unknownServiceReporter = void 0;
}
export {
isPrimitive,
isTypedArray,
isPlainObject,
Channel,
getChannel,
setChannel,
description,
integer,
maxValue,
minLength,
minValue,
regex,
transform,
trim,
any,
array,
boolean,
custom,
lazy,
literal,
looseObject,
nullable,
number,
object,
optional,
picklist,
record,
string,
undefined_,
union,
unknown,
variant,
void_,
message,
pipe,
safeParse,
summarize,
isEqual,
validateSchema,
resolveStaticPath,
createServiceRuntime,
setDelegatedMode,
serviceRegistryApi,
registerService,
getRegisteredServices,
listServices,
describeService,
getService,
clearRegistry
};