@sequenceholdings/studio-cli 0.2.2 → 0.4.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 (128) hide show
  1. package/README.md +616 -78
  2. package/dist/access/commands.d.ts +3 -0
  3. package/dist/access/commands.js +91 -0
  4. package/dist/agents/commands.d.ts +1 -1
  5. package/dist/agents/commands.js +5 -0
  6. package/dist/agents/scaffold.js +5 -7
  7. package/dist/agents/voice-authoring.d.ts +5 -0
  8. package/dist/agents/voice-authoring.js +75 -0
  9. package/dist/agents/voice-publication.d.ts +5 -0
  10. package/dist/agents/voice-publication.js +63 -0
  11. package/dist/agents/voice-shared.d.ts +20 -0
  12. package/dist/agents/voice-shared.js +112 -0
  13. package/dist/agents/voice.d.ts +3 -0
  14. package/dist/agents/voice.js +57 -0
  15. package/dist/app/adapters.d.ts +6 -0
  16. package/dist/app/adapters.js +17 -2
  17. package/dist/app/agent-refs.d.ts +16 -0
  18. package/dist/app/agent-refs.js +36 -0
  19. package/dist/app/application-registration.d.ts +36 -6
  20. package/dist/app/application-registration.js +60 -15
  21. package/dist/app/commands.js +19 -2
  22. package/dist/app/deploy.d.ts +3 -0
  23. package/dist/app/deploy.js +22 -6
  24. package/dist/app/env-bindings.d.ts +21 -0
  25. package/dist/app/env-bindings.js +184 -0
  26. package/dist/app/manifest-validation.js +8 -0
  27. package/dist/app/manifest.d.ts +32 -14
  28. package/dist/app/manifest.js +16 -6
  29. package/dist/app/primitive-scaffold.d.ts +4 -1
  30. package/dist/app/primitive-scaffold.js +4 -4
  31. package/dist/app/readme.js +1 -0
  32. package/dist/app/scaffold-files.js +1 -1
  33. package/dist/app/scaffold.d.ts +6 -4
  34. package/dist/app/scaffold.js +7 -4
  35. package/dist/app/workspace-scaffold.js +12 -7
  36. package/dist/argv.d.ts +7 -0
  37. package/dist/argv.js +56 -0
  38. package/dist/artifact/delegate.js +8 -4
  39. package/dist/atlas-client.d.ts +6 -0
  40. package/dist/atlas-client.js +39 -2
  41. package/dist/auth-cmds/commands.d.ts +1 -1
  42. package/dist/auth-cmds/commands.js +16 -0
  43. package/dist/auth.d.ts +32 -0
  44. package/dist/auth.js +170 -33
  45. package/dist/bin.js +23 -4
  46. package/dist/command-contract.d.ts +137 -0
  47. package/dist/command-contract.js +43 -0
  48. package/dist/command-help.d.ts +8 -0
  49. package/dist/command-help.js +71 -0
  50. package/dist/command-input.d.ts +15 -0
  51. package/dist/command-input.js +33 -0
  52. package/dist/functions/commands.d.ts +2 -1
  53. package/dist/functions/commands.js +78 -33
  54. package/dist/functions/deploy-preflight.d.ts +21 -0
  55. package/dist/functions/deploy-preflight.js +58 -0
  56. package/dist/functions/egress-postgres.d.ts +7 -0
  57. package/dist/functions/egress-postgres.js +36 -0
  58. package/dist/functions/manifest.d.ts +15 -1
  59. package/dist/functions/manifest.js +49 -12
  60. package/dist/functions/secret-reconcile.d.ts +3 -3
  61. package/dist/functions/secret-reconcile.js +5 -7
  62. package/dist/functions/source-selection.js +4 -1
  63. package/dist/main.d.ts +2 -0
  64. package/dist/main.js +75 -25
  65. package/dist/manifest-roles-notice.d.ts +33 -0
  66. package/dist/manifest-roles-notice.js +75 -0
  67. package/dist/orm/delegate.d.ts +16 -0
  68. package/dist/orm/delegate.js +142 -7
  69. package/dist/pipeline/clone-deploy.d.ts +37 -0
  70. package/dist/pipeline/clone-deploy.js +125 -0
  71. package/dist/pipeline/codegen.js +6 -2
  72. package/dist/pipeline/commands.js +21 -5
  73. package/dist/pipeline/lifecycle.d.ts +1 -0
  74. package/dist/pipeline/lifecycle.js +95 -44
  75. package/dist/pipeline/repin-orm.js +6 -2
  76. package/dist/pipeline/stage-secrets.d.ts +4 -1
  77. package/dist/pipeline/stage-secrets.js +7 -3
  78. package/dist/process/build.js +17 -0
  79. package/dist/process/codegen.js +16 -0
  80. package/dist/process/commands.d.ts +15 -7
  81. package/dist/process/commands.js +294 -98
  82. package/dist/process/lint.js +35 -0
  83. package/dist/process/plan-diff.js +9 -0
  84. package/dist/process/simulate.js +8 -0
  85. package/dist/release-age.d.ts +12 -0
  86. package/dist/release-age.js +24 -0
  87. package/dist/repos/commands.d.ts +10 -1
  88. package/dist/repos/commands.js +42 -8
  89. package/dist/repos/pulls.d.ts +3 -0
  90. package/dist/repos/pulls.js +131 -0
  91. package/dist/scaffold-guidance.d.ts +4 -0
  92. package/dist/scaffold-guidance.js +15 -0
  93. package/dist/secrets/commands.d.ts +1 -1
  94. package/dist/secrets/commands.js +97 -16
  95. package/dist/service-accounts/commands.d.ts +3 -0
  96. package/dist/service-accounts/commands.js +50 -0
  97. package/dist/storage/commands.js +23 -1
  98. package/dist/storage/gcs-download.d.ts +13 -0
  99. package/dist/storage/gcs-download.js +41 -0
  100. package/dist/storage/import-cycle.d.ts +41 -0
  101. package/dist/storage/import-cycle.js +123 -0
  102. package/dist/storage/import-files.d.ts +30 -0
  103. package/dist/storage/import-files.js +133 -0
  104. package/dist/storage/import-gcloud.d.ts +12 -0
  105. package/dist/storage/import-gcloud.js +54 -0
  106. package/dist/storage/import-identity.d.ts +12 -0
  107. package/dist/storage/import-identity.js +15 -0
  108. package/dist/storage/import-plan.d.ts +120 -0
  109. package/dist/storage/import-plan.js +189 -0
  110. package/dist/storage/import-preflight.d.ts +36 -0
  111. package/dist/storage/import-preflight.js +62 -0
  112. package/dist/storage/import-progress-map.d.ts +5 -0
  113. package/dist/storage/import-progress-map.js +22 -0
  114. package/dist/storage/import-recover.d.ts +97 -0
  115. package/dist/storage/import-recover.js +186 -0
  116. package/dist/storage/import-run.d.ts +14 -0
  117. package/dist/storage/import-run.js +140 -0
  118. package/dist/templates/guidance/AGENTS.md +10 -0
  119. package/dist/templates/guidance/CLAUDE.md +1 -0
  120. package/dist/templates/process/package.json +2 -2
  121. package/dist/templates/process/pnpm-workspace.yaml +7 -4
  122. package/dist/validation-detail.d.ts +2 -0
  123. package/dist/validation-detail.js +20 -0
  124. package/package.json +9 -9
  125. package/templates/guidance/AGENTS.md +10 -0
  126. package/templates/guidance/CLAUDE.md +1 -0
  127. package/templates/process/package.json +2 -2
  128. package/templates/process/pnpm-workspace.yaml +7 -4
