@sanity/cli-core 3.5.0 → 3.6.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.
@@ -35,7 +35,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
35
35
  *
36
36
  * @deprecated use `getGlobalCliClient` function directly instead.
37
37
  */
38
- protected getGlobalApiClient: (args: GlobalCliClientOptions) => Promise<import("@sanity/client").SanityClient>;
38
+ protected getGlobalApiClient: (args: GlobalCliClientOptions) => Promise<import("sanity").SanityClient>;
39
39
  /**
40
40
  * Get the project API client.
41
41
  *
@@ -44,7 +44,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
44
44
  *
45
45
  * @deprecated use `getProjectCliClient` function directly instead.
46
46
  */
47
- protected getProjectApiClient: (args: ProjectCliClientOptions) => Promise<import("@sanity/client").SanityClient>;
47
+ protected getProjectApiClient: (args: ProjectCliClientOptions) => Promise<import("sanity").SanityClient>;
48
48
  /**
49
49
  * Helper for outputting to the console.
50
50
  *
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable
3
+ * timestamps are returned as-is, so a bad value from the API doesn't fail the command.
4
+ *
5
+ * @param timestamp - An ISO 8601 timestamp
6
+ * @internal
7
+ */
8
+ declare function formatDateTime(timestamp: string): string;
9
+ /**
10
+ * Formats a duration in milliseconds as an approximate, human readable length of
11
+ * time, eg `less than a minute`, `5 minutes` or `2 days`.
12
+ *
13
+ * @param ms - The duration in milliseconds
14
+ * @internal
15
+ */
16
+ declare function formatDuration(ms: number): string;
17
+ /**
18
+ * Formats a date relative to now, eg `2 days ago` or `in 3 hours`.
19
+ *
20
+ * @param date - The date to describe
21
+ * @param now - The reference point to compare against, defaults to the current time
22
+ * @internal
23
+ */
24
+ declare function formatTimeAgo(date: Date, now?: number): string;
25
+ /**
26
+ * Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`
27
+ * for anything that isn't a real calendar date in that exact format.
28
+ *
29
+ * @param value - The date string to parse
30
+ * @internal
31
+ */
32
+ declare function parseDateOnly(value: string): Date | undefined;
33
+ export { formatDateTime, formatDuration, formatTimeAgo, parseDateOnly };
34
+ //# sourceMappingURL=dates.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { formatDateTime, formatDuration, formatTimeAgo, parseDateOnly } from '../util/dates.js';
2
+
3
+ //# sourceMappingURL=dates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/_exports/dates.ts"],"sourcesContent":["export {formatDateTime, formatDuration, formatTimeAgo, parseDateOnly} from '../util/dates.js'\n"],"names":["formatDateTime","formatDuration","formatTimeAgo","parseDateOnly"],"mappings":"AAAA,SAAQA,cAAc,EAAEC,cAAc,EAAEC,aAAa,EAAEC,aAAa,QAAO,mBAAkB"}
@@ -37,6 +37,7 @@ const debug = subdebug('worker:getStudioWorkspaces');
37
37
  }
38
38
  const workDir = dirname(configPath);
39
39
  debug('Work dir %s', workDir);
40
+ // @ts-expect-error - resolveConfig is type-only in sanity@6.11.0; fixed in the next sanity release
40
41
  const { resolveConfig } = await resolveLocalPackage('sanity', workDir);
41
42
  if (typeof resolveConfig !== 'function') {
42
43
  throw new TypeError('Expected `resolveConfig` from `sanity` to be a function');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const emptyAuth = {state: of(getEmptyAuth())}\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: emptyAuth,\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","emptyAuth","state","unauthedWorkspaces","map","workspace","auth"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY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AACC,OAAOvB,GAAGG;IAAe;IAE5C,MAAMqB,qBAAqBP,cAAcQ,GAAG,CAAC,CAACC,YAAe,CAAA;YAC3D,GAAGA,SAAS;YACZC,MAAML;QACR,CAAA;IAEAf,MAAM,0BAA0BiB;IAEhC,OAAOzB,eAAeiB,cAAcQ;AACtC"}
