anhedral 0.10.1 → 0.11.1

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 (183) hide show
  1. package/README.md +79 -124
  2. package/assets/patches/LICENSE.braces +21 -0
  3. package/assets/patches/LICENSE.node-forge +50 -0
  4. package/assets/patches/audit-deps.mjs +167 -0
  5. package/assets/patches/braces@3.0.3.patch +127 -0
  6. package/assets/patches/node-forge@1.4.0.patch +41 -0
  7. package/dist/auth-schema.js +3 -3
  8. package/dist/bin.js +284 -163
  9. package/dist/capabilities.d.ts +4 -4
  10. package/dist/capabilities.js +6 -2
  11. package/dist/capability-contract.d.ts +47 -0
  12. package/dist/capability-contract.js +153 -0
  13. package/dist/catalog-model.d.ts +24 -0
  14. package/dist/catalog-model.js +1 -0
  15. package/dist/catalog-registration.d.ts +16 -0
  16. package/dist/catalog-registration.js +22 -0
  17. package/dist/catalog-snapshot.d.ts +5 -0
  18. package/dist/catalog-snapshot.js +97 -0
  19. package/dist/cli-arguments.d.ts +16 -0
  20. package/dist/cli-arguments.js +115 -0
  21. package/dist/cli-output.d.ts +8 -0
  22. package/dist/cli-output.js +236 -0
  23. package/dist/cloudflare.d.ts +14 -3
  24. package/dist/cloudflare.js +196 -36
  25. package/dist/command-schema.d.ts +21 -0
  26. package/dist/command-schema.js +418 -0
  27. package/dist/delivery.d.ts +12 -5
  28. package/dist/delivery.js +173 -39
  29. package/dist/dependencies.d.ts +24 -0
  30. package/dist/dependencies.js +48 -0
  31. package/dist/dependency-patches.d.ts +7 -0
  32. package/dist/dependency-patches.js +125 -0
  33. package/dist/index.d.ts +26 -1
  34. package/dist/index.js +17 -1
  35. package/dist/inspector-model.d.ts +123 -0
  36. package/dist/inspector-model.js +1 -0
  37. package/dist/integration-service-readers.d.ts +13 -0
  38. package/dist/integration-service-readers.js +173 -0
  39. package/dist/lifecycle-model.d.ts +15 -0
  40. package/dist/lifecycle-model.js +20 -0
  41. package/dist/lifecycle.d.ts +11 -0
  42. package/dist/lifecycle.js +91 -0
  43. package/dist/mobile-delivery.d.ts +100 -0
  44. package/dist/mobile-delivery.js +319 -0
  45. package/dist/neon-service-data.d.ts +8 -0
  46. package/dist/neon-service-data.js +117 -0
  47. package/dist/platforms/mobile.js +8 -5
  48. package/dist/pnpm-policy.d.ts +2 -2
  49. package/dist/pnpm-policy.js +19 -45
  50. package/dist/project-catalog.d.ts +41 -0
  51. package/dist/project-catalog.js +288 -0
  52. package/dist/project-config.d.ts +14 -0
  53. package/dist/project-config.js +89 -0
  54. package/dist/project-inspector.d.ts +4 -0
  55. package/dist/project-inspector.js +702 -0
  56. package/dist/project-lifecycle.d.ts +25 -0
  57. package/dist/project-lifecycle.js +57 -0
  58. package/dist/project-state.d.ts +22 -1
  59. package/dist/project-state.js +361 -27
  60. package/dist/provider-auth.d.ts +41 -0
  61. package/dist/provider-auth.js +209 -0
  62. package/dist/provider-readiness.js +27 -10
  63. package/dist/providers/adapters.d.ts +17 -0
  64. package/dist/providers/adapters.js +272 -0
  65. package/dist/providers/api.d.ts +29 -0
  66. package/dist/providers/api.js +253 -0
  67. package/dist/providers/config.d.ts +15 -0
  68. package/dist/providers/config.js +182 -0
  69. package/dist/providers/definitions.d.ts +318 -0
  70. package/dist/providers/definitions.js +127 -0
  71. package/dist/providers/provision.d.ts +24 -0
  72. package/dist/providers/provision.js +76 -0
  73. package/dist/providers/receipts.d.ts +20 -0
  74. package/dist/providers/receipts.js +66 -0
  75. package/dist/providers/recovery-verification.d.ts +7 -0
  76. package/dist/providers/recovery-verification.js +112 -0
  77. package/dist/providers/recovery.d.ts +30 -0
  78. package/dist/providers/recovery.js +34 -0
  79. package/dist/providers/runtime.d.ts +10 -0
  80. package/dist/providers/runtime.js +254 -0
  81. package/dist/providers/schema.d.ts +28 -0
  82. package/dist/providers/schema.js +49 -0
  83. package/dist/providers/state.d.ts +55 -0
  84. package/dist/providers/state.js +289 -0
  85. package/dist/provision.d.ts +10 -1
  86. package/dist/provision.js +91 -4
  87. package/dist/r2-service-data.d.ts +2 -0
  88. package/dist/r2-service-data.js +136 -0
  89. package/dist/readiness.js +9 -13
  90. package/dist/registry/add.d.ts +6 -0
  91. package/dist/registry/add.js +93 -22
  92. package/dist/registry/commands.d.ts +3 -2
  93. package/dist/registry/commands.js +52 -15
  94. package/dist/registry/options.d.ts +1 -1
  95. package/dist/registry/options.js +5 -4
  96. package/dist/registry/preview.d.ts +11 -0
  97. package/dist/registry/preview.js +91 -0
  98. package/dist/registry/receipt.d.ts +1 -0
  99. package/dist/registry/receipt.js +19 -4
  100. package/dist/registry/resolve.js +5 -1
  101. package/dist/registry/usage.d.ts +10 -0
  102. package/dist/registry/usage.js +18 -37
  103. package/dist/render.d.ts +2 -0
  104. package/dist/render.js +6 -0
  105. package/dist/runtime-policy.d.ts +4 -0
  106. package/dist/runtime-policy.js +21 -0
  107. package/dist/scaffold/auth.js +3 -19
  108. package/dist/scaffold/bootstrap.js +2 -2
  109. package/dist/scaffold/compose.js +9 -3
  110. package/dist/scaffold/database.js +107 -25
  111. package/dist/scaffold/documentation.js +18 -13
  112. package/dist/scaffold/lint.d.ts +4 -0
  113. package/dist/scaffold/lint.js +56 -0
  114. package/dist/scaffold/neon-realtime.d.ts +2 -0
  115. package/dist/scaffold/neon-realtime.js +97 -0
  116. package/dist/scaffold/stack-documentation.js +1 -1
  117. package/dist/scaffold/void.d.ts +4 -0
  118. package/dist/scaffold/void.js +256 -0
  119. package/dist/scaffold/web.js +7 -1
  120. package/dist/scaffold/workspace.js +127 -25
  121. package/dist/service-deletion.d.ts +29 -0
  122. package/dist/service-deletion.js +195 -0
  123. package/dist/service-descriptor.d.ts +10 -0
  124. package/dist/service-descriptor.js +78 -0
  125. package/dist/service-model.d.ts +49 -0
  126. package/dist/service-model.js +8 -0
  127. package/dist/service-operations.d.ts +29 -0
  128. package/dist/service-operations.js +78 -0
  129. package/dist/service-readers.d.ts +8 -0
  130. package/dist/service-readers.js +247 -0
  131. package/dist/services-command.d.ts +39 -0
  132. package/dist/services-command.js +100 -0
  133. package/dist/ship.d.ts +348 -0
  134. package/dist/ship.js +237 -0
  135. package/dist/stack-registry.d.ts +4 -2
  136. package/dist/stack-registry.js +48 -12
  137. package/dist/standard.d.ts +2 -1
  138. package/dist/standard.js +33 -14
  139. package/dist/transaction.d.ts +2 -0
  140. package/dist/transaction.js +10 -0
  141. package/dist/util.js +17 -2
  142. package/dist/vercel.d.ts +5 -3
  143. package/dist/vercel.js +96 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/dist/vinext.d.ts +1 -0
  147. package/dist/vinext.js +13 -1
  148. package/dist/void-execution.d.ts +10 -0
  149. package/dist/void-execution.js +94 -0
  150. package/dist/void-migrations.d.ts +6 -0
  151. package/dist/void-migrations.js +110 -0
  152. package/dist/void-state.d.ts +16 -0
  153. package/dist/void-state.js +65 -0
  154. package/dist/void.d.ts +3 -0
  155. package/dist/void.js +5 -0
  156. package/docs/cli-design.md +67 -0
  157. package/docs/delivery-workflow.md +32 -17
  158. package/docs/plugin-ui.md +102 -0
  159. package/docs/provider-configuration.md +116 -0
  160. package/docs/stack-standard.md +175 -0
  161. package/docs/void-verification.md +185 -0
  162. package/package.json +29 -23
  163. package/assets/anhedral-cli-init-technical.svg +0 -322
  164. package/assets/anhedral-cli-init.svg +0 -322
  165. package/assets/anhedral-mark.svg +0 -4
  166. package/assets/anhedral.svg +0 -4
  167. package/assets/favicon.ico +0 -0
  168. package/assets/security/LICENSES.txt +0 -63
  169. package/assets/security/audit-deps.mjs +0 -300
  170. package/assets/security/braces-regression.mjs +0 -102
  171. package/assets/security/braces@3.0.3.patch +0 -285
  172. package/assets/security/decode-uri-component@0.2.2.patch +0 -149
  173. package/assets/security/decoder-regression.mjs +0 -37
  174. package/assets/security/forge-regression.mjs +0 -46
  175. package/assets/security/manifest.json +0 -53
  176. package/assets/security/node-forge@1.4.0.patch +0 -26
  177. package/dist/managed-hosting.d.ts +0 -49
  178. package/dist/managed-hosting.js +0 -373
  179. package/dist/security-backports.d.ts +0 -3
  180. package/dist/security-backports.js +0 -26
  181. package/docs/application-stack-standard.md +0 -104
  182. package/docs/managed-hosting-architecture.md +0 -87
  183. package/docs/sponsorships.md +0 -25
