@open-mercato/shared 0.9.1-develop.7574.1.837288eec1 → 0.10.1-develop.7576.1.21d5b50435

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 (125) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +4 -4
  3. package/dist/lib/auth/server.js +1 -1
  4. package/dist/lib/auth/server.js.map +2 -2
  5. package/dist/lib/bootstrap/dynamicLoader.js +6 -46
  6. package/dist/lib/bootstrap/dynamicLoader.js.map +2 -2
  7. package/dist/lib/bootstrap/factory.js +3 -4
  8. package/dist/lib/bootstrap/factory.js.map +2 -2
  9. package/dist/lib/catalog-visibility/index.js +0 -4
  10. package/dist/lib/catalog-visibility/index.js.map +2 -2
  11. package/dist/lib/commands/command-bus.js +13 -45
  12. package/dist/lib/commands/command-bus.js.map +2 -2
  13. package/dist/lib/commands/types.js.map +2 -2
  14. package/dist/lib/crud/exporters.js +1 -1
  15. package/dist/lib/crud/exporters.js.map +2 -2
  16. package/dist/lib/crud/ids.js +1 -13
  17. package/dist/lib/crud/ids.js.map +2 -2
  18. package/dist/lib/db/pg-errors.js +0 -14
  19. package/dist/lib/db/pg-errors.js.map +2 -2
  20. package/dist/lib/localization/index.js +1 -9
  21. package/dist/lib/localization/index.js.map +2 -2
  22. package/dist/lib/localization/translatable-fields.js +0 -26
  23. package/dist/lib/localization/translatable-fields.js.map +2 -2
  24. package/dist/lib/number.js +0 -6
  25. package/dist/lib/number.js.map +2 -2
  26. package/dist/lib/openapi/generator.js +67 -84
  27. package/dist/lib/openapi/generator.js.map +2 -2
  28. package/dist/lib/query/engine.js +10 -45
  29. package/dist/lib/query/engine.js.map +2 -2
  30. package/dist/lib/query/join-utils.js +1 -1
  31. package/dist/lib/query/join-utils.js.map +2 -2
  32. package/dist/lib/query/types.js.map +2 -2
  33. package/dist/lib/url.js +0 -24
  34. package/dist/lib/url.js.map +2 -2
  35. package/dist/lib/version.js +1 -1
  36. package/dist/lib/version.js.map +1 -1
  37. package/dist/lib/webhooks/body.js +3 -7
  38. package/dist/lib/webhooks/body.js.map +2 -2
  39. package/dist/lib/webhooks/index.js +0 -2
  40. package/dist/lib/webhooks/index.js.map +2 -2
  41. package/dist/modules/integrations/types.js.map +2 -2
  42. package/dist/modules/notifications/types.js +0 -4
  43. package/dist/modules/notifications/types.js.map +3 -3
  44. package/dist/modules/payment_gateways/types.js +1 -14
  45. package/dist/modules/payment_gateways/types.js.map +2 -2
  46. package/dist/modules/registry.js.map +2 -2
  47. package/dist/modules/search.js.map +2 -2
  48. package/dist/modules/widgets/injection-loader.js +3 -14
  49. package/dist/modules/widgets/injection-loader.js.map +2 -2
  50. package/package.json +3 -10
  51. package/src/lib/__tests__/number.test.ts +1 -24
  52. package/src/lib/auth/__tests__/server.test.ts +0 -14
  53. package/src/lib/auth/server.ts +1 -1
  54. package/src/lib/bootstrap/__tests__/dynamicLoader.appDi.test.ts +2 -2
  55. package/src/lib/bootstrap/__tests__/dynamicLoader.appModuleOverrides.test.ts +2 -2
  56. package/src/lib/bootstrap/__tests__/dynamicLoader.cacheRecovery.test.ts +2 -2
  57. package/src/lib/bootstrap/__tests__/dynamicLoader.commandInterceptors.test.ts +2 -2
  58. package/src/lib/bootstrap/__tests__/dynamicLoader.tsconfig.test.ts +2 -2
  59. package/src/lib/bootstrap/__tests__/factory.test.ts +6 -18
  60. package/src/lib/bootstrap/dynamicLoader.ts +5 -63
  61. package/src/lib/bootstrap/factory.ts +3 -8
  62. package/src/lib/bootstrap/types.ts +1 -5
  63. package/src/lib/catalog-visibility/index.ts +0 -2
  64. package/src/lib/commands/__tests__/command-bus.test.ts +1 -100
  65. package/src/lib/commands/command-bus.ts +10 -42
  66. package/src/lib/commands/command-interceptor.ts +0 -4
  67. package/src/lib/commands/types.ts +0 -14
  68. package/src/lib/crud/__tests__/exporters.test.ts +0 -18
  69. package/src/lib/crud/__tests__/ids.test.ts +1 -34
  70. package/src/lib/crud/exporters.ts +1 -1
  71. package/src/lib/crud/ids.ts +0 -24
  72. package/src/lib/db/__tests__/pg-errors.test.ts +1 -68
  73. package/src/lib/db/pg-errors.ts +0 -35
  74. package/src/lib/encryption/__tests__/tenantDataEncryptionService.test.ts +0 -23
  75. package/src/lib/localization/__tests__/translatable-fields.test.ts +0 -17
  76. package/src/lib/localization/index.ts +1 -8
  77. package/src/lib/localization/translatable-fields.ts +0 -46
  78. package/src/lib/number.ts +0 -13
  79. package/src/lib/openapi/generator.ts +77 -106
  80. package/src/lib/query/engine.ts +8 -58
  81. package/src/lib/query/join-utils.ts +1 -1
  82. package/src/lib/query/types.ts +1 -13
  83. package/src/lib/url.ts +0 -30
  84. package/src/lib/webhooks/__tests__/body.test.ts +0 -48
  85. package/src/lib/webhooks/body.ts +4 -11
  86. package/src/lib/webhooks/index.ts +0 -1
  87. package/src/modules/integrations/types.ts +0 -6
  88. package/src/modules/notifications/types.ts +0 -7
  89. package/src/modules/payment_gateways/__tests__/types.test.ts +0 -44
  90. package/src/modules/payment_gateways/types.ts +6 -52
  91. package/src/modules/registry.ts +0 -5
  92. package/src/modules/search.ts +0 -39
  93. package/src/modules/widgets/injection-loader.ts +3 -33
  94. package/dist/lib/bootstrap/next-subpath-resolve-hook-worker.js +0 -6
  95. package/dist/lib/bootstrap/next-subpath-resolve-hook-worker.js.map +0 -7
  96. package/dist/lib/bootstrap/next-subpath-resolve-hook.js +0 -62
  97. package/dist/lib/bootstrap/next-subpath-resolve-hook.js.map +0 -7
  98. package/dist/lib/catalog-visibility/canonicalizeEffectiveScope.js +0 -33
  99. package/dist/lib/catalog-visibility/canonicalizeEffectiveScope.js.map +0 -7
  100. package/dist/lib/catalog-visibility/hashEffectiveScope.js +0 -9
  101. package/dist/lib/catalog-visibility/hashEffectiveScope.js.map +0 -7
  102. package/dist/lib/db/advisoryLock.js +0 -172
  103. package/dist/lib/db/advisoryLock.js.map +0 -7
  104. package/dist/lib/query/overlap.js +0 -58
  105. package/dist/lib/query/overlap.js.map +0 -7
  106. package/dist/modules/notifications/safeHref.js +0 -20
  107. package/dist/modules/notifications/safeHref.js.map +0 -7
  108. package/src/lib/__tests__/url.cross-site.test.ts +0 -140
  109. package/src/lib/bootstrap/__tests__/dynamicLoader.externalSubpath.test.ts +0 -141
  110. package/src/lib/bootstrap/__tests__/next-subpath-resolve-hook.test.ts +0 -174
  111. package/src/lib/bootstrap/next-subpath-resolve-hook-worker.ts +0 -3
  112. package/src/lib/bootstrap/next-subpath-resolve-hook.ts +0 -130
  113. package/src/lib/catalog-visibility/__tests__/hashEffectiveScope.test.ts +0 -121
  114. package/src/lib/catalog-visibility/canonicalizeEffectiveScope.ts +0 -41
  115. package/src/lib/catalog-visibility/hashEffectiveScope.ts +0 -8
  116. package/src/lib/db/__tests__/advisoryLock.integration.test.ts +0 -343
  117. package/src/lib/db/__tests__/advisoryLock.test.ts +0 -564
  118. package/src/lib/db/advisoryLock.ts +0 -271
  119. package/src/lib/openapi/__tests__/optional-path-params.test.ts +0 -102
  120. package/src/lib/query/__tests__/empty-ids-filter.pg.test.ts +0 -89
  121. package/src/lib/query/__tests__/engine.empty-in-filter.test.ts +0 -79
  122. package/src/lib/query/__tests__/overlap.test.ts +0 -219
  123. package/src/lib/query/overlap.ts +0 -106
  124. package/src/modules/notifications/safeHref.ts +0 -19
  125. package/src/modules/widgets/__tests__/injection-loader.partitioned-registration.test.ts +0 -78
