storyblok 4.26.2 → 4.27.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.
package/dist/index.mjs CHANGED
@@ -13,7 +13,7 @@ import { exec, spawn } from "node:child_process";
13
13
  import { readPackageUp } from "read-package-up";
14
14
  import fs, { access, appendFile, constants, mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
15
15
  import filenamify from "filenamify";
16
- import { createManagementApiClient, normalizeAssetUrl } from "@storyblok/management-api-client";
16
+ import { ClientError, createManagementApiClient, normalizeAssetUrl } from "@storyblok/management-api-client";
17
17
  import { confirm, input, password, select } from "@inquirer/prompts";
18
18
  import { promisify } from "node:util";
19
19
  import { minimatch } from "minimatch";
@@ -27,7 +27,7 @@ import open from "open";
27
27
  import { Octokit } from "octokit";
28
28
  import { pipeline as pipeline$1 } from "node:stream/promises";
29
29
  import { Buffer } from "node:buffer";
30
- import { ClientError, createApiClient } from "@storyblok/api-client";
30
+ import { ClientError as ClientError$1, createApiClient } from "@storyblok/api-client";
31
31
  import { compile as compile$1 } from "json-p3";
32
32
  import * as officialFieldPlugins from "@storyblok/schema/field-plugins";
33
33
  import { createTwoFilesPatch } from "diff";
@@ -746,7 +746,8 @@ const API_ACTIONS = {
746
746
  delete_datasource_entry: "Failed to delete datasource entry",
747
747
  create_space: "Failed to create space",
748
748
  pull_spaces: "Failed to pull spaces",
749
- fetch_blueprints: "Failed to fetch blueprints from GitHub"
749
+ fetch_blueprints: "Failed to fetch blueprints from GitHub",
750
+ search_strata: "Failed to search with Strata"
750
751
  };
751
752
  const API_ERRORS = {
752
753
  unauthorized: "The user is not authorized to access the API",
@@ -1072,6 +1073,8 @@ var UI = class {
1072
1073
  console;
1073
1074
  enabled;
1074
1075
  multiBar;
1076
+ /** Whether a bar was drawn since the last stop: stopping an empty MultiBar still writes. */
1077
+ hasBars = false;
1075
1078
  constructor({ enabled }) {
1076
1079
  this.enabled = enabled;
1077
1080
  this.console = null;
@@ -1101,7 +1104,6 @@ var UI = class {
1101
1104
  if (subtitle) this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);
1102
1105
  else this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));
1103
1106
  this.br();
1104
- this.br();
1105
1107
  }
1106
1108
  br() {
1107
1109
  this.console?.log("");
@@ -1182,9 +1184,14 @@ var UI = class {
1182
1184
  * `cli-progress` already refuses to render on a non-terminal stream, but
1183
1185
  * `@topcli/spinner` has no such check and writes escapes unconditionally. The
1184
1186
  * guard lives here so the rule holds whichever library backs a given widget.
1187
+ *
1188
+ * A terminal on stderr is not enough when stdout is a pipe: the reader, such
1189
+ * as `jq`, usually prints to that same terminal, and each redraw moves the
1190
+ * cursor back over the lines it printed, overwriting results. A redirect to a
1191
+ * file or `/dev/null` has no such reader, so it keeps the live UI. See ADR-0027.
1185
1192
  */
1186
1193
  get canRedraw() {
1187
- return getStderrTarget() === "terminal";
1194
+ return getStderrTarget() === "terminal" && getStdoutTarget() !== "pipe";
1188
1195
  }
1189
1196
  /**
1190
1197
  * Stand-in for a spinner on a stream that cannot animate: CI logs, `2> run.log`.
@@ -1211,6 +1218,7 @@ var UI = class {
1211
1218
  if (!this.canRedraw) return noopProgressBar;
1212
1219
  const bar = this.multiBar?.create(0, 0, options);
1213
1220
  if (!bar) return noopProgressBar;
1221
+ this.hasBars = true;
1214
1222
  return {
1215
1223
  increment: (count = 1) => bar.increment(count, options),
1216
1224
  setTotal: (total) => {
@@ -1221,12 +1229,14 @@ var UI = class {
1221
1229
  };
1222
1230
  }
1223
1231
  stopAllProgressBars() {
1232
+ if (!this.hasBars) return;
1233
+ this.hasBars = false;
1224
1234
  this.multiBar?.stop();
1225
1235
  }
1226
1236
  createSpinner(title) {
1227
1237
  if (!this.enabled) return noopSpinner;
1228
1238
  if (!this.canRedraw) return this.plainSpinner(title);
1229
- const spinner = new Spinner({ verbose: getActiveConfig().verbose });
1239
+ const spinner = new Spinner();
1230
1240
  spinner.stream = process.stderr;
1231
1241
  return spinner.start(title);
1232
1242
  }
@@ -2902,7 +2912,8 @@ const upsertComponent = async (space, component, existingId) => {
2902
2912
  content_type_asset_preview: component.content_type_asset_preview,
2903
2913
  internal_tag_ids: toRequestTagIds(component.internal_tag_ids),
2904
2914
  schema: toWritableSchema(component.schema),
2905
- metadata: component.metadata === null ? {} : component.metadata
2915
+ metadata: component.metadata === null ? {} : component.metadata,
2916
+ updated_at: void 0
2906
2917
  };
2907
2918
  if (existingId) return await updateComponent(space, existingId, payload);
2908
2919
  else return await pushComponent(space, payload);
@@ -7375,7 +7386,7 @@ const redactUrlTokens = (text) => text.replace(URL_TOKEN_PARAM, "$1[redacted]");
7375
7386
  * and are returned as is.
7376
7387
  */
7377
7388
  function redactClientError(maybeError) {
7378
- if (maybeError instanceof ClientError && maybeError.response.status > 0) return maybeError;
7389
+ if (maybeError instanceof ClientError$1 && maybeError.response.status > 0) return maybeError;
7379
7390
  const error = toError(maybeError);
7380
7391
  const redacted = new Error(redactUrlTokens(error.message));
7381
7392
  redacted.name = error.name;
@@ -10523,7 +10534,7 @@ async function createCapiContentFetcher({ spaceId, region, params }) {
10523
10534
  if (Object.keys(params).length > 0) try {
10524
10535
  await listStories({ per_page: 1 });
10525
10536
  } catch (error) {
10526
- if (!(error instanceof ClientError) || error.response.status >= 500) throw error;
10537
+ if (!(error instanceof ClientError$1) || error.response.status >= 500) throw error;
10527
10538
  const reason = error.response.data?.error ?? error.response.data?.message ?? error.message;
10528
10539
  throw new CommandError(`The CDN rejected --capi-params ${JSON.stringify(params)} (HTTP ${error.response.status}): ${String(reason)}`);
10529
10540
  }
@@ -10745,6 +10756,17 @@ function parseList(flag, raw) {
10745
10756
  return items.join(",");
10746
10757
  }
10747
10758
  /**
10759
+ * Reads `--starts-with` as the API's slug prefix.
10760
+ *
10761
+ * `""` or `/` normalizes to no prefix at all, which would widen the run to the
10762
+ * whole space: the opposite of what passing the flag asked for.
10763
+ */
10764
+ function parseStartsWith(raw) {
10765
+ const { starts_with: startsWith } = buildStoryScopeParams({ startsWith: raw });
10766
+ if (startsWith === void 0) throw new CommandError(`--starts-with expects a slug prefix, e.g. 'en/blog', and got: ${JSON.stringify(raw)}`);
10767
+ return startsWith;
10768
+ }
10769
+ /**
10748
10770
  * Rejects options the command accepts on the surface but cannot honour yet.
10749
10771
  *
10750
10772
  * Silently ignoring an explicitly passed flag is worse than failing: the user
@@ -10827,11 +10849,10 @@ function buildQueryParams(text, options, now = /* @__PURE__ */ new Date()) {
10827
10849
  const params = { with_stages: true };
10828
10850
  if (text) params.text_search = text;
10829
10851
  const scope = buildStoryScopeParams({
10830
- startsWith: options.startsWith,
10852
+ startsWith: options.startsWith === void 0 ? void 0 : parseStartsWith(options.startsWith),
10831
10853
  query: options.query,
10832
10854
  extraFilterQuery: options.containerBlock !== void 0 ? { component: { in: parseList("--container-block", options.containerBlock) } } : void 0
10833
10855
  });
10834
- if (options.startsWith !== void 0 && scope.starts_with === void 0) throw new CommandError(`--starts-with expects a slug prefix, e.g. 'en/blog', and got: ${JSON.stringify(options.startsWith)}`);
10835
10856
  Object.assign(params, scope);
10836
10857
  if (options.includesBlock !== void 0) params.contain_component = parseList("--includes-block", options.includesBlock);
10837
10858
  if (options.tag !== void 0) params.with_tag = parseList("--tag", options.tag);
@@ -10933,7 +10954,7 @@ function buildWhereFilters(expressions) {
10933
10954
  if (!expressions?.length) return [];
10934
10955
  return expressions.map((expression) => {
10935
10956
  const query = compileWhere(expression);
10936
- return (story) => query.match(toJsonValue(withoutContentSummary(story))) !== void 0;
10957
+ return (story) => query.test(toJsonValue(withoutContentSummary(story)));
10937
10958
  });
10938
10959
  }
10939
10960
  /**
@@ -11352,6 +11373,33 @@ const uniqueStoriesStream = ({ onRepeat }) => {
11352
11373
  });
11353
11374
  };
11354
11375
  /**
11376
+ * Holds every listed story, then passes them on in the order `order` gives.
11377
+ *
11378
+ * For a listing whose order is not the one the results should come in: the
11379
+ * `--mode semantic` listing comes back in the API's order, and Strata's rank has
11380
+ * to be restored before the content fetch, so `--limit` stops it after the top
11381
+ * results rather than after whichever were listed first. Only for a small,
11382
+ * bounded listing: nothing moves on until the last story has arrived.
11383
+ */
11384
+ const reorderStoriesStream = ({ order }) => {
11385
+ const buffered = [];
11386
+ return new Transform({
11387
+ objectMode: true,
11388
+ transform(story, _encoding, callback) {
11389
+ buffered.push(story);
11390
+ callback();
11391
+ },
11392
+ flush(callback) {
11393
+ try {
11394
+ for (const story of order(buffered)) this.push(story);
11395
+ callback();
11396
+ } catch (maybeError) {
11397
+ callback(toError(maybeError));
11398
+ }
11399
+ }
11400
+ });
11401
+ };
11402
+ /**
11355
11403
  * Drops stories before their content is fetched. The per-story fetch is the
11356
11404
  * expensive part of the pipeline, so any filter decidable from the list response
11357
11405
  * (such as `--publish-status`) belongs here rather than at the end.
@@ -11549,7 +11597,7 @@ async function prepareCapiFilter({ spaceId, region, capiParams, filters, attachC
11549
11597
  * `--check-references`. The run therefore moves at the pace of whatever is
11550
11598
  * reading, rather than ahead of it.
11551
11599
  */
11552
- async function runStoryPipeline({ spaceId, params, preContentFilters, filters, tracker, sink, onListed, capi, skipContent = false, signal, logger, verbose }) {
11600
+ async function runStoryPipeline({ spaceId, params, preContentFilters, filters, tracker, sink, onListed, capi, orderListed, skipContent = false, signal, logger, verbose }) {
11553
11601
  const list = tracker.phase("list");
11554
11602
  const capiFilter = tracker.phase("capiFilter");
11555
11603
  const content = tracker.phase("content");
@@ -11594,6 +11642,7 @@ async function runStoryPipeline({ spaceId, params, preContentFilters, filters, t
11594
11642
  ...params.scheduled_by_status !== void 0 ? [uniqueStoriesStream({ onRepeat: () => {
11595
11643
  list.count("repeated");
11596
11644
  } })] : [],
11645
+ ...orderListed ? [reorderStoriesStream({ order: orderListed })] : [],
11597
11646
  filterListedStoriesStream({
11598
11647
  filters: preContentFilters,
11599
11648
  onDropped: () => {
@@ -11693,7 +11742,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11693
11742
  return [
11694
11743
  {
11695
11744
  key: "list",
11696
- label: "Fetching stories",
11745
+ label: "Listing stories",
11697
11746
  counters: [
11698
11747
  "succeeded",
11699
11748
  "repeated",
@@ -11717,7 +11766,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11717
11766
  },
11718
11767
  {
11719
11768
  key: "content",
11720
- label: "Fetching stories content",
11769
+ label: "Fetching content",
11721
11770
  enabled: !skipContent,
11722
11771
  counters: ["succeeded", "failed"],
11723
11772
  outflow: (counts) => counts.total - counts.failed
@@ -11741,11 +11790,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11741
11790
  * filter reaches it.
11742
11791
  */
11743
11792
  function processStageName({ skipContent, capi, filters }) {
11744
- if (skipContent) {
11745
- if (capi) return "Collecting matches";
11746
- return filters.length > 0 ? "Applying client-side filters" : "Writing results";
11747
- }
11748
- return capi ? "Collecting matches" : "Applying client-side filters";
11793
+ return skipContent && !capi && filters.length === 0 ? "Writing results" : "Filtering";
11749
11794
  }
11750
11795
  /** `1 story`, `210 stories`. */
11751
11796
  const storiesCount = (count) => `${count} ${count === 1 ? "story" : "stories"}`;
@@ -11798,11 +11843,11 @@ function findSummary({ results, elapsedMs, tracker, filters, skipContent, capi }
11798
11843
  });
11799
11844
  }
11800
11845
  /**
11801
- * Reports a deliberate stop as one: the counts that follow describe a partial
11802
- * scan, and anything less explicit than "not an error" reads as one next to them.
11846
+ * Reports a deliberate stop as one: the counts above it describe a partial scan,
11847
+ * which could otherwise read as a failure. The success mark says the rest.
11803
11848
  */
11804
- function stoppedEarlyMessage(limit) {
11805
- return (limit !== void 0 ? `Stopped early on purpose: --limit ${limit} was reached, so the rest of the scope was left unread. ` : "Stopped early on purpose: the command reading this output took what it needed and closed the pipe. ") + "This is not an error — the run exits 0. The counts cover only the part of the scope that ran.";
11849
+ function stoppedEarlyMessage(limit, { limitIsDefault = false } = {}) {
11850
+ return `${limit === void 0 ? "Stopped when the reading command closed the pipe, as expected." : limitIsDefault ? `Stopped at ${limit} results, the default. Set --limit for more.` : `Stopped at --limit ${limit}, as asked.`} The counts above cover only the part of the scope that ran.`;
11806
11851
  }
11807
11852
  /** The content phase's row in the run summary. */
11808
11853
  function contentSummary(tracker) {
@@ -11871,10 +11916,328 @@ const REF_ISSUE_COLUMNS = [...STORY_COLUMNS, {
11871
11916
  header: "issues",
11872
11917
  value: (story) => summarizeIssues(story._ref_issues)
11873
11918
  }];
11919
+ /**
11920
+ * The excerpt is the only flexible column: it can run to well over a thousand
11921
+ * characters, and the name is what identifies the story, so it must not be the
11922
+ * column that gives way.
11923
+ */
11924
+ const SEMANTIC_STORY_COLUMNS = [
11925
+ ...STORY_COLUMNS.map((column) => ({
11926
+ ...column,
11927
+ flexible: false
11928
+ })),
11929
+ {
11930
+ header: "score",
11931
+ value: (story) => story._score.toFixed(2)
11932
+ },
11933
+ {
11934
+ header: "excerpt",
11935
+ value: (story) => story._excerpt.replace(/\s+/g, " "),
11936
+ flexible: true
11937
+ }
11938
+ ];
11939
+ /**
11940
+ * Every `find` option, and whether `--mode semantic` takes it: `null` when it
11941
+ * does, or why not.
11942
+ *
11943
+ * Typed over every option, so a flag added to `find` does not compile until it
11944
+ * is classified here. An option missing from it at runtime is rejected, so the
11945
+ * list fails closed.
11946
+ *
11947
+ * Strata answers with one ranked page of at most 100 hits. A flag that reorders
11948
+ * that page, or that needs the whole space in scope, would answer a different
11949
+ * question than the one asked.
11950
+ */
11951
+ const SEMANTIC_OPTIONS = {
11952
+ space: null,
11953
+ mode: null,
11954
+ entryType: {
11955
+ reason: "Strata only searches stories, never folders",
11956
+ values: ["folder"]
11957
+ },
11958
+ startsWith: null,
11959
+ containerBlock: null,
11960
+ includesBlock: null,
11961
+ query: null,
11962
+ where: null,
11963
+ tag: null,
11964
+ workflowStage: null,
11965
+ publishStatus: null,
11966
+ created: null,
11967
+ updated: null,
11968
+ lastPublished: null,
11969
+ firstPublished: null,
11970
+ scheduled: null,
11971
+ sort: { reason: "results keep Strata's relevance order" },
11972
+ limit: null,
11973
+ references: null,
11974
+ checkReferences: { reason: "the reference check reads every story in scope, not Strata's matches" },
11975
+ skipContent: null,
11976
+ capiFilter: { reason: "Strata returns at most 100 hits, so there is nothing to prune ahead of the Management API fetch" },
11977
+ capiParams: { reason: "semantic mode searches the draft, like the stories it prints; filter by status with --publish-status" }
11978
+ };
11979
+ const isSemanticOption = (name) => Object.hasOwn(SEMANTIC_OPTIONS, name);
11980
+ /** The incompatibility a value runs into, if any. Unknown options fail closed. */
11981
+ function incompatibilityOf(name, value) {
11982
+ if (!isSemanticOption(name)) return { reason: "it is not supported in semantic mode" };
11983
+ const incompatibility = SEMANTIC_OPTIONS[name];
11984
+ if (!incompatibility) return;
11985
+ if (incompatibility.values && !incompatibility.values.includes(String(value))) return;
11986
+ return incompatibility;
11987
+ }
11988
+ /** A value that asks for nothing: an off switch, an empty string or list, or the default. */
11989
+ function isUnset(value, defaultValue) {
11990
+ return value === void 0 || value === false || value === "" || Array.isArray(value) && value.length === 0 || value === defaultValue;
11991
+ }
11992
+ /** One line naming every flag, or flag value, that semantic mode turns down. */
11993
+ function formatUnavailableFlags(command) {
11994
+ return `Not available with --mode semantic: ${command.options.flatMap((option) => {
11995
+ const name = option.attributeName();
11996
+ const incompatibility = isSemanticOption(name) ? SEMANTIC_OPTIONS[name] : void 0;
11997
+ if (!incompatibility || !option.long) return [];
11998
+ return incompatibility.values ? incompatibility.values.map((value) => `${option.long} ${value}`) : [option.long];
11999
+ }).join(", ")}.`;
12000
+ }
12001
+ /**
12002
+ * Settles the flags semantic mode cannot take.
12003
+ *
12004
+ * Set on the command line, one is a usage error that names it. Set in a config
12005
+ * file, it is a default for full-text runs, and nothing on the command line
12006
+ * could clear it (there is no `--no-sort`), so it is left out of this run
12007
+ * instead. Returns the options to run with, and the flags left out.
12008
+ */
12009
+ function resolveSemanticOptions(command, options) {
12010
+ const resolved = { ...options };
12011
+ const ignored = [];
12012
+ const reasons = [];
12013
+ for (const option of command.options) {
12014
+ const name = option.attributeName();
12015
+ const value = command.getOptionValue(name);
12016
+ if (isUnset(value, option.defaultValue)) continue;
12017
+ const incompatibility = incompatibilityOf(name, value);
12018
+ if (!incompatibility) continue;
12019
+ const flag = incompatibility.values ? `${option.long} ${String(value)}` : `${option.long}`;
12020
+ if (command.getOptionValueSource(name) === "cli") reasons.push(`${flag} is not compatible with --mode semantic: ${incompatibility.reason}.`);
12021
+ else {
12022
+ ignored.push(flag);
12023
+ Reflect.deleteProperty(resolved, name);
12024
+ }
12025
+ }
12026
+ if (reasons.length > 0) throw new CommandError([...reasons, formatUnavailableFlags(command)].join("\n"));
12027
+ return {
12028
+ options: resolved,
12029
+ ignored
12030
+ };
12031
+ }
12032
+ /** Rejects values the compatible flags cannot take in semantic mode, before any request. */
12033
+ function assertSemanticOptions(text, options) {
12034
+ if (!text?.trim()) throw new CommandError("--mode semantic needs a search text, e.g. `stories find 'pages about pricing' --mode semantic`.");
12035
+ if (options.containerBlock !== void 0) {
12036
+ if (parseList("--container-block", options.containerBlock).includes(",")) throw new CommandError(`--mode semantic accepts a single --container-block, and got: ${options.containerBlock}`);
12037
+ }
12038
+ }
12039
+ /**
12040
+ * Picks the content version Strata searches.
12041
+ *
12042
+ * The draft, like the Management API stories the command prints, and like the
12043
+ * full-text search. The one exception changes no result: stories that are
12044
+ * `published` have the same draft and published content, so searching the
12045
+ * published version finds the same ones. It leaves out stories that were never
12046
+ * published, so they take no slots of Strata's single page only to be filtered
12047
+ * out afterwards. Stories with unpublished changes are still in the published
12048
+ * version, and `--publish-status published` drops them after the search.
12049
+ */
12050
+ function strataVersion(publishStatus) {
12051
+ if (publishStatus === void 0) return "draft";
12052
+ const statuses = new Set(parsePublishStatuses(publishStatus));
12053
+ return statuses.size === 1 && statuses.has("published") ? "published" : "draft";
12054
+ }
12055
+ /**
12056
+ * Builds the Strata query from the flags it can take.
12057
+ *
12058
+ * `--starts-with` and `--container-block` are pushed down, so they narrow what
12059
+ * Strata ranks rather than what survives of its page. Every other filter runs on
12060
+ * the hydrated stories, like in a full-text run.
12061
+ *
12062
+ * Strata's page is always requested at its largest. Its `limit` counts hits, and a
12063
+ * story can be several hits, so it cannot stand in for `--limit`, which counts
12064
+ * results. The largest page also leaves the most matches for the local filters.
12065
+ *
12066
+ * The version is the draft, unless `--publish-status published` alone makes the
12067
+ * published one equivalent: see {@link strataVersion}.
12068
+ */
12069
+ function buildStrataQuery(text, options) {
12070
+ const startsWith = options.startsWith === void 0 ? void 0 : parseStartsWith(options.startsWith);
12071
+ const contentType = options.containerBlock === void 0 ? void 0 : parseList("--container-block", options.containerBlock);
12072
+ const scoped = startsWith !== void 0 || contentType !== void 0;
12073
+ return {
12074
+ q: text.trim(),
12075
+ version: strataVersion(options.publishStatus),
12076
+ limit: scoped ? 50 : 100,
12077
+ ...startsWith === void 0 ? {} : { starts_with: startsWith },
12078
+ ...contentType === void 0 ? {} : { content_type: contentType }
12079
+ };
12080
+ }
12081
+ /**
12082
+ * Reads `--limit` for a semantic search.
12083
+ *
12084
+ * Without it, the search stops at {@link SEMANTIC_DEFAULT_LIMIT} stories, the
12085
+ * search endpoint's own default: the best matches, rather than everything down
12086
+ * to Strata's weakest. Strata's page
12087
+ * is still requested at its largest, so the local filters have the most
12088
+ * matches to work with. A limit above that page can never be reached, so it is
12089
+ * rejected rather than silently capped.
12090
+ */
12091
+ function parseSemanticLimit(raw, query) {
12092
+ const limit = parseLimit(raw);
12093
+ if (limit === void 0) return {
12094
+ limit: 25,
12095
+ isDefault: true
12096
+ };
12097
+ const max = query.limit ?? 100;
12098
+ if (limit > max) throw new CommandError(`--limit is at most ${max} with --mode semantic${max < 100 ? " with --starts-with or --container-block" : ""}: Strata returns at most ${max} matches. Got: ${raw}`);
12099
+ return {
12100
+ limit,
12101
+ isDefault: false
12102
+ };
12103
+ }
12104
+ /** Collapses Strata's hits to one per story, keeping each story's best one. */
12105
+ function rankHits(hits) {
12106
+ const ranking = /* @__PURE__ */ new Map();
12107
+ for (const { story, score, excerpt } of hits) if (!ranking.has(story.id)) ranking.set(story.id, {
12108
+ score,
12109
+ excerpt
12110
+ });
12111
+ return ranking;
12112
+ }
12113
+ /**
12114
+ * Orders listed stories by their Strata rank and annotates each with it.
12115
+ *
12116
+ * A ranked story the listing did not return (filtered out server-side, or no
12117
+ * longer there) is simply absent.
12118
+ */
12119
+ function* orderByRank(stories, ranking) {
12120
+ const byId = new Map(stories.map((story) => [story.id, story]));
12121
+ for (const [id, { score, excerpt }] of ranking) {
12122
+ const story = byId.get(id);
12123
+ if (story) yield {
12124
+ ...story,
12125
+ _score: score,
12126
+ _excerpt: excerpt
12127
+ };
12128
+ }
12129
+ }
12130
+ /** The longest `Retry-After` the search waits out before it retries. */
12131
+ const STRATA_MAX_RETRY_AFTER = 2e3;
12132
+ /** The wait a 429 asks for, in milliseconds, from `Retry-After` in seconds or as a date. */
12133
+ function retryAfterMs(error) {
12134
+ const response = "response" in error ? error.response : void 0;
12135
+ if (!(response instanceof Response)) return;
12136
+ const header = response.headers.get("Retry-After");
12137
+ if (header === null) return;
12138
+ const seconds = Number(header);
12139
+ if (header.trim() !== "" && Number.isFinite(seconds)) return seconds * 1e3;
12140
+ const date = Date.parse(header);
12141
+ return Number.isNaN(date) ? void 0 : date - Date.now();
12142
+ }
12143
+ /**
12144
+ * Retries for the search request.
12145
+ *
12146
+ * A 429 from the per-second request limit clears within a second or two, so two
12147
+ * short retries absorb it. Strata's own throttling asks for a minute or more,
12148
+ * which the client's default (12 retries, each waiting the full `Retry-After`)
12149
+ * would turn into a silent wait of 12+ minutes. `maxRetryAfter` only shortens
12150
+ * each wait, so retries would still go into a throttle that rejects them: past
12151
+ * 2 seconds, `shouldRetry` makes the search fail right away and say why instead.
12152
+ */
12153
+ const STRATA_RETRY = {
12154
+ limit: 2,
12155
+ methods: ["get"],
12156
+ statusCodes: [429],
12157
+ maxRetryAfter: STRATA_MAX_RETRY_AFTER,
12158
+ backoffLimit: 2e3,
12159
+ shouldRetry: ({ error }) => {
12160
+ const wait = retryAfterMs(error);
12161
+ return wait !== void 0 && wait > STRATA_MAX_RETRY_AFTER ? false : void 0;
12162
+ }
12163
+ };
12164
+ /**
12165
+ * Runs the Strata search through the Management API, as the logged-in user.
12166
+ *
12167
+ * The search honours the user's permissions, so it only matches stories the
12168
+ * user can read, like every other request the command makes. It searches the
12169
+ * draft or the published version alike, with no token beyond the login.
12170
+ */
12171
+ async function searchStrata({ spaceId, query, ui }) {
12172
+ const spinner = ui.createSpinner("Searching with Strata...");
12173
+ try {
12174
+ const { data } = await getMapiClient().strata.search({
12175
+ query,
12176
+ path: { space_id: Number(spaceId) },
12177
+ throwOnError: true,
12178
+ fetchOptions: { retry: STRATA_RETRY }
12179
+ });
12180
+ const hits = data?.results ?? [];
12181
+ const ranking = rankHits(hits);
12182
+ spinner.succeed(`Strata matched ${pluralize$1(ranking.size, "story", "stories")} (${pluralize$1(hits.length, "hit", "hits")})`);
12183
+ return {
12184
+ ranking,
12185
+ ...query.limit !== void 0 && hits.length >= query.limit ? { fullPageOf: query.limit } : {}
12186
+ };
12187
+ } catch (error) {
12188
+ spinner.failed("Strata search failed");
12189
+ throwStrataError(error);
12190
+ }
12191
+ }
12192
+ /** Printed under the summary when Strata's page came back full. */
12193
+ function fullPageMessage(limit) {
12194
+ return `Strata returned its maximum of ${limit} hits, and has no next page, so more stories may match. Narrow the search with --starts-with or --container-block, or make the text more specific.`;
12195
+ }
12196
+ const pluralize$1 = (count, one, many) => `${count} ${count === 1 ? one : many}`;
12197
+ /** Reads the `code` of Strata's `{ error: { code, message } }` body, if the response carries one. */
12198
+ function strataErrorCode(data) {
12199
+ if (!isRecord(data) || !isRecord(data.error)) return;
12200
+ return typeof data.error.code === "string" ? data.error.code : void 0;
12201
+ }
12202
+ function strataErrorMessage(data) {
12203
+ if (!isRecord(data) || !isRecord(data.error)) return;
12204
+ return typeof data.error.message === "string" ? data.error.message : void 0;
12205
+ }
12206
+ /** What to tell the user for the Strata error codes they can act on. */
12207
+ const STRATA_ERROR_HINTS = {
12208
+ feature_disabled: "Strata is not enabled for this space or its organization (feature_disabled).",
12209
+ insufficient_scope: "The token is missing the strata:read scope (insufficient_scope). Log in with a token that has it.",
12210
+ rate_limited: "Strata is rate limiting searches (rate_limited). Try again in a minute."
12211
+ };
12212
+ /**
12213
+ * Turns a failed search into the CLI's errors.
12214
+ *
12215
+ * A 400 is the query itself: a usage error, like any other rejected flag value.
12216
+ * Everything else goes through the usual API error handling, so `--verbose`
12217
+ * shows the status and the response body like for any other request. A Strata
12218
+ * code the user can act on, e.g. `feature_disabled`, gets its own message,
12219
+ * which the bare HTTP status does not tell apart. A 401 keeps the CLI's usual
12220
+ * wording.
12221
+ */
12222
+ function throwStrataError(error) {
12223
+ if (!(error instanceof ClientError) || error.response.status === 0) throw error;
12224
+ const { status, data } = error.response;
12225
+ const code = strataErrorCode(data);
12226
+ const message = strataErrorMessage(data);
12227
+ if (status === 400) throw new CommandError(`Strata rejected the search${code ? ` (${code})` : ""}${message ? `: ${message}` : "."}`);
12228
+ const hint = (code && STRATA_ERROR_HINTS[code]) ?? (status === 429 ? STRATA_ERROR_HINTS.rate_limited : void 0);
12229
+ if (hint) handleAPIError("search_strata", error, message ? `${hint} Details: ${message}` : hint);
12230
+ if (status === 401) handleAPIError("search_strata", error);
12231
+ handleAPIError("search_strata", error, message ? `Strata search failed${code ? ` (${code})` : ""}: ${message}` : void 0);
12232
+ }
11874
12233
  //#endregion
11875
12234
  //#region src/commands/stories/find/run.ts
11876
- async function runFind({ spaceId, params, preContentFilters, filters, skipContent = false, limit, capi, ui, logger, reporter, verbose }) {
11877
- const output = createResultOutput({
12235
+ async function runFind({ spaceId, params, preContentFilters, filters, skipContent = false, limit, limitIsDefault = false, capi, semantic, ui, logger, reporter, verbose }) {
12236
+ const ranking = semantic?.ranking;
12237
+ const output = ranking ? createResultOutput({
12238
+ columns: SEMANTIC_STORY_COLUMNS,
12239
+ limit
12240
+ }) : createResultOutput({
11878
12241
  columns: STORY_COLUMNS,
11879
12242
  limit
11880
12243
  });
@@ -11895,7 +12258,7 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11895
12258
  let earlyExit = false;
11896
12259
  let stoppedByLimit = false;
11897
12260
  try {
11898
- await runStoryPipeline({
12261
+ if (!ranking || ranking.size > 0) await runStoryPipeline({
11899
12262
  spaceId,
11900
12263
  params,
11901
12264
  preContentFilters,
@@ -11903,15 +12266,17 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11903
12266
  tracker,
11904
12267
  sink: output.sink,
11905
12268
  capi,
12269
+ orderListed: ranking ? (stories) => orderByRank(stories, ranking) : void 0,
11906
12270
  skipContent,
11907
12271
  signal: output.signal,
11908
12272
  logger,
11909
12273
  verbose
11910
12274
  });
11911
12275
  } catch (error) {
11912
- if (!isDeliberateStop(error)) throw error;
12276
+ const reason = output.signal.aborted ? output.signal.reason : error;
12277
+ if (!isDeliberateStop(error) && !isDeliberateStop(reason)) throw error;
11913
12278
  earlyExit = true;
11914
- stoppedByLimit = isLimitReached(error);
12279
+ stoppedByLimit = isLimitReached(error) || isLimitReached(reason);
11915
12280
  } finally {
11916
12281
  tracker.stop();
11917
12282
  output.close();
@@ -11932,7 +12297,9 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11932
12297
  capi: capi !== void 0
11933
12298
  })) ui.log(line);
11934
12299
  const notes = [];
11935
- if (earlyExit) notes.push(() => ui.ok(stoppedEarlyMessage(stoppedByLimit ? limit : void 0)));
12300
+ if (earlyExit) notes.push(() => ui.ok(stoppedEarlyMessage(stoppedByLimit ? limit : void 0, { limitIsDefault })));
12301
+ const fullPageOf = semantic?.fullPageOf;
12302
+ if (fullPageOf !== void 0 && !stoppedByLimit) notes.push(() => ui.warn(fullPageMessage(fullPageOf)));
11936
12303
  if (skipContent && !capi && filters.length > 0 && filtered.succeeded === 0) notes.push(() => ui.warn("--where sees list metadata only while --skip-content is set (full_slug, updated_at, content_type, tag_list, published, …), never story content. If the expression reads content, drop --skip-content, and add --capi-filter to keep the run fast."));
11937
12304
  if (list.failed > 0 && params.sort_by) notes.push(() => ui.warn(`If the error above is "Not sortable by this column", --sort ${params.sort_by} names a column the API cannot sort by. Use a story column such as updated_at, created_at, published_at, name, slug or position, or a content field with the 'content.' prefix.`));
11938
12305
  const missing = capiFilter.unresolved - capiFilter.unresolvedFolders;
@@ -12156,18 +12523,18 @@ async function runCheckReferences({ spaceId, params, preContentFilters, whereFil
12156
12523
  function collectValues(value, previous) {
12157
12524
  return previous.concat([value]);
12158
12525
  }
12159
- storiesCommand.command("find").description("Find stories matching filters and print them to stdout as JSONL, one story per line, or as a table in a terminal. Filters combine with AND.").argument("[text]", "full-text search over story name, slug and content (case-insensitive)").option("-s, --space <space>", "space ID").addOption(new Option("--entry-type <type>", "filter by entry type").choices([
12526
+ storiesCommand.command("find").description("Find stories matching filters and print them to stdout as JSONL, one story per line, or as a table in a terminal. Filters combine with AND.").argument("[text]", "full-text search over story name, slug and content (case-insensitive), or a search by meaning with --mode semantic").option("-s, --space <space>", "space ID").addOption(new Option("--mode <mode>", "how [text] matches: 'fulltext', or 'semantic' to rank stories by meaning with Strata").choices(["fulltext", "semantic"]).default("fulltext")).addOption(new Option("--entry-type <type>", "filter by entry type").choices([
12160
12527
  "all",
12161
12528
  "story",
12162
12529
  "folder"
12163
- ]).default("all")).option("--starts-with <path>", "scope to a story subtree, e.g. 'en/blog'").option("--container-block <name>", "stories whose content type (root block) is this component, e.g. 'page'").option("--includes-block <names>", "stories containing all of these blocks at any depth, comma-separated").option("-q, --query <query>", "filter on root-level content fields with filter_query syntax, e.g. '[category][in]=news'").option("--where <jsonpath>", "JSONPath (RFC 9535) filter evaluated locally on each story, repeatable, e.g. \"$..[?(@.component == 'hero')]\" for a hero block at any depth", collectValues, []).option("--tag <names>", "stories carrying any of these tags, comma-separated").option("--workflow-stage <ids>", "stories at any of these workflow stage IDs (numeric), comma-separated").option("--publish-status <statuses>", "stories in any of these publish statuses, comma-separated: published, published-with-changes, draft").option("--created <range>", "stories created in this date range: a duration like '7d', a date like '2024-06', or a range like '2024-01-01..2024-06-30' (UTC unless an offset is given)").option("--updated <range>", "stories last updated in this date range, e.g. '7d' or '..90d'").option("--last-published <range>", "stories last published in this date range, e.g. '2024-06', including ones unpublished since; add --publish-status published for live ones only. Never-published stories never match").option("--first-published <range>", "stories first published in this date range, e.g. '2024-07..2024-09'").option("--scheduled [range]", "stories with a pending scheduled publish, in any language, optionally in this date range, where durations count forward, e.g. '7d' or '7d..14d'").option("--sort <fields>", "order by a story column or 'content.<field>', comma-separated, e.g. 'updated_at:desc' or 'content.title:asc'").option("--limit <n>", "stop after this many results").option("--references <uuids>", "stories that reference all of these story UUIDs, comma-separated").option("--check-references [types]", "report stories with broken, unpublished or stale_url references, listed in a `_ref_issues` array on each story, or summarized in an issues column in a terminal. Optionally only these types, comma-separated, e.g. 'broken'").option("--skip-content", "skip the per-story content fetch and emit list metadata only (--where then sees metadata only)").option("--capi-filter", "evaluate --where against bulk CDN content first and fetch only the matches from MAPI (requires --where)").option("--capi-params <params>", "extra CDN query params for --capi-filter, e.g. 'version=published' or 'language=de'").action(async (text, options, command) => {
12530
+ ]).default("all")).option("--starts-with <path>", "scope to a story subtree, e.g. 'en/blog'. With --mode semantic, only the default-language slug matches").option("--container-block <name>", "stories whose content type (root block) is this component, e.g. 'page'").option("--includes-block <names>", "stories containing all of these blocks at any depth, comma-separated").option("-q, --query <query>", "filter on root-level content fields with filter_query syntax, e.g. '[category][in]=news'").option("--where <jsonpath>", "JSONPath (RFC 9535) filter evaluated locally on each story, repeatable, e.g. \"$..[?(@.component == 'hero')]\" for a hero block at any depth", collectValues, []).option("--tag <names>", "stories carrying any of these tags, comma-separated").option("--workflow-stage <ids>", "stories at any of these workflow stage IDs (numeric), comma-separated").option("--publish-status <statuses>", "stories in any of these publish statuses, comma-separated: published, published-with-changes, draft").option("--created <range>", "stories created in this date range: a duration like '7d', a date like '2024-06', or a range like '2024-01-01..2024-06-30' (UTC unless an offset is given)").option("--updated <range>", "stories last updated in this date range, e.g. '7d' or '..90d'").option("--last-published <range>", "stories last published in this date range, e.g. '2024-06', including ones unpublished since; add --publish-status published for live ones only. Never-published stories never match").option("--first-published <range>", "stories first published in this date range, e.g. '2024-07..2024-09'").option("--scheduled [range]", "stories with a pending scheduled publish, in any language, optionally in this date range, where durations count forward, e.g. '7d' or '7d..14d'").option("--sort <fields>", "order by a story column or 'content.<field>', comma-separated, e.g. 'updated_at:desc' or 'content.title:asc'").option("--limit <n>", "stop after this many results. With --mode semantic, 25 by default and at most 100 (50 with --starts-with or --container-block)").option("--references <uuids>", "stories that reference all of these story UUIDs, comma-separated").option("--check-references [types]", "report stories with broken, unpublished or stale_url references, listed in a `_ref_issues` array on each story, or summarized in an issues column in a terminal. Optionally only these types, comma-separated, e.g. 'broken'").option("--skip-content", "skip the per-story content fetch and emit list metadata only (--where then sees metadata only)").option("--capi-filter", "evaluate --where against bulk CDN content first and fetch only the matches from MAPI (requires --where)").option("--capi-params <params>", "extra CDN query params for --capi-filter, e.g. 'version=published' or 'language=de'").action(async (text, cliOptions, command) => {
12164
12531
  const ui = getUI();
12165
12532
  const logger = getLogger();
12166
12533
  const reporter = getReporter();
12167
12534
  ui.title(`${commands.STORIES}`, colorPalette.STORIES, "Finding stories...");
12168
12535
  logger.info("Finding stories started", {
12169
12536
  text,
12170
- ...options
12537
+ ...cliOptions
12171
12538
  });
12172
12539
  const { space, verbose } = command.optsWithGlobals();
12173
12540
  const { state } = session();
@@ -12176,13 +12543,30 @@ storiesCommand.command("find").description("Find stories matching filters and pr
12176
12543
  handleError(new CommandError("Please provide the space as argument --space YOUR_SPACE_ID."), verbose);
12177
12544
  return;
12178
12545
  }
12546
+ const semantic = cliOptions.mode === "semantic";
12179
12547
  try {
12548
+ let options = cliOptions;
12549
+ if (semantic) {
12550
+ const resolved = resolveSemanticOptions(command, cliOptions);
12551
+ options = resolved.options;
12552
+ if (resolved.ignored.length > 0) {
12553
+ logger.info("Ignoring config values semantic mode cannot take", { ignored: resolved.ignored });
12554
+ ui.info(`Ignoring config values that --mode semantic cannot take: ${resolved.ignored.join(", ")}.`);
12555
+ }
12556
+ }
12557
+ if (semantic) assertSemanticOptions(text, options);
12180
12558
  assertSupportedOptions(options);
12559
+ const strataQuery = semantic && text ? buildStrataQuery(text, options) : void 0;
12181
12560
  const now = /* @__PURE__ */ new Date();
12182
- const params = buildQueryParams(text, options, now);
12561
+ const params = semantic ? buildQueryParams(void 0, {
12562
+ ...options,
12563
+ startsWith: void 0,
12564
+ containerBlock: void 0
12565
+ }, now) : buildQueryParams(text, options, now);
12183
12566
  const preContentFilters = [...buildPublishStatusFilters(options), ...buildDateFilters(options, now)];
12184
12567
  const whereFilters = buildWhereFilters(options.where);
12185
- const limit = parseLimit(options.limit);
12568
+ const semanticLimit = strataQuery ? parseSemanticLimit(options.limit, strataQuery) : void 0;
12569
+ const limit = semanticLimit ? semanticLimit.limit : parseLimit(options.limit);
12186
12570
  const issueTypes = parseIssueTypes(options.checkReferences);
12187
12571
  const context = {
12188
12572
  spaceId: space,
@@ -12192,6 +12576,27 @@ storiesCommand.command("find").description("Find stories matching filters and pr
12192
12576
  reporter,
12193
12577
  verbose
12194
12578
  };
12579
+ if (strataQuery) {
12580
+ const search = await searchStrata({
12581
+ spaceId: space,
12582
+ query: strataQuery,
12583
+ ui
12584
+ });
12585
+ await runFind({
12586
+ ...context,
12587
+ params: {
12588
+ ...params,
12589
+ by_ids: [...search.ranking.keys()].join(",")
12590
+ },
12591
+ preContentFilters,
12592
+ filters: whereFilters,
12593
+ skipContent: options.skipContent === true,
12594
+ limit,
12595
+ limitIsDefault: semanticLimit?.isDefault,
12596
+ semantic: search
12597
+ });
12598
+ return;
12599
+ }
12195
12600
  const capi = options.capiFilter ? await prepareCapiFilter({
12196
12601
  spaceId: space,
12197
12602
  region: state.region,
@@ -17032,7 +17437,6 @@ const program = getProgram();
17032
17437
  const ui = getUI();
17033
17438
  ui.br();
17034
17439
  ui.title("Storyblok CLI", colorPalette.PRIMARY);
17035
- ui.br();
17036
17440
  program.on("command:*", () => {
17037
17441
  console.error(`Invalid command: ${program.args.join(" ")}`);
17038
17442
  console.error("");