@@ -0,0 +1,319 @@
1
+ import path from 'node:path';
2
+ import { realpathSync, existsSync, writeFileSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { EAS_CLI_VERSION } from './dependencies.js';
6
+ import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from './bounded-file.js';
7
+ import { requiredProviders } from './provider-auth.js';
8
+ import { planProviderProvisioning, provisionSelectedProviders } from './providers/provision.js';
9
+ import { configuredRuntime, runtimeTargets, RUNTIME_KEYS } from './providers/runtime.js';
10
+ import { CREDENTIALS } from './providers/api.js';
11
+ import { atomicJson, defaultRunner } from './project-state.js';
12
+ import { withLifecycleOperation } from './lifecycle.js';
13
+ function artifactUrl(value) {
14
+ if (typeof value !== 'string')
15
+ return undefined;
16
+ try {
17
+ const url = new URL(value);
18
+ if (url.protocol !== 'https:' || url.username || url.password)
19
+ return undefined;
20
+ return url.href;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function pendingBuild(root, commit, options, projectId) {
27
+ const file = path.join(root, '.anhedral/mobile-build.pending.json');
28
+ if (!existsSync(file))
29
+ return undefined;
30
+ let pending;
31
+ try {
32
+ pending = JSON.parse(readBoundedFile(file, MAX_PROJECT_JSON_BYTES).toString('utf8'));
33
+ }
34
+ catch {
35
+ throw new Error('Invalid pending EAS build. Inspect the selected project before retrying.');
36
+ }
37
+ if (!pending ||
38
+ typeof pending !== 'object' ||
39
+ Array.isArray(pending) ||
40
+ pending.schemaVersion !== 1 ||
41
+ Object.keys(pending).some((key) => ![
42
+ 'schemaVersion',
43
+ 'status',
44
+ 'commit',
45
+ 'platform',
46
+ 'profile',
47
+ 'projectId',
48
+ 'buildId',
49
+ ].includes(key)) ||
50
+ ![undefined, 'submitting', 'queued'].includes(pending.status) ||
51
+ pending.commit !== commit ||
52
+ pending.platform !== options.platform ||
53
+ pending.profile !== options.profile ||
54
+ pending.projectId !== projectId ||
55
+ (pending.status === 'submitting'
56
+ ? Object.hasOwn(pending, 'buildId')
57
+ : typeof pending.buildId !== 'string' || !/^[a-zA-Z0-9-]{1,255}$/.test(pending.buildId)))
58
+ throw new Error('Pending EAS build differs from the selected source or profile.');
59
+ if (pending.status === 'submitting')
60
+ throw new Error('EAS submission has an unknown outcome. Reconcile the selected project before retrying.');
61
+ return pending;
62
+ }
63
+ /** EAS builds produce artifacts; store submission is a separate user action. */
64
+ export async function buildMobileApplication(root, options, run = defaultRunner) {
65
+ if (options.dryRun)
66
+ return executeMobileBuild(root, options, run);
67
+ // Validate local build configuration before creating an execution record.
68
+ await executeMobileBuild(root, { ...options, dryRun: true }, run);
69
+ return withLifecycleOperation(root, 'mobile', run, (session) => session.phase('mobile-build', () => executeMobileBuild(root, options, run)));
70
+ }
71
+ async function executeMobileBuild(root, options, run = defaultRunner) {
72
+ root = realpathSync(root);
73
+ if (!['ios', 'android'].includes(options.platform) ||
74
+ !/^[a-z][a-z0-9-]{0,63}$/.test(options.profile))
75
+ throw new Error('Select an explicit mobile platform and build profile.');
76
+ if (!requiredProviders(root).some((provider) => provider.id === 'expo'))
77
+ throw new Error('This project does not select Expo.');
78
+ const directory = realpathSync(path.join(root, 'apps/mobile'));
79
+ if (!directory.startsWith(root + path.sep))
80
+ throw new Error('Mobile app escapes project directory.');
81
+ let configuration;
82
+ try {
83
+ configuration = JSON.parse(readBoundedFile(path.join(directory, 'eas.json'), MAX_PROJECT_JSON_BYTES).toString('utf8'));
84
+ }
85
+ catch {
86
+ throw new Error('A valid EAS build configuration is required.');
87
+ }
88
+ const profile = configuration?.build?.[options.profile];
89
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile))
90
+ throw new Error('Requested EAS profile is not configured.');
91
+ if (profile.extends)
92
+ throw new Error('Resolve inherited EAS profiles before automatic delivery.');
93
+ const selectedEnvironment = profile.environment ??
94
+ (profile.developmentClient
95
+ ? 'development'
96
+ : profile.distribution === 'internal'
97
+ ? 'preview'
98
+ : 'production');
99
+ if (!['development', 'preview', 'production'].includes(selectedEnvironment))
100
+ throw new Error('Select an explicit supported EAS environment.');
101
+ const args = [
102
+ 'dlx',
103
+ `eas-cli@${EAS_CLI_VERSION}`,
104
+ 'build',
105
+ '--platform',
106
+ options.platform,
107
+ '--profile',
108
+ options.profile,
109
+ '--non-interactive',
110
+ '--json',
111
+ '--no-wait',
112
+ ];
113
+ if (options.dryRun)
114
+ return {
115
+ platform: options.platform,
116
+ profile: options.profile,
117
+ command: ['pnpm', ...args],
118
+ mutation: false,
119
+ storeSubmission: false,
120
+ integrations: planProviderProvisioning(root),
121
+ };
122
+ const app = JSON.parse(readBoundedFile(path.join(directory, 'app.json'), MAX_PROJECT_JSON_BYTES).toString('utf8')).expo;
123
+ if (['app.config.js', 'app.config.ts'].some((file) => existsSync(path.join(directory, file))))
124
+ throw new Error('Automatic EAS setup requires a static app.json with explicit owner and slug.');
125
+ if (typeof app?.owner !== 'string' ||
126
+ !/^[a-zA-Z0-9_-]+$/.test(app.owner) ||
127
+ typeof app.slug !== 'string' ||
128
+ !/^[a-zA-Z0-9_-]+$/.test(app.slug))
129
+ throw new Error('Set the intended Expo owner and slug in app.json before shipping.');
130
+ const environment = { ...process.env, CI: '1', NO_COLOR: '1' };
131
+ // Expo keeps its own login credential; server/provider keys never reach native builds.
132
+ for (const key of [...Object.values(CREDENTIALS), ...RUNTIME_KEYS])
133
+ if (!key.startsWith('EXPO_PUBLIC_'))
134
+ delete environment[key];
135
+ const source = async () => {
136
+ if (realpathSync((await run('git', ['rev-parse', '--show-toplevel'], root, environment)).trim()) !== root ||
137
+ (await run('git', ['status', '--porcelain'], root, environment)).trim())
138
+ throw new Error('Mobile delivery requires a clean application Git repository.');
139
+ const commit = (await run('git', ['rev-parse', 'HEAD'], root, environment)).trim();
140
+ if (!/^[a-f0-9]{40,64}$/.test(commit))
141
+ throw new Error('Invalid mobile source commit.');
142
+ return commit;
143
+ };
144
+ const initialCommit = await source();
145
+ // An unresolved queue mutation blocks every subsequent provisioning/configuration mutation.
146
+ pendingBuild(root, initialCommit, options, app.extra?.eas?.projectId);
147
+ await run('pnpm', ['run', 'check'], root, environment);
148
+ if ((await source()) !== initialCommit)
149
+ throw new Error('Source changed during mobile checks.');
150
+ const configured = await provisionSelectedProviders(root, false, run);
151
+ if (!configured.ready)
152
+ return {
153
+ state: 'provider-configuration-required',
154
+ deployed: false,
155
+ integrations: configured,
156
+ storeSubmission: false,
157
+ };
158
+ const runtime = configuredRuntime(root);
159
+ const commit = await source();
160
+ if (commit !== initialCommit)
161
+ throw new Error('Source changed during provider configuration.');
162
+ const cli = ['dlx', `eas-cli@${EAS_CLI_VERSION}`];
163
+ if (!app.extra?.eas?.projectId) {
164
+ await run('pnpm', [...cli, 'project:init', '--non-interactive', '--force'], directory, environment);
165
+ const linked = JSON.parse(readBoundedFile(path.join(directory, 'app.json'), MAX_PROJECT_JSON_BYTES).toString('utf8')).expo;
166
+ if (linked?.owner !== app.owner ||
167
+ linked.slug !== app.slug ||
168
+ typeof linked.extra?.eas?.projectId !== 'string' ||
169
+ !/^[a-f0-9-]{36}$/i.test(linked.extra.eas.projectId))
170
+ throw new Error('EAS did not confirm a project link for the selected owner and slug. Inspect the account before retrying.');
171
+ return {
172
+ state: 'configuration-required',
173
+ deployed: false,
174
+ storeSubmission: false,
175
+ nextAction: 'Review and commit the EAS project link written to app.json, then run ship again.',
176
+ };
177
+ }
178
+ const projectId = app.extra.eas.projectId;
179
+ if (typeof projectId !== 'string' || !/^[a-f0-9-]{36}$/i.test(projectId))
180
+ throw new Error('Invalid EAS project ID.');
181
+ const remote = await run('pnpm', [...cli, 'project:info'], directory, environment);
182
+ const remoteName = remote
183
+ .split(/\r?\n/)
184
+ .find((line) => /^fullName\s+/.test(line.trim()))
185
+ ?.trim()
186
+ .split(/\s+/)[1];
187
+ const remoteId = remote
188
+ .split(/\r?\n/)
189
+ .find((line) => /^ID\s+/.test(line.trim()))
190
+ ?.trim()
191
+ .split(/\s+/)[1];
192
+ if (remoteId !== projectId || remoteName !== `@${app.owner}/${app.slug}`)
193
+ throw new Error('EAS project identity differs from the selected owner and project.');
194
+ const values = runtimeTargets(root, runtime)['apps/mobile/.env.local'];
195
+ if (values && Object.keys(values).length) {
196
+ const file = path.join(tmpdir(), `anhedral-expo-${randomUUID()}.env`);
197
+ try {
198
+ writeFileSync(file, Object.entries(values)
199
+ .map(([key, value]) => `${key}=${JSON.stringify(value)}\n`)
200
+ .join(''), { mode: 0o600, flag: 'wx' });
201
+ await run('pnpm', [...cli, 'env:push', '--environment', selectedEnvironment, '--path', file, '--force'], directory, environment);
202
+ }
203
+ finally {
204
+ rmSync(file, { force: true });
205
+ }
206
+ }
207
+ let builds;
208
+ let expectedBuildId;
209
+ const pendingFile = path.join(root, '.anhedral/mobile-build.pending.json');
210
+ try {
211
+ const pending = pendingBuild(root, commit, options, projectId);
212
+ if (pending) {
213
+ const buildId = pending.buildId;
214
+ if (!buildId)
215
+ throw new Error('Pending EAS build has no verified ID.');
216
+ expectedBuildId = buildId;
217
+ builds = [
218
+ JSON.parse(await run('pnpm', [...cli, 'build:view', buildId, '--json'], directory, environment)),
219
+ ];
220
+ }
221
+ else {
222
+ if ((await source()) !== commit)
223
+ throw new Error('Source changed before EAS build submission.');
224
+ // Record intent before the remote queue mutation, including lost or invalid responses.
225
+ atomicJson(pendingFile, {
226
+ schemaVersion: 1,
227
+ status: 'submitting',
228
+ commit,
229
+ platform: options.platform,
230
+ profile: options.profile,
231
+ projectId,
232
+ });
233
+ builds = JSON.parse(await run('pnpm', args, directory, { ...environment, ...values }));
234
+ }
235
+ }
236
+ catch {
237
+ throw new Error('EAS build did not return verified completion; inspect the selected Expo project before retrying.');
238
+ }
239
+ if (!Array.isArray(builds) || builds.length !== 1)
240
+ throw new Error('EAS returned an unexpected build selection.');
241
+ const build = builds[0];
242
+ const downloadUrl = artifactUrl(build?.artifacts?.applicationArchiveUrl ?? build?.artifacts?.buildUrl);
243
+ if (typeof build?.id !== 'string' || !/^[a-zA-Z0-9-]{1,255}$/.test(build.id))
244
+ throw new Error('EAS did not return a valid build ID.');
245
+ if (build.project?.id !== projectId ||
246
+ build.project?.ownerAccount?.name !== app.owner ||
247
+ build.project?.slug !== app.slug)
248
+ throw new Error('EAS build belongs to a different project.');
249
+ if (build.platform !== options.platform.toUpperCase() ||
250
+ build.buildProfile !== options.profile ||
251
+ (build.environment !== undefined && build.environment !== selectedEnvironment) ||
252
+ (options.platform === 'ios' && build.isForIosSimulator !== (profile.ios?.simulator === true)))
253
+ throw new Error('EAS build platform, profile or environment differs from the selected configuration.');
254
+ if (build.gitCommitHash !== commit)
255
+ throw new Error('EAS build source differs from the selected source commit.');
256
+ if (expectedBuildId && build.id !== expectedBuildId)
257
+ throw new Error('EAS returned a different build than the recorded selection.');
258
+ atomicJson(pendingFile, {
259
+ schemaVersion: 1,
260
+ status: 'queued',
261
+ commit,
262
+ platform: options.platform,
263
+ profile: options.profile,
264
+ projectId,
265
+ buildId: build.id,
266
+ });
267
+ const buildPage = `https://expo.dev/accounts/${app.owner}/projects/${app.slug}/builds/${build.id}`;
268
+ if (['NEW', 'IN_QUEUE', 'IN_PROGRESS', 'PENDING_CANCEL'].includes(build.status))
269
+ return {
270
+ schemaVersion: 1,
271
+ state: 'building',
272
+ buildId: build.id,
273
+ buildPageUrl: buildPage,
274
+ commit,
275
+ platform: options.platform,
276
+ profile: options.profile,
277
+ storeSubmission: false,
278
+ nextAction: 'Run the same ship command again to inspect this build without creating another build.',
279
+ };
280
+ if (build.status !== 'FINISHED' || !downloadUrl)
281
+ throw new Error('EAS has not confirmed a completed downloadable build. Inspect the recorded build before retrying.');
282
+ if ((await source()) !== commit)
283
+ throw new Error('Source changed during mobile build; do not treat this artifact as the current release.');
284
+ const owner = build.project?.ownerAccount?.name;
285
+ const slug = build.project?.slug;
286
+ const buildPageUrl = typeof owner === 'string' &&
287
+ /^[a-zA-Z0-9_-]+$/.test(owner) &&
288
+ typeof slug === 'string' &&
289
+ /^[a-zA-Z0-9_-]+$/.test(slug)
290
+ ? `https://expo.dev/accounts/${owner}/projects/${slug}/builds/${build.id}`
291
+ : undefined;
292
+ const result = {
293
+ schemaVersion: 1,
294
+ projectId,
295
+ owner: app.owner,
296
+ slug: app.slug,
297
+ recordedAt: new Date().toISOString(),
298
+ ...(buildPageUrl ? { buildPageUrl } : {}),
299
+ commit,
300
+ platform: options.platform,
301
+ profile: options.profile,
302
+ buildId: build.id,
303
+ downloadUrl,
304
+ state: 'built',
305
+ storeSubmission: false,
306
+ artifact: options.platform === 'ios'
307
+ ? profile.ios?.simulator === true
308
+ ? 'ios-simulator'
309
+ : 'ipa'
310
+ : profile.android?.buildType === 'apk' ||
311
+ profile.distribution === 'internal' ||
312
+ profile.developmentClient === true
313
+ ? 'apk'
314
+ : 'aab',
315
+ };
316
+ atomicJson(path.join(root, '.anhedral/mobile-build.json'), result);
317
+ rmSync(pendingFile, { force: true });
318
+ return result;
319
+ }
@@ -0,0 +1,8 @@
1
+ import { neon } from '@neondatabase/serverless';
2
+ import type { ApiRequest } from './providers/api.js';
3
+ import { type IntegrationService } from './integration-service-readers.js';
4
+ import type { ServiceData } from './service-model.js';
5
+ export type NeonRead = (query: string, params?: unknown[]) => Promise<Record<string, unknown>[]>;
6
+ export declare function neonReadConnection(service: IntegrationService, api: ApiRequest, env?: NodeJS.ProcessEnv, createClient?: typeof neon): Promise<NeonRead>;
7
+ export declare function listNeonTables(read: NeonRead): Promise<string[]>;
8
+ export declare function browseNeonData(read: NeonRead, table: string, offset?: number): Promise<ServiceData>;
@@ -0,0 +1,117 @@
1
+ import { neon } from '@neondatabase/serverless';
2
+ import { setting } from './providers/config.js';
3
+ import { record } from './service-readers.js';
4
+ import { inspectIntegrationResource, } from './integration-service-readers.js';
5
+ const identifier = (value) => {
6
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(value))
7
+ throw new Error('Unsupported database identifier.');
8
+ return `"${value}"`;
9
+ };
10
+ const sensitive = /password|secret|token|email|phone|address|authorization|cookie|session|private|credential/i;
11
+ export async function neonReadConnection(service, api, env = process.env, createClient = neon) {
12
+ if (service.provider !== 'neon')
13
+ throw new Error('Choose the selected Neon project.');
14
+ const project = await inspectIntegrationResource(service, api);
15
+ const connection = env[`ANHEDRAL_NEON_READONLY_URL_${String(project.id)
16
+ .replace(/[^a-zA-Z0-9]/g, '_')
17
+ .toUpperCase()}`] ?? env.ANHEDRAL_NEON_READONLY_URL;
18
+ if (!connection)
19
+ throw new Error('Provide ANHEDRAL_NEON_READONLY_URL for a restricted read-only role.');
20
+ let url;
21
+ try {
22
+ url = new URL(connection);
23
+ }
24
+ catch {
25
+ throw new Error('Invalid read-only database connection.');
26
+ }
27
+ if (!['postgres:', 'postgresql:'].includes(url.protocol) ||
28
+ !url.hostname.endsWith('.neon.tech') ||
29
+ !url.username ||
30
+ !url.password ||
31
+ (url.port && url.port !== '5432') ||
32
+ decodeURIComponent(url.pathname.slice(1)) !== setting(service.settings, 'database'))
33
+ throw new Error('Read-only database connection does not match selected configuration.');
34
+ const endpoints = record(await api(`/api/v2/projects/${project.id}/endpoints`)).endpoints;
35
+ if (!Array.isArray(endpoints) ||
36
+ endpoints.length > 100 ||
37
+ !endpoints.some((endpoint) => record(endpoint).host === url.hostname.replace(/-pooler\./, '.')))
38
+ throw new Error('Database endpoint does not belong to the selected Neon project.');
39
+ const sql = createClient(connection);
40
+ return async (query, params = []) => {
41
+ try {
42
+ const result = await sql.transaction([
43
+ sql.query("SELECT set_config('statement_timeout','5000',true)"),
44
+ sql.query("SELECT current_setting('transaction_read_only') = 'on' AS read_only, (SELECT rolsuper OR rolcreatedb OR rolcreaterole FROM pg_roles WHERE rolname = current_user) AS privileged, EXISTS(SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind IN ('r','p') AND has_table_privilege(current_user,c.oid,'INSERT,UPDATE,DELETE,TRUNCATE')) AS writable"),
45
+ sql.query(query, params),
46
+ ], {
47
+ readOnly: true,
48
+ isolationLevel: 'RepeatableRead',
49
+ fetchOptions: { signal: AbortSignal.timeout(10000), redirect: 'error' },
50
+ });
51
+ const role = result[1]?.[0];
52
+ if (role?.read_only !== true || role.privileged !== false || role.writable !== false)
53
+ throw new Error('Restricted read-only role required.');
54
+ if (!Array.isArray(result[2]) || result[2].length > 1001)
55
+ throw new Error('Database response exceeded limits.');
56
+ return result[2].map(record);
57
+ }
58
+ catch {
59
+ throw new Error('Neon read failed. Check the selected endpoint, restricted role, read permissions and query limits.');
60
+ }
61
+ };
62
+ }
63
+ export async function listNeonTables(read) {
64
+ const rows = await read("SELECT table_name AS name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name LIMIT 1001");
65
+ if (rows.length > 1000)
66
+ throw new Error('Database schema exceeds its table limit.');
67
+ return rows.map((row) => {
68
+ if (typeof row.name !== 'string')
69
+ throw new Error('Invalid database table.');
70
+ identifier(row.name);
71
+ return row.name;
72
+ });
73
+ }
74
+ export async function browseNeonData(read, table, offset = 0) {
75
+ identifier(table);
76
+ if (!Number.isSafeInteger(offset) ||
77
+ offset < 0 ||
78
+ offset > 10000 ||
79
+ !(await listNeonTables(read)).includes(table))
80
+ throw new Error('Choose a bounded existing table page.');
81
+ const fields = await read("SELECT column_name AS name FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 ORDER BY ordinal_position LIMIT 51", [table]);
82
+ if (fields.length > 50 || !fields.length)
83
+ throw new Error('Table exceeds its supported column limit.');
84
+ const columns = fields.map((row) => {
85
+ if (typeof row.name !== 'string')
86
+ throw new Error('Invalid database column.');
87
+ identifier(row.name);
88
+ return row.name;
89
+ });
90
+ const projection = columns
91
+ .map((column) => sensitive.test(column)
92
+ ? `'[masked]'::text AS ${identifier(column)}`
93
+ : `left(${identifier(column)}::text,1000) AS ${identifier(column)}`)
94
+ .join(', ');
95
+ const rows = await read(`SELECT ${projection} FROM public.${identifier(table)} ORDER BY ${columns.map((_, index) => index + 1).join(', ')} LIMIT $1 OFFSET $2`, [26, offset]);
96
+ let masked = columns.some((column) => sensitive.test(column));
97
+ const outputRows = rows.slice(0, 25).map((row) => columns.map((column) => {
98
+ const value = row[column];
99
+ if (value === null)
100
+ return null;
101
+ if (typeof value !== 'string')
102
+ throw new Error('Unsupported database value.');
103
+ if (/^(?:sk[-_]|rk[-_]|whsec[-_]|Bearer )/i.test(value)) {
104
+ masked = true;
105
+ return '[masked]';
106
+ }
107
+ return value.slice(0, 1000);
108
+ }));
109
+ return {
110
+ fetchedAt: new Date().toISOString(),
111
+ columns,
112
+ rows: outputRows,
113
+ offset,
114
+ hasMore: rows.length > 25,
115
+ masked,
116
+ };
117
+ }
@@ -107,12 +107,11 @@ export async function scaffoldExpo({ root, options }) {
107
107
  build: 'pnpm typecheck && pnpm build:web',
108
108
  'build:web': 'expo export --platform web',
109
109
  'eas:login': `pnpm dlx eas-cli@${EAS_CLI_VERSION} login`,
110
+ 'build:simulator:ios': `pnpm dlx eas-cli@${EAS_CLI_VERSION} build --platform ios --profile simulator`,
110
111
  'build:internal:ios': `pnpm dlx eas-cli@${EAS_CLI_VERSION} build --platform ios --profile preview`,
111
112
  'build:internal:android': `pnpm dlx eas-cli@${EAS_CLI_VERSION} build --platform android --profile preview`,
112
113
  'build:production:ios': `pnpm dlx eas-cli@${EAS_CLI_VERSION} build --platform ios --profile production`,
113
114
  'build:production:android': `pnpm dlx eas-cli@${EAS_CLI_VERSION} build --platform android --profile production`,
114
- 'submit:ios': `pnpm dlx eas-cli@${EAS_CLI_VERSION} submit --platform ios --profile production --latest`,
115
- 'submit:android': `pnpm dlx eas-cli@${EAS_CLI_VERSION} submit --platform android --profile production --latest`,
116
115
  typecheck: 'tsc --noEmit',
117
116
  lint: 'eslint app components lib --max-warnings 0',
118
117
  },