@@ -0,0 +1,50 @@
1
+ import { getJson, postJson } from '../atlas-client.js';
2
+ import { printCliError } from '../cli-errors.js';
3
+ import { requiredStringFlag, validateCommandInput, wantsHelp } from '../command-input.js';
4
+ import { buildContext, clientOptions } from '../functions/commands.js';
5
+ export const SERVICE_ACCOUNTS_USAGE = `usage:
6
+ seq-studio service-accounts list -e <env> [--json]
7
+ seq-studio service-accounts show <account-id> -e <env> [--json]
8
+ seq-studio service-accounts create <slug> --display-name <name> -e <env> [--description <text>] [--json]
9
+
10
+ All results are JSON. Authenticate: seq-studio login --env <env>.
11
+ Administrator provisioning: listing needs Service Accounts surface access;
12
+ create needs its editor grant; show needs admin on that account.
13
+ A normal builder should use the account ID/slug supplied by their administrator.
14
+ Creation does not grant the account access to data or functions. Grant required
15
+ runtime access with seq-studio access using principal user: service-account|<id>.
16
+ The server checks creator, actor, and resource authority on every operation.
17
+ No credential is issued or printed by these commands.
18
+ `;
19
+ export async function runServiceAccountsCommand(sub, args) {
20
+ if (!sub || wantsHelp({ sub, args })) {
21
+ console.log(SERVICE_ACCOUNTS_USAGE);
22
+ return sub ? 0 : 1;
23
+ }
24
+ try {
25
+ if (!['list', 'show', 'create'].includes(sub)) {
26
+ throw new Error(`Unknown service-accounts command: ${sub}. See --help.`);
27
+ }
28
+ validateCommandInput({ args,
29
+ flags: sub === 'create' ? { 'display-name': 'string', description: 'string' } : {},
30
+ positional: sub === 'list' ? 0 : 1,
31
+ });
32
+ const target = args.positional[0];
33
+ const body = sub === 'create' ? {
34
+ slug: target,
35
+ displayName: requiredStringFlag({ args, key: 'display-name' }),
36
+ ...(typeof args.flags.description === 'string' ? { description: args.flags.description } : {}),
37
+ } : undefined;
38
+ if (target !== undefined && !target.trim())
39
+ throw new Error('An account ID or slug is required.');
40
+ const ctx = await buildContext(args);
41
+ const request = { ...clientOptions(ctx), path: `/api/service-accounts${sub === 'show' ? `/${encodeURIComponent(target)}` : ''}` };
42
+ const result = sub === 'create' ? await postJson({ ...request, body }) : await getJson(request);
43
+ console.log(JSON.stringify(result, null, 2));
44
+ return 0;
45
+ }
46
+ catch (error) {
47
+ printCliError(error);
48
+ return 1;
49
+ }
50
+ }
@@ -1,6 +1,6 @@
1
1
  import { createReadStream, createWriteStream } from 'node:fs';
