@sanity/cli 7.13.0 → 7.14.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 (36) hide show
  1. package/dist/actions/auth/getProviderName.js +13 -0
  2. package/dist/actions/auth/getProviderName.js.map +1 -1
  3. package/dist/actions/debug/types.js.map +1 -1
  4. package/dist/actions/deploy/deployApp.js +1 -0
  5. package/dist/actions/deploy/deployApp.js.map +1 -1
  6. package/dist/actions/deploy/deployChecks.js +25 -4
  7. package/dist/actions/deploy/deployChecks.js.map +1 -1
  8. package/dist/actions/deploy/resolveDeployTarget.js +23 -4
  9. package/dist/actions/deploy/resolveDeployTarget.js.map +1 -1
  10. package/dist/actions/init/initAction.js +3 -3
  11. package/dist/actions/init/initAction.js.map +1 -1
  12. package/dist/commands/cors/add.js +13 -7
  13. package/dist/commands/cors/add.js.map +1 -1
  14. package/dist/commands/datasets/copy.js +6 -3
  15. package/dist/commands/datasets/copy.js.map +1 -1
  16. package/dist/commands/debug.js +1 -1
  17. package/dist/commands/debug.js.map +1 -1
  18. package/dist/exports/invokeSanityCli/commandPolicies/index.js +6 -0
  19. package/dist/exports/invokeSanityCli/commandPolicies/index.js.map +1 -0
  20. package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +167 -0
  21. package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -0
  22. package/dist/exports/invokeSanityCli/commandPolicies/policy.js +46 -0
  23. package/dist/exports/invokeSanityCli/commandPolicies/policy.js.map +1 -0
  24. package/dist/exports/invokeSanityCli/help.js +146 -0
  25. package/dist/exports/invokeSanityCli/help.js.map +1 -0
  26. package/dist/exports/invokeSanityCli/index.d.ts +60 -0
  27. package/dist/exports/invokeSanityCli/index.js +177 -0
  28. package/dist/exports/invokeSanityCli/index.js.map +1 -0
  29. package/dist/server/devServer.js +16 -2
  30. package/dist/server/devServer.js.map +1 -1
  31. package/dist/util/getProjectDefaults.js +4 -1
  32. package/dist/util/getProjectDefaults.js.map +1 -1
  33. package/dist/util/packageManager/preferredPm.js +45 -6
  34. package/dist/util/packageManager/preferredPm.js.map +1 -1
  35. package/oclif.manifest.json +1 -1
  36. package/package.json +9 -4
