monorise 2.0.0-dev.1 → 2.0.0-dev.3

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.
@@ -26,6 +26,7 @@ declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C
26
26
  baseSchema: z.ZodObject<B, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_33 ? { [k_6 in keyof T_33]: T_33[k_6]; } : never, z.baseObjectInputType<B> extends infer T_34 ? { [k_7 in keyof T_34]: T_34[k_7]; } : never>;
27
27
  createSchema?: CO | undefined;
28
28
  searchableFields?: (keyof B)[] | undefined;
29
+ search?: SearchConfig<keyof B> | undefined;
29
30
  uniqueFields?: (keyof B)[] | undefined;
30
31
  mutual?: {
31
32
  subscribes?: {
@@ -121,6 +122,41 @@ declare enum Entity {
121
122
  interface EntitySchemaMap {
122
123
  [key: string]: Record<string, any>;
123
124
  }
125
+ /**
126
+ * @description How a field's value is matched. `words`: split on spaces and
127
+ * symbols, and each word is matched from its start ("jo" finds "John").
128
+ */
129
+ type SearchMatch = 'words';
130
+ /**
131
+ * @description Search settings shared by an entity's `search` config and the
132
+ * `search` key of `monorise.config.ts`. An entity's value replaces the
133
+ * global one.
134
+ */
135
+ interface SearchSettings {
136
+ /**
137
+ * @description Most words indexed per entity, counted across `fields` in
138
+ * order after duplicates and `ignoreWords` are dropped. Words past it can't
139
+ * be searched. Each word is a copy of the entity that every update of the
140
+ * entity rewrites. Defaults to `DEFAULT_MAX_WORDS` (8).
141
+ */
142
+ maxWords?: number;
143
+ /**
144
+ * @description Words that are never indexed and are skipped in queries
145
+ * (also known as stop words). Replaces the default list: spread
146
+ * `DEFAULT_IGNORE_WORDS` to extend it, or pass `[]` to ignore nothing.
147
+ */
148
+ ignoreWords?: readonly string[];
149
+ }
150
+ interface SearchConfig<K extends PropertyKey = string> extends SearchSettings {
151
+ /**
152
+ * @description Fields to index, most-searched first: earlier fields fill
153
+ * `maxWords` first.
154
+ */
155
+ fields: {
156
+ field: K;
157
+ match?: SearchMatch;
158
+ }[];
159
+ }
124
160
  /**
125
161
  * @description Configuration for a mutual relationship between two entities.
126
162
  * Defines the schema for mutualData validation. Define once, reference from both entity configs.
@@ -284,7 +320,28 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
284
320
  * @description Minimal schema required to create an entity
285
321
  */
286
322
  createSchema?: CO;
323
+ /**
324
+ * @description (Optional) Fields `?query=` matches against, by scanning every
325
+ * entity of this type. Use `search` instead to look matches up by word
326
+ * without the scan. Can't be combined with `search`.
327
+ */
287
328
  searchableFields?: (keyof B)[];
329
+ /**
330
+ * @description (Optional) Index these fields by word, so `?query=` reads
331
+ * only the entities that contain the words searched for. Can't be combined
332
+ * with `searchableFields`.
333
+ *
334
+ * `maxWords` and `ignoreWords` fall back to the `search` settings in
335
+ * `monorise.config.ts`, then to the built-in defaults.
336
+ *
337
+ * @example
338
+ * ```ts
339
+ * search: {
340
+ * fields: [{ field: 'displayName' }, { field: 'email' }],
341
+ * },
342
+ * ```
343
+ */
344
+ search?: SearchConfig<keyof B>;
288
345
  uniqueFields?: (keyof B)[];
289
346
  /**
290
347
  * @description Define mutual relationship of this entity with other entities
@@ -704,6 +761,74 @@ type ApiKeyRoutePermission = keyof ApiKeyRoutePermissions extends never ? string
704
761
  */
705
762
  type ApiKeyPolicies = Record<string, ApiKeyPolicy>;
706
763
 
764
+ declare const DEFAULT_MAX_WORDS = 8;
765
+ /**
766
+ * @description Words ignored unless an entity or `monorise.config.ts` sets
767
+ * its own list. Deliberately short: an ignored word can never be found on its
768
+ * own, so words that are also names ("an", "will", "may") are left out.
769
+ */
770
+ declare const DEFAULT_IGNORE_WORDS: readonly string[];
771
+ type ResolvedSearchConfig = {
772
+ fields: {
773
+ field: string;
774
+ match: SearchMatch;
775
+ }[];
776
+ maxWords: number;
777
+ ignoreWords: string[];
778
+ };
779
+ /**
780
+ * @description Lowercases and strips accents, so "José" and "jose" match.
781
+ */
782
+ declare function foldText(text: string): string;
783
+ /**
784
+ * @description Splits on anything that isn't a letter or digit:
785
+ * "example@mail.com" becomes ["example", "mail", "com"].
786
+ */
787
+ declare function splitWords(text: string): string[];
788
+ /**
789
+ * @description An entity's `search` config with the `monorise.config.ts`
790
+ * settings and built-in defaults filled in.
791
+ */
792
+ declare function resolveSearchConfig(search: SearchConfig<PropertyKey>, defaults?: SearchSettings): ResolvedSearchConfig;
793
+ /**
794
+ * @description Throws on settings the index can't use. `where` names the
795
+ * config in the message.
796
+ */
797
+ declare function validateSearchSettings(settings: SearchSettings, where: string): void;
798
+ /**
799
+ * @description Changes whenever the words an entity is indexed by would.
800
+ * Only used to notice that, so it doesn't need to be cryptographic (cyrb53).
801
+ */
802
+ declare function searchConfigHash(config: ResolvedSearchConfig): string;
803
+ /**
804
+ * @description The words an entity can be found by: fields in config order,
805
+ * without one-letter words, ignored words and duplicates, up to `maxWords`.
806
+ * Writing the index and checking a match both use this, so a word past the
807
+ * cap is never found, whichever word a query is looked up by.
808
+ */
809
+ declare function indexedWords(data: Record<string, unknown> | undefined, config: ResolvedSearchConfig): string[];
810
+ type SearchTerm = {
811
+ /** Each must be the start of one of the entity's indexed words. */
812
+ words: string[];
813
+ /** Must also appear as typed in one field: quoted, or joined by symbols. */
814
+ phrase?: string;
815
+ };
816
+ type SearchPlan = {
817
+ /** The word whose index rows are read. Without one, nothing matches. */
818
+ anchor?: string;
819
+ terms: SearchTerm[];
820
+ };
821
+ /**
822
+ * @description Parses a query. Plain words match from the start of a word,
823
+ * in any order. Quoted text and text joined by symbols ("example@mail.com")
824
+ * must also appear exactly. The anchor is the longest word.
825
+ */
826
+ declare function planSearch(query: string, ignoreWords: readonly string[]): SearchPlan;
827
+ /**
828
+ * @description Whether an entity's data matches a planned query.
829
+ */
830
+ declare function matchesSearch(data: Record<string, unknown> | undefined, plan: SearchPlan, config: ResolvedSearchConfig): boolean;
831
+
707
832
  /**
708
833
  * @description Built-in policy: read, write and delete on every entity and
709
834
  * relationship, plus every custom route. Every key in the legacy array form of
@@ -816,4 +941,4 @@ declare const validateApiKeyPolicies: (policies: unknown, entityConfigs: Record<
816
941
  */
817
942
  declare const defineApiKeyPolicies: (policies: ApiKeyPolicies) => ApiKeyPolicies;
818
943
 
819
- export { type AdjustmentCondition, type AdjustmentConditionFn, type ApiKeyAccessLevel, type ApiKeyEntityAccess, type ApiKeyEntityGrant, type ApiKeyEntityTags, type ApiKeyFieldAccess, type ApiKeyFieldList, type ApiKeyMutualAccess, type ApiKeyMutualDataFields, type ApiKeyMutualGrant, type ApiKeyPolicies, type ApiKeyPolicy, type ApiKeyPolicyEntityConfig, type ApiKeyRoutePermission, type ApiKeyRoutePermissions, type ApiKeySystemField, type CompiledApiKeyPolicy, type CreatedEntity, DEFAULT_API_KEY_POLICY, type DraftEntity, Entity, type EntitySchemaMap, FULL_API_KEY_POLICY, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, compileApiKeyPolicy, createEntityConfig, createMutualConfig, defineApiKeyPolicies, resolveEffectiveMutualSchema, validateApiKeyPolicies };
944
+ export { type AdjustmentCondition, type AdjustmentConditionFn, type ApiKeyAccessLevel, type ApiKeyEntityAccess, type ApiKeyEntityGrant, type ApiKeyEntityTags, type ApiKeyFieldAccess, type ApiKeyFieldList, type ApiKeyMutualAccess, type ApiKeyMutualDataFields, type ApiKeyMutualGrant, type ApiKeyPolicies, type ApiKeyPolicy, type ApiKeyPolicyEntityConfig, type ApiKeyRoutePermission, type ApiKeyRoutePermissions, type ApiKeySystemField, type CompiledApiKeyPolicy, type CreatedEntity, DEFAULT_API_KEY_POLICY, DEFAULT_IGNORE_WORDS, DEFAULT_MAX_WORDS, type DraftEntity, Entity, type EntitySchemaMap, FULL_API_KEY_POLICY, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type ResolvedSearchConfig, type SearchConfig, type SearchMatch, type SearchPlan, type SearchSettings, type SearchTerm, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, compileApiKeyPolicy, createEntityConfig, createMutualConfig, defineApiKeyPolicies, foldText, indexedWords, matchesSearch, planSearch, resolveEffectiveMutualSchema, resolveSearchConfig, searchConfigHash, splitWords, validateApiKeyPolicies, validateSearchSettings };
@@ -37,6 +37,144 @@ var Entity = /* @__PURE__ */ ((Entity2) => {
37
37
 
38
38
  // utils/index.ts
39
39
  import { z } from "zod";
40
+
41
+ // utils/search.ts
42
+ var DEFAULT_MAX_WORDS = 8;
43
+ var DEFAULT_IGNORE_WORDS = [
44
+ "the",
45
+ "and",
46
+ "of",
47
+ "in",
48
+ "to",
49
+ "for",
50
+ "with",
51
+ "on",
52
+ "at",
53
+ "by",
54
+ "from",
55
+ "or",
56
+ "is",
57
+ "are",
58
+ "was",
59
+ "be",
60
+ "as",
61
+ "it",
62
+ "this",
63
+ "that"
64
+ ];
65
+ var MIN_WORD_LENGTH = 2;
66
+ var NON_WORD = /[^\p{L}\p{N}]+/u;
67
+ var MARKS = new RegExp("\\p{M}", "gu");
68
+ function foldText(text) {
69
+ return text.normalize("NFKD").replace(MARKS, "").toLowerCase();
70
+ }
71
+ function splitWords(text) {
72
+ return foldText(text).split(NON_WORD).filter(Boolean);
73
+ }
74
+ var collapseSpaces = (text) => text.trim().replace(/\s+/g, " ");
75
+ function resolveSearchConfig(search, defaults) {
76
+ var _a, _b, _c, _d;
77
+ const ignoreWords = (_b = (_a = search.ignoreWords) != null ? _a : defaults == null ? void 0 : defaults.ignoreWords) != null ? _b : DEFAULT_IGNORE_WORDS;
78
+ return {
79
+ fields: search.fields.map(({ field, match }) => ({
80
+ field: String(field),
81
+ match: match != null ? match : "words"
82
+ })),
83
+ maxWords: (_d = (_c = search.maxWords) != null ? _c : defaults == null ? void 0 : defaults.maxWords) != null ? _d : DEFAULT_MAX_WORDS,
84
+ ignoreWords: [...new Set(ignoreWords.map(foldText))].sort()
85
+ };
86
+ }
87
+ function validateSearchSettings(settings, where) {
88
+ const { maxWords, ignoreWords } = settings;
89
+ if (maxWords !== void 0 && (!Number.isInteger(maxWords) || maxWords < 1)) {
90
+ throw new Error(`${where}: 'search.maxWords' must be a positive integer.`);
91
+ }
92
+ if (ignoreWords !== void 0 && (!Array.isArray(ignoreWords) || ignoreWords.some((word) => typeof word !== "string"))) {
93
+ throw new Error(
94
+ `${where}: 'search.ignoreWords' must be an array of strings.`
95
+ );
96
+ }
97
+ }
98
+ function searchConfigHash(config) {
99
+ const input = JSON.stringify(config);
100
+ let h1 = 3735928559;
101
+ let h2 = 1103547991;
102
+ for (let i = 0; i < input.length; i++) {
103
+ const char = input.charCodeAt(i);
104
+ h1 = Math.imul(h1 ^ char, 2654435761);
105
+ h2 = Math.imul(h2 ^ char, 1597334677);
106
+ }
107
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
108
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
109
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
110
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
111
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
112
+ }
113
+ function fieldValues(data, field) {
114
+ const value = data == null ? void 0 : data[field];
115
+ const values = Array.isArray(value) ? value : [value];
116
+ return values.filter((v) => typeof v === "string" || typeof v === "number").map(String);
117
+ }
118
+ function indexedWords(data, config) {
119
+ const ignore = new Set(config.ignoreWords);
120
+ const words = /* @__PURE__ */ new Set();
121
+ for (const { field } of config.fields) {
122
+ for (const value of fieldValues(data, field)) {
123
+ for (const word of splitWords(value)) {
124
+ if (word.length < MIN_WORD_LENGTH || ignore.has(word)) continue;
125
+ words.add(word);
126
+ if (words.size === config.maxWords) return [...words];
127
+ }
128
+ }
129
+ }
130
+ return [...words];
131
+ }
132
+ function planSearch(query, ignoreWords) {
133
+ var _a;
134
+ const ignore = new Set(ignoreWords);
135
+ const parsed = [];
136
+ const termPattern = /"([^"]+)"|(\S+)/g;
137
+ for (let match = termPattern.exec(query); match; match = termPattern.exec(query)) {
138
+ parsed.push({ text: (_a = match[1]) != null ? _a : match[2], quoted: match[1] !== void 0 });
139
+ }
140
+ const terms = [];
141
+ let trailing;
142
+ parsed.forEach(({ text, quoted }, i) => {
143
+ var _a2, _b;
144
+ const parts = splitWords(text);
145
+ const words = parts.filter(
146
+ (word) => word.length >= MIN_WORD_LENGTH && !ignore.has(word)
147
+ );
148
+ if (quoted || parts.length > 1) {
149
+ terms.push({ words, phrase: collapseSpaces(foldText(text)) });
150
+ } else if (words.length) {
151
+ terms.push({ words });
152
+ } else if (i === parsed.length - 1 && ((_b = (_a2 = parts[0]) == null ? void 0 : _a2.length) != null ? _b : 0) >= MIN_WORD_LENGTH) {
153
+ trailing = parts[0];
154
+ }
155
+ });
156
+ const required = terms.flatMap((term) => term.words);
157
+ if (!required.length && trailing) {
158
+ return { anchor: trailing, terms: [...terms, { words: [trailing] }] };
159
+ }
160
+ const anchor = required.reduce(
161
+ (longest, word) => !longest || word.length > longest.length ? word : longest,
162
+ void 0
163
+ );
164
+ return { anchor, terms };
165
+ }
166
+ function matchesSearch(data, plan, config) {
167
+ if (!plan.anchor) return false;
168
+ const words = indexedWords(data, config);
169
+ const values = config.fields.flatMap(
170
+ ({ field }) => fieldValues(data, field).map((value) => collapseSpaces(foldText(value)))
171
+ );
172
+ return plan.terms.every(
173
+ ({ words: termWords, phrase }) => termWords.every((word) => words.some((w) => w.startsWith(word))) && (!phrase || values.some((value) => value.includes(phrase)))
174
+ );
175
+ }
176
+
177
+ // utils/index.ts
40
178
  function resolveEffectiveMutualSchema(mutualSchema, createMutualSchema) {
41
179
  if (!createMutualSchema) return mutualSchema;
42
180
  if (!mutualSchema) return createMutualSchema;
@@ -51,6 +189,25 @@ function makeSchema(config, effectiveMutualSchema) {
51
189
  return finalSchema;
52
190
  }
53
191
  var createEntityConfig = (config) => {
192
+ var _a;
193
+ if (config.search) {
194
+ if (config.searchableFields) {
195
+ throw new Error(
196
+ `${config.name}: 'search' and 'searchableFields' can't both be set. 'searchableFields' scans every entity on each search; 'search' looks matches up by word. Keep one.`
197
+ );
198
+ }
199
+ if (!((_a = config.search.fields) == null ? void 0 : _a.length)) {
200
+ throw new Error(`${config.name}: 'search.fields' needs at least one field.`);
201
+ }
202
+ for (const { field, match } of config.search.fields) {
203
+ if (match !== void 0 && match !== "words") {
204
+ throw new Error(
205
+ `${config.name}: 'search.fields' entry '${String(field)}' has an unknown match '${match}'. Supported: 'words'.`
206
+ );
207
+ }
208
+ }
209
+ validateSearchSettings(config.search, String(config.name));
210
+ }
54
211
  const { mutualSchema, createMutualSchema } = config.mutual || {};
55
212
  const effectiveMutualSchema = resolveEffectiveMutualSchema(
56
213
  mutualSchema,
@@ -456,13 +613,23 @@ var defineApiKeyPolicies = (policies) => {
456
613
  };
457
614
  export {
458
615
  DEFAULT_API_KEY_POLICY,
616
+ DEFAULT_IGNORE_WORDS,
617
+ DEFAULT_MAX_WORDS,
459
618
  Entity,
460
619
  FULL_API_KEY_POLICY,
461
620
  compileApiKeyPolicy,
462
621
  createEntityConfig,
463
622
  createMutualConfig,
464
623
  defineApiKeyPolicies,
624
+ foldText,
625
+ indexedWords,
626
+ matchesSearch,
627
+ planSearch,
465
628
  resolveEffectiveMutualSchema,
466
- validateApiKeyPolicies
629
+ resolveSearchConfig,
630
+ searchConfigHash,
631
+ splitWords,
632
+ validateApiKeyPolicies,
633
+ validateSearchSettings
467
634
  };
468
635
  //# sourceMappingURL=index.js.map