@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7994.1.c9f31972aa

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.
@@ -0,0 +1,156 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawn } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import test from 'node:test'
7
+
8
+ import { LLM_PROVIDERS } from '../providers.mjs'
9
+
10
+ const providerModule = new URL('../providers.mjs', import.meta.url).href
11
+ const stepsModule = new URL('../steps.mjs', import.meta.url).href
12
+
13
+ async function runProvider({ interactive = false, options = {}, answers = [], rootContents = 'EXISTING=keep\n', appContents = 'APP_EXISTING=keep\n', ambient = {}, step = false } = {}) {
14
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'om-starter-provider-'))
15
+ const rootEnv = path.join(root, '.env')
16
+ const appEnv = path.join(root, 'apps', 'mercato', '.env')
17
+ fs.mkdirSync(path.dirname(appEnv), { recursive: true })
18
+ fs.writeFileSync(rootEnv, rootContents)
19
+ fs.writeFileSync(appEnv, appContents)
20
+ const env = { ...process.env }
21
+ for (const entry of LLM_PROVIDERS) {
22
+ delete env[entry.keyEnv]
23
+ if (entry.baseUrlEnv) delete env[entry.baseUrlEnv]
24
+ }
25
+ Object.assign(env, ambient, {
26
+ OM_TEST_PROVIDER_INPUT: JSON.stringify({ providerModule, stepsModule, interactive, files: { rootEnv, appEnv }, options, step, repoRoot: root }),
27
+ })
28
+ const script = `
29
+ const input = JSON.parse(process.env.OM_TEST_PROVIDER_INPUT)
30
+ const { ensureLlmProvider } = await import(input.providerModule)
31
+ const { llmProviderStep, runSteps } = await import(input.stepsModule)
32
+ Object.defineProperty(process.stdin, 'isTTY', { value: input.interactive })
33
+ const outcome = input.step
34
+ ? await runSteps([llmProviderStep, { id: 'next', title: 'Next step', apply: async () => console.log('NEXT_STEP_REACHED') }], { repoRoot: input.repoRoot, flags: { nonInteractive: true }, log: console.log })
35
+ : await ensureLlmProvider(input.files, input.options)
36
+ console.log('PROVIDER_RESULT=' + JSON.stringify(outcome))
37
+ `
38
+ try {
39
+ const output = await new Promise((resolve, reject) => {
40
+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { env, stdio: ['pipe', 'pipe', 'pipe'] })
41
+ let combined = ''
42
+ let promptOutput = ''
43
+ let nextAnswer = 0
44
+ const timeout = setTimeout(() => {
45
+ child.kill()
46
+ reject(new Error(`Provider prompt did not finish: ${combined}`))
47
+ }, 5000)
48
+ child.stdout.on('data', (chunk) => {
49
+ combined += chunk
50
+ promptOutput += chunk
51
+ const pending = answers[nextAnswer]
52
+ if (pending && promptOutput.includes(pending.prompt)) {
53
+ promptOutput = ''
54
+ nextAnswer += 1
55
+ child.stdin.write(`${pending.answer}\n`)
56
+ }
57
+ })
58
+ child.stderr.on('data', (chunk) => { combined += chunk })
59
+ child.on('error', (error) => { clearTimeout(timeout); reject(error) })
60
+ child.on('close', (code) => {
61
+ clearTimeout(timeout)
62
+ if (code !== 0) reject(new Error(`Provider child exited ${code}: ${combined}`))
63
+ else resolve(combined)
64
+ })
65
+ })
66
+ const match = output.match(/PROVIDER_RESULT=(.*)/)
67
+ assert.ok(match, output)
68
+ return {
69
+ outcome: JSON.parse(match[1]),
70
+ output,
71
+ rootContents: fs.readFileSync(rootEnv, 'utf8'),
72
+ appContents: fs.readFileSync(appEnv, 'utf8'),
73
+ }
74
+ } finally {
75
+ fs.rmSync(root, { recursive: true, force: true })
76
+ }
77
+ }
78
+
79
+ for (const scenario of [
80
+ { name: 'non-interactive flag', options: { nonInteractive: true } },
81
+ { name: 'non-TTY input', options: {} },
82
+ { name: 'explicit skip flag', options: { skipPrompt: true }, interactive: true },
83
+ ]) {
84
+ test(`optional provider setup continues without credentials with ${scenario.name}`, async () => {
85
+ const result = await runProvider(scenario)
86
+ assert.equal(result.outcome, 'skipped')
87
+ assert.equal(result.rootContents, 'EXISTING=keep\n')
88
+ assert.equal(result.appContents, 'APP_EXISTING=keep\n')
89
+ assert.match(result.output, /continuing without AI/i)
90
+ assert.doesNotMatch(result.output, /Choose a provider/)
91
+ })
92
+ }
93
+
94
+ for (const answer of ['', '0']) {
95
+ test(`interactive provider selection ${JSON.stringify(answer)} skips without changing environment files`, async () => {
96
+ const result = await runProvider({ interactive: true, answers: [{ prompt: 'Choose a provider', answer }] })
97
+ assert.equal(result.outcome, 'skipped')
98
+ assert.match(result.output, /\[ 0\] Skip for now/)
99
+ assert.equal(result.rootContents, 'EXISTING=keep\n')
100
+ assert.equal(result.appContents, 'APP_EXISTING=keep\n')
101
+ })
102
+ }
103
+
104
+ test('an empty required API key skips AI instead of trapping setup in the provider menu', async () => {
105
+ const result = await runProvider({
106
+ interactive: true,
107
+ answers: [{ prompt: 'Choose a provider', answer: '1' }, { prompt: 'Paste your OpenAI API key', answer: '' }],
108
+ })
109
+ assert.equal(result.outcome, 'skipped')
110
+ assert.equal(result.rootContents, 'EXISTING=keep\n')
111
+ assert.equal(result.appContents, 'APP_EXISTING=keep\n')
112
+ assert.doesNotMatch(result.output, /Try again/)
113
+ })
114
+
115
+ test('configured provider still synchronizes the app environment when prompting is skipped', async () => {
116
+ const result = await runProvider({
117
+ options: { skipPrompt: true },
118
+ rootContents: 'OM_AI_PROVIDER=azure\nOM_AI_MODEL=fixture-deployment\nAZURE_OPENAI_API_KEY=fixture-key\n',
119
+ appContents: 'OM_AI_PROVIDER=openai\nAZURE_OPENAI_API_KEY=\n',
120
+ })
121
+ assert.equal(result.outcome, 'configured')
122
+ assert.match(result.appContents, /OM_AI_PROVIDER=azure/)
123
+ assert.match(result.appContents, /AZURE_OPENAI_API_KEY=fixture-key/)
124
+ assert.doesNotMatch(result.output, /fixture-key/)
125
+ })
126
+
127
+ test('optional AI setup lets the following startup step run without credentials', async () => {
128
+ const result = await runProvider({ step: true })
129
+ assert.equal(result.outcome.ok, true)
130
+ assert.match(result.output, /NEXT_STEP_REACHED/)
131
+ assert.equal(result.rootContents, 'EXISTING=keep\n')
132
+ })
133
+
134
+
135
+ test('a user can still configure a provider interactively and synchronize the app environment', async () => {
136
+ const result = await runProvider({
137
+ interactive: true,
138
+ answers: [
139
+ { prompt: 'Choose a provider', answer: '1' },
140
+ { prompt: 'Paste your OpenAI API key', answer: 'fixture-interactive-key' },
141
+ { prompt: 'OpenAI base URL', answer: '' },
142
+ { prompt: 'OpenAI model', answer: '' },
143
+ ],
144
+ })
145
+ assert.equal(result.outcome, 'configured')
146
+ assert.match(result.rootContents, /OPENAI_API_KEY=fixture-interactive-key/)
147
+ assert.match(result.appContents, /OM_AI_PROVIDER=openai/)
148
+ assert.match(result.appContents, /OPENAI_API_KEY=fixture-interactive-key/)
149
+ assert.doesNotMatch(result.output, /fixture-interactive-key/)
150
+ })
151
+
152
+
153
+ test('optional AI skip output separates its warning with a blank line and wide-glyph spacing', async () => {
154
+ const result = await runProvider({ step: true })
155
+ assert.match(result.output, /\n[ \t]*\n[ \t]*⚠️ {2}Continuing without AI/)
156
+ })
@@ -0,0 +1,241 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import test from 'node:test'
6
+ import { verifyServiceConnections, ServiceConnectionError } from '../service-connections.mjs'
7
+ import { serviceConnectionsStep, runSteps } from '../steps.mjs'
8
+
9
+ const databaseUrl = 'postgres://fixture:db-secret@127.0.0.1:5432/fixture?application_name=query-secret'
10
+ const env = { DATABASE_URL: databaseUrl, REDIS_URL: 'redis://:redis-secret@127.0.0.1:6379/2', QUEUE_REDIS_URL: 'redis://:queue-secret@127.0.0.1:6380/3', MEILISEARCH_HOST: 'http://127.0.0.1:7700', MEILISEARCH_API_KEY: 'meili-secret' }
11
+
12
+ function clients({ postgresFailure, redisFailure, redisError = 'WRONGPASS redis-secret queue-secret', queryFailure, neverConnect = false } = {}) {
13
+ const calls = []
14
+ const closed = []
15
+ class Client {
16
+ constructor(options) { calls.push(['postgres-options', options]) }
17
+ async connect() { if (neverConnect) return new Promise(() => {}); if (postgresFailure) throw postgresFailure }
18
+ async query(sql) { calls.push(['query', sql]); if (queryFailure) throw queryFailure; return { rows: [{ value: 1 }] } }
19
+ async end() { closed.push('postgres') }
20
+ }
21
+ class Redis {
22
+ constructor(url, options) { this.url = url; calls.push(['redis-options', url, options]) }
23
+ on(_event, handler) { this.onError = handler }
24
+ async connect() { if (redisFailure?.(this.url)) throw new Error(redisError) }
25
+ async ping() { calls.push(['ping', this.url]); return 'PONG' }
26
+ disconnect() { closed.push(this.url) }
27
+ }
28
+ return { calls, closed, loadModule: async (_root, name) => name === 'pg' ? { Client } : Redis }
29
+ }
30
+
31
+ function options(mock, overrides = {}) {
32
+ return { projectDir: '/missing-fixture', env, loadModule: mock.loadModule, log: () => {}, fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ results: [] }), body: { cancel: async () => {} } }), ...overrides }
33
+ }
34
+
35
+ function redacted(error) {
36
+ for (const secret of ['db-secret', 'query-secret', 'redis-secret', 'queue-secret', 'meili-secret']) assert.ok(!error.message.includes(secret), error.message)
37
+ return true
38
+ }
39
+
40
+ test('verifies PostgreSQL query, every configured Redis consumer and a protected Meilisearch API', async () => {
41
+ const mock = clients()
42
+ let responseClosed = false
43
+ const result = await verifyServiceConnections(options(mock, { fetchImpl: async (url, request) => {
44
+ assert.equal(url.pathname, '/indexes')
45
+ assert.equal(request.headers.Authorization, 'Bearer meili-secret')
46
+ assert.ok(request.signal)
47
+ return { ok: true, status: 200, json: async () => ({ results: [] }), body: { cancel: async () => { responseClosed = true } } }
48
+ } }))
49
+ assert.deepEqual(result.checked, ['DATABASE_URL', 'REDIS_URL', 'QUEUE_REDIS_URL', 'MEILISEARCH_HOST'])
50
+ assert.deepEqual(mock.calls.filter(([kind]) => kind === 'query'), [['query', 'SELECT 1']])
51
+ assert.deepEqual(mock.calls.filter(([kind]) => kind === 'ping').map(([, url]) => url), [env.REDIS_URL, env.QUEUE_REDIS_URL])
52
+ assert.equal(mock.closed.length, 3)
53
+ assert.equal(responseClosed, true)
54
+ })
55
+
56
+ test('the documents collaboration Redis is only verified when collaboration is enabled', async () => {
57
+ const collabEnv = { DATABASE_URL: databaseUrl, DOCUMENTS_COLLAB_REDIS_URL: 'redis://127.0.0.1:6379' }
58
+ const disabled = clients({ redisFailure: () => true })
59
+ const result = await verifyServiceConnections(options(disabled, { env: collabEnv }))
60
+ assert.deepEqual(result.checked, ['DATABASE_URL'])
61
+ assert.equal(disabled.calls.filter(([kind]) => kind === 'redis-options').length, 0)
62
+
63
+ const enabled = clients({ redisFailure: () => true })
64
+ await assert.rejects(
65
+ verifyServiceConnections(options(enabled, { env: { ...collabEnv, NEXT_PUBLIC_DOCUMENTS_COLLAB_URL: 'ws://localhost:4101' } })),
66
+ /DOCUMENTS_COLLAB_REDIS_URL/,
67
+ )
68
+ })
69
+
70
+ test('PostgreSQL credential rejection is actionable, redacted and closes the connection', async () => {
71
+ const mock = clients({ postgresFailure: Object.assign(new Error('db-secret query-secret'), { code: '28P01' }) })
72
+ await assert.rejects(verifyServiceConnections(options(mock)), (error) => {
73
+ assert.ok(error instanceof ServiceConnectionError)
74
+ assert.equal(error.service, 'PostgreSQL')
75
+ assert.equal(error.kind, 'authentication')
76
+ assert.match(error.message, /DATABASE_URL/)
77
+ return redacted(error)
78
+ })
79
+ assert.deepEqual(mock.closed, ['postgres'])
80
+ })
81
+
82
+ test('a separate Redis consumer with wrong credentials stops verification and disconnects', async () => {
83
+ const mock = clients({ redisFailure: (url) => url === env.QUEUE_REDIS_URL })
84
+ await assert.rejects(verifyServiceConnections(options(mock)), (error) => {
85
+ assert.equal(error.kind, 'authentication')
86
+ assert.equal(error.envKey, 'QUEUE_REDIS_URL')
87
+ return redacted(error)
88
+ })
89
+ assert.deepEqual(mock.closed, ['postgres', env.REDIS_URL, env.QUEUE_REDIS_URL])
90
+ })
91
+
92
+ test('Meilisearch rejects an invalid key even when the server responds to unauthenticated health', async () => {
93
+ const mock = clients()
94
+ let closed = false
95
+ await assert.rejects(verifyServiceConnections(options(mock, { fetchImpl: async (url) => {
96
+ assert.equal(url.pathname, '/indexes')
97
+ return { ok: false, status: 401, body: { cancel: async () => { closed = true } } }
98
+ } })), (error) => {
99
+ assert.equal(error.service, 'Meilisearch')
100
+ assert.equal(error.kind, 'authentication')
101
+ return redacted(error)
102
+ })
103
+ assert.equal(closed, true)
104
+ })
105
+
106
+ test('unreachable and timed-out PostgreSQL fail with bounded, sanitized errors', async () => {
107
+ for (const config of [{ postgresFailure: Object.assign(new Error('db-secret'), { code: 'ECONNREFUSED' }) }, { neverConnect: true }]) {
108
+ const mock = clients(config)
109
+ await assert.rejects(verifyServiceConnections(options(mock, { timeoutMs: 20 })), (error) => {
110
+ assert.equal(error.kind, 'unreachable')
111
+ return redacted(error)
112
+ })
113
+ assert.deepEqual(mock.closed, ['postgres'])
114
+ }
115
+ })
116
+
117
+ test('loads env files with app and shell precedence while leaving their contents unchanged', async () => {
118
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'service-check-env-'))
119
+ try {
120
+ const root = path.join(dir, 'root.env')
121
+ const app = path.join(dir, '.env')
122
+ fs.writeFileSync(root, 'DATABASE_URL=postgres://root:pw@localhost/root\n')
123
+ fs.writeFileSync(app, 'DATABASE_URL=postgres://app:pw@localhost/app\n')
124
+ const mock = clients()
125
+ await verifyServiceConnections(options(mock, { projectDir: dir, envFiles: [root], env: {} }))
126
+ assert.equal(mock.calls[0][1].connectionString, 'postgres://app:pw@localhost/app')
127
+ assert.equal(fs.readFileSync(app, 'utf8'), 'DATABASE_URL=postgres://app:pw@localhost/app\n')
128
+ const shell = clients()
129
+ await verifyServiceConnections(options(shell, { projectDir: dir, envFiles: [root], env: { DATABASE_URL: databaseUrl } }))
130
+ assert.equal(shell.calls[0][1].connectionString, databaseUrl)
131
+ } finally { fs.rmSync(dir, { recursive: true, force: true }) }
132
+ })
133
+
134
+ test('missing dependencies and invalid URLs fail before setup mutates a database', async () => {
135
+ const mock = clients()
136
+ await assert.rejects(verifyServiceConnections(options(mock, { env: {} })), /DATABASE_URL.*missing or invalid/)
137
+ await assert.rejects(verifyServiceConnections(options(mock, { loadModule: async () => { throw Object.assign(new Error('missing'), { code: 'MISSING_DEPENDENCY' }) } })), /yarn install/)
138
+ const order = []
139
+ const ctx = { mode: 'hybrid', repoRoot: '/missing', env: {}, log: () => {}, verifyServiceConnectionsImpl: async () => { order.push('credentials'); throw new Error('Credentials rejected') } }
140
+ const result = await runSteps([serviceConnectionsStep, { id: 'database', title: 'Database', apply: async () => order.push('database') }], ctx)
141
+ assert.equal(result.ok, false)
142
+ assert.equal(result.failedStep, 'service-connections')
143
+ assert.deepEqual(order, ['credentials'])
144
+ })
145
+
146
+ test('shared verifier and template copy stay byte-identical', () => {
147
+ assert.deepEqual(fs.readFileSync(new URL('../service-connections.mjs', import.meta.url)), fs.readFileSync(new URL('../../../create-app/template/scripts/dev-service-connections.mjs', import.meta.url)))
148
+ })
149
+
150
+
151
+ test('Meilisearch checks the application API key without substituting a server-only master key', async () => {
152
+ const mock = clients()
153
+ const configuration = { ...env, MEILISEARCH_API_KEY: '', MEILISEARCH_MASTER_KEY: 'server-master-secret' }
154
+ await assert.rejects(verifyServiceConnections(options(mock, { env: configuration, fetchImpl: async (_url, request) => {
155
+ assert.deepEqual(request.headers, {})
156
+ return { ok: false, status: 401, body: { cancel: async () => {} } }
157
+ } })), (error) => {
158
+ assert.equal(error.kind, 'authentication')
159
+ assert.ok(!error.message.includes('server-master-secret'))
160
+ return true
161
+ })
162
+ })
163
+
164
+ test('fetch connection causes and abort timeouts are reported as unreachable without leaking their cause', async () => {
165
+ for (const failure of [new TypeError('fetch failed', { cause: Object.assign(new Error('meili-secret'), { code: 'ECONNREFUSED' }) }), Object.assign(new Error('meili-secret'), { name: 'TimeoutError' })]) {
166
+ const mock = clients()
167
+ await assert.rejects(verifyServiceConnections(options(mock, { fetchImpl: async () => { throw failure } })), (error) => {
168
+ assert.equal(error.kind, 'unreachable')
169
+ return redacted(error)
170
+ })
171
+ }
172
+ })
173
+
174
+
175
+ test('Meilisearch rejects an unrelated HTTP 200 service or malformed API body', async () => {
176
+ for (const json of [async () => ({ application: 'unrelated' }), async () => { throw new SyntaxError('HTML response') }]) {
177
+ const mock = clients()
178
+ let closed = false
179
+ await assert.rejects(verifyServiceConnections(options(mock, { fetchImpl: async () => ({ ok: true, status: 200, json, body: { cancel: async () => { closed = true } } }) })), (error) => {
180
+ assert.equal(error.service, 'Meilisearch')
181
+ assert.equal(error.kind, 'connection')
182
+ return redacted(error)
183
+ })
184
+ assert.equal(closed, true)
185
+ }
186
+ })
187
+
188
+
189
+ test('native fetch responses pass after their JSON stream is consumed and retain authentication errors', async () => {
190
+ const mock = clients()
191
+ const result = await verifyServiceConnections(options(mock, { fetchImpl: async () => new Response(JSON.stringify({ results: [] }), { status: 200 }) }))
192
+ assert.equal(result.ok, true)
193
+ await assert.rejects(verifyServiceConnections(options(clients(), { fetchImpl: async () => new Response('Unauthorized', { status: 401 }) })), (error) => {
194
+ assert.equal(error.service, 'Meilisearch')
195
+ assert.equal(error.kind, 'authentication')
196
+ return true
197
+ })
198
+ })
199
+
200
+
201
+ test('Redis AUTH against a server without a configured password is an actionable credential failure', async () => {
202
+ const mock = clients({ redisFailure: () => true, redisError: 'ERR AUTH <password> called without any password configured for the default user' })
203
+ await assert.rejects(verifyServiceConnections(options(mock)), (error) => {
204
+ assert.equal(error.service, 'Redis')
205
+ assert.equal(error.kind, 'authentication')
206
+ return redacted(error)
207
+ })
208
+ })
209
+
210
+
211
+ test('Redis preserves emitted authentication details when connect rejects with a generic closed-connection error', async () => {
212
+ class Redis {
213
+ on(_event, handler) { this.onError = handler }
214
+ async connect() { this.onError(new Error('WRONGPASS redis-secret')); throw new Error('Connection is closed.') }
215
+ disconnect() {}
216
+ }
217
+ const mock = clients()
218
+ await assert.rejects(verifyServiceConnections(options(mock, { loadModule: async (root, name) => name === 'ioredis' ? Redis : mock.loadModule(root, name) })), (error) => {
219
+ assert.equal(error.kind, 'authentication')
220
+ return redacted(error)
221
+ })
222
+ })
223
+
224
+
225
+ test('a missing selected PostgreSQL database verifies credentials read-only through maintenance before initialization creates it', async () => {
226
+ const calls = []
227
+ const closed = []
228
+ class Client {
229
+ constructor(options) { this.url = new URL(options.connectionString); calls.push(this.url.pathname) }
230
+ on() {}
231
+ async connect() { if (this.url.pathname === '/fresh') throw Object.assign(new Error('does not exist'), { code: '3D000' }) }
232
+ async query(sql) { assert.equal(sql, 'SELECT 1'); calls.push(sql) }
233
+ async end() { closed.push(this.url.pathname) }
234
+ }
235
+ const messages = []
236
+ const result = await verifyServiceConnections({ projectDir: '/missing', env: { DATABASE_URL: 'postgres://fixture:pw@localhost/fresh' }, loadModule: async () => ({ Client }), log: (line) => messages.push(line) })
237
+ assert.equal(result.ok, true)
238
+ assert.deepEqual(calls, ['/fresh', '/postgres', 'SELECT 1'])
239
+ assert.deepEqual(closed, ['/fresh', '/postgres'])
240
+ assert.match(messages.join('\n'), /initialization will handle its creation/)
241
+ })