@@ -194,10 +193,14 @@ const styles = StyleSheet.create({
194
193
  cli: { version: '>= 16.0.0' },
195
194
  build: {
196
195
  development: { developmentClient: true, distribution: 'internal' },
197
- preview: { distribution: 'internal' },
198
- production: { autoIncrement: true },
196
+ preview: {
197
+ environment: 'preview',
198
+ distribution: 'internal',
199
+ android: { buildType: 'apk' },
200
+ },
201
+ simulator: { environment: 'preview', ios: { simulator: true } },
202
+ production: { environment: 'production', autoIncrement: true },
199
203
  },
200
- submit: { production: {} },
201
204
  }, null, 2) + '\n');
202
205
  appendGitignore(dir, ['.env', '.env.*', '!.env.example', '.expo', 'dist', 'node_modules']);
203
206
  }
@@ -1,4 +1,4 @@
1
1
  /** Preserve unrelated starter YAML while replacing the settings this initializer owns. */
2
2
  export declare function setPnpmPolicy(root: string, policy: Record<string, unknown>): void;
3
- /** Merge reviewed patches without deleting starter-maintained mappings. */
4
- export declare function mergePnpmPatches(root: string, patches: Record<string, string>): void;
3
+ /** Extend a pnpm patch map without replacing unrelated patches or YAML comments. */
4
+ export declare function pnpmPatchPolicy(source: string, coordinate: string, patch: string): string;
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { writeFile } from './util.js';
4
+ import { isMap, parseDocument } from 'yaml';
4
5
  function policyBlock(key) {
5
6
  const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6
7
  return new RegExp(`^(?:${escaped}|"${escaped}"|'${escaped}')[ \\t]*:.*(?:\\r?\\n|$)(?:[ \\t]+[^\\n]*(?:\\n|$)|#[^\\n]*(?:\\n|$)|[ \\t]*\\n)*`, 'gm');
@@ -17,50 +18,23 @@ export function setPnpmPolicy(root, policy) {
17
18
  }
18
19
  writeFile(file, source);
19
20
  }