@@ -0,0 +1,167 @@
1
+ import { allow, conditionalDenyFlags, conditionalPolicy, deny } from './policy.js';
2
+ /**
3
+ * A typed `-F/--field` value of `@<file>` or `@-` makes the `api` command
4
+ * read the host's filesystem or stdin (raw `-f` fields are always verbatim).
5
+ */ function fieldReadsFromHost(field) {
6
+ if (typeof field !== 'string') return false;
7
+ const separatorIndex = field.indexOf('=');
8
+ return separatorIndex > 0 && field[separatorIndex + 1] === '@';
9
+ }
10
+ /**
11
+ * MCP programmatic mode disables local project/config discovery (see the CLI
12
+ * execution context). Missing project or dataset values may therefore produce
13
+ * a usage error, but cannot cause local filesystem access. Destructive remote
14
+ * operations are allowed and do not by themselves make a command unsafe.
15
+ *
16
+ * Every manifest command must have exactly one policy here:
17
+ * - allow: every valid invocation is safe
18
+ * - conditional: safety depends on parsed arguments or flags
19
+ * - deny: no invocation is safe
20
+ */ export const mcpPolicy = {
21
+ // Special exception, this can be very dangerous but is also super useful
22
+ // to expose. Only the host input channels are refused: `--input` reads the
23
+ // request body from the host's filesystem or stdin, and `-F key=@<file>` /
24
+ // `-F key=@-` field values do the same.
25
+ api: conditionalPolicy({
26
+ deniedFlags: [
27
+ 'input'
28
+ ],
29
+ validate: ({ flags })=>!Array.isArray(flags.field) || !flags.field.some((field)=>fieldReadsFromHost(field))
30
+ }),
31
+ 'backups:disable': allow,
32
+ // Writes a downloaded backup to the local filesystem.
33
+ 'backups:download': deny,
34
+ 'backups:enable': allow,
35
+ 'backups:list': allow,
36
+ // Requires a local Studio project and writes build output to disk.
37
+ build: deny,
38
+ // Reads and rewrites local source code.
39
+ codemod: deny,
40
+ 'cors:add': allow,
41
+ 'cors:delete': allow,
42
+ 'cors:list': allow,
43
+ 'datasets:alias:create': allow,
44
+ 'datasets:alias:delete': allow,
45
+ 'datasets:alias:link': allow,
46
+ 'datasets:alias:unlink': allow,
47
+ 'datasets:copy': allow,
48
+ 'datasets:create': allow,
49
+ 'datasets:delete': allow,
50
+ 'datasets:embeddings:disable': allow,
51
+ 'datasets:embeddings:enable': allow,
52
+ 'datasets:embeddings:status': allow,
53
+ // Writes dataset contents and assets to the local filesystem.
54
+ 'datasets:export': deny,
55
+ // Reads import data from the local filesystem and may replace documents.
56
+ 'datasets:import': deny,
57
+ 'datasets:list': allow,
58
+ 'datasets:visibility:get': allow,
59
+ 'datasets:visibility:set': allow,
60
+ // Inspects local project files and can print authentication secrets.
61
+ debug: deny,
62
+ // Reads, builds, and deploys a local Studio project.
63
+ deploy: deny,
64
+ // Loads a local Studio project and starts a development server.
65
+ dev: deny,
66
+ // Opens a browser on the machine running the MCP server.
67
+ 'docs:browse': deny,
68
+ // --web opens a browser on the machine running the MCP server.
69
+ 'docs:read': conditionalDenyFlags('web'),
70
+ 'docs:search': allow,
71
+ // Reads and executes local project configuration for diagnostics.
72
+ doctor: deny,
73
+ // Reads document input from disk or launches a local editor.
74
+ 'documents:create': deny,
75
+ 'documents:delete': allow,
76
+ 'documents:get': allow,
77
+ 'documents:query': allow,
78
+ // Loads a local Studio schema to validate documents.
79
+ 'documents:validate': deny,
80
+ // Executes arbitrary code in the local Studio context.
81
+ exec: deny,
82
+ // Loads a local schema and deploys a GraphQL API.
83
+ 'graphql:deploy': deny,
84
+ 'graphql:list': allow,
85
+ // --api loads GraphQL definitions from the local project; explicit project/dataset flags are safe.
86
+ 'graphql:undeploy': conditionalDenyFlags('api'),
87
+ 'hooks:attempt': allow,
88
+ 'hooks:create': allow,
89
+ 'hooks:delete': allow,
90
+ 'hooks:list': allow,
91
+ 'hooks:logs': allow,
92
+ // Creates or modifies a local project and may install dependencies.
93
+ init: deny,
94
+ // Installs packages into the local project.
95
+ install: deny,
96
+ // Opens a browser on the machine running the MCP server.
97
+ learn: deny,
98
+ // Performs an authentication flow.
99
+ login: deny,
100
+ // Performs an authentication operation and clears local credentials.
101
+ logout: deny,
102
+ // Reads local project configuration and opens a browser.
103
+ manage: deny,
104
+ // Loads local Studio configuration and writes manifest files.
105
+ 'manifest:extract': deny,
106
+ // Reads and writes local MCP client configuration.
107
+ 'mcp:configure': deny,
108
+ // Writes an aspect definition to the local filesystem.
109
+ 'media:create-aspect': deny,
110
+ 'media:delete-aspect': allow,
111
+ // Reads a local aspect definition before deploying it.
112
+ 'media:deploy-aspect': deny,
113
+ // Writes media assets to the local filesystem.
114
+ 'media:export': deny,
115
+ // Reads media assets from the local filesystem.
116
+ 'media:import': deny,
117
+ // Creates migration source files in the local project.
118
+ 'migrations:create': deny,
119
+ // Reads and loads migration definitions from the local project.
120
+ 'migrations:list': deny,
121
+ // Executes local migration code that may perform arbitrary document mutations.
122
+ 'migrations:run': deny,
123
+ // --web opens a browser on the machine running the MCP server.
124
+ 'openapi:get': conditionalDenyFlags('web'),
125
+ 'openapi:list': conditionalDenyFlags('web'),
126
+ 'organizations:create': allow,
127
+ 'organizations:delete': allow,
128
+ 'organizations:get': allow,
129
+ 'organizations:list': allow,
130
+ 'organizations:update': allow,
131
+ // Serves a local production build.
132
+ preview: deny,
133
+ 'projects:create': allow,
134
+ 'projects:list': allow,
135
+ // Loads the local Studio configuration to resolve the datasets containing each schema.
136
+ 'schemas:delete': deny,
137
+ // Loads local schema files before deploying them.
138
+ 'schemas:deploy': deny,
139
+ // Loads local Studio configuration and writes an extracted schema to disk.
140
+ 'schemas:extract': deny,
141
+ // Requires a local project and loads its schema configuration.
142
+ 'schemas:list': deny,
143
+ // Loads and executes a local Studio schema.
144
+ 'schemas:validate': deny,
145
+ // Installs skills into local editor configuration directories.
146
+ 'skills:install': deny,
147
+ // Changes account telemetry preferences and mutates local cached configuration.
148
+ 'telemetry:disable': deny,
149
+ // Changes account telemetry preferences and mutates local cached configuration.
150
+ 'telemetry:enable': deny,
151
+ 'telemetry:status': allow,
152
+ // Creates authentication credentials.
153
+ 'tokens:create': deny,
154
+ // Deletes authentication credentials.
155
+ 'tokens:delete': deny,
156
+ // Exposes authentication credential metadata.
157
+ 'tokens:list': deny,
158
+ // Loads local CLI and workbench configuration to identify the deployed Studio or application.
159
+ undeploy: deny,
160
+ // Grants a user access to a project.
161
+ 'users:invite': deny,
162
+ 'users:list': allow,
163
+ // Reads the local project and installed package tree.
164
+ versions: deny
165
+ };
166
+
167
+ //# sourceMappingURL=mcpPolicy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/exports/invokeSanityCli/commandPolicies/mcpPolicy.ts"],"sourcesContent":["import {\n allow,\n type CommandPolicySet,\n conditionalDenyFlags,\n conditionalPolicy,\n deny,\n} from './policy.js'\n\n/**\n * A typed `-F/--field` value of `@<file>` or `@-` makes the `api` command\n * read the host's filesystem or stdin (raw `-f` fields are always verbatim).\n */\nfunction fieldReadsFromHost(field: unknown): boolean {\n if (typeof field !== 'string') return false\n const separatorIndex = field.indexOf('=')\n return separatorIndex > 0 && field[separatorIndex + 1] === '@'\n}\n\n/**\n * MCP programmatic mode disables local project/config discovery (see the CLI\n * execution context). Missing project or dataset values may therefore produce\n * a usage error, but cannot cause local filesystem access. Destructive remote\n * operations are allowed and do not by themselves make a command unsafe.\n *\n * Every manifest command must have exactly one policy here:\n * - allow: every valid invocation is safe\n * - conditional: safety depends on parsed arguments or flags\n * - deny: no invocation is safe\n */\nexport const mcpPolicy: CommandPolicySet = {\n // Special exception, this can be very dangerous but is also super useful\n // to expose. Only the host input channels are refused: `--input` reads the\n // request body from the host's filesystem or stdin, and `-F key=@<file>` /\n // `-F key=@-` field values do the same.\n api: conditionalPolicy({\n deniedFlags: ['input'],\n validate: ({flags}) =>\n !Array.isArray(flags.field) || !flags.field.some((field) => fieldReadsFromHost(field)),\n }),\n\n 'backups:disable': allow,\n // Writes a downloaded backup to the local filesystem.\n 'backups:download': deny,\n 'backups:enable': allow,\n 'backups:list': allow,\n\n // Requires a local Studio project and writes build output to disk.\n build: deny,\n\n // Reads and rewrites local source code.\n codemod: deny,\n\n 'cors:add': allow,\n 'cors:delete': allow,\n 'cors:list': allow,\n\n 'datasets:alias:create': allow,\n 'datasets:alias:delete': allow,\n 'datasets:alias:link': allow,\n 'datasets:alias:unlink': allow,\n 'datasets:copy': allow,\n 'datasets:create': allow,\n 'datasets:delete': allow,\n 'datasets:embeddings:disable': allow,\n 'datasets:embeddings:enable': allow,\n 'datasets:embeddings:status': allow,\n // Writes dataset contents and assets to the local filesystem.\n 'datasets:export': deny,\n // Reads import data from the local filesystem and may replace documents.\n 'datasets:import': deny,\n 'datasets:list': allow,\n 'datasets:visibility:get': allow,\n 'datasets:visibility:set': allow,\n\n // Inspects local project files and can print authentication secrets.\n debug: deny,\n\n // Reads, builds, and deploys a local Studio project.\n deploy: deny,\n\n // Loads a local Studio project and starts a development server.\n dev: deny,\n\n // Opens a browser on the machine running the MCP server.\n 'docs:browse': deny,\n // --web opens a browser on the machine running the MCP server.\n 'docs:read': conditionalDenyFlags('web'),\n 'docs:search': allow,\n\n // Reads and executes local project configuration for diagnostics.\n doctor: deny,\n\n // Reads document input from disk or launches a local editor.\n 'documents:create': deny,\n 'documents:delete': allow,\n 'documents:get': allow,\n 'documents:query': allow,\n // Loads a local Studio schema to validate documents.\n 'documents:validate': deny,\n\n // Executes arbitrary code in the local Studio context.\n exec: deny,\n\n // Loads a local schema and deploys a GraphQL API.\n 'graphql:deploy': deny,\n 'graphql:list': allow,\n // --api loads GraphQL definitions from the local project; explicit project/dataset flags are safe.\n 'graphql:undeploy': conditionalDenyFlags('api'),\n\n 'hooks:attempt': allow,\n 'hooks:create': allow,\n 'hooks:delete': allow,\n 'hooks:list': allow,\n 'hooks:logs': allow,\n\n // Creates or modifies a local project and may install dependencies.\n init: deny,\n\n // Installs packages into the local project.\n install: deny,\n\n // Opens a browser on the machine running the MCP server.\n learn: deny,\n\n // Performs an authentication flow.\n login: deny,\n\n // Performs an authentication operation and clears local credentials.\n logout: deny,\n\n // Reads local project configuration and opens a browser.\n manage: deny,\n\n // Loads local Studio configuration and writes manifest files.\n 'manifest:extract': deny,\n\n // Reads and writes local MCP client configuration.\n 'mcp:configure': deny,\n\n // Writes an aspect definition to the local filesystem.\n 'media:create-aspect': deny,\n 'media:delete-aspect': allow,\n // Reads a local aspect definition before deploying it.\n 'media:deploy-aspect': deny,\n // Writes media assets to the local filesystem.\n 'media:export': deny,\n // Reads media assets from the local filesystem.\n 'media:import': deny,\n\n // Creates migration source files in the local project.\n 'migrations:create': deny,\n // Reads and loads migration definitions from the local project.\n 'migrations:list': deny,\n // Executes local migration code that may perform arbitrary document mutations.\n 'migrations:run': deny,\n\n // --web opens a browser on the machine running the MCP server.\n 'openapi:get': conditionalDenyFlags('web'),\n 'openapi:list': conditionalDenyFlags('web'),\n\n 'organizations:create': allow,\n 'organizations:delete': allow,\n 'organizations:get': allow,\n 'organizations:list': allow,\n 'organizations:update': allow,\n\n // Serves a local production build.\n preview: deny,\n\n 'projects:create': allow,\n 'projects:list': allow,\n\n // Loads the local Studio configuration to resolve the datasets containing each schema.\n 'schemas:delete': deny,\n // Loads local schema files before deploying them.\n 'schemas:deploy': deny,\n // Loads local Studio configuration and writes an extracted schema to disk.\n 'schemas:extract': deny,\n // Requires a local project and loads its schema configuration.\n 'schemas:list': deny,\n // Loads and executes a local Studio schema.\n 'schemas:validate': deny,\n\n // Installs skills into local editor configuration directories.\n 'skills:install': deny,\n\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:disable': deny,\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:enable': deny,\n 'telemetry:status': allow,\n\n // Creates authentication credentials.\n 'tokens:create': deny,\n // Deletes authentication credentials.\n 'tokens:delete': deny,\n // Exposes authentication credential metadata.\n 'tokens:list': deny,\n\n // Loads local CLI and workbench configuration to identify the deployed Studio or application.\n undeploy: deny,\n\n // Grants a user access to a project.\n 'users:invite': deny,\n 'users:list': allow,\n\n // Reads the local project and installed package tree.\n versions: deny,\n}\n"],"names":["allow","conditionalDenyFlags","conditionalPolicy","deny","fieldReadsFromHost","field","separatorIndex","indexOf","mcpPolicy","api","deniedFlags","validate","flags","Array","isArray","some","build","codemod","debug","deploy","dev","doctor","exec","init","install","learn","login","logout","manage","preview","undeploy","versions"],"mappings":"AAAA,SACEA,KAAK,EAELC,oBAAoB,EACpBC,iBAAiB,EACjBC,IAAI,QACC,cAAa;AAEpB;;;CAGC,GACD,SAASC,mBAAmBC,KAAc;IACxC,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,MAAMC,iBAAiBD,MAAME,OAAO,CAAC;IACrC,OAAOD,iBAAiB,KAAKD,KAAK,CAACC,iBAAiB,EAAE,KAAK;AAC7D;AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAME,YAA8B;IACzC,yEAAyE;IACzE,2EAA2E;IAC3E,2EAA2E;IAC3E,wCAAwC;IACxCC,KAAKP,kBAAkB;QACrBQ,aAAa;YAAC;SAAQ;QACtBC,UAAU,CAAC,EAACC,KAAK,EAAC,GAChB,CAACC,MAAMC,OAAO,CAACF,MAAMP,KAAK,KAAK,CAACO,MAAMP,KAAK,CAACU,IAAI,CAAC,CAACV,QAAUD,mBAAmBC;IACnF;IAEA,mBAAmBL;IACnB,sDAAsD;IACtD,oBAAoBG;IACpB,kBAAkBH;IAClB,gBAAgBA;IAEhB,mEAAmE;IACnEgB,OAAOb;IAEP,wCAAwC;IACxCc,SAASd;IAET,YAAYH;IACZ,eAAeA;IACf,aAAaA;IAEb,yBAAyBA;IACzB,yBAAyBA;IACzB,uBAAuBA;IACvB,yBAAyBA;IACzB,iBAAiBA;IACjB,mBAAmBA;IACnB,mBAAmBA;IACnB,+BAA+BA;IAC/B,8BAA8BA;IAC9B,8BAA8BA;IAC9B,8DAA8D;IAC9D,mBAAmBG;IACnB,yEAAyE;IACzE,mBAAmBA;IACnB,iBAAiBH;IACjB,2BAA2BA;IAC3B,2BAA2BA;IAE3B,qEAAqE;IACrEkB,OAAOf;IAEP,qDAAqD;IACrDgB,QAAQhB;I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gBA;IAChB,4CAA4C;IAC5C,oBAAoBA;IAEpB,+DAA+D;IAC/D,kBAAkBA;IAElB,gFAAgF;IAChF,qBAAqBA;IACrB,gFAAgF;IAChF,oBAAoBA;IACpB,oBAAoBH;IAEpB,sCAAsC;IACtC,iBAAiBG;IACjB,sCAAsC;IACtC,iBAAiBA;IACjB,8CAA8C;IAC9C,eAAeA;IAEf,8FAA8F;IAC9F2B,UAAU3B;IAEV,qCAAqC;IACrC,gBAAgBA;IAChB,cAAcH;IAEd,sDAAsD;IACtD+B,UAAU5B;AACZ,EAAC"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Per-source command policies for programmatic CLI invocation.
3
+ *
4
+ * A policy decides, for one invocation source (e.g. the remote MCP server),
5
+ * which commands may be invoked and — for conditional entries — which parsed
6
+ * invocations of those commands are acceptable. Policies are exhaustive:
7
+ * every command in this package's oclif manifest has exactly one entry, so a
8
+ * newly added CLI command cannot slip into (or ambiguously stay out of) the
9
+ * invokable surface. A unit test enforces this; at runtime an uncategorized
10
+ * command id fails closed (treated as deny).
11
+ */ /** The parsed command invocation a conditional policy is evaluated against. */ /** Every valid invocation of the command is safe. */ export const allow = {
12
+ kind: 'allow',
13
+ validate: ()=>true
14
+ };
15
+ /** No invocation of the command is safe. Behaves like an unknown command. */ export const deny = {
16
+ kind: 'deny',
17
+ validate: ()=>false
18
+ };
19
+ /**
20
+ * Conditional policies to deny flags. The flags are also hidden
21
+ * from rendered help, so hosts are never told about surface they cannot use.
22
+ */ export function conditionalDenyFlags(...names) {
23
+ return {
24
+ deniedFlags: names,
25
+ kind: 'conditional',
26
+ validate: ({ flags })=>names.every((name)=>flags[name] === undefined || flags[name] === false)
27
+ };
28
+ }
29
+ /**
30
+ * Conditional policy combining {@link conditionalDenyFlags} with an extra
31
+ * predicate on the parsed invocation, for conditions a flag name alone
32
+ * cannot express — e.g. flag values that would read from the host machine.
33
+ * `deniedFlags` are hidden from rendered help; the predicate is not
34
+ * expressible there, so flags it constrains stay advertised.
35
+ */ export function conditionalPolicy(options) {
36
+ const denyFlags = conditionalDenyFlags(...options.deniedFlags ?? []);
37
+ return {
38
+ ...denyFlags,
39
+ validate: (invocation)=>denyFlags.validate(invocation) && options.validate(invocation)
40
+ };
41
+ }
42
+ export function isConditionalInvocationPolicy(policy) {
43
+ return policy.kind === 'conditional';
44
+ }
45
+
46
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/exports/invokeSanityCli/commandPolicies/policy.ts"],"sourcesContent":["/**\n * Per-source command policies for programmatic CLI invocation.\n *\n * A policy decides, for one invocation source (e.g. the remote MCP server),\n * which commands may be invoked and — for conditional entries — which parsed\n * invocations of those commands are acceptable. Policies are exhaustive:\n * every command in this package's oclif manifest has exactly one entry, so a\n * newly added CLI command cannot slip into (or ambiguously stay out of) the\n * invokable surface. A unit test enforces this; at runtime an uncategorized\n * command id fails closed (treated as deny).\n */\n\n/** The parsed command invocation a conditional policy is evaluated against. */\ninterface Invocation {\n args: Readonly<Record<string, unknown>>\n flags: Readonly<Record<string, unknown>>\n}\n\ntype InvocationPolicy = (invocation: Invocation) => boolean\n\ntype ConditionalInvocationPolicy = CommandPolicy & {\n /**\n * Flag names this policy refuses. Declarative so the help renderer can\n * omit them (and examples using them) from the advertised command surface.\n */\n deniedFlags: readonly string[]\n\n kind: 'conditional'\n}\n\nexport interface CommandPolicy {\n kind: 'allow' | 'conditional' | 'deny'\n validate: InvocationPolicy\n}\n\n/** Every valid invocation of the command is safe. */\nexport const allow: CommandPolicy = {kind: 'allow', validate: () => true}\n\n/** No invocation of the command is safe. Behaves like an unknown command. */\nexport const deny: CommandPolicy = {kind: 'deny', validate: () => false}\n\n/**\n * Conditional policies to deny flags. The flags are also hidden\n * from rendered help, so hosts are never told about surface they cannot use.\n */\nexport function conditionalDenyFlags(...names: string[]): ConditionalInvocationPolicy {\n return {\n deniedFlags: names,\n kind: 'conditional',\n validate: ({flags}) =>\n names.every((name) => flags[name] === undefined || flags[name] === false),\n }\n}\n\n/**\n * Conditional policy combining {@link conditionalDenyFlags} with an extra\n * predicate on the parsed invocation, for conditions a flag name alone\n * cannot express — e.g. flag values that would read from the host machine.\n * `deniedFlags` are hidden from rendered help; the predicate is not\n * expressible there, so flags it constrains stay advertised.\n */\nexport function conditionalPolicy(options: {\n deniedFlags?: string[]\n validate: InvocationPolicy\n}): ConditionalInvocationPolicy {\n const denyFlags = conditionalDenyFlags(...(options.deniedFlags ?? []))\n return {\n ...denyFlags,\n validate: (invocation) => denyFlags.validate(invocation) && options.validate(invocation),\n }\n}\n\nexport function isConditionalInvocationPolicy(\n policy: CommandPolicy,\n): policy is ConditionalInvocationPolicy {\n return policy.kind === 'conditional'\n}\n\n/** A complete policy table, keyed by oclif command id. */\nexport type CommandPolicySet = Readonly<Record<string, CommandPolicy>>\n\n/** Where an invocation originates; selects the policy to enforce. */\nexport type InvocationSource = 'mcp'\n"],"names":["allow","kind","validate","deny","conditionalDenyFlags","names","deniedFlags","flags","every","name","undefined","conditionalPolicy","options","denyFlags","invocation","isConditionalInvocationPolicy","policy"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,6EAA6E,GAuB7E,mDAAmD,GACnD,OAAO,MAAMA,QAAuB;IAACC,MAAM;IAASC,UAAU,IAAM;AAAI,EAAC;AAEzE,2EAA2E,GAC3E,OAAO,MAAMC,OAAsB;IAACF,MAAM;IAAQC,UAAU,IAAM;AAAK,EAAC;AAExE;;;CAGC,GACD,OAAO,SAASE,qBAAqB,GAAGC,KAAe;IACrD,OAAO;QACLC,aAAaD;QACbJ,MAAM;QACNC,UAAU,CAAC,EAACK,KAAK,EAAC,GAChBF,MAAMG,KAAK,CAAC,CAACC,OAASF,KAAK,CAACE,KAAK,KAAKC,aAAaH,KAAK,CAACE,KAAK,KAAK;IACvE;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASE,kBAAkBC,OAGjC;IACC,MAAMC,YAAYT,wBAAyBQ,QAAQN,WAAW,IAAI,EAAE;IACpE,OAAO;QACL,GAAGO,SAAS;QACZX,UAAU,CAACY,aAAeD,UAAUX,QAAQ,CAACY,eAAeF,QAAQV,QAAQ,CAACY;IAC/E;AACF;AAEA,OAAO,SAASC,8BACdC,MAAqB;IAErB,OAAOA,OAAOf,IAAI,KAAK;AACzB"}
@@ -0,0 +1,146 @@
1
+ import { Help } from '@oclif/core';
2
+ import { getHelpFlagAdditions } from '@oclif/core/help';
3
+ import { isConditionalInvocationPolicy } from './commandPolicies/policy.js';
4
+ /** Command ids a policy exposes: entries that are not denied. */ function visibleCommandIds(policySet) {
5
+ return new Set(Object.entries(policySet).filter(([, policy])=>policy.kind !== 'deny').map(([id])=>id));
6
+ }
7
+ /** Topic names covering the visible commands: every prefix of every id. */ function visibleTopicNames(commandIds) {
8
+ const names = new Set();
9
+ for (const id of commandIds){
10
+ const parts = id.split(':');
11
+ for(let length = 1; length < parts.length; length++){
12
+ names.add(parts.slice(0, length).join(':'));
13
+ }
14
+ }
15
+ return names;
16
+ }
17
+ /** Thrown when help is requested for a subject outside the policy surface. */ class NotInvokableError extends Error {
18
+ }
19
+ /**
20
+ * A copy of `command` without the policy's denied flags, and without examples
21
+ * that use them (under any spelling: `--web`, `--w`, `-w`), so rendered help
22
+ * only advertises invocations the policy accepts.
23
+ */ function withoutDeniedFlags(command, policy) {
24
+ if (!policy || !isConditionalInvocationPolicy(policy)) return {
25
+ ...command
26
+ };
27
+ const denied = policy.deniedFlags;
28
+ if (denied.length === 0) return {
29
+ ...command
30
+ };
31
+ const flags = {
32
+ ...command.flags
33
+ };
34
+ const spellings = [];
35
+ for (const name of denied){
36
+ const definition = flags[name];
37
+ if (!definition) continue;
38
+ spellings.push(`--${name}`);
39
+ if (definition.char) spellings.push(`-${definition.char}`);
40
+ for (const alias of definition.aliases ?? [])spellings.push(`--${alias}`, `-${alias}`);
41
+ delete flags[name];
42
+ }
43
+ const usesDeniedFlag = (example)=>{
44
+ const text = typeof example === 'string' ? example : example.command;
45
+ return spellings.some((spelling)=>new RegExp(String.raw`(^|\s)${spelling}(=|\s|$)`).test(text ?? ''));
46
+ };
47
+ return {
48
+ ...command,
49
+ examples: command.examples?.filter((example)=>!usesDeniedFlag(example)),
50
+ flags
51
+ };
52
+ }
53
+ /**
54
+ * oclif help renderer scoped to a policy's command surface. Subject
55
+ * resolution (root vs topic vs command help) is oclif's own; the policy is
56
+ * enforced at the rendering entry points so the rest of the CLI stays
57
+ * invisible to embedding hosts, and listings are filtered to non-denied
58
+ * commands and their topics only.
59
+ *
60
+ * Output is collected in {@link InvokableHelp.lines} instead of being written
61
+ * to the process streams.
62
+ */ class InvokableHelp extends Help {
63
+ lines = [];
64
+ commandIds;
65
+ policySet;
66
+ topicNames;
67
+ constructor(config, policySet){
68
+ super(config, {
69
+ stripAnsi: true
70
+ });
71
+ this.policySet = policySet;
72
+ this.commandIds = visibleCommandIds(policySet);
73
+ this.topicNames = visibleTopicNames(this.commandIds);
74
+ }
75
+ // The copies below are load-bearing: oclif's formatters rewrite ids/names
76
+ // in place (`cors:list` → `cors list`). Without copies those writes corrupt
77
+ // the shared (cached) config, breaking the policy checks on subsequent
78
+ // invocations.
79
+ get sortedCommands() {
80
+ return super.sortedCommands.filter((command)=>this.commandIds.has(command.id)).map((command)=>({
81
+ ...command
82
+ }));
83
+ }
84
+ get sortedTopics() {
85
+ // Topic names and descriptions come from the oclif config (oclif.config.js)
86
+ return super.sortedTopics.filter((topic)=>this.topicNames.has(topic.name)).map((topic)=>({
87
+ ...topic
88
+ }));
89
+ }
90
+ log(...args) {
91
+ this.lines.push(...args);
92
+ }
93
+ async showCommandHelp(command) {
94
+ if (!this.commandIds.has(command.id)) throw new NotInvokableError(command.id);
95
+ return super.showCommandHelp(withoutDeniedFlags(command, this.policySet[command.id]));
96
+ }
97
+ async showTopicHelp(topic) {
98
+ if (!this.topicNames.has(topic.name)) throw new NotInvokableError(topic.name);
99
+ return super.showTopicHelp({
100
+ ...topic
101
+ });
102
+ }
103
+ }
104
+ /**
105
+ * Render help text for a policy's command surface: root help for a bare help
106
+ * request, or topic/command help when `argv` names a subject (e.g.
107
+ * `['cors', '--help']`), exactly as oclif would resolve it. ANSI styling is
108
+ * stripped so programmatic callers get plain text.
109
+ *
110
+ * Returns `undefined` when the subject is unknown or denied — callers should
111
+ * respond the same way as for an unknown command, so hosts cannot probe the
112
+ * full CLI surface through help.
113
+ *
114
+ * @internal
115
+ */ export async function renderInvokableHelp(config, argv, policySet) {
116
+ const help = new InvokableHelp(config, policySet);
117
+ try {
118
+ await help.showHelp(argv);
119
+ } catch (err) {
120
+ // Subjects outside the policy surface (NotInvokableError) and subjects
121
+ // oclif itself cannot resolve (CLIError, marked with an `oclif` property)
122
+ // both yield no help output.
123
+ if (err instanceof NotInvokableError || err.oclif) return undefined;
124
+ throw err;
125
+ }
126
+ return help.lines.join('\n').trimEnd();
127
+ }
128
+ /**
129
+ * Whether `argv` asks for help rather than a command invocation: a leading
130
+ * `help` (oclif's help command), or a recognized help flag before any `--`
131
+ * terminator. The flags come from {@link getHelpFlagAdditions} — the same
132
+ * source oclif's own dispatch consults — so this surface recognizes exactly
133
+ * what the regular CLI recognizes.
134
+ *
135
+ * @internal
136
+ */ export function isHelpRequest(argv, config) {
137
+ if (argv[0] === 'help') return true;
138
+ const helpFlags = getHelpFlagAdditions(config);
139
+ for (const token of argv){
140
+ if (token === '--') return false;
141
+ if (helpFlags.includes(token)) return true;
142
+ }
143
+ return false;
144
+ }
145
+
146
+ //# sourceMappingURL=help.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/exports/invokeSanityCli/help.ts"],"sourcesContent":["import {type Command, type Config, Help, type Interfaces} from '@oclif/core'\nimport {getHelpFlagAdditions} from '@oclif/core/help'\n\nimport {\n type CommandPolicy,\n type CommandPolicySet,\n isConditionalInvocationPolicy,\n} from './commandPolicies/policy.js'\n\n/** Command ids a policy exposes: entries that are not denied. */\nfunction visibleCommandIds(policySet: CommandPolicySet): Set<string> {\n return new Set(\n Object.entries(policySet)\n .filter(([, policy]) => policy.kind !== 'deny')\n .map(([id]) => id),\n )\n}\n\n/** Topic names covering the visible commands: every prefix of every id. */\nfunction visibleTopicNames(commandIds: Set<string>): Set<string> {\n const names = new Set<string>()\n for (const id of commandIds) {\n const parts = id.split(':')\n for (let length = 1; length < parts.length; length++) {\n names.add(parts.slice(0, length).join(':'))\n }\n }\n return names\n}\n\n/** Thrown when help is requested for a subject outside the policy surface. */\nclass NotInvokableError extends Error {}\n\n/**\n * A copy of `command` without the policy's denied flags, and without examples\n * that use them (under any spelling: `--web`, `--w`, `-w`), so rendered help\n * only advertises invocations the policy accepts.\n */\nfunction withoutDeniedFlags(command: Command.Loadable, policy?: CommandPolicy): Command.Loadable {\n if (!policy || !isConditionalInvocationPolicy(policy)) return {...command}\n\n const denied = policy.deniedFlags\n if (denied.length === 0) return {...command}\n\n const flags = {...command.flags}\n const spellings: string[] = []\n for (const name of denied) {\n const definition = flags[name]\n if (!definition) continue\n spellings.push(`--${name}`)\n if (definition.char) spellings.push(`-${definition.char}`)\n for (const alias of definition.aliases ?? []) spellings.push(`--${alias}`, `-${alias}`)\n delete flags[name]\n }\n\n const usesDeniedFlag = (example: Command.Example) => {\n const text = typeof example === 'string' ? example : example.command\n return spellings.some((spelling) =>\n new RegExp(String.raw`(^|\\s)${spelling}(=|\\s|$)`).test(text ?? ''),\n )\n }\n\n return {\n ...command,\n examples: command.examples?.filter((example) => !usesDeniedFlag(example)),\n flags,\n }\n}\n\n/**\n * oclif help renderer scoped to a policy's command surface. Subject\n * resolution (root vs topic vs command help) is oclif's own; the policy is\n * enforced at the rendering entry points so the rest of the CLI stays\n * invisible to embedding hosts, and listings are filtered to non-denied\n * commands and their topics only.\n *\n * Output is collected in {@link InvokableHelp.lines} instead of being written\n * to the process streams.\n */\nclass InvokableHelp extends Help {\n public readonly lines: string[] = []\n\n private readonly commandIds: Set<string>\n private readonly policySet: CommandPolicySet\n private readonly topicNames: Set<string>\n\n constructor(config: Config, policySet: CommandPolicySet) {\n super(config, {stripAnsi: true})\n this.policySet = policySet\n this.commandIds = visibleCommandIds(policySet)\n this.topicNames = visibleTopicNames(this.commandIds)\n }\n\n // The copies below are load-bearing: oclif's formatters rewrite ids/names\n // in place (`cors:list` → `cors list`). Without copies those writes corrupt\n // the shared (cached) config, breaking the policy checks on subsequent\n // invocations.\n\n protected override get sortedCommands(): Command.Loadable[] {\n return super.sortedCommands\n .filter((command) => this.commandIds.has(command.id))\n .map((command) => ({...command}))\n }\n\n protected override get sortedTopics(): Interfaces.Topic[] {\n // Topic names and descriptions come from the oclif config (oclif.config.js)\n return super.sortedTopics\n .filter((topic) => this.topicNames.has(topic.name))\n .map((topic) => ({...topic}))\n }\n\n protected override log(...args: string[]): void {\n this.lines.push(...args)\n }\n\n public override async showCommandHelp(command: Command.Loadable): Promise<void> {\n if (!this.commandIds.has(command.id)) throw new NotInvokableError(command.id)\n return super.showCommandHelp(withoutDeniedFlags(command, this.policySet[command.id]))\n }\n\n protected override async showTopicHelp(topic: Interfaces.Topic): Promise<void> {\n if (!this.topicNames.has(topic.name)) throw new NotInvokableError(topic.name)\n return super.showTopicHelp({...topic})\n }\n}\n\n/**\n * Render help text for a policy's command surface: root help for a bare help\n * request, or topic/command help when `argv` names a subject (e.g.\n * `['cors', '--help']`), exactly as oclif would resolve it. ANSI styling is\n * stripped so programmatic callers get plain text.\n *\n * Returns `undefined` when the subject is unknown or denied — callers should\n * respond the same way as for an unknown command, so hosts cannot probe the\n * full CLI surface through help.\n *\n * @internal\n */\nexport async function renderInvokableHelp(\n config: Config,\n argv: string[],\n policySet: CommandPolicySet,\n): Promise<string | undefined> {\n const help = new InvokableHelp(config, policySet)\n try {\n await help.showHelp(argv)\n } catch (err) {\n // Subjects outside the policy surface (NotInvokableError) and subjects\n // oclif itself cannot resolve (CLIError, marked with an `oclif` property)\n // both yield no help output.\n if (err instanceof NotInvokableError || err.oclif) return undefined\n throw err\n }\n return help.lines.join('\\n').trimEnd()\n}\n\n/**\n * Whether `argv` asks for help rather than a command invocation: a leading\n * `help` (oclif's help command), or a recognized help flag before any `--`\n * terminator. The flags come from {@link getHelpFlagAdditions} — the same\n * source oclif's own dispatch consults — so this surface recognizes exactly\n * what the regular CLI recognizes.\n *\n * @internal\n */\nexport function isHelpRequest(argv: string[], config: Config): boolean {\n if (argv[0] === 'help') return true\n const helpFlags = getHelpFlagAdditions(config)\n for (const token of argv) {\n if (token === '--') return false\n if (helpFlags.includes(token)) return true\n }\n return false\n}\n"],"names":["Help","getHelpFlagAdditions","isConditionalInvocationPolicy","visibleCommandIds","policySet","Set","Object","entries","filter","policy","kind","map","id","visibleTopicNames","commandIds","names","parts","split","length","add","slice","join","NotInvokableError","Error","withoutDeniedFlags","command","denied","deniedFlags","flags","spellings","name","definition","push","char","alias","aliases","usesDeniedFlag","example","text","some","spelling","RegExp","String","raw","test","examples","InvokableHelp","lines","topicNames","config","stripAnsi","sortedCommands","has","sortedTopics","topic","log","args","showCommandHelp","showTopicHelp","renderInvokableHelp","argv","help","showHelp","err","oclif","undefined","trimEnd","isHelpRequest","helpFlags","token","includes"],"mappings":"AAAA,SAAmCA,IAAI,QAAwB,cAAa;AAC5E,SAAQC,oBAAoB,QAAO,mBAAkB;AAErD,SAGEC,6BAA6B,QACxB,8BAA6B;AAEpC,+DAA+D,GAC/D,SAASC,kBAAkBC,SAA2B;IACpD,OAAO,IAAIC,IACTC,OAAOC,OAAO,CAACH,WACZI,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,QACvCC,GAAG,CAAC,CAAC,CAACC,GAAG,GAAKA;AAErB;AAEA,yEAAyE,GACzE,SAASC,kBAAkBC,UAAuB;IAChD,MAAMC,QAAQ,IAAIV;IAClB,KAAK,MAAMO,MAAME,WAAY;QAC3B,MAAME,QAAQJ,GAAGK,KAAK,CAAC;QACvB,IAAK,IAAIC,SAAS,GAAGA,SAASF,MAAME,MAAM,EAAEA,SAAU;YACpDH,MAAMI,GAAG,CAACH,MAAMI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AAU,CAACI,GAAG,CAACE,MAAMxB,IAAI,GAAG,MAAM,IAAIR,kBAAkBgC,MAAMxB,IAAI;QAC5E,OAAO,KAAK,CAAC4B,cAAc;YAAC,GAAGJ,KAAK;QAAA;IACtC;AACF;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeK,oBACpBV,MAAc,EACdW,IAAc,EACdxD,SAA2B;IAE3B,MAAMyD,OAAO,IAAIf,cAAcG,QAAQ7C;IACvC,IAAI;QACF,MAAMyD,KAAKC,QAAQ,CAACF;IACtB,EAAE,OAAOG,KAAK;QACZ,uEAAuE;QACvE,0EAA0E;QAC1E,6BAA6B;QAC7B,IAAIA,eAAezC,qBAAqByC,IAAIC,KAAK,EAAE,OAAOC;QAC1D,MAAMF;IACR;IACA,OAAOF,KAAKd,KAAK,CAAC1B,IAAI,CAAC,MAAM6C,OAAO;AACtC;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcP,IAAc,EAAEX,MAAc;IAC1D,IAAIW,IAAI,CAAC,EAAE,KAAK,QAAQ,OAAO;IAC/B,MAAMQ,YAAYnE,qBAAqBgD;IACvC,KAAK,MAAMoB,SAAST,KAAM;QACxB,IAAIS,UAAU,MAAM,OAAO;QAC3B,IAAID,UAAUE,QAAQ,CAACD,QAAQ,OAAO;IACxC;IACA,OAAO;AACT"}
@@ -0,0 +1,60 @@
1
+ import { Config } from "@oclif/core";
2
+
3
+ /** Where an invocation originates; selects the policy to enforce. */
4
+ declare type InvocationSource = "mcp";
5
+
6
+ /**
7
+ * Run a policy-permitted CLI command in-process and capture its result.
8
+ *
9
+ * Command-level failures (unknown command, bad flags, API errors) are
10
+ * reported through `exitCode`/`output` rather than thrown, so callers can
11
+ * relay them verbatim.
12
+ *
13
+ * @internal
14
+ */
15
+ export declare function invokeSanityCli({
16
+ args,
17
+ config,
18
+ source,
19
+ token,
20
+ }: InvokeSanityCliOptions): Promise<InvokeSanityCliResult>;
21
+
22
+ /**
23
+ * @internal
24
+ */
25
+ export declare interface InvokeSanityCliOptions {
26
+ /**
27
+ * Arguments after `sanity` (a leading `sanity` token is tolerated), either
28
+ * as a single string — shell-style quoting is supported, but no shell is
29
+ * ever executed — or as a pre-split argv array.
30
+ */
31
+ args: string | string[];
32
+ /**
33
+ * Where this invocation originates. Selects the command policy to enforce:
34
+ * which commands are invokable and which invocations of them are permitted.
35
+ */
36
+ source: InvocationSource;
37
+ /**
38
+ * Auth token for this invocation. Scoped to this call via the CLI execution
39
+ * context: it never touches process env or the process-wide token cache, so
40
+ * concurrent invocations with different tokens are fully isolated.
41
+ */
42
+ token: string;
43
+ /**
44
+ * Optional oclif config override (mainly for tests). Defaults to this
45
+ * package's config, loaded once and cached across invocations.
46
+ */
47
+ config?: Config;
48
+ }
49
+
50
+ /**
51
+ * @internal
52
+ */
53
+ export declare interface InvokeSanityCliResult {
54
+ /** `0` on success, the command's exit code otherwise. */
55
+ exitCode: number;
56
+ /** Combined stdout and stderr output, in emission order. */
57
+ output: string;
58
+ }
59
+
60
+ export {};
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Programmatic (in-process) invocation of CLI commands, e.g. from an MCP
3
+ * server. The invokable surface is governed by a per-source command policy
4
+ * (see ./commandPolicies): every CLI command is explicitly allowed, denied,
5
+ * or allowed conditionally on the parsed invocation.
6
+ *
7
+ * {@link invokeSanityCli} handles arg parsing, policy enforcement, command
8
+ * dispatch, per-invocation auth, and output capture.
9
+ * ```ts
10
+ * import {invokeSanityCli} from '@sanity/cli/invokeSanityCli'
11
+ *
12
+ * const {exitCode, output} = await invokeSanityCli({
13
+ * args: 'cors list --project-id abc123',
14
+ * source: 'mcp',
15
+ * token: extra.authInfo.token,
16
+ * })
17
+ * ```
18
+ *
19
+ * Help works like the regular CLI, scoped to the source's policy: `--help`
20
+ * (or `help`) renders root help listing the invokable topics, and a subject
21
+ * (`cors --help`, `cors list --help`) renders topic or command help.
22
+ */ import { Config, Parser } from '@oclif/core';
23
+ import { getHelpFlagAdditions, normalizeArgv } from '@oclif/core/help';
24
+ import { CLI_TELEMETRY_SYMBOL, exitCodes, noopLogger, setCliTelemetry } from '@sanity/cli-core';
25
+ import { runWithCliExecutionContext } from '@sanity/cli-core/executionContext';
26
+ import { parseArgsStringToArgv } from 'string-argv';
27
+ import { commandPolicies } from './commandPolicies/index.js';
28
+ import { deny, isConditionalInvocationPolicy } from './commandPolicies/policy.js';
29
+ import { isHelpRequest, renderInvokableHelp } from './help.js';
30
+ /**
31
+ * Load the oclif `Config` for this package, needed to resolve, load, and run
32
+ * commands. Loading it once and reusing it across invocations avoids
33
+ * re-reading the command manifest per call.
34
+ */ function loadCliCommandConfig() {
35
+ return Config.load(import.meta.url);
36
+ }
37
+ function unknownCommandResult(argv, policySet) {
38
+ const available = Object.entries(policySet).filter(([, policy])=>policy.kind !== 'deny').map(([id])=>id.replaceAll(':', ' ')).toSorted();
39
+ return {
40
+ exitCode: exitCodes.USAGE_ERROR,
41
+ output: [
42
+ `Unknown or unsupported command: ${argv.slice(0, 2).join(' ') || '(none)'}`,
43
+ `Available commands: ${available.join(', ')}`
44
+ ].join('\n')
45
+ };
46
+ }
47
+ let cachedConfig;
48
+ /**
49
+ * Unlike a shell, string-argv keeps quotes that are glued to unquoted text:
50
+ * `--name="my project"` tokenizes with the quotes intact. Strip a matching
51
+ * wrapping quote pair from the value side of `--flag=`-shaped tokens so the
52
+ * common shell-style form yields the value the caller intended.
53
+ */ function stripFlagQuotes(rawToken) {
54
+ const match = /^(-{1,2}[^\s=]+=)(['"])([\s\S]*)\2$/.exec(rawToken);
55
+ return match ? match[1] + match[3] : rawToken;
56
+ }
57
+ /**
58
+ * Run a policy-permitted CLI command in-process and capture its result.
59
+ *
60
+ * Command-level failures (unknown command, bad flags, API errors) are
61
+ * reported through `exitCode`/`output` rather than thrown, so callers can
62
+ * relay them verbatim.
63
+ *
64
+ * @internal
65
+ */ export async function invokeSanityCli({ args, config, source, token }) {
66
+ const resolvedConfig = config ?? await (cachedConfig ??= loadCliCommandConfig());
67
+ const policySet = commandPolicies[source];
68
+ // Commands log through the global telemetry store; default it to a noop
69
+ // store so embedding hosts need no telemetry wiring (and see no warnings),
70
+ // without clobbering a store the host may have installed itself.
71
+ if (!globalThis[CLI_TELEMETRY_SYMBOL]) {
72
+ setCliTelemetry(noopLogger);
73
+ }
74
+ // Pre-split argv arrays are taken verbatim; only string input goes through
75
+ // shell-style tokenization and quote normalization.
76
+ let argv = typeof args === 'string' ? parseArgsStringToArgv(args).map((t)=>stripFlagQuotes(t)) : [
77
+ ...args
78
+ ];
79
+ if (argv[0] === 'sanity') argv = argv.slice(1);
80
+ // Help requests are routed through oclif's help system, scoped to the
81
+ // source's policy: root help for a bare request, topic/command help when a
82
+ // subject is given. Denied subjects get the standard unknown-command
83
+ // response (identical to a truly unknown command, so hosts can't probe the
84
+ // full CLI surface through help), and a help request never executes a
85
+ // command.
86
+ if (isHelpRequest(argv, resolvedConfig)) {
87
+ try {
88
+ // Drop a leading `help` so the rest is the subject, mirroring how
89
+ // oclif's dispatch consumes the token before the help command sees argv
90
+ const helpArgv = argv[0] === 'help' ? argv.slice(1) : argv;
91
+ const output = await renderInvokableHelp(resolvedConfig, helpArgv, policySet);
92
+ if (output !== undefined) return {
93
+ exitCode: exitCodes.SUCCESS,
94
+ output
95
+ };
96
+ const helpFlags = getHelpFlagAdditions(resolvedConfig);
97
+ return unknownCommandResult(helpArgv.filter((token)=>!helpFlags.includes(token)), policySet);
98
+ } catch (err) {
99
+ return {
100
+ exitCode: exitCodes.RUNTIME_ERROR,
101
+ output: err instanceof Error ? err.message : String(err)
102
+ };
103
+ }
104
+ }
105
+ // Resolve the command id the same way oclif's dispatch would (collating
106
+ // space-separated topics, accepting colon-separated ids as-is), then apply
107
+ // the policy. Denied and uncategorized ids fail closed, indistinguishable
108
+ // from commands that don't exist.
109
+ const [commandId = '', ...commandArgv] = normalizeArgv(resolvedConfig, argv);
110
+ const policy = policySet[commandId] ?? deny;
111
+ const commandDefinition = policy.kind === 'deny' ? undefined : resolvedConfig.findCommand(commandId);
112
+ if (!commandDefinition) return unknownCommandResult(argv, policySet);
113
+ const CommandClass = await commandDefinition.load();
114
+ // Parse with the command's real definitions (without executing anything) so
115
+ // conditional policies are evaluated against typed args/flags, not tokens.
116
+ let invocation;
117
+ try {
118
+ const parsed = await Parser.parse(commandArgv, {
119
+ args: CommandClass.args,
120
+ baseFlags: CommandClass.baseFlags,
121
+ enableJsonFlag: CommandClass.enableJsonFlag,
122
+ flags: CommandClass.flags,
123
+ strict: CommandClass.strict
124
+ });
125
+ invocation = {
126
+ args: parsed.args,
127
+ flags: parsed.flags
128
+ };
129
+ } catch (err) {
130
+ return {
131
+ exitCode: exitCodes.USAGE_ERROR,
132
+ output: err instanceof Error ? err.message : String(err)
133
+ };
134
+ }
135
+ if (!policy.validate(invocation)) {
136
+ const displayId = commandId.replaceAll(':', ' ');
137
+ let output = `This invocation of \`${displayId}\` is not supported here`;
138
+ if (isConditionalInvocationPolicy(policy)) {
139
+ const usedDeniedFlags = policy.deniedFlags.filter((name)=>invocation.flags[name] !== undefined && invocation.flags[name] !== false);
140
+ output = `\nThe ${usedDeniedFlags.map((name)=>`--${name}`).join(', ')} flag is not supported here for \`${displayId}\``;
141
+ }
142
+ return {
143
+ exitCode: exitCodes.USAGE_ERROR,
144
+ output
145
+ };
146
+ }
147
+ const output = [];
148
+ const sink = (line)=>output.push(line);
149
+ try {
150
+ await runWithCliExecutionContext({
151
+ stderr: sink,
152
+ stdout: sink,
153
+ token
154
+ }, ()=>CommandClass.run(commandArgv, resolvedConfig));
155
+ return {
156
+ exitCode: exitCodes.SUCCESS,
157
+ output: output.join('\n')
158
+ };
159
+ } catch (err) {
160
+ const exit = err.oclif?.exit;
161
+ // `this.exit(0)` throws an ExitError but is a successful outcome
162
+ if (exit === exitCodes.SUCCESS) {
163
+ return {
164
+ exitCode: exitCodes.SUCCESS,
165
+ output: output.join('\n')
166
+ };
167
+ }
168
+ const message = err instanceof Error ? err.message : String(err);
169
+ if (message) output.push(message);
170
+ return {
171
+ exitCode: typeof exit === 'number' ? exit : exitCodes.RUNTIME_ERROR,
172
+ output: output.join('\n')
173
+ };
174
+ }
175
+ }
176
+
177
+ //# sourceMappingURL=index.js.map