@shortcut/mcp 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1657 -1653
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -14567,1296 +14567,925 @@ var require_lib = __commonJS((exports) => {
14567
14567
  __exportStar(require_data_contracts(), exports);
14568
14568
  });
14569
14569
 
14570
- // src/client/cache.ts
14571
- class Cache {
14572
- cache;
14573
- age;
14574
- constructor() {
14575
- this.cache = new Map;
14576
- this.age = 0;
14577
- }
14578
- get(key) {
14579
- return this.cache.get(key) ?? null;
14580
- }
14581
- values() {
14582
- return Array.from(this.cache.values());
14570
+ // node_modules/zod/lib/index.mjs
14571
+ var util;
14572
+ (function(util2) {
14573
+ util2.assertEqual = (val) => val;
14574
+ function assertIs(_arg) {}
14575
+ util2.assertIs = assertIs;
14576
+ function assertNever(_x) {
14577
+ throw new Error;
14583
14578
  }
14584
- setMany(values) {
14585
- this.cache.clear();
14586
- for (const [key, value] of values) {
14587
- this.cache.set(key, value);
14579
+ util2.assertNever = assertNever;
14580
+ util2.arrayToEnum = (items) => {
14581
+ const obj = {};
14582
+ for (const item of items) {
14583
+ obj[item] = item;
14588
14584
  }
14589
- this.age = Date.now();
14590
- }
14591
- clear() {
14592
- this.cache.clear();
14593
- this.age = 0;
14585
+ return obj;
14586
+ };
14587
+ util2.getValidEnumValues = (obj) => {
14588
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
14589
+ const filtered = {};
14590
+ for (const k of validKeys) {
14591
+ filtered[k] = obj[k];
14592
+ }
14593
+ return util2.objectValues(filtered);
14594
+ };
14595
+ util2.objectValues = (obj) => {
14596
+ return util2.objectKeys(obj).map(function(e) {
14597
+ return obj[e];
14598
+ });
14599
+ };
14600
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
14601
+ const keys = [];
14602
+ for (const key in object) {
14603
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
14604
+ keys.push(key);
14605
+ }
14606
+ }
14607
+ return keys;
14608
+ };
14609
+ util2.find = (arr, checker) => {
14610
+ for (const item of arr) {
14611
+ if (checker(item))
14612
+ return item;
14613
+ }
14614
+ return;
14615
+ };
14616
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
14617
+ function joinValues(array, separator = " | ") {
14618
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
14594
14619
  }
14595
- get isStale() {
14596
- return Date.now() - this.age > 1000 * 60 * 5;
14620
+ util2.joinValues = joinValues;
14621
+ util2.jsonStringifyReplacer = (_, value) => {
14622
+ if (typeof value === "bigint") {
14623
+ return value.toString();
14624
+ }
14625
+ return value;
14626
+ };
14627
+ })(util || (util = {}));
14628
+ var objectUtil;
14629
+ (function(objectUtil2) {
14630
+ objectUtil2.mergeShapes = (first, second) => {
14631
+ return {
14632
+ ...first,
14633
+ ...second
14634
+ };
14635
+ };
14636
+ })(objectUtil || (objectUtil = {}));
14637
+ var ZodParsedType = util.arrayToEnum([
14638
+ "string",
14639
+ "nan",
14640
+ "number",
14641
+ "integer",
14642
+ "float",
14643
+ "boolean",
14644
+ "date",
14645
+ "bigint",
14646
+ "symbol",
14647
+ "function",
14648
+ "undefined",
14649
+ "null",
14650
+ "array",
14651
+ "object",
14652
+ "unknown",
14653
+ "promise",
14654
+ "void",
14655
+ "never",
14656
+ "map",
14657
+ "set"
14658
+ ]);
14659
+ var getParsedType = (data) => {
14660
+ const t = typeof data;
14661
+ switch (t) {
14662
+ case "undefined":
14663
+ return ZodParsedType.undefined;
14664
+ case "string":
14665
+ return ZodParsedType.string;
14666
+ case "number":
14667
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
14668
+ case "boolean":
14669
+ return ZodParsedType.boolean;
14670
+ case "function":
14671
+ return ZodParsedType.function;
14672
+ case "bigint":
14673
+ return ZodParsedType.bigint;
14674
+ case "symbol":
14675
+ return ZodParsedType.symbol;
14676
+ case "object":
14677
+ if (Array.isArray(data)) {
14678
+ return ZodParsedType.array;
14679
+ }
14680
+ if (data === null) {
14681
+ return ZodParsedType.null;
14682
+ }
14683
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
14684
+ return ZodParsedType.promise;
14685
+ }
14686
+ if (typeof Map !== "undefined" && data instanceof Map) {
14687
+ return ZodParsedType.map;
14688
+ }
14689
+ if (typeof Set !== "undefined" && data instanceof Set) {
14690
+ return ZodParsedType.set;
14691
+ }
14692
+ if (typeof Date !== "undefined" && data instanceof Date) {
14693
+ return ZodParsedType.date;
14694
+ }
14695
+ return ZodParsedType.object;
14696
+ default:
14697
+ return ZodParsedType.unknown;
14597
14698
  }
14598
- }
14699
+ };
14700
+ var ZodIssueCode = util.arrayToEnum([
14701
+ "invalid_type",
14702
+ "invalid_literal",
14703
+ "custom",
14704
+ "invalid_union",
14705
+ "invalid_union_discriminator",
14706
+ "invalid_enum_value",
14707
+ "unrecognized_keys",
14708
+ "invalid_arguments",
14709
+ "invalid_return_type",
14710
+ "invalid_date",
14711
+ "invalid_string",
14712
+ "too_small",
14713
+ "too_big",
14714
+ "invalid_intersection_types",
14715
+ "not_multiple_of",
14716
+ "not_finite"
14717
+ ]);
14718
+ var quotelessJson = (obj) => {
14719
+ const json = JSON.stringify(obj, null, 2);
14720
+ return json.replace(/"([^"]+)":/g, "$1:");
14721
+ };
14599
14722
 