@@ -1,141 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- *
4
- * The CLI bundle externalizes every bare package import. Node's ESM resolver only maps an
5
- * extensionless subpath such as `next/link` when the package publishes an `exports` map; for a
6
- * legacy package (no `exports`, like `next`) it requires the file extension and the bundle
7
- * fails with ERR_MODULE_NOT_FOUND (#6993). The external plugin therefore rewrites such
8
- * subpaths to the file `require.resolve` finds, and leaves everything else untouched.
9
- */
10
- import { spawnSync } from 'node:child_process'
11
- import fs from 'node:fs'
12
- import os from 'node:os'
13
- import path from 'node:path'
14
-
15
- import { compileAppSourceFile, createCliBundlePlugins } from '../dynamicLoader'
16
-
17
- function writePackage(appRoot: string, name: string, manifest: Record<string, unknown>, files: Record<string, string>) {
18
- const packageDir = path.join(appRoot, 'node_modules', ...name.split('/'))
19
- fs.mkdirSync(packageDir, { recursive: true })
20
- fs.writeFileSync(path.join(packageDir, 'package.json'), JSON.stringify({ name, version: '1.0.0', ...manifest }))
21
- for (const [relativePath, content] of Object.entries(files)) {
22
- const filePath = path.join(packageDir, relativePath)
23
- fs.mkdirSync(path.dirname(filePath), { recursive: true })
24
- fs.writeFileSync(filePath, content)
25
- }
26
- }
27
-
28
- async function bundleWithCliPlugins(appRoot: string, source: string): Promise<{ outfile: string; output: string }> {
29
- const esbuild = await import('esbuild')
30
- const generatedDir = path.join(appRoot, '.mercato', 'generated')
31
- fs.mkdirSync(generatedDir, { recursive: true })
32
- const entry = path.join(generatedDir, 'entry.ts')
33
- fs.writeFileSync(entry, source)
34
- const outfile = path.join(generatedDir, 'entry.mjs')
35
- await esbuild.build({
36
- entryPoints: [entry],
37
- outfile,
38
- absWorkingDir: appRoot,
39
- bundle: true,
40
- format: 'esm',
41
- platform: 'node',
42
- target: 'node18',
43
- plugins: createCliBundlePlugins(appRoot),
44
- })
45
- return { outfile, output: fs.readFileSync(outfile, 'utf8') }
46
- }
47
-
48
- describe('createCliBundlePlugins — externalized package subpaths', () => {
49
- let appRoot: string
50
-
51
- beforeEach(() => {
52
- appRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'om-external-subpath-')))
53
- fs.writeFileSync(path.join(appRoot, 'package.json'), JSON.stringify({ name: 'app', type: 'module' }))
54
- writePackage(appRoot, 'legacy-pkg', { main: 'index.js' }, {
55
- 'index.js': "module.exports = 'legacy-root'\n",
56
- 'link.js': "module.exports = 'legacy-link'\n",
57
- 'dist/nested/index.js': "module.exports = 'legacy-nested'\n",
58
- })
59
- writePackage(appRoot, '@scope/legacy-scoped', {}, {
60
- 'tools.js': "module.exports = 'scoped-tools'\n",
61
- })
62
- writePackage(appRoot, 'exports-pkg', { exports: { './feature': './lib/feature.js' } }, {
63
- 'lib/feature.js': "module.exports = 'exports-feature'\n",
64
- })
65
- })
66
-
67
- afterEach(() => {
68
- fs.rmSync(appRoot, { recursive: true, force: true })
69
- })
70
-
71
- it('appends the resolved file to extensionless subpaths of packages without an exports map', async () => {
72
- const { output } = await bundleWithCliPlugins(appRoot, [
73
- "import link from 'legacy-pkg/link'",
74
- "import nested from 'legacy-pkg/dist/nested'",
75
- "import tools from '@scope/legacy-scoped/tools'",
76
- 'export const values = [link, nested, tools]',
77
- '',
78
- ].join('\n'))
79
-
80
- expect(output).toContain('"legacy-pkg/link.js"')
81
- expect(output).toContain('"legacy-pkg/dist/nested/index.js"')
82
- expect(output).toContain('"@scope/legacy-scoped/tools.js"')
83
- })
84
-
85
- it('keeps package roots, exports-mapped subpaths, builtins and unresolvable specifiers unchanged', async () => {
86
- const { output } = await bundleWithCliPlugins(appRoot, [
87
- "import root from 'legacy-pkg'",
88
- "import feature from 'exports-pkg/feature'",
89
- "import explicit from 'legacy-pkg/link.js'",
90
- "import { readFile } from 'fs/promises'",
91
- "import missing from 'missing-pkg/sub'",
92
- 'export const values = [root, feature, explicit, readFile, missing]',
93
- '',
94
- ].join('\n'))
95
-
96
- expect(output).toContain('"legacy-pkg"')
97
- expect(output).toContain('"exports-pkg/feature"')
98
- expect(output).toContain('"legacy-pkg/link.js"')
99
- expect(output).toContain('"fs/promises"')
100
- expect(output).toContain('"missing-pkg/sub"')
101
- })
102
-
103
- it('produces a bundle Node ESM can load', async () => {
104
- const { outfile } = await bundleWithCliPlugins(appRoot, [
105
- "import link from 'legacy-pkg/link'",
106
- "import feature from 'exports-pkg/feature'",
107
- 'console.log(JSON.stringify([link, feature]))',
108
- '',
109
- ].join('\n'))
110
-
111
- const result = spawnSync(process.execPath, [outfile], { encoding: 'utf8' })
112
-
113
- expect(result.stderr).not.toContain('ERR_MODULE_NOT_FOUND')
114
- expect(result.status).toBe(0)
115
- expect(JSON.parse(result.stdout.trim())).toEqual(['legacy-link', 'exports-feature'])
116
- })
117
-
118
- it('records the rewritten package manifest so a package upgrade invalidates the cached bundle', async () => {
119
- fs.writeFileSync(path.join(appRoot, 'tsconfig.json'), JSON.stringify({ compilerOptions: { target: 'ES2022' } }))
120
- const generatedDir = path.join(appRoot, '.mercato', 'generated')
121
- fs.mkdirSync(generatedDir, { recursive: true })
122
- const entry = path.join(generatedDir, 'registry.generated.ts')
123
- fs.writeFileSync(entry, "import link from 'legacy-pkg/link'\nexport const value = link\n")
124
- const outFile = path.join(generatedDir, 'registry.generated.mjs')
125
-
126
- await compileAppSourceFile(entry, { appRoot, outFile })
127
- const metadata = JSON.parse(fs.readFileSync(`${outFile}.cache.json`, 'utf8')) as {
128
- dependencies: Record<string, string>
129
- }
130
- expect(Object.keys(metadata.dependencies)).toContain('node_modules/legacy-pkg/package.json')
131
-
132
- const firstOutputMtime = fs.statSync(outFile).mtimeMs
133
- await compileAppSourceFile(entry, { appRoot, outFile })
134
- expect(fs.statSync(outFile).mtimeMs).toBe(firstOutputMtime)
135
-
136
- writePackage(appRoot, 'legacy-pkg', { exports: { './link': './link.js' } }, {})
137
- await compileAppSourceFile(entry, { appRoot, outFile })
138
- expect(fs.readFileSync(outFile, 'utf8')).toContain('"legacy-pkg/link"')
139
- expect(fs.readFileSync(outFile, 'utf8')).not.toContain('"legacy-pkg/link.js"')
140
- })
141
- })
@@ -1,174 +0,0 @@
1
- import {
2
- installNextSubpathResolveHook,
3
- resetNextSubpathResolveHookForTests,
4
- resolveNextSubpath,
5
- resolveNextSubpathAsync,
6
- } from '../next-subpath-resolve-hook'
7
-
8
- function notFound(specifier: string): Error & { code: string } {
9
- return Object.assign(new Error(`Cannot find module '${specifier}'`), { code: 'ERR_MODULE_NOT_FOUND' })
10
- }
11
-
12
- describe('resolveNextSubpath (#6118)', () => {
13
- const context = { parentURL: 'file:///app/route.js' }
14
-
15
- it('leaves specifiers other than next/<subpath> to the default resolver', () => {
16
- const nextResolve = jest.fn(() => ({ url: 'file:///app/node_modules/zod/index.js' }))
17
-
18
- const result = resolveNextSubpath('zod', context, nextResolve)
19
-
20
- expect(result.url).toBe('file:///app/node_modules/zod/index.js')
21
- expect(nextResolve).toHaveBeenCalledTimes(1)
22
- expect(nextResolve).toHaveBeenCalledWith('zod', context)
23
- })
24
-
25
- it('does not touch a next/<subpath> that resolves on its own', () => {
26
- // The day `next` ships an exports map the hook must step aside.
27
- const nextResolve = jest.fn(() => ({ url: 'file:///app/node_modules/next/server.js' }))
28
-
29
- resolveNextSubpath('next/server', context, nextResolve)
30
-
31
- expect(nextResolve).toHaveBeenCalledTimes(1)
32
- })
33
-
34
- it('retries a bare next/<subpath> with the .js suffix when Node cannot resolve it', () => {
35
- // `next` has no exports map and Node ESM does no extension guessing, so
36
- // `next/server` fails while `next/server.js` is a real file.
37
- const nextResolve = jest
38
- .fn()
39
- .mockImplementationOnce(() => { throw notFound('/app/node_modules/next/server') })
40
- .mockImplementationOnce(() => ({ url: 'file:///app/node_modules/next/server.js' }))
41
-
42
- const result = resolveNextSubpath('next/server', context, nextResolve)
43
-
44
- expect(result.url).toBe('file:///app/node_modules/next/server.js')
45
- expect(nextResolve).toHaveBeenNthCalledWith(1, 'next/server', context)
46
- expect(nextResolve).toHaveBeenNthCalledWith(2, 'next/server.js', context)
47
- })
48
-
49
- it('covers the other subpaths route modules import', () => {
50
- for (const subpath of ['next/headers', 'next/navigation', 'next/cache']) {
51
- const nextResolve = jest
52
- .fn()
53
- .mockImplementationOnce(() => { throw notFound(subpath) })
54
- .mockImplementationOnce((resolvedSpecifier: string) => ({
55
- url: `file:///app/node_modules/${resolvedSpecifier}`,
56
- }))
57
- expect(resolveNextSubpath(subpath, context, nextResolve).url).toBe(`file:///app/node_modules/${subpath}.js`)
58
- }
59
- })
60
-
61
- it('does not retry deeper or already-suffixed specifiers', () => {
62
- for (const specifier of ['next/server.js', 'next/dist/server/web/spec-extension/response', 'next']) {
63
- const nextResolve = jest.fn(() => { throw notFound(specifier) })
64
- expect(() => resolveNextSubpath(specifier, context, nextResolve)).toThrow(/Cannot find module/)
65
- expect(nextResolve).toHaveBeenCalledTimes(1)
66
- }
67
- })
68
-
69
- it('rethrows the original error when the .js form is missing too', () => {
70
- const original = notFound('/app/node_modules/next/server')
71
- const nextResolve = jest
72
- .fn()
73
- .mockImplementationOnce(() => { throw original })
74
- .mockImplementationOnce(() => { throw notFound('/app/node_modules/next/server.js') })
75
-
76
- expect(() => resolveNextSubpath('next/server', context, nextResolve)).toThrow(original)
77
- })
78
-
79
- it('rethrows errors that are not ERR_MODULE_NOT_FOUND without retrying', () => {
80
- const syntaxError = Object.assign(new Error('bad package.json'), { code: 'ERR_INVALID_PACKAGE_CONFIG' })
81
- const nextResolve = jest.fn(() => { throw syntaxError })
82
-
83
- expect(() => resolveNextSubpath('next/server', context, nextResolve)).toThrow(syntaxError)
84
- expect(nextResolve).toHaveBeenCalledTimes(1)
85
- })
86
- })
87
-
88
- describe('installNextSubpathResolveHook', () => {
89
- beforeEach(() => {
90
- resetNextSubpathResolveHookForTests()
91
- })
92
-
93
- it('registers the resolve hook once per process', () => {
94
- const register = jest.fn()
95
-
96
- expect(installNextSubpathResolveHook(register, null)).toBe(true)
97
- expect(installNextSubpathResolveHook(register, null)).toBe(false)
98
-
99
- expect(register).toHaveBeenCalledTimes(1)
100
- expect(register).toHaveBeenCalledWith({ resolve: resolveNextSubpath })
101
- })
102
-
103
- it('registers an asynchronous hook on Node 22.0-22.14', () => {
104
- const registerHookModule = jest.fn()
105
-
106
- expect(installNextSubpathResolveHook(null, registerHookModule)).toBe(true)
107
- expect(registerHookModule).toHaveBeenCalledWith(
108
- expect.objectContaining({ href: expect.stringMatching(/next-subpath-resolve-hook-worker\.js$/) }),
109
- expect.stringMatching(/^file:/),
110
- )
111
- })
112
-
113
- it('is a no-op on a runtime without either registration API', () => {
114
- expect(installNextSubpathResolveHook(null, null)).toBe(false)
115
- })
116
- })
117
-
118
- describe('resolveNextSubpathAsync', () => {
119
- const context = { parentURL: 'file:///app/route.js' }
120
-
121
- it('retries a bare next/<subpath> with the .js suffix', async () => {
122
- const nextResolve = jest
123
- .fn()
124
- .mockRejectedValueOnce(notFound('/app/node_modules/next/server'))
125
- .mockResolvedValueOnce({ url: 'file:///app/node_modules/next/server.js' })
126
-
127
- const result = await resolveNextSubpathAsync('next/server', context, nextResolve)
128
-
129
- expect(result.url).toBe('file:///app/node_modules/next/server.js')
130
- expect(nextResolve).toHaveBeenNthCalledWith(1, 'next/server', context)
131
- expect(nextResolve).toHaveBeenNthCalledWith(2, 'next/server.js', context)
132
- })
133
- })
134
-
135
- describe('installNextSubpathResolveHook against the runtime node:module', () => {
136
- afterEach(() => {
137
- jest.dontMock('node:module')
138
- jest.resetModules()
139
- })
140
-
141
- it('installs through node:module.register on Node 22.0-22.14', () => {
142
- // A named import of `registerHooks` would throw while the module loads on
143
- // such a runtime; the helper must load and use the older registration API.
144
- jest.resetModules()
145
- const register = jest.fn()
146
- jest.doMock('node:module', () => ({ register }))
147
- let installed: boolean | undefined
148
- jest.isolateModules(() => {
149
- // eslint-disable-next-line @typescript-eslint/no-require-imports
150
- const hookModule = require('../next-subpath-resolve-hook') as typeof import('../next-subpath-resolve-hook')
151
- installed = hookModule.installNextSubpathResolveHook()
152
- })
153
- expect(installed).toBe(true)
154
- expect(register).toHaveBeenCalledTimes(1)
155
- expect(register.mock.calls[0][0]).toEqual(
156
- expect.objectContaining({ href: expect.stringMatching(/next-subpath-resolve-hook-worker\.js$/) }),
157
- )
158
- })
159
-
160
- it('installs through node:module.registerHooks when the runtime has it', () => {
161
- jest.resetModules()
162
- const register = jest.fn()
163
- jest.doMock('node:module', () => ({ registerHooks: register }))
164
- let installed: boolean | undefined
165
- jest.isolateModules(() => {
166
- // eslint-disable-next-line @typescript-eslint/no-require-imports
167
- const hookModule = require('../next-subpath-resolve-hook') as typeof import('../next-subpath-resolve-hook')
168
- installed = hookModule.installNextSubpathResolveHook()
169
- })
170
- expect(installed).toBe(true)
171
- expect(register).toHaveBeenCalledTimes(1)
172
- expect(register.mock.calls[0][0]).toEqual({ resolve: expect.any(Function) })
173
- })
174
- })
@@ -1,3 +0,0 @@
1
- import { resolveNextSubpathAsync } from './next-subpath-resolve-hook'
2
-
3
- export const resolve = resolveNextSubpathAsync
@@ -1,130 +0,0 @@
1
- /**
2
- * Node ESM resolution for `next/<subpath>` outside the Next bundler (#6118, #7102).
3
- *
4
- * Installed by the `mercato` CLI entry, so every CLI command and worker it
5
- * runs can load package dists that import `next/dynamic`, `next/link`,
6
- * `next/server` … The `next/dynamic` imports in particular MUST keep the bare
7
- * specifier: Next's `next_dynamic` compiler transform only matches it exactly.
8
- *
9
- * `mercato ai_assistant mcp:serve-http` (and `mcp:serve`, `mcp:dev`,
10
- * `mcp:list-tools`) run in plain Node, and the AI API operation runner loads
11
- * API route modules with a runtime `import()`. Those modules import
12
- * `NextResponse` from `'next/server'`: a bare package subpath that only a
13
- * bundler resolves, because `next` ships no `exports` map and Node's ESM
14
- * resolver does no extension guessing. Every route with that import (287 of
15
- * them on the 0.7.0 packages) therefore fails to load with
16
- * `ERR_MODULE_NOT_FOUND … node_modules/next/server`, and every tool backed by
17
- * such a route returns "Failed to load route module".
18
- *
19
- * `next/server.js`, `next/headers.js`, `next/navigation.js` … do exist as files,
20
- * which is why `@open-mercato/shared` imports `'next/headers.js'`. Rather than
21
- * rewriting several hundred imports across every package (and every
22
- * third-party module), this hook retries a failed bare `next/<subpath>` with
23
- * the `.js` suffix. It only runs in the processes that install it, only for
24
- * `next/*` specifiers, and only after the normal resolution failed, so it
25
- * becomes a no-op the day `next` publishes an `exports` map.
26
- */
27
- import * as nodeModule from 'node:module'
28
-
29
- type ResolveContext = Record<string, unknown>
30
- type ResolveResult = { url: string; format?: string | null | undefined; shortCircuit?: boolean }
31
- type NextResolve = (specifier: string, context?: ResolveContext) => ResolveResult
32
- type AsyncNextResolve = (specifier: string, context?: ResolveContext) => ResolveResult | Promise<ResolveResult>
33
-
34
- /** Bare `next/<one segment>` specifiers, e.g. `next/server`, `next/headers`. */
35
- const NEXT_BARE_SUBPATH = /^next\/[A-Za-z0-9_-]+$/
36
-
37
- let installed = false
38
-
39
- function isModuleNotFound(error: unknown): boolean {
40
- return Boolean(error) && typeof error === 'object' && (error as { code?: unknown }).code === 'ERR_MODULE_NOT_FOUND'
41
- }
42
-
43
- /**
44
- * The resolve hook itself. Exported so it can be tested without touching the
45
- * process-global hook chain.
46
- */
47
- export function resolveNextSubpath(
48
- specifier: string,
49
- context: ResolveContext,
50
- nextResolve: NextResolve,
51
- ): ResolveResult {
52
- if (!NEXT_BARE_SUBPATH.test(specifier)) return nextResolve(specifier, context)
53
- try {
54
- return nextResolve(specifier, context)
55
- } catch (error) {
56
- if (!isModuleNotFound(error)) throw error
57
- try {
58
- return nextResolve(`${specifier}.js`, context)
59
- } catch {
60
- // Neither form resolves (Next is not installed at all): surface the
61
- // original error, which names the specifier the caller wrote.
62
- throw error
63
- }
64
- }
65
- }
66
-
67
- export async function resolveNextSubpathAsync(
68
- specifier: string,
69
- context: ResolveContext,
70
- nextResolve: AsyncNextResolve,
71
- ): Promise<ResolveResult> {
72
- if (!NEXT_BARE_SUBPATH.test(specifier)) return nextResolve(specifier, context)
73
- try {
74
- return await nextResolve(specifier, context)
75
- } catch (error) {
76
- if (!isModuleNotFound(error)) throw error
77
- try {
78
- return await nextResolve(`${specifier}.js`, context)
79
- } catch {
80
- throw error
81
- }
82
- }
83
- }
84
-
85
- type RegisterHooks = (hooks: { resolve: typeof resolveNextSubpath }) => unknown
86
- type RegisterHookModule = (specifier: string | URL, parentURL?: string | URL) => unknown
87
-
88
- /**
89
- * `module.registerHooks` exists from Node 22.15. It is read off the namespace
90
- * rather than imported by name: in the published ESM build a named import of an
91
- * export the running Node lacks fails while the module links, before the check
92
- * in `installNextSubpathResolveHook` can run, and the package still declares
93
- * `node >= 22.0.0`.
94
- */
95
- function runtimeRegisterHooks(): RegisterHooks | undefined {
96
- const candidate = (nodeModule as unknown as { registerHooks?: unknown }).registerHooks
97
- return typeof candidate === 'function' ? (candidate as RegisterHooks) : undefined
98
- }
99
-
100
- function runtimeRegisterHookModule(): RegisterHookModule | undefined {
101
- const candidate = (nodeModule as unknown as { register?: unknown }).register
102
- return typeof candidate === 'function' ? (candidate as RegisterHookModule) : undefined
103
- }
104
-
105
- /**
106
- * Install the hook once per process. Returns `true` when it was installed by
107
- * this call, `false` when it already was or when the runtime has neither
108
- * registration API. Node 22.15+ uses the synchronous hook API; earlier
109
- * supported Node 22 releases use the asynchronous hook API.
110
- */
111
- export function installNextSubpathResolveHook(
112
- registerHooks: RegisterHooks | null | undefined = runtimeRegisterHooks(),
113
- registerHookModule: RegisterHookModule | null | undefined = runtimeRegisterHookModule(),
114
- ): boolean {
115
- if (installed) return false
116
- if (typeof registerHooks === 'function') {
117
- registerHooks({ resolve: resolveNextSubpath })
118
- } else if (typeof registerHookModule === 'function') {
119
- registerHookModule(new URL('./next-subpath-resolve-hook-worker.js', import.meta.url), import.meta.url)
120
- } else {
121
- return false
122
- }
123
- installed = true
124
- return true
125
- }
126
-
127
- /** Test seam: forget that the hook was installed. */
128
- export function resetNextSubpathResolveHookForTests(): void {
129
- installed = false
130
- }
@@ -1,121 +0,0 @@
1
- import { canonicalizeEffectiveScope } from '../canonicalizeEffectiveScope'
2
- import { hashEffectiveScope } from '../hashEffectiveScope'
3
- import type { AssortmentScope, EffectiveAssortmentScope } from '../types'
4
- import { mulberry32, randomAssortmentScope } from './testFixtures'
5
-
6
- function shuffle<T>(rng: () => number, items: T[]): T[] {
7
- const copy = [...items]
8
- for (let index = copy.length - 1; index > 0; index -= 1) {
9
- const swap = Math.floor(rng() * (index + 1))
10
- const held = copy[index]
11
- copy[index] = copy[swap]
12
- copy[swap] = held
13
- }
14
- return copy
15
- }
16
-
17
- function shuffleScope(rng: () => number, scope: AssortmentScope): AssortmentScope {
18
- const entries = shuffle(rng, Object.entries(scope)).map(([key, value]) => {
19
- if (key === 'allOf') {
20
- return [key, shuffle(rng, (value as AssortmentScope[]).map((nested) => shuffleScope(rng, nested)))]
21
- }
22
- return [key, shuffle(rng, value as string[])]
23
- })
24
- return Object.fromEntries(entries) as AssortmentScope
25
- }
26
-
27
- function randomEffective(rng: () => number): EffectiveAssortmentScope {
28
- if (rng() < 0.1) return null
29
- const branches: AssortmentScope[] = []
30
- const count = Math.floor(rng() * 4)
31
- for (let index = 0; index < count; index += 1) {
32
- const branch = randomAssortmentScope(rng)
33
- if (rng() < 0.3) {
34
- branch.allOf = [randomAssortmentScope(rng), randomAssortmentScope(rng)]
35
- }
36
- branches.push(branch)
37
- }
38
- return branches
39
- }
40
-
41
- describe('canonicalizeEffectiveScope', () => {
42
- it('distinguishes unrestricted (null) from deny-all ([])', () => {
43
- expect(canonicalizeEffectiveScope(null)).toBe('null')
44
- expect(canonicalizeEffectiveScope([])).toBe('[]')
45
- expect(hashEffectiveScope(null)).not.toBe(hashEffectiveScope([]))
46
- })
47
-
48
- it('treats empty arrays as absent keys', () => {
49
- expect(canonicalizeEffectiveScope([{ categoryIds: [], tagIds: ['t1'], excludeTagIds: [] }])).toBe(
50
- canonicalizeEffectiveScope([{ tagIds: ['t1'] }]),
51
- )
52
- expect(canonicalizeEffectiveScope([{ categoryIds: [], allOf: [] }])).toBe(canonicalizeEffectiveScope([{}]))
53
- })
54
-
55
- it('keeps an empty branch (matches everything) distinct from no branches', () => {
56
- expect(canonicalizeEffectiveScope([{}])).toBe('[{}]')
57
- expect(canonicalizeEffectiveScope([{}])).not.toBe(canonicalizeEffectiveScope([]))
58
- })
59
-
60
- it('is invariant to key order, id order and duplicate ids', () => {
61
- const left: EffectiveAssortmentScope = [{ tagIds: ['b', 'a', 'a'], categoryIds: ['y', 'x'] }]
62
- const right: EffectiveAssortmentScope = [{ categoryIds: ['x', 'y'], tagIds: ['a', 'b'] }]
63
- expect(canonicalizeEffectiveScope(left)).toBe(canonicalizeEffectiveScope(right))
64
- expect(hashEffectiveScope(left)).toBe(hashEffectiveScope(right))
65
- })
66
-
67
- it('is invariant to branch order and collapses identical branches', () => {
68
- const forward: EffectiveAssortmentScope = [{ categoryIds: ['a'] }, { tagIds: ['b'] }]
69
- const reversed: EffectiveAssortmentScope = [{ tagIds: ['b'] }, { categoryIds: ['a'] }, { categoryIds: ['a'] }]
70
- expect(canonicalizeEffectiveScope(forward)).toBe(canonicalizeEffectiveScope(reversed))
71
- })
72
-
73
- it('canonicalizes nested allOf entries and their order', () => {
74
- const left: EffectiveAssortmentScope = [
75
- { categoryIds: ['a'], allOf: [{ tagIds: ['t2', 't1'] }, { excludeProductIds: ['p1'], allOf: [{ categoryIds: ['c2', 'c1'] }] }] },
76
- ]
77
- const right: EffectiveAssortmentScope = [
78
- { allOf: [{ allOf: [{ categoryIds: ['c1', 'c2'] }], excludeProductIds: ['p1'] }, { tagIds: ['t1', 't2'] }], categoryIds: ['a'] },
79
- ]
80
- expect(canonicalizeEffectiveScope(left)).toBe(canonicalizeEffectiveScope(right))
81
- })
82
-
83
- it('distinguishes scopes that match differently', () => {
84
- expect(canonicalizeEffectiveScope([{ categoryIds: ['a'] }])).not.toBe(canonicalizeEffectiveScope([{ tagIds: ['a'] }]))
85
- expect(canonicalizeEffectiveScope([{ categoryIds: ['a'], tagIds: ['b'] }])).not.toBe(
86
- canonicalizeEffectiveScope([{ categoryIds: ['a'] }, { tagIds: ['b'] }]),
87
- )
88
- expect(canonicalizeEffectiveScope([{ categoryIds: ['a'] }])).not.toBe(
89
- canonicalizeEffectiveScope([{ excludeCategoryIds: ['a'] }]),
90
- )
91
- })
92
- })
93
-
94
- describe('hashEffectiveScope', () => {
95
- it('returns 16 lowercase hex characters', () => {
96
- expect(hashEffectiveScope([{ categoryIds: ['a'] }])).toMatch(/^[0-9a-f]{16}$/)
97
- expect(hashEffectiveScope(null)).toMatch(/^[0-9a-f]{16}$/)
98
- })
99
-
100
- it('property: shuffling branch, key and id order preserves the hash', () => {
101
- for (let seed = 1; seed <= 200; seed += 1) {
102
- const rng = mulberry32(seed)
103
- const scope = randomEffective(rng)
104
- const shuffled = scope === null ? null : shuffle(rng, scope.map((branch) => shuffleScope(rng, branch)))
105
- expect(hashEffectiveScope(shuffled)).toBe(hashEffectiveScope(scope))
106
- }
107
- })
108
-
109
- it('property: equal canonical form if and only if equal hash across random pairs', () => {
110
- const rng = mulberry32(4242)
111
- const scopes: EffectiveAssortmentScope[] = []
112
- for (let index = 0; index < 60; index += 1) scopes.push(randomEffective(rng))
113
- for (const left of scopes) {
114
- for (const right of scopes) {
115
- const sameCanonical = canonicalizeEffectiveScope(left) === canonicalizeEffectiveScope(right)
116
- const sameHash = hashEffectiveScope(left) === hashEffectiveScope(right)
117
- expect(sameHash).toBe(sameCanonical)
118
- }
119
- }
120
- })
121
- })
@@ -1,41 +0,0 @@
1
- import type { AssortmentScope, EffectiveAssortmentScope } from './types'
2
-
3
- const ID_LIST_KEYS = [
4
- 'categoryIds',
5
- 'excludeCategoryIds',
6
- 'excludeProductIds',
7
- 'excludeTagIds',
8
- 'tagIds',
9
- ] as const
10
-
11
- function compareStrings(left: string, right: string): number {
12
- if (left < right) return -1
13
- if (left > right) return 1
14
- return 0
15
- }
16
-
17
- function sortedUnique(values: string[]): string[] {
18
- return Array.from(new Set(values)).sort(compareStrings)
19
- }
20
-
21
- function canonicalizeBranch(scope: AssortmentScope): string {
22
- const members: string[] = []
23
- const nested = (scope.allOf ?? []).map(canonicalizeBranch)
24
- if (nested.length > 0) members.push(`"allOf":[${sortedUnique(nested).join(',')}]`)
25
- for (const key of ID_LIST_KEYS) {
26
- const ids = scope[key] ?? []
27
- if (ids.length > 0) members.push(`${JSON.stringify(key)}:${JSON.stringify(sortedUnique(ids))}`)
28
- }
29
- return `{${members.join(',')}}`
30
- }
31
-
32
- /**
33
- * Deterministic serialization of a resolved scope. `null` (unrestricted) serializes as `null`
34
- * and `[]` (deny-all) as `[]`, so the two never collide. Empty and absent arrays are
35
- * equivalent, id lists are sorted and deduplicated, and OR-branches and `allOf` entries are
36
- * ordered by their own canonical form with identical ones collapsed.
37
- */
38
- export function canonicalizeEffectiveScope(scope: EffectiveAssortmentScope): string {
39
- if (scope === null) return 'null'
40
- return `[${sortedUnique(scope.map(canonicalizeBranch)).join(',')}]`
41
- }
@@ -1,8 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- import { canonicalizeEffectiveScope } from './canonicalizeEffectiveScope'
3
- import type { EffectiveAssortmentScope } from './types'
4
-
5
- /** 16-hex-character sha256 digest of the canonical scope (SPEC-029 §6.1 truncation). Server-only: uses node:crypto. */
6
- export function hashEffectiveScope(scope: EffectiveAssortmentScope): string {
7
- return createHash('sha256').update(canonicalizeEffectiveScope(scope)).digest('hex').slice(0, 16)
8
- }