2
2
  import { readFile, stat, writeFile } from 'node:fs/promises';
3
- import { basename, resolve } from 'node:path';
3
+ import { basename, dirname, resolve } from 'node:path';
4
4
  import { Readable } from 'node:stream';
5
5
  import { pipeline } from 'node:stream/promises';
6
6
  import { randomUUID } from 'node:crypto';
@@ -10,7 +10,9 @@ import { getAccessTokenWithMode } from '../auth.js';
10
10
  import { resolveEnvWithDiscovery } from '../config.js';
11
11
  import { getJson, postJson, putJson, patchJson, deleteJson, } from '../atlas-client.js';
12
12
  import { printCliError } from '../cli-errors.js';
13
+ import { runStorageImport } from './import-run.js';
13
14
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
15
+ import { writeScaffoldGuidance } from '../scaffold-guidance.js';
14
16
  const usage = `usage:
15
17
  seq-studio storage init <workspace-name> [--out workspace.yml]
16
18
  seq-studio storage validate [workspace.yml]
@@ -19,6 +21,9 @@ const usage = `usage:
19
21
  seq-studio storage show --workspace <id> [--node <id>] -e <env>
20
22
  seq-studio storage mkdir <name> --workspace <id> [--parent <id>] -e <env>
21
23
  seq-studio storage upload <file> --workspace <id> [--path <path>] [--parent <id>] [--replace <file-id> --revision <n>] [--resume <upload-id>] -e <env>
24
+ seq-studio storage import <directory|gs://bucket/prefix> --workspace <id> [--path <prefix>] [--parent <id>] [--concurrency <n>] [--progress <file>] [--yes] -e <env>
25
+ seq-studio storage uploads --workspace <id> -e <env>
26
+ seq-studio storage reconcile --workspace <id> [--abort-incomplete] -e <env>
22
27
  seq-studio storage download --workspace <id> --node <id> --out <file> [--version <id>] -e <env>
23
28
  seq-studio storage trash|restore|purge --workspace <id> --node <id> --revision <n> [-e <env>] [--yes]
24
29
  seq-studio storage access --workspace <id> [--node <id>] [--file <access.json>] -e <env>
@@ -48,6 +53,7 @@ export async function runStorageCommand(sub, args) {
48
53
  const manifest = workspaceManifestSchema.parse({ workspace: { name } });
49
54
  const output = resolve(flag('out') ?? 'workspace.yml');
50
55
  await writeFile(output, `workspace:\n name: ${manifest.workspace.name}\n description: ""\n`, { flag: 'wx' });
56
+ await writeScaffoldGuidance({ directory: dirname(output) });
51
57
  console.log(output);
52
58
  return 0;
53
59
  }
