@algolia/wizard 0.89.0 → 0.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +87 -34
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -1514,6 +1514,15 @@ function PromptInput() {
1514
1514
  return /* @__PURE__ */ jsxs10(Box10, { flexDirection: "column", children: [
1515
1515
  inputReq.error && /* @__PURE__ */ jsx9(Text11, { color: COLORS.danger, children: inputReq.error }),
1516
1516
  inputReq.messages?.map((m, i) => /* @__PURE__ */ jsx9(Text11, { color: COLORS.muted, children: m }, `msg-${i}`)),
1517
+ inputReq.suggestion && /* @__PURE__ */ jsxs10(Text11, { color: COLORS.muted, children: [
1518
+ "Press",
1519
+ " ",
1520
+ /* @__PURE__ */ jsx9(Text11, { color: COLORS.accent, bold: true, children: "Enter" }),
1521
+ " ",
1522
+ "to use",
1523
+ " ",
1524
+ /* @__PURE__ */ jsx9(Text11, { color: COLORS.accent, bold: true, children: inputReq.suggestion })
1525
+ ] }),
1517
1526
  /* @__PURE__ */ jsxs10(Box10, { children: [
1518
1527
  /* @__PURE__ */ jsxs10(Text11, { color: COLORS.primary, children: [
1519
1528
  inputReq.prompt,
@@ -2358,7 +2367,7 @@ async function ensureApplication(resumeAppId) {
2358
2367
  // package.json
2359
2368
  var package_default = {
2360
2369
  name: "@algolia/wizard",
2361
- version: "0.89.0",
2370
+ version: "0.91.0",
2362
2371
  description: "Magically implement Algolia functionality in your codebase",
2363
2372
  type: "module",
2364
2373
  engines: {
@@ -2831,6 +2840,9 @@ async function runWorkflow(workflow, startWorkflowAppId, options) {
2831
2840
  }
2832
2841
  }
2833
2842
 
2843
+ // src/actions/selectIndex.ts
2844
+ import { basename } from "node:path";
2845
+
2834
2846
  // src/actions/listIndices.ts
2835
2847
  import { z as z5 } from "zod";
2836
2848
  var indicesListSchema = z5.object({
@@ -2865,11 +2877,27 @@ function indexNameError(name) {
2865
2877
  return "Index name cannot end with .txt, .bin, or .idx.";
2866
2878
  return void 0;
2867
2879
  }
2880
+ function slug(text) {
2881
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
2882
+ }
2883
+ function suggestIndexName(project, entity, taken) {
2884
+ const base = ([slug(project), slug(entity ?? "")].filter(Boolean).join("_") || "records").slice(0, MAX_INDEX_NAME_LENGTH);
2885
+ let name = base;
2886
+ for (let n = 2; taken.includes(name); n++) {
2887
+ const suffix = `_${n}`;
2888
+ name = base.slice(0, MAX_INDEX_NAME_LENGTH - suffix.length) + suffix;
2889
+ }
2890
+ return name;
2891
+ }
2868
2892
  var selectIndexStep = async (ctx) => {
2869
2893
  await requireApplication(ctx.appId);
2870
2894
  const indices = await listIndices();
2871
2895
  const names = indices.map((i) => i.name);
2872
2896
  const hasIndices = names.length > 0;
2897
+ const entity = ctx.getStepOutput(
2898
+ "confirm-entities"
2899
+ )?.confirmedEntities?.[0]?.name;
2900
+ const suggested = suggestIndexName(basename(process.cwd()), entity, names);
2873
2901
  let error;
2874
2902
  let chosen;
2875
2903
  while (chosen === void 0) {
@@ -2886,6 +2914,7 @@ var selectIndexStep = async (ctx) => {
2886
2914
  messages: [
2887
2915
  "This app has no existing indices \u2014 enter a name to create one."
2888
2916
  ],
2917
+ suggestion: suggested,
2889
2918
  error
2890
2919
  });
2891
2920
  if (typeof selection !== "string") {
@@ -2894,17 +2923,18 @@ var selectIndexStep = async (ctx) => {
2894
2923
  let candidate;
2895
2924
  let isNewName = true;
2896
2925
  if (!hasIndices) {
2897
- candidate = selection.trim();
2926
+ candidate = selection.trim() || suggested;
2898
2927
  } else if (selection === CREATE_NEW_INDEX) {
2899
2928
  const name = await ctx.requestUserInput({
2900
2929
  prompt: "Name the new index:",
2901
2930
  promptType: "textInput",
2902
- options: []
2931
+ options: [],
2932
+ suggestion: suggested
2903
2933
  });
2904
2934
  if (typeof name !== "string") {
2905
2935
  throw new Error("selectIndex received an unexpected non-text result");
2906
2936
  }
2907
- candidate = name.trim();
2937
+ candidate = name.trim() || suggested;
2908
2938
  } else {
2909
2939
  candidate = selection;
2910
2940
  isNewName = false;
@@ -3140,14 +3170,14 @@ import z9 from "zod";
3140
3170
  import { readFile as readFile4 } from "node:fs/promises";
3141
3171
 
3142
3172
  // src/lib/tools/env.ts
3143
- import { basename } from "node:path";
3173
+ import { basename as basename2 } from "node:path";
3144
3174
  function isEnvFile(filePath) {
3145
- const name = basename(filePath);
3175
+ const name = basename2(filePath);
3146
3176
  return name === ".env" || name.startsWith(".env.");
3147
3177
  }
3148
3178
  function isSecretEnvFile(filePath) {
3149
3179
  if (!isEnvFile(filePath)) return false;
3150
- const name = basename(filePath);
3180
+ const name = basename2(filePath);
3151
3181
  return !/\.(example|sample|template)$/.test(name);
3152
3182
  }
3153
3183
  function secretEnvWriteRefusal(filePath) {
@@ -3782,7 +3812,7 @@ import { execFile as execFile2 } from "node:child_process";
3782
3812
  import { tool as tool8 } from "ai";
3783
3813
  import z15 from "zod";
3784
3814
  import { lstat as lstat3, readdir as readdir2, readFile as readFile8, realpath, stat as stat2 } from "node:fs/promises";
3785
- import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative as relative4, sep as sep2 } from "node:path";
3815
+ import { basename as basename3, isAbsolute as isAbsolute2, join as join8, relative as relative4, sep as sep2 } from "node:path";
3786
3816
  import { performance } from "node:perf_hooks";
3787
3817
  import { Worker } from "node:worker_threads";
3788
3818
  var MAX_GIT_OUTPUT_BYTES = 32e6;
@@ -4125,7 +4155,7 @@ async function safeSearchPath(rootPath, file) {
4125
4155
  }
4126
4156
  async function searchableFiles(root, target) {
4127
4157
  try {
4128
- if (SKIP_FILES.has(basename2(target)) && (await lstat3(target)).isFile()) {
4158
+ if (SKIP_FILES.has(basename3(target)) && (await lstat3(target)).isFile()) {
4129
4159
  return [target];
4130
4160
  }
4131
4161
  const gitRoot = await gitRootForTarget(root, target);
@@ -4304,7 +4334,7 @@ import { tool as tool9 } from "ai";
4304
4334
  import z16 from "zod";
4305
4335
  import { createHash as createHash2 } from "node:crypto";
4306
4336
  import { readFile as readFile9, stat as stat3 } from "node:fs/promises";
4307
- import { basename as basename3, relative as relative5, resolve as resolve3 } from "node:path";
4337
+ import { basename as basename4, relative as relative5, resolve as resolve3 } from "node:path";
4308
4338
 
4309
4339
  // src/lib/tools/utils/prompt.ts
4310
4340
  var chain = Promise.resolve();
@@ -4402,7 +4432,7 @@ function commandDiffersFromReviewedScript(ctx, command, cwd) {
4402
4432
  if (approval.command === command && approval.cwd === cwd) return false;
4403
4433
  if (approval.command === command) return true;
4404
4434
  const scriptReferences = [
4405
- basename3(approval.filePath),
4435
+ basename4(approval.filePath),
4406
4436
  relative5(ctx.root, approval.filePath),
4407
4437
  ".algolia-wizard"
4408
4438
  ];
@@ -5123,8 +5153,8 @@ function generateRecordTool(ctx, createModel = defaultCreateModel2) {
5123
5153
  ...record,
5124
5154
  objectID: nanoid2()
5125
5155
  }));
5126
- const slug = entityName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
5127
- const relPath = `${DATA_DIR}/${slug}.json`;
5156
+ const slug2 = entityName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
5157
+ const relPath = `${DATA_DIR}/${slug2}.json`;
5128
5158
  const resolved2 = resolveInRoot(ctx, relPath);
5129
5159
  if (resolved2.ok === false) return resolved2.error;
5130
5160
  const writeError = await safeWriteFile(
@@ -6077,7 +6107,7 @@ import {
6077
6107
  // src/lib/git.ts
6078
6108
  import { execFile as execFile3 } from "node:child_process";
6079
6109
  import { copyFile, mkdir as mkdir4, stat as stat4 } from "node:fs/promises";
6080
- import { basename as basename4, dirname as dirname3, isAbsolute as isAbsolute3, join as join9, resolve as resolve4 } from "node:path";
6110
+ import { basename as basename5, dirname as dirname3, isAbsolute as isAbsolute3, join as join9, resolve as resolve4 } from "node:path";
6081
6111
  var MAX_BUFFER = 32 * 1024 * 1024;
6082
6112
  function git(args) {
6083
6113
  return new Promise((resolve6, reject) => {
@@ -6114,7 +6144,7 @@ async function copyUploadIntoProject(repoRoot, ingestDir, sourcePath) {
6114
6144
  } catch {
6115
6145
  return { ok: false, reason: `"${sourcePath}" does not exist` };
6116
6146
  }
6117
- const relPath = join9(ingestDir, basename4(source));
6147
+ const relPath = join9(ingestDir, basename5(source));
6118
6148
  const dest = join9(repoRoot, relPath);
6119
6149
  if (resolve4(source) === resolve4(dest)) {
6120
6150
  return { ok: true, relPath };
@@ -6490,6 +6520,27 @@ function packageSearchInstructions(input) {
6490
6520
  "Install any Algolia packages you import with the project's own package manager via runShell, and declare them in the project's dependency manifest."
6491
6521
  ];
6492
6522
  }
6523
+ function cdnAutocompleteShape(placeholder) {
6524
+ return `Use this shape for the autocomplete call. Replace the item fields and the getURL route with the real record fields and an existing route:
6525
+ \`\`\`js
6526
+ window.instantsearch.widgets.autocomplete({
6527
+ container: '#autocomplete',
6528
+ placeholder: ${JSON.stringify(placeholder)},
6529
+ indices: [
6530
+ {
6531
+ indexName: window.${SEARCH_CONFIG_INDEX_NAME},
6532
+ getURL: (item) => '/existing-route/' + item.slug,
6533
+ templates: {
6534
+ item: ({ item, onSelect }, { html, components }) =>
6535
+ html\`<div onClick=\${onSelect}>\${components.Highlight({ hit: item, attribute: 'name' })}</div>\`,
6536
+ noResults: (_, { html }) => html\`<span>No results</span>\`,
6537
+ },
6538
+ },
6539
+ ],
6540
+ })
6541
+ \`\`\`
6542
+ The widget reads the item and noResults templates only from each indices entry. Its own top-level templates option accepts only panel. If item is not inside indices[].templates, the widget throws "Template must be 'string' or 'function', was 'undefined' (key: item)" on the first search and shows no results.`;
6543
+ }
6493
6544
  function cdnSearchInstructions(input) {
6494
6545
  const entityName = input.findings.confirmedEntities?.[0]?.name;
6495
6546
  const placeholder = entityName ? `Search ${entityName} records...` : "Search indexed content...";
@@ -6499,7 +6550,8 @@ function cdnSearchInstructions(input) {
6499
6550
  input.searchKey ? `Set window.${SEARCH_CONFIG_SEARCH_KEY} to "${input.searchKey}".` : `A real search-only key could not be provisioned${input.searchKeyError ? ` (${input.searchKeyError})` : ""} \u2014 set window.${SEARCH_CONFIG_SEARCH_KEY} to the placeholder "${SEARCH_KEY_PLACEHOLDER}" and add a prominent TODO for the developer to fill in a real one.`,
6500
6551
  'Load these exact pinned tags in order before the config and search scripts: <script src="https://cdn.jsdelivr.net/npm/algoliasearch@5.59.0/dist/lite/builds/browser.umd.js" integrity="sha256-pduQHl1jn0IaN/BIpSotQm7Y5THdpKcX3Bw6xdRteRw=" crossorigin="anonymous"></script> then <script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.117.0/dist/instantsearch.production.min.js" integrity="sha256-5zhKxAGeH7ThWfnmdD4pS1gsmafE2b8aWRsq8set/dc=" crossorigin="anonymous"></script>.',
6501
6552
  'When using the InstantSearch theme, load this exact tag before the application styles: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.22.1/themes/satellite-min.css" integrity="sha256-5/eHPZl63VYJSDVOKrOgGe/5+owUkX3uPAW6+XYeLNc=" crossorigin="anonymous">. Never use an unversioned or differently versioned theme URL, and never omit its integrity attribute.',
6502
- `In that classic search script, use window['algoliasearch/lite'].liteClient and window.instantsearch. Add window.instantsearch.widgets.autocomplete as the only search widget. Configure it with container '#autocomplete', the content-specific placeholder ${JSON.stringify(placeholder)}, and an indices array containing one object whose indexName is window.${SEARCH_CONFIG_INDEX_NAME}; put item and noResults functions in its templates option, implement getURL only for an existing route, and match the item template to the entity schema. Keep insights: true and call search.start(). Do not substitute searchBox or hits, omit indices, use imports or exports, or use type="module".`
6553
+ `In that classic search script, use window['algoliasearch/lite'].liteClient and window.instantsearch. Add window.instantsearch.widgets.autocomplete as the only search widget. Configure it with container '#autocomplete', the content-specific placeholder ${JSON.stringify(placeholder)}, and an indices array containing one object whose indexName is window.${SEARCH_CONFIG_INDEX_NAME}. Put the item and noResults functions in the templates option of that indices entry, implement getURL only for an existing route, and match the item template to the entity schema. Keep insights: true and call search.start(). Do not substitute searchBox or hits, omit indices, use imports or exports, or use type="module".`,
6554
+ cdnAutocompleteShape(placeholder)
6503
6555
  ];
6504
6556
  }
6505
6557
  function validationInstructions(input) {
@@ -6522,7 +6574,8 @@ function validationInstructions(input) {
6522
6574
  "Do not modify files. Report each implementation issue as a concrete instruction for the next implementation pass.",
6523
6575
  `Detected verification tools: ${JSON.stringify(input.findings.verification ?? [])}. Use only a type checker; ignore any linter or formatter in this list.`,
6524
6576
  ...!input.frontendHasPackageJson ? [
6525
- "The frontend has no package.json: never create one or run npm, pnpm, yarn, or bun. Validate the CDN implementation by inspecting its HTML or template and classic scripts for the search container, Algolia \u2192 InstantSearch \u2192 config \u2192 search load order, browser globals, autocomplete widget configuration, search.start(), and exact pinned CDN URLs and integrity attributes for every Algolia script or stylesheet. Source inspection is required even when the project has no automated checks. window.instantsearch.widgets.autocomplete is a real widget in the pinned InstantSearch build; do not report its use as an error, and do not fetch a remote bundle or URL to verify it."
6577
+ "The frontend has no package.json: never create one or run npm, pnpm, yarn, or bun. Validate the CDN implementation by inspecting its HTML or template and classic scripts for the search container, Algolia \u2192 InstantSearch \u2192 config \u2192 search load order, browser globals, autocomplete widget configuration, search.start(), and exact pinned CDN URLs and integrity attributes for every Algolia script or stylesheet. Source inspection is required even when the project has no automated checks. window.instantsearch.widgets.autocomplete is a real widget in the pinned InstantSearch build; do not report its use as an error, and do not fetch a remote bundle or URL to verify it.",
6578
+ "In the autocomplete call, confirm that the item and noResults templates are inside the templates option of the indices entry, not in the top-level templates option of the widget. The top-level templates option accepts only panel, so an item template there throws on the first search and no results show. If item is missing from indices[].templates, set sufficient=false and tell the next pass to move the templates into the indices entry."
6526
6579
  ] : [],
6527
6580
  "Always call reportStatus with status=success after validation, even when sufficient=false.",
6528
6581
  "Set sufficient=false if the input's computed accessible name is empty or generic, including when aria-labelledby references a missing or empty element; a placeholder does not count as the label.",
@@ -6662,8 +6715,8 @@ async function firstRecordIn(filePath) {
6662
6715
  async function ingestedRecordSample(repoRoot, entityName, uploadFilePath) {
6663
6716
  const candidates = [];
6664
6717
  if (entityName) {
6665
- const slug = entityName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
6666
- candidates.push(join11(repoRoot, INGEST_DIR, "data", `${slug}.json`));
6718
+ const slug2 = entityName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
6719
+ candidates.push(join11(repoRoot, INGEST_DIR, "data", `${slug2}.json`));
6667
6720
  }
6668
6721
  if (uploadFilePath?.toLowerCase().endsWith(".json")) {
6669
6722
  candidates.push(join11(repoRoot, uploadFilePath));
@@ -7600,9 +7653,9 @@ async function getPlaybooks() {
7600
7653
  );
7601
7654
  return data;
7602
7655
  }
7603
- async function createPlaybookExecution(appId, slug, indexName, options) {
7656
+ async function createPlaybookExecution(appId, slug2, indexName, options) {
7604
7657
  const { data } = await dashboardRequest(
7605
- `/api/1/playbook-integrations/applications/${appId}/playbooks/${slug}/executions`,
7658
+ `/api/1/playbook-integrations/applications/${appId}/playbooks/${slug2}/executions`,
7606
7659
  playbookExecutionCreateResponseSchema,
7607
7660
  {
7608
7661
  method: "POST",
@@ -7643,9 +7696,9 @@ async function assessPlaybookExecution(uuid) {
7643
7696
  var selectPlaybookSchema = z33.object({
7644
7697
  slug: z33.string()
7645
7698
  });
7646
- function persistSlug(ctx, slug) {
7647
- ctx.setUserInput("playbookSlug", slug);
7648
- return { slug };
7699
+ function persistSlug(ctx, slug2) {
7700
+ ctx.setUserInput("playbookSlug", slug2);
7701
+ return { slug: slug2 };
7649
7702
  }
7650
7703
  async function selectPlaybookStep(ctx, requestedSlug) {
7651
7704
  const playbooks = await getPlaybooks();
@@ -7776,13 +7829,13 @@ async function confirmIndexStep(ctx) {
7776
7829
  if (!sampleIndex) {
7777
7830
  return null;
7778
7831
  }
7779
- const { slug } = ctx.getStepOutput("select-playbook");
7832
+ const { slug: slug2 } = ctx.getStepOutput("select-playbook");
7780
7833
  const selection = await ctx.requestUserInput({
7781
7834
  prompt: "Ready to create sample index?",
7782
7835
  promptType: "multipleChoice",
7783
7836
  options: [CONTINUE_OPTION, GO_BACK_OPTION2],
7784
7837
  messages: [
7785
- `A new index called "algolia_playbooks_${slug}_sample_index" will be created with sample ${slug} data.`
7838
+ `A new index called "algolia_playbooks_${slug2}_sample_index" will be created with sample ${slug2} data.`
7786
7839
  ],
7787
7840
  helpText: "Going back lets you choose a different index."
7788
7841
  });
@@ -7934,13 +7987,13 @@ var POLL_NOTICES = [
7934
7987
  { message: "detecting required fields\u2026" }
7935
7988
  ];
7936
7989
  async function dataAssessmentStep(ctx) {
7937
- const { slug } = ctx.getStepOutput("select-playbook");
7990
+ const { slug: slug2 } = ctx.getStepOutput("select-playbook");
7938
7991
  const { indexName, existingExecution } = indexForAssessment(ctx);
7939
7992
  if (existingExecution) return existingExecution;
7940
7993
  try {
7941
7994
  showNotice(ctx, CREATING_EXECUTION_NOTICE);
7942
7995
  const { id: appId } = await requireApplication();
7943
- const execution = await resolveExecution(ctx, appId, slug, indexName);
7996
+ const execution = await resolveExecution(ctx, appId, slug2, indexName);
7944
7997
  const assessed = await runAssessment(ctx, execution, indexName);
7945
7998
  ctx.clearNotices();
7946
7999
  await promptReady(ctx, assessed);
@@ -8045,24 +8098,24 @@ function unexpectedAssessmentStatus(status) {
8045
8098
  `data-assessment received an unexpected assessment status: ${status}`
8046
8099
  );
8047
8100
  }
8048
- async function resolveExecution(ctx, appId, slug, indexName) {
8049
- const created = await createWithRecovery(ctx, appId, slug, indexName);
8101
+ async function resolveExecution(ctx, appId, slug2, indexName) {
8102
+ const created = await createWithRecovery(ctx, appId, slug2, indexName);
8050
8103
  if (!created.resumed) return created;
8051
8104
  const choice = await promptResumeExecution(ctx, indexName);
8052
8105
  if (choice === CONTINUE_EXECUTION_OPTION) return created;
8053
8106
  if (choice === RESTART_OPTION) {
8054
- return createWithRecovery(ctx, appId, slug, indexName, { forceNew: true });
8107
+ return createWithRecovery(ctx, appId, slug2, indexName, { forceNew: true });
8055
8108
  }
8056
8109
  if (choice === GO_BACK_OPTION3) {
8057
8110
  return ctx.returnToStep("select-index");
8058
8111
  }
8059
8112
  throw new Error("data-assessment received an unexpected execution choice");
8060
8113
  }
8061
- async function createWithRecovery(ctx, appId, slug, indexName, options) {
8114
+ async function createWithRecovery(ctx, appId, slug2, indexName, options) {
8062
8115
  return retryOnDashboardError(
8063
8116
  () => {
8064
8117
  showNotice(ctx, CREATING_EXECUTION_NOTICE);
8065
- return createPlaybookExecution(appId, slug, indexName, options);
8118
+ return createPlaybookExecution(appId, slug2, indexName, options);
8066
8119
  },
8067
8120
  onRequestFailure(ctx, indexName)
8068
8121
  );
@@ -9741,7 +9794,7 @@ async function resetProjectState() {
9741
9794
  // package.json with { type: 'json' }
9742
9795
  var package_default2 = {
9743
9796
  name: "@algolia/wizard",
9744
- version: "0.89.0",
9797
+ version: "0.91.0",
9745
9798
  description: "Magically implement Algolia functionality in your codebase",
9746
9799
  type: "module",
9747
9800
  engines: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@algolia/wizard",
3
- "version": "0.89.0",
3
+ "version": "0.91.0",
4
4
  "description": "Magically implement Algolia functionality in your codebase",
5
5
  "type": "module",
6
6
  "engines": {