14600
- // src/client/shortcut.ts
14601
- class ShortcutClientWrapper {
14602
- client;
14603
- currentUser = null;
14604
- userCache;
14605
- teamCache;
14606
- workflowCache;
14607
- constructor(client) {
14608
- this.client = client;
14609
- this.userCache = new Cache;
14610
- this.teamCache = new Cache;
14611
- this.workflowCache = new Cache;
14723
+ class ZodError extends Error {
14724
+ get errors() {
14725
+ return this.issues;
14612
14726
  }
14613
- async loadMembers() {
14614
- if (this.userCache.isStale) {
14615
- const response = await this.client.listMembers({});
14616
- const members = response?.data ?? null;
14617
- if (members) {
14618
- this.userCache.setMany(members.map((member) => [member.id, member]));
14619
- }
14727
+ constructor(issues) {
14728
+ super();
14729
+ this.issues = [];
14730
+ this.addIssue = (sub) => {
14731
+ this.issues = [...this.issues, sub];
14732
+ };
14733
+ this.addIssues = (subs = []) => {
14734
+ this.issues = [...this.issues, ...subs];
14735
+ };
14736
+ const actualProto = new.target.prototype;
14737
+ if (Object.setPrototypeOf) {
14738
+ Object.setPrototypeOf(this, actualProto);
14739
+ } else {
14740
+ this.__proto__ = actualProto;
14620
14741
  }
14742
+ this.name = "ZodError";
14743
+ this.issues = issues;
14621
14744
  }
14622
- async loadTeams() {
14623
- if (this.teamCache.isStale) {
14624
- const response = await this.client.listGroups();
14625
- const groups = response?.data ?? null;
14626
- if (groups) {
14627
- this.teamCache.setMany(groups.map((group) => [group.id, group]));
14745
+ format(_mapper) {
14746
+ const mapper = _mapper || function(issue) {
14747
+ return issue.message;
14748
+ };
14749
+ const fieldErrors = { _errors: [] };
14750
+ const processError = (error) => {
14751
+ for (const issue of error.issues) {
14752
+ if (issue.code === "invalid_union") {
14753
+ issue.unionErrors.map(processError);
14754
+ } else if (issue.code === "invalid_return_type") {
14755
+ processError(issue.returnTypeError);
14756
+ } else if (issue.code === "invalid_arguments") {
14757
+ processError(issue.argumentsError);
14758
+ } else if (issue.path.length === 0) {
14759
+ fieldErrors._errors.push(mapper(issue));
14760
+ } else {
14761
+ let curr = fieldErrors;
14762
+ let i = 0;
14763
+ while (i < issue.path.length) {
14764
+ const el = issue.path[i];
14765
+ const terminal = i === issue.path.length - 1;
14766
+ if (!terminal) {
14767
+ curr[el] = curr[el] || { _errors: [] };
14768
+ } else {
14769
+ curr[el] = curr[el] || { _errors: [] };
14770
+ curr[el]._errors.push(mapper(issue));
14771
+ }
14772
+ curr = curr[el];
14773
+ i++;
14774
+ }
14775
+ }
14628
14776
  }
14777
+ };
14778
+ processError(this);
14779
+ return fieldErrors;
14780
+ }
14781
+ static assert(value) {
14782
+ if (!(value instanceof ZodError)) {
14783
+ throw new Error(`Not a ZodError: ${value}`);
14629
14784
  }
14630
14785
  }
14631
- async loadWorkflows() {
14632
- if (this.workflowCache.isStale) {
14633
- const response = await this.client.listWorkflows();
14634
- const workflows = response?.data ?? null;
14635
- if (workflows) {
14636
- this.workflowCache.setMany(workflows.map((workflow) => [workflow.id, workflow]));
14637
- }
14638
- }
14639
- }
14640
- async getCurrentUser() {
14641
- if (this.currentUser)
14642
- return this.currentUser;
14643
- const response = await this.client.getCurrentMemberInfo();
14644
- const user = response?.data;
14645
- if (!user)
14646
- return null;
14647
- this.currentUser = user;
14648
- return user;
14786
+ toString() {
14787
+ return this.message;
14649
14788
  }
14650
- async getUser(userId) {
14651
- const response = await this.client.getMember(userId, {});
14652
- const user = response?.data;
14653
- if (!user)
14654
- return null;
14655
- return user;
14789
+ get message() {
14790
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
14656
14791
  }
14657
- async getUserMap(userIds) {
14658
- await this.loadMembers();
14659
- return new Map(userIds.map((id) => [id, this.userCache.get(id)]).filter((user) => user[1] !== null));
14792
+ get isEmpty() {
14793
+ return this.issues.length === 0;
14660
14794
  }
14661
- async getUsers(userIds) {
14662
- await this.loadMembers();
14663
- return userIds.map((id) => this.userCache.get(id)).filter((user) => user !== null);
14795
+ flatten(mapper = (issue) => issue.message) {
14796
+ const fieldErrors = {};
14797
+ const formErrors = [];
14798
+ for (const sub of this.issues) {
14799
+ if (sub.path.length > 0) {
14800
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
14801
+ fieldErrors[sub.path[0]].push(mapper(sub));
14802
+ } else {
14803
+ formErrors.push(mapper(sub));
14804
+ }
14805
+ }
14806
+ return { formErrors, fieldErrors };
14664
14807
  }
14665
- async listMembers() {
14666
- await this.loadMembers();
14667
- const members = Array.from(this.userCache.values());
14668
- return members;
14808
+ get formErrors() {
14809
+ return this.flatten();
14669
14810
  }
14670
- async getWorkflowMap(workflowIds) {
14671
- await this.loadWorkflows();
14672
- return new Map(workflowIds.map((id) => [id, this.workflowCache.get(id)]).filter((workflow) => workflow[1] !== null));
14811
+ }
14812
+ ZodError.create = (issues) => {
14813
+ const error = new ZodError(issues);
14814
+ return error;
14815
+ };
14816
+ var errorMap = (issue, _ctx) => {
14817
+ let message;
14818
+ switch (issue.code) {
14819
+ case ZodIssueCode.invalid_type:
14820
+ if (issue.received === ZodParsedType.undefined) {
14821
+ message = "Required";
14822
+ } else {
14823
+ message = `Expected ${issue.expected}, received ${issue.received}`;
14824
+ }
14825
+ break;
14826
+ case ZodIssueCode.invalid_literal:
14827
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
14828
+ break;
14829
+ case ZodIssueCode.unrecognized_keys:
14830
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
14831
+ break;
14832
+ case ZodIssueCode.invalid_union:
14833
+ message = `Invalid input`;
14834
+ break;
14835
+ case ZodIssueCode.invalid_union_discriminator:
14836
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
14837
+ break;
14838
+ case ZodIssueCode.invalid_enum_value:
14839
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
14840
+ break;
14841
+ case ZodIssueCode.invalid_arguments:
14842
+ message = `Invalid function arguments`;
14843
+ break;
14844
+ case ZodIssueCode.invalid_return_type:
14845
+ message = `Invalid function return type`;
14846
+ break;
14847
+ case ZodIssueCode.invalid_date:
14848
+ message = `Invalid date`;
14849
+ break;
14850
+ case ZodIssueCode.invalid_string:
14851
+ if (typeof issue.validation === "object") {
14852
+ if ("includes" in issue.validation) {
14853
+ message = `Invalid input: must include "${issue.validation.includes}"`;
14854
+ if (typeof issue.validation.position === "number") {
14855
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
14856
+ }
14857
+ } else if ("startsWith" in issue.validation) {
14858
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
14859
+ } else if ("endsWith" in issue.validation) {
14860
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
14861
+ } else {
14862
+ util.assertNever(issue.validation);
14863
+ }
14864
+ } else if (issue.validation !== "regex") {
14865
+ message = `Invalid ${issue.validation}`;
14866
+ } else {
14867
+ message = "Invalid";
14868
+ }
14869
+ break;
14870
+ case ZodIssueCode.too_small:
14871
+ if (issue.type === "array")
14872
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
14873
+ else if (issue.type === "string")
14874
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
14875
+ else if (issue.type === "number")
14876
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
14877
+ else if (issue.type === "date")
14878
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
14879
+ else
14880
+ message = "Invalid input";
14881
+ break;
14882
+ case ZodIssueCode.too_big:
14883
+ if (issue.type === "array")
14884
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
14885
+ else if (issue.type === "string")
14886
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
14887
+ else if (issue.type === "number")
14888
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
14889
+ else if (issue.type === "bigint")
14890
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
14891
+ else if (issue.type === "date")
14892
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
14893
+ else
14894
+ message = "Invalid input";
14895
+ break;
14896
+ case ZodIssueCode.custom:
14897
+ message = `Invalid input`;
14898
+ break;
14899
+ case ZodIssueCode.invalid_intersection_types:
14900
+ message = `Intersection results could not be merged`;
14901
+ break;
14902
+ case ZodIssueCode.not_multiple_of:
14903
+ message = `Number must be a multiple of ${issue.multipleOf}`;
14904
+ break;
14905
+ case ZodIssueCode.not_finite:
14906
+ message = "Number must be finite";
14907
+ break;
14908
+ default:
14909
+ message = _ctx.defaultError;
14910
+ util.assertNever(issue);
14673
14911
  }
14674
- async getWorkflows() {
14675
- await this.loadWorkflows();
14676
- return Array.from(this.workflowCache.values());
14912
+ return { message };
14913
+ };
14914
+ var overrideErrorMap = errorMap;
14915
+ function setErrorMap(map) {
14916
+ overrideErrorMap = map;
14917
+ }
14918
+ function getErrorMap() {
14919
+ return overrideErrorMap;
14920
+ }
14921
+ var makeIssue = (params) => {
14922
+ const { data, path, errorMaps, issueData } = params;
14923
+ const fullPath = [...path, ...issueData.path || []];
14924
+ const fullIssue = {
14925
+ ...issueData,
14926
+ path: fullPath
14927
+ };
14928
+ if (issueData.message !== undefined) {
14929
+ return {
14930
+ ...issueData,
14931
+ path: fullPath,
14932
+ message: issueData.message
14933
+ };
14677
14934
  }
14678
- async getWorkflow(workflowPublicId) {
14679
- const response = await this.client.getWorkflow(workflowPublicId);
14680
- const workflow = response?.data;
14681
- if (!workflow)
14682
- return null;
14683
- return workflow;
14935
+ let errorMessage = "";
14936
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
14937
+ for (const map of maps) {
14938
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
14684
14939
  }
14685
- async getTeams() {
14686
- await this.loadTeams();
14687
- const teams = Array.from(this.teamCache.values());
14688
- return teams;
14940
+ return {
14941
+ ...issueData,
14942
+ path: fullPath,
14943
+ message: errorMessage
14944
+ };
14945
+ };
14946
+ var EMPTY_PATH = [];
14947
+ function addIssueToContext(ctx, issueData) {
14948
+ const overrideMap = getErrorMap();
14949
+ const issue = makeIssue({
14950
+ issueData,
14951
+ data: ctx.data,
14952
+ path: ctx.path,
14953
+ errorMaps: [
14954
+ ctx.common.contextualErrorMap,
14955
+ ctx.schemaErrorMap,
14956
+ overrideMap,
14957
+ overrideMap === errorMap ? undefined : errorMap
14958
+ ].filter((x) => !!x)
14959
+ });
14960
+ ctx.common.issues.push(issue);
14961
+ }
14962
+
14963
+ class ParseStatus {
14964
+ constructor() {
14965
+ this.value = "valid";
14689
14966
  }
14690
- async getTeamMap(teamIds) {
14691
- await this.loadTeams();
14692
- return new Map(teamIds.map((id) => [id, this.teamCache.get(id)]).filter((team) => team[1] !== null));
14967
+ dirty() {
14968
+ if (this.value === "valid")
14969
+ this.value = "dirty";
14693
14970
  }
14694
- async getTeam(teamPublicId) {
14695
- const response = await this.client.getGroup(teamPublicId);
14696
- const group = response?.data;
14697
- if (!group)
14698
- return null;
14699
- return group;
14971
+ abort() {
14972
+ if (this.value !== "aborted")
14973
+ this.value = "aborted";
14700
14974
  }
14701
- async createStory(params) {
14702
- const response = await this.client.createStory(params);
14703
- const story = response?.data ?? null;
14704
- if (!story)
14705
- throw new Error(`Failed to create the story: ${response.status}`);
14706
- return story;
14975
+ static mergeArray(status, results) {
14976
+ const arrayValue = [];
14977
+ for (const s of results) {
14978
+ if (s.status === "aborted")
14979
+ return INVALID;
14980
+ if (s.status === "dirty")
14981
+ status.dirty();
14982
+ arrayValue.push(s.value);
14983
+ }
14984
+ return { status: status.value, value: arrayValue };
14707
14985
  }
14708
- async updateStory(storyPublicId, params) {
14709
- const response = await this.client.updateStory(storyPublicId, params);
14710
- const story = response?.data ?? null;
14711
- if (!story)
14712
- throw new Error(`Failed to update the story: ${response.status}`);
14713
- return story;
14714
- }
14715
- async getStory(storyPublicId) {
14716
- const response = await this.client.getStory(storyPublicId);
14717
- const story = response?.data ?? null;
14718
- if (!story)
14719
- return null;
14720
- return story;
14721
- }
14722
- async getEpic(epicPublicId) {
14723
- const response = await this.client.getEpic(epicPublicId);
14724
- const epic = response?.data ?? null;
14725
- if (!epic)
14726
- return null;
14727
- return epic;
14728
- }
14729
- async getIteration(iterationPublicId) {
14730
- const response = await this.client.getIteration(iterationPublicId);
14731
- const iteration = response?.data ?? null;
14732
- if (!iteration)
14733
- return null;
14734
- return iteration;
14735
- }
14736
- async getMilestone(milestonePublicId) {
14737
- const response = await this.client.getMilestone(milestonePublicId);
14738
- const milestone = response?.data ?? null;
14739
- if (!milestone)
14740
- return null;
14741
- return milestone;
14986
+ static async mergeObjectAsync(status, pairs) {
14987
+ const syncPairs = [];
14988
+ for (const pair of pairs) {
14989
+ const key = await pair.key;
14990
+ const value = await pair.value;
14991
+ syncPairs.push({
14992
+ key,
14993
+ value
14994
+ });
14995
+ }
14996
+ return ParseStatus.mergeObjectSync(status, syncPairs);
14742
14997
  }
14743
- async searchStories(query) {
14744
- const response = await this.client.searchStories({ query, page_size: 25, detail: "full" });
14745
- const stories = response?.data?.data;
14746
- const total = response?.data?.total;
14747
- if (!stories)
14748
- return { stories: null, total: null };
14749
- return { stories, total };
14998
+ static mergeObjectSync(status, pairs) {
14999
+ const finalObject = {};
15000
+ for (const pair of pairs) {
15001
+ const { key, value } = pair;
15002
+ if (key.status === "aborted")
15003
+ return INVALID;
15004
+ if (value.status === "aborted")
15005
+ return INVALID;
15006
+ if (key.status === "dirty")
15007
+ status.dirty();
15008
+ if (value.status === "dirty")
15009
+ status.dirty();
15010
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
15011
+ finalObject[key.value] = value.value;
15012
+ }
15013
+ }
15014
+ return { status: status.value, value: finalObject };
14750
15015
  }
14751
- async searchIterations(query) {
14752
- const response = await this.client.searchIterations({ query, page_size: 25, detail: "full" });
14753
- const iterations = response?.data?.data;
14754
- const total = response?.data?.total;
14755
- if (!iterations)
14756
- return { iterations: null, total: null };
14757
- return { iterations, total };
15016
+ }
15017
+ var INVALID = Object.freeze({
15018
+ status: "aborted"
15019
+ });
15020
+ var DIRTY = (value) => ({ status: "dirty", value });
15021
+ var OK = (value) => ({ status: "valid", value });
15022
+ var isAborted = (x) => x.status === "aborted";
15023
+ var isDirty = (x) => x.status === "dirty";
15024
+ var isValid = (x) => x.status === "valid";
15025
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
15026
+ function __classPrivateFieldGet(receiver, state, kind, f) {
15027
+ if (kind === "a" && !f)
15028
+ throw new TypeError("Private accessor was defined without a getter");
15029
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
15030
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
15031
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15032
+ }
15033
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
15034
+ if (kind === "m")
15035
+ throw new TypeError("Private method is not writable");
15036
+ if (kind === "a" && !f)
15037
+ throw new TypeError("Private accessor was defined without a setter");
15038
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
15039
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
15040
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
15041
+ }
15042
+ var errorUtil;
15043
+ (function(errorUtil2) {
15044
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
15045
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === undefined ? undefined : message.message;
15046
+ })(errorUtil || (errorUtil = {}));
15047
+ var _ZodEnum_cache;
15048
+ var _ZodNativeEnum_cache;
15049
+
15050
+ class ParseInputLazyPath {
15051
+ constructor(parent, value, path, key) {
15052
+ this._cachedPath = [];
15053
+ this.parent = parent;
15054
+ this.data = value;
15055
+ this._path = path;
15056
+ this._key = key;
14758
15057
  }
14759
- async getActiveIteration(teamIds) {
14760
- const response = await this.client.listIterations();
14761
- const iterations = response?.data;
14762
- if (!iterations)
14763
- return new Map;
14764
- const [today] = new Date().toISOString().split("T");
14765
- const activeIterationByTeam = iterations.reduce((acc, iteration) => {
14766
- if (iteration.status !== "started")
14767
- return acc;
14768
- const [startDate] = new Date(iteration.start_date).toISOString().split("T");
14769
- const [endDate] = new Date(iteration.end_date).toISOString().split("T");
14770
- if (!startDate || !endDate)
14771
- return acc;
14772
- if (startDate > today || endDate < today)
14773
- return acc;
14774
- if (!iteration.group_ids?.length)
14775
- iteration.group_ids = ["none"];
14776
- for (const groupId of iteration.group_ids) {
14777
- if (groupId !== "none" && !teamIds.includes(groupId))
14778
- continue;
14779
- const prevIterations = acc.get(groupId);
14780
- if (prevIterations) {
14781
- acc.set(groupId, prevIterations.concat([iteration]));
14782
- } else
14783
- acc.set(groupId, [iteration]);
15058
+ get path() {
15059
+ if (!this._cachedPath.length) {
15060
+ if (this._key instanceof Array) {
15061
+ this._cachedPath.push(...this._path, ...this._key);
15062
+ } else {
15063
+ this._cachedPath.push(...this._path, this._key);
14784
15064
  }
14785
- return acc;
14786
- }, new Map);
14787
- return activeIterationByTeam;
15065
+ }
15066
+ return this._cachedPath;
14788
15067
  }
14789
- async getUpcomingIteration(teamIds) {
14790
- const response = await this.client.listIterations();
14791
- const iterations = response?.data;
14792
- if (!iterations)
14793
- return new Map;
14794
- const [today] = new Date().toISOString().split("T");
14795
- const upcomingIterationByTeam = iterations.reduce((acc, iteration) => {
14796
- if (iteration.status !== "unstarted")
14797
- return acc;
14798
- const [startDate] = new Date(iteration.start_date).toISOString().split("T");
14799
- const [endDate] = new Date(iteration.end_date).toISOString().split("T");
14800
- if (!startDate || !endDate)
14801
- return acc;
14802
- if (startDate < today)
14803
- return acc;
14804
- if (!iteration.group_ids?.length)
14805
- iteration.group_ids = ["none"];
14806
- for (const groupId of iteration.group_ids) {
14807
- if (groupId !== "none" && !teamIds.includes(groupId))
14808
- continue;
14809
- const prevIterations = acc.get(groupId);
14810
- if (prevIterations) {
14811
- acc.set(groupId, prevIterations.concat([iteration]));
14812
- } else
14813
- acc.set(groupId, [iteration]);
15068
+ }
15069
+ var handleResult = (ctx, result) => {
15070
+ if (isValid(result)) {
15071
+ return { success: true, data: result.value };
15072
+ } else {
15073
+ if (!ctx.common.issues.length) {
15074
+ throw new Error("Validation failed but no issues detected.");
15075
+ }
15076
+ return {
15077
+ success: false,
15078
+ get error() {
15079
+ if (this._error)
15080
+ return this._error;
15081
+ const error = new ZodError(ctx.common.issues);
15082
+ this._error = error;
15083
+ return this._error;
14814
15084
  }
14815
- return acc;
14816
- }, new Map);
14817
- return upcomingIterationByTeam;
14818
- }
14819
- async searchEpics(query) {
14820
- const response = await this.client.searchEpics({ query, page_size: 25, detail: "full" });
14821
- const epics = response?.data?.data;
14822
- const total = response?.data?.total;
14823
- if (!epics)
14824
- return { epics: null, total: null };
14825
- return { epics, total };
15085
+ };
14826
15086
  }
14827
- async searchMilestones(query) {
14828
- const response = await this.client.searchMilestones({ query, page_size: 25, detail: "full" });
14829
- const milestones = response?.data?.data;
14830
- const total = response?.data?.total;
14831
- if (!milestones)
14832
- return { milestones: null, total: null };
14833
- return { milestones, total };
15087
+ };
15088
+ function processCreateParams(params) {
15089
+ if (!params)
15090
+ return {};
15091
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
15092
+ if (errorMap2 && (invalid_type_error || required_error)) {
15093
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
14834
15094
  }
14835
- async listIterationStories(iterationPublicId, includeDescription = false) {
14836
- const response = await this.client.listIterationStories(iterationPublicId, {
14837
- includes_description: includeDescription
14838
- });
14839
- const stories = response?.data;
14840
- if (!stories)
14841
- return { stories: null, total: null };
14842
- return { stories, total: stories.length };
15095
+ if (errorMap2)
15096
+ return { errorMap: errorMap2, description };
15097
+ const customMap = (iss, ctx) => {
15098
+ var _a, _b;
15099
+ const { message } = params;
15100
+ if (iss.code === "invalid_enum_value") {
15101
+ return { message: message !== null && message !== undefined ? message : ctx.defaultError };
15102
+ }
15103
+ if (typeof ctx.data === "undefined") {
15104
+ return { message: (_a = message !== null && message !== undefined ? message : required_error) !== null && _a !== undefined ? _a : ctx.defaultError };
15105
+ }
15106
+ if (iss.code !== "invalid_type")
15107
+ return { message: ctx.defaultError };
15108
+ return { message: (_b = message !== null && message !== undefined ? message : invalid_type_error) !== null && _b !== undefined ? _b : ctx.defaultError };
15109
+ };
15110
+ return { errorMap: customMap, description };
15111
+ }
15112
+
15113
+ class ZodType {
15114
+ get description() {
15115
+ return this._def.description;
14843
15116
  }
14844
- async createStoryComment(storyPublicId, params) {
14845
- const response = await this.client.createStoryComment(storyPublicId, params);
14846
- const storyComment = response?.data ?? null;
14847
- if (!storyComment)
14848
- throw new Error(`Failed to create the comment: ${response.status}`);
14849
- return storyComment;
15117
+ _getType(input) {
15118
+ return getParsedType(input.data);
14850
15119
  }
14851
- async createIteration(params) {
14852
- const response = await this.client.createIteration(params);
14853
- const iteration = response?.data ?? null;
14854
- if (!iteration)
14855
- throw new Error(`Failed to create the iteration: ${response.status}`);
14856
- return iteration;
14857
- }
14858
- async createEpic(params) {
14859
- const response = await this.client.createEpic(params);
14860
- const epic = response?.data ?? null;
14861
- if (!epic)
14862
- throw new Error(`Failed to create the epic: ${response.status}`);
14863
- return epic;
15120
+ _getOrReturnCtx(input, ctx) {
15121
+ return ctx || {
15122
+ common: input.parent.common,
15123
+ data: input.data,
15124
+ parsedType: getParsedType(input.data),
15125
+ schemaErrorMap: this._def.errorMap,
15126
+ path: input.path,
15127
+ parent: input.parent
15128
+ };
14864
15129
  }
14865
- async addTaskToStory(storyPublicId, taskParams) {
14866
- const { description, ownerIds } = taskParams;
14867
- const params = {
14868
- description,
14869
- owner_ids: ownerIds
15130
+ _processInputParams(input) {
15131
+ return {
15132
+ status: new ParseStatus,
15133
+ ctx: {
15134
+ common: input.parent.common,
15135
+ data: input.data,
15136
+ parsedType: getParsedType(input.data),
15137
+ schemaErrorMap: this._def.errorMap,
15138
+ path: input.path,
15139
+ parent: input.parent
15140
+ }
14870
15141
  };
14871
- const response = await this.client.createTask(storyPublicId, params);
14872
- const task = response?.data ?? null;
14873
- if (!task)
14874
- throw new Error(`Failed to create the task: ${response.status}`);
14875
- return task;
14876
15142
  }
14877
- async addRelationToStory(storyPublicId, linkedStoryId, verb) {
14878
- const response = await this.client.createStoryLink({
14879
- object_id: linkedStoryId,
14880
- subject_id: storyPublicId,
14881
- verb
14882
- });
14883
- const storyLink = response?.data ?? null;
14884
- if (!storyLink)
14885
- throw new Error(`Failed to create the story links: ${response.status}`);
14886
- return storyLink;
15143
+ _parseSync(input) {
15144
+ const result = this._parse(input);
15145
+ if (isAsync(result)) {
15146
+ throw new Error("Synchronous parse encountered promise.");
15147
+ }
15148
+ return result;
14887
15149
  }
14888
- async getTask(storyPublicId, taskPublicId) {
14889
- const response = await this.client.getTask(storyPublicId, taskPublicId);
14890
- const task = response?.data ?? null;
14891
- if (!task)
14892
- throw new Error(`Failed to get the task: ${response.status}`);
14893
- return task;
15150
+ _parseAsync(input) {
15151
+ const result = this._parse(input);
15152
+ return Promise.resolve(result);
14894
15153
  }
14895
- async updateTask(storyPublicId, taskPublicId, taskParams) {
14896
- const { description, ownerIds } = taskParams;
14897
- const params = {
14898
- description,
14899
- owner_ids: ownerIds,
14900
- complete: taskParams.isCompleted
15154
+ parse(data, params) {
15155
+ const result = this.safeParse(data, params);
15156
+ if (result.success)
15157
+ return result.data;
15158
+ throw result.error;
15159
+ }
15160
+ safeParse(data, params) {
15161
+ var _a;
15162
+ const ctx = {
15163
+ common: {
15164
+ issues: [],
15165
+ async: (_a = params === null || params === undefined ? undefined : params.async) !== null && _a !== undefined ? _a : false,
15166
+ contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap
15167
+ },
15168
+ path: (params === null || params === undefined ? undefined : params.path) || [],
15169
+ schemaErrorMap: this._def.errorMap,
15170
+ parent: null,
15171
+ data,
15172
+ parsedType: getParsedType(data)
14901
15173
  };
14902
- const response = await this.client.updateTask(storyPublicId, taskPublicId, params);
14903
- const task = response?.data ?? null;
14904
- if (!task)
14905
- throw new Error(`Failed to update the task: ${response.status}`);
14906
- return task;
15174
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
15175
+ return handleResult(ctx, result);
14907
15176
  }
14908
- async addExternalLinkToStory(storyPublicId, externalLink) {
14909
- const story = await this.getStory(storyPublicId);
14910
- if (!story)
14911
- throw new Error(`Story ${storyPublicId} not found`);
14912
- const currentLinks = story.external_links || [];
14913
- if (currentLinks.some((link) => link.toLowerCase() === externalLink.toLowerCase())) {
14914
- return story;
15177
+ "~validate"(data) {
15178
+ var _a, _b;
15179
+ const ctx = {
15180
+ common: {
15181
+ issues: [],
15182
+ async: !!this["~standard"].async
15183
+ },
15184
+ path: [],
15185
+ schemaErrorMap: this._def.errorMap,
15186
+ parent: null,
15187
+ data,
15188
+ parsedType: getParsedType(data)
15189
+ };
15190
+ if (!this["~standard"].async) {
15191
+ try {
15192
+ const result = this._parseSync({ data, path: [], parent: ctx });
15193
+ return isValid(result) ? {
15194
+ value: result.value
15195
+ } : {
15196
+ issues: ctx.common.issues
15197
+ };
15198
+ } catch (err) {
15199
+ if ((_b = (_a = err === null || err === undefined ? undefined : err.message) === null || _a === undefined ? undefined : _a.toLowerCase()) === null || _b === undefined ? undefined : _b.includes("encountered")) {
15200
+ this["~standard"].async = true;
15201
+ }
15202
+ ctx.common = {
15203
+ issues: [],
15204
+ async: true
15205
+ };
15206
+ }
14915
15207
  }
14916
- const updatedLinks = [...currentLinks, externalLink];
14917
- return await this.updateStory(storyPublicId, { external_links: updatedLinks });
14918
- }
14919
- async removeExternalLinkFromStory(storyPublicId, externalLink) {
14920
- const story = await this.getStory(storyPublicId);
14921
- if (!story)
14922
- throw new Error(`Story ${storyPublicId} not found`);
14923
- const currentLinks = story.external_links || [];
14924
- const updatedLinks = currentLinks.filter((link) => link.toLowerCase() !== externalLink.toLowerCase());
14925
- return await this.updateStory(storyPublicId, { external_links: updatedLinks });
14926
- }
14927
- async getStoriesByExternalLink(externalLink) {
14928
- const response = await this.client.getExternalLinkStories({
14929
- external_link: externalLink.toLowerCase()
15208
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
15209
+ value: result.value
15210
+ } : {
15211
+ issues: ctx.common.issues
14930
15212
  });
14931
- const stories = response?.data;
14932
- if (!stories)
14933
- return { stories: null, total: null };
14934
- return { stories, total: stories.length };
14935
15213
  }
14936
- async setStoryExternalLinks(storyPublicId, externalLinks) {
14937
- return await this.updateStory(storyPublicId, { external_links: externalLinks });
15214
+ async parseAsync(data, params) {
15215
+ const result = await this.safeParseAsync(data, params);
15216
+ if (result.success)
15217
+ return result.data;
15218
+ throw result.error;
14938
15219
  }
14939
- }
14940
-
14941
- // node_modules/zod/lib/index.mjs
14942
- var util;
14943
- (function(util2) {
14944
- util2.assertEqual = (val) => val;
14945
- function assertIs(_arg) {}
14946
- util2.assertIs = assertIs;
14947
- function assertNever(_x) {
14948
- throw new Error;
15220
+ async safeParseAsync(data, params) {
15221
+ const ctx = {
15222
+ common: {
15223
+ issues: [],
15224
+ contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap,
15225
+ async: true
15226
+ },
15227
+ path: (params === null || params === undefined ? undefined : params.path) || [],
15228
+ schemaErrorMap: this._def.errorMap,
15229
+ parent: null,
15230
+ data,
15231
+ parsedType: getParsedType(data)
15232
+ };
15233
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
15234
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
15235
+ return handleResult(ctx, result);
14949
15236
  }
14950
- util2.assertNever = assertNever;
14951
- util2.arrayToEnum = (items) => {
14952
- const obj = {};
14953
- for (const item of items) {
14954
- obj[item] = item;
14955
- }
14956
- return obj;
14957
- };
14958
- util2.getValidEnumValues = (obj) => {
14959
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
14960
- const filtered = {};
14961
- for (const k of validKeys) {
14962
- filtered[k] = obj[k];
14963
- }
14964
- return util2.objectValues(filtered);
14965
- };
14966
- util2.objectValues = (obj) => {
14967
- return util2.objectKeys(obj).map(function(e) {
14968
- return obj[e];
14969
- });
14970
- };
14971
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
14972
- const keys = [];
14973
- for (const key in object) {
14974
- if (Object.prototype.hasOwnProperty.call(object, key)) {
14975
- keys.push(key);
15237
+ refine(check, message) {
15238
+ const getIssueProperties = (val) => {
15239
+ if (typeof message === "string" || typeof message === "undefined") {
15240
+ return { message };
15241
+ } else if (typeof message === "function") {
15242
+ return message(val);
15243
+ } else {
15244
+ return message;
14976
15245
  }
14977
- }
14978
- return keys;
14979
- };
14980
- util2.find = (arr, checker) => {
14981
- for (const item of arr) {
14982
- if (checker(item))
14983
- return item;
14984
- }
14985
- return;
14986
- };
14987
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
14988
- function joinValues(array, separator = " | ") {
14989
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
14990
- }
14991
- util2.joinValues = joinValues;
14992
- util2.jsonStringifyReplacer = (_, value) => {
14993
- if (typeof value === "bigint") {
14994
- return value.toString();
14995
- }
14996
- return value;
14997
- };
14998
- })(util || (util = {}));
14999
- var objectUtil;
15000
- (function(objectUtil2) {
15001
- objectUtil2.mergeShapes = (first, second) => {
15002
- return {
15003
- ...first,
15004
- ...second
15005
15246
  };
15006
- };
15007
- })(objectUtil || (objectUtil = {}));
15008
- var ZodParsedType = util.arrayToEnum([
15009
- "string",
15010
- "nan",
15011
- "number",
15012
- "integer",
15013
- "float",
15014
- "boolean",
15015
- "date",
15016
- "bigint",
15017
- "symbol",
15018
- "function",
15019
- "undefined",
15020
- "null",
15021
- "array",
15022
- "object",
15023
- "unknown",
15024
- "promise",
15025
- "void",
15026
- "never",
15027
- "map",
15028
- "set"
15029
- ]);
15030
- var getParsedType = (data) => {
15031
- const t = typeof data;
15032
- switch (t) {
15033
- case "undefined":
15034
- return ZodParsedType.undefined;
15035
- case "string":
15036
- return ZodParsedType.string;
15037
- case "number":
15038
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
15039
- case "boolean":
15040
- return ZodParsedType.boolean;
15041
- case "function":
15042
- return ZodParsedType.function;
15043
- case "bigint":
15044
- return ZodParsedType.bigint;
15045
- case "symbol":
15046
- return ZodParsedType.symbol;
15047
- case "object":
15048
- if (Array.isArray(data)) {
15049
- return ZodParsedType.array;
15050
- }
15051
- if (data === null) {
15052
- return ZodParsedType.null;
15053
- }
15054
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
15055
- return ZodParsedType.promise;
15056
- }
15057
- if (typeof Map !== "undefined" && data instanceof Map) {
15058
- return ZodParsedType.map;
15247
+ return this._refinement((val, ctx) => {
15248
+ const result = check(val);
15249
+ const setError = () => ctx.addIssue({
15250
+ code: ZodIssueCode.custom,
15251
+ ...getIssueProperties(val)
15252
+ });
15253
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
15254
+ return result.then((data) => {
15255
+ if (!data) {
15256
+ setError();
15257
+ return false;
15258
+ } else {
15259
+ return true;
15260
+ }
15261
+ });
15059
15262
  }
15060
- if (typeof Set !== "undefined" && data instanceof Set) {
15061
- return ZodParsedType.set;
15263
+ if (!result) {
15264
+ setError();
15265
+ return false;
15266
+ } else {
15267
+ return true;
15062
15268
  }
15063
- if (typeof Date !== "undefined" && data instanceof Date) {
15064
- return ZodParsedType.date;
15269
+ });
15270
+ }
15271
+ refinement(check, refinementData) {
15272
+ return this._refinement((val, ctx) => {
15273
+ if (!check(val)) {
15274
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
15275
+ return false;
15276
+ } else {
15277
+ return true;
15065
15278
  }
15066
- return ZodParsedType.object;
15067
- default:
15068
- return ZodParsedType.unknown;
15279
+ });
15069
15280
  }
15070
- };
15071
- var ZodIssueCode = util.arrayToEnum([
15072
- "invalid_type",
15073
- "invalid_literal",
15074
- "custom",
15075
- "invalid_union",
15076
- "invalid_union_discriminator",
15077
- "invalid_enum_value",
15078
- "unrecognized_keys",
15079
- "invalid_arguments",
15080
- "invalid_return_type",
15081
- "invalid_date",
15082
- "invalid_string",
15083
- "too_small",
15084
- "too_big",
15085
- "invalid_intersection_types",
15086
- "not_multiple_of",
15087
- "not_finite"
15088
- ]);
15089
- var quotelessJson = (obj) => {
15090
- const json = JSON.stringify(obj, null, 2);
15091
- return json.replace(/"([^"]+)":/g, "$1:");
15092
- };
15093
-
15094
- class ZodError extends Error {
15095
- get errors() {
15096
- return this.issues;
15281
+ _refinement(refinement) {
15282
+ return new ZodEffects({
15283
+ schema: this,
15284
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
15285
+ effect: { type: "refinement", refinement }
15286
+ });
15097
15287
  }
15098
- constructor(issues) {
15099
- super();
15100
- this.issues = [];
15101
- this.addIssue = (sub) => {
15102
- this.issues = [...this.issues, sub];
15103
- };
15104
- this.addIssues = (subs = []) => {
15105
- this.issues = [...this.issues, ...subs];
15106
- };
15107
- const actualProto = new.target.prototype;
15108
- if (Object.setPrototypeOf) {
15109
- Object.setPrototypeOf(this, actualProto);
15110
- } else {
15111
- this.__proto__ = actualProto;
15112
- }
15113
- this.name = "ZodError";
15114
- this.issues = issues;
15288
+ superRefine(refinement) {
15289
+ return this._refinement(refinement);
15115
15290
  }
15116
- format(_mapper) {
15117
- const mapper = _mapper || function(issue) {
15118
- return issue.message;
15119
- };
15120
- const fieldErrors = { _errors: [] };
15121
- const processError = (error) => {
15122
- for (const issue of error.issues) {
15123
- if (issue.code === "invalid_union") {
15124
- issue.unionErrors.map(processError);
15125
- } else if (issue.code === "invalid_return_type") {
15126
- processError(issue.returnTypeError);
15127
- } else if (issue.code === "invalid_arguments") {
15128
- processError(issue.argumentsError);
15129
- } else if (issue.path.length === 0) {
15130
- fieldErrors._errors.push(mapper(issue));
15131
- } else {
15132
- let curr = fieldErrors;
15133
- let i = 0;
15134
- while (i < issue.path.length) {
15135
- const el = issue.path[i];
15136
- const terminal = i === issue.path.length - 1;
15137
- if (!terminal) {
15138
- curr[el] = curr[el] || { _errors: [] };
15139
- } else {
15140
- curr[el] = curr[el] || { _errors: [] };
15141
- curr[el]._errors.push(mapper(issue));
15142
- }
15143
- curr = curr[el];
15144
- i++;
15145
- }
15146
- }
15147
- }
15291
+ constructor(def) {
15292
+ this.spa = this.safeParseAsync;
15293
+ this._def = def;
15294
+ this.parse = this.parse.bind(this);
15295
+ this.safeParse = this.safeParse.bind(this);
15296
+ this.parseAsync = this.parseAsync.bind(this);
15297
+ this.safeParseAsync = this.safeParseAsync.bind(this);
15298
+ this.spa = this.spa.bind(this);
15299
+ this.refine = this.refine.bind(this);
15300
+ this.refinement = this.refinement.bind(this);
15301
+ this.superRefine = this.superRefine.bind(this);
15302
+ this.optional = this.optional.bind(this);
15303
+ this.nullable = this.nullable.bind(this);
15304
+ this.nullish = this.nullish.bind(this);
15305
+ this.array = this.array.bind(this);
15306
+ this.promise = this.promise.bind(this);
15307
+ this.or = this.or.bind(this);
15308
+ this.and = this.and.bind(this);
15309
+ this.transform = this.transform.bind(this);
15310
+ this.brand = this.brand.bind(this);
15311
+ this.default = this.default.bind(this);
15312
+ this.catch = this.catch.bind(this);
15313
+ this.describe = this.describe.bind(this);
15314
+ this.pipe = this.pipe.bind(this);
15315
+ this.readonly = this.readonly.bind(this);
15316
+ this.isNullable = this.isNullable.bind(this);
15317
+ this.isOptional = this.isOptional.bind(this);
15318
+ this["~standard"] = {
15319
+ version: 1,
15320
+ vendor: "zod",
15321
+ validate: (data) => this["~validate"](data)
15148
15322
  };
15149
- processError(this);
15150
- return fieldErrors;
15151
15323
  }
15152
- static assert(value) {
15153
- if (!(value instanceof ZodError)) {
15154
- throw new Error(`Not a ZodError: ${value}`);
15155
- }
15324
+ optional() {
15325
+ return ZodOptional.create(this, this._def);
15156
15326
  }
15157
- toString() {
15158
- return this.message;
15327
+ nullable() {
15328
+ return ZodNullable.create(this, this._def);
15159
15329
  }
15160
- get message() {
15161
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
15330
+ nullish() {
15331
+ return this.nullable().optional();
15162
15332
  }
15163
- get isEmpty() {
15164
- return this.issues.length === 0;
15333
+ array() {
15334
+ return ZodArray.create(this);
15165
15335
  }
15166
- flatten(mapper = (issue) => issue.message) {
15167
- const fieldErrors = {};
15168
- const formErrors = [];
15169
- for (const sub of this.issues) {
15170
- if (sub.path.length > 0) {
15171
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
15172
- fieldErrors[sub.path[0]].push(mapper(sub));
15173
- } else {
15174
- formErrors.push(mapper(sub));
15175
- }
15176
- }
15177
- return { formErrors, fieldErrors };
15336
+ promise() {
15337
+ return ZodPromise.create(this, this._def);
15178
15338
  }
15179
- get formErrors() {
15180
- return this.flatten();
15339
+ or(option) {
15340
+ return ZodUnion.create([this, option], this._def);
15181
15341
  }
15182
- }
15183
- ZodError.create = (issues) => {
15184
- const error = new ZodError(issues);
15185
- return error;
15186
- };
15187
- var errorMap = (issue, _ctx) => {
15188
- let message;
15189
- switch (issue.code) {
15190
- case ZodIssueCode.invalid_type:
15191
- if (issue.received === ZodParsedType.undefined) {
15192
- message = "Required";
15193
- } else {
15194
- message = `Expected ${issue.expected}, received ${issue.received}`;
15195
- }
15196
- break;
15197
- case ZodIssueCode.invalid_literal:
15198
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
15199
- break;
15200
- case ZodIssueCode.unrecognized_keys:
15201
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
15202
- break;
15203
- case ZodIssueCode.invalid_union:
15204
- message = `Invalid input`;
15205
- break;
15206
- case ZodIssueCode.invalid_union_discriminator:
15207
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
15208
- break;
15209
- case ZodIssueCode.invalid_enum_value:
15210
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
15211
- break;
15212
- case ZodIssueCode.invalid_arguments:
15213
- message = `Invalid function arguments`;
15214
- break;
15215
- case ZodIssueCode.invalid_return_type:
15216
- message = `Invalid function return type`;
15217
- break;
15218
- case ZodIssueCode.invalid_date:
15219
- message = `Invalid date`;
15220
- break;
15221
- case ZodIssueCode.invalid_string:
15222
- if (typeof issue.validation === "object") {
15223
- if ("includes" in issue.validation) {
15224
- message = `Invalid input: must include "${issue.validation.includes}"`;
15225
- if (typeof issue.validation.position === "number") {
15226
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
15227
- }
15228
- } else if ("startsWith" in issue.validation) {
15229
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
15230
- } else if ("endsWith" in issue.validation) {
15231
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
15232
- } else {
15233
- util.assertNever(issue.validation);
15234
- }
15235
- } else if (issue.validation !== "regex") {
15236
- message = `Invalid ${issue.validation}`;
15237
- } else {
15238
- message = "Invalid";
15239
- }
15240
- break;
15241
- case ZodIssueCode.too_small:
15242
- if (issue.type === "array")
15243
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
15244
- else if (issue.type === "string")
15245
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
15246
- else if (issue.type === "number")
15247
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
15248
- else if (issue.type === "date")
15249
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
15250
- else
15251
- message = "Invalid input";
15252
- break;
15253
- case ZodIssueCode.too_big:
15254
- if (issue.type === "array")
15255
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
15256
- else if (issue.type === "string")
15257
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
15258
- else if (issue.type === "number")
15259
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
15260
- else if (issue.type === "bigint")
15261
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
15262
- else if (issue.type === "date")
15263
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
15264
- else
15265
- message = "Invalid input";
15266
- break;
15267
- case ZodIssueCode.custom:
15268
- message = `Invalid input`;
15269
- break;
15270
- case ZodIssueCode.invalid_intersection_types:
15271
- message = `Intersection results could not be merged`;
15272
- break;
15273
- case ZodIssueCode.not_multiple_of:
15274
- message = `Number must be a multiple of ${issue.multipleOf}`;
15275
- break;
15276
- case ZodIssueCode.not_finite:
15277
- message = "Number must be finite";
15278
- break;
15279
- default:
15280
- message = _ctx.defaultError;
15281
- util.assertNever(issue);
15342
+ and(incoming) {
15343
+ return ZodIntersection.create(this, incoming, this._def);
15282
15344
  }
15283
- return { message };
15284
- };
15285
- var overrideErrorMap = errorMap;
15286
- function setErrorMap(map) {
15287
- overrideErrorMap = map;
15288
- }
15289
- function getErrorMap() {
15290
- return overrideErrorMap;
15291
- }
15292
- var makeIssue = (params) => {
15293
- const { data, path, errorMaps, issueData } = params;
15294
- const fullPath = [...path, ...issueData.path || []];
15295
- const fullIssue = {
15296
- ...issueData,
15297
- path: fullPath
15298
- };
15299
- if (issueData.message !== undefined) {
15300
- return {
15301
- ...issueData,
15302
- path: fullPath,
15303
- message: issueData.message
15304
- };
15345
+ transform(transform) {
15346
+ return new ZodEffects({
15347
+ ...processCreateParams(this._def),
15348
+ schema: this,
15349
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
15350
+ effect: { type: "transform", transform }
15351
+ });
15305
15352
  }
15306
- let errorMessage = "";
15307
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
15308
- for (const map of maps) {
15309
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
15353
+ default(def) {
15354
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
15355
+ return new ZodDefault({
15356
+ ...processCreateParams(this._def),
15357
+ innerType: this,
15358
+ defaultValue: defaultValueFunc,
15359
+ typeName: ZodFirstPartyTypeKind.ZodDefault
15360
+ });
15310
15361
  }
15311
- return {
15312
- ...issueData,
15313
- path: fullPath,
15314
- message: errorMessage
15315
- };
15316
- };
15317
- var EMPTY_PATH = [];
15318
- function addIssueToContext(ctx, issueData) {
15319
- const overrideMap = getErrorMap();
15320
- const issue = makeIssue({
15321
- issueData,
15322
- data: ctx.data,
15323
- path: ctx.path,
15324
- errorMaps: [
15325
- ctx.common.contextualErrorMap,
15326
- ctx.schemaErrorMap,
15327
- overrideMap,
15328
- overrideMap === errorMap ? undefined : errorMap
15329
- ].filter((x) => !!x)
15330
- });
15331
- ctx.common.issues.push(issue);
15332
- }
15333
-
15334
- class ParseStatus {
15335
- constructor() {
15336
- this.value = "valid";
15362
+ brand() {
15363
+ return new ZodBranded({
15364
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
15365
+ type: this,
15366
+ ...processCreateParams(this._def)
15367
+ });
15337
15368
  }
15338
- dirty() {
15339
- if (this.value === "valid")
15340
- this.value = "dirty";
15369
+ catch(def) {
15370
+ const catchValueFunc = typeof def === "function" ? def : () => def;
15371
+ return new ZodCatch({
15372
+ ...processCreateParams(this._def),
15373
+ innerType: this,
15374
+ catchValue: catchValueFunc,
15375
+ typeName: ZodFirstPartyTypeKind.ZodCatch
15376
+ });
15341
15377
  }
15342
- abort() {
15343
- if (this.value !== "aborted")
15344
- this.value = "aborted";
15378
+ describe(description) {
15379
+ const This = this.constructor;
15380
+ return new This({
15381
+ ...this._def,
15382
+ description
15383
+ });
15345
15384
  }
15346
- static mergeArray(status, results) {
15347
- const arrayValue = [];
15348
- for (const s of results) {
15349
- if (s.status === "aborted")
15350
- return INVALID;
15351
- if (s.status === "dirty")
15352
- status.dirty();
15353
- arrayValue.push(s.value);
15354
- }
15355
- return { status: status.value, value: arrayValue };
15385
+ pipe(target) {
15386
+ return ZodPipeline.create(this, target);
15356
15387
  }
15357
- static async mergeObjectAsync(status, pairs) {
15358
- const syncPairs = [];
15359
- for (const pair of pairs) {
15360
- const key = await pair.key;
15361
- const value = await pair.value;
15362
- syncPairs.push({
15363
- key,
15364
- value
15365
- });
15366
- }
15367
- return ParseStatus.mergeObjectSync(status, syncPairs);
15388
+ readonly() {
15389
+ return ZodReadonly.create(this);
15368
15390
  }
15369
- static mergeObjectSync(status, pairs) {
15370
- const finalObject = {};
15371
- for (const pair of pairs) {
15372
- const { key, value } = pair;
15373
- if (key.status === "aborted")
15374
- return INVALID;
15375
- if (value.status === "aborted")
15376
- return INVALID;
15377
- if (key.status === "dirty")
15378
- status.dirty();
15379
- if (value.status === "dirty")
15380
- status.dirty();
15381
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
15382
- finalObject[key.value] = value.value;
15383
- }
15384
- }
15385
- return { status: status.value, value: finalObject };
15391
+ isOptional() {
15392
+ return this.safeParse(undefined).success;
15393
+ }
15394
+ isNullable() {
15395
+ return this.safeParse(null).success;
15386
15396
  }
15387
15397
  }
15388
- var INVALID = Object.freeze({
15389
- status: "aborted"
15390
- });
15391
- var DIRTY = (value) => ({ status: "dirty", value });
15392
- var OK = (value) => ({ status: "valid", value });
15393
- var isAborted = (x) => x.status === "aborted";
15394
- var isDirty = (x) => x.status === "dirty";
15395
- var isValid = (x) => x.status === "valid";
15396
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
15397
- function __classPrivateFieldGet(receiver, state, kind, f) {
15398
- if (kind === "a" && !f)
15399
- throw new TypeError("Private accessor was defined without a getter");
15400
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
15401
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
15402
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15403
- }
15404
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
15405
- if (kind === "m")
15406
- throw new TypeError("Private method is not writable");
15407
- if (kind === "a" && !f)
15408
- throw new TypeError("Private accessor was defined without a setter");
15409
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
15410
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
15411
- return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
15412
- }
15413
- var errorUtil;
15414
- (function(errorUtil2) {
15415
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
15416
- errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === undefined ? undefined : message.message;
15417
- })(errorUtil || (errorUtil = {}));
15418
- var _ZodEnum_cache;
15419
- var _ZodNativeEnum_cache;
15420
-
15421
- class ParseInputLazyPath {
15422
- constructor(parent, value, path, key) {
15423
- this._cachedPath = [];
15424
- this.parent = parent;
15425
- this.data = value;
15426
- this._path = path;
15427
- this._key = key;
15428
- }
15429
- get path() {
15430
- if (!this._cachedPath.length) {
15431
- if (this._key instanceof Array) {
15432
- this._cachedPath.push(...this._path, ...this._key);
15433
- } else {
15434
- this._cachedPath.push(...this._path, this._key);
15435
- }
15436
- }
15437
- return this._cachedPath;
15398
+ var cuidRegex = /^c[^\s-]{8,}$/i;
15399
+ var cuid2Regex = /^[0-9a-z]+$/;
15400
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
15401
+ 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;
15402
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
15403
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
15404
+ 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)?)??$/;
15405
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
15406
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
15407
+ var emojiRegex;
15408
+ 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])$/;
15409
+ 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])$/;
15410
+ 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]))$/;
15411
+ 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])$/;
15412
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
15413
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
15414
+ 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])))`;
15415
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
15416
+ function timeRegexSource(args) {
15417
+ let secondsRegexSource = `[0-5]\\d`;
15418
+ if (args.precision) {
15419
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
15420
+ } else if (args.precision == null) {
15421
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
15438
15422
  }
15423
+ const secondsQuantifier = args.precision ? "+" : "?";
15424
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
15439
15425
  }
15440
- var handleResult = (ctx, result) => {
15441
- if (isValid(result)) {
15442
- return { success: true, data: result.value };
15443
- } else {
15444
- if (!ctx.common.issues.length) {
15445
- throw new Error("Validation failed but no issues detected.");
15446
- }
15447
- return {
15448
- success: false,
15449
- get error() {
15450
- if (this._error)
15451
- return this._error;
15452
- const error = new ZodError(ctx.common.issues);
15453
- this._error = error;
15454
- return this._error;
15455
- }
15456
- };
15426
+ function timeRegex(args) {
15427
+ return new RegExp(`^${timeRegexSource(args)}$`);
15428
+ }
15429
+ function datetimeRegex(args) {
15430
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
15431
+ const opts = [];
15432
+ opts.push(args.local ? `Z?` : `Z`);
15433
+ if (args.offset)
15434
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
15435
+ regex = `${regex}(${opts.join("|")})`;
15436
+ return new RegExp(`^${regex}$`);
15437
+ }
15438
+ function isValidIP(ip, version) {
15439
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
15440
+ return true;
15457
15441
  }
15458
- };
15459
- function processCreateParams(params) {
15460
- if (!params)
15461
- return {};
15462
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
15463
- if (errorMap2 && (invalid_type_error || required_error)) {
15464
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
15442
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
15443
+ return true;
15465
15444
  }
15466
- if (errorMap2)
15467
- return { errorMap: errorMap2, description };
15468
- const customMap = (iss, ctx) => {
15469
- var _a, _b;
15470
- const { message } = params;
15471
- if (iss.code === "invalid_enum_value") {
15472
- return { message: message !== null && message !== undefined ? message : ctx.defaultError };
15473
- }
15474
- if (typeof ctx.data === "undefined") {
15475
- return { message: (_a = message !== null && message !== undefined ? message : required_error) !== null && _a !== undefined ? _a : ctx.defaultError };
15476
- }
15477
- if (iss.code !== "invalid_type")
15478
- return { message: ctx.defaultError };
15479
- return { message: (_b = message !== null && message !== undefined ? message : invalid_type_error) !== null && _b !== undefined ? _b : ctx.defaultError };
15480
- };
15481
- return { errorMap: customMap, description };
15445
+ return false;
15482
15446
  }
15483
-
15484
- class ZodType {
15485
- get description() {
15486
- return this._def.description;
15487
- }
15488
- _getType(input) {
15489
- return getParsedType(input.data);
15447
+ function isValidJWT(jwt, alg) {
15448
+ if (!jwtRegex.test(jwt))
15449
+ return false;
15450
+ try {
15451
+ const [header] = jwt.split(".");
15452
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
15453
+ const decoded = JSON.parse(atob(base64));
15454
+ if (typeof decoded !== "object" || decoded === null)
15455
+ return false;
15456
+ if (!decoded.typ || !decoded.alg)
15457
+ return false;
15458
+ if (alg && decoded.alg !== alg)
15459
+ return false;
15460
+ return true;
15461
+ } catch (_a) {
15462
+ return false;
15490
15463
  }
15491
- _getOrReturnCtx(input, ctx) {
15492
- return ctx || {
15493
- common: input.parent.common,
15494
- data: input.data,
15495
- parsedType: getParsedType(input.data),
15496
- schemaErrorMap: this._def.errorMap,
15497
- path: input.path,
15498
- parent: input.parent
15499
- };
15464
+ }
15465
+ function isValidCidr(ip, version) {
15466
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
15467
+ return true;
15500
15468
  }
15501
- _processInputParams(input) {
15502
- return {
15503
- status: new ParseStatus,
15504
- ctx: {
15505
- common: input.parent.common,
15506
- data: input.data,
15507
- parsedType: getParsedType(input.data),
15508
- schemaErrorMap: this._def.errorMap,
15509
- path: input.path,
15510
- parent: input.parent
15511
- }
15512
- };
15469
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
15470
+ return true;
15513
15471
  }
15514
- _parseSync(input) {
15515
- const result = this._parse(input);
15516
- if (isAsync(result)) {
15517
- throw new Error("Synchronous parse encountered promise.");
15472
+ return false;
15473
+ }
15474
+
15475
+ class ZodString extends ZodType {
15476
+ _parse(input) {
15477
+ if (this._def.coerce) {
15478
+ input.data = String(input.data);
15518
15479
  }
15519
- return result;
15520
- }
15521
- _parseAsync(input) {
15522
- const result = this._parse(input);
15523
- return Promise.resolve(result);
15524
- }
15525
- parse(data, params) {
15526
- const result = this.safeParse(data, params);
15527
- if (result.success)
15528
- return result.data;
15529
- throw result.error;
15530
- }
15531
- safeParse(data, params) {
15532
- var _a;
15533
- const ctx = {
15534
- common: {
15535
- issues: [],
15536
- async: (_a = params === null || params === undefined ? undefined : params.async) !== null && _a !== undefined ? _a : false,
15537
- contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap
15538
- },
15539
- path: (params === null || params === undefined ? undefined : params.path) || [],
15540
- schemaErrorMap: this._def.errorMap,
15541
- parent: null,
15542
- data,
15543
- parsedType: getParsedType(data)
15544
- };
15545
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
15546
- return handleResult(ctx, result);
15547
- }
15548
- "~validate"(data) {
15549
- var _a, _b;
15550
- const ctx = {
15551
- common: {
15552
- issues: [],
15553
- async: !!this["~standard"].async
15554
- },
15555
- path: [],
15556
- schemaErrorMap: this._def.errorMap,
15557
- parent: null,
15558
- data,
15559
- parsedType: getParsedType(data)
15560
- };
15561
- if (!this["~standard"].async) {
15562
- try {
15563
- const result = this._parseSync({ data, path: [], parent: ctx });
15564
- return isValid(result) ? {
15565
- value: result.value
15566
- } : {
15567
- issues: ctx.common.issues
15568
- };
15569
- } catch (err) {
15570
- if ((_b = (_a = err === null || err === undefined ? undefined : err.message) === null || _a === undefined ? undefined : _a.toLowerCase()) === null || _b === undefined ? undefined : _b.includes("encountered")) {
15571
- this["~standard"].async = true;
15572
- }
15573
- ctx.common = {
15574
- issues: [],
15575
- async: true
15576
- };
15577
- }
15578
- }
15579
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
15580
- value: result.value
15581
- } : {
15582
- issues: ctx.common.issues
15583
- });
15584
- }
15585
- async parseAsync(data, params) {
15586
- const result = await this.safeParseAsync(data, params);
15587
- if (result.success)
15588
- return result.data;
15589
- throw result.error;
15590
- }
15591
- async safeParseAsync(data, params) {
15592
- const ctx = {
15593
- common: {
15594
- issues: [],
15595
- contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap,
15596
- async: true
15597
- },
15598
- path: (params === null || params === undefined ? undefined : params.path) || [],
15599
- schemaErrorMap: this._def.errorMap,
15600
- parent: null,
15601
- data,
15602
- parsedType: getParsedType(data)
15603
- };
15604
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
15605
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
15606
- return handleResult(ctx, result);
15607
- }
15608
- refine(check, message) {
15609
- const getIssueProperties = (val) => {
15610
- if (typeof message === "string" || typeof message === "undefined") {
15611
- return { message };
15612
- } else if (typeof message === "function") {
15613
- return message(val);
15614
- } else {
15615
- return message;
15616
- }
15617
- };
15618
- return this._refinement((val, ctx) => {
15619
- const result = check(val);
15620
- const setError = () => ctx.addIssue({
15621
- code: ZodIssueCode.custom,
15622
- ...getIssueProperties(val)
15623
- });
15624
- if (typeof Promise !== "undefined" && result instanceof Promise) {
15625
- return result.then((data) => {
15626
- if (!data) {
15627
- setError();
15628
- return false;
15629
- } else {
15630
- return true;
15631
- }
15632
- });
15633
- }
15634
- if (!result) {
15635
- setError();
15636
- return false;
15637
- } else {
15638
- return true;
15639
- }
15640
- });
15641
- }
15642
- refinement(check, refinementData) {
15643
- return this._refinement((val, ctx) => {
15644
- if (!check(val)) {
15645
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
15646
- return false;
15647
- } else {
15648
- return true;
15649
- }
15650
- });
15651
- }
15652
- _refinement(refinement) {
15653
- return new ZodEffects({
15654
- schema: this,
15655
- typeName: ZodFirstPartyTypeKind.ZodEffects,
15656
- effect: { type: "refinement", refinement }
15657
- });
15658
- }
15659
- superRefine(refinement) {
15660
- return this._refinement(refinement);
15661
- }
15662
- constructor(def) {
15663
- this.spa = this.safeParseAsync;
15664
- this._def = def;
15665
- this.parse = this.parse.bind(this);
15666
- this.safeParse = this.safeParse.bind(this);
15667
- this.parseAsync = this.parseAsync.bind(this);
15668
- this.safeParseAsync = this.safeParseAsync.bind(this);
15669
- this.spa = this.spa.bind(this);
15670
- this.refine = this.refine.bind(this);
15671
- this.refinement = this.refinement.bind(this);
15672
- this.superRefine = this.superRefine.bind(this);
15673
- this.optional = this.optional.bind(this);
15674
- this.nullable = this.nullable.bind(this);
15675
- this.nullish = this.nullish.bind(this);
15676
- this.array = this.array.bind(this);
15677
- this.promise = this.promise.bind(this);
15678
- this.or = this.or.bind(this);
15679
- this.and = this.and.bind(this);
15680
- this.transform = this.transform.bind(this);
15681
- this.brand = this.brand.bind(this);
15682
- this.default = this.default.bind(this);
15683
- this.catch = this.catch.bind(this);
15684
- this.describe = this.describe.bind(this);
15685
- this.pipe = this.pipe.bind(this);
15686
- this.readonly = this.readonly.bind(this);
15687
- this.isNullable = this.isNullable.bind(this);
15688
- this.isOptional = this.isOptional.bind(this);
15689
- this["~standard"] = {
15690
- version: 1,
15691
- vendor: "zod",
15692
- validate: (data) => this["~validate"](data)
15693
- };
15694
- }
15695
- optional() {
15696
- return ZodOptional.create(this, this._def);
15697
- }
15698
- nullable() {
15699
- return ZodNullable.create(this, this._def);
15700
- }
15701
- nullish() {
15702
- return this.nullable().optional();
15703
- }
15704
- array() {
15705
- return ZodArray.create(this);
15706
- }
15707
- promise() {
15708
- return ZodPromise.create(this, this._def);
15709
- }
15710
- or(option) {
15711
- return ZodUnion.create([this, option], this._def);
15712
- }
15713
- and(incoming) {
15714
- return ZodIntersection.create(this, incoming, this._def);
15715
- }
15716
- transform(transform) {
15717
- return new ZodEffects({
15718
- ...processCreateParams(this._def),
15719
- schema: this,
15720
- typeName: ZodFirstPartyTypeKind.ZodEffects,
15721
- effect: { type: "transform", transform }
15722
- });
15723
- }
15724
- default(def) {
15725
- const defaultValueFunc = typeof def === "function" ? def : () => def;
15726
- return new ZodDefault({
15727
- ...processCreateParams(this._def),
15728
- innerType: this,
15729
- defaultValue: defaultValueFunc,
15730
- typeName: ZodFirstPartyTypeKind.ZodDefault
15731
- });
15732
- }
15733
- brand() {
15734
- return new ZodBranded({
15735
- typeName: ZodFirstPartyTypeKind.ZodBranded,
15736
- type: this,
15737
- ...processCreateParams(this._def)
15738
- });
15739
- }
15740
- catch(def) {
15741
- const catchValueFunc = typeof def === "function" ? def : () => def;
15742
- return new ZodCatch({
15743
- ...processCreateParams(this._def),
15744
- innerType: this,
15745
- catchValue: catchValueFunc,
15746
- typeName: ZodFirstPartyTypeKind.ZodCatch
15747
- });
15748
- }
15749
- describe(description) {
15750
- const This = this.constructor;
15751
- return new This({
15752
- ...this._def,
15753
- description
15754
- });
15755
- }
15756
- pipe(target) {
15757
- return ZodPipeline.create(this, target);
15758
- }
15759
- readonly() {
15760
- return ZodReadonly.create(this);
15761
- }
15762
- isOptional() {
15763
- return this.safeParse(undefined).success;
15764
- }
15765
- isNullable() {
15766
- return this.safeParse(null).success;
15767
- }
15768
- }
15769
- var cuidRegex = /^c[^\s-]{8,}$/i;
15770
- var cuid2Regex = /^[0-9a-z]+$/;
15771
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
15772
- 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;
15773
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
15774
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
15775
- 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)?)??$/;
15776
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
15777
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
15778
- var emojiRegex;
15779
- 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])$/;
15780
- 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])$/;
15781
- 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]))$/;
15782
- 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])$/;
15783
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
15784
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
15785
- 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])))`;
15786
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
15787
- function timeRegexSource(args) {
15788
- let secondsRegexSource = `[0-5]\\d`;
15789
- if (args.precision) {
15790
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
15791
- } else if (args.precision == null) {
15792
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
15793
- }
15794
- const secondsQuantifier = args.precision ? "+" : "?";
15795
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
15796
- }
15797
- function timeRegex(args) {
15798
- return new RegExp(`^${timeRegexSource(args)}$`);
15799
- }
15800
- function datetimeRegex(args) {
15801
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
15802
- const opts = [];
15803
- opts.push(args.local ? `Z?` : `Z`);
15804
- if (args.offset)
15805
- opts.push(`([+-]\\d{2}:?\\d{2})`);
15806
- regex = `${regex}(${opts.join("|")})`;
15807
- return new RegExp(`^${regex}$`);
15808
- }
15809
- function isValidIP(ip, version) {
15810
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
15811
- return true;
15812
- }
15813
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
15814
- return true;
15815
- }
15816
- return false;
15817
- }
15818
- function isValidJWT(jwt, alg) {
15819
- if (!jwtRegex.test(jwt))
15820
- return false;
15821
- try {
15822
- const [header] = jwt.split(".");
15823
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
15824
- const decoded = JSON.parse(atob(base64));
15825
- if (typeof decoded !== "object" || decoded === null)
15826
- return false;
15827
- if (!decoded.typ || !decoded.alg)
15828
- return false;
15829
- if (alg && decoded.alg !== alg)
15830
- return false;
15831
- return true;
15832
- } catch (_a) {
15833
- return false;
15834
- }
15835
- }
15836
- function isValidCidr(ip, version) {
15837
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
15838
- return true;
15839
- }
15840
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
15841
- return true;
15842
- }
15843
- return false;
15844
- }
15845
-
15846
- class ZodString extends ZodType {
15847
- _parse(input) {
15848
- if (this._def.coerce) {
15849
- input.data = String(input.data);
15850
- }
15851
- const parsedType = this._getType(input);
15852
- if (parsedType !== ZodParsedType.string) {
15853
- const ctx2 = this._getOrReturnCtx(input);
15854
- addIssueToContext(ctx2, {
15855
- code: ZodIssueCode.invalid_type,
15856
- expected: ZodParsedType.string,
15857
- received: ctx2.parsedType
15858
- });
15859
- return INVALID;
15480
+ const parsedType = this._getType(input);
15481
+ if (parsedType !== ZodParsedType.string) {
15482
+ const ctx2 = this._getOrReturnCtx(input);
15483
+ addIssueToContext(ctx2, {
15484
+ code: ZodIssueCode.invalid_type,
15485
+ expected: ZodParsedType.string,
15486
+ received: ctx2.parsedType
15487
+ });
15488
+ return INVALID;
15860
15489
  }
15861
15490
  const status = new ParseStatus;
15862
15491
  let ctx = undefined;
@@ -21184,492 +20813,863 @@ class McpServer {
21184
20813
  isError: true
21185
20814
  };
21186
20815
  }
21187
- }
21188
- });
21189
- this._toolHandlersInitialized = true;
20816
+ }
20817
+ });
20818
+ this._toolHandlersInitialized = true;
20819
+ }
20820
+ setCompletionRequestHandler() {
20821
+ if (this._completionHandlerInitialized) {
20822
+ return;
20823
+ }
20824
+ this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value);
20825
+ this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
20826
+ switch (request.params.ref.type) {
20827
+ case "ref/prompt":
20828
+ return this.handlePromptCompletion(request, request.params.ref);
20829
+ case "ref/resource":
20830
+ return this.handleResourceCompletion(request, request.params.ref);
20831
+ default:
20832
+ throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
20833
+ }
20834
+ });
20835
+ this._completionHandlerInitialized = true;
20836
+ }
20837
+ async handlePromptCompletion(request, ref) {
20838
+ const prompt = this._registeredPrompts[ref.name];
20839
+ if (!prompt) {
20840
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
20841
+ }
20842
+ if (!prompt.enabled) {
20843
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
20844
+ }
20845
+ if (!prompt.argsSchema) {
20846
+ return EMPTY_COMPLETION_RESULT;
20847
+ }
20848
+ const field = prompt.argsSchema.shape[request.params.argument.name];
20849
+ if (!(field instanceof Completable)) {
20850
+ return EMPTY_COMPLETION_RESULT;
20851
+ }
20852
+ const def = field._def;
20853
+ const suggestions = await def.complete(request.params.argument.value);
20854
+ return createCompletionResult(suggestions);
20855
+ }
20856
+ async handleResourceCompletion(request, ref) {
20857
+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
20858
+ if (!template) {
20859
+ if (this._registeredResources[ref.uri]) {
20860
+ return EMPTY_COMPLETION_RESULT;
20861
+ }
20862
+ throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
20863
+ }
20864
+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
20865
+ if (!completer) {
20866
+ return EMPTY_COMPLETION_RESULT;
20867
+ }
20868
+ const suggestions = await completer(request.params.argument.value);
20869
+ return createCompletionResult(suggestions);
20870
+ }
20871
+ setResourceRequestHandlers() {
20872
+ if (this._resourceHandlersInitialized) {
20873
+ return;
20874
+ }
20875
+ this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value);
20876
+ this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value);
20877
+ this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value);
20878
+ this.server.registerCapabilities({
20879
+ resources: {
20880
+ listChanged: true
20881
+ }
20882
+ });
20883
+ this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
20884
+ const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
20885
+ uri,
20886
+ name: resource.name,
20887
+ ...resource.metadata
20888
+ }));
20889
+ const templateResources = [];
20890
+ for (const template of Object.values(this._registeredResourceTemplates)) {
20891
+ if (!template.resourceTemplate.listCallback) {
20892
+ continue;
20893
+ }
20894
+ const result = await template.resourceTemplate.listCallback(extra);
20895
+ for (const resource of result.resources) {
20896
+ templateResources.push({
20897
+ ...resource,
20898
+ ...template.metadata
20899
+ });
20900
+ }
20901
+ }
20902
+ return { resources: [...resources, ...templateResources] };
20903
+ });
20904
+ this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
20905
+ const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
20906
+ name,
20907
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
20908
+ ...template.metadata
20909
+ }));
20910
+ return { resourceTemplates };
20911
+ });
20912
+ this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
20913
+ const uri = new URL(request.params.uri);
20914
+ const resource = this._registeredResources[uri.toString()];
20915
+ if (resource) {
20916
+ if (!resource.enabled) {
20917
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
20918
+ }
20919
+ return resource.readCallback(uri, extra);
20920
+ }
20921
+ for (const template of Object.values(this._registeredResourceTemplates)) {
20922
+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
20923
+ if (variables) {
20924
+ return template.readCallback(uri, variables, extra);
20925
+ }
20926
+ }
20927
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
20928
+ });
20929
+ this.setCompletionRequestHandler();
20930
+ this._resourceHandlersInitialized = true;
20931
+ }
20932
+ setPromptRequestHandlers() {
20933
+ if (this._promptHandlersInitialized) {
20934
+ return;
20935
+ }
20936
+ this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value);
20937
+ this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value);
20938
+ this.server.registerCapabilities({
20939
+ prompts: {
20940
+ listChanged: true
20941
+ }
20942
+ });
20943
+ this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
20944
+ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
20945
+ return {
20946
+ name,
20947
+ description: prompt.description,
20948
+ arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
20949
+ };
20950
+ })
20951
+ }));
20952
+ this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
20953
+ const prompt = this._registeredPrompts[request.params.name];
20954
+ if (!prompt) {
20955
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
20956
+ }
20957
+ if (!prompt.enabled) {
20958
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
20959
+ }
20960
+ if (prompt.argsSchema) {
20961
+ const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments);
20962
+ if (!parseResult.success) {
20963
+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`);
20964
+ }
20965
+ const args = parseResult.data;
20966
+ const cb = prompt.callback;
20967
+ return await Promise.resolve(cb(args, extra));
20968
+ } else {
20969
+ const cb = prompt.callback;
20970
+ return await Promise.resolve(cb(extra));
20971
+ }
20972
+ });
20973
+ this.setCompletionRequestHandler();
20974
+ this._promptHandlersInitialized = true;
20975
+ }
20976
+ resource(name, uriOrTemplate, ...rest) {
20977
+ let metadata;
20978
+ if (typeof rest[0] === "object") {
20979
+ metadata = rest.shift();
20980
+ }
20981
+ const readCallback = rest[0];
20982
+ if (typeof uriOrTemplate === "string") {
20983
+ if (this._registeredResources[uriOrTemplate]) {
20984
+ throw new Error(`Resource ${uriOrTemplate} is already registered`);
20985
+ }
20986
+ const registeredResource = {
20987
+ name,
20988
+ metadata,
20989
+ readCallback,
20990
+ enabled: true,
20991
+ disable: () => registeredResource.update({ enabled: false }),
20992
+ enable: () => registeredResource.update({ enabled: true }),
20993
+ remove: () => registeredResource.update({ uri: null }),
20994
+ update: (updates) => {
20995
+ if (typeof updates.uri !== "undefined" && updates.uri !== uriOrTemplate) {
20996
+ delete this._registeredResources[uriOrTemplate];
20997
+ if (updates.uri)
20998
+ this._registeredResources[updates.uri] = registeredResource;
20999
+ }
21000
+ if (typeof updates.name !== "undefined")
21001
+ registeredResource.name = updates.name;
21002
+ if (typeof updates.metadata !== "undefined")
21003
+ registeredResource.metadata = updates.metadata;
21004
+ if (typeof updates.callback !== "undefined")
21005
+ registeredResource.readCallback = updates.callback;
21006
+ if (typeof updates.enabled !== "undefined")
21007
+ registeredResource.enabled = updates.enabled;
21008
+ this.sendResourceListChanged();
21009
+ }
21010
+ };
21011
+ this._registeredResources[uriOrTemplate] = registeredResource;
21012
+ this.setResourceRequestHandlers();
21013
+ this.sendResourceListChanged();
21014
+ return registeredResource;
21015
+ } else {
21016
+ if (this._registeredResourceTemplates[name]) {
21017
+ throw new Error(`Resource template ${name} is already registered`);
21018
+ }
21019
+ const registeredResourceTemplate = {
21020
+ resourceTemplate: uriOrTemplate,
21021
+ metadata,
21022
+ readCallback,
21023
+ enabled: true,
21024
+ disable: () => registeredResourceTemplate.update({ enabled: false }),
21025
+ enable: () => registeredResourceTemplate.update({ enabled: true }),
21026
+ remove: () => registeredResourceTemplate.update({ name: null }),
21027
+ update: (updates) => {
21028
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
21029
+ delete this._registeredResourceTemplates[name];
21030
+ if (updates.name)
21031
+ this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
21032
+ }
21033
+ if (typeof updates.template !== "undefined")
21034
+ registeredResourceTemplate.resourceTemplate = updates.template;
21035
+ if (typeof updates.metadata !== "undefined")
21036
+ registeredResourceTemplate.metadata = updates.metadata;
21037
+ if (typeof updates.callback !== "undefined")
21038
+ registeredResourceTemplate.readCallback = updates.callback;
21039
+ if (typeof updates.enabled !== "undefined")
21040
+ registeredResourceTemplate.enabled = updates.enabled;
21041
+ this.sendResourceListChanged();
21042
+ }
21043
+ };
21044
+ this._registeredResourceTemplates[name] = registeredResourceTemplate;
21045
+ this.setResourceRequestHandlers();
21046
+ this.sendResourceListChanged();
21047
+ return registeredResourceTemplate;
21048
+ }
21190
21049
  }
21191
- setCompletionRequestHandler() {
21192
- if (this._completionHandlerInitialized) {
21193
- return;
21050
+ tool(name, ...rest) {
21051
+ if (this._registeredTools[name]) {
21052
+ throw new Error(`Tool ${name} is already registered`);
21194
21053
  }
21195
- this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value);
21196
- this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
21197
- switch (request.params.ref.type) {
21198
- case "ref/prompt":
21199
- return this.handlePromptCompletion(request, request.params.ref);
21200
- case "ref/resource":
21201
- return this.handleResourceCompletion(request, request.params.ref);
21202
- default:
21203
- throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
21054
+ let description;
21055
+ if (typeof rest[0] === "string") {
21056
+ description = rest.shift();
21057
+ }
21058
+ let paramsSchema;
21059
+ let annotations;
21060
+ if (rest.length > 1) {
21061
+ const firstArg = rest[0];
21062
+ if (isZodRawShape(firstArg)) {
21063
+ paramsSchema = rest.shift();
21064
+ if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShape(rest[0])) {
21065
+ annotations = rest.shift();
21066
+ }
21067
+ } else if (typeof firstArg === "object" && firstArg !== null) {
21068
+ annotations = rest.shift();
21204
21069
  }
21205
- });
21206
- this._completionHandlerInitialized = true;
21070
+ }
21071
+ const cb = rest[0];
21072
+ const registeredTool = {
21073
+ description,
21074
+ inputSchema: paramsSchema === undefined ? undefined : z.object(paramsSchema),
21075
+ annotations,
21076
+ callback: cb,
21077
+ enabled: true,
21078
+ disable: () => registeredTool.update({ enabled: false }),
21079
+ enable: () => registeredTool.update({ enabled: true }),
21080
+ remove: () => registeredTool.update({ name: null }),
21081
+ update: (updates) => {
21082
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
21083
+ delete this._registeredTools[name];
21084
+ if (updates.name)
21085
+ this._registeredTools[updates.name] = registeredTool;
21086
+ }
21087
+ if (typeof updates.description !== "undefined")
21088
+ registeredTool.description = updates.description;
21089
+ if (typeof updates.paramsSchema !== "undefined")
21090
+ registeredTool.inputSchema = z.object(updates.paramsSchema);
21091
+ if (typeof updates.callback !== "undefined")
21092
+ registeredTool.callback = updates.callback;
21093
+ if (typeof updates.annotations !== "undefined")
21094
+ registeredTool.annotations = updates.annotations;
21095
+ if (typeof updates.enabled !== "undefined")
21096
+ registeredTool.enabled = updates.enabled;
21097
+ this.sendToolListChanged();
21098
+ }
21099
+ };
21100
+ this._registeredTools[name] = registeredTool;
21101
+ this.setToolRequestHandlers();
21102
+ this.sendToolListChanged();
21103
+ return registeredTool;
21207
21104
  }
21208
- async handlePromptCompletion(request, ref) {
21209
- const prompt = this._registeredPrompts[ref.name];
21210
- if (!prompt) {
21211
- throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
21105
+ prompt(name, ...rest) {
21106
+ if (this._registeredPrompts[name]) {
21107
+ throw new Error(`Prompt ${name} is already registered`);
21212
21108
  }
21213
- if (!prompt.enabled) {
21214
- throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
21109
+ let description;
21110
+ if (typeof rest[0] === "string") {
21111
+ description = rest.shift();
21215
21112
  }
21216
- if (!prompt.argsSchema) {
21217
- return EMPTY_COMPLETION_RESULT;
21113
+ let argsSchema;
21114
+ if (rest.length > 1) {
21115
+ argsSchema = rest.shift();
21218
21116
  }
21219
- const field = prompt.argsSchema.shape[request.params.argument.name];
21220
- if (!(field instanceof Completable)) {
21221
- return EMPTY_COMPLETION_RESULT;
21117
+ const cb = rest[0];
21118
+ const registeredPrompt = {
21119
+ description,
21120
+ argsSchema: argsSchema === undefined ? undefined : z.object(argsSchema),
21121
+ callback: cb,
21122
+ enabled: true,
21123
+ disable: () => registeredPrompt.update({ enabled: false }),
21124
+ enable: () => registeredPrompt.update({ enabled: true }),
21125
+ remove: () => registeredPrompt.update({ name: null }),
21126
+ update: (updates) => {
21127
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
21128
+ delete this._registeredPrompts[name];
21129
+ if (updates.name)
21130
+ this._registeredPrompts[updates.name] = registeredPrompt;
21131
+ }
21132
+ if (typeof updates.description !== "undefined")
21133
+ registeredPrompt.description = updates.description;
21134
+ if (typeof updates.argsSchema !== "undefined")
21135
+ registeredPrompt.argsSchema = z.object(updates.argsSchema);
21136
+ if (typeof updates.callback !== "undefined")
21137
+ registeredPrompt.callback = updates.callback;
21138
+ if (typeof updates.enabled !== "undefined")
21139
+ registeredPrompt.enabled = updates.enabled;
21140
+ this.sendPromptListChanged();
21141
+ }
21142
+ };
21143
+ this._registeredPrompts[name] = registeredPrompt;
21144
+ this.setPromptRequestHandlers();
21145
+ this.sendPromptListChanged();
21146
+ return registeredPrompt;
21147
+ }
21148
+ isConnected() {
21149
+ return this.server.transport !== undefined;
21150
+ }
21151
+ sendResourceListChanged() {
21152
+ if (this.isConnected()) {
21153
+ this.server.sendResourceListChanged();
21222
21154
  }
21223
- const def = field._def;
21224
- const suggestions = await def.complete(request.params.argument.value);
21225
- return createCompletionResult(suggestions);
21226
21155
  }
21227
- async handleResourceCompletion(request, ref) {
21228
- const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
21229
- if (!template) {
21230
- if (this._registeredResources[ref.uri]) {
21231
- return EMPTY_COMPLETION_RESULT;
21232
- }
21233
- throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
21156
+ sendToolListChanged() {
21157
+ if (this.isConnected()) {
21158
+ this.server.sendToolListChanged();
21234
21159
  }
21235
- const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
21236
- if (!completer) {
21237
- return EMPTY_COMPLETION_RESULT;
21160
+ }
21161
+ sendPromptListChanged() {
21162
+ if (this.isConnected()) {
21163
+ this.server.sendPromptListChanged();
21238
21164
  }
21239
- const suggestions = await completer(request.params.argument.value);
21240
- return createCompletionResult(suggestions);
21241
21165
  }
21242
- setResourceRequestHandlers() {
21243
- if (this._resourceHandlersInitialized) {
21244
- return;
21166
+ }
21167
+ var EMPTY_OBJECT_JSON_SCHEMA = {
21168
+ type: "object"
21169
+ };
21170
+ function isZodRawShape(obj) {
21171
+ if (typeof obj !== "object" || obj === null)
21172
+ return false;
21173
+ const isEmptyObject = Object.keys(obj).length === 0;
21174
+ return isEmptyObject || Object.values(obj).some(isZodTypeLike);
21175
+ }
21176
+ function isZodTypeLike(value) {
21177
+ return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
21178
+ }
21179
+ function promptArgumentsFromSchema(schema) {
21180
+ return Object.entries(schema.shape).map(([name, field]) => ({
21181
+ name,
21182
+ description: field.description,
21183
+ required: !field.isOptional()
21184
+ }));
21185
+ }
21186
+ function createCompletionResult(suggestions) {
21187
+ return {
21188
+ completion: {
21189
+ values: suggestions.slice(0, 100),
21190
+ total: suggestions.length,
21191
+ hasMore: suggestions.length > 100
21245
21192
  }
21246
- this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value);
21247
- this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value);
21248
- this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value);
21249
- this.server.registerCapabilities({
21250
- resources: {
21251
- listChanged: true
21252
- }
21253
- });
21254
- this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
21255
- const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
21256
- uri,
21257
- name: resource.name,
21258
- ...resource.metadata
21259
- }));
21260
- const templateResources = [];
21261
- for (const template of Object.values(this._registeredResourceTemplates)) {
21262
- if (!template.resourceTemplate.listCallback) {
21263
- continue;
21264
- }
21265
- const result = await template.resourceTemplate.listCallback(extra);
21266
- for (const resource of result.resources) {
21267
- templateResources.push({
21268
- ...resource,
21269
- ...template.metadata
21270
- });
21271
- }
21272
- }
21273
- return { resources: [...resources, ...templateResources] };
21274
- });
21275
- this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
21276
- const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
21277
- name,
21278
- uriTemplate: template.resourceTemplate.uriTemplate.toString(),
21279
- ...template.metadata
21280
- }));
21281
- return { resourceTemplates };
21282
- });
21283
- this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
21284
- const uri = new URL(request.params.uri);
21285
- const resource = this._registeredResources[uri.toString()];
21286
- if (resource) {
21287
- if (!resource.enabled) {
21288
- throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
21289
- }
21290
- return resource.readCallback(uri, extra);
21291
- }
21292
- for (const template of Object.values(this._registeredResourceTemplates)) {
21293
- const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
21294
- if (variables) {
21295
- return template.readCallback(uri, variables, extra);
21296
- }
21297
- }
21298
- throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
21299
- });
21300
- this.setCompletionRequestHandler();
21301
- this._resourceHandlersInitialized = true;
21193
+ };
21194
+ }
21195
+ var EMPTY_COMPLETION_RESULT = {
21196
+ completion: {
21197
+ values: [],
21198
+ hasMore: false
21199
+ }
21200
+ };
21201
+
21202
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
21203
+ import process2 from "node:process";
21204
+
21205
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
21206
+ class ReadBuffer {
21207
+ append(chunk) {
21208
+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
21302
21209
  }
21303
- setPromptRequestHandlers() {
21304
- if (this._promptHandlersInitialized) {
21305
- return;
21210
+ readMessage() {
21211
+ if (!this._buffer) {
21212
+ return null;
21306
21213
  }
21307
- this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value);
21308
- this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value);
21309
- this.server.registerCapabilities({
21310
- prompts: {
21311
- listChanged: true
21312
- }
21313
- });
21314
- this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
21315
- prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
21316
- return {
21317
- name,
21318
- description: prompt.description,
21319
- arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
21320
- };
21321
- })
21322
- }));
21323
- this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
21324
- const prompt = this._registeredPrompts[request.params.name];
21325
- if (!prompt) {
21326
- throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
21327
- }
21328
- if (!prompt.enabled) {
21329
- throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
21330
- }
21331
- if (prompt.argsSchema) {
21332
- const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments);
21333
- if (!parseResult.success) {
21334
- throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`);
21335
- }
21336
- const args = parseResult.data;
21337
- const cb = prompt.callback;
21338
- return await Promise.resolve(cb(args, extra));
21339
- } else {
21340
- const cb = prompt.callback;
21341
- return await Promise.resolve(cb(extra));
21342
- }
21343
- });
21344
- this.setCompletionRequestHandler();
21345
- this._promptHandlersInitialized = true;
21214
+ const index = this._buffer.indexOf(`
21215
+ `);
21216
+ if (index === -1) {
21217
+ return null;
21218
+ }
21219
+ const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
21220
+ this._buffer = this._buffer.subarray(index + 1);
21221
+ return deserializeMessage(line);
21346
21222
  }
21347
- resource(name, uriOrTemplate, ...rest) {
21348
- let metadata;
21349
- if (typeof rest[0] === "object") {
21350
- metadata = rest.shift();
21223
+ clear() {
21224
+ this._buffer = undefined;
21225
+ }
21226
+ }
21227
+ function deserializeMessage(line) {
21228
+ return JSONRPCMessageSchema.parse(JSON.parse(line));
21229
+ }
21230
+ function serializeMessage(message) {
21231
+ return JSON.stringify(message) + `
21232
+ `;
21233
+ }
21234
+
21235
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
21236
+ class StdioServerTransport {
21237
+ constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
21238
+ this._stdin = _stdin;
21239
+ this._stdout = _stdout;
21240
+ this._readBuffer = new ReadBuffer;
21241
+ this._started = false;
21242
+ this._ondata = (chunk) => {
21243
+ this._readBuffer.append(chunk);
21244
+ this.processReadBuffer();
21245
+ };
21246
+ this._onerror = (error) => {
21247
+ var _a;
21248
+ (_a = this.onerror) === null || _a === undefined || _a.call(this, error);
21249
+ };
21250
+ }
21251
+ async start() {
21252
+ if (this._started) {
21253
+ throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
21351
21254
  }
21352
- const readCallback = rest[0];
21353
- if (typeof uriOrTemplate === "string") {
21354
- if (this._registeredResources[uriOrTemplate]) {
21355
- throw new Error(`Resource ${uriOrTemplate} is already registered`);
21356
- }
21357
- const registeredResource = {
21358
- name,
21359
- metadata,
21360
- readCallback,
21361
- enabled: true,
21362
- disable: () => registeredResource.update({ enabled: false }),
21363
- enable: () => registeredResource.update({ enabled: true }),
21364
- remove: () => registeredResource.update({ uri: null }),
21365
- update: (updates) => {
21366
- if (typeof updates.uri !== "undefined" && updates.uri !== uriOrTemplate) {
21367
- delete this._registeredResources[uriOrTemplate];
21368
- if (updates.uri)
21369
- this._registeredResources[updates.uri] = registeredResource;
21370
- }
21371
- if (typeof updates.name !== "undefined")
21372
- registeredResource.name = updates.name;
21373
- if (typeof updates.metadata !== "undefined")
21374
- registeredResource.metadata = updates.metadata;
21375
- if (typeof updates.callback !== "undefined")
21376
- registeredResource.readCallback = updates.callback;
21377
- if (typeof updates.enabled !== "undefined")
21378
- registeredResource.enabled = updates.enabled;
21379
- this.sendResourceListChanged();
21255
+ this._started = true;
21256
+ this._stdin.on("data", this._ondata);
21257
+ this._stdin.on("error", this._onerror);
21258
+ }
21259
+ processReadBuffer() {
21260
+ var _a, _b;
21261
+ while (true) {
21262
+ try {
21263
+ const message = this._readBuffer.readMessage();
21264
+ if (message === null) {
21265
+ break;
21380
21266
  }
21381
- };
21382
- this._registeredResources[uriOrTemplate] = registeredResource;
21383
- this.setResourceRequestHandlers();
21384
- this.sendResourceListChanged();
21385
- return registeredResource;
21386
- } else {
21387
- if (this._registeredResourceTemplates[name]) {
21388
- throw new Error(`Resource template ${name} is already registered`);
21267
+ (_a = this.onmessage) === null || _a === undefined || _a.call(this, message);
21268
+ } catch (error) {
21269
+ (_b = this.onerror) === null || _b === undefined || _b.call(this, error);
21389
21270
  }
21390
- const registeredResourceTemplate = {
21391
- resourceTemplate: uriOrTemplate,
21392
- metadata,
21393
- readCallback,
21394
- enabled: true,
21395
- disable: () => registeredResourceTemplate.update({ enabled: false }),
21396
- enable: () => registeredResourceTemplate.update({ enabled: true }),
21397
- remove: () => registeredResourceTemplate.update({ name: null }),
21398
- update: (updates) => {
21399
- if (typeof updates.name !== "undefined" && updates.name !== name) {
21400
- delete this._registeredResourceTemplates[name];
21401
- if (updates.name)
21402
- this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
21403
- }
21404
- if (typeof updates.template !== "undefined")
21405
- registeredResourceTemplate.resourceTemplate = updates.template;
21406
- if (typeof updates.metadata !== "undefined")
21407
- registeredResourceTemplate.metadata = updates.metadata;
21408
- if (typeof updates.callback !== "undefined")
21409
- registeredResourceTemplate.readCallback = updates.callback;
21410
- if (typeof updates.enabled !== "undefined")
21411
- registeredResourceTemplate.enabled = updates.enabled;
21412
- this.sendResourceListChanged();
21413
- }
21414
- };
21415
- this._registeredResourceTemplates[name] = registeredResourceTemplate;
21416
- this.setResourceRequestHandlers();
21417
- this.sendResourceListChanged();
21418
- return registeredResourceTemplate;
21419
21271
  }
21420
21272
  }
21421
- tool(name, ...rest) {
21422
- if (this._registeredTools[name]) {
21423
- throw new Error(`Tool ${name} is already registered`);
21273
+ async close() {
21274
+ var _a;
21275
+ this._stdin.off("data", this._ondata);
21276
+ this._stdin.off("error", this._onerror);
21277
+ const remainingDataListeners = this._stdin.listenerCount("data");
21278
+ if (remainingDataListeners === 0) {
21279
+ this._stdin.pause();
21424
21280
  }
21425
- let description;
21426
- if (typeof rest[0] === "string") {
21427
- description = rest.shift();
21281
+ this._readBuffer.clear();
21282
+ (_a = this.onclose) === null || _a === undefined || _a.call(this);
21283
+ }
21284
+ send(message) {
21285
+ return new Promise((resolve) => {
21286
+ const json = serializeMessage(message);
21287
+ if (this._stdout.write(json)) {
21288
+ resolve();
21289
+ } else {
21290
+ this._stdout.once("drain", resolve);
21291
+ }
21292
+ });
21293
+ }
21294
+ }
21295
+
21296
+ // src/server.ts
21297
+ var import_client = __toESM(require_lib(), 1);
21298
+
21299
+ // src/client/cache.ts
21300
+ class Cache {
21301
+ cache;
21302
+ age;
21303
+ constructor() {
21304
+ this.cache = new Map;
21305
+ this.age = 0;
21306
+ }
21307
+ get(key) {
21308
+ return this.cache.get(key) ?? null;
21309
+ }
21310
+ values() {
21311
+ return Array.from(this.cache.values());
21312
+ }
21313
+ setMany(values) {
21314
+ this.cache.clear();
21315
+ for (const [key, value] of values) {
21316
+ this.cache.set(key, value);
21428
21317
  }
21429
- let paramsSchema;
21430
- let annotations;
21431
- if (rest.length > 1) {
21432
- const firstArg = rest[0];
21433
- if (isZodRawShape(firstArg)) {
21434
- paramsSchema = rest.shift();
21435
- if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShape(rest[0])) {
21436
- annotations = rest.shift();
21437
- }
21438
- } else if (typeof firstArg === "object" && firstArg !== null) {
21439
- annotations = rest.shift();
21318
+ this.age = Date.now();
21319
+ }
21320
+ clear() {
21321
+ this.cache.clear();
21322
+ this.age = 0;
21323
+ }
21324
+ get isStale() {
21325
+ return Date.now() - this.age > 1000 * 60 * 5;
21326
+ }
21327
+ }
21328
+
21329
+ // src/client/shortcut.ts
21330
+ class ShortcutClientWrapper {
21331
+ client;
21332
+ currentUser = null;
21333
+ userCache;
21334
+ teamCache;
21335
+ workflowCache;
21336
+ constructor(client) {
21337
+ this.client = client;
21338
+ this.userCache = new Cache;
21339
+ this.teamCache = new Cache;
21340
+ this.workflowCache = new Cache;
21341
+ }
21342
+ async loadMembers() {
21343
+ if (this.userCache.isStale) {
21344
+ const response = await this.client.listMembers({});
21345
+ const members = response?.data ?? null;
21346
+ if (members) {
21347
+ this.userCache.setMany(members.map((member) => [member.id, member]));
21440
21348
  }
21441
21349
  }
21442
- const cb = rest[0];
21443
- const registeredTool = {
21444
- description,
21445
- inputSchema: paramsSchema === undefined ? undefined : z.object(paramsSchema),
21446
- annotations,
21447
- callback: cb,
21448
- enabled: true,
21449
- disable: () => registeredTool.update({ enabled: false }),
21450
- enable: () => registeredTool.update({ enabled: true }),
21451
- remove: () => registeredTool.update({ name: null }),
21452
- update: (updates) => {
21453
- if (typeof updates.name !== "undefined" && updates.name !== name) {
21454
- delete this._registeredTools[name];
21455
- if (updates.name)
21456
- this._registeredTools[updates.name] = registeredTool;
21457
- }
21458
- if (typeof updates.description !== "undefined")
21459
- registeredTool.description = updates.description;
21460
- if (typeof updates.paramsSchema !== "undefined")
21461
- registeredTool.inputSchema = z.object(updates.paramsSchema);
21462
- if (typeof updates.callback !== "undefined")
21463
- registeredTool.callback = updates.callback;
21464
- if (typeof updates.annotations !== "undefined")
21465
- registeredTool.annotations = updates.annotations;
21466
- if (typeof updates.enabled !== "undefined")
21467
- registeredTool.enabled = updates.enabled;
21468
- this.sendToolListChanged();
21469
- }
21470
- };
21471
- this._registeredTools[name] = registeredTool;
21472
- this.setToolRequestHandlers();
21473
- this.sendToolListChanged();
21474
- return registeredTool;
21475
21350
  }
21476
- prompt(name, ...rest) {
21477
- if (this._registeredPrompts[name]) {
21478
- throw new Error(`Prompt ${name} is already registered`);
21479
- }
21480
- let description;
21481
- if (typeof rest[0] === "string") {
21482
- description = rest.shift();
21351
+ async loadTeams() {
21352
+ if (this.teamCache.isStale) {
21353
+ const response = await this.client.listGroups();
21354
+ const groups = response?.data ?? null;
21355
+ if (groups) {
21356
+ this.teamCache.setMany(groups.map((group) => [group.id, group]));
21357
+ }
21483
21358
  }
21484
- let argsSchema;
21485
- if (rest.length > 1) {
21486
- argsSchema = rest.shift();
21359
+ }
21360
+ async loadWorkflows() {
21361
+ if (this.workflowCache.isStale) {
21362
+ const response = await this.client.listWorkflows();
21363
+ const workflows = response?.data ?? null;
21364
+ if (workflows) {
21365
+ this.workflowCache.setMany(workflows.map((workflow) => [workflow.id, workflow]));
21366
+ }
21487
21367
  }
21488
- const cb = rest[0];
21489
- const registeredPrompt = {
21490
- description,
21491
- argsSchema: argsSchema === undefined ? undefined : z.object(argsSchema),
21492
- callback: cb,
21493
- enabled: true,
21494
- disable: () => registeredPrompt.update({ enabled: false }),
21495
- enable: () => registeredPrompt.update({ enabled: true }),
21496
- remove: () => registeredPrompt.update({ name: null }),
21497
- update: (updates) => {
21498
- if (typeof updates.name !== "undefined" && updates.name !== name) {
21499
- delete this._registeredPrompts[name];
21500
- if (updates.name)
21501
- this._registeredPrompts[updates.name] = registeredPrompt;
21502
- }
21503
- if (typeof updates.description !== "undefined")
21504
- registeredPrompt.description = updates.description;
21505
- if (typeof updates.argsSchema !== "undefined")
21506
- registeredPrompt.argsSchema = z.object(updates.argsSchema);
21507
- if (typeof updates.callback !== "undefined")
21508
- registeredPrompt.callback = updates.callback;
21509
- if (typeof updates.enabled !== "undefined")
21510
- registeredPrompt.enabled = updates.enabled;
21511
- this.sendPromptListChanged();
21368
+ }
21369
+ async getCurrentUser() {
21370
+ if (this.currentUser)
21371
+ return this.currentUser;
21372
+ const response = await this.client.getCurrentMemberInfo();
21373
+ const user = response?.data;
21374
+ if (!user)
21375
+ return null;
21376
+ this.currentUser = user;
21377
+ return user;
21378
+ }
21379
+ async getUser(userId) {
21380
+ const response = await this.client.getMember(userId, {});
21381
+ const user = response?.data;
21382
+ if (!user)
21383
+ return null;
21384
+ return user;
21385
+ }
21386
+ async getUserMap(userIds) {
21387
+ await this.loadMembers();
21388
+ return new Map(userIds.map((id) => [id, this.userCache.get(id)]).filter((user) => user[1] !== null));
21389
+ }
21390
+ async getUsers(userIds) {
21391
+ await this.loadMembers();
21392
+ return userIds.map((id) => this.userCache.get(id)).filter((user) => user !== null);
21393
+ }
21394
+ async listMembers() {
21395
+ await this.loadMembers();
21396
+ const members = Array.from(this.userCache.values());
21397
+ return members;
21398
+ }
21399
+ async getWorkflowMap(workflowIds) {
21400
+ await this.loadWorkflows();
21401
+ return new Map(workflowIds.map((id) => [id, this.workflowCache.get(id)]).filter((workflow) => workflow[1] !== null));
21402
+ }
21403
+ async getWorkflows() {
21404
+ await this.loadWorkflows();
21405
+ return Array.from(this.workflowCache.values());
21406
+ }
21407
+ async getWorkflow(workflowPublicId) {
21408
+ const response = await this.client.getWorkflow(workflowPublicId);
21409
+ const workflow = response?.data;
21410
+ if (!workflow)
21411
+ return null;
21412
+ return workflow;
21413
+ }
21414
+ async getTeams() {
21415
+ await this.loadTeams();
21416
+ const teams = Array.from(this.teamCache.values());
21417
+ return teams;
21418
+ }
21419
+ async getTeamMap(teamIds) {
21420
+ await this.loadTeams();
21421
+ return new Map(teamIds.map((id) => [id, this.teamCache.get(id)]).filter((team) => team[1] !== null));
21422
+ }
21423
+ async getTeam(teamPublicId) {
21424
+ const response = await this.client.getGroup(teamPublicId);
21425
+ const group = response?.data;
21426
+ if (!group)
21427
+ return null;
21428
+ return group;
21429
+ }
21430
+ async createStory(params) {
21431
+ const response = await this.client.createStory(params);
21432
+ const story = response?.data ?? null;
21433
+ if (!story)
21434
+ throw new Error(`Failed to create the story: ${response.status}`);
21435
+ return story;
21436
+ }
21437
+ async updateStory(storyPublicId, params) {
21438
+ const response = await this.client.updateStory(storyPublicId, params);
21439
+ const story = response?.data ?? null;
21440
+ if (!story)
21441
+ throw new Error(`Failed to update the story: ${response.status}`);
21442
+ return story;
21443
+ }
21444
+ async getStory(storyPublicId) {
21445
+ const response = await this.client.getStory(storyPublicId);
21446
+ const story = response?.data ?? null;
21447
+ if (!story)
21448
+ return null;
21449
+ return story;
21450
+ }
21451
+ async getEpic(epicPublicId) {
21452
+ const response = await this.client.getEpic(epicPublicId);
21453
+ const epic = response?.data ?? null;
21454
+ if (!epic)
21455
+ return null;
21456
+ return epic;
21457
+ }
21458
+ async getIteration(iterationPublicId) {
21459
+ const response = await this.client.getIteration(iterationPublicId);
21460
+ const iteration = response?.data ?? null;
21461
+ if (!iteration)
21462
+ return null;
21463
+ return iteration;
21464
+ }
21465
+ async getMilestone(milestonePublicId) {
21466
+ const response = await this.client.getMilestone(milestonePublicId);
21467
+ const milestone = response?.data ?? null;
21468
+ if (!milestone)
21469
+ return null;
21470
+ return milestone;
21471
+ }
21472
+ async searchStories(query) {
21473
+ const response = await this.client.searchStories({ query, page_size: 25, detail: "full" });
21474
+ const stories = response?.data?.data;
21475
+ const total = response?.data?.total;
21476
+ if (!stories)
21477
+ return { stories: null, total: null };
21478
+ return { stories, total };
21479
+ }
21480
+ async searchIterations(query) {
21481
+ const response = await this.client.searchIterations({ query, page_size: 25, detail: "full" });
21482
+ const iterations = response?.data?.data;
21483
+ const total = response?.data?.total;
21484
+ if (!iterations)
21485
+ return { iterations: null, total: null };
21486
+ return { iterations, total };
21487
+ }
21488
+ async getActiveIteration(teamIds) {
21489
+ const response = await this.client.listIterations();
21490
+ const iterations = response?.data;
21491
+ if (!iterations)
21492
+ return new Map;
21493
+ const [today] = new Date().toISOString().split("T");
21494
+ const activeIterationByTeam = iterations.reduce((acc, iteration) => {
21495
+ if (iteration.status !== "started")
21496
+ return acc;
21497
+ const [startDate] = new Date(iteration.start_date).toISOString().split("T");
21498
+ const [endDate] = new Date(iteration.end_date).toISOString().split("T");
21499
+ if (!startDate || !endDate)
21500
+ return acc;
21501
+ if (startDate > today || endDate < today)
21502
+ return acc;
21503
+ if (!iteration.group_ids?.length)
21504
+ iteration.group_ids = ["none"];
21505
+ for (const groupId of iteration.group_ids) {
21506
+ if (groupId !== "none" && !teamIds.includes(groupId))
21507
+ continue;
21508
+ const prevIterations = acc.get(groupId);
21509
+ if (prevIterations) {
21510
+ acc.set(groupId, prevIterations.concat([iteration]));
21511
+ } else
21512
+ acc.set(groupId, [iteration]);
21513
+ }
21514
+ return acc;
21515
+ }, new Map);
21516
+ return activeIterationByTeam;
21517
+ }
21518
+ async getUpcomingIteration(teamIds) {
21519
+ const response = await this.client.listIterations();
21520
+ const iterations = response?.data;
21521
+ if (!iterations)
21522
+ return new Map;
21523
+ const [today] = new Date().toISOString().split("T");
21524
+ const upcomingIterationByTeam = iterations.reduce((acc, iteration) => {
21525
+ if (iteration.status !== "unstarted")
21526
+ return acc;
21527
+ const [startDate] = new Date(iteration.start_date).toISOString().split("T");
21528
+ const [endDate] = new Date(iteration.end_date).toISOString().split("T");
21529
+ if (!startDate || !endDate)
21530
+ return acc;
21531
+ if (startDate < today)
21532
+ return acc;
21533
+ if (!iteration.group_ids?.length)
21534
+ iteration.group_ids = ["none"];
21535
+ for (const groupId of iteration.group_ids) {
21536
+ if (groupId !== "none" && !teamIds.includes(groupId))
21537
+ continue;
21538
+ const prevIterations = acc.get(groupId);
21539
+ if (prevIterations) {
21540
+ acc.set(groupId, prevIterations.concat([iteration]));
21541
+ } else
21542
+ acc.set(groupId, [iteration]);
21512
21543
  }
21513
- };
21514
- this._registeredPrompts[name] = registeredPrompt;
21515
- this.setPromptRequestHandlers();
21516
- this.sendPromptListChanged();
21517
- return registeredPrompt;
21544
+ return acc;
21545
+ }, new Map);
21546
+ return upcomingIterationByTeam;
21518
21547
  }
21519
- isConnected() {
21520
- return this.server.transport !== undefined;
21548
+ async searchEpics(query) {
21549
+ const response = await this.client.searchEpics({ query, page_size: 25, detail: "full" });
21550
+ const epics = response?.data?.data;
21551
+ const total = response?.data?.total;
21552
+ if (!epics)
21553
+ return { epics: null, total: null };
21554
+ return { epics, total };
21521
21555
  }
21522
- sendResourceListChanged() {
21523
- if (this.isConnected()) {
21524
- this.server.sendResourceListChanged();
21525
- }
21556
+ async searchMilestones(query) {
21557
+ const response = await this.client.searchMilestones({ query, page_size: 25, detail: "full" });
21558
+ const milestones = response?.data?.data;
21559
+ const total = response?.data?.total;
21560
+ if (!milestones)
21561
+ return { milestones: null, total: null };
21562
+ return { milestones, total };
21526
21563
  }
21527
- sendToolListChanged() {
21528
- if (this.isConnected()) {
21529
- this.server.sendToolListChanged();
21530
- }
21564
+ async listIterationStories(iterationPublicId, includeDescription = false) {
21565
+ const response = await this.client.listIterationStories(iterationPublicId, {
21566
+ includes_description: includeDescription
21567
+ });
21568
+ const stories = response?.data;
21569
+ if (!stories)
21570
+ return { stories: null, total: null };
21571
+ return { stories, total: stories.length };
21531
21572
  }
21532
- sendPromptListChanged() {
21533
- if (this.isConnected()) {
21534
- this.server.sendPromptListChanged();
21535
- }
21573
+ async createStoryComment(storyPublicId, params) {
21574
+ const response = await this.client.createStoryComment(storyPublicId, params);
21575
+ const storyComment = response?.data ?? null;
21576
+ if (!storyComment)
21577
+ throw new Error(`Failed to create the comment: ${response.status}`);
21578
+ return storyComment;
21536
21579
  }
21537
- }
21538
- var EMPTY_OBJECT_JSON_SCHEMA = {
21539
- type: "object"
21540
- };
21541
- function isZodRawShape(obj) {
21542
- if (typeof obj !== "object" || obj === null)
21543
- return false;
21544
- const isEmptyObject = Object.keys(obj).length === 0;
21545
- return isEmptyObject || Object.values(obj).some(isZodTypeLike);
21546
- }
21547
- function isZodTypeLike(value) {
21548
- return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
21549
- }
21550
- function promptArgumentsFromSchema(schema) {
21551
- return Object.entries(schema.shape).map(([name, field]) => ({
21552
- name,
21553
- description: field.description,
21554
- required: !field.isOptional()
21555
- }));
21556
- }
21557
- function createCompletionResult(suggestions) {
21558
- return {
21559
- completion: {
21560
- values: suggestions.slice(0, 100),
21561
- total: suggestions.length,
21562
- hasMore: suggestions.length > 100
21563
- }
21564
- };
21565
- }
21566
- var EMPTY_COMPLETION_RESULT = {
21567
- completion: {
21568
- values: [],
21569
- hasMore: false
21580
+ async createIteration(params) {
21581
+ const response = await this.client.createIteration(params);
21582
+ const iteration = response?.data ?? null;
21583
+ if (!iteration)
21584
+ throw new Error(`Failed to create the iteration: ${response.status}`);
21585
+ return iteration;
21570
21586
  }
21571
- };
21572
-
21573
- // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
21574
- import process2 from "node:process";
21575
-
21576
- // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
21577
- class ReadBuffer {
21578
- append(chunk) {
21579
- this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
21587
+ async createEpic(params) {
21588
+ const response = await this.client.createEpic(params);
21589
+ const epic = response?.data ?? null;
21590
+ if (!epic)
21591
+ throw new Error(`Failed to create the epic: ${response.status}`);
21592
+ return epic;
21580
21593
  }
21581
- readMessage() {
21582
- if (!this._buffer) {
21583
- return null;
21584
- }
21585
- const index = this._buffer.indexOf(`
21586
- `);
21587
- if (index === -1) {
21588
- return null;
21589
- }
21590
- const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
21591
- this._buffer = this._buffer.subarray(index + 1);
21592
- return deserializeMessage(line);
21594
+ async addTaskToStory(storyPublicId, taskParams) {
21595
+ const { description, ownerIds } = taskParams;
21596
+ const params = {
21597
+ description,
21598
+ owner_ids: ownerIds
21599
+ };
21600
+ const response = await this.client.createTask(storyPublicId, params);
21601
+ const task = response?.data ?? null;
21602
+ if (!task)
21603
+ throw new Error(`Failed to create the task: ${response.status}`);
21604
+ return task;
21593
21605
  }
21594
- clear() {
21595
- this._buffer = undefined;
21606
+ async addRelationToStory(storyPublicId, linkedStoryId, verb) {
21607
+ const response = await this.client.createStoryLink({
21608
+ object_id: linkedStoryId,
21609
+ subject_id: storyPublicId,
21610
+ verb
21611
+ });
21612
+ const storyLink = response?.data ?? null;
21613
+ if (!storyLink)
21614
+ throw new Error(`Failed to create the story links: ${response.status}`);
21615
+ return storyLink;
21596
21616
  }
21597
- }
21598
- function deserializeMessage(line) {
21599
- return JSONRPCMessageSchema.parse(JSON.parse(line));
21600
- }
21601
- function serializeMessage(message) {
21602
- return JSON.stringify(message) + `
21603
- `;
21604
- }
21605
-
21606
- // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
21607
- class StdioServerTransport {
21608
- constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
21609
- this._stdin = _stdin;
21610
- this._stdout = _stdout;
21611
- this._readBuffer = new ReadBuffer;
21612
- this._started = false;
21613
- this._ondata = (chunk) => {
21614
- this._readBuffer.append(chunk);
21615
- this.processReadBuffer();
21616
- };
21617
- this._onerror = (error) => {
21618
- var _a;
21619
- (_a = this.onerror) === null || _a === undefined || _a.call(this, error);
21620
- };
21617
+ async getTask(storyPublicId, taskPublicId) {
21618
+ const response = await this.client.getTask(storyPublicId, taskPublicId);
21619
+ const task = response?.data ?? null;
21620
+ if (!task)
21621
+ throw new Error(`Failed to get the task: ${response.status}`);
21622
+ return task;
21621
21623
  }
21622
- async start() {
21623
- if (this._started) {
21624
- throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
21625
- }
21626
- this._started = true;
21627
- this._stdin.on("data", this._ondata);
21628
- this._stdin.on("error", this._onerror);
21624
+ async updateTask(storyPublicId, taskPublicId, taskParams) {
21625
+ const { description, ownerIds } = taskParams;
21626
+ const params = {
21627
+ description,
21628
+ owner_ids: ownerIds,
21629
+ complete: taskParams.isCompleted
21630
+ };
21631
+ const response = await this.client.updateTask(storyPublicId, taskPublicId, params);
21632
+ const task = response?.data ?? null;
21633
+ if (!task)
21634
+ throw new Error(`Failed to update the task: ${response.status}`);
21635
+ return task;
21629
21636
  }
21630
- processReadBuffer() {
21631
- var _a, _b;
21632
- while (true) {
21633
- try {
21634
- const message = this._readBuffer.readMessage();
21635
- if (message === null) {
21636
- break;
21637
- }
21638
- (_a = this.onmessage) === null || _a === undefined || _a.call(this, message);
21639
- } catch (error) {
21640
- (_b = this.onerror) === null || _b === undefined || _b.call(this, error);
21641
- }
21637
+ async addExternalLinkToStory(storyPublicId, externalLink) {
21638
+ const story = await this.getStory(storyPublicId);
21639
+ if (!story)
21640
+ throw new Error(`Story ${storyPublicId} not found`);
21641
+ const currentLinks = story.external_links || [];
21642
+ if (currentLinks.some((link) => link.toLowerCase() === externalLink.toLowerCase())) {
21643
+ return story;
21642
21644
  }
21645
+ const updatedLinks = [...currentLinks, externalLink];
21646
+ return await this.updateStory(storyPublicId, { external_links: updatedLinks });
21643
21647
  }
21644
- async close() {
21645
- var _a;
21646
- this._stdin.off("data", this._ondata);
21647
- this._stdin.off("error", this._onerror);
21648
- const remainingDataListeners = this._stdin.listenerCount("data");
21649
- if (remainingDataListeners === 0) {
21650
- this._stdin.pause();
21651
- }
21652
- this._readBuffer.clear();
21653
- (_a = this.onclose) === null || _a === undefined || _a.call(this);
21648
+ async removeExternalLinkFromStory(storyPublicId, externalLink) {
21649
+ const story = await this.getStory(storyPublicId);
21650
+ if (!story)
21651
+ throw new Error(`Story ${storyPublicId} not found`);
21652
+ const currentLinks = story.external_links || [];
21653
+ const updatedLinks = currentLinks.filter((link) => link.toLowerCase() !== externalLink.toLowerCase());
21654
+ return await this.updateStory(storyPublicId, { external_links: updatedLinks });
21654
21655
  }
21655
- send(message) {
21656
- return new Promise((resolve) => {
21657
- const json = serializeMessage(message);
21658
- if (this._stdout.write(json)) {
21659
- resolve();
21660
- } else {
21661
- this._stdout.once("drain", resolve);
21662
- }
21656
+ async getStoriesByExternalLink(externalLink) {
21657
+ const response = await this.client.getExternalLinkStories({
21658
+ external_link: externalLink.toLowerCase()
21663
21659
  });
21660
+ const stories = response?.data;
21661
+ if (!stories)
21662
+ return { stories: null, total: null };
21663
+ return { stories, total: stories.length };
21664
+ }
21665
+ async setStoryExternalLinks(storyPublicId, externalLinks) {
21666
+ return await this.updateStory(storyPublicId, { external_links: externalLinks });
21664
21667
  }
21665
21668
  }
21666
21669
 
21667
- // src/server.ts
21668
- var import_client = __toESM(require_lib(), 1);
21669
-
21670
21670
  // package.json
21671
21671
  var name = "@shortcut/mcp";
21672
- var version = "0.8.4";
21672
+ var version = "0.9.0";
21673
21673
 
21674
21674
  // src/tools/base.ts
21675
21675
  class BaseTools {
@@ -22320,14 +22320,16 @@ The story will be added to the default state for the workflow.
22320
22320
  type: z.enum(["feature", "bug", "chore"]).default("feature").describe("The type of the story"),
22321
22321
  owner: z.string().optional().describe("The user id of the owner of the story"),
22322
22322
  epic: z.number().optional().describe("The epic id of the epic the story belongs to"),
22323
+ iteration: z.number().optional().describe("The iteration id of the iteration the story belongs to"),
22323
22324
  team: z.string().optional().describe("The team ID or mention name of the team the story belongs to. Required unless a workflow is specified."),
22324
22325
  workflow: z.number().optional().describe("The workflow ID to add the story to. Required unless a team is specified.")
22325
- }, async ({ name: name2, description, type, owner, epic, team, workflow }) => await tools.createStory({
22326
+ }, async ({ name: name2, description, type, owner, epic, iteration, team, workflow }) => await tools.createStory({
22326
22327
  name: name2,
22327
22328
  description,
22328
22329
  type,
22329
22330
  owner,
22330
22331
  epic,
22332
+ iteration,
22331
22333
  team,
22332
22334
  workflow
22333
22335
  }));
@@ -22338,6 +22340,7 @@ The story will be added to the default state for the workflow.
22338
22340
  type: z.enum(["feature", "bug", "chore"]).optional().describe("The type of the story"),
22339
22341
  epic: z.number().nullable().optional().describe("The epic id of the epic the story belongs to, or null to unset"),
22340
22342
  estimate: z.number().nullable().optional().describe("The point estimate of the story, or null to unset"),
22343
+ iteration: z.number().nullable().optional().describe("The iteration id of the iteration the story belongs to, or null to unset"),
22341
22344
  owner_ids: z.array(z.string()).optional().describe("Array of user UUIDs to assign as owners of the story"),
22342
22345
  workflow_state_id: z.number().optional().describe("The workflow state ID to move the story to"),
22343
22346
  labels: z.array(z.object({
@@ -22419,7 +22422,7 @@ The story will be added to the default state for the workflow.
22419
22422
  return this.toResult(`Unassigned current user as owner of story sc-${storyPublicId}`);
22420
22423
  }
22421
22424
  createBranchName(currentUser, story) {
22422
- return `${currentUser.mention_name}/sc-${story.id}/${story.name.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]/g, "")}`.substring(0, 50);
22425
+ return `${currentUser.mention_name}/sc-${story.id}/${story.name.toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]/g, "")}`.substring(0, 50);
22423
22426
  }
22424
22427
  async getStoryBranchName(storyPublicId) {
22425
22428
  const currentUser = await this.client.getCurrentUser();
@@ -22437,6 +22440,7 @@ The story will be added to the default state for the workflow.
22437
22440
  type,
22438
22441
  owner,
22439
22442
  epic,
22443
+ iteration,
22440
22444
  team,
22441
22445
  workflow
22442
22446
  }) {
@@ -22457,6 +22461,7 @@ The story will be added to the default state for the workflow.
22457
22461
  story_type: type,
22458
22462
  owner_ids: owner ? [owner] : [],
22459
22463
  epic_id: epic,
22464
+ iteration_id: iteration,
22460
22465
  group_id: team,
22461
22466
  workflow_state_id: fullWorkflow.default_state_id
22462
22467
  });
@@ -22478,10 +22483,7 @@ The story will be added to the default state for the workflow.
22478
22483
  throw new Error(`Failed to retrieve Shortcut story with public ID: ${storyPublicId}.`);
22479
22484
  return this.toResult(`Story: sc-${storyPublicId}`, await this.entityWithRelatedEntities(story, "story"));
22480
22485
  }
22481
- async createStoryComment({
22482
- storyPublicId,
22483
- text
22484
- }) {
22486
+ async createStoryComment({ storyPublicId, text }) {
22485
22487
  if (!storyPublicId)
22486
22488
  throw new Error("Story public ID is required");
22487
22489
  if (!text)
@@ -22512,6 +22514,8 @@ The story will be added to the default state for the workflow.
22512
22514
  updateParams.epic_id = updates.epic;
22513
22515
  if (updates.estimate !== undefined)
22514
22516
  updateParams.estimate = updates.estimate;
22517
+ if (updates.iteration !== undefined)
22518
+ updateParams.iteration_id = updates.iteration;
22515
22519
  if (updates.owner_ids !== undefined)
22516
22520
  updateParams.owner_ids = updates.owner_ids;
22517
22521
  if (updates.workflow_state_id !== undefined)