@arcadia-eternity/content-sdk 4.4.2 → 4.5.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.
@@ -19,7 +19,8 @@ const sharedFields = {
19
19
  packages: z.record(z.string().regex(packagePattern), z
20
20
  .string()
21
21
  .min(1)
22
- .refine(value => !!value.trim() && !/(?:file:|link:|workspace:|\/|\\)/.test(value), '额外 npm 包需要可共享的注册表版本约束')),
22
+ .refine(value => /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(value) ||
23
+ (!!value.trim() && !/(?:file:|link:|workspace:|\/|\\)/.test(value)), '额外 npm 包需要可共享的注册表版本约束')),
23
24
  sources: z
24
25
  .array(z.string().regex(packagePattern))
25
26
  .max(20)
@@ -1,6 +1,7 @@
1
- import type { ContentWorkspace, EnvironmentVersion, PrepareVersionInput, StaticPreparer } from './content-workspace.js';
1
+ import type { ContentWorkspace, EnvironmentInstallation, PrepareEnvironmentInput, StaticPreparer } from './content-workspace.js';
2
2
  import type { ManagedSource } from './managed-sources.js';
3
3
  export interface ManagedProjectsOptions {
4
+ bundledPackageRoot?: string;
4
5
  registry?: string;
5
6
  offline?: boolean;
6
7
  /** Host permission to acquire metadata/materials; never grants authority to execute them. */
@@ -21,17 +22,22 @@ export declare class ManagedProjects {
21
22
  #private;
22
23
  readonly root: string;
23
24
  constructor(root: string, options?: ManagedProjectsOptions);
24
- prepareVersion(workspace: ContentWorkspace, input: {
25
- onProgress?: PrepareVersionInput['onProgress'];
25
+ prepareEnvironment(workspace: ContentWorkspace, input: {
26
+ onProgress?: PrepareEnvironmentInput['onProgress'];
26
27
  environmentId: string;
27
- expectedRevision: string;
28
+ expectedRevision: string | null;
29
+ document?: PrepareEnvironmentInput['document'];
28
30
  signal?: AbortSignal;
29
31
  beforeCommit?: () => Promise<void>;
30
- }, validate: StaticPreparer): Promise<EnvironmentVersion>;
32
+ }, validate: StaticPreparer): Promise<EnvironmentInstallation>;
33
+ /** Refresh only shipped bytes, without resolving or downloading third-party dependencies. */
34
+ synchronizeBundledBase(workspace: ContentWorkspace, validate: StaticPreparer): Promise<void>;
35
+ synchronizeProject<T>(project: string, consume: (directory: string, version: string) => Promise<T>): Promise<T | undefined>;
31
36
  /** Transfer an installed project to the host's existing library without a second copy. */
32
37
  prepareProject<T>(document: unknown, input: {
33
38
  signal?: AbortSignal;
34
- onProgress?: PrepareVersionInput['onProgress'];
39
+ onProgress?: PrepareEnvironmentInput['onProgress'];
40
+ projectDirectory?: string;
35
41
  }, consume: (directory: string, signal: AbortSignal) => Promise<T>): Promise<T>;
36
42
  close(): Promise<void>;
37
43
  }
@@ -1,12 +1,13 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import { join, resolve } from 'node:path';
4
5
  import { promisify } from 'node:util';
5
6
  import { valid, validRange } from 'semver';
6
- import { inspectNpmProject, resolveNpmInvocation } from '@arcadia-eternity/pack-loader/node';
7
+ import { inspectNpmProject, resolveNpmInvocation, withShippedEnvironmentProject, withShippedCatalogArchive, } from '@arcadia-eternity/pack-loader/node';
7
8
  import { normalizeEnvironmentDocument } from './debug-environments.js';
8
9
  import { acquireSource } from './managed-sources.js';
9
- import { contentError, materialFiles } from './workspace-materials.js';
10
+ import { contentError, materialFiles, writeMaterials } from './workspace-materials.js';
10
11
  import { errorCode, isRecord } from './types.js';
11
12
  const execute = promisify(execFile);
12
13
  const DEFAULT_TIMEOUT = 120_000;
@@ -34,7 +35,9 @@ function checkDependencySpecs(manifest) {
34
35
  if (!isRecord(entries))
35
36
  throw contentError('INSTALL_DEPENDENCY_INVALID');
36
37
  for (const [name, range] of Object.entries(entries)) {
37
- if (!packageName.test(name) || typeof range !== 'string' || !validRange(range))
38
+ if (!packageName.test(name) ||
39
+ typeof range !== 'string' ||
40
+ (!validRange(range) && !/^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(range)))
38
41
  throw contentError('INSTALL_DEPENDENCY_SOURCE_FORBIDDEN');
39
42
  }
40
43
  }
@@ -51,7 +54,7 @@ function checkLock(lock, candidates = false) {
51
54
  throw contentError('INSTALL_LOCK_INVALID');
52
55
  if (typeof entry.resolved !== 'string')
53
56
  continue;
54
- if (candidates && /^file:candidates\/source-[0-9]+\.tgz$/.test(entry.resolved))
57
+ if (candidates && /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(entry.resolved))
55
58
  continue;
56
59
  const url = new URL(entry.resolved);
57
60
  if (url.protocol !== 'https:' || url.username || url.password)
@@ -137,20 +140,101 @@ export class ManagedProjects {
137
140
  throw contentError('NPM_INSTALL_FAILED');
138
141
  }
139
142
  }
140
- prepareVersion(workspace, input, validate) {
143
+ prepareEnvironment(workspace, input, validate) {
141
144
  if (typeof validate !== 'function')
142
145
  return Promise.reject(contentError('STATIC_PREPARER_REQUIRED'));
143
146
  return this.#track(this.#prepare(async () => {
144
- const draft = await workspace.getDraft(input.environmentId);
145
- if (draft.revision !== input.expectedRevision)
146
- throw contentError('REVISION_CONFLICT');
147
- return draft.document;
148
- }, input, async (directory, signal) => {
149
- const current = await workspace.getDraft(input.environmentId);
150
- if (current.revision !== input.expectedRevision)
147
+ const draft = await workspace.getDraft(input.environmentId).catch(error => {
148
+ if (errorCode(error) !== 'ENOENT')
149
+ throw error;
150
+ return undefined;
151
+ });
152
+ if ((draft?.revision ?? null) !== input.expectedRevision)
151
153
  throw contentError('REVISION_CONFLICT');
152
- return workspace.prepareVersion({ ...input, projectDirectory: directory, signal }, validate);
154
+ return input.document ?? draft?.document;
155
+ }, { ...input, projectDirectory: join(workspace.root, 'environments', input.environmentId) }, async (directory, signal, document) => {
156
+ return workspace.prepareEnvironment({ ...input, document, projectDirectory: directory, signal }, validate);
157
+ }));
158
+ }
159
+ /** Refresh only shipped bytes, without resolving or downloading third-party dependencies. */
160
+ async synchronizeBundledBase(workspace, validate) {
161
+ for (const draft of await workspace.listDrafts()) {
162
+ await this.synchronizeProject(join(workspace.root, 'environments', draft.document.id), async (directory, version) => {
163
+ const name = '@arcadia-eternity/data-pack-base';
164
+ await workspace.prepareEnvironment({
165
+ environmentId: draft.document.id,
166
+ expectedRevision: draft.revision,
167
+ document: {
168
+ ...draft.document,
169
+ packages: { ...draft.document.packages, [name]: version },
170
+ sources: draft.document.sources.filter(source => source !== name),
171
+ },
172
+ projectDirectory: directory,
173
+ signal: this.#controller.signal,
174
+ }, validate);
175
+ });
176
+ }
177
+ }
178
+ synchronizeProject(project, consume) {
179
+ return this.#track(this.#synchronizeProject(project, consume));
180
+ }
181
+ async #synchronizeProject(project, consume) {
182
+ const signal = this.#controller.signal;
183
+ signal.throwIfAborted();
184
+ const base = '@arcadia-eternity/data-pack-base';
185
+ const manifest = JSON.parse(await readFile(join(project, 'package.json'), 'utf8'));
186
+ const installed = join('node_modules', base).replaceAll('\\', '/');
187
+ const lock = JSON.parse(await readFile(join(project, 'package-lock.json'), 'utf8').catch(error => {
188
+ if (errorCode(error) !== 'ENOENT')
189
+ throw error;
190
+ return JSON.stringify({ lockfileVersion: 3, packages: { '': { dependencies: manifest.dependencies ?? {} } } });
153
191
  }));
