@open-mercato/shared 0.6.7 → 0.6.8-develop.6874.1.982d6097d8

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 (195) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +57 -6
  3. package/build.mjs +2 -4
  4. package/dist/lib/ai/safety-identifier.js +32 -0
  5. package/dist/lib/ai/safety-identifier.js.map +7 -0
  6. package/dist/lib/auth/organizationScope.js +34 -0
  7. package/dist/lib/auth/organizationScope.js.map +7 -0
  8. package/dist/lib/auth/server.js +15 -2
  9. package/dist/lib/auth/server.js.map +2 -2
  10. package/dist/lib/bootstrap/clientOnlyModules.js +55 -0
  11. package/dist/lib/bootstrap/clientOnlyModules.js.map +7 -0
  12. package/dist/lib/bootstrap/dynamicLoader.js +117 -43
  13. package/dist/lib/bootstrap/dynamicLoader.js.map +2 -2
  14. package/dist/lib/commands/command-bus.js +5 -1
  15. package/dist/lib/commands/command-bus.js.map +2 -2
  16. package/dist/lib/commands/command-interceptor-runner.js +2 -2
  17. package/dist/lib/commands/command-interceptor-runner.js.map +2 -2
  18. package/dist/lib/crud/enricher-runner.js +2 -11
  19. package/dist/lib/crud/enricher-runner.js.map +2 -2
  20. package/dist/lib/crud/factory.js +72 -9
  21. package/dist/lib/crud/factory.js.map +2 -2
  22. package/dist/lib/crud/interceptor-runner.js +2 -2
  23. package/dist/lib/crud/interceptor-runner.js.map +2 -2
  24. package/dist/lib/crud/mutation-guard-registry.js +2 -2
  25. package/dist/lib/crud/mutation-guard-registry.js.map +2 -2
  26. package/dist/lib/crud/types.js +4 -0
  27. package/dist/lib/crud/types.js.map +3 -3
  28. package/dist/lib/data/consistency.js +19 -0
  29. package/dist/lib/data/consistency.js.map +7 -0
  30. package/dist/lib/data/engine.js +37 -11
  31. package/dist/lib/data/engine.js.map +2 -2
  32. package/dist/lib/db/entityMetadata.js +26 -0
  33. package/dist/lib/db/entityMetadata.js.map +7 -0
  34. package/dist/lib/db/pg-errors.js +42 -0
  35. package/dist/lib/db/pg-errors.js.map +2 -2
  36. package/dist/lib/di/container.js +48 -6
  37. package/dist/lib/di/container.js.map +2 -2
  38. package/dist/lib/email/send.js +56 -0
  39. package/dist/lib/email/send.js.map +2 -2
  40. package/dist/lib/encryption/subscriber.js +2 -10
  41. package/dist/lib/encryption/subscriber.js.map +2 -2
  42. package/dist/lib/encryption/tenantDataEncryptionService.js +52 -17
  43. package/dist/lib/encryption/tenantDataEncryptionService.js.map +2 -2
  44. package/dist/lib/i18n/config.js +1 -1
  45. package/dist/lib/i18n/config.js.map +2 -2
  46. package/dist/lib/i18n/server.js +4 -4
  47. package/dist/lib/i18n/server.js.map +3 -3
  48. package/dist/lib/logger/extension.js +29 -0
  49. package/dist/lib/logger/extension.js.map +7 -0
  50. package/dist/lib/logger/index.js +47 -3
  51. package/dist/lib/logger/index.js.map +3 -3
  52. package/dist/lib/modules/registry.js +5 -1
  53. package/dist/lib/modules/registry.js.map +2 -2
  54. package/dist/lib/modules/surfaceFingerprint.js +47 -0
  55. package/dist/lib/modules/surfaceFingerprint.js.map +7 -0
  56. package/dist/lib/query/ciphertext-search-warning.js +45 -0
  57. package/dist/lib/query/ciphertext-search-warning.js.map +7 -0
  58. package/dist/lib/query/engine.js +54 -40
  59. package/dist/lib/query/engine.js.map +2 -2
  60. package/dist/lib/query/types.js.map +1 -1
  61. package/dist/lib/redis/connection.js +7 -2
  62. package/dist/lib/redis/connection.js.map +2 -2
  63. package/dist/lib/search/auto-indexing.js +14 -0
  64. package/dist/lib/search/auto-indexing.js.map +7 -0
  65. package/dist/lib/search/availability.js +107 -0
  66. package/dist/lib/search/availability.js.map +7 -0
  67. package/dist/lib/search/config.js +61 -2
  68. package/dist/lib/search/config.js.map +2 -2
  69. package/dist/lib/search/tokenLookup.js +46 -0
  70. package/dist/lib/search/tokenLookup.js.map +7 -0
  71. package/dist/lib/search/tokenize.js +23 -11
  72. package/dist/lib/search/tokenize.js.map +2 -2
  73. package/dist/lib/telemetry/runtime.js +35 -0
  74. package/dist/lib/telemetry/runtime.js.map +7 -0
  75. package/dist/lib/version.js +1 -1
  76. package/dist/lib/version.js.map +1 -1
  77. package/dist/lib/webhooks/body.js +57 -0
  78. package/dist/lib/webhooks/body.js.map +7 -0
  79. package/dist/lib/webhooks/inbound-types.js +1 -0
  80. package/dist/lib/webhooks/inbound-types.js.map +7 -0
  81. package/dist/lib/webhooks/index.js +13 -1
  82. package/dist/lib/webhooks/index.js.map +2 -2
  83. package/dist/lib/webhooks/verify.js +12 -7
  84. package/dist/lib/webhooks/verify.js.map +2 -2
  85. package/dist/modules/analytics.js.map +2 -2
  86. package/dist/modules/overrides.js +50 -1
  87. package/dist/modules/overrides.js.map +2 -2
  88. package/dist/modules/payment_gateways/types.js +8 -1
  89. package/dist/modules/payment_gateways/types.js.map +2 -2
  90. package/dist/modules/registry.js +1 -0
  91. package/dist/modules/registry.js.map +2 -2
  92. package/dist/modules/widgets/extension-points.js +96 -0
  93. package/dist/modules/widgets/extension-points.js.map +7 -0
  94. package/dist/security/enabledModulesRegistry.js +56 -11
  95. package/dist/security/enabledModulesRegistry.js.map +2 -2
  96. package/dist/security/featurePolicy.js +62 -0
  97. package/dist/security/featurePolicy.js.map +7 -0
  98. package/jest.config.cjs +2 -1
  99. package/package.json +19 -9
  100. package/scripts/versionSource.cjs +65 -0
  101. package/src/lib/__tests__/versionSource.test.ts +46 -0
  102. package/src/lib/ai/__tests__/llm-provider-contract.test.ts +59 -0
  103. package/src/lib/ai/__tests__/safety-identifier.test.ts +71 -0
  104. package/src/lib/ai/llm-provider.ts +33 -0
  105. package/src/lib/ai/safety-identifier.ts +73 -0
  106. package/src/lib/auth/__tests__/organizationScope.test.ts +107 -0
  107. package/src/lib/auth/__tests__/server.test.ts +23 -0
  108. package/src/lib/auth/organizationScope.ts +65 -0
  109. package/src/lib/auth/server.ts +23 -2
  110. package/src/lib/bootstrap/__tests__/clientOnlyModules.test.ts +189 -0
  111. package/src/lib/bootstrap/__tests__/dynamicLoader.aliasResolver.test.ts +98 -0
  112. package/src/lib/bootstrap/__tests__/dynamicLoader.appDi.test.ts +211 -0
  113. package/src/lib/bootstrap/__tests__/dynamicLoader.commandInterceptors.test.ts +63 -8
  114. package/src/lib/bootstrap/__tests__/dynamicLoader.generatedCacheRecovery.test.ts +256 -0
  115. package/src/lib/bootstrap/__tests__/dynamicLoader.tsconfig.test.ts +21 -1
  116. package/src/lib/bootstrap/clientOnlyModules.ts +85 -0
  117. package/src/lib/bootstrap/dynamicLoader.ts +213 -65
  118. package/src/lib/commands/__tests__/command-interceptor-runner.test.ts +28 -0
  119. package/src/lib/commands/command-bus.ts +5 -1
  120. package/src/lib/commands/command-interceptor-runner.ts +2 -2
  121. package/src/lib/crud/__tests__/crud-factory.cache-user-scope.test.ts +171 -0
  122. package/src/lib/crud/__tests__/crud-factory.test.ts +351 -0
  123. package/src/lib/crud/__tests__/mutation-guard-registry.test.ts +26 -0
  124. package/src/lib/crud/enricher-runner.ts +2 -11
  125. package/src/lib/crud/factory.ts +82 -6
  126. package/src/lib/crud/interceptor-runner.ts +2 -2
  127. package/src/lib/crud/mutation-guard-registry.ts +2 -2
  128. package/src/lib/crud/types.ts +3 -0
  129. package/src/lib/data/__tests__/consistency.test.ts +38 -0
  130. package/src/lib/data/__tests__/engine.bulk-suppress.test.ts +18 -3
  131. package/src/lib/data/consistency.ts +17 -0
  132. package/src/lib/data/engine.ts +50 -16
  133. package/src/lib/db/__tests__/entityMetadata.test.ts +38 -0
  134. package/src/lib/db/__tests__/pg-errors.test.ts +48 -0
  135. package/src/lib/db/entityMetadata.ts +43 -0
  136. package/src/lib/db/pg-errors.ts +58 -0
  137. package/src/lib/di/__tests__/container-app-di-absent.test.ts +155 -0
  138. package/src/lib/di/__tests__/container-app-di.test.ts +173 -0
  139. package/src/lib/di/__tests__/registrar-error-log.test.ts +154 -0
  140. package/src/lib/di/container.ts +72 -8
  141. package/src/lib/email/__tests__/send.test.ts +37 -1
  142. package/src/lib/email/send.ts +79 -0
  143. package/src/lib/encryption/__tests__/subscriber.test.ts +54 -2
  144. package/src/lib/encryption/__tests__/tenantDataEncryptionService.test.ts +58 -0
  145. package/src/lib/encryption/subscriber.ts +2 -14
  146. package/src/lib/encryption/tenantDataEncryptionService.ts +64 -18
  147. package/src/lib/i18n/__tests__/config.test.ts +8 -0
  148. package/src/lib/i18n/__tests__/server-dictionary-cache.test.ts +30 -0
  149. package/src/lib/i18n/__tests__/server-unbootstrapped.test.ts +29 -0
  150. package/src/lib/i18n/config.ts +2 -2
  151. package/src/lib/i18n/server.ts +6 -2
  152. package/src/lib/logger/__tests__/logger.test.ts +77 -0
  153. package/src/lib/logger/extension.ts +59 -0
  154. package/src/lib/logger/index.ts +59 -1
  155. package/src/lib/modules/__tests__/surfaceFingerprint.test.ts +122 -0
  156. package/src/lib/modules/registry.ts +10 -0
  157. package/src/lib/modules/surfaceFingerprint.ts +87 -0
  158. package/src/lib/query/__tests__/ciphertext-search-warning.test.ts +178 -0
  159. package/src/lib/query/__tests__/engine.test.ts +65 -13
  160. package/src/lib/query/ciphertext-search-warning.ts +95 -0
  161. package/src/lib/query/engine.ts +75 -58
  162. package/src/lib/query/types.ts +4 -5
  163. package/src/lib/redis/__tests__/connection.test.ts +16 -0
  164. package/src/lib/redis/connection.ts +10 -7
  165. package/src/lib/search/__tests__/availability.test.ts +211 -0
  166. package/src/lib/search/__tests__/config.test.ts +177 -0
  167. package/src/lib/search/__tests__/tokenLookup.test.ts +206 -0
  168. package/src/lib/search/__tests__/tokenize.test.ts +49 -0
  169. package/src/lib/search/auto-indexing.ts +22 -0
  170. package/src/lib/search/availability.ts +232 -0
  171. package/src/lib/search/config.ts +106 -8
  172. package/src/lib/search/tokenLookup.ts +133 -0
  173. package/src/lib/search/tokenize.ts +33 -11
  174. package/src/lib/telemetry/runtime.ts +72 -0
  175. package/src/lib/webhooks/__tests__/body.test.ts +95 -0
  176. package/src/lib/webhooks/__tests__/verify.test.ts +20 -1
  177. package/src/lib/webhooks/body.ts +70 -0
  178. package/src/lib/webhooks/inbound-types.ts +125 -0
  179. package/src/lib/webhooks/index.ts +19 -1
  180. package/src/lib/webhooks/verify.ts +17 -9
  181. package/src/modules/__tests__/nav-group-order-override.test.ts +183 -0
  182. package/src/modules/__tests__/registry.test.ts +10 -2
  183. package/src/modules/analytics.ts +7 -0
  184. package/src/modules/customer-auth.ts +1 -0
  185. package/src/modules/encryption.ts +3 -0
  186. package/src/modules/navigation/backendChrome.ts +15 -0
  187. package/src/modules/overrides.ts +103 -0
  188. package/src/modules/payment_gateways/__tests__/types.test.ts +37 -0
  189. package/src/modules/payment_gateways/types.ts +41 -0
  190. package/src/modules/registry.ts +3 -0
  191. package/src/modules/widgets/__tests__/extension-points.test.ts +101 -0
  192. package/src/modules/widgets/extension-points.ts +524 -0
  193. package/src/security/__tests__/featurePolicy.test.ts +166 -0
  194. package/src/security/enabledModulesRegistry.ts +64 -12
  195. package/src/security/featurePolicy.ts +89 -0
