@2kog/kacha 0.1.1 → 0.2.0

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,318 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { constants, createWriteStream } from 'node:fs'
3
+ import { chmod, link, lstat, mkdir, mkdtemp, open, rename, rm, unlink } from 'node:fs/promises'
4
+ import { extname, join } from 'node:path'
5
+ import { Transform } from 'node:stream'
6
+ import { pipeline } from 'node:stream/promises'
7
+ import { isProjectFile } from './oss-collab-remote.js'
8
+ import {
9
+ checkSource, checkStopped, createSnapshot, ensureDirectory, filterProjectFiles, fingerprint,
10
+ readRecord, sameFile, scanProject, syncError, uploadFile, withSyncWorkspace, writeRecord,
11
+ } from './oss-sync-engine.js'
12
+
13
+ const baselinePath = 'config/oss-sync.json'
14
+ const openFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
15
+ const hashPattern = /^[a-f0-9]{64}$/
16
+ const collabTemp = /^config\/oss-sync\.json\.[a-f0-9-]{36}\.tmp$/i
17
+
18
+ function fileAllowed(file) {
19
+ return isProjectFile(file) && !collabTemp.test(file)
20
+ }
21
+
22
+ function assertEntry(entry) {
23
+ if (!entry || typeof entry.hash !== 'string' || !hashPattern.test(entry.hash) ||
24
+ !Number.isSafeInteger(entry.size) || entry.size < 0) {
25
+ throw syncError('OSS_SYNC_STATE_FAILED')
26
+ }
27
+ }
28
+
29
+ async function inspect(file) {
30
+ try {
31
+ return await lstat(file, { bigint: true })
32
+ } catch (error) {
33
+ if (error.code === 'ENOENT') return null
34
+ throw error
35
+ }
36
+ }
37
+
38
+ async function walkParents(root, file, create) {
39
+ const parents = file.split('/').slice(0, -1)
40
+ let path = root
41
+ for (const part of parents) {
42
+ path = join(path, part)
43
+ let info = await inspect(path)
44
+ if (!info && create) {
45
+ await mkdir(path).catch(error => {
46
+ if (error.code !== 'EEXIST') throw error
47
+ })
48
+ info = await inspect(path)
49
+ }
50
+ if (!info) return 'missing'
51
+ if (info.isSymbolicLink()) return 'symlink'
52
+ if (!info.isDirectory()) return 'blocked'
53
+ }
54
+ return 'directory'
55
+ }
56
+
57
+ async function safeTarget(root, file, create = false) {
58
+ const parent = await walkParents(root, file, create)
59
+ if (parent === 'symlink' || parent === 'blocked') throw syncError('OSS_SYNC_INVALID_PATH')
60
+ return join(root, file)
61
+ }
62
+
63
+ async function readLocalFile(file, signal, run) {
64
+ checkStopped(signal)
65
+ const handle = await open(file, openFlags)
66
+ try {
67
+ const info = await handle.stat({ bigint: true })
68
+ if (!info.isFile()) throw syncError('OSS_SYNC_INVALID_PATH')
69
+ const size = Number(info.size)
70
+ if (!Number.isSafeInteger(size)) throw syncError('OSS_SYNC_FILE_UNREADABLE')
71
+ const hash = await fingerprint(handle, size, signal)
72
+ await checkSource(file, info)
73
+ return await run(handle, info, { hash, size })
74
+ } finally {
75
+ await handle.close()
76
+ }
77
+ }
78
+
79
+ async function matchLocal(file, expected, signal, run = (_handle, info) => info) {
80
+ if (expected == null) {
81
+ if (await inspect(file)) throw syncError('OSS_SYNC_FILE_CHANGED')
82
+ return null
83
+ }
84
+ assertEntry(expected)
85
+ try {
86
+ return await readLocalFile(file, signal, async (handle, info, actual) => {
87
+ if (actual.hash !== expected.hash || actual.size !== expected.size) throw syncError('OSS_SYNC_FILE_CHANGED')
88
+ return run(handle, info)
89
+ })
90
+ } catch (error) {
91
+ checkStopped(signal)
92
+ if (['ENOENT', 'ELOOP', 'ENOTDIR'].includes(error.code)) throw syncError('OSS_SYNC_FILE_CHANGED')
93
+ throw error
94
+ }
95
+ }
96
+
97
+ async function receiveFile(remote, entry, stage, signal) {
98
+ const hash = createHash('sha256')
99
+ let bytes = 0
100
+ const meter = new Transform({
101
+ transform(chunk, _encoding, done) {
102
+ bytes += chunk.length
103
+ if (bytes > entry.size) return done(syncError('OSS_SYNC_HASH_MISMATCH'))
104
+ hash.update(chunk)
105
+ done(null, chunk)
106
+ },
107
+ })
108
+
109
+ try {
110
+ const stream = await remote.getBlob(entry.hash)
111
+ await pipeline(stream, meter, createWriteStream(stage, { mode: 0o600, flags: 'wx' }), { signal })
112
+ if (bytes !== entry.size || hash.digest('hex') !== entry.hash) throw syncError('OSS_SYNC_HASH_MISMATCH')
113
+ } catch (error) {
114
+ checkStopped(signal)
115
+ if (error.code === 'OSS_SYNC_HASH_MISMATCH') throw error
116
+ const failure = syncError('OSS_SYNC_DOWNLOAD_FAILED')
117
+ if (Number.isInteger(error.status) && error.status >= 400 && error.status <= 599) failure.status = error.status
118
+ throw failure
119
+ }
120
+ }
121
+
122
+ export async function withLocalProject(projectRoot, signal, fn) {
123
+ return withSyncWorkspace(projectRoot, signal, async ({ root, state, scratch }) => {
124
+ let originalBaseline
125
+ let conflictRoot
126
+
127
+ async function backupLocal(file, target, expected) {
128
+ if (!conflictRoot) {
129
+ const conflicts = join(state, 'conflicts')
130
+ await ensureDirectory(conflicts)
131
+ conflictRoot = await mkdtemp(join(conflicts, 'revision-'))
132
+ }
133
+ const destination = await safeTarget(conflictRoot, file, true)
134
+ const stage = join(scratch, 'backup-' + randomUUID())
135
+ try {
136
+ await matchLocal(target, expected, signal, async (handle, info) => {
137
+ const hash = await createSnapshot(handle, expected.size, stage, signal)
138
+ if (hash !== expected.hash) throw syncError('OSS_SYNC_FILE_CHANGED')
139
+ await checkSource(target, info)
140
+ })
141
+ await link(stage, destination)
142
+ } finally {
143
+ await rm(stage, { force: true })
144
+ }
145
+ return destination.slice(root.length + 1)
146
+ }
147
+
148
+ async function readBaseline() {
149
+ const target = await safeTarget(root, baselinePath)
150
+ const current = await inspect(target)
151
+ if (!current) {
152
+ originalBaseline = null
153
+ return null
154
+ }
155
+ if (!current.isFile()) throw syncError('OSS_SYNC_BASELINE_INVALID')
156
+ let handle
157
+ try {
158
+ handle = await open(target, openFlags)
159
+ const opened = await handle.stat({ bigint: true })
160
+ if (!sameFile(current, opened)) throw syncError('OSS_SYNC_BASELINE_INVALID')
161
+ const manifest = JSON.parse(await handle.readFile('utf8'))
162
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
163
+ throw syncError('OSS_SYNC_BASELINE_INVALID')
164
+ }
165
+ await checkSource(target, opened)
166
+ originalBaseline = opened
167
+ return manifest
168
+ } catch {
169
+ throw syncError('OSS_SYNC_BASELINE_INVALID')
170
+ } finally {
171
+ await handle?.close()
172
+ }
173
+ }
174
+
175
+ return fn({
176
+ async filterFiles(files) {
177
+ const eligible = []
178
+ try {
179
+ for (const file of files) {
180
+ checkStopped(signal)
181
+ if (!fileAllowed(file)) continue
182
+ // Git rejects paths beyond a symlink. Special entries stay outside synchronization.
183
+ const parent = await walkParents(root, file, false)
184
+ if (parent === 'symlink') continue
185
+ const info = parent === 'directory' ? await inspect(join(root, file)) : null
186
+ if (!info || info.isFile()) eligible.push(file)
187
+ }
188
+ return await filterProjectFiles(root, scratch, eligible, signal)
189
+ } catch {
190
+ checkStopped(signal)
191
+ throw syncError('OSS_SYNC_SCAN_FAILED')
192
+ }
193
+ },
194
+
195
+ async scan() {
196
+ const files = Object.create(null)
197
+ for (const { file } of await scanProject(root, scratch, signal)) {
198
+ if (!fileAllowed(file)) continue
199
+ try {
200
+ const path = await safeTarget(root, file)
201
+ files[file] = await readLocalFile(path, signal, (_handle, _info, entry) => entry)
202
+ } catch (error) {
203
+ checkStopped(signal)
204
+ if (['OSS_SYNC_FILE_CHANGED', 'OSS_SYNC_INVALID_PATH', 'ENOENT', 'ELOOP', 'ENOTDIR'].includes(error.code)) {
205
+ throw syncError('OSS_SYNC_FILE_CHANGED')
206
+ }
207
+ throw syncError('OSS_SYNC_FILE_UNREADABLE')
208
+ }
209
+ }
210
+ return files
211
+ },
212
+
213
+ readBaseline,
214
+
215
+ async writeBaseline(manifest) {
216
+ checkStopped(signal)
217
+ if (originalBaseline === undefined) await readBaseline()
218
+ const target = await safeTarget(root, baselinePath, true)
219
+ const current = await inspect(target)
220
+ if (originalBaseline ? !current || !sameFile(originalBaseline, current) : current) {
221
+ throw syncError('OSS_SYNC_BASELINE_INVALID')
222
+ }
223
+ await writeRecord(target, manifest)
224
+ originalBaseline = await inspect(target)
225
+ },
226
+
227
+ async upload({ file, entry, remote, onProgress = () => {} }) {
228
+ if (!fileAllowed(file)) throw syncError('OSS_SYNC_INVALID_PATH')
229
+ assertEntry(entry)
230
+ const path = await safeTarget(root, file)
231
+ const stage = join(scratch, 'upload-' + randomUUID() + extname(file))
232
+ try {
233
+ let skipped
234
+ const local = await matchLocal(path, entry, signal, async (handle, info) => {
235
+ skipped = await remote.hasBlob(entry.hash)
236
+ if (!skipped) {
237
+ const hash = await createSnapshot(handle, entry.size, stage, signal)
238
+ if (hash !== entry.hash) throw syncError('OSS_SYNC_FILE_CHANGED')
239
+ }
240
+ await checkSource(path, info)
241
+ return info
242
+ })
243
+ if (skipped) return 'skipped'
244
+
245
+ const checkpointRoot = join(state, 'checkpoints')
246
+ await ensureDirectory(checkpointRoot)
247
+ if (!hashPattern.test(remote.id)) throw syncError('OSS_SYNC_STATE_FAILED')
248
+ const destination = join(checkpointRoot, remote.id)
249
+ await ensureDirectory(destination)
250
+ const recordFile = join(destination, entry.hash + '.json')
251
+ const record = await readRecord(recordFile)
252
+ const client = {
253
+ put: (_key, snapshot) => remote.putBlob(entry.hash, snapshot, { size: entry.size }),
254
+ multipartUpload: (_key, snapshot, options) => remote.putBlob(entry.hash, snapshot, {
255
+ ...options, multipart: true, size: entry.size,
256
+ }),
257
+ }
258
+ checkStopped(signal)
259
+ await uploadFile({
260
+ client, file, key: remote.blobKey(entry.hash), snapshot: stage, size: entry.size,
261
+ fingerprint: entry.hash, checkpoint: record?.fingerprint === entry.hash ? record.checkpoint : null,
262
+ recordFile, signal, progress: onProgress,
263
+ })
264
+ await rm(recordFile, { force: true })
265
+ await checkSource(path, local)
266
+ return 'uploaded'
267
+ } finally {
268
+ await rm(stage, { force: true })
269
+ }
270
+ },
271
+
272
+ async download({ file, entry, expected, remote, backup = false }) {
273
+ if (!fileAllowed(file)) throw syncError('OSS_SYNC_INVALID_PATH')
274
+ assertEntry(entry)
275
+ const target = await safeTarget(root, file)
276
+ const current = await matchLocal(target, expected, signal)
277
+ const stage = join(scratch, 'download-' + randomUUID())
278
+ try {
279
+ await receiveFile(remote, entry, stage, signal)
280
+ checkStopped(signal)
281
+ await safeTarget(root, file, true)
282
+ const backupPath = backup && current ? await backupLocal(file, target, expected) : undefined
283
+ if (current) {
284
+ await checkSource(target, current)
285
+ await chmod(stage, Number(current.mode) & 0o777)
286
+ await checkSource(target, current)
287
+ await rename(stage, target)
288
+ } else {
289
+ await chmod(stage, 0o666 & ~process.umask())
290
+ await safeTarget(root, file)
291
+ try {
292
+ // A new download must never replace a file created since preview.
293
+ await link(stage, target)
294
+ } catch (error) {
295
+ if (error.code === 'EEXIST') throw syncError('OSS_SYNC_FILE_CHANGED')
296
+ throw error
297
+ }
298
+ }
299
+ return { backup: backupPath }
300
+ } finally {
301
+ await rm(stage, { force: true })
302
+ }
303
+ },
304
+
305
+ async remove({ file, expected }) {
306
+ if (!fileAllowed(file)) throw syncError('OSS_SYNC_INVALID_PATH')
307
+ assertEntry(expected)
308
+ const target = await safeTarget(root, file)
309
+ const current = await matchLocal(target, expected, signal)
310
+ const backup = await backupLocal(file, target, expected)
311
+ await checkSource(target, current)
312
+ checkStopped(signal)
313
+ await unlink(target)
314
+ return { backup }
315
+ },
316
+ })
317
+ })
318
+ }
@@ -0,0 +1,270 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { assertPortablePaths, createRemoteStore, validateManifest } from './oss-collab-remote.js'
3
+ import { withLocalProject } from './oss-collab-local.js'
4
+
5
+ export function collabError(code) {
6
+ return Object.assign(new Error(code), { code })
7
+ }
8
+
9
+ const asMap = files => new Map(Object.entries(files || {}))
10
+ const same = (a, b) => a?.hash === b?.hash && a?.size === b?.size
11
+ const targetName = destination => [destination.bucket, destination.prefix].filter(Boolean).join('/')
12
+ const destinationId = destination => JSON.stringify([destination.endpoint, destination.bucket, destination.prefix])
13
+ const isIgnoreFile = file => file === '.gitignore' || file.endsWith('/.gitignore')
14
+
15
+ function baselineOf(value) {
16
+ try {
17
+ return value ? validateManifest(value) : null
18
+ } catch {
19
+ throw collabError('OSS_SYNC_BASELINE_INVALID')
20
+ }
21
+ }
22
+
23
+ function classify(base, local, remote, paths) {
24
+ const upload = []
25
+ const download = []
26
+ const removeLocal = []
27
+ const removeRemote = []
28
+ const conflicts = []
29
+ const baseline = asMap(base?.files)
30
+ const cloud = asMap(remote?.files)
31
+ for (const file of paths) {
32
+ const l = local.get(file)
33
+ const r = cloud.get(file)
34
+ const b = baseline.get(file)
35
+ if (same(l, r)) continue
36
+ if (!remote) {
37
+ if (l) upload.push({ file, size: l.size })
38
+ } else if (!base) {
39
+ if (!l) download.push({ file, size: r.size })
40
+ else if (r) conflicts.push({ file, local: l, remote: r })
41
+ } else if (same(l, b)) {
42
+ if (r) download.push({ file, size: r.size })
43
+ else removeLocal.push({ file })
44
+ } else if (same(r, b)) {
45
+ if (l) upload.push({ file, size: l.size })
46
+ else removeRemote.push({ file })
47
+ } else {
48
+ conflicts.push({ file, local: l || null, remote: r || null })
49
+ }
50
+ }
51
+ return { upload, download, removeLocal, removeRemote, conflicts }
52
+ }
53
+
54
+ export async function planProject({ root, client, destination, signal, requireRemote = false }) {
55
+ const store = createRemoteStore(client, destination)
56
+ return withLocalProject(root, signal, async workspace => {
57
+ const head = await store.readHead()
58
+ if (requireRemote && !head.manifest) throw collabError('OSS_COLLAB_NO_PUBLISHED_VERSION')
59
+ const localBaseline = await workspace.readBaseline()
60
+ const localFiles = await workspace.scan()
61
+ const base = baselineOf(localBaseline)
62
+ if (base && head.manifest?.projectId !== base.projectId) throw collabError('OSS_COLLAB_PROJECT_MISMATCH')
63
+ const local = asMap(localFiles)
64
+ const candidates = [...new Set([...local.keys(), ...Object.keys(base?.files || {}), ...Object.keys(head.manifest?.files || {})])].sort()
65
+ const eligible = await workspace.filterFiles(candidates)
66
+ try {
67
+ assertPortablePaths(eligible.filter(file => local.has(file) || Object.hasOwn(head.manifest?.files || {}, file)))
68
+ } catch {
69
+ throw collabError('OSS_COLLAB_PATH_COLLISION')
70
+ }
71
+ const changes = classify(base, local, head.manifest, eligible)
72
+ const legacy = head.manifest ? new Map() : await store.listLegacy()
73
+ if (legacy.size && !local.size) throw collabError('OSS_COLLAB_LEGACY_LOCAL_REQUIRED')
74
+ if (!head.manifest && !local.size) throw collabError('OSS_COLLAB_EMPTY_PROJECT')
75
+ const changed = Object.values(changes).some(entries => entries.length)
76
+ const mode = !head.manifest
77
+ ? (legacy.size ? 'migrate' : 'initialize')
78
+ : !base ? 'download' : changed || base.revision !== head.manifest.revision ? 'sync' : 'noop'
79
+ return {
80
+ id: randomUUID(),
81
+ target: targetName(destination),
82
+ revision: head.manifest?.revision || null,
83
+ mode,
84
+ ...changes,
85
+ legacyCount: legacy.size,
86
+ legacyReuseCandidates: changes.upload.filter(({ file, size }) => legacy.get(file)?.size === size).length,
87
+ baseRevision: base?.revision || null,
88
+ createdAt: Date.now(),
89
+ destinationId: destinationId(destination),
90
+ eligible,
91
+ local,
92
+ head,
93
+ legacy,
94
+ }
95
+ })
96
+ }
97
+
98
+ export function planPreview(plan) {
99
+ const { id, target, revision, mode, upload, download, removeLocal, removeRemote, conflicts, legacyCount, legacyReuseCandidates, baseRevision } = plan
100
+ return { id, target, revision, mode, upload, download, removeLocal, removeRemote, conflicts, legacyCount, legacyReuseCandidates, baseRevision }
101
+ }
102
+
103
+ export function selectChanges(plan, { action, resolutions, confirmDeletes }) {
104
+ if (!['sync', 'download'].includes(action) || plan.mode === 'noop' ||
105
+ (action === 'download' && !plan.head.manifest) || (action === 'sync' && plan.mode === 'download')) {
106
+ throw collabError('OSS_COLLAB_PREVIEW_STALE')
107
+ }
108
+ const uploads = action === 'sync' ? [...plan.upload] : []
109
+ const removesRemote = action === 'sync' ? [...plan.removeRemote] : []
110
+ const downloads = [...plan.download]
111
+ const removesLocal = [...plan.removeLocal]
112
+ for (const { file, local, remote } of plan.conflicts) {
113
+ const choice = Object.hasOwn(resolutions, file) ? resolutions[file] : undefined
114
+ if (choice === 'remote') {
115
+ if (remote) downloads.push({ file, size: remote.size, backup: true })
116
+ else removesLocal.push({ file })
117
+ } else if (choice === 'local') {
118
+ if (action !== 'sync') continue
119
+ if (local) uploads.push({ file, size: local.size })
120
+ else removesRemote.push({ file })
121
+ } else {
122
+ throw collabError('OSS_COLLAB_RESOLUTION_REQUIRED')
123
+ }
124
+ }
125
+ if ((removesLocal.length || removesRemote.length) && !confirmDeletes) {
126
+ throw collabError('OSS_COLLAB_DELETE_CONFIRMATION_REQUIRED')
127
+ }
128
+ return { downloads, uploads, removesLocal, removesRemote }
129
+ }
130
+
131
+ function validateCurrentPlan(plan, head, local, baseline, eligible, destination) {
132
+ if (plan.destinationId !== destinationId(destination) || plan.head.position !== head.position ||
133
+ plan.revision !== (head.manifest?.revision || null) || plan.baseRevision !== (baseline?.revision || null) ||
134
+ local.size !== plan.local.size || [...local].some(([file, entry]) => !same(entry, plan.local.get(file))) ||
135
+ eligible.length !== plan.eligible.length || eligible.some((file, index) => file !== plan.eligible[index])) {
136
+ throw collabError('OSS_COLLAB_PREVIEW_STALE')
137
+ }
138
+ }
139
+
140
+ export async function applyProject({ root, client, destination, plan, action, changes, signal, onProgress }) {
141
+ const remote = createRemoteStore(client, destination)
142
+ return withLocalProject(root, signal, async workspace => {
143
+ const job = {
144
+ phase: 'scanning', total: 0, uploaded: 0, downloaded: 0, removed: 0, skipped: 0, failed: 0,
145
+ currentFile: '', currentPercent: 0, failures: [],
146
+ }
147
+ const emit = () => {
148
+ const snapshot = { ...job, failures: [...job.failures] }
149
+ onProgress?.(snapshot)
150
+ return snapshot
151
+ }
152
+ function checkStopped() {
153
+ if (signal?.aborted) throw collabError('OSS_SYNC_STOPPED')
154
+ }
155
+ async function processFile(phase, file, handler) {
156
+ checkStopped()
157
+ job.phase = phase
158
+ job.currentFile = file
159
+ job.currentPercent = 0
160
+ emit()
161
+ try {
162
+ const result = await handler()
163
+ job[result]++
164
+ } catch (error) {
165
+ checkStopped()
166
+ if (error?.code === 'OSS_SYNC_STATE_FAILED') throw error
167
+ const code = typeof error?.code === 'string' && /^(OSS_SYNC_|OSS_COLLAB_)[A-Z_]{1,70}$/.test(error.code)
168
+ ? error.code : phase === 'downloading' ? 'OSS_SYNC_DOWNLOAD_FAILED' : 'OSS_SYNC_UPLOAD_FAILED'
169
+ const status = error?.status >= 400 && error.status <= 599 ? Number(error.status) : undefined
170
+ job.failures.push({ file, code, status })
171
+ job.failed++
172
+ }
173
+ job.currentFile = ''
174
+ job.currentPercent = 0
175
+ emit()
176
+ }
177
+
178
+ emit()
179
+ const head = await remote.readHead()
180
+ const baseValue = await workspace.readBaseline()
181
+ const localFiles = await workspace.scan()
182
+ const local = asMap(localFiles)
183
+ const base = baselineOf(baseValue)
184
+ const eligible = await workspace.filterFiles(plan.eligible)
185
+ validateCurrentPlan(plan, head, local, base, eligible, destination)
186
+ if (!head.manifest && plan.mode === 'initialize' && (await remote.listLegacy()).size) throw collabError('OSS_COLLAB_PREVIEW_STALE')
187
+
188
+ const { uploads, downloads, removesLocal, removesRemote } = changes
189
+ const cloud = asMap(head.manifest?.files)
190
+ const next = new Map(cloud)
191
+ for (const { file } of uploads) next.set(file, local.get(file))
192
+ for (const { file } of removesRemote) next.delete(file)
193
+ // Validate the complete manifest before applying filesystem changes.
194
+ const manifest = action === 'sync' && (!head.manifest || uploads.length || removesRemote.length) ? validateManifest({
195
+ projectId: head.manifest?.projectId || randomUUID(),
196
+ revision: randomUUID(),
197
+ parent: head.manifest?.revision || null,
198
+ createdAt: new Date().toISOString(),
199
+ files: Object.fromEntries([...next].sort(([a], [b]) => a.localeCompare(b))),
200
+ }) : null
201
+
202
+ const operations = new Set([...uploads, ...downloads, ...removesLocal, ...removesRemote].map(item => item.file))
203
+ const conflicts = new Set(plan.conflicts.map(item => item.file))
204
+ job.skipped = eligible.filter(file => !operations.has(file) && !conflicts.has(file) && local.has(file) && same(local.get(file), cloud.get(file))).length
205
+ job.total = job.skipped + uploads.length + downloads.length + removesLocal.length + removesRemote.length
206
+ emit()
207
+
208
+ const incoming = [
209
+ ...removesLocal.map(change => ({ ...change, remove: true })),
210
+ ...downloads,
211
+ ]
212
+ async function applyIncoming(change) {
213
+ const { file, backup, remove } = change
214
+ await processFile('downloading', file, async () => {
215
+ if (remove) {
216
+ await workspace.remove({ file, expected: local.get(file) })
217
+ return 'removed'
218
+ }
219
+ await workspace.download({ file, entry: cloud.get(file), expected: local.get(file) || null, remote, backup })
220
+ return 'downloaded'
221
+ })
222
+ }
223
+ const incomingRules = incoming.filter(({ file }) => isIgnoreFile(file))
224
+ for (const change of incomingRules) await applyIncoming(change)
225
+ if (job.failed) return emit()
226
+
227
+ const remaining = incoming.filter(({ file }) => !isIgnoreFile(file))
228
+ const stillEligible = incomingRules.length
229
+ ? new Set(await workspace.filterFiles(remaining.map(({ file }) => file)))
230
+ : null
231
+ for (const change of remaining) {
232
+ if (stillEligible && !stillEligible.has(change.file)) {
233
+ job.skipped++
234
+ emit()
235
+ } else {
236
+ await applyIncoming(change)
237
+ }
238
+ }
239
+ if (job.failed) return emit()
240
+
241
+ // Once cloud changes are applied, record that baseline even if a later upload needs a retry.
242
+ if (head.manifest && base?.revision !== head.manifest.revision) await workspace.writeBaseline(head.manifest)
243
+ if (!manifest) return emit()
244
+ const outgoing = [...uploads, ...removesRemote].map(({ file }) => file)
245
+ if ((await workspace.filterFiles(outgoing)).length !== outgoing.length) throw collabError('OSS_COLLAB_PREVIEW_STALE')
246
+
247
+ for (const { file } of uploads) {
248
+ const entry = local.get(file)
249
+ await processFile('uploading', file, async () => {
250
+ if (plan.legacy.get(file)?.size === entry.size && await remote.reuseLegacy(file, entry.hash, entry.size, signal)) {
251
+ return 'skipped'
252
+ }
253
+ return await workspace.upload({
254
+ file, entry, remote, onProgress(percent) {
255
+ job.currentPercent = percent
256
+ emit()
257
+ },
258
+ })
259
+ })
260
+ }
261
+ if (job.failed) return emit()
262
+ checkStopped()
263
+ job.phase = 'publishing'
264
+ emit()
265
+ await remote.publish(manifest, head)
266
+ await workspace.writeBaseline(manifest)
267
+ job.removed += removesRemote.length
268
+ return emit()
269
+ })
270
+ }