20
- /** Merge reviewed patches without deleting starter-maintained mappings. */
21
- export function mergePnpmPatches(root, patches) {
22
- const file = path.join(root, 'pnpm-workspace.yaml');
23
- const source = existsSync(file) ? readFileSync(file, 'utf8') : '';
24
- const blocks = [...source.matchAll(policyBlock('patchedDependencies'))];
25
- if (blocks.length > 1)
26
- throw new Error('Duplicate patchedDependencies configuration');
27
- const block = blocks[0]?.[0] ?? '';
28
- const existing = patchRows(block, patches);
29
- const replacement = 'patchedDependencies:\n' +
30
- existing +
31
- Object.entries(patches)
32
- .map(([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}\n`)
33
- .join('');
34
- const remaining = source.replace(policyBlock('patchedDependencies'), '');
35
- writeFile(file, remaining + `${remaining.endsWith('\n') || !remaining ? '' : '\n'}${replacement}`);
36
- }
37
- function patchRows(block, patches) {
38
- if (!block)
39
- return '';
40
- const [header, ...rows] = block.split(/\r?\n/);
41
- const value = header.slice(header.indexOf(':') + 1).trim();
42
- if (value && !value.startsWith('#')) {
43
- const object = JSON.parse(value);
44
- if (!object ||
45
- Array.isArray(object) ||
46
- typeof object !== 'object' ||
47
- Object.values(object).some((entry) => typeof entry !== 'string'))
48
- throw new Error('Unsupported patchedDependencies mapping');
49
- return Object.entries(object)
50
- .filter(([key]) => !Object.hasOwn(patches, key))
51
- .map(([key, entry]) => ` ${JSON.stringify(key)}: ${JSON.stringify(entry)}\n`)
52
- .join('');
21
+ /** Extend a pnpm patch map without replacing unrelated patches or YAML comments. */
22
+ export function pnpmPatchPolicy(source, coordinate, patch) {
23
+ const document = parseDocument(source);
24
+ if (document.errors.length || !isMap(document.contents))
25
+ throw new Error('Invalid pnpm workspace YAML; preserve and review its patch configuration.');
26
+ let mapping = document.get('patchedDependencies', true);
27
+ if (mapping === undefined) {
28
+ document.set('patchedDependencies', document.createNode({}));
29
+ mapping = document.get('patchedDependencies', true);
53
30
  }
54
- return rows
55
- .filter((row) => {
56
- if (!row.trim() || row.trimStart().startsWith('#'))
57
- return true;
58
- const match = row.match(/^ (?:"([^"\\]+)"|'([^']+)'|([^\s:'"]+)):\s*(?:"[^"\\]+"|'[^']+'|[^\s{}[\]&*!|>]+)(?:\s+#.*)?\s*$/);
59
- if (!match)
60
- throw new Error('Unsupported patchedDependencies mapping');
61
- return !Object.hasOwn(patches, match[1] ?? match[2] ?? match[3]);
62
- })
63
- .filter((row, index, rows) => row || index < rows.length - 1)
64
- .map((row) => `${row}\n`)
65
- .join('');
31
+ if (!isMap(mapping))
32
+ throw new Error('patchedDependencies must be an explicit YAML mapping.');
33
+ const previous = mapping.get(coordinate);
34
+ if (previous !== undefined && previous !== patch)
35
+ throw new Error(`A different customer patch is already configured for ${coordinate}.`);
36
+ if (previous === patch)
37
+ return source;
38
+ mapping.set(coordinate, patch);
39
+ return document.toString({ lineWidth: 0 });
66
40
  }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import type { Dashboard, DashboardTool, ToolArguments } from './catalog-model.js';
3
+ export type CatalogErrorCode = 'CATALOG_BUSY' | 'CATALOG_INVALID' | 'PROJECT_NOT_FOUND' | 'PROJECT_UNAVAILABLE' | 'INVALID_INPUT' | 'CATALOG_FAILURE';
4
+ export declare class CatalogError extends Error {
5
+ readonly code: CatalogErrorCode;
6
+ constructor(code: CatalogErrorCode);
7
+ }
8
+ export declare function catalogFailure(error: unknown): {
9
+ message: string;
10
+ nextAction: string;
11
+ code: CatalogErrorCode;
12
+ };
13
+ declare const entrySchema: z.ZodObject<{
14
+ id: z.ZodString;
15
+ root: z.ZodString;
16
+ name: z.ZodString;
17
+ updatedAt: z.ZodString;
18
+ sourceIdentity: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strict>;
20
+ export type ProjectEntry = z.infer<typeof entrySchema>;
21
+ export declare class ProjectStore {
22
+ readonly directory: string;
23
+ readonly file: string;
24
+ constructor(directory: string);
25
+ private read;
26
+ private write;
27
+ register(root: string, displayName?: string): string;
28
+ private mutate;
29
+ /** Explicit local operator recovery only; uncertain ownership never removes a lock. */
30
+ recoverCatalogLock(): {
31
+ recovered: boolean;
32
+ };
33
+ context(id: string): {
34
+ id: string;
35
+ name: string;
36
+ directory: string;
37
+ };
38
+ snapshot(selectedId?: string | null): Dashboard;
39
+ call(tool: DashboardTool, raw: ToolArguments): Dashboard;
40
+ }
41
+ export {};