1
+ {"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n // @ts-expect-error - resolveConfig is type-only in sanity@6.11.0; fixed in the next sanity release\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const emptyAuth = {state: of(getEmptyAuth())}\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: emptyAuth,\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","emptyAuth","state","unauthedWorkspaces","map","workspace","auth"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,QAAQN,SAAS;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeO,oBAAoBC,UAAkB;IAC1D,IAAIX,cAAc;QAChB,MAAM,IAAIY,MAAM;IAClB;IACA,MAAMC,cAAc,AAAC,CAAA,MAAMf,KAAKa,WAAU,EAAGE,WAAW;IACxD,IAAIA,aAAa;QACfF,aAAa,MAAMJ,qBAAqBI;IAC1C;IACAF,MAAM,iCAAiCE;IACvC,IAAIG,SAAS,MAAMV,SAASO;IAE5BF,MAAM,sBAAsBK;IAC5B,IAAI,CAACN,eAAeM,SAAS;QAC3B,IAAI,CAAE,CAAA,aAAaA,MAAK,KAAM,CAACN,eAAeM,OAAOC,OAAO,GAAG;YAC7DN,MAAM,wCAAwCE;YAC9C,MAAM,IAAIK,UAAU,CAAC,iCAAiC,EAAEL,WAAW,CAAC,CAAC;QACvE;QAEAG,SAASA,OAAOC,OAAO;IACzB;IAEA,MAAME,UAAUlB,QAAQY;IACxBF,MAAM,eAAeQ;IACrB,mGAAmG;IACnG,MAAM,EAACC,aAAa,EAAC,GAAG,MAAMZ,oBAA6C,UAAUW;IACrF,IAAI,OAAOC,kBAAkB,YAAY;QACvC,MAAM,IAAIF,UAAU;IACtB;IAEA,kFAAkF;IAClF,mFAAmF;IACnF,MAAMG,gBAAgBC,MAAMC,OAAO,CAACP,UAChCA,SACA;QAAC;YAAC,GAAGA,MAAM;YAAEQ,UAAUR,OAAOQ,QAAQ,IAAI;YAAKC,MAAMT,OAAOS,IAAI,IAAI;QAAS;KAAE;IAEnF,MAAMC,YAAY;QAACC,OAAOvB,GAAGG;IAAe;IAE5C,MAAMqB,qBAAqBP,cAAcQ,GAAG,CAAC,CAACC,YAAe,CAAA;YAC3D,GAAGA,SAAS;YACZC,MAAML;QACR,CAAA;IAEAf,MAAM,0BAA0BiB;IAEhC,OAAOzB,eAAeiB,cAAcQ;AACtC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\n\nimport {up as packageUp} from 'empathic/package'\nimport {\n createRequester as createGetItRequester,\n type FetchHeaders,\n type RequesterOptions,\n type RequestFunction,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {debug as debugMiddleware} from 'get-it/middleware'\nimport {createDebug} from 'obug'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for creating a Sanity CLI requester.\n *\n * Extends get-it v9's {@link RequesterOptions} with Sanity CLI defaults for\n * User-Agent headers and debug logging.\n *\n * @public\n */\nexport type CreateRequesterOptions = Omit<RequesterOptions, 'headers'> & {\n /**\n * Debug logging middleware. Defaults to enabled with namespace `sanity:cli`.\n * Pass `false` to disable.\n */\n debug?: false | {namespace?: string; verbose?: boolean}\n /**\n * Default headers for all requests.\n * Omitting uses a lazy User-Agent of `@sanity/cli-core@<version>`.\n * Pass `false` to send no default headers.\n */\n headers?: false | Record<string, string>\n}\n\n/**\n * Creates a get-it requester with Sanity CLI defaults.\n *\n * Defaults:\n * - User-Agent header: `@sanity/cli-core@<version>` (lazy)\n * - Debug logging via `DEBUG=sanity:cli` (verbose)\n * - HTTP error throwing on (get-it default)\n *\n * @param options - Optional configuration to customize or disable defaults\n * @returns A configured get-it request function\n * @public\n */\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'json'},\n): RequestFunction<'json'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'text'},\n): RequestFunction<'text'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'stream'},\n): RequestFunction<'stream'>\nexport function createRequester(options?: CreateRequesterOptions): RequestFunction\nexport function createRequester(\n options?: CreateRequesterOptions,\n): RequestFunction<'json' | 'stream' | 'text' | undefined> {\n const {debug, headers, middleware = [], ...getItOptions} = options ?? {}\n\n // A programmatic invocation must not inherit the embedding process's DEBUG setting or write request/response bodies outside its output sinks.\n const resolvedMiddleware: Array<TransformMiddleware | WrappingMiddleware> = [...middleware]\n if (!getCliExecutionContext() && debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof debug === 'object' ? debug : {}\n const {namespace, verbose} = {...debugDefaults, ...customDebug}\n resolvedMiddleware.push(debugMiddleware({log: createDebug(namespace), verbose}))\n }\n\n return createGetItRequester({\n ...getItOptions,\n headers: resolveDefaultHeaders(headers),\n middleware: resolvedMiddleware,\n })\n}\n\n/**\n * Builds default headers, including a lazy User-Agent unless overridden or disabled.\n *\n * @internal\n */\nfunction resolveDefaultHeaders(\n headers: false | Record<string, string> | undefined,\n): FetchHeaders | undefined {\n if (headers === false) {\n return undefined\n }\n\n const customHeaders = typeof headers === 'object' ? headers : {}\n if (Object.keys(customHeaders).some((header) => header.toLowerCase() === 'user-agent')) {\n return customHeaders\n }\n\n return {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n}\n\n/**\n * Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.\n *\n * @returns The name and version of the package\n * @internal\n */\nfunction getPackageInfo(): {name: string; version: string} {\n if (cachedPkg) return cachedPkg\n\n const pkgPath = packageUp({cwd: import.meta.dirname})\n if (!pkgPath) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n const packageJson = JSON.parse(readFileSync(pkgPath, 'utf8'))\n cachedPkg = {\n name: packageJson.name ?? '@sanity/cli-core',\n version: packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["readFileSync","up","packageUp","createRequester","createGetItRequester","debug","debugMiddleware","createDebug","getCliExecutionContext","cachedPkg","options","headers","middleware","getItOptions","resolvedMiddleware","debugDefaults","namespace","verbose","customDebug","push","log","resolveDefaultHeaders","undefined","customHeaders","Object","keys","some","header","toLowerCase","pkg","getPackageInfo","name","version","pkgPath","cwd","dirname","Error","packageJson","JSON","parse"],"mappings":"AAAA,SAAQA,YAAY,QAAO,UAAS;AAEpC,SAAQC,MAAMC,SAAS,QAAO,mBAAkB;AAChD,SACEC,mBAAmBC,oBAAoB,QAMlC,SAAQ;AACf,SAAQC,SAASC,eAAe,QAAO,oBAAmB;AAC1D,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D,IAAIC;AA8CJ,OAAO,SAASN,gBACdO,OAAgC;IAEhC,MAAM,EAACL,KAAK,EAAEM,OAAO,EAAEC,aAAa,EAAE,EAAE,G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,OAAOvB;AACT"}
1
+ {"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\n\nimport {up as packageUp} from 'empathic/package'\nimport {\n createRequester as createGetItRequester,\n type FetchHeaders,\n type RequesterOptions,\n type RequestFunction,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {debug as debugMiddleware} from 'get-it/middleware'\nimport {createDebug} from 'obug'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for creating a Sanity CLI requester.\n *\n * Extends get-it v9's {@link RequesterOptions} with Sanity CLI defaults for\n * User-Agent headers and debug logging.\n *\n * @public\n */\nexport type CreateRequesterOptions = Omit<RequesterOptions, 'headers'> & {\n /**\n * Debug logging middleware. Defaults to enabled with namespace `sanity:cli`.\n * Pass `false` to disable.\n */\n debug?: false | {namespace?: string; verbose?: boolean}\n /**\n * Default headers for all requests.\n * Omitting uses a lazy User-Agent of `@sanity/cli-core@<version>`.\n * Pass `false` to send no default headers.\n */\n headers?: false | Record<string, string>\n}\n\n/**\n * Creates a get-it requester with Sanity CLI defaults.\n *\n * Defaults:\n * - User-Agent header: `@sanity/cli-core@<version>` (lazy)\n * - Debug logging via `DEBUG=sanity:cli` (verbose)\n * - HTTP error throwing on (get-it default)\n *\n * @param options - Optional configuration to customize or disable defaults\n * @returns A configured get-it request function\n * @public\n */\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'json'},\n): RequestFunction<'json'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'text'},\n): RequestFunction<'text'>\nexport function createRequester(\n options: CreateRequesterOptions & {as: 'stream'},\n): RequestFunction<'stream'>\nexport function createRequester(options?: CreateRequesterOptions): RequestFunction\nexport function createRequester(\n options?: CreateRequesterOptions,\n): RequestFunction<'json' | 'stream' | 'text' | undefined> {\n const {debug, headers, middleware = [], ...getItOptions} = options ?? {}\n\n // A programmatic invocation must not inherit the embedding process's DEBUG setting or write request/response bodies outside its output sinks.\n const resolvedMiddleware: Array<TransformMiddleware | WrappingMiddleware> = [...middleware]\n if (!getCliExecutionContext() && debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof debug === 'object' ? debug : {}\n const {namespace, verbose} = {...debugDefaults, ...customDebug}\n resolvedMiddleware.push(debugMiddleware({log: createDebug(namespace), verbose}))\n }\n\n return createGetItRequester({\n ...getItOptions,\n headers: resolveDefaultHeaders(headers),\n middleware: resolvedMiddleware,\n })\n}\n\n/**\n * Builds default headers, including a lazy User-Agent unless overridden or disabled.\n *\n * @internal\n */\nfunction resolveDefaultHeaders(\n headers: false | Record<string, string> | undefined,\n): FetchHeaders | undefined {\n if (headers === false) {\n return undefined\n }\n\n const customHeaders = typeof headers === 'object' ? headers : {}\n if (Object.keys(customHeaders).some((header) => header.toLowerCase() === 'user-agent')) {\n return customHeaders\n }\n\n return {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n}\n\n/**\n * Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.\n *\n * @returns The name and version of the package\n * @internal\n */\nfunction getPackageInfo(): {name: string; version: string} {\n if (cachedPkg) return cachedPkg\n\n const pkgPath = packageUp({cwd: import.meta.dirname})\n if (!pkgPath) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n const packageJson = JSON.parse(readFileSync(pkgPath, 'utf8'))\n cachedPkg = {\n name: packageJson.name ?? '@sanity/cli-core',\n version: packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["readFileSync","up","packageUp","createRequester","createGetItRequester","debug","debugMiddleware","createDebug","getCliExecutionContext","cachedPkg","options","headers","middleware","getItOptions","resolvedMiddleware","debugDefaults","namespace","verbose","customDebug","push","log","resolveDefaultHeaders","undefined","customHeaders","Object","keys","some","header","toLowerCase","pkg","getPackageInfo","name","version","pkgPath","cwd","dirname","Error","packageJson","JSON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QACA,GAAGT,aAAa;IAClB;AACF;AAEA;;;;;CAKC,GACD,SAASO;IACP,IAAIrB,WAAW,OAAOA;IAEtB,MAAMwB,UAAU/B,UAAU;QAACgC,KAAK,YAAYC,OAAO;IAAA;IACnD,IAAI,CAACF,SAAS;QACZ,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,cAAcC,KAAKC,KAAK,CAACvC,aAAaiC,SAAS;IACrDxB,YAAY;QACVsB,MAAMM,YAAYN,IAAI,IAAI;QAC1BC,SAASK,YAAYL,OAAO,IAAI;IAClC;IACA,OAAOvB;AACT"}
@@ -0,0 +1,125 @@
1
+ const MS_IN = {
2
+ day: 86_400_000,
3
+ hour: 3_600_000,
4
+ minute: 60_000,
5
+ month: 2_592_000_000,
6
+ second: 1000,
7
+ week: 604_800_000,
8
+ year: 31_536_000_000
9
+ };
10
+ /** Largest unit first, so the first unit the duration fills is the one we report. */ const UNITS = [
11
+ {
12
+ ms: MS_IN.year,
13
+ unit: 'year'
14
+ },
15
+ {
16
+ ms: MS_IN.month,
17
+ unit: 'month'
18
+ },
19
+ {
20
+ ms: MS_IN.week,
21
+ unit: 'week'
22
+ },
23
+ {
24
+ ms: MS_IN.day,
25
+ unit: 'day'
26
+ },
27
+ {
28
+ ms: MS_IN.hour,
29
+ unit: 'hour'
30
+ },
31
+ {
32
+ ms: MS_IN.minute,
33
+ unit: 'minute'
34
+ },
35
+ {
36
+ ms: MS_IN.second,
37
+ unit: 'second'
38
+ }
39
+ ];
40
+ const relativeTime = new Intl.RelativeTimeFormat('en', {
41
+ numeric: 'always'
42
+ });
43
+ const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
44
+ function pad(value, length = 2) {
45
+ return String(value).padStart(length, '0');
46
+ }
47
+ /**
48
+ * Returns the coarsest unit the elapsed time fills and the rounded number of those
49
+ * units, or `undefined` below a second.
50
+ *
51
+ * Rounding can land the value on the boundary of the next unit up, so we promote
52
+ * rather than report `60 minutes` where `1 hour` is meant. Units aren't all whole
53
+ * multiples of each other, so the boundary is the rounded count we'd display, which
54
+ * is why 25+ days reads as `1 month` rather than `4 weeks`.
55
+ */ function selectUnit(elapsed) {
56
+ let index = UNITS.findIndex(({ ms })=>elapsed >= ms);
57
+ if (index === -1) return undefined;
58
+ while(index > 0 && Math.round(elapsed / UNITS[index].ms) >= Math.round(UNITS[index - 1].ms / UNITS[index].ms)){
59
+ index -= 1;
60
+ }
61
+ const { ms, unit } = UNITS[index];
62
+ return {
63
+ unit,
64
+ value: Math.round(elapsed / ms)
65
+ };
66
+ }
67
+ /**
68
+ * Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable
69
+ * timestamps are returned as-is, so a bad value from the API doesn't fail the command.
70
+ *
71
+ * @param timestamp - An ISO 8601 timestamp
72
+ * @internal
73
+ */ export function formatDateTime(timestamp) {
74
+ const date = new Date(timestamp);
75
+ if (!Number.isFinite(date.getTime())) return timestamp;
76
+ const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
77
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
78
+ return `${day} ${time}`;
79
+ }
80
+ /**
81
+ * Formats a duration in milliseconds as an approximate, human readable length of
82
+ * time, eg `less than a minute`, `5 minutes` or `2 days`.
83
+ *
84
+ * @param ms - The duration in milliseconds
85
+ * @internal
86
+ */ export function formatDuration(ms) {
87
+ if (!Number.isFinite(ms)) return '';
88
+ const selected = selectUnit(Math.abs(ms));
89
+ if (!selected || selected.unit === 'second') return 'less than a minute';
90
+ const unit = selected.value === 1 ? selected.unit : `${selected.unit}s`;
91
+ return `${selected.value} ${unit}`;
92
+ }
93
+ /**
94
+ * Formats a date relative to now, eg `2 days ago` or `in 3 hours`.
95
+ *
96
+ * @param date - The date to describe
97
+ * @param now - The reference point to compare against, defaults to the current time
98
+ * @internal
99
+ */ export function formatTimeAgo(date, now = Date.now()) {
100
+ const delta = date.getTime() - now;
101
+ if (!Number.isFinite(delta)) return '';
102
+ const selected = selectUnit(Math.abs(delta));
103
+ if (!selected) return 'just now';
104
+ return relativeTime.format(delta < 0 ? -selected.value : selected.value, selected.unit);
105
+ }
106
+ /**
107
+ * Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`
108
+ * for anything that isn't a real calendar date in that exact format.
109
+ *
110
+ * @param value - The date string to parse
111
+ * @internal
112
+ */ export function parseDateOnly(value) {
113
+ const match = DATE_ONLY_PATTERN.exec(value);
114
+ if (!match) return undefined;
115
+ const year = Number(match[1]);
116
+ const month = Number(match[2]);
117
+ const day = Number(match[3]);
118
+ const date = new Date(year, month - 1, day);
119
+ // `new Date(2024, 1, 31)` silently rolls over into March, so reject anything
120
+ // that didn't survive the round trip
121
+ const isRoundTrip = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
122
+ return isRoundTrip ? date : undefined;
123
+ }
124
+
125
+ //# sourceMappingURL=dates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/dates.ts"],"sourcesContent":["const MS_IN = {\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n month: 2_592_000_000, // 30 days\n second: 1000,\n week: 604_800_000,\n year: 31_536_000_000, // 365 days\n} as const\n\n/** Largest unit first, so the first unit the duration fills is the one we report. */\nconst UNITS: {ms: number; unit: Intl.RelativeTimeFormatUnit}[] = [\n {ms: MS_IN.year, unit: 'year'},\n {ms: MS_IN.month, unit: 'month'},\n {ms: MS_IN.week, unit: 'week'},\n {ms: MS_IN.day, unit: 'day'},\n {ms: MS_IN.hour, unit: 'hour'},\n {ms: MS_IN.minute, unit: 'minute'},\n {ms: MS_IN.second, unit: 'second'},\n]\n\nconst relativeTime = new Intl.RelativeTimeFormat('en', {numeric: 'always'})\n\nconst DATE_ONLY_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\nfunction pad(value: number, length = 2): string {\n return String(value).padStart(length, '0')\n}\n\n/**\n * Returns the coarsest unit the elapsed time fills and the rounded number of those\n * units, or `undefined` below a second.\n *\n * Rounding can land the value on the boundary of the next unit up, so we promote\n * rather than report `60 minutes` where `1 hour` is meant. Units aren't all whole\n * multiples of each other, so the boundary is the rounded count we'd display, which\n * is why 25+ days reads as `1 month` rather than `4 weeks`.\n */\nfunction selectUnit(\n elapsed: number,\n): {unit: Intl.RelativeTimeFormatUnit; value: number} | undefined {\n let index = UNITS.findIndex(({ms}) => elapsed >= ms)\n if (index === -1) return undefined\n\n while (\n index > 0 &&\n Math.round(elapsed / UNITS[index].ms) >= Math.round(UNITS[index - 1].ms / UNITS[index].ms)\n ) {\n index -= 1\n }\n\n const {ms, unit} = UNITS[index]\n return {unit, value: Math.round(elapsed / ms)}\n}\n\n/**\n * Formats a timestamp as `YYYY-MM-DD HH:mm:ss` in the local time zone. Unparseable\n * timestamps are returned as-is, so a bad value from the API doesn't fail the command.\n *\n * @param timestamp - An ISO 8601 timestamp\n * @internal\n */\nexport function formatDateTime(timestamp: string): string {\n const date = new Date(timestamp)\n if (!Number.isFinite(date.getTime())) return timestamp\n\n const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`\n const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n return `${day} ${time}`\n}\n\n/**\n * Formats a duration in milliseconds as an approximate, human readable length of\n * time, eg `less than a minute`, `5 minutes` or `2 days`.\n *\n * @param ms - The duration in milliseconds\n * @internal\n */\nexport function formatDuration(ms: number): string {\n if (!Number.isFinite(ms)) return ''\n\n const selected = selectUnit(Math.abs(ms))\n if (!selected || selected.unit === 'second') return 'less than a minute'\n\n const unit = selected.value === 1 ? selected.unit : `${selected.unit}s`\n return `${selected.value} ${unit}`\n}\n\n/**\n * Formats a date relative to now, eg `2 days ago` or `in 3 hours`.\n *\n * @param date - The date to describe\n * @param now - The reference point to compare against, defaults to the current time\n * @internal\n */\nexport function formatTimeAgo(date: Date, now: number = Date.now()): string {\n const delta = date.getTime() - now\n if (!Number.isFinite(delta)) return ''\n\n const selected = selectUnit(Math.abs(delta))\n if (!selected) return 'just now'\n\n return relativeTime.format(delta < 0 ? -selected.value : selected.value, selected.unit)\n}\n\n/**\n * Parses a `YYYY-MM-DD` date into a `Date` at local midnight. Returns `undefined`\n * for anything that isn't a real calendar date in that exact format.\n *\n * @param value - The date string to parse\n * @internal\n */\nexport function parseDateOnly(value: string): Date | undefined {\n const match = DATE_ONLY_PATTERN.exec(value)\n if (!match) return undefined\n\n const year = Number(match[1])\n const month = Number(match[2])\n const day = Number(match[3])\n const date = new Date(year, month - 1, day)\n\n // `new Date(2024, 1, 31)` silently rolls over into March, so reject anything\n // that didn't survive the round trip\n const isRoundTrip =\n date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day\n\n return isRoundTrip ? date : undefined\n}\n"],"names":["MS_IN","day","hour","minute","month","second","week","year","UNITS","ms","unit","relativeTime","Intl","RelativeTimeFormat","numeric","DATE_ONLY_PATTERN","pad","value","length","String","padStart","selectUnit","elapsed","index","findIndex","undefined","Math","round","formatDateTime","timestamp","date","Date","Number","isFinite","getTime","getFullYear","getMonth","getDate","time","getHours","getMinutes","getSeconds","formatDuration","selected","abs","formatTimeAgo","now","delta","format","parseDateOnly","match","exec","isRoundTrip"],"mappings":"AAAA,MAAMA,QAAQ;IACZC,KAAK;IACLC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,QAAQ;IACRC,MAAM;IACNC,MAAM;AACR;AAEA,mFAAmF,GACnF,MAAMC,QAA2D;IAC/D;QAACC,IAAIT,MAAMO,IAAI;QAAEG,MAAM;IAAM;IAC7B;QAACD,IAAIT,MAAMI,KAAK;QAAEM,MAAM;IAAO;IAC/B;QAACD,IAAIT,MAAMM,IAAI;QAAEI,MAAM;IAAM;IAC7B;QAACD,IAAIT,MAAMC,GAAG;QAAES,MAAM;IAAK;IAC3B;QAACD,IAAIT,MAAME,IAAI;QAAEQ,MAAM;IAAM;IAC7B;QAACD,IA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KAAKK,WAAW,OAAO5B,QAAQuB,KAAKM,QAAQ,OAAOhC,QAAQ,KAAK0B,KAAKO,OAAO,OAAOpC;IAErF,OAAOmD,cAActB,OAAOL;AAC9B"}
@@ -10,8 +10,8 @@ import { getCliExecutionContext } from '../executionContext.js';
10
10
  success: '✔',
11
11
  warning: '⚠'
12
12
  };
13
- function resolveAffix(value1) {
14
- const resolved = typeof value1 === 'function' ? value1() : value1;
13
+ function resolveAffix(value) {
14
+ const resolved = typeof value === 'function' ? value() : value;
15
15
  return typeof resolved === 'string' ? resolved : '';
16
16
  }
17
17
  /**
@@ -80,11 +80,24 @@ function resolveAffix(value1) {
80
80
  };
81
81
  return instance;
82
82
  }
83
+ // Ora's default `discardStdin: true` puts stdin in raw mode, which stops the
84
+ // kernel from turning Ctrl+C into SIGINT (and ora's userland re-signal
85
+ // fallback never fires on a non-flowing stdin), hanging the process. Keep it
86
+ // off by default; explicit caller options still win.
87
+ function normalize(options) {
88
+ const resolved = typeof options === 'string' ? {
89
+ text: options
90
+ } : options ?? {};
91
+ return {
92
+ discardStdin: false,
93
+ ...resolved
94
+ };
95
+ }
83
96
  export function spinner(options) {
84
- return getCliExecutionContext() ? silentSpinner(options) : ora(options);
97
+ return getCliExecutionContext() ? silentSpinner(options) : ora(normalize(options));
85
98
  }
86
99
  export function spinnerPromise(action, options) {
87
- if (!getCliExecutionContext()) return oraPromise(action, options);
100
+ if (!getCliExecutionContext()) return oraPromise(action, normalize(options));
88
101
  return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action);
89
102
  }
90
103
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PersistOptions,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\n/**\n * Uncolored counterparts of the `log-symbols` glyphs a real spinner persists\n * with. Lines forwarded to an execution context are handed to the embedding\n * host verbatim, so they should not carry ANSI codes the host has to strip.\n */\nconst persistSymbols = {\n error: '✖',\n info: 'ℹ',\n success: '✔',\n warning: '⚠',\n}\n\nfunction resolveAffix(value: Options['prefixText'] | Options['suffixText']): string {\n const resolved = typeof value === 'function' ? value() : value\n return typeof resolved === 'string' ? resolved : ''\n}\n\n/**\n * Stand-in for a real spinner, used when a CLI execution context is active.\n *\n * Frame animation and transient text updates have nowhere useful to go, so they\n * are dropped. The lines a spinner *persists* (`succeed`, `fail`, `warn`,\n * `info`, `stopAndPersist`) are the command's actual output rather than\n * progress, so they are forwarded to the context's sink instead of being\n * swallowed. Ora writes to `process.stderr` by default, so the `stderr` sink is\n * preferred, falling back to `stdout`.\n */\nfunction silentSpinner(options?: Options | string): Ora {\n const resolved = typeof options === 'string' ? {text: options} : (options ?? {})\n const context = getCliExecutionContext()\n const emit = resolved.isSilent ? undefined : (context?.stderr ?? context?.stdout)\n\n const prefixText = resolveAffix(resolved.prefixText)\n const suffixText = resolveAffix(resolved.suffixText)\n const state = {text: resolved.text ?? ''}\n\n const persist = (symbol: string, text?: string): void => {\n if (!emit) return\n\n // Mirrors ora's own line layout, minus the trailing whitespace it leaves\n // behind when only one of the symbol and the text is present.\n const body = text ?? state.text\n const line =\n (prefixText ? `${prefixText} ` : '') +\n symbol +\n (symbol && body ? ` ${body}` : body) +\n (suffixText ? ` ${suffixText}` : '')\n\n if (line.trim() !== '') emit(line)\n }\n\n const instance = {\n clear: () => instance,\n fail: (text?: string) => {\n persist(persistSymbols.error, text)\n return instance\n },\n frame: () => '',\n info: (text?: string) => {\n persist(persistSymbols.info, text)\n return instance\n },\n isSpinning: false,\n prefixText,\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: (persistOptions: PersistOptions = {}) => {\n persist(persistOptions.symbol ?? '', persistOptions.text)\n return instance\n },\n succeed: (text?: string) => {\n persist(persistSymbols.success, text)\n return instance\n },\n suffixText,\n get text(): string {\n return state.text\n },\n set text(value: string) {\n state.text = value\n },\n warn: (text?: string) => {\n persist(persistSymbols.warning, text)\n return instance\n },\n }\n return instance as unknown as Ora\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(options)\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, options)\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","persistSymbols","error","info","success","warning","resolveAffix","value","resolved","silentSpinner","options","text","context","emit","isSilent","undefined","stderr","stdout","prefixText","suffixText","state","persist","symbol","body","line","trim","instance","clear","fail","frame","isSpinning","render","start","stop","stopAndPersist","persistOptions","succeed","warn","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAIL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D;;;;CAIC,GACD,MAAMC,iBAAiB;IACrBC,OAAO;IACPC,MAAM;IACNC,SAAS;IACTC,SAAS;AACX;AAEA,SAASC,aAAaC,MAAoD;IACxE,MAAMC,WAAW,OAAOD,WAAU,aAAaA,WAAUA;IACzD,OAAO,OAAOC,aAAa,WAAWA,WAAW;AACnD;AAEA;;;;;;;;;CASC,GACD,SAASC,cAAcC,OAA0B;IAC/C,MAAMF,WAAW,OAAOE,YAAY,WAAW;QAACC,MAAMD;IAAO,IAAKA,WAAW,CAAC;IAC9E,MAAME,UAAUZ;IAChB,MAAMa,OAAOL,SAASM,QAAQ,GAAGC,YAAaH,SAASI,UAAUJ,SAASK;IAE1E,MAAMC,aAAaZ,aAAaE,SAASU,UAAU;IACnD,MAAMC,aAAab,aAAaE,SAASW,UAAU;IACnD,M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,eACdC,MAA4D,EAC5D9B,OAAoC;IAEpC,IAAI,CAACV,0BAA0B,OAAOD,WAAWyC,QAAQ9B;IACzD,OAAO+B,QAAQC,OAAO,CAAC,OAAOF,WAAW,aAAaA,OAAO/B,cAAcC,YAAY8B;AACzF"}
1
+ {"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PersistOptions,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\n/**\n * Uncolored counterparts of the `log-symbols` glyphs a real spinner persists\n * with. Lines forwarded to an execution context are handed to the embedding\n * host verbatim, so they should not carry ANSI codes the host has to strip.\n */\nconst persistSymbols = {\n error: '✖',\n info: 'ℹ',\n success: '✔',\n warning: '⚠',\n}\n\nfunction resolveAffix(value: Options['prefixText'] | Options['suffixText']): string {\n const resolved = typeof value === 'function' ? value() : value\n return typeof resolved === 'string' ? resolved : ''\n}\n\n/**\n * Stand-in for a real spinner, used when a CLI execution context is active.\n *\n * Frame animation and transient text updates have nowhere useful to go, so they\n * are dropped. The lines a spinner *persists* (`succeed`, `fail`, `warn`,\n * `info`, `stopAndPersist`) are the command's actual output rather than\n * progress, so they are forwarded to the context's sink instead of being\n * swallowed. Ora writes to `process.stderr` by default, so the `stderr` sink is\n * preferred, falling back to `stdout`.\n */\nfunction silentSpinner(options?: Options | string): Ora {\n const resolved = typeof options === 'string' ? {text: options} : (options ?? {})\n const context = getCliExecutionContext()\n const emit = resolved.isSilent ? undefined : (context?.stderr ?? context?.stdout)\n\n const prefixText = resolveAffix(resolved.prefixText)\n const suffixText = resolveAffix(resolved.suffixText)\n const state = {text: resolved.text ?? ''}\n\n const persist = (symbol: string, text?: string): void => {\n if (!emit) return\n\n // Mirrors ora's own line layout, minus the trailing whitespace it leaves\n // behind when only one of the symbol and the text is present.\n const body = text ?? state.text\n const line =\n (prefixText ? `${prefixText} ` : '') +\n symbol +\n (symbol && body ? ` ${body}` : body) +\n (suffixText ? ` ${suffixText}` : '')\n\n if (line.trim() !== '') emit(line)\n }\n\n const instance = {\n clear: () => instance,\n fail: (text?: string) => {\n persist(persistSymbols.error, text)\n return instance\n },\n frame: () => '',\n info: (text?: string) => {\n persist(persistSymbols.info, text)\n return instance\n },\n isSpinning: false,\n prefixText,\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: (persistOptions: PersistOptions = {}) => {\n persist(persistOptions.symbol ?? '', persistOptions.text)\n return instance\n },\n succeed: (text?: string) => {\n persist(persistSymbols.success, text)\n return instance\n },\n suffixText,\n get text(): string {\n return state.text\n },\n set text(value: string) {\n state.text = value\n },\n warn: (text?: string) => {\n persist(persistSymbols.warning, text)\n return instance\n },\n }\n return instance as unknown as Ora\n}\n\n// Ora's default `discardStdin: true` puts stdin in raw mode, which stops the\n// kernel from turning Ctrl+C into SIGINT (and ora's userland re-signal\n// fallback never fires on a non-flowing stdin), hanging the process. Keep it\n// off by default; explicit caller options still win.\nfunction normalize<T extends Options>(options?: string | T): T {\n const resolved = typeof options === 'string' ? ({text: options} as T) : (options ?? ({} as T))\n return {discardStdin: false, ...resolved}\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(normalize(options))\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, normalize(options))\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","persistSymbols","error","info","success","warning","resolveAffix","value","resolved","silentSpinner","options","text","context","emit","isSilent","undefined","stderr","stdout","prefixText","suffixText","state","persist","symbol","body","line","trim","instance","clear","fail","frame","isSpinning","render","start","stop","stopAndPersist","persistOptions","succeed","warn","normalize","discardStdin","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAIL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D;;;;CAIC,GACD,MAAMC,iBAAiB;IACrBC,OAAO;IACPC,MAAM;IACNC,SAAS;IACTC,SAAS;AACX;AAEA,SAASC,aAAaC,KAAoD;IACxE,MAAMC,WAAW,OAAOD,UAAU,aAAaA,UAAUA;IACzD,OAAO,OAAOC,aAAa,WAAWA,WAAW;AACnD;AAEA;;;;;;;;;CASC,GACD,SAASC,cAAcC,OAA0B;IAC/C,MAAMF,WAAW,OAAOE,YAAY,WAAW;QAACC,MAAMD;IAAO,IAAKA,WAAW,CAAC;IAC9E,MAAME,UAAUZ;IAChB,MAAMa,OAAOL,SAASM,QAAQ,GAAGC,YAAaH,SAASI,UAAUJ,SAASK;IAE1E,MAAMC,aAAaZ,aAAaE,SAASU,UAAU;IACnD,MAAMC,aAAab,aAAaE,SAASW,UAAU;IACnD,MAAMC,QAAQ;QAACT,MAAMH,SAASG,IAAI,IAAI;IAAE;IAExC,MAAMU,UAAU,CAACC,QAAgBX;QAC/B,IAAI,CAACE,MAAM;QAEX,yEAAyE;QACzE,8DAA8D;QAC9D,MAAMU,OAAOZ,QAAQS,MAAMT,IAAI;QAC/B,MAAMa,OACJ,AAACN,CAAAA,aAAa,GAAGA,WAAW,CAAC,CAAC,GAAG,EAAC,IAClCI,SACCA,CAAAA,UAAUC,OAAO,CAAC,CAAC,EAAEA,MAAM,GAAGA,IAAG,IACjCJ,CAAAA,aAAa,CAAC,CAAC,EAAEA,YAAY,GAAG,EAAC;QAEpC,IAAIK,KAAKC,IAAI,OAAO,IAAIZ,KAAKW;IAC/B;IAEA,MAAME,WAAW;QACfC,OAAO,IAAMD;QACbE,MAAM,CAACjB;YACLU,QAAQpB,eAAeC,KAAK,EAAES;YAC9B,OAAOe;QACT;QACAG,OAAO,IAAM;QACb1B,MAAM,CAACQ;YACLU,QAAQpB,eAAeE,IAAI,EAAEQ;YAC7B,OAAOe;QACT;QACAI,YAAY;QACZZ;QACAa,QAAQ,IAAML;QACdM,OAAO,IAAMN;QACbO,MAAM,IAAMP;QACZQ,gBAAgB,CAACC,iBAAiC,CAAC,CAAC;YAClDd,QAAQc,eAAeb,MAAM,IAAI,IAAIa,eAAexB,IAAI;YACxD,OAAOe;QACT;QACAU,SAAS,CAACzB;YACRU,QAAQpB,eAAeG,OAAO,EAAEO;YAChC,OAAOe;QACT;QACAP;QACA,IAAIR;YACF,OAAOS,MAAMT,IAAI;QACnB;QACA,IAAIA,MAAKJ,KAAa,CAAE;YACtBa,MAAMT,IAAI,GAAGJ;QACf;QACA8B,MAAM,CAAC1B;YACLU,QAAQpB,eAAeI,OAAO,EAAEM;YAChC,OAAOe;QACT;IACF;IACA,OAAOA;AACT;AAEA,6EAA6E;AAC7E,uEAAuE;AACvE,6EAA6E;AAC7E,qDAAqD;AACrD,SAASY,UAA6B5B,OAAoB;IACxD,MAAMF,WAAW,OAAOE,YAAY,WAAY;QAACC,MAAMD;IAAO,IAAWA,WAAY,CAAC;IACtF,OAAO;QAAC6B,cAAc;QAAO,GAAG/B,QAAQ;IAAA;AAC1C;AAEA,OAAO,SAASgC,QAAQ9B,OAA0B;IAChD,OAAOV,2BAA2BS,cAAcC,WAAWZ,IAAIwC,UAAU5B;AAC3E;AAEA,OAAO,SAAS+B,eACdC,MAA4D,EAC5DhC,OAAoC;IAEpC,IAAI,CAACV,0BAA0B,OAAOD,WAAW2C,QAAQJ,UAAU5B;IACnE,OAAOiC,QAAQC,OAAO,CAAC,OAAOF,WAAW,aAAaA,OAAOjC,cAAcC,YAAYgC;AACzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "3.5.0",
3
+ "version": "3.6.0",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -49,6 +49,10 @@
49
49
  "source": "./src/_exports/debug.ts",
50
50
  "default": "./dist/_exports/debug.js"
51
51
  },
52
+ "./dates": {
53
+ "source": "./src/_exports/dates.ts",
54
+ "default": "./dist/_exports/dates.js"
55
+ },
52
56
  "./errors": {
53
57
  "source": "./src/_exports/errors.ts",
54
58
  "default": "./dist/_exports/errors.js"
@@ -113,11 +117,11 @@
113
117
  "dependencies": {
114
118
  "@inquirer/prompts": "^8.5.2",
115
119
  "@oclif/core": "^4.11.14",
116
- "@sanity/client": "^8.1.0",
120
+ "@sanity/client": "^8.4.0",
117
121
  "boxen": "^8.0.1",
118
122
  "empathic": "^2.0.1",
119
- "get-it": "^9.5.0",
120
- "get-tsconfig": "^4.14.0",
123
+ "get-it": "^9.5.2",
124
+ "get-tsconfig": "^4.14.3",
121
125
  "import-meta-resolve": "^4.2.0",
122
126
  "jiti": "^2.7.0",
123
127
  "jsdom": "^29.1.1",
@@ -127,14 +131,14 @@
127
131
  "ora": "^9.0.0",
128
132
  "rxjs": "^7.8.2",
129
133
  "tsx": "^4.23.12",
130
- "vite": "^8.2.1",
134
+ "vite": "^8.2.2",
131
135
  "vite-node": "^6.0.0",
132
136
  "wrap-ansi": "^9.0.2",
133
- "zod": "^4.4.3"
137
+ "zod": "^4.5.2"
134
138
  },
135
139
  "devDependencies": {
136
140
  "@eslint/compat": "^2.1.0",
137
- "@sanity/pkg-utils": "^12.2.0",
141
+ "@sanity/pkg-utils": "^12.3.4",
138
142
  "@sanity/telemetry": "^1.1.0",
139
143
  "@swc/cli": "^0.8.1",
140
144
  "@swc/core": "^1.15.43",
@@ -142,9 +146,9 @@
142
146
  "@types/node": "^22.20.0",
143
147
  "babel-plugin-react-compiler": "^1.0.0",
144
148
  "eslint": "^10.7.0",
145
- "oxc-transform-react": "^0.145.0",
149
+ "oxc-transform-react": "^0.147.0",
146
150
  "publint": "^0.3.21",
147
- "sanity": "^6.7.0",
151
+ "sanity": "^6.11.0",
148
152
  "typescript": "^6.0.3",
149
153
  "vitest": "^4.1.11",
150
154
  "@repo/package.config": "0.0.1",