@valbuild/shared 0.122.0 → 0.123.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.
@@ -2,6 +2,7 @@ import { Internal, CODE_LANGUAGES, DEFAULT_COLOR_FORMAT } from '@valbuild/core';
2
2
  import { b as base64DataUrlToUint8Array } from '../../dist/utils-00f3e1df.esm.js';
3
3
  import { z } from 'zod';
4
4
  import { fromError } from 'zod-validation-error';
5
+ import FlexSearch from 'flexsearch';
5
6
 
6
7
  function _toPrimitive(t, r) {
7
8
  if ("object" != typeof t || !t) return t;
@@ -4666,13 +4667,21 @@ function checkGallerySchema(moduleSchema) {
4666
4667
  };
4667
4668
  }
4668
4669
  function buildImageGalleryPatch(args, moduleSchema) {
4670
+ var _args$metadata$alt;
4669
4671
  var wrong = checkGallerySchema(moduleSchema);
4670
4672
  if (wrong) return wrong;
4671
4673
  var remote = isRemoteSchema(moduleSchema);
4672
4674
  var patch = [{
4673
4675
  op: "add",
4674
4676
  path: [args.filePath],
4675
- value: _objectSpread2({}, args.metadata)
4677
+ value: _objectSpread2(_objectSpread2({}, args.metadata), {}, {
4678
+ // `alt` is a REQUIRED field of a gallery entry (`s.images()` gives it a
4679
+ // nullable string schema), so an entry written without one is invalid
4680
+ // the moment it lands — and the caller that had no alt to give is the
4681
+ // common case, not the odd one. Null is what the Studio's own upload
4682
+ // writes there.
4683
+ alt: (_args$metadata$alt = args.metadata.alt) !== null && _args$metadata$alt !== void 0 ? _args$metadata$alt : null
4684
+ })
4676
4685
  }, {
4677
4686
  op: "file",
4678
4687
  path: [args.filePath],
@@ -5164,4 +5173,702 @@ function filterBlockingValidationErrors(validationErrors, schemas, sources) {
5164
5173
  return partitionValidationErrors(resolved).surfaced;
5165
5174
  }
5166
5175
 
5167
- export { Api, BinaryFileRef, CodeOptions, ColorOptions, DEFAULT_ERROR_MESSAGE, DateOptions, FileOptions, HistoricalCommit, HistoricalModule, HistoricalPatchSet, HistoryError, ImageEncodeOption, ImageOptions, JSONValue, JSON_ENTRIES_BATCH_MAX, ModuleComparison, ParentRef$1 as ParentRef, Patch, PatchBlock, PatchGroup, PatchId, PatchJSON, RemirrorBr, RemirrorBulletList, RemirrorHeading, RemirrorImage, RemirrorJSON, RemirrorLinkMark, RemirrorListItem, RemirrorOrderedList, RemirrorParagraph, RemirrorText, RemirrorTextMark, RestoreVerdict, RichTextOptions, SerializedArraySchema, SerializedBooleanSchema, SerializedCodeSchema, SerializedColorSchema, SerializedDateSchema, SerializedDateTimeSchema, SerializedFileSchema, SerializedImageSchema, SerializedKeyOfSchema, SerializedLiteralSchema, SerializedNumberSchema, SerializedObjectSchema, SerializedRecordSchema, SerializedRichTextSchema, SerializedRouteSchema, SerializedSchema, SerializedSettingsSchema, SerializedStringSchema, SerializedUnionSchema, SharedValConfig, VAL_AI_SESSION_STORAGE_KEY, VAL_CANVAS_MESSAGE, VAL_CANVAS_PARAM, VAL_CONFIG_SESSION_STORAGE_KEY, VAL_ENABLE_COOKIE_NAME, VAL_SESSION_COOKIE, VAL_STATE_COOKIE, VAL_THEME_SESSION_STORAGE_KEY, ValCommit, ValDeployment, buildDuplicatePatch, buildEmptyAtPathPatch, buildFileRefValue, buildImageGalleryPatch, buildRemoveImageGalleryEntryPatch, checkCompatibility, createRegExpFromPattern, createValClient, describeContainerAtPath, emptyOf, explainIncompatible, filterBlockingValidationErrors, filterRoutesByPatterns, findSimilar, getErrorMessageFromUnknownJson, getInlineImgInfo, getNextAppRouterSitemapTree, getNextAppRouterSourceFolder, getPatternFromModuleFilePath, getRoutesOf, getRoutesWithModulePaths, getSourceAt, isRemoteSchema, isValCanvasFrame, isValCanvasPageMessage, isValCanvasStudioMessage, levenshtein, newestCommitSha, parseRoutePattern, partitionValidationErrors, remirrorToRichTextSource, resolveSchemaSourceFixForError, resolveSchemaSourceFixes, resolveSerializedSchemaAtPath, richTextToRemirror, safeParsePatch, toolNames, urlOf, validateRoutePatterns, withValCanvasParam };
5176
+ /**
5177
+ * Every decision `encode` makes, with none of the pixels.
5178
+ *
5179
+ * The re-encode itself happens in two places that share nothing: the Studio
5180
+ * runs it on a `<canvas>` before the upload leaves the browser
5181
+ * (`packages/ui/spa/utils/encodeImage.ts`), and the MCP image tool runs it on
5182
+ * `sharp` in the server process (`@valbuild/mcp`). What must NOT differ between
5183
+ * them is what `s.image({ encode })` means — which images are converted, how
5184
+ * far they are scaled, and when the original wins anyway. So the decisions live
5185
+ * here, once, and each side supplies only its own encoder.
5186
+ *
5187
+ * See `architecture/media.md`.
5188
+ */
5189
+
5190
+ var ENCODE_DEFAULTS = {
5191
+ quality: 0.8,
5192
+ maxWidth: 2560,
5193
+ maxHeight: 2560
5194
+ };
5195
+ var ENCODE_MIME_TYPE_OF = {
5196
+ webp: "image/webp"
5197
+ };
5198
+
5199
+ /**
5200
+ * Formats an encoder cannot round-trip without losing something: SVG is vector,
5201
+ * an animated GIF keeps only its first frame, and AVIF is already smaller than
5202
+ * anything we would produce.
5203
+ */
5204
+ var NEVER_ENCODED = ["image/svg+xml", "image/gif", "image/avif"];
5205
+
5206
+ /** A dimension bound the encoder can act on, else the default. */
5207
+ function usableBound(value, fallback) {
5208
+ return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
5209
+ }
5210
+
5211
+ /**
5212
+ * The schema's own option first, then the gallery it references, then off.
5213
+ *
5214
+ * Mirrors how `ImageField` resolves `accept` and `directory`. A gallery-backed
5215
+ * field (`s.image(galleryVal)`) serializes with EMPTY options, so without the
5216
+ * gallery fallback it could never inherit what the gallery asked for — and
5217
+ * `s.image(galleryVal, { encode: false })` is how such a field opts back out.
5218
+ *
5219
+ * Nonsense numbers fall back to the defaults rather than through. `fitWithin`
5220
+ * reads a bound of 0 (or NaN, or a negative) as "everything already fits", so
5221
+ * an unusable `maxWidth` would otherwise SILENTLY disable the downscale it was
5222
+ * asking for, and a `quality` outside 0–1 is ignored by `canvas.toBlob` just as
5223
+ * quietly. Falling back is deliberately not throwing: a schema is evaluated by
5224
+ * the CLI's `node:vm` sandbox and by the Next server, so a typo'd quality would
5225
+ * take a whole project down over an upload-time optimisation.
5226
+ */
5227
+ function resolveEncodeSettings(fieldOption, galleryOption) {
5228
+ var option = fieldOption !== undefined ? fieldOption : galleryOption;
5229
+ if (!option) {
5230
+ return null;
5231
+ }
5232
+ var quality = option.quality;
5233
+ return {
5234
+ type: option.type,
5235
+ quality: quality !== undefined && Number.isFinite(quality) && quality > 0 ? Math.min(quality, 1) : ENCODE_DEFAULTS.quality,
5236
+ maxWidth: usableBound(option.maxWidth, ENCODE_DEFAULTS.maxWidth),
5237
+ maxHeight: usableBound(option.maxHeight, ENCODE_DEFAULTS.maxHeight)
5238
+ };
5239
+ }
5240
+
5241
+ /**
5242
+ * Dimensions scaled to fit inside the box, or null when the image already does.
5243
+ *
5244
+ * Null is the signal for "no downscale was needed", which the size comparison
5245
+ * in {@link chooseEncoded} turns on.
5246
+ */
5247
+ function fitWithin(width, height, maxWidth, maxHeight) {
5248
+ if (!(width > 0) || !(height > 0) || !(maxWidth > 0) || !(maxHeight > 0) || width <= maxWidth && height <= maxHeight) {
5249
+ return null;
5250
+ }
5251
+ var scale = Math.min(maxWidth / width, maxHeight / height);
5252
+ return {
5253
+ // At least one pixel: a very wide, very short image would otherwise round
5254
+ // its height to zero, and a zero-sized canvas cannot be encoded.
5255
+ width: Math.max(1, Math.round(width * scale)),
5256
+ height: Math.max(1, Math.round(height * scale))
5257
+ };
5258
+ }
5259
+
5260
+ /**
5261
+ * Whether a schema that declares `accept` would take this mime type.
5262
+ *
5263
+ * The same rules as `ImageSchema.executeValidate`, which validates the STORED
5264
+ * mimeType against `accept` — so converting to a type `accept` forbids would
5265
+ * upload a file the schema reports as invalid the moment it lands. Delegated to
5266
+ * `@valbuild/core` rather than re-spelled, because a second reading of one
5267
+ * `accept` string is how a converted image passes here and fails there.
5268
+ */
5269
+ function isMimeTypeAccepted(mimeType, accept) {
5270
+ if (!accept) {
5271
+ return true;
5272
+ }
5273
+ return Internal.mimeTypeMatchesAccept(mimeType, accept);
5274
+ }
5275
+
5276
+ /** Formats left alone: the lossy list, plus the target type when it already fits. */
5277
+ function isSkippedSource(sourceMimeType, targetMimeType, needsDownscale) {
5278
+ if (NEVER_ENCODED.includes(sourceMimeType)) {
5279
+ return true;
5280
+ }
5281
+ return sourceMimeType === targetMimeType && !needsDownscale;
5282
+ }
5283
+
5284
+ /**
5285
+ * Whether to upload what the encoder produced, or the file that was picked.
5286
+ *
5287
+ * Two ways the encoded bytes lose. They are not actually the type we asked for
5288
+ * — `canvas.toBlob` answers an unsupported type with a PNG rather than with
5289
+ * null, so "not null" is not the same question as "is a webp". Or they are
5290
+ * simply bigger, which happens for small and flat images: measured, an 8x8
5291
+ * solid PNG of 74 bytes becomes a 548 byte webp. A downscale overrides that,
5292
+ * since the original is then the wrong size whatever it weighs.
5293
+ */
5294
+ function chooseEncoded(input) {
5295
+ if (input.encodedSize === null || input.encodedType !== input.targetMimeType) {
5296
+ return false;
5297
+ }
5298
+ if (input.needsDownscale) {
5299
+ return true;
5300
+ }
5301
+ return input.encodedSize < input.originalSize;
5302
+ }
5303
+
5304
+ /**
5305
+ * `photo.png` -> `photo.webp`. The extension is re-derived downstream too, but
5306
+ * the name should not lie.
5307
+ */
5308
+ function withExtension(filename, ext) {
5309
+ var base = filename.split(".").slice(0, -1).join(".") || filename;
5310
+ return "".concat(base, ".").concat(ext);
5311
+ }
5312
+
5313
+ /**
5314
+ * The one way to build a child's source path.
5315
+ *
5316
+ * There were five hand-rolled versions of this, three of them subtly different
5317
+ * and two of them wrong, and the wrong ones were wrong in a way that hid: a
5318
+ * module path segment has to be JSON-quoted if it is a string and bare if it is
5319
+ * an array index, and both broken copies appended the raw key at the module
5320
+ * root. An unquoted key parses fine as long as it contains no `.` — so every
5321
+ * object field and every ordinary record key still resolved, and only a key with
5322
+ * a dot in it broke. That is exactly what a media gallery is keyed by, so
5323
+ * clicking a file in the Media panel navigated to
5324
+ * `?p=/public/val/red-8x8_bfbd0.png`, which `splitModulePath` reads as the two
5325
+ * segments `/public/val/red-8x8_bfbd0` and `png`, and the studio said the module
5326
+ * was not found.
5327
+ *
5328
+ * So: one function, and never a template string. `Internal.createValPathOfItem`
5329
+ * is the rule itself — `JSON.stringify` quotes a string and leaves a number
5330
+ * bare, which is precisely the module-path grammar — and everything here defers
5331
+ * to it rather than restating it.
5332
+ */
5333
+ function sourcePathOfChild(parent, key) {
5334
+ /**
5335
+ * A parent that is already `…?p=` gets the key with no separator.
5336
+ *
5337
+ * The search index walks from `moduleFilePath + "?p="` rather than from the
5338
+ * module file path, so that every path it produces has a module path — and
5339
+ * `createValPathOfItem` would see the separator and join with a `.`, giving
5340
+ * `?p=."title"`.
5341
+ */
5342
+ if (parent.endsWith(Internal.ModuleFilePathSep)) {
5343
+ return "".concat(parent).concat(JSON.stringify(key));
5344
+ }
5345
+ var path = Internal.createValPathOfItem(parent, key);
5346
+ if (path === undefined) {
5347
+ // Only when the parent is empty, which callers cannot produce: every walk
5348
+ // starts from a module file path. Thrown rather than skipped so a future
5349
+ // change that breaks that assumption is loud.
5350
+ throw new Error("Could not build a source path for '".concat(key, "' under ").concat(parent));
5351
+ }
5352
+ return path;
5353
+ }
5354
+
5355
+ /**
5356
+ * The same thing, for callers holding the module file path and module path apart.
5357
+ *
5358
+ * `ModulePath` is empty at the module root, which is the case both broken copies
5359
+ * got wrong: there is no separator in the path yet, so the key is the first
5360
+ * segment and still has to be quoted.
5361
+ */
5362
+ function concatModulePath(moduleFilePath, modulePath, key) {
5363
+ return sourcePathOfChild(modulePath ? Internal.joinModuleFilePathAndModulePath(moduleFilePath, modulePath) : moduleFilePath, key);
5364
+ }
5365
+
5366
+ /**
5367
+ * Traverses a schema and source pair, calling a callback for each leaf node.
5368
+ * Handles all schema types including primitives, objects, arrays, records, unions, richtext, files, images, etc.
5369
+ *
5370
+ * @param source - The JSON source data
5371
+ * @param schema - The serialized schema
5372
+ * @param path - The current source path
5373
+ * @param callback - Function called for each traversable node with { source, schema, path }
5374
+ */
5375
+ function traverseSchemaSource(source, schema, path, callback) {
5376
+ if (!(schema !== null && schema !== void 0 && schema.type)) {
5377
+ throw new Error("Schema not found for " + path);
5378
+ }
5379
+ if (source === null) {
5380
+ return;
5381
+ }
5382
+
5383
+ // An un-loaded `.jsonValues()` entry is an opaque `{_type:"json"}` marker, not
5384
+ // the value its schema describes. Skip it — its content is traversed once
5385
+ // loaded, since the sync engine substitutes it in place of the marker.
5386
+ //
5387
+ // Without this the marker falls through to whichever branch its ITEM schema
5388
+ // selects: an object/record item walks the marker's OWN keys, so an entry
5389
+ // schema with a field named `_type` or `patch_id` would index the marker's
5390
+ // internals as if they were content.
5391
+ if (Internal.isJson(source)) {
5392
+ return;
5393
+ }
5394
+
5395
+ // Handle primitives
5396
+ if (schema.type === "string") {
5397
+ if (typeof source === "string") {
5398
+ callback({
5399
+ source: source,
5400
+ schema: schema,
5401
+ path: path
5402
+ });
5403
+ }
5404
+ return;
5405
+ }
5406
+ if (schema.type === "number") {
5407
+ if (typeof source === "number") {
5408
+ callback({
5409
+ source: source,
5410
+ schema: schema,
5411
+ path: path
5412
+ });
5413
+ }
5414
+ return;
5415
+ }
5416
+ if (schema.type === "boolean") {
5417
+ if (typeof source === "boolean") {
5418
+ callback({
5419
+ source: source,
5420
+ schema: schema,
5421
+ path: path
5422
+ });
5423
+ }
5424
+ return;
5425
+ }
5426
+
5427
+ // Handle richtext - flatten and call callback
5428
+ if (schema.type === "richtext") {
5429
+ callback({
5430
+ source: source,
5431
+ schema: schema,
5432
+ path: path
5433
+ });
5434
+ return;
5435
+ }
5436
+
5437
+ // Handle file/image
5438
+ if (schema.type === "file" || schema.type === "image") {
5439
+ if (source && _typeof(source) === "object" && "path" in source && typeof source.path === "string") {
5440
+ callback({
5441
+ source: source,
5442
+ schema: schema,
5443
+ path: path
5444
+ });
5445
+ }
5446
+ return;
5447
+ }
5448
+
5449
+ // Handle date
5450
+ if (schema.type === "date") {
5451
+ if (typeof source === "string") {
5452
+ callback({
5453
+ source: source,
5454
+ schema: schema,
5455
+ path: path
5456
+ });
5457
+ }
5458
+ return;
5459
+ }
5460
+
5461
+ // Handle dateTime
5462
+ if (schema.type === "dateTime") {
5463
+ if (typeof source === "string") {
5464
+ callback({
5465
+ source: source,
5466
+ schema: schema,
5467
+ path: path
5468
+ });
5469
+ }
5470
+ return;
5471
+ }
5472
+
5473
+ // Handle color
5474
+ if (schema.type === "color") {
5475
+ if (typeof source === "string") {
5476
+ callback({
5477
+ source: source,
5478
+ schema: schema,
5479
+ path: path
5480
+ });
5481
+ }
5482
+ return;
5483
+ }
5484
+
5485
+ // Handle code
5486
+ if (schema.type === "code") {
5487
+ if (typeof source === "string") {
5488
+ callback({
5489
+ source: source,
5490
+ schema: schema,
5491
+ path: path
5492
+ });
5493
+ }
5494
+ return;
5495
+ }
5496
+
5497
+ // Handle keyOf
5498
+ if (schema.type === "keyOf") {
5499
+ if (typeof source === "string" || typeof source === "number") {
5500
+ callback({
5501
+ source: source,
5502
+ schema: schema,
5503
+ path: path
5504
+ });
5505
+ }
5506
+ return;
5507
+ }
5508
+
5509
+ // Handle literal
5510
+ if (schema.type === "literal") {
5511
+ callback({
5512
+ source: source,
5513
+ schema: schema,
5514
+ path: path
5515
+ });
5516
+ return;
5517
+ }
5518
+
5519
+ // Handle route
5520
+ if (schema.type === "route") {
5521
+ if (typeof source === "string") {
5522
+ callback({
5523
+ source: source,
5524
+ schema: schema,
5525
+ path: path
5526
+ });
5527
+ }
5528
+ return;
5529
+ }
5530
+
5531
+ // Handle array
5532
+ if (schema.type === "array") {
5533
+ if (!Array.isArray(source)) {
5534
+ return;
5535
+ }
5536
+ if (!schema.item) {
5537
+ throw new Error("Schema (" + schema.type + ") item not found for " + path);
5538
+ }
5539
+ for (var i = 0; i < source.length; i++) {
5540
+ var subPath = sourcePathOfChild(path, i);
5541
+ traverseSchemaSource(source[i], schema.item, subPath, callback);
5542
+ }
5543
+ return;
5544
+ }
5545
+
5546
+ // Handle object, record and settings
5547
+ if (schema.type === "object" || schema.type === "record" ||
5548
+ // Settings walks like an object, and starting from the SOURCE is what makes
5549
+ // its optional keys work: an absent section has nothing to traverse.
5550
+ schema.type === "settings") {
5551
+ if (_typeof(source) !== "object" || source === null || Array.isArray(source)) {
5552
+ return;
5553
+ }
5554
+ for (var key in source) {
5555
+ var _schema$items;
5556
+ var subSchema = schema.type === "record" ? schema.item : (_schema$items = schema.items) === null || _schema$items === void 0 ? void 0 : _schema$items[key];
5557
+ if (!subSchema) {
5558
+ continue;
5559
+ }
5560
+ var _subPath = sourcePathOfChild(path, key);
5561
+ traverseSchemaSource(source[key], subSchema, _subPath, callback);
5562
+ }
5563
+ return;
5564
+ }
5565
+
5566
+ // Handle union
5567
+ if (schema.type === "union") {
5568
+ var schemaKey = schema.key;
5569
+ if (typeof schemaKey === "string") {
5570
+ // Tagged union - find matching sub-schema
5571
+ if (source && _typeof(source) === "object" && !Array.isArray(source) && schemaKey in source) {
5572
+ var itemKey = source[schemaKey];
5573
+ if (typeof itemKey === "string") {
5574
+ var schemaOfItem = schema.items.filter(function (item) {
5575
+ return item.type === "object";
5576
+ }).find(function (item) {
5577
+ var itemKeySchema = item.items[schemaKey];
5578
+ if ((itemKeySchema === null || itemKeySchema === void 0 ? void 0 : itemKeySchema.type) === "literal") {
5579
+ return itemKeySchema.value === itemKey;
5580
+ }
5581
+ return false;
5582
+ });
5583
+ if (schemaOfItem) {
5584
+ traverseSchemaSource(source, schemaOfItem, path, callback);
5585
+ }
5586
+ }
5587
+ }
5588
+ } else {
5589
+ // Literal union - treat as primitive
5590
+ if (typeof source === "string") {
5591
+ callback({
5592
+ source: source,
5593
+ schema: schema,
5594
+ path: path
5595
+ });
5596
+ }
5597
+ }
5598
+ return;
5599
+ }
5600
+
5601
+ // Exhaustive check
5602
+ var exhaustiveCheck = schema;
5603
+ throw new Error("Unsupported schema type: " + JSON.stringify(exhaustiveCheck));
5604
+ }
5605
+
5606
+ /**
5607
+ * Flattens richtext source to a plain string, extracting only text content.
5608
+ * Used for indexing richtext content in search.
5609
+ */
5610
+ function flattenRichText(source) {
5611
+ var res = "";
5612
+ function rec(child) {
5613
+ if (typeof child === "string") {
5614
+ res += child;
5615
+ } else {
5616
+ if (child && _typeof(child) === "object" && "children" in child && Array.isArray(child.children)) {
5617
+ var _iterator = _createForOfIteratorHelper(child.children),
5618
+ _step;
5619
+ try {
5620
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5621
+ var c = _step.value;
5622
+ rec(c);
5623
+ }
5624
+ } catch (err) {
5625
+ _iterator.e(err);
5626
+ } finally {
5627
+ _iterator.f();
5628
+ }
5629
+ }
5630
+ }
5631
+ }
5632
+ rec({
5633
+ children: source
5634
+ });
5635
+ return res;
5636
+ }
5637
+
5638
+ /**
5639
+ * Resolves a file ref (local path or remote URL) to a clean local-style path.
5640
+ */
5641
+ function cleanRefPath(ref) {
5642
+ var remoteRefRes = Internal.remote.splitRemoteRef(ref);
5643
+ return remoteRefRes.status === "success" ? "/".concat(remoteRefRes.filePath) : ref;
5644
+ }
5645
+
5646
+ /**
5647
+ * Extract a human-readable filename from a file ref (local path or remote URL).
5648
+ * Handles both remote refs (via splitRemoteRef) and plain `/public/...` paths.
5649
+ */
5650
+ function getFilenameFromRef(ref) {
5651
+ var cleanPath = cleanRefPath(ref);
5652
+ return cleanPath.split("/").pop() || cleanPath;
5653
+ }
5654
+
5655
+ /**
5656
+ * Parse a file ref into its constituent parts: a clean path, filename, and
5657
+ * folder (the path relative to `/public`).
5658
+ *
5659
+ * The `folder` strips the standard `/public` prefix so it shows a
5660
+ * concise location like `/images` instead of `/public/images`.
5661
+ */
5662
+ function getRefParts(ref) {
5663
+ var cleanPath = cleanRefPath(ref);
5664
+ var filename = cleanPath.split("/").pop() || cleanPath;
5665
+ // Only strip a leading "/public" path segment: "/publicity/a.png" must keep its folder
5666
+ var folder = cleanPath.replace(/^\/public(?=\/|$)/, "").replace(/\/[^/]+$/, "") || "/";
5667
+ return {
5668
+ cleanPath: cleanPath,
5669
+ filename: filename,
5670
+ folder: folder
5671
+ };
5672
+ }
5673
+
5674
+ /**
5675
+ * The search index and the labels to render for its hits.
5676
+ *
5677
+ * Kept as a plain module rather than living inside a worker so it can be tested:
5678
+ * a worker entry runs `self.onmessage` on import, which no test environment here
5679
+ * provides.
5680
+ *
5681
+ * In `@valbuild/shared` rather than the Studio because there are now two
5682
+ * realms searching the same content: the Studio's `SearchStore`, which keeps an
5683
+ * index alive in a worker and re-indexes a module at a time, and the MCP
5684
+ * `search_content` tool, which builds one per call and throws it away. What
5685
+ * counts as a document, and what a hit is labelled, must not differ between
5686
+ * them — an agent and an editor searching the same project should find the same
5687
+ * things.
5688
+ */
5689
+
5690
+ /** An index with nothing in it. Fill it with {@link indexModule}. */
5691
+ function createSearchIndex() {
5692
+ return {
5693
+ index: new FlexSearch.Index({
5694
+ tokenize: "forward"
5695
+ }),
5696
+ pathToLabel: new Map(),
5697
+ docsByModule: new Map()
5698
+ };
5699
+ }
5700
+
5701
+ /**
5702
+ * Index one module, replacing whatever was previously indexed for it.
5703
+ *
5704
+ * Remove-then-add rather than `update`, because the set of paths in a module is
5705
+ * not stable: deleting an array item or a record entry means documents that must
5706
+ * disappear, and `update` only revises ids it is given.
5707
+ *
5708
+ * `.jsonValues()` entries are indexed only once their content is loaded — an
5709
+ * un-loaded entry is an opaque marker that {@link traverseSchemaSource} skips, so
5710
+ * the index is naturally PARTIAL and grows as batches land. That is why the search
5711
+ * UI loads the entries on the first query and re-indexes (debounced) as they
5712
+ * arrive, rather than pretending an empty result set is an answer.
5713
+ */
5714
+ function indexModule(searchIndex, moduleFilePath, source, schema) {
5715
+ var index = searchIndex.index,
5716
+ pathToLabel = searchIndex.pathToLabel,
5717
+ docsByModule = searchIndex.docsByModule;
5718
+ removeModule(searchIndex, moduleFilePath);
5719
+ var docs = new Set();
5720
+ docsByModule.set(moduleFilePath, docs);
5721
+ var path = moduleFilePath + "?p=";
5722
+ traverseSchemaSource(source, schema, path, function (_ref) {
5723
+ var source = _ref.source,
5724
+ schema = _ref.schema,
5725
+ path = _ref.path;
5726
+ if (source === null) {
5727
+ return;
5728
+ }
5729
+ var searchText = "";
5730
+ var label = "";
5731
+
5732
+ // Handle primitives
5733
+ if (schema.type === "string" || schema.type === "number" || schema.type === "boolean" || schema.type === "date" || schema.type === "dateTime" || schema.type === "color" || schema.type === "code" || schema.type === "keyOf" || schema.type === "route") {
5734
+ var _source$toString, _source$toString2;
5735
+ searchText = (_source$toString = source === null || source === void 0 ? void 0 : source.toString()) !== null && _source$toString !== void 0 ? _source$toString : "";
5736
+ label = (_source$toString2 = source === null || source === void 0 ? void 0 : source.toString()) !== null && _source$toString2 !== void 0 ? _source$toString2 : "";
5737
+ } else if (schema.type === "literal") {
5738
+ searchText = schema.value.toString();
5739
+ label = schema.value.toString();
5740
+ }
5741
+ // Handle richtext - flatten to get text content
5742
+ else if (schema.type === "richtext") {
5743
+ searchText = flattenRichText(source);
5744
+ // Use first 50 chars as label
5745
+ label = searchText.substring(0, 50) || "richtext";
5746
+ }
5747
+ // Handle file/image
5748
+ else if (schema.type === "file" || schema.type === "image") {
5749
+ if (source !== null && _typeof(source) === "object" && "path" in source && typeof source.path === "string") {
5750
+ // The label is the bare filename - the folder is shown separately in
5751
+ // the UI - but both are searchable.
5752
+ var _getRefParts = getRefParts(source.path),
5753
+ filename = _getRefParts.filename,
5754
+ folder = _getRefParts.folder;
5755
+ var alt = "alt" in source ? source.alt : "";
5756
+ searchText = filename + " " + folder + " " + alt;
5757
+ label = filename;
5758
+ }
5759
+ }
5760
+
5761
+ // Add to index if we have search text
5762
+ if (searchText) {
5763
+ var _Internal$splitModule = Internal.splitModuleFilePathAndModulePath(path),
5764
+ _Internal$splitModule2 = _slicedToArray(_Internal$splitModule, 2),
5765
+ modulePath = _Internal$splitModule2[1];
5766
+ var cleanPath = fastRemoveNonWordChars(modulePath) + " ";
5767
+ index.add(path, cleanPath + " " + path + " " + searchText);
5768
+ pathToLabel.set(path, label);
5769
+ docs.add(path);
5770
+ }
5771
+ });
5772
+ }
5773
+
5774
+ /**
5775
+ * Drop everything indexed for one module.
5776
+ *
5777
+ * Also used for a module that has gone away entirely — otherwise its documents
5778
+ * stay searchable and a hit navigates to a path that no longer exists.
5779
+ */
5780
+ function removeModule(searchIndex, moduleFilePath) {
5781
+ var index = searchIndex.index,
5782
+ pathToLabel = searchIndex.pathToLabel,
5783
+ docsByModule = searchIndex.docsByModule;
5784
+ var existing = docsByModule.get(moduleFilePath);
5785
+ if (existing === undefined) return;
5786
+ var _iterator = _createForOfIteratorHelper(existing),
5787
+ _step;
5788
+ try {
5789
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5790
+ var id = _step.value;
5791
+ index.remove(id);
5792
+ pathToLabel["delete"](id);
5793
+ }
5794
+ } catch (err) {
5795
+ _iterator.e(err);
5796
+ } finally {
5797
+ _iterator.f();
5798
+ }
5799
+ docsByModule["delete"](moduleFilePath);
5800
+ }
5801
+
5802
+ /**
5803
+ * Index every module, from scratch.
5804
+ *
5805
+ * Now a loop over {@link indexModule} rather than its own walk, so the full
5806
+ * build and the incremental one cannot drift in what they consider a document.
5807
+ */
5808
+ function buildSearchIndex(modules) {
5809
+ var searchIndex = createSearchIndex();
5810
+ for (var moduleFilePathS in modules) {
5811
+ var moduleFilePath = moduleFilePathS;
5812
+ var _modules$moduleFilePa = modules[moduleFilePath],
5813
+ source = _modules$moduleFilePa.source,
5814
+ schema = _modules$moduleFilePa.schema;
5815
+ indexModule(searchIndex, moduleFilePath, source, schema);
5816
+ }
5817
+ return searchIndex;
5818
+ }
5819
+ var NON_CHARS = new Set(["/", "-", "_", ".", ":", "?", "&", "=", "@", '"', "'"]);
5820
+ function fastRemoveNonWordChars(str) {
5821
+ var result = "";
5822
+ for (var i = 0; i < str.length; i++) {
5823
+ var _char = str[i];
5824
+ if (!NON_CHARS.has(_char)) {
5825
+ result += _char;
5826
+ } else {
5827
+ result += " ";
5828
+ }
5829
+ }
5830
+ return result;
5831
+ }
5832
+
5833
+ /**
5834
+ * How many hits are counted before `total` stops being a count.
5835
+ *
5836
+ * FlexSearch stops as soon as it has the number of ids it was asked for, so a
5837
+ * `total` taken from a page-sized search is just the page size again — which
5838
+ * reads as "that is all there is" to anyone who did not write it. Counting is
5839
+ * asking for more ids than the page needs, so it costs an array of ids and no
5840
+ * more; this bound is where that stops being free, and `totalIsLowerBound` says
5841
+ * it was reached rather than letting the number quietly lie.
5842
+ */
5843
+ var MAX_COUNTED_RESULTS = 10000;
5844
+ function performSearch(searchIndex, query) {
5845
+ var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
5846
+ var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
5847
+ if (searchIndex === null || !query.trim()) {
5848
+ return {
5849
+ results: [],
5850
+ total: 0,
5851
+ totalIsLowerBound: false
5852
+ };
5853
+ }
5854
+ var index = searchIndex.index,
5855
+ pathToLabel = searchIndex.pathToLabel;
5856
+ var counted = Math.max(offset + limit, MAX_COUNTED_RESULTS);
5857
+ var searchResults = index.search(query, {
5858
+ limit: counted
5859
+ });
5860
+ var total = searchResults.length;
5861
+ var paged = searchResults.slice(offset, offset + limit);
5862
+ return {
5863
+ results: paged.map(function (id) {
5864
+ return {
5865
+ path: id,
5866
+ label: pathToLabel.get(id) || id
5867
+ };
5868
+ }),
5869
+ total: total,
5870
+ totalIsLowerBound: total >= counted
5871
+ };
5872
+ }
5873
+
5874
+ export { Api, BinaryFileRef, CodeOptions, ColorOptions, DEFAULT_ERROR_MESSAGE, DateOptions, ENCODE_DEFAULTS, ENCODE_MIME_TYPE_OF, FileOptions, HistoricalCommit, HistoricalModule, HistoricalPatchSet, HistoryError, ImageEncodeOption, ImageOptions, JSONValue, JSON_ENTRIES_BATCH_MAX, ModuleComparison, NEVER_ENCODED, ParentRef$1 as ParentRef, Patch, PatchBlock, PatchGroup, PatchId, PatchJSON, RemirrorBr, RemirrorBulletList, RemirrorHeading, RemirrorImage, RemirrorJSON, RemirrorLinkMark, RemirrorListItem, RemirrorOrderedList, RemirrorParagraph, RemirrorText, RemirrorTextMark, RestoreVerdict, RichTextOptions, SerializedArraySchema, SerializedBooleanSchema, SerializedCodeSchema, SerializedColorSchema, SerializedDateSchema, SerializedDateTimeSchema, SerializedFileSchema, SerializedImageSchema, SerializedKeyOfSchema, SerializedLiteralSchema, SerializedNumberSchema, SerializedObjectSchema, SerializedRecordSchema, SerializedRichTextSchema, SerializedRouteSchema, SerializedSchema, SerializedSettingsSchema, SerializedStringSchema, SerializedUnionSchema, SharedValConfig, VAL_AI_SESSION_STORAGE_KEY, VAL_CANVAS_MESSAGE, VAL_CANVAS_PARAM, VAL_CONFIG_SESSION_STORAGE_KEY, VAL_ENABLE_COOKIE_NAME, VAL_SESSION_COOKIE, VAL_STATE_COOKIE, VAL_THEME_SESSION_STORAGE_KEY, ValCommit, ValDeployment, buildDuplicatePatch, buildEmptyAtPathPatch, buildFileRefValue, buildImageGalleryPatch, buildRemoveImageGalleryEntryPatch, buildSearchIndex, checkCompatibility, chooseEncoded, concatModulePath, createRegExpFromPattern, createSearchIndex, createValClient, describeContainerAtPath, emptyOf, explainIncompatible, filterBlockingValidationErrors, filterRoutesByPatterns, findSimilar, fitWithin, flattenRichText, getErrorMessageFromUnknownJson, getFilenameFromRef, getInlineImgInfo, getNextAppRouterSitemapTree, getNextAppRouterSourceFolder, getPatternFromModuleFilePath, getRefParts, getRoutesOf, getRoutesWithModulePaths, getSourceAt, indexModule, isMimeTypeAccepted, isRemoteSchema, isSkippedSource, isValCanvasFrame, isValCanvasPageMessage, isValCanvasStudioMessage, levenshtein, newestCommitSha, parseRoutePattern, partitionValidationErrors, performSearch, remirrorToRichTextSource, removeModule, resolveEncodeSettings, resolveSchemaSourceFixForError, resolveSchemaSourceFixes, resolveSerializedSchemaAtPath, richTextToRemirror, safeParsePatch, sourcePathOfChild, toolNames, traverseSchemaSource, urlOf, validateRoutePatterns, withExtension, withValCanvasParam };