192
+ if (!Object.hasOwn(manifest.dependencies ?? {}, base) &&
193
+ !lock.packages?.[installed] &&
194
+ !manifest.arcadiaEnvironment?.sources?.includes(base))
195
+ return;
196
+ if (!this.#options.bundledPackageRoot)
197
+ throw contentError('BUNDLED_PACKAGE_UNAVAILABLE');
198
+ return withShippedEnvironmentProject(this.#options.bundledPackageRoot, async (shipped) => {
199
+ const fresh = await materialFiles(shipped, { signal });
200
+ const current = await materialFiles(project, { allowMissingLock: true, signal });
201
+ const baseFiles = fresh.filter(file => file.path.startsWith(installed + '/'));
202
+ const version = JSON.parse(baseFiles.find(file => file.path === installed + '/package.json').bytes.toString())
203
+ .version;
204
+ const previous = new Map(current.filter(file => file.path.startsWith(installed + '/')).map(file => [file.path, file.bytes]));
205
+ if (manifest.dependencies?.[base] === version &&
206
+ previous.size === baseFiles.length &&
207
+ baseFiles.every(file => previous.get(file.path)?.equals(file.bytes)))
208
+ return;
209
+ await mkdir(this.root, { recursive: true });
210
+ const directory = await mkdtemp(join(this.root, 'sync-base-'));
211
+ try {
212
+ manifest.dependencies = { ...manifest.dependencies, [base]: version };
213
+ if (manifest.arcadiaManagedSources)
214
+ delete manifest.arcadiaManagedSources[base];
215
+ lock.packages[''] = { ...lock.packages[''], dependencies: manifest.dependencies };
216
+ for (const key of Object.keys(lock.packages))
217
+ if (key === installed || key.startsWith(installed + '/'))
218
+ delete lock.packages[key];
219
+ lock.packages[installed] = { name: base, version };
220
+ const files = current.filter(file => !file.path.startsWith(installed + '/') &&
221
+ file.path !== 'node_modules/.package-lock.json' &&
222
+ file.path !== 'package.json' &&
223
+ file.path !== 'package-lock.json');
224
+ await writeMaterials(directory, [
225
+ ...files,
226
+ ...baseFiles,
227
+ { path: 'package.json', bytes: Buffer.from(JSON.stringify(manifest)) },
228
+ { path: 'package-lock.json', bytes: Buffer.from(JSON.stringify(lock)) },
229
+ ]);
230
+ await inspectNpmProject(directory);
231
+ signal.throwIfAborted();
232
+ return await consume(directory, version);
233
+ }
234
+ finally {
235
+ await rm(directory, { recursive: true, force: true });
236
+ }
237
+ });
154
238
  }