@@ -156,6 +162,22 @@ export async function runStorageCommand(sub, args) {
156
162
  }
157
163
  break;
158
164
  }
165
+ case 'import':
166
+ return runStorageImport({
167
+ args,
168
+ env,
169
+ token,
170
+ workspace,
171
+ flag,
172
+ });
173
+ case 'uploads':
174
+ print(await workspace.uploads.list());
175
+ break;
176
+ case 'reconcile':
177
+ print(await workspace.uploads.reconcile({
178
+ abortIncomplete: args.flags['abort-incomplete'] === true,
179
+ }));
180
+ break;
159
181
  case 'download': {
160
182
  const output = resolve(required('out'));
161
183
  const signed = await workspace.download(required('node'), {
@@ -0,0 +1,13 @@
1
+ /** Read a GCS object with the operator's token. Redirects stay on Google storage and drop the bearer token. */
2
+ export declare function gcsMediaUrl({ bucket, name }: {
3
+ bucket: string;
4
+ name: string;
5
+ }): string;
6
+ export declare function allowedDownloadRedirect(location: string): URL;
7
+ export declare function openGcsObject({ fetch: fetcher, token, bucket, name, signal, }: {
8
+ fetch: typeof fetch;
9
+ token: string;
10
+ bucket: string;
11
+ name: string;
12
+ signal?: AbortSignal;
13
+ }): Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1,41 @@
1
+ /** Read a GCS object with the operator's token. Redirects stay on Google storage and drop the bearer token. */
2
+ const STORAGE_HOST = 'storage.googleapis.com';
3
+ export function gcsMediaUrl({ bucket, name }) {
4
+ if (!bucket || bucket.includes('/') || !name || name.startsWith('/') || name.includes('\\'))
5
+ throw new Error('Invalid GCS object name');
6
+ const url = new URL(`https://${STORAGE_HOST}/storage/v1/b/${encodeURIComponent(bucket)}/o/${encodeURIComponent(name)}`);
7
+ url.searchParams.set('alt', 'media');
8
+ return url.toString();
9
+ }
10
+ export function allowedDownloadRedirect(location) {
11
+ let url;
12
+ try {
13
+ url = new URL(location);
14
+ }
15
+ catch {
16
+ throw new Error('GCS download redirect was not a URL');
17
+ }
18
+ const hostOk = url.hostname === STORAGE_HOST || url.hostname.endsWith(`.${STORAGE_HOST}`);
19
+ if (url.protocol !== 'https:' || url.username || url.password || url.port || !hostOk)
20
+ throw new Error('GCS download redirect left Google storage');
21
+ return url;
22
+ }
23
+ export async function openGcsObject({ fetch: fetcher, token, bucket, name, signal, }) {
24
+ const first = await fetcher(gcsMediaUrl({ bucket, name }), {
25
+ headers: { Authorization: `Bearer ${token}` },
26
+ redirect: 'manual',
27
+ signal,
28
+ });
29
+ const response = await followStorageRedirect({ response: first, fetch: fetcher, signal });
30
+ if (!response.ok || !response.body)
31
+ throw new Error(`GCS object read failed (${response.status})`);
32
+ return response.body;
33
+ }
34
+ async function followStorageRedirect({ response, fetch: fetcher, signal, }) {
35
+ if (response.status < 300 || response.status >= 400)
36
+ return response;
37
+ const location = response.headers.get('location');
38
+ if (!location)
39
+ throw new Error('GCS download redirect was missing a location');
40
+ return fetcher(allowedDownloadRedirect(location), { redirect: 'error', signal });
41
+ }
@@ -0,0 +1,41 @@
1
+ import { type StorageClient } from '@sequenceholdings/storage';
2
+ import type { ClassifiedImport, ImportProgress } from './import-plan.js';
3
+ type Workspace = ReturnType<StorageClient['workspace']>;
4
+ /**
5
+ * Replays go out even when the pending cap is full, because those reservations
6
+ * already exist. Fresh reservations share whatever slots the cap still allows,
7
+ * and the combined start never exceeds one batch.
8
+ */
9
+ export declare function selectImportBatch<TPending, TStart extends {
10
+ replay: boolean;
11
+ }>({ starts, pending, slots, batchLimit, }: {
12
+ starts: TStart[];
13
+ pending: TPending[];
14
+ slots: number;
15
+ batchLimit?: number;
16
+ }): {
17
+ replayNow: TStart[];
18
+ freshNow: TStart[];
19
+ wave: TPending[];
20
+ laterStarts: TStart[];
21
+ rest: TPending[];
22
+ };
23
+ export declare function transferImport({ workspace, progress, progressPath, classified, perPrincipal, concurrency, parentId, bucket, token, }: {
24
+ workspace: Workspace;
25
+ progress: ImportProgress;
26
+ progressPath: string;
27
+ classified: ClassifiedImport;
28
+ perPrincipal: number;
29
+ concurrency: number;
30
+ parentId: string | null;
31
+ bucket?: string;
32
+ token: string | null;
33
+ }): Promise<string[]>;
34
+ /** A wave with nothing left to reserve or transfer is finished, not out of slots. */
35
+ export declare function importCycleOutcome({ live, starting, wave, deferred, }: {
36
+ live: number;
37
+ starting: number;
38
+ wave: number;
39
+ deferred: number;
40
+ }): 'transfer' | 'done' | 'blocked';
41
+ export {};
@@ -0,0 +1,123 @@
1
+ import { STORAGE_UPLOAD_BATCH_LIMIT } from '@sequenceholdings/storage';
2
+ import { eachLimited, openImportSource, saveProgress } from './import-files.js';
3
+ import { prepareWave, recoverResume, } from './import-recover.js';
4
+ /**
5
+ * Replays go out even when the pending cap is full, because those reservations
6
+ * already exist. Fresh reservations share whatever slots the cap still allows,
7
+ * and the combined start never exceeds one batch.
8
+ */
9
+ export function selectImportBatch({ starts, pending, slots, batchLimit = STORAGE_UPLOAD_BATCH_LIMIT, }) {
10
+ const limit = Math.max(0, batchLimit);
11
+ const replays = starts.filter((start) => start.replay);
12
+ const fresh = starts.filter((start) => !start.replay);
13
+ const replayNow = replays.slice(0, limit);
14
+ const room = limit - replayNow.length;
15
+ const slotRoom = Math.max(0, Math.min(room, slots));
16
+ const replaySlotCost = slots > 0 ? replayNow.length : 0;
17
+ const admissionRoom = Math.max(0, slotRoom - replaySlotCost);
18
+ const freshNow = fresh.slice(0, admissionRoom);
19
+ return {
20
+ replayNow,
21
+ freshNow,
22
+ wave: pending.slice(0, admissionRoom - freshNow.length),
23
+ laterStarts: [...replays.slice(limit), ...fresh.slice(admissionRoom)],
24
+ rest: pending.slice(admissionRoom - freshNow.length),
25
+ };
26
+ }
27
+ export async function transferImport({ workspace, progress, progressPath, classified, perPrincipal, concurrency, parentId, bucket, token, }) {
28
+ const controller = new AbortController();
29
+ const cancel = () => controller.abort();
30
+ process.once('SIGINT', cancel);
31
+ const failures = [];
32
+ try {
33
+ let queue = classified.pending;
34
+ let resume = classified.resume;
35
+ while (resume.length || queue.length) {
36
+ const listed = await workspace.uploads.list();
37
+ const slots = listed.limits.perPrincipal - listed.items.length;
38
+ const recovered = await recoverResume({ workspace, resume, parentId });
39
+ for (const conflict of recovered.conflicts)
40
+ failures.push(`${conflict.relativePath}: ${conflict.reason}`);
41
+ noteRecovered(progress, recovered.done);
42
+ const selected = selectImportBatch({ starts: recovered.starts, pending: queue, slots });
43
+ const starting = [...selected.replayNow, ...selected.freshNow];
44
+ const outcome = importCycleOutcome({
45
+ live: recovered.resume.length,
46
+ starting: starting.length,
47
+ wave: selected.wave.length,
48
+ deferred: selected.laterStarts.length + selected.rest.length,
49
+ });
50
+ if (outcome !== 'transfer') {
51
+ if (recovered.done.length)
52
+ await saveProgress(progressPath, progress);
53
+ if (outcome === 'blocked')
54
+ failures.push(`No pending-upload slots left (${perPrincipal} per person). Run storage uploads and storage reconcile.`);
55
+ break;
56
+ }
57
+ failures.push(...(await transferWave({
58
+ workspace,
59
+ progress,
60
+ progressPath,
61
+ resume: recovered.resume,
62
+ starts: starting,
63
+ wave: selected.wave,
64
+ concurrency,
65
+ parentId,
66
+ bucket,
67
+ token,
68
+ signal: controller.signal,
69
+ })));
70
+ resume = selected.laterStarts.map((start) => start.resumeItem);
71
+ queue = selected.rest;
72
+ }
73
+ }
74
+ finally {
75
+ process.removeListener('SIGINT', cancel);
76
+ }
77
+ return failures;
78
+ }
79
+ /** A wave with nothing left to reserve or transfer is finished, not out of slots. */
80
+ export function importCycleOutcome({ live, starting, wave, deferred, }) {
81
+ if (live > 0 || starting > 0 || wave > 0)
82
+ return 'transfer';
83
+ return deferred > 0 ? 'blocked' : 'done';
84
+ }
85
+ function noteRecovered(progress, done) {
86
+ for (const item of done) {
87
+ const previous = progress.inflight[item.relativePath];
88
+ progress.completed[item.relativePath] = {
89
+ fileId: item.fileId,
90
+ uploadId: item.uploadId,
91
+ size: previous?.size ?? 0,
92
+ checksum: previous?.checksum,
93
+ idempotencyKey: item.idempotencyKey,
94
+ };
95
+ delete progress.inflight[item.relativePath];
96
+ }
97
+ }
98
+ async function transferWave({ workspace, progress, progressPath, resume, starts, wave, concurrency, parentId, bucket, token, signal, }) {
99
+ const transfers = await prepareWave({
100
+ workspace,
101
+ progress,
102
+ progressPath,
103
+ resume,
104
+ starts,
105
+ wave,
106
+ parentId,
107
+ });
108
+ return eachLimited(transfers, concurrency, async (item) => {
109
+ if (!item.sessionId)
110
+ throw new Error(`${item.object.relativePath}: batch did not return a session`);
111
+ const session = await workspace.uploads.resume(item.sessionId, await openImportSource({ object: item.object, bucket, token, signal }), { size: item.object.size, signal });
112
+ progress.completed[item.object.relativePath] = {
113
+ fileId: session.fileId,
114
+ uploadId: session.id,
115
+ size: item.object.size,
116
+ checksum: item.object.checksum,
117
+ idempotencyKey: item.idempotencyKey,
118
+ };
119
+ delete progress.inflight[item.object.relativePath];
120
+ await saveProgress(progressPath, progress);
121
+ console.error(`imported ${item.object.relativePath}`);
122
+ });
123
+ }
@@ -0,0 +1,30 @@
1
+ import { type StartStorageUpload } from '@sequenceholdings/storage';
2
+ import { type ImportProgress, type ImportSourceObject } from './import-plan.js';
3
+ /** The progress file and its `*.tmp` siblings are not source objects. */
4
+ export declare function isImportProgressFile({ relativePath, progressRelative, }: {
5
+ relativePath: string;
6
+ progressRelative: string | null;
7
+ }): boolean;
8
+ export declare function walkDirectory(root: string, options?: {
9
+ progressRelative?: string | null;
10
+ }): Promise<ImportSourceObject[]>;
11
+ export declare function loadProgress(path: string, expected: {
12
+ source: string;
13
+ workspaceId: string;
14
+ destPrefix: string;
15
+ parentId: string | null;
16
+ }): Promise<ImportProgress>;
17
+ /** One writer at a time. Concurrent completions share this file, and a shared temp path loses a rename. */
18
+ export declare function saveProgress(path: string, progress: ImportProgress): Promise<void>;
19
+ export declare function eachLimited<T>(items: T[], limit: number, run: (item: T) => Promise<void>): Promise<string[]>;
20
+ export declare function batchItem(item: {
21
+ destination: string;
22
+ idempotencyKey: string;
23
+ object: ImportSourceObject;
24
+ }, parentId: string | null): StartStorageUpload;
25
+ export declare function openImportSource({ object, bucket, token, signal, }: {
26
+ object: ImportSourceObject;
27
+ bucket?: string;
28
+ token: string | null;
29
+ signal: AbortSignal;
30
+ }): Promise<ReadableStream<Uint8Array<ArrayBufferLike>> | import("fs").ReadStream>;
@@ -0,0 +1,133 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
4
+ import { join, relative, sep } from 'node:path';
5
+ import { Crc32c } from '@sequenceholdings/storage';
6
+ import { openGcsObject } from './gcs-download.js';
7
+ import { emptyImportProgress, parseImportProgress, } from './import-plan.js';
8
+ /** The progress file and its `*.tmp` siblings are not source objects. */
9
+ export function isImportProgressFile({ relativePath, progressRelative, }) {
10
+ if (!progressRelative || progressRelative.startsWith('..') || progressRelative.startsWith('/'))
11
+ return false;
12
+ if (relativePath === progressRelative)
13
+ return true;
14
+ const slash = progressRelative.lastIndexOf('/');
15
+ const directory = slash === -1 ? '' : progressRelative.slice(0, slash + 1);
16
+ const base = progressRelative.slice(directory.length);
17
+ if (!relativePath.startsWith(directory))
18
+ return false;
19
+ const name = relativePath.slice(directory.length);
20
+ return name.startsWith(`${base}.`) && name.endsWith('.tmp') && !name.includes('/');
21
+ }
22
+ export async function walkDirectory(root, options) {
23
+ const progressRelative = options?.progressRelative ?? null;
24
+ const objects = [];
25
+ async function visit(current) {
26
+ for (const entry of await readdir(current, { withFileTypes: true })) {
27
+ if (entry.isSymbolicLink())
28
+ continue;
29
+ const path = join(current, entry.name);
30
+ if (entry.isDirectory())
31
+ await visit(path);
32
+ else if (entry.isFile()) {
33
+ const relativePath = relative(root, path).split(sep).join('/');
34
+ if (isImportProgressFile({ relativePath, progressRelative }))
35
+ continue;
36
+ const info = await stat(path);
37
+ objects.push({
38
+ relativePath,
39
+ size: info.size,
40
+ checksum: await checksumFile(path),
41
+ contentType: 'application/octet-stream',
42
+ sourceName: path,
43
+ });
44
+ }
45
+ }
46
+ }
47
+ await visit(root);
48
+ return objects;
49
+ }
50
+ async function checksumFile(path) {
51
+ const checksum = new Crc32c();
52
+ for await (const chunk of createReadStream(path))
53
+ checksum.update(chunk);
54
+ return checksum.digest();
55
+ }
56
+ export async function loadProgress(path, expected) {
57
+ try {
58
+ return parseImportProgress(JSON.parse(await readFile(path, 'utf8')), expected);
59
+ }
60
+ catch (error) {
61
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
62
+ return emptyImportProgress(expected);
63
+ throw error;
64
+ }
65
+ }
66
+ const progressWrites = new Map();
67
+ /** One writer at a time. Concurrent completions share this file, and a shared temp path loses a rename. */
68
+ export function saveProgress(path, progress) {
69
+ const previous = progressWrites.get(path) ?? Promise.resolve();
70
+ const write = previous
71
+ .catch(() => undefined)
72
+ .then(() => writeProgress(path, progress));
73
+ const tracked = write.finally(() => {
74
+ if (progressWrites.get(path) === tracked)
75
+ progressWrites.delete(path);
76
+ });
77
+ progressWrites.set(path, tracked);
78
+ return tracked;
79
+ }
80
+ async function writeProgress(path, progress) {
81
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
82
+ await writeFile(temporary, `${JSON.stringify(progress, null, 2)}\n`, { mode: 0o600 });
83
+ await rename(temporary, path);
84
+ }
85
+ export async function eachLimited(items, limit, run) {
86
+ const failures = [];
87
+ let cursor = 0;
88
+ async function worker() {
89
+ for (;;) {
90
+ const index = cursor;
91
+ cursor += 1;
92
+ const item = items[index];
93
+ if (!item)
94
+ return;
95
+ try {
96
+ await run(item);
97
+ }
98
+ catch (error) {
99
+ failures.push(error instanceof Error ? error.message : 'Import item failed');
100
+ }
101
+ }
102
+ }
103
+ const workers = Math.min(limit, items.length);
104
+ if (workers > 0)
105
+ await Promise.all(Array.from({ length: workers }, () => worker()));
106
+ return failures;
107
+ }
108
+ export function batchItem(item, parentId) {
109
+ return {
110
+ path: item.destination,
111
+ parentId,
112
+ size: item.object.size,
113
+ contentType: item.object.contentType,
114
+ idempotencyKey: item.idempotencyKey,
115
+ ...(item.object.checksum ? { checksum: item.object.checksum } : {}),
116
+ };
117
+ }
118
+ export async function openImportSource({ object, bucket, token, signal, }) {
119
+ if (!bucket) {
120
+ if (!object.sourceName)
121
+ throw new Error('Local import source is missing a path');
122
+ return createReadStream(object.sourceName);
123
+ }
124
+ if (!token || !object.sourceName)
125
+ throw new Error('GCS import is missing a credential or object name');
126
+ return openGcsObject({
127
+ fetch: globalThis.fetch,
128
+ token,
129
+ bucket,
130
+ name: object.sourceName,
131
+ signal,
132
+ });
133
+ }
@@ -0,0 +1,12 @@
1
+ export interface GcloudIdentity {
2
+ project: string | null;
3
+ account: string | null;
4
+ tokenExpiry: string | null;
5
+ accessToken: string | null;
6
+ error: string | null;
7
+ }
8
+ export declare function readGcloudIdentity(): Promise<GcloudIdentity>;
9
+ export declare function listGcsObjects({ bucket, prefix, }: {
10
+ bucket: string;
11
+ prefix: string;
12
+ }): Promise<unknown>;
@@ -0,0 +1,54 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { z } from 'zod';
4
+ const exec = promisify(execFile);
5
+ const gcloudConfigSchema = z.object({
6
+ configuration: z
7
+ .object({
8
+ properties: z
9
+ .object({
10
+ core: z
11
+ .object({ project: z.string().optional(), account: z.string().optional() })
12
+ .optional(),
13
+ })
14
+ .optional(),
15
+ })
16
+ .optional(),
17
+ credential: z
18
+ .object({ access_token: z.string().optional(), token_expiry: z.string().optional() })
19
+ .optional(),
20
+ });
21
+ export async function readGcloudIdentity() {
22
+ const empty = { project: null, account: null, tokenExpiry: null, accessToken: null };
23
+ try {
24
+ const { stdout } = await exec('gcloud', ['config', 'config-helper', '--format=json'], {
25
+ timeout: 15_000,
26
+ maxBuffer: 1024 * 1024,
27
+ });
28
+ let parsed;
29
+ try {
30
+ parsed = gcloudConfigSchema.parse(JSON.parse(stdout));
31
+ }
32
+ catch {
33
+ return { ...empty, error: 'gcloud config-helper returned an unexpected payload' };
34
+ }
35
+ return {
36
+ project: parsed.configuration?.properties?.core?.project ?? null,
37
+ account: parsed.configuration?.properties?.core?.account ?? null,
38
+ tokenExpiry: parsed.credential?.token_expiry ?? null,
39
+ accessToken: parsed.credential?.access_token ?? null,
40
+ error: null,
41
+ };
42
+ }
43
+ catch {
44
+ // The failure can include config-helper stdout, which carries the access token.
45
+ return { ...empty, error: 'gcloud config-helper failed' };
46
+ }
47
+ }
48
+ export async function listGcsObjects({ bucket, prefix, }) {
49
+ const uri = prefix ? `gs://${bucket}/${prefix}` : `gs://${bucket}`;
50
+ const { stdout } = await exec('gcloud', ['storage', 'objects', 'list', uri, '--format=json'], { timeout: 120_000, maxBuffer: 32 * 1024 * 1024 });
51
+ if (!stdout.trim())
52
+ return [];
53
+ return JSON.parse(stdout);
54
+ }
@@ -0,0 +1,12 @@
1
+ /** Whether a published version is the source bytes, not merely the same size. */
2
+ export declare function publishedIdentity({ versions, fileId, versionId, checksum, }: {
3
+ versions?: (fileId: string) => Promise<{
4
+ items: Array<{
5
+ id: string;
6
+ checksum: string;
7
+ }>;
8
+ }>;
9
+ fileId: string;
10
+ versionId: string;
11
+ checksum?: string;
12
+ }): Promise<'match' | 'mismatch' | 'unknown'>;
@@ -0,0 +1,15 @@
1
+ /** Whether a published version is the source bytes, not merely the same size. */
2
+ export async function publishedIdentity({ versions, fileId, versionId, checksum, }) {
3
+ if (!checksum || !versions)
4
+ return 'unknown';
5
+ try {
6
+ const listed = await versions(fileId);
7
+ const published = listed.items.find((version) => version.id === versionId)?.checksum;
8
+ if (!published)
9
+ return 'unknown';
10
+ return published === checksum ? 'match' : 'mismatch';
11
+ }
12
+ catch {
13
+ return 'unknown';
14
+ }
15
+ }