@arcadia-eternity/content-sdk 4.3.3 → 4.4.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.
Files changed (121) hide show
  1. package/README.md +3 -3
  2. package/bin/arcadia-content-mcp.mjs +2 -0
  3. package/bin/arcadia-content.mjs +2 -0
  4. package/dist/asset-inspect.d.ts +30 -0
  5. package/dist/asset-inspect.js +84 -0
  6. package/dist/author-api.d.ts +48 -0
  7. package/dist/author-api.js +128 -0
  8. package/dist/author-reference.d.ts +61 -0
  9. package/dist/author-reference.js +130 -0
  10. package/dist/build-content.d.ts +2 -0
  11. package/dist/build-content.js +29 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/cli.js +81 -0
  14. package/dist/content-query.d.ts +30 -0
  15. package/dist/content-query.js +326 -0
  16. package/dist/content-workspace.d.ts +204 -0
  17. package/dist/content-workspace.js +981 -0
  18. package/dist/debug-environments.d.ts +96 -0
  19. package/dist/debug-environments.js +135 -0
  20. package/dist/demo.d.ts +1 -0
  21. package/dist/demo.js +18 -0
  22. package/dist/effect-build.d.ts +3 -0
  23. package/dist/effect-build.js +44 -0
  24. package/dist/environment-rules.d.ts +7 -0
  25. package/dist/environment-rules.js +94 -0
  26. package/dist/environment.d.ts +48 -0
  27. package/dist/environment.js +184 -0
  28. package/dist/job-journal.d.ts +19 -0
  29. package/dist/job-journal.js +110 -0
  30. package/dist/jobs.d.ts +103 -0
  31. package/dist/jobs.js +626 -0
  32. package/dist/lib/content.d.ts +24 -0
  33. package/dist/lib/content.js +106 -0
  34. package/dist/lib/presentation.d.ts +26 -0
  35. package/dist/lib/presentation.js +252 -0
  36. package/dist/lib/yaml-sharing.d.ts +16 -0
  37. package/dist/lib/yaml-sharing.js +130 -0
  38. package/dist/managed-projects.d.ts +37 -0
  39. package/dist/managed-projects.js +305 -0
  40. package/dist/managed-sources.d.ts +28 -0
  41. package/dist/managed-sources.js +541 -0
  42. package/dist/mcp-contracts.d.ts +420 -0
  43. package/dist/mcp-contracts.js +146 -0
  44. package/dist/mcp.d.ts +2 -0
  45. package/dist/mcp.js +228 -0
  46. package/dist/module-path.d.ts +1 -0
  47. package/dist/module-path.js +8 -0
  48. package/dist/pack-project.d.ts +10 -0
  49. package/dist/pack-project.js +178 -0
  50. package/dist/preview-control.d.ts +17 -0
  51. package/dist/preview-control.js +273 -0
  52. package/dist/preview.d.ts +24 -0
  53. package/dist/preview.js +332 -0
  54. package/dist/project-teams.d.ts +51 -0
  55. package/dist/project-teams.js +106 -0
  56. package/dist/project.d.ts +18 -0
  57. package/dist/project.js +146 -0
  58. package/dist/rename.d.ts +2 -0
  59. package/dist/rename.js +128 -0
  60. package/dist/setup.d.ts +2 -0
  61. package/dist/setup.js +117 -0
  62. package/dist/source-lock.d.ts +9 -0
  63. package/dist/source-lock.js +117 -0
  64. package/dist/template/README.md +2 -0
  65. package/dist/template/docs/presentation.md +3 -3
  66. package/dist/template/package.json +3 -7
  67. package/dist/template/test/pack.test.mjs +10 -7
  68. package/dist/testing.d.ts +58 -0
  69. package/dist/testing.js +205 -0
  70. package/dist/types.d.ts +5 -0
  71. package/dist/types.js +14 -0
  72. package/dist/workbench-context.d.ts +10 -0
  73. package/dist/workbench-context.js +27 -0
  74. package/dist/workspace-cli.d.ts +1 -0
  75. package/dist/workspace-cli.js +66 -0
  76. package/dist/workspace-materials.d.ts +19 -0
  77. package/dist/workspace-materials.js +165 -0
  78. package/dist/workspace.d.ts +190 -0
  79. package/dist/workspace.js +726 -0
  80. package/package.json +34 -27
  81. package/dist/asset-inspect.mjs +0 -67
  82. package/dist/author-api.mjs +0 -112
  83. package/dist/author-reference.mjs +0 -121
  84. package/dist/build-content.mjs +0 -30
  85. package/dist/cli.mjs +0 -76
  86. package/dist/content-query.mjs +0 -283
  87. package/dist/content-workspace.d.mts +0 -161
  88. package/dist/content-workspace.mjs +0 -936
  89. package/dist/debug-environments.mjs +0 -154
  90. package/dist/demo.mjs +0 -22
  91. package/dist/effect-build.d.mts +0 -2
  92. package/dist/effect-build.mjs +0 -46
  93. package/dist/environment-rules.d.mts +0 -5
  94. package/dist/environment-rules.mjs +0 -92
  95. package/dist/environment.mjs +0 -183
  96. package/dist/job-journal.mjs +0 -94
  97. package/dist/jobs.mjs +0 -579
  98. package/dist/lib/content.mjs +0 -95
  99. package/dist/lib/presentation.mjs +0 -240
  100. package/dist/lib/yaml-sharing.mjs +0 -101
  101. package/dist/managed-projects.d.mts +0 -35
  102. package/dist/managed-projects.mjs +0 -303
  103. package/dist/managed-sources.d.mts +0 -19
  104. package/dist/managed-sources.mjs +0 -503
  105. package/dist/mcp-contracts.mjs +0 -153
  106. package/dist/mcp.mjs +0 -369
  107. package/dist/pack-project.mjs +0 -157
  108. package/dist/preview-control.mjs +0 -260
  109. package/dist/preview.mjs +0 -313
  110. package/dist/project-teams.mjs +0 -98
  111. package/dist/project.mjs +0 -140
  112. package/dist/rename.mjs +0 -112
  113. package/dist/setup.mjs +0 -134
  114. package/dist/source-lock.mjs +0 -103
  115. package/dist/testing.mjs +0 -204
  116. package/dist/workbench-context.mjs +0 -18
  117. package/dist/workspace-cli.mjs +0 -60
  118. package/dist/workspace-materials.mjs +0 -153
  119. package/dist/workspace.mjs +0 -684
  120. /package/dist/{index.d.mts → index.d.ts} +0 -0
  121. /package/dist/{index.mjs → index.js} +0 -0