155
239
  /** Transfer an installed project to the host's existing library without a second copy. */
156
240
  prepareProject(document, input, consume) {
@@ -183,19 +267,88 @@ export class ManagedProjects {
183
267
  throw contentError('INSTALL_PACKAGE_LIMIT');
184
268
  const dependencies = {};
185
269
  for (const [name, range] of Object.entries(document.packages)) {
186
- if (typeof range !== 'string' || range.length > 256 || !validRange(range))
270
+ if (typeof range !== 'string' ||
271
+ range.length > 256 ||
272
+ (!validRange(range) && !/^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(range)))
187
273
  throw contentError('INSTALL_VERSION_INVALID');
188
274
  dependencies[name] = range;
189
275
  }
276
+ const baseName = '@arcadia-eternity/data-pack-base';
277
+ const includesBase = Object.hasOwn(dependencies, baseName) || document.sources.includes(baseName);
278
+ if (Object.hasOwn(dependencies, baseName) && document.sources.includes(baseName))
279
+ throw contentError('INSTALL_DUPLICATE_PACKAGE');
280
+ const baseRoot = this.#options.bundledPackageRoot;
281
+ if (includesBase && !baseRoot)
282
+ throw contentError('BUNDLED_PACKAGE_UNAVAILABLE');
283
+ if (includesBase) {
284
+ const baseManifest = JSON.parse(await readFile(join(baseRoot, 'package.json'), 'utf8'));
285
+ if (baseManifest.name !== baseName)
286
+ throw contentError('BUNDLED_PACKAGE_INVALID');
287
+ dependencies[baseName] = baseManifest.version;
288
+ document.packages[baseName] = baseManifest.version;
289
+ document.sources = document.sources.filter(name => name !== baseName);
290
+ if (Object.keys(dependencies).every(name => name === baseName) && document.sources.length === 0) {
291
+ await input.onProgress?.({ stage: 'preparing' });
292
+ return await withShippedEnvironmentProject(baseRoot, async (staged) => {
293
+ const manifest = JSON.parse(await readFile(join(staged, 'package.json'), 'utf8'));
294
+ const saved = input.projectDirectory
295
+ ? JSON.parse(await readFile(join(input.projectDirectory, 'package.json'), 'utf8').catch(error => {
296
+ if (errorCode(error) !== 'ENOENT')
297
+ throw error;
298
+ return '{}';
299
+ }))
300
+ : {};
301
+ const project = {
302
+ ...manifest,
303
+ ...saved,
304
+ dependencies: {
305
+ [baseName]: baseManifest.version,
306
+ },
307
+ };
308
+ const lock = JSON.parse(await readFile(join(staged, 'package-lock.json'), 'utf8'));
309
+ lock.name = project.name;
310
+ lock.version = project.version;
311
+ lock.packages[''] = { name: project.name, version: project.version, dependencies: project.dependencies };
312
+ await writeFile(join(staged, 'package.json'), JSON.stringify(project));
313
+ await writeFile(join(staged, 'package-lock.json'), JSON.stringify(lock));
314
+ signal.throwIfAborted();
315
+ return consume(staged, signal, document);
316
+ });
317
+ }
318
+ }
190
319
  // Acquisition approval is separate from any runtime execution policy. This
191
320
  // installer never evaluates author modules or invokes lifecycle scripts.
192
- if (!this.#options.allowThirdPartyContent && (Object.keys(dependencies).length || document.sources.length))
321
+ if (!this.#options.allowThirdPartyContent &&
322
+ (Object.keys(dependencies).some(name => name !== baseName) || document.sources.some(name => name !== baseName)))
193
323
  throw contentError('THIRD_PARTY_CONTENT_NOT_AUTHORIZED');
194
324
  await mkdir(join(this.root, 'staging'), { recursive: true, mode: 0o700 });
195
325
  directory = await mkdtemp(join(this.root, 'staging', 'prepare-'));
196
326
  await mkdir(join(directory, 'candidates'));
327
+ for (const [name, spec] of Object.entries(dependencies)) {
328
+ if (name === baseName)
329
+ continue;
330
+ if (!spec.startsWith('file:'))
331
+ continue;
332
+ if (!input.projectDirectory)
333
+ throw contentError('ENVIRONMENT_SOURCE_MISSING');
334
+ const relativeFile = spec.slice(5);
335
+ const sourceFile = join(await realpath(input.projectDirectory), relativeFile);
336
+ if ((await realpath(sourceFile)) !== sourceFile)
337
+ throw contentError('MATERIAL_PATH_ESCAPE');
338
+ await writeFile(join(directory, relativeFile), await readFile(sourceFile));
339
+ }
340
+ if (includesBase) {
341
+ await withShippedCatalogArchive(baseRoot, undefined, async (file) => {
342
+ const bytes = await readFile(file);
343
+ const filename = `candidates/base-${createHash('sha256').update(bytes).digest('hex')}.tgz`;
344
+ await writeFile(join(directory, filename), bytes);
345
+ dependencies[baseName] = 'file:' + filename;
346
+ });
347
+ }
197
348
  const provenance = {};
198
349
  for (const [index, name] of document.sources.entries()) {
350
+ if (name === baseName)
351
+ continue;
199
352
  if (Object.hasOwn(dependencies, name))
200
353
  throw contentError('INSTALL_DUPLICATE_PACKAGE');
201
354
  const source = this.#options.sources[name];
@@ -231,15 +384,35 @@ export class ManagedProjects {
231
384
  const files = await readdir(output);
232
385
  if (files.length !== 1 || !files[0].endsWith('.tgz'))
233
386
  throw contentError('INSTALL_PACK_INVALID');
234
- const filename = 'candidates/source-' + index + '.tgz';
387
+ const archiveDigest = createHash('sha256')
388
+ .update(await readFile(join(output, files[0])))
389
+ .digest('hex');
390
+ const filename = `candidates/source-${index}-${archiveDigest}.tgz`;
235
391
  await rename(join(output, files[0]), join(directory, filename));
236
392
  dependencies[name] = 'file:' + filename;
237
393
  provenance[name] = captured.provenance;
238
394
  await rm(captured.directory, { recursive: true, force: true });
239
395
  await rm(output, { recursive: true, force: true });
240
396
  }
397
+ const savedManifest = input.projectDirectory
398
+ ? JSON.parse(await readFile(join(input.projectDirectory, 'package.json'), 'utf8').catch(error => {
399
+ if (errorCode(error) !== 'ENOENT')
400
+ throw error;
401
+ return '{}';
402
+ }))
403
+ : {};
404
+ if (input.projectDirectory) {
405
+ const lock = await readFile(join(input.projectDirectory, 'package-lock.json')).catch(error => {
406
+ if (errorCode(error) !== 'ENOENT')
407
+ throw error;
408
+ return undefined;
409
+ });
410
+ if (lock)
411
+ await writeFile(join(directory, 'package-lock.json'), lock);
412
+ }
241
413
  await writeFile(join(directory, 'package.json'), JSON.stringify({
242
- name: 'arcadia-managed-environment',
414
+ ...savedManifest,
415
+ name: savedManifest.name ?? 'arcadia-managed-environment',
243
416
  version: '1.0.0',
244
417
  private: true,
245
418
  dependencies,
@@ -276,7 +449,7 @@ export class ManagedProjects {
276
449
  await materialFiles(directory, { signal, maxBytes: this.#options.maxBytes, maxFiles: this.#options.maxFiles });
277
450
  signal.throwIfAborted();
278
451
  await input.onProgress?.({ stage: 'preparing' });
279
- return await consume(directory, signal);
452
+ return await consume(directory, signal, document);
280
453
  }
281
454
  catch (error) {
282
455
  if (isRecord(error) && (error.name === 'AbortError' || error.name === 'TimeoutError'))
@@ -21,7 +21,7 @@
21
21
  "devDependencies": {
22
22
  "@types/node": "26.6.6",
23
23
  "typescript": "6.0.3",
24
- "@arcadia-eternity/content-sdk": "4.4.2"
24
+ "@arcadia-eternity/content-sdk": "4.5.1"
25
25
  },
26
26
  "arcadia": {
27
27
  "formatVersion": 1,
@@ -3,7 +3,8 @@ export declare function contentError(code: string, message?: string): Error & {
3
3
  code: string;
4
4
  };
5
5
  /** Capture data bytes only. Symlink targets must remain inside the installed project. */
6
- export declare function materialFiles(root: string, { signal, maxBytes, maxFiles, onRead, }?: {
6
+ export declare function materialFiles(root: string, { signal, maxBytes, maxFiles, onRead, allowMissingLock, }?: {
7
+ allowMissingLock?: boolean;
7
8
  signal?: AbortSignal;
8
9
  maxBytes?: number;
9
10
  maxFiles?: number;
@@ -12,8 +13,9 @@ export declare function materialFiles(root: string, { signal, maxBytes, maxFiles
12
13
  path: string;
13
14
  bytes: Buffer;
14
15
  }>>;
15
- export declare function writeMaterials(root: string, files: unknown, { signal, maxBytes, maxFiles, }?: {
16
+ export declare function writeMaterials(root: string, files: unknown, { signal, maxBytes, maxFiles, allowMissingLock, }?: {
16
17
  signal?: AbortSignal;
17
18
  maxBytes?: number;
18
19
  maxFiles?: number;
20
+ allowMissingLock?: boolean;
19
21
  }): Promise<void>;
@@ -23,7 +23,7 @@ function checkedMaterialPath(value) {
23
23
  return value;
24
24
  }
25
25
  /** Capture data bytes only. Symlink targets must remain inside the installed project. */
26
- export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, onRead, } = {}) {
26
+ export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, onRead, allowMissingLock = false, } = {}) {
27
27
  root = await realpath(root);
28
28
  const result = [];
29
29
  const captured = [];
@@ -73,7 +73,9 @@ export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024
73
73
  await lstat(join(root, name));
74
74
  }
75
75
  catch (error) {
76
- if (errorCode(error) === 'ENOENT' && name !== 'package.json' && name !== 'package-lock.json')
76
+ if (errorCode(error) === 'ENOENT' &&
77
+ name !== 'package.json' &&
78
+ (allowMissingLock || name !== 'package-lock.json'))
77
79
  continue;
78
80
  throw error;
79
81
  }
@@ -105,7 +107,7 @@ export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024
105
107
  }
106
108
  return result;
107
109
  }
108
- export async function writeMaterials(root, files, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, } = {}) {
110
+ export async function writeMaterials(root, files, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, allowMissingLock = false, } = {}) {
109
111
  if (!Array.isArray(files) || files.length > maxFiles)
110
112
  throw contentError('MATERIAL_LIMIT');
111
113
  const seen = new Set();
@@ -134,8 +136,10 @@ export async function writeMaterials(root, files, { signal, maxBytes = 256 * 102
134
136
  await mkdir(dirname(join(root, path)), { recursive: true });
135
137
  await writeFile(join(root, path), bytes, { flag: 'wx', mode: 0o600 });
136
138
  }
137
- if (!seen.has('package.json') || !seen.has('package-lock.json'))
139
+ if (!seen.has('package.json') || (!allowMissingLock && !seen.has('package-lock.json')))
138
140
  throw contentError('MATERIAL_LOCK_REQUIRED');
141
+ if (!seen.has('package-lock.json'))
142
+ return;
139
143
  // npm may omit this directory for a valid empty dependency graph. Static npm
140
144
  // inspection still expects it, including after a file-only archive round trip.
141
145
  await mkdir(join(root, 'node_modules'), { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcadia-eternity/content-sdk",
3
- "version": "4.4.2",
3
+ "version": "4.5.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -53,9 +53,9 @@
53
53
  "yaml": "2.9.1",
54
54
  "yauzl": "3.4.0",
55
55
  "zod": "4.6.7",
56
- "@arcadia-eternity/battle": "4.4.2",
57
- "@arcadia-eternity/pack-loader": "4.4.2",
58
- "@arcadia-eternity/schema": "4.4.2"
56
+ "@arcadia-eternity/battle": "4.5.1",
57
+ "@arcadia-eternity/schema": "4.5.1",
58
+ "@arcadia-eternity/pack-loader": "4.5.1"
59
59
  },
60
60
  "repository": {
61
61
  "type": "git",