@@ -1,7 +1,12 @@
1
1
  import {
2
+ DEFAULT_SEARCH_MAX_FIELD_CHARS,
3
+ DEFAULT_SEARCH_MAX_TOKENS_PER_FIELD,
4
+ DEFAULT_SEARCH_MAX_TOKENS_PER_RECORD,
2
5
  DEFAULT_SEARCH_MIN_TOKEN_LENGTH,
6
+ isSearchFieldBlocklisted,
3
7
  resolveSearchConfig,
4
8
  resolveSearchMinTokenLength,
9
+ resolveSearchTokenLimits,
5
10
  } from '../config'
6
11
 
7
12
  describe('resolveSearchMinTokenLength', () => {
@@ -40,3 +45,175 @@ describe('resolveSearchMinTokenLength', () => {
40
45
  expect(resolveSearchConfig().minTokenLength).toBe(resolveSearchMinTokenLength())
41
46
  })
42
47
  })
48
+
49
+ describe('OM_SEARCH_FIELD_BLOCKLIST parsing', () => {
50
+ const originalValue = process.env.OM_SEARCH_FIELD_BLOCKLIST
51
+
52
+ afterEach(() => {
53
+ if (originalValue === undefined) {
54
+ delete process.env.OM_SEARCH_FIELD_BLOCKLIST
55
+ } else {
56
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = originalValue
57
+ }
58
+ })
59
+
60
+ it('always includes the built-in defaults', () => {
61
+ delete process.env.OM_SEARCH_FIELD_BLOCKLIST
62
+ const config = resolveSearchConfig()
63
+ expect(config.blocklistedFields).toEqual(expect.arrayContaining(['password', 'token', 'secret', 'hash']))
64
+ expect(config.entityBlocklistedFields).toEqual({})
65
+ })
66
+
67
+ it('treats an unprefixed entry as global and lowercases it', () => {
68
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = ' Body , body '
69
+ const config = resolveSearchConfig()
70
+ expect(config.blocklistedFields.filter((entry) => entry === 'body')).toHaveLength(1)
71
+ expect(config.entityBlocklistedFields).toEqual({})
72
+ })
73
+
74
+ it('routes an entityType@field entry into the per-entity map only', () => {
75
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = 'customers:customer_interaction@body'
76
+ const config = resolveSearchConfig()
77
+ expect(config.blocklistedFields).not.toContain('body')
78
+ expect(config.entityBlocklistedFields).toEqual({ 'customers:customer_interaction': ['body'] })
79
+ })
80
+
81
+ it('groups several fields under the same entity type', () => {
82
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = 'customers:customer_interaction@body,customers:customer_interaction@subject'
83
+ expect(resolveSearchConfig().entityBlocklistedFields).toEqual({
84
+ 'customers:customer_interaction': ['body', 'subject'],
85
+ })
86
+ })
87
+
88
+ it('ignores entries whose field part is empty', () => {
89
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = 'customers:customer_interaction@,@,body'
90
+ const config = resolveSearchConfig()
91
+ expect(config.blocklistedFields).toContain('body')
92
+ expect(config.entityBlocklistedFields).toEqual({})
93
+ })
94
+
95
+ it('treats a leading separator as a global entry', () => {
96
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = '@body'
97
+ const config = resolveSearchConfig()
98
+ expect(config.blocklistedFields).toContain('body')
99
+ expect(config.entityBlocklistedFields).toEqual({})
100
+ })
101
+
102
+ it('stores entity types that collide with inherited object keys as own entries', () => {
103
+ process.env.OM_SEARCH_FIELD_BLOCKLIST = 'constructor@body,toString@summary,__proto__@notes'
104
+ const config = resolveSearchConfig()
105
+
106
+ expect(Object.getPrototypeOf(config.entityBlocklistedFields)).toBeNull()
107
+ expect(config.entityBlocklistedFields?.['constructor']).toEqual(['body'])
108
+ expect(config.entityBlocklistedFields?.['tostring']).toEqual(['summary'])
109
+ expect(config.entityBlocklistedFields?.['__proto__']).toEqual(['notes'])
110
+ expect(isSearchFieldBlocklisted('body', 'constructor', config)).toBe(true)
111
+ expect(isSearchFieldBlocklisted('summary', 'toString', config)).toBe(true)
112
+ expect(isSearchFieldBlocklisted('notes', '__proto__', config)).toBe(true)
113
+ })
114
+ })
115
+
116
+ describe('search token limits', () => {
117
+ const variableNames = [
118
+ 'OM_SEARCH_MAX_FIELD_CHARS',
119
+ 'OM_SEARCH_MAX_TOKENS_PER_FIELD',
120
+ 'OM_SEARCH_MAX_TOKENS_PER_RECORD',
121
+ ] as const
122
+ const originalValues = Object.fromEntries(variableNames.map((name) => [name, process.env[name]]))
123
+
124
+ afterEach(() => {
125
+ for (const name of variableNames) {
126
+ const original = originalValues[name]
127
+ if (original === undefined) delete process.env[name]
128
+ else process.env[name] = original
129
+ }
130
+ })
131
+
132
+ it('uses safe defaults when limits are unset', () => {
133
+ for (const name of variableNames) delete process.env[name]
134
+
135
+ expect(resolveSearchTokenLimits(resolveSearchConfig())).toEqual({
136
+ maxFieldChars: DEFAULT_SEARCH_MAX_FIELD_CHARS,
137
+ maxTokensPerField: DEFAULT_SEARCH_MAX_TOKENS_PER_FIELD,
138
+ maxTokensPerRecord: DEFAULT_SEARCH_MAX_TOKENS_PER_RECORD,
139
+ })
140
+ })
141
+
142
+ it('accepts zero to disable individual limits', () => {
143
+ for (const name of variableNames) process.env[name] = '0'
144
+
145
+ expect(resolveSearchTokenLimits(resolveSearchConfig())).toEqual({
146
+ maxFieldChars: 0,
147
+ maxTokensPerField: 0,
148
+ maxTokensPerRecord: 0,
149
+ })
150
+ })
151
+
152
+ it('normalizes invalid custom config values to defaults', () => {
153
+ expect(resolveSearchTokenLimits({
154
+ enabled: true,
155
+ minTokenLength: 3,
156
+ enablePartials: true,
157
+ hashAlgorithm: 'sha256',
158
+ storeRawTokens: false,
159
+ blocklistedFields: [],
160
+ maxFieldChars: Number.NaN,
161
+ maxTokensPerField: -1,
162
+ maxTokensPerRecord: 4.8,
163
+ })).toEqual({
164
+ maxFieldChars: DEFAULT_SEARCH_MAX_FIELD_CHARS,
165
+ maxTokensPerField: DEFAULT_SEARCH_MAX_TOKENS_PER_FIELD,
166
+ maxTokensPerRecord: 4,
167
+ })
168
+ })
169
+ })
170
+
171
+ describe('isSearchFieldBlocklisted', () => {
172
+ const baseConfig = {
173
+ enabled: true,
174
+ minTokenLength: 3,
175
+ enablePartials: true,
176
+ hashAlgorithm: 'sha256' as const,
177
+ storeRawTokens: false,
178
+ }
179
+
180
+ it('matches global entries by substring for any entity type', () => {
181
+ const config = { ...baseConfig, blocklistedFields: ['password'], entityBlocklistedFields: {} }
182
+ expect(isSearchFieldBlocklisted('password_hash', 'customers:person', config)).toBe(true)
183
+ expect(isSearchFieldBlocklisted('password_hash', null, config)).toBe(true)
184
+ expect(isSearchFieldBlocklisted('display_name', 'customers:person', config)).toBe(false)
185
+ })
186
+
187
+ it('applies an entity-scoped entry only to its own entity type', () => {
188
+ const config = {
189
+ ...baseConfig,
190
+ blocklistedFields: [],
191
+ entityBlocklistedFields: { 'customers:customer_interaction': ['body'] },
192
+ }
193
+ expect(isSearchFieldBlocklisted('body', 'customers:customer_interaction', config)).toBe(true)
194
+ expect(isSearchFieldBlocklisted('body', 'customers:person', config)).toBe(false)
195
+ expect(isSearchFieldBlocklisted('body', null, config)).toBe(false)
196
+ })
197
+
198
+ it('compares entity types case-insensitively', () => {
199
+ const config = {
200
+ ...baseConfig,
201
+ blocklistedFields: [],
202
+ entityBlocklistedFields: { 'customers:customer_interaction': ['body'] },
203
+ }
204
+ expect(isSearchFieldBlocklisted('BODY', ' Customers:Customer_Interaction ', config)).toBe(true)
205
+ })
206
+
207
+ it('ignores inherited Object.prototype keys when looking up an entity type', () => {
208
+ const config = { ...baseConfig, blocklistedFields: [], entityBlocklistedFields: {} }
209
+ expect(isSearchFieldBlocklisted('body', 'constructor', config)).toBe(false)
210
+ expect(isSearchFieldBlocklisted('body', 'toString', config)).toBe(false)
211
+ expect(isSearchFieldBlocklisted('body', '__proto__', config)).toBe(false)
212
+ })
213
+
214
+ it('tolerates a config without the per-entity map', () => {
215
+ const config = { ...baseConfig, blocklistedFields: ['secret'] }
216
+ expect(isSearchFieldBlocklisted('client_secret', 'customers:person', config)).toBe(true)
217
+ expect(isSearchFieldBlocklisted('body', 'customers:person', config)).toBe(false)
218
+ })
219
+ })
@@ -0,0 +1,206 @@
1
+ import {
2
+ findEntityIdsBySearchTokens,
3
+ findEntityIdsBySearchTokensCompat,
4
+ } from '../tokenLookup'
5
+ import { resolveSearchConfig } from '../config'
6
+ import { tokenizeText } from '../tokenize'
7
+
8
+ type KyselyCall = {
9
+ method: string
10
+ args: unknown[]
11
+ }
12
+
13
+ function createKyselyMock(rows: Array<{ entity_id: unknown }>) {
14
+ const calls: KyselyCall[] = []
15
+ const tableNameRef: { value: string | null } = { value: null }
16
+ const builder: Record<string, unknown> = {}
17
+ const passthrough = (method: string) =>
18
+ (...args: unknown[]) => {
19
+ calls.push({ method, args })
20
+ return builder
21
+ }
22
+ builder.select = passthrough('select')
23
+ builder.where = passthrough('where')
24
+ builder.groupBy = passthrough('groupBy')
25
+ builder.having = passthrough('having')
26
+ builder.execute = jest.fn(async () => rows)
27
+
28
+ const db = {
29
+ selectFrom: (table: string) => {
30
+ tableNameRef.value = table
31
+ return builder
32
+ },
33
+ }
34
+ return { db: db as never, calls, tableNameRef, builder }
35
+ }
36
+
37
+ function compileSql(raw: unknown): string {
38
+ if (raw && typeof raw === 'object' && 'toOperationNode' in raw && typeof raw.toOperationNode === 'function') {
39
+ const node = raw.toOperationNode() as { sqlFragments?: unknown }
40
+ return Array.isArray(node.sqlFragments) ? node.sqlFragments.join(' ? ') : ''
41
+ }
42
+ if (raw && typeof raw === 'object' && 'sql' in raw) return String(raw.sql)
43
+ return String(raw)
44
+ }
45
+
46
+ function rawWhereFragments(calls: KyselyCall[]): string[] {
47
+ return calls
48
+ .filter((call) => call.method === 'where' && call.args.length === 1)
49
+ .map((call) => compileSql(call.args[0]))
50
+ }
51
+
52
+ describe('findEntityIdsBySearchTokens', () => {
53
+ const baseInput = {
54
+ entityType: 'customers:customer_entity',
55
+ query: 'Hello',
56
+ }
57
+
58
+ it('skips the lookup for a blank query', async () => {
59
+ const { db, builder } = createKyselyMock([])
60
+ const result = await findEntityIdsBySearchTokens({ ...baseInput, db, query: ' ' })
61
+ expect(result).toEqual({ matched: false, reason: 'empty-query' })
62
+ expect(builder.execute).not.toHaveBeenCalled()
63
+ })
64
+
65
+ it('skips the lookup when token search is disabled', async () => {
66
+ const { db, builder } = createKyselyMock([])
67
+ const result = await findEntityIdsBySearchTokens({
68
+ ...baseInput,
69
+ db,
70
+ config: { ...resolveSearchConfig(), enabled: false },
71
+ })
72
+ expect(result).toEqual({ matched: false, reason: 'search-disabled' })
73
+ expect(builder.execute).not.toHaveBeenCalled()
74
+ })
75
+
76
+ it('skips the lookup when the query yields no indexable tokens', async () => {
77
+ const { db, builder } = createKyselyMock([])
78
+ const result = await findEntityIdsBySearchTokens({ ...baseInput, db, query: '!' })
79
+ expect(result).toEqual({ matched: false, reason: 'no-tokens' })
80
+ expect(builder.execute).not.toHaveBeenCalled()
81
+ })
82
+
83
+ it('requires every query token to be present on the record', async () => {
84
+ const { db, calls } = createKyselyMock([{ entity_id: 'a' }])
85
+ await findEntityIdsBySearchTokens({ ...baseInput, db, query: 'ada lovelace' })
86
+
87
+ const expectedHashes = tokenizeText('ada lovelace', resolveSearchConfig()).hashes
88
+ const hashFilter = calls.find((call) => call.args[0] === 'token_hash' && call.args[1] === 'in')
89
+ expect(hashFilter?.args[2]).toEqual(expectedHashes)
90
+
91
+ const having = calls.find((call) => call.method === 'having')
92
+ expect(compileSql(having?.args[0])).toContain('count(distinct token_hash) >=')
93
+ })
94
+
95
+ it('returns the matched ids and drops non-string rows', async () => {
96
+ const { db, tableNameRef } = createKyselyMock([
97
+ { entity_id: 'id-1' },
98
+ { entity_id: null },
99
+ { entity_id: 42 },
100
+ { entity_id: '' },
101
+ { entity_id: 'id-2' },
102
+ ])
103
+ const result = await findEntityIdsBySearchTokens({ ...baseInput, db })
104
+ expect(result).toEqual({ matched: true, ids: ['id-1', 'id-2'] })
105
+ expect(tableNameRef.value).toBe('search_tokens')
106
+ })
107
+
108
+ it('reports an empty match instead of a skip when nothing matched', async () => {
109
+ const { db } = createKyselyMock([])
110
+ const result = await findEntityIdsBySearchTokens({ ...baseInput, db })
111
+ expect(result).toEqual({ matched: true, ids: [] })
112
+ })
113
+
114
+ it('narrows a single field with equality and multiple fields with IN', async () => {
115
+ const single = createKyselyMock([])
116
+ await findEntityIdsBySearchTokens({ ...baseInput, db: single.db, fields: ['name'] })
117
+ expect(single.calls).toContainEqual({ method: 'where', args: ['field', '=', 'name'] })
118
+
119
+ const multi = createKyselyMock([])
120
+ await findEntityIdsBySearchTokens({ ...baseInput, db: multi.db, fields: ['name', 'email'] })
121
+ expect(multi.calls).toContainEqual({ method: 'where', args: ['field', 'in', ['name', 'email']] })
122
+ })
123
+
124
+ it('omits the field predicate when no fields are supplied', async () => {
125
+ const { db, calls } = createKyselyMock([])
126
+ await findEntityIdsBySearchTokens({ ...baseInput, db, fields: [] })
127
+ expect(calls.some((call) => call.args[0] === 'field')).toBe(false)
128
+ })
129
+
130
+ it('omits tenant and organization predicates when the scope is absent', async () => {
131
+ const { db, calls } = createKyselyMock([])
132
+ await findEntityIdsBySearchTokens({ ...baseInput, db })
133
+ expect(rawWhereFragments(calls)).toEqual([])
134
+ expect(calls.some((call) => call.args[0] === 'organization_id')).toBe(false)
135
+ })
136
+
137
+ it('emits a null-safe tenant predicate for an explicit null tenant', async () => {
138
+ const { db, calls } = createKyselyMock([])
139
+ await findEntityIdsBySearchTokens({ ...baseInput, db, scope: { tenantId: null } })
140
+ expect(rawWhereFragments(calls).some((s) => s.includes('tenant_id is not distinct from'))).toBe(true)
141
+ })
142
+
143
+ it('emits a null-safe organization predicate for an explicit null organization', async () => {
144
+ const { db, calls } = createKyselyMock([])
145
+ await findEntityIdsBySearchTokens({ ...baseInput, db, scope: { organizationId: null } })
146
+ expect(rawWhereFragments(calls).some((s) => s.includes('organization_id is not distinct from'))).toBe(true)
147
+ })
148
+
149
+ it('prefers a concrete organization over the visible-organization list', async () => {
150
+ const { db, calls } = createKyselyMock([])
151
+ await findEntityIdsBySearchTokens({
152
+ ...baseInput,
153
+ db,
154
+ scope: { organizationId: 'org-1', organizationIds: ['org-1', 'org-2'] },
155
+ })
156
+ expect(calls).toContainEqual({ method: 'where', args: ['organization_id', '=', 'org-1'] })
157
+ expect(calls.some((call) => call.args[1] === 'in' && call.args[0] === 'organization_id')).toBe(false)
158
+ })
159
+
160
+ it('falls back to the visible-organization list when no organization is selected', async () => {
161
+ const { db, calls } = createKyselyMock([])
162
+ await findEntityIdsBySearchTokens({
163
+ ...baseInput,
164
+ db,
165
+ scope: { organizationIds: ['org-1', 'org-2'] },
166
+ })
167
+ expect(calls).toContainEqual({ method: 'where', args: ['organization_id', 'in', ['org-1', 'org-2']] })
168
+ })
169
+ })
170
+
171
+ describe('findEntityIdsBySearchTokensCompat', () => {
172
+ it('returns null only for a blank query', async () => {
173
+ const { db } = createKyselyMock([])
174
+ await expect(findEntityIdsBySearchTokensCompat({
175
+ db,
176
+ entityType: 'customers:customer_entity',
177
+ query: ' ',
178
+ })).resolves.toBeNull()
179
+ })
180
+
181
+ it('returns an empty array for the remaining skip reasons', async () => {
182
+ const noTokens = createKyselyMock([])
183
+ await expect(findEntityIdsBySearchTokensCompat({
184
+ db: noTokens.db,
185
+ entityType: 'customers:customer_entity',
186
+ query: '!',
187
+ })).resolves.toEqual([])
188
+
189
+ const disabled = createKyselyMock([])
190
+ await expect(findEntityIdsBySearchTokensCompat({
191
+ db: disabled.db,
192
+ entityType: 'customers:customer_entity',
193
+ query: 'Hello',
194
+ config: { ...resolveSearchConfig(), enabled: false },
195
+ })).resolves.toEqual([])
196
+ })
197
+
198
+ it('returns the matched ids', async () => {
199
+ const { db } = createKyselyMock([{ entity_id: 'id-1' }])
200
+ await expect(findEntityIdsBySearchTokensCompat({
201
+ db,
202
+ entityType: 'customers:customer_entity',
203
+ query: 'Hello',
204
+ })).resolves.toEqual(['id-1'])
205
+ })
206
+ })
@@ -0,0 +1,49 @@
1
+ import type { SearchConfig } from '../config'
2
+ import { tokenizeText } from '../tokenize'
3
+
4
+ const baseConfig: SearchConfig = {
5
+ enabled: true,
6
+ minTokenLength: 3,
7
+ enablePartials: true,
8
+ hashAlgorithm: 'sha256',
9
+ storeRawTokens: false,
10
+ blocklistedFields: [],
11
+ }
12
+
13
+ describe('tokenizeText limits', () => {
14
+ test('truncates oversized field text before tokenizing', () => {
15
+ const config = { ...baseConfig, enablePartials: false, maxFieldChars: 10 }
16
+
17
+ const { tokens } = tokenizeText('aaaa bbbb cccc', config)
18
+
19
+ expect(tokens).toEqual(['aaaa', 'bbbb'])
20
+ })
21
+
22
+ test('bounds prefix expansion while collecting tokens', () => {
23
+ const config = { ...baseConfig, maxFieldChars: 100, maxTokensPerField: 5 }
24
+
25
+ const { tokens, hashes } = tokenizeText('a'.repeat(100), config)
26
+
27
+ expect(tokens).toEqual(['aaa', 'aaaa', 'aaaaa', 'aaaaaa', 'aaaaaaa'])
28
+ expect(hashes).toHaveLength(5)
29
+ })
30
+
31
+ test('applies safe defaults to legacy configs without limit fields', () => {
32
+ const { tokens } = tokenizeText('a'.repeat(50_000), baseConfig)
33
+
34
+ expect(tokens).toHaveLength(5_000)
35
+ })
36
+
37
+ test('allows a limit to be disabled explicitly', () => {
38
+ const config = {
39
+ ...baseConfig,
40
+ enablePartials: false,
41
+ maxFieldChars: 0,
42
+ maxTokensPerField: 0,
43
+ }
44
+
45
+ const { tokens } = tokenizeText('alpha beta gamma delta', config)
46
+
47
+ expect(tokens).toEqual(['alpha', 'beta', 'gamma', 'delta'])
48
+ })
49
+ })
@@ -0,0 +1,22 @@
1
+ import { parseBooleanToken } from '../boolean'
2
+
3
+ /**
4
+ * Module id backing the tenant-scoped vector auto-indexing switch. Kept as `vector`
5
+ * (rather than `search`) for backwards compatibility with rows written before the
6
+ * search module absorbed the vector settings.
7
+ */
8
+ export const SEARCH_AUTO_INDEX_CONFIG_MODULE = 'vector'
9
+ export const SEARCH_AUTO_INDEX_CONFIG_KEY = 'auto_index_enabled'
10
+
11
+ /**
12
+ * Instance-wide kill switch for vector auto-indexing. Lives in `@open-mercato/shared`
13
+ * so consumers outside `@open-mercato/search` (for example the query index status page)
14
+ * can report vector coverage honestly without duplicating the env-var contract.
15
+ */
16
+ export function envDisablesAutoIndexing(): boolean {
17
+ const raw =
18
+ process.env.OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING ??
19
+ process.env.DISABLE_VECTOR_SEARCH_AUTOINDEXING
20
+ if (!raw) return false
21
+ return parseBooleanToken(raw) === true
22
+ }