package/dist/project.mjs DELETED
@@ -1,140 +0,0 @@
1
- import { cp, lstat, mkdir, readFile, realpath, readdir, symlink, writeFile } from 'node:fs/promises'
2
- import { dirname, join } from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
- import { createRequire } from 'node:module'
5
- import { WorkspaceError } from './workspace.mjs'
6
- const require = createRequire(import.meta.url)
7
- const moduleRoot = fileURLToPath(new URL('../', import.meta.url))
8
- export function authorConnection(
9
- root,
10
- execute = false,
11
- env = process.env,
12
- readOnly = false,
13
- contextFile,
14
- published = false,
15
- ) {
16
- return {
17
- mcpServers: {
18
- arcadia: {
19
- command: process.execPath,
20
- args: [
21
- fileURLToPath(new URL('./mcp.mjs', import.meta.url)),
22
- root,
23
- ...(readOnly ? ['--read-only'] : execute ? ['--execute'] : []),
24
- ...(contextFile ? ['--context-file', contextFile] : []),
25
- ...(published ? ['--published'] : []),
26
- ],
27
- env: {
28
- ELECTRON_RUN_AS_NODE: '1',
29
- ...(env.ARCADIA_NPM_CLI ? { ARCADIA_NPM_CLI: env.ARCADIA_NPM_CLI } : {}),
30
- ...(env.ARCADIA_PREVIEW_CLIENT_URL ? { ARCADIA_PREVIEW_CLIENT_URL: env.ARCADIA_PREVIEW_CLIENT_URL } : {}),
31
- },
32
- },
33
- },
34
- }
35
- }
36
- async function packageRoot(name, entry) {
37
- let path = dirname(require.resolve(entry))
38
- for (;;) {
39
- try {
40
- if (JSON.parse(await readFile(join(path, 'package.json'), 'utf8')).name === name) return realpath(path)
41
- } catch {
42
- /* Walk to owning package. */
43
- }
44
- const parent = dirname(path)
45
- if (parent === path) throw new Error(`Cannot find SDK package ${name}`)
46
- path = parent
47
- }
48
- }
49
- /** Connect bundled tools only when absent. Never replace a project's existing dependencies. */
50
- export async function connectDevelopmentSdk(root) {
51
- root = await realpath(root)
52
- // Existing dependency directories must not redirect writes outside this project.
53
- async function directory(parts) {
54
- let current = root
55
- for (const part of parts) {
56
- current = join(current, part)
57
- try {
58
- await mkdir(current)
59
- } catch (error) {
60
- if (error.code !== 'EEXIST') throw error
61
- }
62
- const info = await lstat(current)
63
- if (info.isSymbolicLink() || !info.isDirectory())
64
- throw new WorkspaceError('PATH_INVALID', 'SDK 目录必须是项目内普通目录', current)
65
- }
66
- return current
67
- }
68
- // Validate all parents before adding any links.
69
- await directory(['node_modules'])
70
- await directory(['node_modules', '@arcadia-eternity'])
71
- await directory(['node_modules', '.bin'])
72
- const packages = {
73
- '@arcadia-eternity/battle': await packageRoot('@arcadia-eternity/battle', '@arcadia-eternity/battle/engine'),
74
- '@arcadia-eternity/pack-loader': await packageRoot(
75
- '@arcadia-eternity/pack-loader',
76
- '@arcadia-eternity/pack-loader/node',
77
- ),
78
- '@arcadia-eternity/content-sdk': moduleRoot,
79
- typescript: await packageRoot('typescript', 'typescript'),
80
- }
81
- const linked = []
82
- for (const [name, source] of Object.entries(packages)) {
83
- const target = join(root, 'node_modules', name)
84
- await directory(['node_modules', ...name.split('/').slice(0, -1)])
85
- try {
86
- await lstat(target)
87
- continue
88
- } catch (error) {
89
- if (error.code !== 'ENOENT') throw error
90
- }
91
- await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir')
92
- linked.push(name)
93
- }
94
- // npm scripts use the shared CLI, while the desktop invokes its absolute entry directly.
95
- const bin = join(root, 'node_modules/.bin')
96
- await directory(['node_modules', '.bin'])
97
- for (const [name, entry] of [
98
- ['arcadia-content', 'cli.mjs'],
99
- ['arcadia-content-mcp', 'mcp.mjs'],
100
- ]) {
101
- const script = fileURLToPath(new URL(entry, import.meta.url))
102
- if (process.platform === 'win32')
103
- await writeFile(join(bin, name + '.cmd'), `@echo off\r\nnode "${script}" %*\r\n`, { flag: 'wx' }).catch(e => {
104
- if (e.code !== 'EEXIST') throw e
105
- })
106
- else
107
- await symlink(script, join(bin, name)).catch(e => {
108
- if (e.code !== 'EEXIST') throw e
109
- })
110
- }
111
- return { linked }
112
- }
113
- export async function createSourceProject(directory, identity) {
114
- if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(identity)) throw new WorkspaceError('PROJECT_INVALID', '项目 ID 无效')
115
- await mkdir(directory) // No overwrite or merge with existing directories.
116
- let template = fileURLToPath(new URL('./template/', import.meta.url))
117
- try {
118
- await lstat(template)
119
- } catch {
120
- template = fileURLToPath(new URL('../template/', import.meta.url))
121
- }
122
- for (const entry of await readdir(template))
123
- await cp(join(template, entry), join(directory, entry), { recursive: true, force: false, errorOnExist: true })
124
- async function renameText(root) {
125
- for (const entry of await readdir(root, { withFileTypes: true })) {
126
- const file = join(root, entry.name)
127
- if (entry.isDirectory()) await renameText(file)
128
- else if (/\.(json|ya?ml|mjs|ts|md)$/.test(entry.name)) {
129
- const text = await readFile(file, 'utf8')
130
- await writeFile(file, text.replaceAll('example-content-pack', identity).replaceAll('example-pack', identity))
131
- }
132
- }
133
- }
134
- await renameText(directory)
135
- const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'))
136
- manifest.name = `@arcadia-local/${identity}`
137
- await writeFile(join(directory, 'package.json'), JSON.stringify(manifest, null, 2) + '\n')
138
- await connectDevelopmentSdk(directory)
139
- return directory
140
- }
package/dist/rename.mjs DELETED
@@ -1,112 +0,0 @@
1
- #!/usr/bin/env node
2
- import { readFile, writeFile } from 'node:fs/promises'
3
- import { resolve } from 'node:path'
4
- import YAML from 'yaml'
5
- import { AuthorWorkspace } from './workspace.mjs'
6
- import { teamDocument } from './project-teams.mjs'
7
- import { readContentSources } from './lib/content.mjs'
8
-
9
- const args = process.argv.slice(2)
10
- if (args.includes('--help')) {
11
- console.log('arcadia-content rename --name @your-scope/my-pack --project-id my-pack --namespace my-pack')
12
- process.exit(0)
13
- }
14
- const options = {}
15
- for (let i = 0; i < args.length; i += 2) {
16
- if (
17
- !['--name', '--project-id', '--namespace'].includes(args[i]) ||
18
- options[args[i]] ||
19
- !args[i + 1] ||
20
- args[i + 1].startsWith('--')
21
- )
22
- throw new Error(`Unknown, duplicate or incomplete option: ${args[i]}`)
23
- options[args[i]] = args[i + 1]
24
- }
25
- if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/.test(options['--name'] ?? '') || options['--name'].length > 214)
26
- throw new Error('Provide a lowercase npm package name.')
27
- if (
28
- !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/.test(options['--project-id'] ?? '') ||
29
- ['base', 'constructor', 'prototype'].includes(options['--project-id'])
30
- )
31
- throw new Error('Provide a non-reserved project ID (1–80 letters, digits, dots, underscores or hyphens).')
32
- if (!/^[a-z0-9][a-z0-9_.-]{0,79}$/.test(options['--namespace'] ?? '') || options['--namespace'] === 'base')
33
- throw new Error('Provide a non-reserved lowercase namespace (1–80 characters).')
34
-
35
- const root = resolve('.')
36
- const packagePath = resolve('package.json')
37
- const manifest = JSON.parse(await readFile(packagePath, 'utf8'))
38
- const oldId = manifest.arcadia.projectId
39
- const oldNamespace = manifest.arcadia.namespace
40
- const sources = await readContentSources(root)
41
- const workspace = await AuthorWorkspace.open(root, { watch: false })
42
- for (const { file } of await workspace.files()) {
43
- if (!/^debug\/teams\/[^/]+\.yaml$/.test(file)) continue
44
- const source = await workspace.read(file)
45
- const document = YAML.parseDocument(source.text)
46
- if (document.errors.length) throw document.errors[0]
47
- teamDocument(document.toJS())
48
- sources.push({ kind: 'project-team', file: resolve(file), document, version: source.version, relative: file })
49
- }
50
- function rewrite(value) {
51
- if (Array.isArray(value)) return value.map(rewrite)
52
- if (!value || typeof value !== 'object') return value
53
- const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]))
54
- if (result.$ref?.projectId === oldId) result.$ref.projectId = options['--project-id']
55
- if (
56
- result.namespace === oldNamespace &&
57
- typeof result.id === 'string' &&
58
- Object.keys(result).every(key => ['namespace', 'id'].includes(key))
59
- )
60
- result.namespace = options['--namespace']
61
- return result
62
- }
63
- manifest.name = options['--name']
64
- manifest.arcadia.projectId = options['--project-id']
65
- manifest.arcadia.namespace = options['--namespace']
66
- const changes = sources.map(source => {
67
- if (!source.document) return { file: source.file, text: JSON.stringify(rewrite(source.value), null, 2) + '\n' }
68
- // Detach alias uses before editing: an anchor may also supply an unrelated content ID.
69
- const aliases = new Map()
70
- YAML.visit(source.document, {
71
- Alias(_key, alias) {
72
- const replacement = source.document.createNode(alias.toJS(source.document), {
73
- aliasDuplicateObjects: false,
74
- })
75
- replacement.comment = alias.comment
76
- replacement.commentBefore = alias.commentBefore
77
- aliases.set(alias, replacement)
78
- },
79
- })
80
- YAML.visit(source.document, { Alias: (_key, alias) => aliases.get(alias) })
81
- YAML.visit(source.document, {
82
- Map(_key, node) {
83
- if (source.kind === 'project-team') {
84
- const update = value => {
85
- if (YAML.isScalar(value) && typeof value.value === 'string' && value.value.startsWith(`${oldNamespace}:`))
86
- value.value = options['--namespace'] + value.value.slice(oldNamespace.length)
87
- }
88
- for (const key of ['species', 'ability', 'emblem']) update(node.get(key, true))
89
- const skills = node.get('skills', true)
90
- if (YAML.isSeq(skills)) skills.items.forEach(update)
91
- }
92
- const namespace = node.get('namespace', true)
93
- if (YAML.isScalar(namespace) && namespace.value === oldNamespace && node.has('id') && node.items.length === 2)
94
- namespace.value = options['--namespace']
95
- const reference = node.get('$ref', true)
96
- if (!YAML.isMap(reference)) return
97
- const project = reference.get('projectId', true)
98
- if (YAML.isScalar(project) && project.value === oldId) project.value = options['--project-id']
99
- },
100
- })
101
- return { file: source.file, text: String(source.document), version: source.version, relative: source.relative }
102
- })
103
- await writeFile(packagePath, JSON.stringify(manifest, null, 2) + '\n')
104
- for (const change of changes) {
105
- if (change.relative)
106
- await workspace.write({ file: change.relative, expectedVersion: change.version, text: change.text })
107
- else await writeFile(change.file, change.text)
108
- }
109
- await workspace.close()
110
- console.log(
111
- `Renamed to ${manifest.name}. Update repository metadata before publishing. Keep projectId and namespace stable after sharing.`,
112
- )
package/dist/setup.mjs DELETED
@@ -1,134 +0,0 @@
1
- #!/usr/bin/env node
2
- import { spawn, execFileSync } from 'node:child_process'
3
- import { access, mkdir, readFile, writeFile } from 'node:fs/promises'
4
- import { basename, join, resolve } from 'node:path'
5
- import { fileURLToPath } from 'node:url'
6
-
7
- export async function setup(args = process.argv.slice(2), root = process.cwd()) {
8
- root = resolve(root)
9
- const options = { offline: false }
10
- for (let i = 0; i < args.length; i++) {
11
- const arg = args[i]
12
- if (arg === '--help') {
13
- console.log('arcadia-content setup [--sdk-dir /path/to/sdk] [--offline]')
14
- return
15
- }
16
- if (arg === '--offline' && !options.offline) options.offline = true
17
- else if (arg === '--sdk-dir' && !options.sdkDir && args[i + 1] && !args[i + 1].startsWith('--'))
18
- options.sdkDir = resolve(args[++i])
19
- else throw new Error(`Unknown, duplicate or incomplete option: ${arg}`)
20
- }
21
-
22
- const pin = JSON.parse(await readFile(join(root, 'arcadia-sdk.json'), 'utf8'))
23
- if (!/^[a-f0-9]{40}$/.test(pin.revision) || !/^\d+\.\d+\.\d+$/.test(pin.pnpmVersion) || pin.sdkApi !== 2)
24
- throw new Error('Invalid SDK pin in arcadia-sdk.json')
25
- if (process.platform === 'win32' || Number(process.versions.node.split('.')[0]) !== 24)
26
- throw new Error('This development SDK currently supports Node.js 24 on Linux or macOS.')
27
-
28
- const env = {
29
- ...process.env,
30
- pnpm_config_verify_deps_before_run: 'false',
31
- ELECTRON_SKIP_BINARY_DOWNLOAD: '1',
32
- }
33
- function run(command, args, cwd = root) {
34
- return new Promise((resolve, reject) => {
35
- const child = spawn(command, args, { cwd, env, stdio: 'inherit' })
36
- child.on('error', reject)
37
- child.on('exit', code => (code === 0 ? resolve() : reject(new Error(`${command} exited with ${code}`))))
38
- })
39
- }
40
- const exists = path =>
41
- access(path).then(
42
- () => true,
43
- () => false,
44
- )
45
- const state = join(root, '.arcadia')
46
- await mkdir(state, { recursive: true })
47
- const sdkDirectory = options.sdkDir ?? join(state, `sdk-${pin.revision}`)
48
-
49
- try {
50
- if (!options.sdkDir && !(await exists(join(sdkDirectory, 'arcadia-author-sdk.json')))) {
51
- if (options.offline) throw new Error('Prepare an SDK first, or supply --sdk-dir for offline setup.')
52
- const source = join(state, `source-${pin.revision}`)
53
- if (!(await exists(source))) {
54
- await mkdir(source)
55
- await run('git', ['init', '--quiet'], source)
56
- await run('git', ['remote', 'add', 'origin', pin.repository], source)
57
- }
58
- await run('git', ['fetch', '--depth=1', 'origin', pin.revision], source)
59
- await run('git', ['checkout', '--detach', pin.revision], source)
60
- const head = execFileSync('git', ['rev-parse', 'HEAD'], {
61
- cwd: source,
62
- encoding: 'utf8',
63
- }).trim()
64
- const changes = execFileSync('git', ['status', '--porcelain'], {
65
- cwd: source,
66
- encoding: 'utf8',
67
- }).trim()
68
- if (head !== pin.revision || changes)
69
- throw new Error('The cached SDK source must match the pinned revision without local changes.')
70
- const pnpm = args => run('npx', ['--yes', `--package=pnpm@${pin.pnpmVersion}`, 'pnpm', ...args], source)
71
- await pnpm(['install', '--frozen-lockfile', '--ignore-scripts'])
72
- await pnpm(['--filter', './packages/content-dev...', '--filter', '@arcadia-eternity/protocol...', 'run', 'build'])
73
- await run(process.execPath, ['scripts/stage-author-sdk.mjs', sdkDirectory], source)
74
- }
75
- const index = JSON.parse(await readFile(join(sdkDirectory, 'arcadia-author-sdk.json'), 'utf8'))
76
- if (
77
- index.format !== 'arcadia.author-sdk-local' ||
78
- index.version !== 1 ||
79
- index.sdkApi !== pin.sdkApi ||
80
- index.build?.formatVersion !== 1 ||
81
- ![index.build.coreBuildId, index.build.registryBuildId].every(id => /^[a-f0-9]{64}$/.test(id))
82
- )
83
- throw new Error('SDK manifest format, API or build identity does not match this template.')
84
- const required = new Set(
85
- ['battle', 'const', 'interface', 'pack-loader', 'protocol', 'schema', 'content-sdk'].map(
86
- name => `@arcadia-eternity/${name}`,
87
- ),
88
- )
89
- const archives = []
90
- for (const pkg of index.packages) {
91
- if (!required.delete(pkg.name) || basename(pkg.filename) !== pkg.filename || !pkg.filename.endsWith('.tgz'))
92
- throw new Error(`Unexpected or duplicated SDK archive: ${pkg.name}`)
93
- const file = join(sdkDirectory, pkg.filename)
94
- archives.push(file)
95
- }
96
- if (required.size) throw new Error(`Missing SDK packages: ${[...required].join(', ')}`)
97
- await run('npm', [
98
- 'install',
99
- '--ignore-scripts',
100
- '--no-save',
101
- '--no-package-lock',
102
- '--no-audit',
103
- '--no-fund',
104
- ...(options.offline ? ['--offline'] : []),
105
- ...archives,
106
- ])
107
- await writeFile(
108
- join(state, 'sdk-installed.json'),
109
- JSON.stringify(
110
- {
111
- sdkApi: index.sdkApi,
112
- source: options.sdkDir ? 'provided-sdk' : pin.repository,
113
- revision: options.sdkDir ? null : pin.revision,
114
- build: index.build,
115
- },
116
- null,
117
- 2,
118
- ) + '\n',
119
- )
120
- console.log('SDK installed. Run npm test, npm run demo, or npm run pack.')
121
- } catch (error) {
122
- throw new Error(`SDK setup failed: ${error.message}`, { cause: error })
123
- }
124
- }
125
- if (
126
- process.argv[1] &&
127
- !import.meta.url.startsWith('data:') &&
128
- resolve(process.argv[1]) === fileURLToPath(import.meta.url)
129
- ) {
130
- setup().catch(error => {
131
- console.error(error.message)
132
- process.exitCode = 1
133
- })
134
- }
@@ -1,103 +0,0 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { lstat, mkdir, open, readFile, readdir, realpath, unlink } from 'node:fs/promises'
3
- import { join } from 'node:path'
4
- import { setTimeout as delay } from 'node:timers/promises'
5
- import writeFileAtomic from 'write-file-atomic'
6
-
7
- const claimName = /^([1-9][0-9]*)-([a-f0-9-]{36})\.json$/
8
- const busy = file => Object.assign(new Error('其他作者操作正在保存此项目,请稍后重试'), { code: 'SOURCE_BUSY', file })
9
- const invalid = file => Object.assign(new Error('作者保存协调目录必须是普通目录'), { code: 'PATH_INVALID', file })
10
-
11
- async function directory(root, file) {
12
- if ((await realpath(root)) !== root) throw invalid(file)
13
- let path = root
14
- for (const part of ['.arcadia', 'author-locks']) {
15
- path = join(path, part)
16
- try {
17
- await mkdir(path, { mode: 0o700 })
18
- } catch (error) {
19
- if (error.code !== 'EEXIST') throw error
20
- }
21
- const info = await lstat(path)
22
- if (!info.isDirectory() || info.isSymbolicLink()) throw invalid(file)
23
- }
24
- return path
25
- }
26
-
27
- async function claims(path, file) {
28
- const names = (await readdir(path)).filter(name => claimName.test(name))
29
- if (names.length > 1024) throw busy(file)
30
- const result = []
31
- for (const name of names) {
32
- const pid = Number(claimName.exec(name)[1])
33
- if (!Number.isSafeInteger(pid)) throw busy(file)
34
- const claim = join(path, name)
35
- try {
36
- // Each attempt has a fresh UUID. Removing a dead process's claim cannot
37
- // remove a replacement owner's claim, unlike reclaiming one shared lock.
38
- try {
39
- process.kill(pid, 0)
40
- } catch (error) {
41
- if (error.code === 'ESRCH') {
42
- await unlink(claim)
43
- continue
44
- }
45
- if (error.code !== 'EPERM') throw error
46
- }
47
- const info = await lstat(claim)
48
- if (!info.isFile() || info.isSymbolicLink() || info.size > 1024) throw invalid(file)
49
- let ticket = null
50
- try {
51
- const value = JSON.parse(await readFile(claim, 'utf8'))
52
- if (typeof value.ticket === 'string' && /^[1-9][0-9]{0,99}$/.test(value.ticket)) ticket = BigInt(value.ticket)
53
- } catch (error) {
54
- // An initial exclusive write may be visible before its bytes arrive.
55
- // Treat an incomplete live claim as choosing, never as unlocked.
56
- if (!(error instanceof SyntaxError)) throw error
57
- }
58
- result.push({ name, ticket })
59
- } catch (error) {
60
- if (error.code !== 'ENOENT') throw error
61
- }
62
- }
63
- return result
64
- }
65
-
66
- /** Serialize each source write across cooperating local author processes in this project.
67
- * One project lock also covers filename aliases on case-insensitive filesystems.
68
- * Each file still commits separately; ordinary external editors still use CAS checks.
69
- * Lamport's bakery ordering avoids stealing a live owner's lock after a timeout.
70
- * Claims live outside source revisions. PID reuse can delay recovery, never bypass a live owner.
71
- */
72
- export async function withSourceLock(root, file, action, { timeoutMs = 5000 } = {}) {
73
- const path = await directory(root, file)
74
- const name = `${process.pid}-${randomUUID()}.json`
75
- const claim = join(path, name)
76
- const deadline = Date.now() + timeoutMs
77
- const handle = await open(claim, 'wx', 0o600)
78
- try {
79
- try {
80
- await handle.writeFile(JSON.stringify({ ticket: null }))
81
- } finally {
82
- await handle.close()
83
- }
84
- const current = await claims(path, file)
85
- const ticket = current.reduce((highest, entry) => (entry.ticket > highest ? entry.ticket : highest), 0n) + 1n
86
- await writeFileAtomic(claim, JSON.stringify({ ticket: ticket.toString() }), { mode: 0o600 })
87
- for (;;) {
88
- const contenders = await claims(path, file)
89
- const blocked = contenders.some(
90
- entry =>
91
- entry.name !== name &&
92
- (entry.ticket === null || entry.ticket < ticket || (entry.ticket === ticket && entry.name < name)),
93
- )
94
- if (!blocked) return await action()
95
- if (Date.now() >= deadline) throw busy(file)
96
- await delay(20)
97
- }
98
- } finally {
99
- await unlink(claim).catch(error => {
100
- if (error.code !== 'ENOENT') throw error
101
- })
102
- }
103
- }