@hasna/projects
Version:
High-level project management CLI, MCP server, SDK, and AI SDK agent loop for coding agents
8,254 lines • 295 kB
JavaScript
// @bun
var __defProp = Object.defineProperty;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: __exportSetter.bind(all, name)
});
};
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
var exports_external = {};
__export(exports_external, {
void: () => voidType,
util: () => util,
unknown: () => unknownType,
union: () => unionType,
undefined: () => undefinedType,
tuple: () => tupleType,
transformer: () => effectsType,
symbol: () => symbolType,
string: () => stringType,
strictObject: () => strictObjectType,
setErrorMap: () => setErrorMap,
set: () => setType,
record: () => recordType,
quotelessJson: () => quotelessJson,
promise: () => promiseType,
preprocess: () => preprocessType,
pipeline: () => pipelineType,
ostring: () => ostring,
optional: () => optionalType,
onumber: () => onumber,
oboolean: () => oboolean,
objectUtil: () => objectUtil,
object: () => objectType,
number: () => numberType,
nullable: () => nullableType,
null: () => nullType,
never: () => neverType,
nativeEnum: () => nativeEnumType,
nan: () => nanType,
map: () => mapType,
makeIssue: () => makeIssue,
literal: () => literalType,
lazy: () => lazyType,
late: () => late,
isValid: () => isValid,
isDirty: () => isDirty,
isAsync: () => isAsync,
isAborted: () => isAborted,
intersection: () => intersectionType,
instanceof: () => instanceOfType,
getParsedType: () => getParsedType,
getErrorMap: () => getErrorMap,
function: () => functionType,
enum: () => enumType,
effect: () => effectsType,
discriminatedUnion: () => discriminatedUnionType,
defaultErrorMap: () => en_default,
datetimeRegex: () => datetimeRegex,
date: () => dateType,
custom: () => custom,
coerce: () => coerce,
boolean: () => booleanType,
bigint: () => bigIntType,
array: () => arrayType,
any: () => anyType,
addIssueToContext: () => addIssueToContext,
ZodVoid: () => ZodVoid,
ZodUnknown: () => ZodUnknown,
ZodUnion: () => ZodUnion,
ZodUndefined: () => ZodUndefined,
ZodType: () => ZodType,
ZodTuple: () => ZodTuple,
ZodTransformer: () => ZodEffects,
ZodSymbol: () => ZodSymbol,
ZodString: () => ZodString,
ZodSet: () => ZodSet,
ZodSchema: () => ZodType,
ZodRecord: () => ZodRecord,
ZodReadonly: () => ZodReadonly,
ZodPromise: () => ZodPromise,
ZodPipeline: () => ZodPipeline,
ZodParsedType: () => ZodParsedType,
ZodOptional: () => ZodOptional,
ZodObject: () => ZodObject,
ZodNumber: () => ZodNumber,
ZodNullable: () => ZodNullable,
ZodNull: () => ZodNull,
ZodNever: () => ZodNever,
ZodNativeEnum: () => ZodNativeEnum,
ZodNaN: () => ZodNaN,
ZodMap: () => ZodMap,
ZodLiteral: () => ZodLiteral,
ZodLazy: () => ZodLazy,
ZodIssueCode: () => ZodIssueCode,
ZodIntersection: () => ZodIntersection,
ZodFunction: () => ZodFunction,
ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
ZodError: () => ZodError,
ZodEnum: () => ZodEnum,
ZodEffects: () => ZodEffects,
ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
ZodDefault: () => ZodDefault,
ZodDate: () => ZodDate,
ZodCatch: () => ZodCatch,
ZodBranded: () => ZodBranded,
ZodBoolean: () => ZodBoolean,
ZodBigInt: () => ZodBigInt,
ZodArray: () => ZodArray,
ZodAny: () => ZodAny,
Schema: () => ZodType,
ParseStatus: () => ParseStatus,
OK: () => OK,
NEVER: () => NEVER,
INVALID: () => INVALID,
EMPTY_PATH: () => EMPTY_PATH,
DIRTY: () => DIRTY,
BRAND: () => BRAND
});
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
util2.assertEqual = (_) => {};
function assertIs(_arg) {}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error;
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var en_default = errorMap;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === en_default ? undefined : en_default
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
class ParseInputLazyPath {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (Array.isArray(this._key)) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
}
var handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message ?? ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: message ?? required_error ?? ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return { errorMap: customMap, description };
}
class ZodType {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus,
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(undefined).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) {
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
}
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
if (!header)
return false;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if ("typ" in decoded && decoded?.typ !== "JWT")
return false;
if (!decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
cidr(options) {
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
}
datetime(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
}
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = undefined;
const status = new ParseStatus;
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
}
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
class ZodBoolean extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus;
let ctx = undefined;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
}
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
class ZodSymbol extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
class ZodUndefined extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
class ZodNull extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
class ZodAny extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
class ZodUnknown extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
class ZodNever extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
}
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
class ZodVoid extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
}
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : undefined,
maximum: tooBig ? def.exactLength.value : undefined,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
}
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = { shape, keys };
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== undefined ? {
errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: errorUtil.errToObj(message).message ?? defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) {
if (!mask[key]) {
shape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => shape
});
}
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
}
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
class ZodUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = undefined;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
}
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [undefined];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [undefined, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
static create(discriminator, options, params) {
const optionsMap = new Map;
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0;index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
class ZodIntersection extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
}
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
}
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = new Map;
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = new Map;
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
}
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = new Set;
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
}
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}
class ZodLazy extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
}
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
class ZodLiteral extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
}
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(this._def.values);
}
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(util.getValidEnumValues(this._def.values));
}
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
}
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
}
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
class ZodEffects extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
}
}
util.assertNever(effect);
}
}
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
class ZodOptional extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(undefined);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
class ZodNullable extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
class ZodDefault extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
}
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
}
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
class ZodNaN extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
}
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
}
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
function cleanParams(params, data) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
const r = check(data);
if (r instanceof Promise) {
return r.then((r2) => {
if (!r2) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
});
}
if (!r) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
return;
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: true }),
number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: true
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
var NEVER = INVALID;
// src/serve/projection-policy.ts
import { ActorPointerSchema, EvidencePointerSchema, ResourcePointerSchema } from "@hasna/contracts";
// src/lib/guarded-project-mutation.ts
import { createHash } from "crypto";
var COMPLETE_STABLE_PROJECT_ID_PATTERN = "^wks_[A-Za-z0-9_-]{12,}$";
var COMPLETE_STABLE_PROJECT_ID_RE = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
function assertPositiveBounds(bounds) {
if (!Number.isInteger(bounds.response_byte_limit) || bounds.response_byte_limit <= 0) {
throw new Error("response_byte_limit must be a positive integer");
}
if (!Number.isInteger(bounds.time_budget_ms) || bounds.time_budget_ms <= 0) {
throw new Error("time_budget_ms must be a positive integer");
}
}
function canonicalJson(value) {
return JSON.stringify(canonicalize(value));
}
function canonicalize(value) {
if (Array.isArray(value))
return value.map((item) => canonicalize(item));
if (!value || typeof value !== "object")
return value;
const out = {};
for (const key of Object.keys(value).sort()) {
const next = value[key];
if (next !== undefined)
out[key] = canonicalize(next);
}
return out;
}
function sha256(value) {
return createHash("sha256").update(value).digest("hex");
}
function responseControl(payload, bounds, startedAtMs, operation = "guarded mutation", completeness = {
complete: true,
truncated: false
}) {
assertPositiveBounds(bounds);
const bytes = Buffer.byteLength(JSON.stringify(payload), "utf8");
const elapsed = Math.max(Date.now() - startedAtMs, 0);
if (bytes > bounds.response_byte_limit) {
throw new Error(`${operation} response byte budget exceeded: ${bytes} > ${bounds.response_byte_limit}`);
}
if (elapsed > bounds.time_budget_ms) {
throw new Error(`${operation} time budget exceeded: ${elapsed} > ${bounds.time_budget_ms}`);
}
return {
response_byte_limit: bounds.response_byte_limit,
time_budget_ms: bounds.time_budget_ms,
response_bytes: bytes,
elapsed_ms: elapsed,
...completeness
};
}
// src/serve/projection-policy.ts
var exact = exports_external.string().trim().min(1).max(200).refine((v) => !v.includes("*"));
var tenant = exports_external.string().uuid().transform((v) => v.toLowerCase());
var digest = exports_external.string().regex(/^[a-f0-9]{64}$/);
var subject = exports_external.object({ app: exact, tenant_id: tenant, agent: exact, kid: exact.optional() }).strict();
var owner = ActorPointerSchema.refine((v) => Boolean(v.provider) && !v.id.includes("*") && !v.provider.includes("*"), "owner must have an exact authority");
var evidence = EvidencePointerSchema.refine((v) => Boolean(v.uri && v.sha256), "policy evidence requires uri and digest");
var resource = ResourcePointerSchema.refine((v) => Boolean(v.sourcePackage && v.externalId), "policy reference requires source package and immutable external id");
var ProjectionPolicySchema = exports_external.object({
schema: exports_external.literal("projects.projection_issuer_policy.v1"),
id: exact,
revision: exports_external.number().int().positive().max(Number.MAX_SAFE_INTEGER),
digest,
state: exports_external.enum(["active", "disabled"]),
authority: exact,
evidence_refs: exports_external.array(evidence).min(1).max(32),
bindings: exports_external.array(exports_external.object({
project_id: exports_external.string().regex(new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN)),
tenant_id: tenant,
subjects: exports_external.array(subject).min(1).max(64),
operations: exports_external.array(exports_external.enum(["issue", "read"])).min(1).max(2),
owner_refs: exports_external.array(owner).min(1).max(32),
repository_ref: resource.refine((v) => v.kind === "repo"),
workspace_ref: resource.refine((v) => v.kind === "project")
}).strict()).min(1).max(256)
}).strict();
class ProjectionError extends Error {
status;
code;
constructor(status, code) {
super(code);
this.status = status;
this.code = code;
}
}
function projectionPolicyDigest(value) {
const { digest: _, ...body } = value;
return sha256(canonicalJson(body));
}
function freeze(value) {
if (value && typeof value === "object") {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
function validateProjectionPolicy(input) {
try {
if (Buffer.byteLength(JSON.stringify(input)) > 262144)
return;
const p = ProjectionPolicySchema.parse(input);
if (p.digest !== projectionPolicyDigest(p))
return;
const projects = new Set;
for (const b of p.bindings) {
if (projects.has(b.project_id) || b.workspace_ref.externalId !== b.project_id || b.workspace_ref.sourcePackage !== "@hasna/projects")
return;
projects.add(b.project_id);
if (new Set(b.operations).size !== b.operations.length)
return;
if (new Set(b.owner_refs.map((v) => `${v.kind}:${v.id}`)).size !== b.owner_refs.length)
return;
for (let i = 0;i < b.subjects.length; i++) {
const s = b.subjects[i];
if (s.tenant_id !== b.tenant_id)
return;
if (b.subjects.slice(0, i).some((v) => v.app === s.app && v.agent === s.agent && (!v.kid || !s.kid || v.kid === s.kid)))
return;
}
}
return freeze(p);
} catch {
return;
}
}
function authorizeProjection(policy, principal, projectId, operation) {
if (!policy || policy.state !== "active")
throw new ProjectionError(403, "PROJECTION_POLICY_UNAVAILABLE");
const tid = tenant.safeParse(principal.tid);
const b = policy.bindings.find((v) => v.project_id === projectId);
if (!tid.success || !b || tid.data !== b.tenant_id || !principal.agent || !principal.scopes.includes(operation === "issue" ? "projects:write" : "projects:read") || !b.operations.includes(operation) || !b.subjects.some((s) => s.app === principal.app && s.agent === principal.agent && s.tenant_id === tid.data && (!s.kid || s.kid === principal.kid))) {
throw new ProjectionError(403, "PROJECTION_NOT_AUTHORIZED");
}
return b;
}
// src/serve/projection-http.ts
async function readProjectionBody(request) {
if (!request.body)
throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
const reader = request.body.getReader();
const chunks = [];
let size = 0;
let timer;
try {
return await Promise.race([
(async () => {
while (true) {
const chunk = await reader.read();
if (chunk.done)
break;
size += chunk.value.byteLength;
if (size > 8192)
throw new ProjectionError(413, "PROJECTION_REQUEST_TOO_LARGE");
chunks.push(chunk.value);
}
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
}
})(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new ProjectionError(408, "PROJECTION_BODY_TIMEOUT")), 5000);
})
]);
} finally {
clearTimeout(timer);
reader.cancel().catch(() => {});
}
}
// src/serve/app.ts
import {
verifyApiKey
} from "@hasna/contracts/auth";
// src/serve/product-projection.ts
import { ProductProjectionSchema, computeDeploymentRecordDigest } from "@hasna/contracts";
var ProjectionIssueSchema = exports_external.object({
request_id: exports_external.string().uuid(),
expected_revision: exports_external.string().min(1).max(200),
project_digest: exports_external.string().regex(/^[a-f0-9]{64}$/),
resource_link_collection_digest: exports_external.string().regex(/^[a-f0-9]{64}$/),
resource_link_max_items: exports_external.number().int().min(1).max(1000),
response_byte_limit: exports_external.number().int().min(1024).max(1048576),
time_budget_ms: exports_external.number().int().min(1).max(30000)
}).strict();
var ProjectionReadSchema = ProjectionIssueSchema.pick({ response_byte_limit: true, time_budget_ms: true });
// ../../node_modules/.bun/nanoid@5.1.16/node_modules/nanoid/index.js
import { webcrypto as crypto2 } from "crypto";
var POOL_SIZE_MULTIPLIER = 128;
var pool;
var poolOffset;
function fillPool(bytes) {
if (bytes < 0)
throw new RangeError("Wrong ID size");
try {
if (!pool || pool.length < bytes) {
pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
crypto2.getRandomValues(pool);
poolOffset = 0;
} else if (poolOffset + bytes > pool.length) {
crypto2.getRandomValues(pool);
poolOffset = 0;
}
} catch (e) {
pool = undefined;
throw e;
}
poolOffset += bytes;
}
function random(bytes) {
fillPool(bytes |= 0);
return pool.subarray(poolOffset - bytes, poolOffset);
}
function customRandom(alphabet, defaultSize, getRandom) {
let safeByteCutoff = 256 - 256 % alphabet.length;
if (safeByteCutoff === 256) {
let mask = alphabet.length - 1;
return (size = defaultSize) => {
if (!size)
return "";
let id = "";
while (true) {
let bytes = getRandom(size);
let i = size;
while (i--) {
id += alphabet[bytes[i] & mask];
if (id.length >= size)
return id;
}
}
};
}
let step = Math.ceil(1.6 * 256 * defaultSize / safeByteCutoff);
return (size = defaultSize) => {
if (!size)
return "";
let id = "";
while (true) {
let bytes = getRandom(step);
let i = step;
while (i--) {
if (bytes[i] < safeByteCutoff) {
id += alphabet[bytes[i] % alphabet.length];
if (id.length >= size)
return id;
}
}
}
};
}
function customAlphabet(alphabet, size = 21) {
return customRandom(alphabet, size, random);
}
// src/types/workspace.ts
var PROJECT_RESOURCE_AUTHORITIES = ["todos", "conversations", "knowledge", "mementos", "orgs", "contacts", "files"];
// src/lib/project-relations.ts
var COMPLETE_STABLE_PROJECT_ID_RE2 = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
// src/lib/project-channel-guard.ts
var channelNameListCache = new Map;
// src/lib/project-registration.ts
import { join, resolve } from "path";
// src/lib/project-management.ts
var FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES = 4 * 1024;
// src/lib/project-resource-links.ts
import {
ProjectResourceLinkCollectionV1Schema,
ProjectResourceLinkInputSchema,
ProjectResourceLinkSchema
} from "@hasna/contracts/schemas";
var SOURCE_PACKAGE_BY_AUTHORITY = {
todos: "@hasna/todos",
conversations: "@hasna/conversations",
knowledge: "@hasna/knowledge",
mementos: "@hasna/mementos",
orgs: "@hasna/orgs",
contacts: "@hasna/contacts",
files: "@hasna/files"
};
var TARGET_KINDS_BY_AUTHORITY = {
todos: ["project", "task", "task_list", "plan"],
conversations: ["project", "channel"],
knowledge: ["collection", "item"],
mementos: ["project", "item"],
orgs: ["org", "project"],
contacts: ["contact"],
files: ["project"]
};
var LINK_FIELDS = new Set([
"authority",
"service_instance",
"source_package",
"target_kind",
"locator",
"scope",
"labels"
]);
var LOCATOR_FIELDS = new Set(["kind", "value"]);
var LABEL_FIELDS = new Set(["name", "channel_name", "path", "tags"]);
var COMPLETE_EXTERNAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$";
var UUID_RE = new RegExp(COMPLETE_EXTERNAL_UUID_PATTERN);
var CONVERSATIONS_CHANNEL_ID_RE = /^chn_[0-9a-f]{32}$/;
var URN_RE = /^urn:[a-z0-9][a-z0-9-]{0,31}:[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]+$/;
var PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX = "urn:hasna:files:project:";
var FILES_PROJECT_LOCATOR_RE = /^urn:hasna:files:project:prj_[A-Za-z0-9_-]+$/;
function projectResourceLinkConversationsChannelLocatorKind(value) {
if (UUID_RE.test(value))
return "external_uuid";
if (CONVERSATIONS_CHANNEL_ID_RE.test(value))
return "conversations_channel_id";
return null;
}
function assertClosedObject(value, allowed, label) {
for (const key of Object.keys(value)) {
if (!allowed.has(key))
throw new Error(`${label} contains unknown field '${key}'`);
}
}
function requiredString(value, label) {
if (typeof value !== "string" || !value.trim())
throw new Error(`${label} must be a non-empty string`);
return value.trim();
}
function canonicalProjectResourceLinkUri(value, label) {
if (URN_RE.test(value))
return value;
let url;
try {
url = new URL(value);
} catch {
throw new Error(`${label} must be a canonical https URI or URN`);
}
if (url.protocol !== "https:" || url.username || url.password) {
throw new Error(`${label} must be a non-secret canonical https URI or URN`);
}
if (url.search || url.hash)
throw new Error(`${label} must not contain query or fragment components`);
return url.toString();
}
function normalizeLabels(value) {
if (value === undefined)
return {};
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("resource link labels must be an object");
}
assertClosedObject(value, LABEL_FIELDS, "resource link labels");
const raw = value;
const labels = {};
if (raw["name"] !== undefined)
labels.name = requiredString(raw["name"], "resource link labels.name");
if (raw["channel_name"] !== undefined)
labels.channel_name = requiredString(raw["channel_name"], "resource link labels.channel_name");
if (raw["path"] !== undefined)
labels.path = requiredString(raw["path"], "resource link labels.path");
if (raw["tags"] !== undefined) {
if (!Array.isArray(raw["tags"]) || raw["tags"].some((tag) => typeof tag !== "string")) {
throw new Error("resource link labels.tags must be an array of strings");
}
labels.tags = [...new Set(raw["tags"].map((tag) => tag.trim()).filter(Boolean))].sort();
}
return labels;
}
function normalizeProjectResourceLink(input) {
if (!input || typeof input !== "object" || Array.isArray(input))
throw new Error("resource link must be an object");
assertClosedObject(input, LINK_FIELDS, "resource link");
if (!PROJECT_RESOURCE_AUTHORITIES.includes(input.authority)) {
throw new Error("resource link authority is unsupported");
}
const authority = input.authority;
const serviceInstance = canonicalProjectResourceLinkUri(requiredString(input.service_instance, "resource link service_instance"), "resource link service_instance");
const expectedPackage = SOURCE_PACKAGE_BY_AUTHORITY[authority];
if (input.source_package !== expectedPackage) {
throw new Error(`resource link source_package for ${authority} must be ${expectedPackage}`);
}
if (!TARGET_KINDS_BY_AUTHORITY[authority].includes(input.target_kind)) {
throw new Error(`resource link target_kind '${input.target_kind}' is not valid for ${authority}`);
}
if (!input.locator || typeof input.locator !== "object" || Array.isArray(input.locator)) {
throw new Error("resource link locator must be an object");
}
assertClosedObject(input.locator, LOCATOR_FIELDS, "resource link locator");
const locatorValue = requiredString(input.locator.value, "resource link locator.value");
let normalizedLocatorValue;
if (input.locator.kind === "external_uuid") {
if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "external_uuid") {
throw new Error("resource link external_uuid must be a complete UUID");
}
normalizedLocatorValue = locatorValue.toLowerCase();
} else if (input.locator.kind === "canonical_uri") {
normalizedLocatorValue = canonicalProjectResourceLinkUri(locatorValue, "resource link canonical_uri");
} else if (input.locator.kind === "conversations_channel_id") {
if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "conversations_channel_id") {
throw new Error("resource link conversations channel ID must match chn_<32hex>");
}
normalizedLocatorValue = locatorValue.toLowerCase();
} else {
throw new Error("resource link locator.kind must be external_uuid, canonical_uri, or conversations_channel_id");
}
const locator = {
kind: input.locator.kind,
value: normalizedLocatorValue
};
if (input.scope !== "resource" && input.scope !== "collection") {
throw new Error("resource link scope must be resource or collection");
}
const labels = normalizeLabels(input.labels);
if (locator.kind === "conversations_channel_id" && !(authority === "conversations" && input.target_kind === "channel")) {
throw new Error("resource link conversations_channel_id is only valid for Conversations channel links");
}
if (input.authority === "todos" && input.target_kind === "task") {
if (locator.kind !== "external_uuid") {
throw new Error("Todos task links require a complete external_uuid task ID");
}
const taskLocator = { kind: "external_uuid", value: locator.value };
return ProjectResourceLinkInputSchema.parse({
...input,
service_instance: serviceInstance,
locator: taskLocator,
labels
});
}
if (authority === "conversations" && input.target_kind === "channel") {
if (locator.kind !== "external_uuid" && locator.kind !== "conversations_channel_id") {
throw new Error("conversations channel links require an immutable external_uuid or conversations_channel_id");
}
if (!labels.channel_name) {
throw new Error("conversations channel links require labels.channel_name as mutable compatibility data");
}
}
if (authority === "contacts" && input.target_kind === "contact") {
if (locator.kind !== "external_uuid") {
throw new Error("contacts contact links require an immutable external_uuid");
}
const contactLocator = { kind: "external_uuid", value: locator.value };
return ProjectResourceLinkInputSchema.parse({
...input,
service_instance: serviceInstance,
locator: contactLocator,
labels
});
}
if (authority === "files" && input.target_kind === "project") {
if (input.scope !== "collection") {
throw new Error("files project links require scope collection");
}
if (locator.kind !== "canonical_uri") {
throw new Error(`files project links require a canonical_uri locator of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
}
if (!FILES_PROJECT_LOCATOR_RE.test(locator.value)) {
throw new Error(`files project links require a locator value of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
}
}
return ProjectResourceLinkInputSchema.parse({
...input,
service_instance: serviceInstance,
locator,
labels
});
}
var PROJECTIONS = [
{ key: "todos_project_id", match: (link) => link.authority === "todos" && link.target_kind === "project" },
{ key: "todos_task_list_id", match: (link) => link.authority === "todos" && link.target_kind === "task_list" },
{ key: "mementos_project_id", match: (link) => link.authority === "mementos" && link.target_kind === "project" },
{ key: "orgs_org_id", match: (link) => link.authority === "orgs" && link.target_kind === "org" },
{ key: "orgs_project_id", match: (link) => link.authority === "orgs" && link.target_kind === "project" },
{ key: "conversations_channel", match: (link) => link.authority === "conversations" && link.target_kind === "channel" }
];
var PROJECT_RESOURCE_LINK_INTEGRATION_KEYS = PROJECTIONS.map((projection) => projection.key);
// src/db/workspaces.ts
var nanoid = customAlphabet(`0123456789${"abcdefghijklmnopqrstuvwxyz"}`, 12);
// src/lib/project-registration.ts
class ProjectRegistrationPathHandle {
#absolutePath;
#pathDigest;
constructor(path) {
this.#absolutePath = resolve(path);
this.#pathDigest = sha256(this.#absolutePath);
}
static fromPath(path) {
if (!path?.trim())
throw new Error("project registration requires a non-empty target path");
return new ProjectRegistrationPathHandle(path);
}
get digest() {
return this.#pathDigest;
}
withOwnedPath(consumer) {
return consumer(this.#absolutePath);
}
}
// src/serve/pg-store.ts
var PROJECT_RELATION_HIERARCHY_LOCK_KEY = BigInt.asIntN(64, BigInt(`0x${sha256("hasna.projects.project-relations:hierarchy-graph").slice(0, 16)}`));
class NotFoundError extends Error {
status = 404;
constructor(message) {
super(message);
this.name = "NotFoundError";
}
}
class ValidationError extends Error {
status = 400;
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
class ProjectRegistrationLedgerError extends Error {
reason;
status;
constructor(reason, message, status = 409) {
super(message);
this.reason = reason;
this.status = status;
this.name = "ProjectRegistrationLedgerError";
}
}
var WORKSPACE_LIST_DEFAULT_LIMIT = 100;
var WORKSPACE_LIST_MAX_LIMIT = 1000;
// src/serve/projection-openapi.ts
var ref = (name) => ({ $ref: `#/components/schemas/${name}` });
var string = { type: "string" };
var digest2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
var object = (properties, required = Object.keys(properties)) => ({ type: "object", additionalProperties: false, properties, required });
var bounds = {
response_byte_limit: { type: "integer", minimum: 1024, maximum: 1048576 },
time_budget_ms: { type: "integer", minimum: 1, maximum: 30000 }
};
var pointer = object({ kind: string, id: string, name: string, uri: string, externalId: string, sourcePackage: string, tags: { type: "array", items: string } }, ["kind", "id", "tags"]);
var actor = object({ kind: string, id: string, name: string, provider: string, accountId: string, machineId: string }, ["kind", "id"]);
var evidence2 = object({ id: string, kind: string, uri: string, sha256: string, summary: string }, ["id"]);
var projectionOpenApiSchemas = {
ProductProjectionIssue: object({
request_id: { type: "string", format: "uuid" },
expected_revision: { type: "string", minLength: 1, maxLength: 200 },
project_digest: digest2,
resource_link_collection_digest: digest2,
resource_link_max_items: { type: "integer", minimum: 1, maximum: 1000 },
...bounds
}),
ProductProjection: object({
schema: { type: "string", enum: ["hasna.product_projection.v1"] },
id: string,
createdAt: string,
producer: actor,
digest: string,
revision: { type: "integer" },
sourceRevision: { type: "integer" },
sourceProjectRef: pointer,
slug: string,
displayName: string,
repositoryRef: pointer,
workspaceRef: pointer,
lifecycle: { type: "string", enum: ["draft", "active", "paused", "archived"] },
ownerRefs: { type: "array", items: actor },
projectedAt: string,
sourceEvidenceRefs: { type: "array", items: evidence2 }
}),
ProductProjectionReceipt: object({
schema: { type: "string", enum: ["projects.product_projection_receipt.v1"] },
receipt_id: string,
project_id: string,
tenant_id: string,
issued_revision: { type: "integer" },
issued_at: string,
request: ref("ProductProjectionIssue"),
request_digest: digest2,
subject: object({ app: string, tenant_id: string, agent: string, kid: string }),
policy: object({ id: string, revision: { type: "integer" }, digest: digest2, authority: string }),
source: object({
project: ref("Workspace"),
revision: string,
project_digest: digest2,
resource_links: { type: "array", items: ref("ProjectResourceLink") },
resource_link_collection_digest: digest2
}),
projection: ref("ProductProjection")
})
};
var project = { name: "id", in: "path", required: true, schema: string };
var result = (status) => ({
[status]: { description: "Exact immutable historical receipt; no execution authority", content: { "application/json": { schema: ref("ProductProjectionReceipt") } } },
"400": { description: "Invalid request" },
"403": { description: "Missing policy or subject authority" },
"409": { description: "Source/idempotency conflict" },
"422": { description: "Bounds or unrepresentable source" }
});
var projectionOpenApiPaths = {
"/v1/projects/{id}/product-projections": { post: {
operationId: "issueProductProjection",
summary: "Issue an immutable factual ProductProjection (server policy required)",
parameters: [project],
requestBody: { required: true, content: { "application/json": { schema: ref("ProductProjectionIssue") } } },
responses: result("201")
} },
"/v1/projects/{id}/product-projections/{receiptId}": { get: {
operationId: "readProductProjection",
summary: "Read one authorized immutable ProductProjection receipt",
parameters: [
project,
{ name: "receiptId", in: "path", required: true, schema: { type: "string", pattern: "^ppr_[a-f0-9]{64}$" } },
...Object.entries(bounds).map(([name, schema]) => ({ name, in: "query", required: true, schema }))
],
responses: result("200")
} }
};
// src/serve/openapi.ts
function buildOpenApiSpec(version) {
const ID_PARAM = {
name: "id",
in: "path",
required: true,
description: "Resource id or slug",
schema: { type: "string" }
};
const EXACT_PROJECT_ID_PARAM = {
name: "id",
in: "path",
required: true,
description: "Complete stable project id beginning with wks_; slugs and partial ids are refused",
schema: { type: "string", pattern: COMPLETE_STABLE_PROJECT_ID_PATTERN }
};
const OPERATION_ID_PARAM = {
name: "operation_id",
in: "path",
required: true,
description: "The full-registration operation id whose immutable history is addressed",
schema: { type: "string" }
};
const ref2 = (name) => ({ $ref: `#/components/schemas/${name}` });
const jsonBody = (schemaName, required = true) => ({
required,
content: { "application/json": { schema: ref2(schemaName) } }
});
const jsonResp = (schemaName, description = "OK") => ({
description,
content: { "application/json": { schema: ref2(schemaName) } }
});
const projectResourceLinkInputBranch = (authority, sourcePackage, targetKinds, locator = ref2("ProjectResourcePortableLocator"), labels = ref2("ProjectResourceLinkLabels"), scopes = ["resource", "collection"]) => ({
type: "object",
additionalProperties: false,
properties: {
authority: { type: "string", enum: [authority] },
service_instance: { type: "string" },
source_package: { type: "string", enum: [sourcePackage] },
target_kind: { type: "string", enum: targetKinds },
locator,
scope: { type: "string", enum: scopes },
labels
},
required: ["authority", "service_instance", "source_package", "target_kind", "locator", "scope"]
});
const projectResourceLinkBranch = (authority, sourcePackage, targetKinds, locator = ref2("ProjectResourcePortableLocator"), labels = ref2("ProjectResourceLinkLabels"), scopes = ["resource", "collection"]) => {
const input = projectResourceLinkInputBranch(authority, sourcePackage, targetKinds, locator, labels, scopes);
return {
...input,
properties: {
...input.properties,
id: { type: "string" },
project_id: { type: "string" },
labels,
created_at: { type: "string" },
updated_at: { type: "string" }
},
required: [...input.required, "id", "project_id", "labels", "created_at", "updated_at"]
};
};
return {
openapi: "3.1.0",
info: {
title: "Projects API",
version,
description: "HTTP API for @hasna/projects (workspace/project management). Reads and writes go directly to PostgreSQL. All /v1 routes require an API key (x-api-key or Authorization: Bearer)."
},
servers: [{ url: "/" }],
components: {
securitySchemes: {
apiKey: { type: "apiKey", in: "header", name: "x-api-key" }
},
schemas: {
...projectionOpenApiSchemas,
ProjectRegistrationManifestCreate: {
type: "object",
properties: {
operation_id: { type: "string" },
request_digest: { type: "string" },
project_id: { type: "string" },
project_slug: { type: "string" },
plan: { type: "object", additionalProperties: true }
},
required: ["operation_id", "request_digest", "project_id", "project_slug", "plan"]
},
ProjectRegistrationManifest: {
type: "object",
properties: {
operation_id: { type: "string" },
route: { type: "string" },
request_digest: { type: "string" },
project_id: { type: "string" },
project_slug: { type: "string" },
plan: { type: "object", additionalProperties: true },
created_at: { type: "string" }
},
required: [
"operation_id",
"route",
"request_digest",
"project_id",
"project_slug",
"plan",
"created_at"
]
},
ProjectRegistrationManifestResult: {
type: "object",
properties: {
manifest: ref2("ProjectRegistrationManifest"),
created: { type: "boolean" }
},
required: ["manifest", "created"]
},
ProjectRegistrationManifestRead: {
type: "object",
properties: {
manifest: { anyOf: [ref2("ProjectRegistrationManifest"), { type: "null" }] }
},
required: ["manifest"]
},
ProjectRegistrationReceiptAppend: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
authority: { type: "string" },
resource_kind: { type: "string" },
direction: { type: "string", enum: ["forward", "inverse"] },
idempotency_key: { type: "string" },
target_id: { type: "string", nullable: true },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
reason: { type: "string", nullable: true },
result_revision: { type: "string", nullable: true },
result_digest: { type: "string", nullable: true },
duplicate_of_receipt_id: { type: "string", nullable: true },
authority_receipt: { type: "object", additionalProperties: true, nullable: true },
artifacts: { type: "array", items: { type: "object", additionalProperties: true } },
preconditions: { type: "array", items: { type: "object", additionalProperties: true } },
rollback: { type: "array", items: { type: "object", additionalProperties: true } }
},
required: [
"operation_id",
"step_id",
"authority",
"resource_kind",
"direction",
"idempotency_key",
"request_digest",
"precondition_digest",
"outcome"
]
},
ProjectRegistrationReceipt: {
type: "object",
properties: {
receipt_id: { type: "string" },
operation_id: { type: "string" },
sequence: { type: "integer" },
step_id: { type: "string" },
authority: { type: "string" },
resource_kind: { type: "string" },
direction: { type: "string", enum: ["forward", "inverse"] },
idempotency_key: { type: "string" },
target_id: { type: "string", nullable: true },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
reason: { type: "string", nullable: true },
result_revision: { type: "string", nullable: true },
result_digest: { type: "string", nullable: true },
duplicate_of_receipt_id: { type: "string", nullable: true },
authority_receipt: { type: "object", additionalProperties: true, nullable: true },
artifacts: { type: "array", items: { type: "object", additionalProperties: true } },
preconditions: { type: "array", items: { type: "object", additionalProperties: true } },
rollback: { type: "array", items: { type: "object", additionalProperties: true } },
created_at: { type: "string" }
},
required: [
"receipt_id",
"operation_id",
"sequence",
"step_id",
"authority",
"resource_kind",
"direction",
"idempotency_key",
"target_id",
"request_digest",
"precondition_digest",
"outcome",
"reason",
"result_revision",
"result_digest",
"duplicate_of_receipt_id",
"authority_receipt",
"artifacts",
"preconditions",
"rollback",
"created_at"
]
},
ProjectRegistrationReceiptResult: {
type: "object",
properties: { receipt: ref2("ProjectRegistrationReceipt") },
required: ["receipt"]
},
ProjectRegistrationReceiptLookup: {
type: "object",
properties: {
receipt: ref2("ProjectRegistrationReceipt"),
response_control: { type: "object", additionalProperties: true }
},
required: ["receipt", "response_control"]
},
ProjectRegistrationReceiptList: {
type: "object",
properties: {
receipts: { type: "array", items: ref2("ProjectRegistrationReceipt") }
},
required: ["receipts"]
},
Root: {
type: "object",
properties: {
id: { type: "string" },
slug: { type: "string" },
name: { type: "string" },
base_path: { type: "string" },
tags: { type: "array", items: { type: "string" } },
default_kind: { type: "string", nullable: true },
repo_visibility: { type: "string", nullable: true },
allowed_recipes: { type: "array", items: { type: "string" } },
allowed_agents: { type: "array", items: { type: "string" } },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" },
updated_at: { type: "string" }
},
required: ["id", "slug", "name", "base_path"]
},
CreateRoot: {
type: "object",
properties: {
name: { type: "string" },
base_path: { type: "string" },
slug: { type: "string" },
tags: { type: "array", items: { type: "string" } },
default_kind: { type: "string" },
repo_visibility: { type: "string", enum: ["public", "private"] },
github_org: { type: "string" },
metadata: { type: "object", additionalProperties: true }
},
required: ["name", "base_path"]
},
UpdateRoot: {
type: "object",
properties: {
name: { type: "string" },
base_path: { type: "string" },
slug: { type: "string" },
tags: { type: "array", items: { type: "string" } },
default_kind: { type: "string" },
repo_visibility: { type: "string", enum: ["public", "private"] },
github_org: { type: "string" },
metadata: { type: "object", additionalProperties: true }
}
},
Agent: {
type: "object",
properties: {
id: { type: "string" },
slug: { type: "string" },
name: { type: "string" },
kind: { type: "string", enum: ["human", "ai", "service", "cli"] },
provider: { type: "string", nullable: true },
model: { type: "string", nullable: true },
role: { type: "string", nullable: true },
permissions: { type: "array", items: { type: "string" } },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" },
updated_at: { type: "string" }
},
required: ["id", "slug", "name", "kind"]
},
CreateAgent: {
type: "object",
properties: {
name: { type: "string" },
kind: { type: "string", enum: ["human", "ai", "service", "cli"] },
slug: { type: "string" },
provider: { type: "string" },
model: { type: "string" },
role: { type: "string" },
permissions: { type: "array", items: { type: "string" } },
metadata: { type: "object", additionalProperties: true }
},
required: ["name"]
},
Recipe: {
type: "object",
properties: {
id: { type: "string" },
slug: { type: "string" },
name: { type: "string" },
description: { type: "string", nullable: true },
kind: { type: "string", nullable: true },
version: { type: "integer" },
steps: { type: "array", items: { type: "object", additionalProperties: true } },
default_tags: { type: "array", items: { type: "string" } },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" },
updated_at: { type: "string" }
},
required: ["id", "slug", "name"]
},
CreateRecipe: {
type: "object",
properties: {
name: { type: "string" },
slug: { type: "string" },
description: { type: "string" },
kind: { type: "string" },
version: { type: "integer" },
steps: { type: "array", items: { type: "object", additionalProperties: true } },
default_tags: { type: "array", items: { type: "string" } },
metadata: { type: "object", additionalProperties: true }
},
required: ["name"]
},
Workspace: {
type: "object",
properties: {
id: { type: "string" },
slug: { type: "string" },
name: { type: "string" },
description: { type: "string", nullable: true },
kind: { type: "string" },
status: { type: "string", enum: ["active", "archived", "deleted"] },
root_id: { type: "string", nullable: true },
recipe_id: { type: "string", nullable: true },
canonical_machine: { type: "string", nullable: true },
primary_path: { type: "string", nullable: true },
git_remote: { type: "string", nullable: true },
s3_bucket: { type: "string", nullable: true },
s3_prefix: { type: "string", nullable: true },
tags: { type: "array", items: { type: "string" } },
integrations: { type: "object", additionalProperties: { type: "string" } },
metadata: { type: "object", additionalProperties: true },
last_opened_at: { type: "string", nullable: true },
created_at: { type: "string" },
updated_at: { type: "string" },
synced_at: { type: "string", nullable: true }
},
required: [
"id",
"slug",
"name",
"kind",
"status",
"s3_bucket",
"s3_prefix",
"last_opened_at",
"synced_at"
]
},
CreateWorkspace: {
type: "object",
properties: {
name: { type: "string" },
slug: { type: "string" },
description: { type: "string" },
kind: { type: "string" },
root_id: { type: "string" },
recipe_id: { type: "string" },
primary_path: { type: "string" },
git_remote: { type: "string" },
tags: { type: "array", items: { type: "string" } },
integrations: { type: "object", additionalProperties: true },
metadata: { type: "object", additionalProperties: true },
agent_id: { type: "string" }
},
required: ["name"]
},
UpdateWorkspace: {
type: "object",
properties: {
name: { type: "string" },
slug: { type: "string" },
description: { type: "string", nullable: true },
kind: { type: "string" },
status: { type: "string", enum: ["active", "archived", "deleted"] },
root_id: { type: "string", nullable: true },
recipe_id: { type: "string", nullable: true },
canonical_machine: { type: "string", nullable: true },
primary_path: { type: "string", nullable: true },
git_remote: { type: "string", nullable: true },
tags: { type: "array", items: { type: "string" } },
integrations: { type: "object", additionalProperties: true },
metadata: { type: "object", additionalProperties: true },
last_opened_at: { type: "string", nullable: true },
agent_id: { type: "string" }
}
},
WorkspaceEvent: {
type: "object",
properties: {
id: { type: "string" },
workspace_id: { type: "string", nullable: true },
agent_id: { type: "string", nullable: true },
event_type: { type: "string" },
source: { type: "string" },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" }
},
required: ["id", "event_type", "source"]
},
WorkspaceList: {
type: "object",
description: "A single page of projects. `count` is the page length; `total` is how many rows match the filter. When `has_more` is true the caller must request the next page with `offset` \u2014 a full page is otherwise indistinguishable from the last one.",
properties: {
filter_contract: { type: "string", enum: ["projects.list.v2"], description: "Present on current producers so compact clients can fail closed against servers that ignore additive filters." },
applied_filters: {
type: "object",
additionalProperties: false,
properties: {
query_scope: { type: "string", enum: ["legacy", "identity", "discovery", "structured", "all"] },
tags: { type: "array", items: { type: "string" } },
exclude_evals: { type: "boolean" },
exclude_registry_fixtures: { type: "boolean" }
},
required: ["query_scope", "tags", "exclude_evals", "exclude_registry_fixtures"]
},
workspaces: { type: "array", items: ref2("Workspace") },
count: { type: "integer", description: "Rows in this page." },
total: { type: "integer", description: "Rows matching the filter, ignoring limit/offset." },
offset: { type: "integer", description: "Offset this page starts at." },
limit: { type: "integer", description: "Effective per-page limit after server clamping." },
has_more: { type: "boolean", description: "More rows exist past this page." },
complete: { type: "boolean", description: "True only when this page proves the complete matching population." }
},
required: ["workspaces", "count", "total", "offset", "limit", "has_more", "complete"]
},
GuardedResponseControl: {
type: "object",
properties: {
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 },
response_bytes: { type: "integer", minimum: 1 },
elapsed_ms: { type: "integer", minimum: 0 },
complete: { type: "boolean", const: true },
truncated: { type: "boolean", const: false }
},
required: [
"response_byte_limit",
"time_budget_ms",
"response_bytes",
"elapsed_ms",
"complete",
"truncated"
]
},
GuardedProjectRead: {
type: "object",
properties: {
ok: { type: "boolean", const: true },
project_id: { type: "string" },
project: ref2("Workspace"),
current_revision: { type: "string" },
resource_links: { type: "array", items: ref2("ProjectResourceLink") },
resource_link_count: { type: "integer", minimum: 0 },
resource_link_max_items: { type: "integer", minimum: 1 },
resource_link_collection_digest: { type: "string" },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"project_id",
"project",
"current_revision",
"resource_links",
"resource_link_count",
"resource_link_max_items",
"resource_link_collection_digest",
"response_control"
]
},
ProjectResourceLinkLabels: {
type: "object",
additionalProperties: false,
properties: {
name: { type: "string" },
channel_name: { type: "string" },
path: { type: "string" },
tags: { type: "array", items: { type: "string" } }
}
},
ProjectResourceConversationsChannelLabels: {
type: "object",
additionalProperties: false,
properties: {
name: { type: "string" },
channel_name: { type: "string" },
path: { type: "string" },
tags: { type: "array", items: { type: "string" } }
},
required: ["channel_name"]
},
ProjectResourceExternalUuidLocator: {
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["external_uuid"] },
value: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN }
},
required: ["kind", "value"]
},
ProjectResourceCanonicalUriLocator: {
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["canonical_uri"] },
value: { type: "string" }
},
required: ["kind", "value"]
},
ProjectResourceConversationsChannelLocator: {
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["conversations_channel_id"] },
value: { type: "string", pattern: "^chn_[0-9a-f]{32}$" }
},
required: ["kind", "value"]
},
ProjectResourceLinkLocator: {
oneOf: [
ref2("ProjectResourceExternalUuidLocator"),
ref2("ProjectResourceCanonicalUriLocator"),
ref2("ProjectResourceConversationsChannelLocator")
]
},
ProjectResourcePortableLocator: {
oneOf: [
ref2("ProjectResourceExternalUuidLocator"),
ref2("ProjectResourceCanonicalUriLocator")
]
},
ProjectResourceConversationsChannelLinkLocator: {
oneOf: [
ref2("ProjectResourceExternalUuidLocator"),
ref2("ProjectResourceConversationsChannelLocator")
]
},
ProjectResourceLinkInput: {
oneOf: [
projectResourceLinkInputBranch("todos", "@hasna/todos", ["project", "task_list", "plan"]),
projectResourceLinkInputBranch("todos", "@hasna/todos", ["task"], ref2("ProjectResourceExternalUuidLocator")),
projectResourceLinkInputBranch("conversations", "@hasna/conversations", ["project"]),
projectResourceLinkInputBranch("conversations", "@hasna/conversations", ["channel"], ref2("ProjectResourceConversationsChannelLinkLocator"), ref2("ProjectResourceConversationsChannelLabels")),
projectResourceLinkInputBranch("knowledge", "@hasna/knowledge", ["collection", "item"]),
projectResourceLinkInputBranch("mementos", "@hasna/mementos", ["project", "item"]),
projectResourceLinkInputBranch("orgs", "@hasna/orgs", ["org", "project"]),
projectResourceLinkInputBranch("contacts", "@hasna/contacts", ["contact"], ref2("ProjectResourceExternalUuidLocator")),
projectResourceLinkInputBranch("files", "@hasna/files", ["project"], ref2("ProjectResourceCanonicalUriLocator"), ref2("ProjectResourceLinkLabels"), ["collection"])
]
},
ProjectResourceLink: {
oneOf: [
projectResourceLinkBranch("todos", "@hasna/todos", ["project", "task_list", "plan"]),
projectResourceLinkBranch("todos", "@hasna/todos", ["task"], ref2("ProjectResourceExternalUuidLocator")),
projectResourceLinkBranch("conversations", "@hasna/conversations", ["project"]),
projectResourceLinkBranch("conversations", "@hasna/conversations", ["channel"], ref2("ProjectResourceConversationsChannelLinkLocator"), ref2("ProjectResourceConversationsChannelLabels")),
projectResourceLinkBranch("knowledge", "@hasna/knowledge", ["collection", "item"]),
projectResourceLinkBranch("mementos", "@hasna/mementos", ["project", "item"]),
projectResourceLinkBranch("orgs", "@hasna/orgs", ["org", "project"]),
projectResourceLinkBranch("contacts", "@hasna/contacts", ["contact"], ref2("ProjectResourceExternalUuidLocator")),
projectResourceLinkBranch("files", "@hasna/files", ["project"], ref2("ProjectResourceCanonicalUriLocator"), ref2("ProjectResourceLinkLabels"), ["collection"])
]
},
ProjectResourceLinkCollectionV1: {
type: "object",
additionalProperties: false,
properties: {
schema: { type: "string", enum: ["hasna.project_resource_link_collection.v1"] },
project_id: { type: "string" },
current_revision: { type: "string" },
links: { type: "array", items: ref2("ProjectResourceLink") },
link_count: { type: "integer", minimum: 0 },
max_items: { type: "integer", minimum: 1 },
collection_digest: { type: "string" },
complete: { type: "boolean", enum: [true] },
truncated: { type: "boolean", enum: [false] }
},
required: [
"schema",
"project_id",
"current_revision",
"links",
"link_count",
"max_items",
"collection_digest",
"complete",
"truncated"
]
},
ProjectResourceLinkSnapshot: {
type: "object",
properties: {
project: ref2("Workspace"),
links: { type: "array", items: ref2("ProjectResourceLink") },
collection_digest: { type: "string" }
},
required: ["project", "links", "collection_digest"]
},
ProjectResourceLinkRead: {
type: "object",
properties: {
ok: { type: "boolean", const: true },
project_id: { type: "string" },
project: ref2("Workspace"),
current_revision: { type: "string" },
links: { type: "array", items: ref2("ProjectResourceLink") },
link_count: { type: "integer", minimum: 0 },
max_items: { type: "integer", minimum: 1 },
collection_digest: { type: "string" },
complete: { type: "boolean", const: true },
truncated: { type: "boolean", const: false },
contract: ref2("ProjectResourceLinkCollectionV1"),
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"project_id",
"project",
"current_revision",
"links",
"link_count",
"max_items",
"collection_digest",
"complete",
"truncated",
"contract",
"response_control"
]
},
ProjectResourceLinkMutationRequest: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
mode: { type: "string", enum: ["add", "reconcile"] },
expected_revision: { type: "string" },
links: { type: "array", items: ref2("ProjectResourceLinkInput") },
integrations: { type: "object", additionalProperties: true },
max_items: { type: "integer", minimum: 1 },
dry_run: { type: "boolean" },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"expected_revision",
"links",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectResourceLinkMutationResult: {
type: "object",
properties: {
ok: { type: "boolean" },
dry_run: { type: "boolean" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
mode: { type: "string", enum: ["add", "reconcile"] },
idempotency_key: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
project_id: { type: "string" },
expected_revision: { type: "string" },
current_revision: { type: "string" },
before: ref2("ProjectResourceLinkSnapshot"),
after: { anyOf: [ref2("ProjectResourceLinkSnapshot"), { type: "null" }] },
receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"dry_run",
"outcome",
"mode",
"idempotency_key",
"request_digest",
"precondition_digest",
"project_id",
"expected_revision",
"current_revision",
"before",
"after",
"receipt",
"response_control"
]
},
ProjectRelation: {
type: "object",
additionalProperties: false,
properties: {
relation_id: { type: "string" },
version: { type: "integer", minimum: 1 },
relation: { type: "string", enum: ["parent_of", "depends_on", "related_to"] },
direction: { type: "string", enum: ["outbound", "inbound"] },
self_project_id: { type: "string" },
counterpart_project_id: { type: "string" },
counterpart_slug: { anyOf: [{ type: "string" }, { type: "null" }] },
counterpart_name: { anyOf: [{ type: "string" }, { type: "null" }] },
counterpart_status: { anyOf: [{ type: "string" }, { type: "null" }] },
created_at: { type: "string" }
},
required: [
"relation_id",
"version",
"relation",
"direction",
"self_project_id",
"counterpart_project_id",
"counterpart_slug",
"counterpart_name",
"counterpart_status",
"created_at"
]
},
ProjectRelationSnapshot: {
type: "object",
properties: {
project: ref2("Workspace"),
relations: { type: "array", items: ref2("ProjectRelation") },
collection_digest: { type: "string" }
},
required: ["project", "relations", "collection_digest"]
},
ProjectRelationRead: {
type: "object",
properties: {
ok: { type: "boolean", const: true },
project_id: { type: "string" },
project: ref2("Workspace"),
current_revision: { type: "string" },
relations: { type: "array", items: ref2("ProjectRelation") },
outbound_count: { type: "integer", minimum: 0 },
inbound_count: { type: "integer", minimum: 0 },
relation_count: { type: "integer", minimum: 0 },
max_items: { type: "integer", minimum: 1 },
collection_digest: { type: "string" },
complete: { type: "boolean", const: true },
truncated: { type: "boolean", const: false },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"project_id",
"project",
"current_revision",
"relations",
"outbound_count",
"inbound_count",
"relation_count",
"max_items",
"collection_digest",
"complete",
"truncated",
"response_control"
]
},
ProjectRelationMutationRequest: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
mode: { type: "string", enum: ["add", "supersede"] },
to_project_id: { type: "string" },
relation: { type: "string", enum: ["parent_of", "depends_on", "related_to"] },
expected_revision: { type: "string" },
expected_relation_version: {
type: "integer",
minimum: 1,
description: "The live relation version the caller observed. A relation write never advances the project row, so " + "expected_revision alone cannot detect that another caller already superseded the same ordered pair. " + "Required for supersede: without it the write is refused as relation_state_precondition_required, and " + "one whose observed version is no longer the live head as stale_relation_state."
},
dry_run: { type: "boolean" },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"to_project_id",
"relation",
"expected_revision",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectRelationMutationResult: {
type: "object",
properties: {
ok: { type: "boolean" },
dry_run: { type: "boolean" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
mode: { type: "string", enum: ["add", "supersede"] },
idempotency_key: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
project_id: { type: "string" },
expected_revision: { type: "string" },
current_revision: { type: "string" },
relation_id: { type: "string" },
before: ref2("ProjectRelationSnapshot"),
after: { anyOf: [ref2("ProjectRelationSnapshot"), { type: "null" }] },
receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"dry_run",
"outcome",
"mode",
"idempotency_key",
"request_digest",
"precondition_digest",
"project_id",
"expected_revision",
"current_revision",
"relation_id",
"before",
"after",
"receipt",
"response_control"
]
},
WorkspaceLocation: {
type: "object",
additionalProperties: false,
properties: {
id: { type: "string" },
workspace_id: { type: "string" },
path: { type: "string" },
machine_id: { type: "string" },
label: { type: "string" },
kind: { type: "string" },
is_primary: { type: "boolean" },
exists_at_create: { type: "boolean" },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" }
},
required: [
"id",
"workspace_id",
"path",
"machine_id",
"label",
"kind",
"is_primary",
"exists_at_create",
"metadata",
"created_at"
]
},
AddWorkspaceLocation: {
type: "object",
additionalProperties: false,
properties: {
path: { type: "string" },
machine_id: { type: "string" },
label: { type: "string" },
kind: { type: "string" },
is_primary: { type: "boolean" },
metadata: { type: "object", additionalProperties: true }
},
required: ["path"]
},
WorkspaceAgentAssignment: {
type: "object",
additionalProperties: false,
properties: {
id: { type: "string" },
workspace_id: { type: "string" },
agent_id: { type: "string" },
role: { type: "string" },
assigned_by: { type: "string", nullable: true },
metadata: { type: "object", additionalProperties: true },
created_at: { type: "string" },
agent: ref2("Agent")
},
required: ["id", "workspace_id", "agent_id", "role", "metadata", "created_at"]
},
AssignWorkspaceAgent: {
type: "object",
additionalProperties: false,
properties: {
agent_id: { type: "string" },
role: { type: "string" },
assigned_by: { type: "string" },
metadata: { type: "object", additionalProperties: true }
},
required: ["agent_id"]
},
WorkspaceLock: {
type: "object",
additionalProperties: false,
properties: {
id: { type: "string" },
lock_key: { type: "string" },
workspace_id: { type: "string", nullable: true },
agent_id: { type: "string", nullable: true },
reason: { type: "string", nullable: true },
created_at: { type: "string" },
expires_at: { type: "string", nullable: true }
},
required: ["id", "lock_key", "created_at"]
},
AcquireWorkspaceLock: {
type: "object",
additionalProperties: false,
properties: {
lock_key: { type: "string" },
workspace_id: { type: "string" },
agent_id: { type: "string" },
reason: { type: "string" },
ttl_seconds: { type: "integer" }
},
required: ["lock_key"]
},
ProjectQuarantineSnapshot: {
type: "object",
additionalProperties: false,
properties: {
project: ref2("Workspace"),
project_digest: { type: "string" },
resource_links: { type: "array", items: ref2("ProjectResourceLink") },
resource_link_collection_digest: { type: "string" },
workspace_locations: { type: "array", items: ref2("WorkspaceLocation") },
workspace_location_collection_digest: { type: "string" }
},
required: [
"project",
"project_digest",
"resource_links",
"resource_link_collection_digest",
"workspace_locations",
"workspace_location_collection_digest"
]
},
ProjectQuarantineRead: {
type: "object",
additionalProperties: false,
properties: {
ok: { type: "boolean", const: true },
project_id: { type: "string" },
current_revision: { type: "string" },
snapshot: ref2("ProjectQuarantineSnapshot"),
resource_link_count: { type: "integer", minimum: 0 },
workspace_location_count: { type: "integer", minimum: 0 },
complete: { type: "boolean", const: true },
truncated: { type: "boolean", const: false },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"project_id",
"current_revision",
"snapshot",
"resource_link_count",
"workspace_location_count",
"complete",
"truncated",
"response_control"
]
},
ProjectQuarantineRequest: {
type: "object",
additionalProperties: false,
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
expected_revision: { type: "string" },
expected_project_digest: { type: "string" },
expected_resource_link_collection_digest: { type: "string" },
expected_resource_link_ids: { type: "array", items: { type: "string" } },
resource_link_max_items: { type: "integer", minimum: 1 },
expected_workspace_location_collection_digest: { type: "string" },
expected_workspace_location_ids: { type: "array", items: { type: "string" } },
workspace_location_max_items: { type: "integer", minimum: 1 },
quarantine_name: { type: "string", minLength: 1 },
quarantine_slug: { type: "string", pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
dry_run: { type: "boolean" },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"expected_revision",
"expected_project_digest",
"expected_resource_link_collection_digest",
"expected_resource_link_ids",
"resource_link_max_items",
"expected_workspace_location_collection_digest",
"expected_workspace_location_ids",
"workspace_location_max_items",
"quarantine_name",
"quarantine_slug",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectQuarantineRollbackRequest: {
type: "object",
additionalProperties: false,
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
accepted_receipt_id: { type: "string" },
expected_current_revision: { type: "string" },
resource_link_max_items: { type: "integer", minimum: 1 },
workspace_location_max_items: { type: "integer", minimum: 1 },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"accepted_receipt_id",
"expected_current_revision",
"resource_link_max_items",
"workspace_location_max_items",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectQuarantineResult: {
type: "object",
additionalProperties: false,
properties: {
ok: { type: "boolean" },
dry_run: { type: "boolean" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
idempotency_key: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
project_id: { type: "string" },
expected_revision: { type: "string" },
current_revision: { type: "string" },
before: ref2("ProjectQuarantineSnapshot"),
after: { anyOf: [ref2("ProjectQuarantineSnapshot"), { type: "null" }] },
receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
rollback: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
accepted_receipt_id: { type: "string" },
expected_current_revision: { type: "string" }
},
required: ["accepted_receipt_id", "expected_current_revision"]
},
{ type: "null" }
]
},
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"dry_run",
"outcome",
"idempotency_key",
"request_digest",
"precondition_digest",
"project_id",
"expected_revision",
"current_revision",
"before",
"after",
"receipt",
"rollback",
"response_control"
]
},
ContactProjectMembershipSnapshot: {
type: "object",
additionalProperties: false,
properties: {
contact_id: { type: "string" },
project_id: { type: "string" },
linked: { type: "boolean" },
version: { type: "string" }
},
required: ["contact_id", "project_id", "linked", "version"]
},
ProjectContactLinkEvidence: {
type: "object",
additionalProperties: false,
properties: {
system: { type: "string", enum: ["contacts", "projects"] },
step_id: { type: "string" },
outcome: { type: "string" },
receipt_id: { type: ["string", "null"] },
compensated: { type: "boolean" }
},
required: ["system", "step_id", "outcome", "receipt_id", "compensated"]
},
ProjectContactLinkMutationRequest: {
type: "object",
additionalProperties: false,
properties: {
operation_id: { type: "string" },
labels: ref2("ProjectResourceLinkLabels"),
max_items: { type: "integer", minimum: 1 },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: ["operation_id", "max_items", "response_byte_limit", "time_budget_ms"]
},
ProjectContactLinkMutationResult: {
type: "object",
additionalProperties: false,
properties: {
ok: { type: "boolean", const: true },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted"] },
authority: { type: "string", const: "contacts" },
project_id: { type: "string" },
contact_id: { type: "string" },
membership: ref2("ContactProjectMembershipSnapshot"),
project_link: { anyOf: [ref2("ProjectResourceLink"), { type: "null" }] },
evidence: { type: "array", items: ref2("ProjectContactLinkEvidence") },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"outcome",
"authority",
"project_id",
"contact_id",
"membership",
"project_link",
"evidence",
"response_control"
]
},
ProjectContactLinkListResult: {
type: "object",
additionalProperties: false,
properties: {
ok: { type: "boolean", const: true },
authority: { type: "string", const: "contacts" },
project_id: { type: "string" },
membership_revision: { type: "string" },
project_revision: { type: "string" },
contact_ids: { type: "array", items: { type: "string" } },
synchronized_contact_ids: { type: "array", items: { type: "string" } },
missing_project_link_contact_ids: { type: "array", items: { type: "string" } },
stale_project_link_contact_ids: { type: "array", items: { type: "string" } },
project_links: { type: "array", items: ref2("ProjectResourceLink") },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"authority",
"project_id",
"membership_revision",
"project_revision",
"contact_ids",
"synchronized_contact_ids",
"missing_project_link_contact_ids",
"stale_project_link_contact_ids",
"project_links",
"response_control"
]
},
ProjectResourceLinkRollbackRequest: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
accepted_receipt_id: { type: "string" },
expected_current_revision: { type: "string" },
max_items: { type: "integer", minimum: 1 },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"accepted_receipt_id",
"expected_current_revision",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectResourceLinkProducerBinding: {
type: "object",
additionalProperties: false,
properties: {
authority_id: { type: "string" },
tenant_id: { type: "string" },
corpus_id: { anyOf: [{ type: "string" }, { type: "null" }] },
capability_digest: { type: "string" }
},
required: ["authority_id", "tenant_id", "corpus_id", "capability_digest"]
},
ProjectResourceLinkProducerEvidence: {
type: "object",
additionalProperties: false,
properties: {
created_by_operation: { type: "boolean" },
forward_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
child_link_receipt_ids: { type: "array", items: { type: "string" } },
target_revision: { type: "string" },
target_digest: { type: "string" },
inverse_verified: { anyOf: [{ type: "boolean" }, { type: "null" }] },
inverse_outcome: { anyOf: [{ type: "string" }, { type: "null" }] }
},
required: [
"created_by_operation",
"forward_receipt_id",
"child_link_receipt_ids",
"target_revision",
"target_digest",
"inverse_verified",
"inverse_outcome"
]
},
ProjectResourceLinkMigrationItemInput: {
type: "object",
additionalProperties: false,
properties: {
link: ref2("ProjectResourceLinkInput"),
producer_resource_kind: { type: "string" },
producer_binding: ref2("ProjectResourceLinkProducerBinding")
},
required: ["link", "producer_resource_kind", "producer_binding"]
},
ProjectResourceLinkMigrationItem: {
type: "object",
additionalProperties: false,
properties: {
link: ref2("ProjectResourceLinkInput"),
link_id: { type: "string", pattern: "^prl_" },
producer_resource_kind: { type: "string" },
producer_binding: ref2("ProjectResourceLinkProducerBinding"),
producer_evidence: {
anyOf: [ref2("ProjectResourceLinkProducerEvidence"), { type: "null" }]
}
},
required: [
"link",
"link_id",
"producer_resource_kind",
"producer_binding",
"producer_evidence"
]
},
ProjectResourceLinkProjectsReferenceProof: {
oneOf: [
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["accepted_inverse"] },
forward_receipt_id: { type: "string" },
inverse_receipt_id: { type: "string" },
verified_revision: { type: "string" },
collection_digest: { type: "string" },
link_ids_checked: { type: "array", items: { type: "string" } },
complete: { type: "boolean", enum: [true] },
truncated: { type: "boolean", enum: [false] },
request_digest: { type: "string" },
precondition_digest: { type: "string" }
},
required: [
"kind",
"forward_receipt_id",
"inverse_receipt_id",
"verified_revision",
"collection_digest",
"link_ids_checked",
"complete",
"truncated",
"request_digest",
"precondition_digest"
]
},
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["no_projects_write"] },
verified_revision: { type: "string" },
collection_digest: { type: "string" },
link_ids_checked: { type: "array", items: { type: "string" } },
complete: { type: "boolean", enum: [true] },
truncated: { type: "boolean", enum: [false] },
request_digest: { type: "string" },
precondition_digest: { type: "string" }
},
required: [
"kind",
"verified_revision",
"collection_digest",
"link_ids_checked",
"complete",
"truncated",
"request_digest",
"precondition_digest"
]
}
]
},
ProjectResourceLinkMigrationManifestV1: {
type: "object",
additionalProperties: false,
properties: {
schema: { type: "string", enum: ["projects.project_resource_link_migration_manifest.v1"] },
manifest_id: { type: "string", pattern: "^prlm_" },
project_id: { type: "string" },
operation_id: { type: "string" },
step_id: { type: "string" },
state: {
type: "string",
enum: [
"planned",
"producer_applied",
"projects_applied",
"verified",
"rollback_in_progress",
"rolled_back",
"retained_target",
"failed_reconcilable"
]
},
expected_project_revision: { type: "string" },
desired_collection_digest: { type: "string" },
links: { type: "array", items: ref2("ProjectResourceLinkMigrationItem") },
projects_forward_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
projects_inverse_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
projects_reference_proof: {
anyOf: [ref2("ProjectResourceLinkProjectsReferenceProof"), { type: "null" }]
},
last_verified_projects_revision: { anyOf: [{ type: "string" }, { type: "null" }] },
last_verified_projects_digest: { anyOf: [{ type: "string" }, { type: "null" }] },
transition_version: { type: "integer", minimum: 1 },
created_at: { type: "string" },
updated_at: { type: "string" }
},
required: [
"schema",
"manifest_id",
"project_id",
"operation_id",
"step_id",
"state",
"expected_project_revision",
"desired_collection_digest",
"links",
"projects_forward_receipt_id",
"projects_inverse_receipt_id",
"projects_reference_proof",
"last_verified_projects_revision",
"last_verified_projects_digest",
"transition_version",
"created_at",
"updated_at"
]
},
ProjectResourceLinkMigrationEvent: {
type: "object",
additionalProperties: false,
properties: {
event_id: { type: "string", pattern: "^prlme_" },
manifest_id: { type: "string", pattern: "^prlm_" },
transition_version: { type: "integer", minimum: 1 },
from_state: { anyOf: [{ type: "string" }, { type: "null" }] },
to_state: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
evidence: { type: "object", additionalProperties: true },
created_at: { type: "string" }
},
required: [
"event_id",
"manifest_id",
"transition_version",
"from_state",
"to_state",
"request_digest",
"precondition_digest",
"evidence",
"created_at"
]
},
ProjectResourceLinkMigrationPlanRequest: {
type: "object",
additionalProperties: false,
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
expected_project_revision: { type: "string" },
links: { type: "array", items: ref2("ProjectResourceLinkMigrationItemInput") },
max_items: { type: "integer", minimum: 1 },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"expected_project_revision",
"links",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectResourceLinkMigrationAdvanceRequest: {
type: "object",
additionalProperties: false,
properties: {
expected_transition_version: { type: "integer", minimum: 1 },
next_state: {
type: "string",
enum: ["producer_applied", "projects_applied", "verified", "failed_reconcilable"]
},
max_items: { type: "integer", minimum: 1 },
producer_evidence: {
type: "array",
items: ref2("ProjectResourceLinkProducerEvidence")
},
projects_forward_receipt_id: { type: "string" },
last_verified_projects_revision: { type: "string" },
last_verified_projects_digest: { type: "string" },
evidence: { type: "object", additionalProperties: true },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"expected_transition_version",
"next_state",
"evidence",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectResourceLinkMigrationRollbackRequest: {
type: "object",
additionalProperties: false,
properties: {
expected_transition_version: { type: "integer", minimum: 1 },
max_items: { type: "integer", minimum: 1 },
producer_outcome: {
type: "string",
enum: ["pending", "complete", "retained_target", "failed_reconcilable"]
},
producer_evidence: {
type: "array",
items: ref2("ProjectResourceLinkProducerEvidence")
},
evidence: { type: "object", additionalProperties: true },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"expected_transition_version",
"producer_outcome",
"evidence",
"response_byte_limit",
"time_budget_ms"
]
},
ProjectResourceLinkMigrationResult: {
type: "object",
additionalProperties: false,
properties: {
ok: { type: "boolean" },
outcome: {
type: "string",
enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"]
},
manifest: ref2("ProjectResourceLinkMigrationManifestV1"),
events: { type: "array", items: ref2("ProjectResourceLinkMigrationEvent") },
response_control: ref2("GuardedResponseControl")
},
required: ["ok", "outcome", "manifest", "events", "response_control"]
},
GuardedProjectMutationReceipt: {
type: "object",
properties: {
receipt_id: { type: "string" },
operation_id: { type: "string" },
step_id: { type: "string" },
direction: { type: "string", enum: ["forward", "inverse"] },
idempotency_key: { type: "string" },
target_id: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
expected_revision: { type: "string" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
reason: { type: "string", nullable: true },
result_project_id: { type: "string", nullable: true },
duplicate_of_receipt_id: { type: "string", nullable: true },
before: { type: "object", additionalProperties: true, nullable: true },
after: { type: "object", additionalProperties: true, nullable: true },
post_revision: { type: "string", nullable: true },
created_at: { type: "string" }
},
required: [
"receipt_id",
"operation_id",
"step_id",
"direction",
"idempotency_key",
"target_id",
"request_digest",
"precondition_digest",
"expected_revision",
"outcome",
"reason",
"result_project_id",
"duplicate_of_receipt_id",
"before",
"after",
"post_revision",
"created_at"
]
},
GuardedProjectMutationRequest: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
direction: { type: "string", enum: ["forward", "inverse"] },
expected_revision: { type: "string" },
patch: ref2("UpdateWorkspace"),
dry_run: { type: "boolean" },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: ["operation_id", "step_id", "expected_revision", "patch", "response_byte_limit", "time_budget_ms"]
},
GuardedProjectMutationResult: {
type: "object",
properties: {
ok: { type: "boolean" },
dry_run: { type: "boolean" },
outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
idempotency_key: { type: "string" },
request_digest: { type: "string" },
precondition_digest: { type: "string" },
project_id: { type: "string" },
expected_revision: { type: "string" },
current_revision: { type: "string" },
before: ref2("Workspace"),
after: { anyOf: [ref2("Workspace"), { type: "null" }] },
receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
response_control: ref2("GuardedResponseControl")
},
required: [
"ok",
"dry_run",
"outcome",
"idempotency_key",
"request_digest",
"precondition_digest",
"project_id",
"expected_revision",
"current_revision",
"before",
"after",
"receipt",
"response_control"
]
},
GuardedProjectMutationReceiptLookup: {
type: "object",
properties: {
receipt: ref2("GuardedProjectMutationReceipt"),
response_control: ref2("GuardedResponseControl")
},
required: ["receipt", "response_control"]
},
GuardedProjectMutationRollbackRequest: {
type: "object",
properties: {
operation_id: { type: "string" },
step_id: { type: "string" },
accepted_receipt_id: { type: "string" },
expected_current_revision: { type: "string" },
agent_id: { type: "string" },
source: { type: "string" },
command: { type: "string" },
response_byte_limit: { type: "integer", minimum: 1 },
time_budget_ms: { type: "integer", minimum: 1 }
},
required: [
"operation_id",
"step_id",
"accepted_receipt_id",
"expected_current_revision",
"response_byte_limit",
"time_budget_ms"
]
},
RootList: {
type: "object",
properties: { roots: { type: "array", items: ref2("Root") }, count: { type: "integer" } },
required: ["roots", "count"]
},
AgentList: {
type: "object",
properties: { agents: { type: "array", items: ref2("Agent") }, count: { type: "integer" } },
required: ["agents", "count"]
},
RecipeList: {
type: "object",
properties: { recipes: { type: "array", items: ref2("Recipe") }, count: { type: "integer" } },
required: ["recipes", "count"]
},
Machine: {
type: "object",
properties: {
slug: { type: "string" },
status: { type: "string" },
role: { type: "string", enum: ["mirror-hub", "assignable", "avoid"] }
},
required: ["slug", "status", "role"]
},
MachineList: {
type: "object",
properties: { machines: { type: "array", items: ref2("Machine") }, count: { type: "integer" } },
required: ["machines", "count"]
},
EventList: {
type: "object",
properties: { events: { type: "array", items: ref2("WorkspaceEvent") }, count: { type: "integer" } },
required: ["events", "count"]
},
LocationList: {
type: "object",
properties: { locations: { type: "array", items: ref2("WorkspaceLocation") }, count: { type: "integer" } },
required: ["locations", "count"]
},
LocationAdded: {
type: "object",
properties: { project: ref2("Workspace"), location: ref2("WorkspaceLocation") },
required: ["project", "location"]
},
AgentAssignmentList: {
type: "object",
properties: { assignments: { type: "array", items: ref2("WorkspaceAgentAssignment") }, count: { type: "integer" } },
required: ["assignments", "count"]
},
AgentAssignment: {
type: "object",
properties: { assignment: ref2("WorkspaceAgentAssignment") },
required: ["assignment"]
},
LockList: {
type: "object",
properties: { locks: { type: "array", items: ref2("WorkspaceLock") }, count: { type: "integer" } },
required: ["locks", "count"]
},
LockRelease: {
type: "object",
properties: { released: { type: "boolean" } },
required: ["released"]
},
RecordEvent: {
type: "object",
properties: {
event_type: { type: "string" },
source: { type: "string" },
agent_id: { type: "string" },
prompt: { type: "string" },
command: { type: "string" },
before: { type: "object", additionalProperties: true, nullable: true },
after: { type: "object", additionalProperties: true, nullable: true },
metadata: { type: "object", additionalProperties: true }
},
required: ["event_type"]
},
EventRecorded: {
type: "object",
properties: { event: ref2("WorkspaceEvent") },
required: ["event"]
},
DeleteResult: {
type: "object",
properties: { deleted: { type: "boolean" }, hard: { type: "boolean" }, id: { type: "string" } },
required: ["deleted"]
},
Health: {
type: "object",
properties: { status: { type: "string" }, version: { type: "string" } },
required: ["status", "version"]
},
LegacyVersionResponse: {
type: "object",
description: "Compatibility response for /version.",
properties: {
status: { type: "string" },
version: { type: "string" }
},
required: ["status", "version"]
},
Error: {
type: "object",
properties: { error: { type: "string" }, reason: { type: "string" } },
required: ["error"]
}
}
},
security: [{ apiKey: [] }],
paths: {
...projectionOpenApiPaths,
"/health": {
get: {
operationId: "getHealth",
summary: "Liveness probe",
security: [],
responses: { "200": jsonResp("Health") }
}
},
"/ready": {
get: {
operationId: "getReady",
summary: "Readiness probe (checks DB connectivity)",
security: [],
responses: { "200": jsonResp("Health"), "503": jsonResp("Health", "Not ready") }
}
},
"/version": {
get: {
operationId: "getVersion",
summary: "Service version",
security: [],
responses: { "200": jsonResp("LegacyVersionResponse") }
}
},
"/v1/projects": {
get: {
operationId: "listProjects",
summary: "List projects (workspaces)",
parameters: [
{ name: "status", in: "query", required: false, schema: { type: "string" } },
{ name: "kind", in: "query", required: false, schema: { type: "string" } },
{ name: "root_id", in: "query", required: false, schema: { type: "string" } },
{ name: "query", in: "query", required: false, schema: { type: "string", maxLength: 512 } },
{ name: "query_scope", in: "query", required: false, schema: { type: "string", enum: ["identity", "discovery", "structured", "all"] } },
{ name: "tag", in: "query", required: false, schema: { type: "string", maxLength: 128 } },
{ name: "tags", in: "query", required: false, style: "form", explode: true, schema: { type: "array", maxItems: 50, items: { type: "string", maxLength: 128 } } },
{ name: "exclude_evals", in: "query", required: false, schema: { type: "boolean", default: false } },
{ name: "include_fixtures", in: "query", required: false, schema: { type: "boolean", default: false } },
{
name: "limit",
in: "query",
required: false,
description: `Rows per page (default ${WORKSPACE_LIST_DEFAULT_LIMIT}, clamped to ${WORKSPACE_LIST_MAX_LIMIT}). A larger value is clamped, not honoured \u2014 page with offset and read has_more.`,
schema: { type: "integer" }
},
{ name: "offset", in: "query", required: false, schema: { type: "integer" } }
],
responses: { "200": jsonResp("WorkspaceList") }
},
post: {
operationId: "createProject",
summary: "Create a project (workspace)",
requestBody: jsonBody("CreateWorkspace"),
responses: { "201": jsonResp("Workspace", "Created"), "400": jsonResp("Error", "Invalid") }
}
},
"/v1/projects/{id}": {
get: {
operationId: "getProject",
summary: "Get a project by id or slug",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
},
patch: {
operationId: "updateProject",
summary: "Update a project",
parameters: [ID_PARAM],
requestBody: jsonBody("UpdateWorkspace"),
responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
},
delete: {
operationId: "deleteProject",
summary: "Delete a project (soft by default, ?hard=true for hard delete)",
parameters: [
ID_PARAM,
{ name: "hard", in: "query", required: false, schema: { type: "boolean" } }
],
responses: { "200": jsonResp("DeleteResult"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/projects/{id}/guarded-metadata": {
get: {
operationId: "guardedReadProject",
summary: "Read one project by exact stable id with bounded complete JSON and its current mutation revision",
parameters: [
EXACT_PROJECT_ID_PARAM,
{
name: "response_byte_limit",
in: "query",
required: true,
schema: { type: "integer", minimum: 1 }
},
{
name: "time_budget_ms",
in: "query",
required: true,
schema: { type: "integer", minimum: 1 }
},
{
name: "resource_link_max_items",
in: "query",
required: false,
schema: { type: "integer", minimum: 1, default: 1000 }
}
],
responses: {
"200": jsonResp("GuardedProjectRead"),
"400": jsonResp("Error", "Invalid target or budget"),
"404": jsonResp("Error", "Not found")
}
},
post: {
operationId: "guardedUpdateProject",
summary: "Conditionally update one exact project and return a deterministic terminal receipt",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("GuardedProjectMutationRequest"),
responses: {
"200": jsonResp("GuardedProjectMutationResult"),
"400": jsonResp("Error", "Invalid target, precondition, or budget"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/guarded-metadata/receipts": {
get: {
operationId: "lookupGuardedProjectMutationReceipt",
summary: "Look up exactly one terminal guarded mutation receipt",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "operation_id", in: "query", required: true, schema: { type: "string" } },
{ name: "step_id", in: "query", required: true, schema: { type: "string" } },
{ name: "direction", in: "query", required: true, schema: { type: "string", enum: ["forward", "inverse"] } },
{ name: "idempotency_key", in: "query", required: true, schema: { type: "string" } },
{ name: "max_items", in: "query", required: true, schema: { type: "integer", const: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("GuardedProjectMutationReceiptLookup"),
"400": jsonResp("Error", "Invalid lookup or terminal cardinality"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/guarded-metadata/rollback": {
post: {
operationId: "rollbackGuardedProjectMutation",
summary: "Conditionally roll back one accepted guarded mutation receipt",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("GuardedProjectMutationRollbackRequest"),
responses: {
"200": jsonResp("GuardedProjectMutationResult"),
"400": jsonResp("Error", "Invalid receipt, precondition, or budget"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-links": {
get: {
operationId: "readProjectResourceLinks",
summary: "Read the complete typed project resource-link collection under explicit bounds",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectResourceLinkRead"),
"400": jsonResp("Error", "Invalid target or collection bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-links/add": {
post: {
operationId: "addProjectResourceLinks",
summary: "Idempotently add typed resource links under a project revision CAS",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectResourceLinkMutationRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMutationResult"),
"400": jsonResp("Error", "Invalid link, revision, digest, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-links/reconcile": {
post: {
operationId: "reconcileProjectResourceLinks",
summary: "Reconcile the complete typed resource-link collection under a project revision CAS",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectResourceLinkMutationRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMutationResult"),
"400": jsonResp("Error", "Invalid link, revision, digest, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-links/rollback": {
post: {
operationId: "rollbackProjectResourceLinks",
summary: "Restore the exact pre-mutation typed resource-link collection from an accepted receipt",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectResourceLinkRollbackRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMutationResult"),
"400": jsonResp("Error", "Invalid receipt, revision, digest, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/relations": {
get: {
operationId: "readProjectRelations",
summary: "Read one project's complete two-sided typed relation collection under explicit bounds",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectRelationRead"),
"400": jsonResp("Error", "Invalid target or collection bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/relations/add": {
post: {
operationId: "addProjectRelation",
summary: "Declare the first typed relation for one ordered pair of Projects identities under a project revision CAS",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectRelationMutationRequest"),
responses: {
"200": jsonResp("ProjectRelationMutationResult"),
"400": jsonResp("Error", "Invalid relation, endpoint, revision, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/relations/supersede": {
post: {
operationId: "supersedeProjectRelation",
summary: "Replace the declared typed relation of one ordered pair, preserving the retired version",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectRelationMutationRequest"),
responses: {
"200": jsonResp("ProjectRelationMutationResult"),
"400": jsonResp("Error", "Invalid relation, endpoint, revision, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/duplicate-quarantine": {
get: {
operationId: "readDuplicateProjectQuarantinePreimage",
summary: "Read the exact complete project, resource-link, and path-selector preimage for quarantine",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "resource_link_max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "workspace_location_max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectQuarantineRead"),
"400": jsonResp("Error", "Invalid target or incomplete collection bound"),
"404": jsonResp("Error", "Not found")
}
},
post: {
operationId: "quarantineDuplicateProject",
summary: "Atomically retire duplicate selectors and links while retaining reversible provenance",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectQuarantineRequest"),
responses: {
"200": jsonResp("ProjectQuarantineResult"),
"400": jsonResp("Error", "Invalid precondition, target set, digest, or collection bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/duplicate-quarantine/rollback": {
post: {
operationId: "rollbackDuplicateProjectQuarantine",
summary: "Restore the exact project metadata, resource links, and path selectors from the accepted receipt",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectQuarantineRollbackRequest"),
responses: {
"200": jsonResp("ProjectQuarantineResult"),
"400": jsonResp("Error", "Invalid receipt, revision, digest, or post-write state"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-link-migrations/plan": {
post: {
operationId: "planProjectResourceLinkMigration",
summary: "Persist a durable resource-link migration manifest before any authority write",
parameters: [EXACT_PROJECT_ID_PARAM],
requestBody: jsonBody("ProjectResourceLinkMigrationPlanRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMigrationResult"),
"400": jsonResp("Error", "Invalid link, authority binding, revision, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-link-migrations/{manifestId}": {
get: {
operationId: "readProjectResourceLinkMigration",
summary: "Read one durable migration manifest and its complete immutable event history",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } },
{ name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectResourceLinkMigrationResult"),
"400": jsonResp("Error", "Invalid manifest target or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-link-migrations/{manifestId}/advance": {
post: {
operationId: "advanceProjectResourceLinkMigration",
summary: "CAS-advance a manifest after reconciling exact producer or Projects evidence",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } }
],
requestBody: jsonBody("ProjectResourceLinkMigrationAdvanceRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMigrationResult"),
"400": jsonResp("Error", "Invalid transition, receipt, readback, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/resource-link-migrations/{manifestId}/rollback": {
post: {
operationId: "rollbackProjectResourceLinkMigration",
summary: "Remove Projects references first, persist proof, then record producer rollback outcome",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } }
],
requestBody: jsonBody("ProjectResourceLinkMigrationRollbackRequest"),
responses: {
"200": jsonResp("ProjectResourceLinkMigrationResult"),
"400": jsonResp("Error", "Ambiguous state, failed reference proof, stale transition, or bound"),
"404": jsonResp("Error", "Not found")
}
}
},
"/v1/projects/{id}/contacts": {
get: {
operationId: "listProjectContacts",
summary: "List Contacts-authoritative project memberships and compare synchronized Project resource links",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectContactLinkListResult"),
"400": jsonResp("Error", "Invalid target or collection bound"),
"404": jsonResp("Error", "Not found"),
"503": jsonResp("Error", "Contacts authority is not configured")
}
}
},
"/v1/projects/{id}/contacts/{contact_id}/attach": {
post: {
operationId: "attachProjectContact",
summary: "Attach a Contact through Contacts-authoritative compensation-safe coordination",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "contact_id", in: "path", required: true, schema: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN } }
],
requestBody: jsonBody("ProjectContactLinkMutationRequest"),
responses: {
"200": jsonResp("ProjectContactLinkMutationResult"),
"400": jsonResp("Error", "Invalid target, operation, or bound"),
"404": jsonResp("Error", "Not found"),
"409": jsonResp("Error", "Contacts or Projects compare-and-swap conflict"),
"503": jsonResp("Error", "Contacts authority is not configured")
}
}
},
"/v1/projects/{id}/contacts/{contact_id}/detach": {
post: {
operationId: "detachProjectContact",
summary: "Detach a Contact through Contacts-authoritative compensation-safe coordination",
parameters: [
EXACT_PROJECT_ID_PARAM,
{ name: "contact_id", in: "path", required: true, schema: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN } }
],
requestBody: jsonBody("ProjectContactLinkMutationRequest"),
responses: {
"200": jsonResp("ProjectContactLinkMutationResult"),
"400": jsonResp("Error", "Invalid target, operation, or bound"),
"404": jsonResp("Error", "Not found"),
"409": jsonResp("Error", "Contacts or Projects compare-and-swap conflict"),
"503": jsonResp("Error", "Contacts authority is not configured")
}
}
},
"/v1/projects/{id}/archive": {
post: {
operationId: "archiveProject",
summary: "Archive a project",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/projects/{id}/unarchive": {
post: {
operationId: "unarchiveProject",
summary: "Unarchive a project",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/projects/{id}/events": {
get: {
operationId: "listProjectEvents",
summary: "List a project's events",
parameters: [ID_PARAM, { name: "limit", in: "query", required: false, schema: { type: "integer" } }],
responses: { "200": jsonResp("EventList"), "404": jsonResp("Error", "Not found") }
},
post: {
operationId: "recordProjectEvent",
summary: "Record a custom audit event for a project",
parameters: [ID_PARAM],
requestBody: jsonBody("RecordEvent"),
responses: { "201": jsonResp("EventRecorded", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/projects/{id}/locations": {
get: {
operationId: "listProjectLocations",
summary: "List a project's registered folder locations",
parameters: [ID_PARAM],
responses: { "200": jsonResp("LocationList"), "404": jsonResp("Error", "Not found") }
},
post: {
operationId: "addProjectLocation",
summary: "Register an extra folder location for a project",
parameters: [ID_PARAM],
requestBody: jsonBody("AddWorkspaceLocation"),
responses: { "201": jsonResp("LocationAdded", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/projects/{id}/agents": {
get: {
operationId: "listProjectAgents",
summary: "List a project's agent assignments",
parameters: [ID_PARAM],
responses: { "200": jsonResp("AgentAssignmentList"), "404": jsonResp("Error", "Not found") }
},
post: {
operationId: "assignProjectAgent",
summary: "Assign a registered agent to a project role",
parameters: [ID_PARAM],
requestBody: jsonBody("AssignWorkspaceAgent"),
responses: { "201": jsonResp("AgentAssignment", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/locks": {
get: {
operationId: "listLocks",
summary: "List active project mutation locks",
responses: { "200": jsonResp("LockList") }
},
post: {
operationId: "acquireLock",
summary: "Acquire a project mutation lock",
requestBody: jsonBody("AcquireWorkspaceLock"),
responses: { "201": jsonResp("Lock", "Created"), "400": jsonResp("Error", "Invalid or held") }
}
},
"/v1/locks/{key}": {
delete: {
operationId: "releaseLock",
summary: "Release a project mutation lock (holder-scoped by lock id; key-only DELETE is the force path)",
parameters: [{
name: "key",
in: "path",
required: true,
description: "Lock key",
schema: { type: "string" }
}, {
name: "lock_id",
in: "query",
required: false,
description: "The acquired lock's unique id. When present, releases ONLY that holder's row (a stale holder cannot delete a successor's lock). When absent, the delete is the named force-release path used by the admin unlock verbs.",
schema: { type: "string" }
}],
responses: { "200": jsonResp("LockRelease"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/roots": {
get: {
operationId: "listRoots",
summary: "List roots",
responses: { "200": jsonResp("RootList") }
},
post: {
operationId: "createRoot",
summary: "Create a root",
requestBody: jsonBody("CreateRoot"),
responses: { "201": jsonResp("Root", "Created"), "400": jsonResp("Error", "Invalid") }
}
},
"/v1/roots/{id}": {
get: {
operationId: "getRoot",
summary: "Get a root by id or slug",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Root"), "404": jsonResp("Error", "Not found") }
},
patch: {
operationId: "updateRoot",
summary: "Update a root",
parameters: [ID_PARAM],
requestBody: jsonBody("UpdateRoot"),
responses: { "200": jsonResp("Root"), "404": jsonResp("Error", "Not found") }
},
delete: {
operationId: "deleteRoot",
summary: "Delete a root",
parameters: [
ID_PARAM,
{ name: "detach", in: "query", required: false, schema: { type: "boolean" } }
],
responses: { "200": jsonResp("DeleteResult"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/agents": {
get: {
operationId: "listAgents",
summary: "List agents",
responses: { "200": jsonResp("AgentList") }
},
post: {
operationId: "createAgent",
summary: "Create an agent",
requestBody: jsonBody("CreateAgent"),
responses: { "201": jsonResp("Agent", "Created"), "400": jsonResp("Error", "Invalid") }
}
},
"/v1/agents/{id}": {
get: {
operationId: "getAgent",
summary: "Get an agent by id or slug",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Agent"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/machines": {
get: {
operationId: "listMachines",
summary: "List canonical machines in the registry",
responses: { "200": jsonResp("MachineList") }
}
},
"/v1/recipes": {
get: {
operationId: "listRecipes",
summary: "List recipes",
responses: { "200": jsonResp("RecipeList") }
},
post: {
operationId: "createRecipe",
summary: "Create a recipe",
requestBody: jsonBody("CreateRecipe"),
responses: { "201": jsonResp("Recipe", "Created"), "400": jsonResp("Error", "Invalid") }
}
},
"/v1/recipes/{id}": {
get: {
operationId: "getRecipe",
summary: "Get a recipe by id or slug",
parameters: [ID_PARAM],
responses: { "200": jsonResp("Recipe"), "404": jsonResp("Error", "Not found") }
}
},
"/v1/project-registration/manifests": {
post: {
operationId: "createProjectRegistrationManifest",
summary: "Create or read the immutable manifest for one full-registration operation",
requestBody: jsonBody("ProjectRegistrationManifestCreate"),
responses: {
"200": jsonResp("ProjectRegistrationManifestResult"),
"400": jsonResp("Error", "Invalid"),
"409": jsonResp("Error", "The operation id already has a manifest with different semantics")
}
}
},
"/v1/project-registration/manifests/{operation_id}": {
get: {
operationId: "readProjectRegistrationManifest",
summary: "Read one operation's registration manifest",
parameters: [OPERATION_ID_PARAM],
responses: { "200": jsonResp("ProjectRegistrationManifestRead") }
}
},
"/v1/project-registration/receipts": {
get: {
operationId: "lookupProjectRegistrationReceipt",
summary: "Look up the single terminal receipt for one registration step",
parameters: [
{ name: "operation_id", in: "query", required: true, schema: { type: "string" } },
{ name: "step_id", in: "query", required: true, schema: { type: "string" } },
{ name: "direction", in: "query", required: true, schema: { type: "string", enum: ["forward", "inverse"] } },
{ name: "idempotency_key", in: "query", required: true, schema: { type: "string" } },
{ name: "max_items", in: "query", required: true, schema: { type: "integer", enum: [1] } },
{ name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
{ name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
],
responses: {
"200": jsonResp("ProjectRegistrationReceiptLookup"),
"409": jsonResp("Error", "The step does not resolve to exactly one terminal receipt")
}
},
post: {
operationId: "appendProjectRegistrationReceipt",
summary: "Append one immutable registration receipt (idempotent by content)",
requestBody: jsonBody("ProjectRegistrationReceiptAppend"),
responses: {
"200": jsonResp("ProjectRegistrationReceiptResult"),
"400": jsonResp("Error", "Invalid"),
"409": jsonResp("Error", "The step was already accepted with different semantics")
}
}
},
"/v1/project-registration/operations/{operation_id}/receipts": {
get: {
operationId: "listProjectRegistrationReceipts",
summary: "List an operation's receipts in sequence order, or its accepted step receipts",
parameters: [
OPERATION_ID_PARAM,
{ name: "step_id", in: "query", required: false, schema: { type: "string" } },
{ name: "direction", in: "query", required: false, schema: { type: "string", enum: ["forward", "inverse"] } },
{ name: "outcome", in: "query", required: false, schema: { type: "string", enum: ["accepted"] } },
{ name: "limit", in: "query", required: false, schema: { type: "integer", minimum: 1 } }
],
responses: { "200": jsonResp("ProjectRegistrationReceiptList") }
}
}
}
};
}
// src/lib/project-contact-links.ts
var PROJECT_CONTACT_RESOURCE_LINK_TYPE = {
authority: "contacts",
source_package: "@hasna/contacts",
target_kind: "contact",
locator_kind: "external_uuid",
scope: "resource"
};
var PROJECT_CONTACT_LINK_STEPS = {
contactsMembership: "contacts-membership",
projectsResourceLink: "projects-resource-link"
};
class ProjectContactLinkOperationError extends Error {
code;
stage;
compensated;
cause;
compensation_error;
constructor(input) {
const causeMessage = input.cause instanceof Error ? input.cause.message : String(input.cause);
const suffix = input.compensation_error ? `; compensation failed: ${input.compensation_error instanceof Error ? input.compensation_error.message : String(input.compensation_error)}` : input.compensated ? "; authoritative membership was restored" : "";
super(`${input.code} at ${input.stage}: ${causeMessage}${suffix}`);
this.name = "ProjectContactLinkOperationError";
this.code = input.code;
this.stage = input.stage;
this.compensated = input.compensated;
this.cause = input.cause;
this.compensation_error = input.compensation_error ?? null;
}
}
function uniqueSorted(values) {
return [...new Set(values)].sort((a, b) => a.localeCompare(b));
}
function contactsMembershipStepId(direction, expectedVersion) {
return `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:${direction}:${sha256(expectedVersion).slice(0, 16)}`;
}
function projectContactResourceLink(serviceInstance, contactId, labels) {
return normalizeProjectResourceLink({
authority: PROJECT_CONTACT_RESOURCE_LINK_TYPE.authority,
service_instance: serviceInstance,
source_package: PROJECT_CONTACT_RESOURCE_LINK_TYPE.source_package,
target_kind: PROJECT_CONTACT_RESOURCE_LINK_TYPE.target_kind,
locator: {
kind: PROJECT_CONTACT_RESOURCE_LINK_TYPE.locator_kind,
value: contactId
},
scope: PROJECT_CONTACT_RESOURCE_LINK_TYPE.scope,
labels
});
}
function isProjectContactLink(link, serviceInstance, contactId) {
let sameServiceInstance = false;
try {
sameServiceInstance = canonicalProjectResourceLinkUri(link.service_instance, "project contact link service_instance") === canonicalProjectResourceLinkUri(serviceInstance, "Contacts authority service_instance");
} catch {
return false;
}
return link.authority === PROJECT_CONTACT_RESOURCE_LINK_TYPE.authority && link.source_package === PROJECT_CONTACT_RESOURCE_LINK_TYPE.source_package && link.target_kind === PROJECT_CONTACT_RESOURCE_LINK_TYPE.target_kind && sameServiceInstance && link.locator.kind === PROJECT_CONTACT_RESOURCE_LINK_TYPE.locator_kind && (contactId === undefined || link.locator.value === contactId);
}
function resourceLinkInput(link) {
const { id: _id, project_id: _projectId, created_at: _createdAt, updated_at: _updatedAt, ...input } = link;
return input;
}
function acceptedProjectMutation(result2) {
if (!result2.ok || !result2.after || result2.outcome !== "accepted" && result2.outcome !== "duplicate_of_accepted") {
throw new Error(`Projects resource-link mutation was not accepted: ${result2.outcome}${result2.receipt?.reason ? ` (${result2.receipt.reason})` : ""}`);
}
return result2;
}
function projectEvidence(result2) {
return {
system: "projects",
step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
outcome: result2.outcome,
receipt_id: result2.receipt?.receipt_id ?? null,
compensated: false
};
}
function contactsEvidence(result2, compensated = false) {
return {
system: "contacts",
step_id: result2.step_id,
outcome: result2.outcome,
receipt_id: result2.receipt_id,
compensated
};
}
async function compensateContacts(direction, dependencies, input, contactId, expectedVersion) {
const mutation = direction === "attach" ? dependencies.contacts.attach.bind(dependencies.contacts) : dependencies.contacts.detach.bind(dependencies.contacts);
return mutation({
contact_id: contactId,
project_id: input.project_id,
operation_id: input.operation_id,
step_id: contactsMembershipStepId("compensate", expectedVersion),
expected_version: expectedVersion
});
}
async function listProjectContacts(dependencies, input) {
const [membership, projectRead] = await Promise.all([
dependencies.contacts.listProjectMemberships({
project_id: input.project_id,
max_items: input.max_items
}),
dependencies.projects.readProjectResourceLinks({
project_id: input.project_id,
max_items: input.max_items,
response_byte_limit: input.response_byte_limit,
time_budget_ms: input.time_budget_ms
})
]);
const projectLinks = projectRead.links.filter((link) => isProjectContactLink(link, dependencies.contacts.service_instance));
const contactIds = uniqueSorted(membership.contact_ids);
const projectContactIds = uniqueSorted(projectLinks.map((link) => link.locator.value));
const authoritySet = new Set(contactIds);
const projectSet = new Set(projectContactIds);
return {
ok: true,
authority: "contacts",
project_id: input.project_id,
membership_revision: membership.membership_revision,
project_revision: projectRead.current_revision,
contact_ids: contactIds,
synchronized_contact_ids: contactIds.filter((id) => projectSet.has(id)),
missing_project_link_contact_ids: contactIds.filter((id) => !projectSet.has(id)),
stale_project_link_contact_ids: projectContactIds.filter((id) => !authoritySet.has(id)),
project_links: projectLinks
};
}
async function attachProjectContact(dependencies, input) {
const desiredLink = projectContactResourceLink(dependencies.contacts.service_instance, input.contact_id, input.labels);
const [membershipBefore, projectRead] = await Promise.all([
dependencies.contacts.readMembership({
contact_id: input.contact_id,
project_id: input.project_id
}),
dependencies.projects.readProjectResourceLinks({
project_id: input.project_id,
max_items: input.max_items,
response_byte_limit: input.response_byte_limit,
time_budget_ms: input.time_budget_ms
})
]);
const existingLink = projectRead.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, desiredLink.locator.value));
if (membershipBefore.linked && existingLink) {
return {
ok: true,
outcome: "duplicate_of_accepted",
authority: "contacts",
project_id: input.project_id,
contact_id: desiredLink.locator.value,
membership: membershipBefore,
project_link: existingLink,
evidence: []
};
}
let membershipAfter = membershipBefore;
let membershipMutation = null;
if (!membershipBefore.linked) {
try {
membershipMutation = await dependencies.contacts.attach({
contact_id: desiredLink.locator.value,
project_id: input.project_id,
operation_id: input.operation_id,
step_id: contactsMembershipStepId("forward", membershipBefore.version),
expected_version: membershipBefore.version
});
membershipAfter = membershipMutation.after;
} catch (cause) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_CONTACTS_WRITE_FAILED",
stage: PROJECT_CONTACT_LINK_STEPS.contactsMembership,
compensated: false,
cause
});
}
}
let rawProjectMutation;
try {
rawProjectMutation = await dependencies.projects.mutateProjectResourceLinks({
project_id: input.project_id,
operation_id: input.operation_id,
step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
mode: "add",
expected_revision: projectRead.current_revision,
links: [desiredLink],
max_items: input.max_items,
response_byte_limit: input.response_byte_limit,
time_budget_ms: input.time_budget_ms,
agent_id: input.agent_id,
source: input.source,
command: input.command
});
} catch (cause) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: false,
cause
});
}
let projectMutation;
try {
projectMutation = acceptedProjectMutation(rawProjectMutation);
} catch (cause) {
if (!membershipMutation || membershipBefore.linked) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: false,
cause
});
}
try {
await compensateContacts("detach", dependencies, input, desiredLink.locator.value, membershipAfter.version);
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: true,
cause
});
} catch (compensationError) {
if (compensationError instanceof ProjectContactLinkOperationError && compensationError.code === "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED") {
throw compensationError;
}
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
stage: `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:compensate`,
compensated: false,
cause,
compensation_error: compensationError
});
}
}
const projectLink = projectMutation.after.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, desiredLink.locator.value)) ?? null;
return {
ok: true,
outcome: projectMutation.outcome === "duplicate_of_accepted" && !membershipMutation ? "duplicate_of_accepted" : "accepted",
authority: "contacts",
project_id: input.project_id,
contact_id: desiredLink.locator.value,
membership: membershipAfter,
project_link: projectLink,
evidence: [
...membershipMutation ? [contactsEvidence(membershipMutation)] : [],
projectEvidence(projectMutation)
]
};
}
async function detachProjectContact(dependencies, input) {
const normalized = projectContactResourceLink(dependencies.contacts.service_instance, input.contact_id, input.labels);
const [membershipBefore, projectRead] = await Promise.all([
dependencies.contacts.readMembership({
contact_id: normalized.locator.value,
project_id: input.project_id
}),
dependencies.projects.readProjectResourceLinks({
project_id: input.project_id,
max_items: input.max_items,
response_byte_limit: input.response_byte_limit,
time_budget_ms: input.time_budget_ms
})
]);
const existingLink = projectRead.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, normalized.locator.value));
if (!membershipBefore.linked && !existingLink) {
return {
ok: true,
outcome: "duplicate_of_accepted",
authority: "contacts",
project_id: input.project_id,
contact_id: normalized.locator.value,
membership: membershipBefore,
project_link: null,
evidence: []
};
}
let membershipAfter = membershipBefore;
let membershipMutation = null;
if (membershipBefore.linked) {
try {
membershipMutation = await dependencies.contacts.detach({
contact_id: normalized.locator.value,
project_id: input.project_id,
operation_id: input.operation_id,
step_id: contactsMembershipStepId("forward", membershipBefore.version),
expected_version: membershipBefore.version
});
membershipAfter = membershipMutation.after;
} catch (cause) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_CONTACTS_WRITE_FAILED",
stage: PROJECT_CONTACT_LINK_STEPS.contactsMembership,
compensated: false,
cause
});
}
}
let projectMutation = null;
if (existingLink) {
const desired = projectRead.links.filter((link) => link.id !== existingLink.id).map(resourceLinkInput);
let rawProjectMutation;
try {
rawProjectMutation = await dependencies.projects.mutateProjectResourceLinks({
project_id: input.project_id,
operation_id: input.operation_id,
step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
mode: "reconcile",
expected_revision: projectRead.current_revision,
links: desired,
max_items: input.max_items,
response_byte_limit: input.response_byte_limit,
time_budget_ms: input.time_budget_ms,
agent_id: input.agent_id,
source: input.source,
command: input.command
});
} catch (cause) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: false,
cause
});
}
try {
projectMutation = acceptedProjectMutation(rawProjectMutation);
} catch (cause) {
if (!membershipMutation || !membershipBefore.linked) {
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: false,
cause
});
}
try {
await compensateContacts("attach", dependencies, input, normalized.locator.value, membershipAfter.version);
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED",
stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
compensated: true,
cause
});
} catch (compensationError) {
if (compensationError instanceof ProjectContactLinkOperationError && compensationError.code === "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED") {
throw compensationError;
}
throw new ProjectContactLinkOperationError({
code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
stage: `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:compensate`,
compensated: false,
cause,
compensation_error: compensationError
});
}
}
}
return {
ok: true,
outcome: projectMutation || membershipMutation ? "accepted" : "duplicate_of_accepted",
authority: "contacts",
project_id: input.project_id,
contact_id: normalized.locator.value,
membership: membershipAfter,
project_link: null,
evidence: [
...membershipMutation ? [contactsEvidence(membershipMutation)] : [],
...projectMutation ? [projectEvidence(projectMutation)] : []
]
};
}
// src/lib/contacts-authority-adapter.ts
import { resolveClientTransport, resolveCredential } from "@hasna/contracts/client";
class ContactsAuthorityHttpError extends Error {
status;
method;
path;
constructor(input) {
super(`Contacts authority ${input.method} ${input.path} failed: ${input.detail}`);
this.name = "ContactsAuthorityHttpError";
this.status = input.status;
this.method = input.method;
this.path = input.path;
}
}
// src/lib/project-list-output.ts
var PROJECT_QUERY_SCOPES = ["identity", "discovery", "structured", "all"];
var PROJECT_LIST_FIELDS = [
"id",
"slug",
"name",
"status",
"kind",
"path",
"canonical_machine",
"root_id",
"recipe_id",
"git_remote",
"updated_at"
];
var DEFAULT_PROJECT_LIST_MAX_BYTES = 32 * 1024;
var MAX_PROJECT_LIST_MAX_BYTES = 256 * 1024;
var MAX_PROJECT_QUERY_LENGTH = 512;
var MAX_PROJECT_QUERY_TAGS = 50;
var MAX_PROJECT_QUERY_TAG_LENGTH = 128;
var PROJECT_LIST_V2_CONTRACT = "projects.list.v2";
var PROJECT_LIST_FIELD_SET = new Set(PROJECT_LIST_FIELDS);
var PROJECT_QUERY_SCOPE_SET = new Set(PROJECT_QUERY_SCOPES);
function isProjectQueryScope(value) {
return PROJECT_QUERY_SCOPE_SET.has(value);
}
// src/serve/app.ts
var READ_SCOPE = "projects:read";
var WRITE_SCOPE = "projects:write";
function jsonResponse(body, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json", ...extraHeaders }
});
}
function boundedJsonResponse(body, bounds2, startedAtMs, status = 200) {
const payload = {
...body && typeof body === "object" && !Array.isArray(body) ? body : { data: body }
};
payload["response_control"] = responseControl(payload, bounds2, startedAtMs);
return jsonResponse(payload, status);
}
function guardedJsonResponse(body, bounds2, startedAtMs, status = 200) {
if (body && typeof body === "object" && !Array.isArray(body) && "response_control" in body) {
return jsonResponse(body, status);
}
return boundedJsonResponse(body, bounds2, startedAtMs, status);
}
function errorResponse(message, status, reason) {
return jsonResponse(reason ? { error: message, reason } : { error: message }, status);
}
function statusForError(err) {
if (err instanceof NotFoundError)
return 404;
if (err instanceof ProjectRegistrationLedgerError)
return err.status;
if (err instanceof ValidationError)
return 400;
if (err instanceof ContactsAuthorityHttpError)
return err.status;
if (err instanceof ProjectContactLinkOperationError) {
const causeStatus = statusForError(err.cause);
if (causeStatus !== 500)
return causeStatus;
if (err.cause instanceof Error && /(not accepted|revision|precondition|conflict|expected[_ ]version)/i.test(err.cause.message)) {
return 409;
}
return 502;
}
return 500;
}
function toBool(value) {
return value === "1" || value === "true" || value === "yes";
}
async function readJsonBody(req) {
const text = await req.text();
if (!text.trim())
return {};
try {
const parsed = JSON.parse(text);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
return parsed;
throw new ValidationError("request body must be a JSON object");
} catch (err) {
if (err instanceof ValidationError)
throw err;
throw new ValidationError("invalid JSON body");
}
}
function createFetchHandler(options) {
const { store, version, contacts } = options;
const projectionPolicy = validateProjectionPolicy(options.projectionPolicy);
const appName = options.app ?? "projects";
const verifier = verifyApiKey({
app: appName,
signingSecret: options.signingSecret,
...options.keyStatus ? { keyStatus: options.keyStatus } : {},
...options.allowUnregisteredKeys ? { allowUnregisteredKeys: true } : {},
...options.audit ? { audit: options.audit } : {}
});
return async function handle(req) {
const url = new URL(req.url);
const path = url.pathname.replace(/\/+$/, "") || "/";
const method = req.method.toUpperCase();
if (path === "/health" && method === "GET") {
return jsonResponse({ status: "ok", version });
}
if (path === "/version" && method === "GET") {
return jsonResponse({ status: "ok", version });
}
if (path === "/ready" && method === "GET") {
try {
const ok = await store.ping();
return ok ? jsonResponse({ status: "ready", version }) : jsonResponse({ status: "degraded", version }, 503);
} catch {
return jsonResponse({ status: "unavailable", version }, 503);
}
}
if (path === "/openapi.json" && method === "GET") {
return jsonResponse(buildOpenApiSpec(version));
}
if (path === "/" && method === "GET") {
return jsonResponse({ name: `${appName}-serve`, version, openapi: "/openapi.json" });
}
if (!path.startsWith("/v1/")) {
return errorResponse("Not found", 404);
}
const requiredScopes = method === "GET" ? [READ_SCOPE] : [WRITE_SCOPE];
const decision = await verifier.authenticate(req.headers, { method, path, requiredScopes });
if (!decision.ok) {
return errorResponse(decision.message, decision.status, decision.reason);
}
const projectionPath = /^\/v1\/projects\/([^/]+)\/product-projections(?:\/([^/]+))?$/.exec(path);
if (projectionPath) {
try {
const projectId = projectionPath[1];
const receiptId = projectionPath[2];
if (method === "POST" && !receiptId) {
authorizeProjection(projectionPolicy, decision.principal, projectId, "issue");
return jsonResponse(await store.issueProductProjection(projectionPolicy, decision.principal, projectId, await readProjectionBody(req)), 201);
}
if (method === "GET" && receiptId) {
authorizeProjection(projectionPolicy, decision.principal, projectId, "read");
const q = url.searchParams;
if ([...q.keys()].some((k) => !["response_byte_limit", "time_budget_ms"].includes(k)) || q.getAll("response_byte_limit").length !== 1 || q.getAll("time_budget_ms").length !== 1)
throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
return jsonResponse(await store.readProductProjection(projectionPolicy, decision.principal, projectId, receiptId, {
response_byte_limit: Number(q.get("response_byte_limit")),
time_budget_ms: Number(q.get("time_budget_ms"))
}));
}
return errorResponse("PROJECTION_METHOD_NOT_ALLOWED", 405);
} catch (error) {
return errorResponse(error instanceof ProjectionError ? error.code : "PROJECTION_REQUEST_REFUSED", error instanceof ProjectionError ? error.status : 422);
}
}
try {
return await route(req, url, path, method, store, contacts);
} catch (err) {
const status = statusForError(err);
const message = err instanceof Error ? err.message : "internal error";
if (status === 500)
console.error("projects-serve error:", err);
return errorResponse(message, status, err instanceof ProjectRegistrationLedgerError ? err.reason : undefined);
}
};
}
function requiredText(value, label) {
if (typeof value !== "string" || value.length === 0) {
throw new ValidationError(`${label} must be a non-empty string`);
}
return value;
}
function optionalText(value, label) {
if (value === undefined || value === null)
return null;
if (typeof value !== "string")
throw new ValidationError(`${label} must be a string`);
return value;
}
function jsonObjectField(value, label) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new ValidationError(`${label} must be a JSON object`);
}
return value;
}
function optionalObjectArray(value, label) {
if (value === undefined || value === null)
return [];
if (!Array.isArray(value))
throw new ValidationError(`${label} must be an array`);
return value.map((item) => jsonObjectField(item, `${label} entry`));
}
function registrationDirection(value) {
const direction = requiredText(value, "direction");
if (direction !== "forward" && direction !== "inverse") {
throw new ValidationError("direction must be forward or inverse");
}
return direction;
}
function registrationOutcome(value) {
const outcome = requiredText(value, "outcome");
if (outcome !== "accepted" && outcome !== "duplicate_of_accepted" && outcome !== "terminal_nonacceptance") {
throw new ValidationError("outcome must be accepted, duplicate_of_accepted or terminal_nonacceptance");
}
return outcome;
}
function requiredQuery(url, keys) {
const q = url.searchParams;
for (const key of q.keys()) {
if (!keys.includes(key))
throw new ValidationError(`unexpected query parameter '${key}'`);
}
for (const key of keys) {
if (q.getAll(key).length !== 1) {
throw new ValidationError(`query parameter '${key}' must be provided exactly once`);
}
}
return q;
}
function positiveIntegerQuery(q, key) {
const value = Number(q.get(key));
if (!Number.isInteger(value) || value < 1) {
throw new ValidationError(`query parameter '${key}' must be a positive integer`);
}
return value;
}
async function route(req, url, path, method, store, contacts) {
const segments = path.split("/").filter(Boolean);
const [, resource2, id, sub, extra, action] = segments;
if (resource2 === "project-registration") {
if (id === "manifests" && sub === undefined) {
if (method === "POST") {
const body = await readJsonBody(req);
return jsonResponse(await store.createProjectRegistrationManifest({
operation_id: requiredText(body.operation_id, "operation_id"),
request_digest: requiredText(body.request_digest, "request_digest"),
project_id: requiredText(body.project_id, "project_id"),
project_slug: requiredText(body.project_slug, "project_slug"),
plan: jsonObjectField(body.plan, "plan")
}));
}
return errorResponse("REGISTRATION_METHOD_NOT_ALLOWED", 405);
}
if (id === "manifests" && sub !== undefined && method === "GET") {
return jsonResponse({ manifest: await store.readProjectRegistrationManifest(sub) });
}
if (id === "receipts" && sub === undefined && method === "POST") {
const body = await readJsonBody(req);
const receipt = await store.appendProjectRegistrationReceipt({
operation_id: requiredText(body.operation_id, "operation_id"),
step_id: requiredText(body.step_id, "step_id"),
authority: requiredText(body.authority, "authority"),
resource_kind: requiredText(body.resource_kind, "resource_kind"),
direction: registrationDirection(body.direction),
idempotency_key: requiredText(body.idempotency_key, "idempotency_key"),
target_id: optionalText(body.target_id, "target_id"),
request_digest: requiredText(body.request_digest, "request_digest"),
precondition_digest: requiredText(body.precondition_digest, "precondition_digest"),
outcome: registrationOutcome(body.outcome),
reason: optionalText(body.reason, "reason"),
result_revision: optionalText(body.result_revision, "result_revision"),
result_digest: optionalText(body.result_digest, "result_digest"),
duplicate_of_receipt_id: optionalText(body.duplicate_of_receipt_id, "duplicate_of_receipt_id"),
authority_receipt: body.authority_receipt === undefined || body.authority_receipt === null ? null : jsonObjectField(body.authority_receipt, "authority_receipt"),
artifacts: optionalObjectArray(body.artifacts, "artifacts"),
preconditions: optionalObjectArray(body.preconditions, "preconditions"),
rollback: optionalObjectArray(body.rollback, "rollback")
});
return jsonResponse({ receipt });
}
if (id === "receipts" && sub === undefined && method === "GET") {
const q = requiredQuery(url, [
"operation_id",
"step_id",
"direction",
"idempotency_key",
"max_items",
"response_byte_limit",
"time_budget_ms"
]);
if (q.get("max_items") !== "1") {
throw new ValidationError("query parameter 'max_items' must be exactly 1");
}
const lookup = await store.lookupProjectRegistrationReceipt({
operation_id: requiredText(q.get("operation_id"), "operation_id"),
step_id: requiredText(q.get("step_id"), "step_id"),
direction: registrationDirection(q.get("direction")),
idempotency_key: requiredText(q.get("idempotency_key"), "idempotency_key"),
max_items: 1,
response_byte_limit: positiveIntegerQuery(q, "response_byte_limit"),
time_budget_ms: positiveIntegerQuery(q, "time_budget_ms")
});
return jsonResponse(lookup);
}
if (id === "operations" && sub !== undefined && extra === "receipts" && method === "GET") {
const q = url.searchParams;
for (const key of q.keys()) {
if (!["step_id", "direction", "outcome", "limit"].includes(key)) {
throw new ValidationError(`unexpected query parameter '${key}'`);
}
}
const stepId = q.get("step_id");
const direction = q.get("direction");
const outcome = q.get("outcome");
const limit = q.get("limit");
if (stepId !== null || direction !== null || outcome !== null || limit !== null) {
if (stepId === null || direction === null || outcome !== "accepted" || limit === null) {
throw new ValidationError("a bounded receipt read requires step_id, direction, outcome=accepted and limit");
}
const bounded = Number(limit);
if (!Number.isInteger(bounded) || bounded < 1) {
throw new ValidationError("limit must be a positive integer");
}
return jsonResponse({
receipts: await store.findProjectRegistrationReceipts({
operation_id: sub,
step_id: stepId,
direction: registrationDirection(direction),
limit: bounded
})
});
}
return jsonResponse({ receipts: await store.listProjectRegistrationReceipts(sub) });
}
return errorResponse("REGISTRATION_ROUTE_NOT_FOUND", 404);
}
if (resource2 === "projects") {
if (!id) {
if (method === "GET") {
const q = url.searchParams;
const rawQueryScope = q.get("query_scope");
const additiveTags = q.getAll("tags");
const usesV2Filters = rawQueryScope !== null || additiveTags.length > 0 || q.has("exclude_evals");
const legacyTag = q.get("tag");
const rawTags = usesV2Filters ? [...legacyTag ? [legacyTag] : [], ...additiveTags] : legacyTag ? [legacyTag] : [];
if (usesV2Filters && rawTags.length > MAX_PROJECT_QUERY_TAGS) {
throw new ValidationError(`at most ${MAX_PROJECT_QUERY_TAGS} project tags may be queried`);
}
const tags = [...new Set(rawTags.filter(Boolean))];
if (usesV2Filters && tags.some((value) => value.length > MAX_PROJECT_QUERY_TAG_LENGTH)) {
throw new ValidationError(`project query tags must be at most ${MAX_PROJECT_QUERY_TAG_LENGTH} characters`);
}
const query = q.get("query");
if (usesV2Filters && query && query.length > MAX_PROJECT_QUERY_LENGTH) {
throw new ValidationError(`query must be at most ${MAX_PROJECT_QUERY_LENGTH} characters`);
}
let queryScope;
if (rawQueryScope) {
if (!isProjectQueryScope(rawQueryScope)) {
throw new ValidationError("query_scope must be one of: identity, discovery, structured, all");
}
queryScope = rawQueryScope;
}
const includeFixtures = q.get("include_fixtures") === "true";
const excludeEvals = q.get("exclude_evals") === "true";
const filter = {
...q.get("status") ? { status: q.get("status") } : {},
...q.get("kind") ? { kind: q.get("kind") } : {},
...q.get("root_id") ? { root_id: q.get("root_id") } : {},
...query ? { query } : {},
...queryScope ? { query_scope: queryScope } : {},
...tags.length ? { tags } : {},
...includeFixtures ? {} : { exclude_registry_fixtures: true },
...excludeEvals ? { exclude_eval_artifacts: true } : {},
...q.get("limit") ? { limit: Number(q.get("limit")) } : {},
...q.get("offset") ? { offset: Number(q.get("offset")) } : {}
};
const workspaces = await store.listWorkspaces(filter);
const offset = Math.max(Number(q.get("offset") ?? 0) || 0, 0);
const total = await store.countWorkspaces(filter);
return jsonResponse({
filter_contract: PROJECT_LIST_V2_CONTRACT,
applied_filters: {
query_scope: queryScope ?? "legacy",
tags,
exclude_evals: excludeEvals,
exclude_registry_fixtures: !includeFixtures
},
workspaces,
count: workspaces.length,
total,
offset,
limit: Math.min(Math.max(filter.limit ?? WORKSPACE_LIST_DEFAULT_LIMIT, 1), WORKSPACE_LIST_MAX_LIMIT),
has_more: offset + workspaces.length < total,
complete: offset === 0 && workspaces.length === total
});
}
if (method === "POST") {
const body = await readJsonBody(req);
const workspace = await store.createWorkspace(body);
return jsonResponse(workspace, 201);
}
return errorResponse("Method not allowed", 405);
}
if (!sub) {
if (method === "GET")
return jsonResponse(await store.requireWorkspace(id));
if (method === "PATCH" || method === "PUT") {
const body = await readJsonBody(req);
return jsonResponse(await store.updateWorkspace(id, body));
}
if (method === "DELETE") {
const hard = toBool(url.searchParams.get("hard"));
const result2 = await store.deleteWorkspace(id, { hard });
return jsonResponse({ deleted: true, hard: result2.hard, id: result2.workspace.id });
}
return errorResponse("Method not allowed", 405);
}
if (sub === "guarded-metadata" && extra === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.guardedReadWorkspace({
project_id: id,
resource_link_max_items: Number(url.searchParams.get("resource_link_max_items") ?? 1000),
...bounds2
}, started);
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "guarded-metadata" && extra === undefined && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.guardedUpdateWorkspace({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "guarded-metadata" && extra === "receipts" && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.lookupGuardedWorkspaceMutationReceipt({
project_id: id,
operation_id: url.searchParams.get("operation_id") ?? "",
step_id: url.searchParams.get("step_id") ?? "",
direction: url.searchParams.get("direction") ?? "forward",
idempotency_key: url.searchParams.get("idempotency_key") ?? "",
max_items: Number(url.searchParams.get("max_items")),
...bounds2
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "guarded-metadata" && extra === "rollback" && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.rollbackGuardedWorkspaceMutation({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "relations" && extra === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.readProjectRelations({
project_id: id,
max_items: Number(url.searchParams.get("max_items")),
...bounds2
}, started);
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "relations" && (extra === "add" || extra === "supersede") && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.mutateProjectRelation({
...body,
project_id: id,
mode: extra
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-links" && extra === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.readProjectResourceLinks({
project_id: id,
max_items: Number(url.searchParams.get("max_items")),
...bounds2
}, started);
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-links" && (extra === "add" || extra === "reconcile") && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.mutateProjectResourceLinks({
...body,
project_id: id,
mode: extra
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-links" && extra === "rollback" && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.rollbackProjectResourceLinks({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "duplicate-quarantine" && extra === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.readDuplicateProjectQuarantinePreimage({
project_id: id,
resource_link_max_items: Number(url.searchParams.get("resource_link_max_items")),
workspace_location_max_items: Number(url.searchParams.get("workspace_location_max_items")),
...bounds2
}, started);
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "duplicate-quarantine" && extra === undefined && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.quarantineDuplicateProject({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "duplicate-quarantine" && extra === "rollback" && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.rollbackDuplicateProjectQuarantine({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-link-migrations" && extra === "plan" && action === undefined && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.planProjectResourceLinkMigration({ ...body, project_id: id });
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-link-migrations" && extra && action === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await store.readProjectResourceLinkMigration({
project_id: id,
manifest_id: extra,
max_items: Number(url.searchParams.get("max_items")),
...bounds2
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-link-migrations" && extra && action === "advance" && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.advanceProjectResourceLinkMigration({
...body,
project_id: id,
manifest_id: extra
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "resource-link-migrations" && extra && action === "rollback" && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const result2 = await store.rollbackProjectResourceLinkMigration({
...body,
project_id: id,
manifest_id: extra
});
return guardedJsonResponse(result2, bounds2, started);
}
if (sub === "contacts") {
if (!contacts)
return errorResponse("Contacts authority is not configured", 503);
if (extra === undefined && method === "GET") {
const started = Date.now();
const bounds2 = {
max_items: Number(url.searchParams.get("max_items")),
response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
};
const result2 = await listProjectContacts({ projects: store, contacts }, {
project_id: id,
...bounds2
});
return boundedJsonResponse(result2, bounds2, started);
}
if (extra && (action === "attach" || action === "detach") && method === "POST") {
const started = Date.now();
const body = await readJsonBody(req);
const bounds2 = {
max_items: Number(body.max_items),
response_byte_limit: Number(body.response_byte_limit),
time_budget_ms: Number(body.time_budget_ms)
};
const mutation = action === "attach" ? attachProjectContact : detachProjectContact;
const result2 = await mutation({ projects: store, contacts }, {
project_id: id,
contact_id: extra,
operation_id: String(body.operation_id ?? ""),
...body.labels && typeof body.labels === "object" ? { labels: body.labels } : {},
...bounds2,
source: "system",
command: `${method} ${path}`
});
return boundedJsonResponse(result2, bounds2, started);
}
return errorResponse("Method not allowed", 405);
}
if (sub === "archive" && method === "POST")
return jsonResponse(await store.archiveWorkspace(id));
if (sub === "unarchive" && method === "POST")
return jsonResponse(await store.unarchiveWorkspace(id));
if (sub === "events" && method === "GET") {
const ws = await store.requireWorkspace(id);
const limit = url.searchParams.get("limit");
const events = await store.listWorkspaceEvents(ws.id, limit ? Number(limit) : undefined);
return jsonResponse({ events, count: events.length });
}
if (sub === "locations" && method === "GET") {
const ws = await store.requireWorkspace(id);
const locations = await store.listWorkspaceLocations(ws.id);
return jsonResponse({ locations, count: locations.length });
}
if (sub === "locations" && method === "POST") {
const ws = await store.requireWorkspace(id);
const body = await readJsonBody(req);
if (typeof body.path !== "string" || !body.path.trim()) {
throw new ValidationError("path is required");
}
const location = await store.addWorkspaceLocation({
workspace_id: ws.id,
path: body.path,
machine_id: typeof body.machine_id === "string" ? body.machine_id : undefined,
label: typeof body.label === "string" ? body.label : undefined,
kind: typeof body.kind === "string" ? body.kind : undefined,
is_primary: typeof body.is_primary === "boolean" ? body.is_primary : undefined,
metadata: body.metadata ?? undefined,
agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
source: "system",
command: "POST /v1/projects/:id/locations"
});
const updated = await store.requireWorkspace(ws.id);
return jsonResponse({ project: updated, location }, 201);
}
if (sub === "agents" && method === "GET") {
const ws = await store.requireWorkspace(id);
const assignments = await store.listWorkspaceAgents(ws.id);
return jsonResponse({ assignments, count: assignments.length });
}
if (sub === "agents" && method === "POST") {
const ws = await store.requireWorkspace(id);
const body = await readJsonBody(req);
if (typeof body.agent_id !== "string" || !body.agent_id.trim()) {
throw new ValidationError("agent_id is required");
}
const assignment = await store.assignAgentToWorkspace({
workspace_id: ws.id,
agent_id: body.agent_id,
role: typeof body.role === "string" ? body.role : undefined,
assigned_by: typeof body.assigned_by === "string" ? body.assigned_by : undefined,
metadata: body.metadata ?? undefined
});
await store.recordEvent({
workspace_id: ws.id,
agent_id: assignment.assigned_by ?? undefined,
event_type: "agent_assigned",
source: "system",
command: "POST /v1/projects/:id/agents",
after: { agent_id: assignment.agent_id, role: assignment.role, assignment_id: assignment.id }
});
return jsonResponse({ assignment }, 201);
}
if (sub === "events" && method === "POST") {
const ws = await store.requireWorkspace(id);
const body = await readJsonBody(req);
if (typeof body.event_type !== "string" || !body.event_type.trim()) {
throw new ValidationError("event_type is required");
}
const event = await store.recordEvent({
workspace_id: ws.id,
agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
event_type: body.event_type,
source: typeof body.source === "string" ? body.source : "system",
prompt: typeof body.prompt === "string" ? body.prompt : undefined,
command: typeof body.command === "string" ? body.command : undefined,
before: body.before ?? undefined,
after: body.after ?? undefined,
metadata: body.metadata ?? undefined
});
return jsonResponse({ event }, 201);
}
return errorResponse("Not found", 404);
}
if (resource2 === "roots") {
if (!id) {
if (method === "GET") {
const roots = await store.listRoots();
return jsonResponse({ roots, count: roots.length });
}
if (method === "POST") {
const body = await readJsonBody(req);
return jsonResponse(await store.createRoot(body), 201);
}
return errorResponse("Method not allowed", 405);
}
if (method === "GET") {
const root = await store.getRoot(id);
if (!root)
return errorResponse(`Root not found: ${id}`, 404);
return jsonResponse(root);
}
if (method === "PATCH" || method === "PUT") {
const body = await readJsonBody(req);
return jsonResponse(await store.updateRoot(id, body));
}
if (method === "DELETE") {
const detach = toBool(url.searchParams.get("detach"));
const result2 = await store.deleteRoot(id, detach);
return jsonResponse({ deleted: true, id: result2.root.id, detached_workspaces: result2.detached_workspaces });
}
return errorResponse("Method not allowed", 405);
}
if (resource2 === "agents") {
if (!id) {
if (method === "GET") {
const agents = await store.listAgents();
return jsonResponse({ agents, count: agents.length });
}
if (method === "POST") {
const body = await readJsonBody(req);
return jsonResponse(await store.createAgent(body), 201);
}
return errorResponse("Method not allowed", 405);
}
if (method === "GET") {
const agent = await store.getAgent(id);
if (!agent)
return errorResponse(`Agent not found: ${id}`, 404);
return jsonResponse(agent);
}
return errorResponse("Method not allowed", 405);
}
if (resource2 === "locks") {
if (method === "GET" && !id) {
const locks = await store.listLocks();
return jsonResponse({ locks, count: locks.length });
}
if (method === "POST" && !id) {
const body = await readJsonBody(req);
if (typeof body.lock_key !== "string" || !body.lock_key.trim()) {
throw new ValidationError("lock_key is required");
}
const lock = await store.acquireLock({
lock_key: body.lock_key,
workspace_id: typeof body.workspace_id === "string" ? body.workspace_id : undefined,
agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
reason: typeof body.reason === "string" ? body.reason : undefined,
ttl_seconds: typeof body.ttl_seconds === "number" ? body.ttl_seconds : undefined
});
return jsonResponse({ lock }, 201);
}
if (method === "DELETE" && id) {
const lockKey = decodeURIComponent(id);
const lockId = url.searchParams.get("lock_id");
const released = lockId ? await store.releaseLock(lockKey, lockId) : await store.forceReleaseLock(lockKey);
return jsonResponse({ released });
}
return errorResponse("Method not allowed", 405);
}
if (resource2 === "recipes") {
if (!id) {
if (method === "GET") {
const recipes = await store.listRecipes();
return jsonResponse({ recipes, count: recipes.length });
}
if (method === "POST") {
const body = await readJsonBody(req);
return jsonResponse(await store.createRecipe(body), 201);
}
return errorResponse("Method not allowed", 405);
}
if (method === "GET") {
const recipe = await store.getRecipe(id);
if (!recipe)
return errorResponse(`Recipe not found: ${id}`, 404);
return jsonResponse(recipe);
}
return errorResponse("Method not allowed", 405);
}
if (resource2 === "machines") {
if (id)
return errorResponse("Not found", 404);
if (method === "GET") {
const machines = await store.listMachines();
return jsonResponse({ machines, count: machines.length });
}
return errorResponse("Method not allowed", 405);
}
return errorResponse("Not found", 404);
}
export {
createFetchHandler
};