buckyos 0.7.177 → 0.7.180

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.
@@ -1,9 +1,20 @@
1
1
  import type { CommandContext } from '../core/context.ts'
2
2
  import type { CommandModule } from '../core/command.ts'
3
3
  import { EXIT_PERMISSION, EXIT_UNAVAILABLE, ToolError, UsageError } from '../core/errors.ts'
4
- import { AIWS_MANIFEST_FILE, AIWS_MANIFEST_VERSION, aiwsContentDigest, controlSkeleton } from 'buckyos/node'
4
+ import {
5
+ AIWS_MANIFEST_FILE,
6
+ AIWS_MANIFEST_VERSION,
7
+ aiwsContentDigest,
8
+ controlSkeleton,
9
+ } from 'buckyos/node'
5
10
  import { createDeterministicTarGz, digestFile, readTarGz, sha256Bytes } from './pikg_archive.ts'
6
- import { lintSkillPackage, readSkillDirectory, SKILL_DIRS, skillContentDigest, type SkillPackageFile } from './skill_lint.ts'
11
+ import {
12
+ lintSkillPackage,
13
+ readSkillDirectory,
14
+ SKILL_DIRS,
15
+ skillContentDigest,
16
+ type SkillPackageFile,
17
+ } from './skill_lint.ts'
7
18
  import {
8
19
  APPDOC_ENTRY,
9
20
  appDocObjectId,
@@ -18,11 +29,11 @@ import {
18
29
  EXT_TOOLS_MANIFEST_FILE,
19
30
  EXT_TOOLS_MANIFEST_SCHEMA,
20
31
  EXT_TOOLS_PLATFORMS,
32
+ type ExtToolsManifest,
21
33
  extToolsManifestErrors,
22
34
  extToolsPayloadErrors,
23
- extToolsPlatformOfKey,
24
- type ExtToolsManifest,
25
35
  type ExtToolsPayloadTree,
36
+ extToolsPlatformOfKey,
26
37
  inspectPikg,
27
38
  normalizeArch,
28
39
  PACKAGE_META_ENTRY,
@@ -32,9 +43,9 @@ import {
32
43
  parsePackageMeta,
33
44
  rejectUnknown,
34
45
  stableJsonDigest,
35
- validatePermissions,
36
46
  validateAppPresentation,
37
47
  validateContentHandlers,
48
+ validatePermissions,
38
49
  validateServiceConfigTips,
39
50
  validateSnapshot,
40
51
  validateSubpackageName,
@@ -198,7 +209,8 @@ export function createPikgModule(dependencies: PikgModuleDependencies = {}): Com
198
209
  options: [
199
210
  {
200
211
  name: 'catalog',
201
- description: 'ext-tools: a directory of other packages (<id>/ext-manifest.json) to check requires and same-named commands against',
212
+ description:
213
+ 'ext-tools: a directory of other packages (<id>/ext-manifest.json) to check requires and same-named commands against',
202
214
  type: 'string',
203
215
  },
204
216
  ],
@@ -249,7 +261,8 @@ export function createPikgModule(dependencies: PikgModuleDependencies = {}): Com
249
261
  { name: 'app-did', property: 'app_did', description: 'Explicit App DID', type: 'string' },
250
262
  {
251
263
  name: 'composite',
252
- description: 'aiws-controls: start the package with a composite control (a panel of Blocks) instead of a declarative one',
264
+ description:
265
+ 'aiws-controls: start the package with a composite control (a panel of Blocks) instead of a declarative one',
253
266
  type: 'boolean',
254
267
  },
255
268
  ],
@@ -441,12 +454,22 @@ async function doctorCommand(
441
454
  missing: missingSources,
442
455
  })
443
456
  const skills = pikg.sub_pkgs[PATH_KINDS['agent-skills'].key]
444
- if (skills?.source.type === 'path' && !missingSources.includes(resolve(metaDir, skills.source.path))) {
457
+ if (
458
+ skills?.source.type === 'path' &&
459
+ !missingSources.includes(resolve(metaDir, skills.source.path))
460
+ ) {
445
461
  checks.push(await skillLintCheck(app.name, resolve(metaDir, skills.source.path)))
446
462
  }
447
463
  if (app.categories[0] === PATH_KINDS['ext-tools'].category) {
448
464
  const catalog = optionalInputString(input, 'catalog')
449
- checks.push(...await extToolsChecks(app, pikg, metaDir, catalog ? resolveFromCwd(ctx, catalog) : undefined))
465
+ checks.push(
466
+ ...await extToolsChecks(
467
+ app,
468
+ pikg,
469
+ metaDir,
470
+ catalog ? resolveFromCwd(ctx, catalog) : undefined,
471
+ ),
472
+ )
450
473
  }
451
474
  } catch (error) {
452
475
  checks.push({
@@ -522,9 +545,15 @@ async function initCommand(
522
545
  selector = platform.selector
523
546
  sourceValue = {
524
547
  type: 'path',
525
- path: toPortablePath(relative(join(projectDir, 'dapp_meta'), join(absoluteSource, 'payload', platform.name))),
548
+ path: toPortablePath(
549
+ relative(join(projectDir, 'dapp_meta'), join(absoluteSource, 'payload', platform.name)),
550
+ ),
551
+ }
552
+ sourceSummary = {
553
+ type: 'path',
554
+ path: displaySource(projectDir, absoluteSource),
555
+ platform: platform.name,
526
556
  }
527
- sourceSummary = { type: 'path', path: displaySource(projectDir, absoluteSource), platform: platform.name }
528
557
  try {
529
558
  await getHost().lstat(join(absoluteSource, EXT_TOOLS_MANIFEST_FILE))
530
559
  } catch (error) {
@@ -631,7 +660,10 @@ const MAX_SKILL_SOURCE_BYTES = 64 * 1024 * 1024
631
660
 
632
661
  /** `pikg doctor` of an `agent_skills` source (a directory or a `.tar.gz`): the checks the Agent makes when the package is
633
662
  * installed. What makes it uninstallable fails the check; the rest are warnings. */
634
- async function skillLintCheck(packageName: string, source: string): Promise<Record<string, unknown>> {
663
+ async function skillLintCheck(
664
+ packageName: string,
665
+ source: string,
666
+ ): Promise<Record<string, unknown>> {
635
667
  const check = { name: 'skill_lint', path: source }
636
668
  let files: Map<string, SkillPackageFile>
637
669
  let ignored: string[] = []
@@ -640,13 +672,20 @@ async function skillLintCheck(packageName: string, source: string): Promise<Reco
640
672
  ;({ files, ignored } = await readSkillDirectory(source, MAX_SKILL_SOURCE_BYTES))
641
673
  } else {
642
674
  files = new Map()
643
- for (const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)) {
644
- if (SKILL_DIRS.includes(entry.path.split('/')[0])) files.set(entry.path, { bytes: entry.bytes })
645
- else ignored.push(entry.path)
675
+ for (
676
+ const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)
677
+ ) {
678
+ if (SKILL_DIRS.includes(entry.path.split('/')[0])) {
679
+ files.set(entry.path, { bytes: entry.bytes })
680
+ } else ignored.push(entry.path)
646
681
  }
647
682
  }
648
683
  } catch (error) {
649
- return { ...check, status: 'error', detail: error instanceof Error ? error.message : String(error) }
684
+ return {
685
+ ...check,
686
+ status: 'error',
687
+ detail: error instanceof Error ? error.message : String(error),
688
+ }
650
689
  }
651
690
  const { skills, findings } = lintSkillPackage(packageName, files)
652
691
  const errors = findings.filter((finding) => finding.level === 'error')
@@ -655,7 +694,13 @@ async function skillLintCheck(packageName: string, source: string): Promise<Reco
655
694
  status: errors.length ? 'error' : 'ok',
656
695
  ...(errors.length ? { detail: errors.map((finding) => finding.note).join('; '), errors } : {}),
657
696
  ...(errors.length ? {} : { digest: skillContentDigest(files) }),
658
- skills: skills.map(({ kind, name, scope, size, commands }) => ({ kind, name, scope, size, commands })),
697
+ skills: skills.map(({ kind, name, scope, size, commands }) => ({
698
+ kind,
699
+ name,
700
+ scope,
701
+ size,
702
+ commands,
703
+ })),
659
704
  warnings: findings.filter((finding) => finding.level !== 'error'),
660
705
  ...(ignored.length ? { ignored_files: ignored } : {}),
661
706
  }
@@ -690,19 +735,38 @@ async function writeSkillsSkeleton(dir: string, name: string): Promise<void> {
690
735
 
691
736
  /** A control package skeleton: one declarative control (or a composite one) under controls/<name>/ and its manifest
692
737
  * (digest included). */
693
- async function writeAiwsSkeleton(dir: string, ownerDid: string, name: string, composite: boolean): Promise<void> {
738
+ async function writeAiwsSkeleton(
739
+ dir: string,
740
+ ownerDid: string,
741
+ name: string,
742
+ composite: boolean,
743
+ ): Promise<void> {
694
744
  const kind = composite ? 'composite' : 'declarative'
695
745
  const files = controlSkeleton({ authorDid: ownerDid, name, title: name, kind })
696
746
  const encoder = new TextEncoder()
697
747
  const host = getHost()
698
748
  await host.mkdir(join(dir, 'controls', name), { recursive: true })
699
- for (const [file, text] of Object.entries(files)) await host.writeTextFile(join(dir, 'controls', name, file), text)
700
- const digest = await aiwsContentDigest(Object.entries(files).map(([file, text]) => [file, encoder.encode(text)] as [string, Uint8Array]))
749
+ for (const [file, text] of Object.entries(files)) {
750
+ await host.writeTextFile(join(dir, 'controls', name, file), text)
751
+ }
752
+ const digest = await aiwsContentDigest(
753
+ Object.entries(files).map(([file, text]) =>
754
+ [file, encoder.encode(text)] as [string, Uint8Array]
755
+ ),
756
+ )
701
757
  const manifest = {
702
758
  manifest_version: AIWS_MANIFEST_VERSION,
703
759
  purpose: 'aiws',
704
760
  host_api: composite ? {} : { declarative: 1 },
705
- controls: [{ ident: `${ownerDid}#${name}`, name, kind, version: 1, digest, dir: `controls/${name}/`, title: name }],
761
+ controls: [{
762
+ ident: `${ownerDid}#${name}`,
763
+ name,
764
+ kind,
765
+ version: 1,
766
+ digest,
767
+ dir: `controls/${name}/`,
768
+ title: name,
769
+ }],
706
770
  workspace_templates: [],
707
771
  }
708
772
  await host.writeTextFile(join(dir, AIWS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`)
@@ -710,18 +774,32 @@ async function writeAiwsSkeleton(dir: string, ownerDid: string, name: string, co
710
774
 
711
775
  function hostExtToolsPlatform(): (typeof EXT_TOOLS_PLATFORMS)[number] {
712
776
  const host = getHost()
713
- const os = host.platform === 'darwin' ? 'macos' : host.platform === 'win32' ? 'windows' : host.platform
777
+ const os = host.platform === 'darwin'
778
+ ? 'macos'
779
+ : host.platform === 'win32'
780
+ ? 'windows'
781
+ : host.platform
714
782
  const arch = normalizeArch(host.arch)
715
- const platform = EXT_TOOLS_PLATFORMS.find((known) => known.selector.os === os && known.selector.arch === arch)
783
+ const platform = EXT_TOOLS_PLATFORMS.find((known) =>
784
+ known.selector.os === os && known.selector.arch === arch
785
+ )
716
786
  if (!platform) {
717
- throw new UsageError('UNSUPPORTED_PLATFORM', `extension packages have no payload for ${os}/${arch}`)
787
+ throw new UsageError(
788
+ 'UNSUPPORTED_PLATFORM',
789
+ `extension packages have no payload for ${os}/${arch}`,
790
+ )
718
791
  }
719
792
  return platform
720
793
  }
721
794
 
722
795
  /** An extension package skeleton for this machine's platform: `ext-manifest.json` and one command that runs and has a
723
796
  * smoke script, so the package builds from the first minute. Other platforms are added beside it. */
724
- async function writeExtToolsSkeleton(dir: string, id: string, version: string, platform: string): Promise<void> {
797
+ async function writeExtToolsSkeleton(
798
+ dir: string,
799
+ id: string,
800
+ version: string,
801
+ platform: string,
802
+ ): Promise<void> {
725
803
  const host = getHost()
726
804
  const manifest = {
727
805
  schema: EXT_TOOLS_MANIFEST_SCHEMA,
@@ -736,7 +814,9 @@ async function writeExtToolsSkeleton(dir: string, id: string, version: string, p
736
814
  }
737
815
  const text = `${JSON.stringify(manifest, null, 2)}\n`
738
816
  const payload = join(dir, 'payload', platform)
739
- for (const sub of ['bin', 'smoke', join('store', id)]) await host.mkdir(join(payload, sub), { recursive: true })
817
+ for (const sub of ['bin', 'smoke', join('store', id)]) {
818
+ await host.mkdir(join(payload, sub), { recursive: true })
819
+ }
740
820
  await host.writeTextFile(join(dir, EXT_TOOLS_MANIFEST_FILE), text)
741
821
  await host.writeTextFile(join(payload, EXT_TOOLS_MANIFEST_FILE), text)
742
822
  const windows = platform.startsWith('windows-')
@@ -754,7 +834,9 @@ async function writeExtToolsSkeleton(dir: string, id: string, version: string, p
754
834
  )
755
835
  }
756
836
 
757
- async function readExtToolsManifestFile(path: string): Promise<{ text: string; manifest?: ExtToolsManifest; errors: string[] }> {
837
+ async function readExtToolsManifestFile(
838
+ path: string,
839
+ ): Promise<{ text: string; manifest?: ExtToolsManifest; errors: string[] }> {
758
840
  let text: string
759
841
  try {
760
842
  text = await getHost().readTextFile(path)
@@ -777,9 +859,15 @@ async function readExtToolsManifestFile(path: string): Promise<{ text: string; m
777
859
  }
778
860
 
779
861
  /** A payload directory as `pikg build` would archive it: symlinks read through, and refused when they leave the tree. */
780
- async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPayloadTree; errors: string[] }> {
862
+ async function readExtToolsPayloadTree(
863
+ root: string,
864
+ ): Promise<{ tree: ExtToolsPayloadTree; errors: string[] }> {
781
865
  const host = getHost()
782
- const tree: ExtToolsPayloadTree = { files: new Map(), directories: new Set(), launchers: new Map() }
866
+ const tree: ExtToolsPayloadTree = {
867
+ files: new Map(),
868
+ directories: new Set(),
869
+ launchers: new Map(),
870
+ }
783
871
  const errors: string[] = []
784
872
  const realRoot = await host.realPath(root)
785
873
  const walk = async (directory: string, prefix: string): Promise<void> => {
@@ -793,7 +881,11 @@ async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPa
793
881
  try {
794
882
  physical = await host.realPath(path)
795
883
  } catch (error) {
796
- errors.push(`${archivePath}: ${isHostError(error, 'NotFound') ? 'a dangling symlink' : 'a symlink out of the payload'}`)
884
+ errors.push(
885
+ `${archivePath}: ${
886
+ isHostError(error, 'NotFound') ? 'a dangling symlink' : 'a symlink out of the payload'
887
+ }`,
888
+ )
797
889
  continue
798
890
  }
799
891
  const inside = relative(realRoot, physical)
@@ -822,7 +914,12 @@ async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPa
822
914
 
823
915
  /** `pikg doctor` of an extension package: the manifest against the App, every platform's payload, and, given a catalog
824
916
  * of the other packages, `requires` and same-named commands. */
825
- async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, catalogDir: string | undefined): Promise<Array<Record<string, unknown>>> {
917
+ async function extToolsChecks(
918
+ app: AppMeta,
919
+ pikg: PikgMeta,
920
+ metaDir: string,
921
+ catalogDir: string | undefined,
922
+ ): Promise<Array<Record<string, unknown>>> {
826
923
  const checks: Array<Record<string, unknown>> = []
827
924
  const platforms = new Map<string, string>()
828
925
  const stray: string[] = []
@@ -839,15 +936,27 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
839
936
  const source = sources.length > 0 ? dirname(dirname(sources[0])) : dirname(metaDir)
840
937
  const master = await readExtToolsManifestFile(join(source, EXT_TOOLS_MANIFEST_FILE))
841
938
  const manifestErrors = [...master.errors]
842
- if (stray.length > 0) manifestErrors.push(`sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(', ')}`)
939
+ if (stray.length > 0) {
940
+ manifestErrors.push(
941
+ `sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(', ')}`,
942
+ )
943
+ }
843
944
  const manifest = master.manifest
844
945
  if (manifest) {
845
- if (manifest.id !== app.name) manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`)
846
- if (manifest.version !== app.version) manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`)
946
+ if (manifest.id !== app.name) {
947
+ manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`)
948
+ }
949
+ if (manifest.version !== app.version) {
950
+ manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`)
951
+ }
847
952
  const without = manifest.platforms.filter((name) => !platforms.has(name))
848
- if (without.length > 0) manifestErrors.push(`platforms without a sub package: ${without.join(', ')}`)
953
+ if (without.length > 0) {
954
+ manifestErrors.push(`platforms without a sub package: ${without.join(', ')}`)
955
+ }
849
956
  const unlisted = [...platforms.keys()].filter((name) => !manifest.platforms.includes(name))
850
- if (unlisted.length > 0) manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(', ')}`)
957
+ if (unlisted.length > 0) {
958
+ manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(', ')}`)
959
+ }
851
960
  }
852
961
  checks.push({
853
962
  name: 'ext_tools_manifest',
@@ -862,8 +971,11 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
862
971
  const { tree, errors: walkErrors } = await readExtToolsPayloadTree(dir)
863
972
  errors.push(...walkErrors)
864
973
  const copy = await readExtToolsManifestFile(join(dir, EXT_TOOLS_MANIFEST_FILE))
865
- if (copy.errors.length > 0) errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join('; ')}`)
866
- else if (copy.text !== master.text) errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`)
974
+ if (copy.errors.length > 0) {
975
+ errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join('; ')}`)
976
+ } else if (copy.text !== master.text) {
977
+ errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`)
978
+ }
867
979
  errors.push(...extToolsPayloadErrors(manifest, platform, tree, [source, metaDir]))
868
980
  } catch (error) {
869
981
  if (!isHostError(error, 'NotFound')) throw error
@@ -889,10 +1001,14 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
889
1001
  const catalogErrors: string[] = []
890
1002
  for (const entry of await getHost().readDir(catalogDir)) {
891
1003
  if (entry.isFile) continue
892
- const candidate = await readExtToolsManifestFile(join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE))
1004
+ const candidate = await readExtToolsManifestFile(
1005
+ join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE),
1006
+ )
893
1007
  if (candidate.errors.includes('not found')) continue
894
1008
  if (!candidate.manifest) catalogErrors.push(`${entry.name}: ${candidate.errors.join('; ')}`)
895
- else if (candidate.manifest.id !== manifest.id) others.set(candidate.manifest.id, candidate.manifest)
1009
+ else if (candidate.manifest.id !== manifest.id) {
1010
+ others.set(candidate.manifest.id, candidate.manifest)
1011
+ }
896
1012
  }
897
1013
  for (const required of manifest.requires) {
898
1014
  if (!others.has(required.id)) catalogErrors.push(`requires ${required.id}: not in the catalog`)
@@ -900,8 +1016,16 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
900
1016
  const commands = new Set(manifest.provides.map((provided) => provided.command))
901
1017
  for (const other of others.values()) {
902
1018
  if (manifest.conflicts.includes(other.id) || other.conflicts.includes(manifest.id)) continue
903
- const shared = other.provides.map((provided) => provided.command).filter((command) => commands.has(command))
904
- if (shared.length > 0) catalogErrors.push(`${other.id} also provides ${shared.join(', ')}: one of the two must list the other in conflicts`)
1019
+ const shared = other.provides.map((provided) => provided.command).filter((command) =>
1020
+ commands.has(command)
1021
+ )
1022
+ if (shared.length > 0) {
1023
+ catalogErrors.push(
1024
+ `${other.id} also provides ${
1025
+ shared.join(', ')
1026
+ }: one of the two must list the other in conflicts`,
1027
+ )
1028
+ }
905
1029
  }
906
1030
  checks.push({
907
1031
  name: 'ext_tools_catalog',
@@ -1305,7 +1429,11 @@ function parseAppMeta(value: Record<string, unknown>): AppMeta {
1305
1429
  }),
1306
1430
  categories: categories as string[],
1307
1431
  permissions,
1308
- ...(value.content_handlers === undefined ? {} : { content_handlers: developmentValidation(() => validateContentHandlers(value.content_handlers, permissions)) }),
1432
+ ...(value.content_handlers === undefined ? {} : {
1433
+ content_handlers: developmentValidation(() =>
1434
+ validateContentHandlers(value.content_handlers, permissions)
1435
+ ),
1436
+ }),
1309
1437
  selector_type: developmentString(value.selector_type, 'app.json.selector_type'),
1310
1438
  service_config_tips: serviceConfig,
1311
1439
  }
@@ -1560,17 +1688,31 @@ function assertSafeCleanTarget(
1560
1688
  }
1561
1689
  }
1562
1690
 
1563
- async function replaceDirectory(temporary: string, destination: string): Promise<void> {
1564
- let exists = false
1691
+ async function pathExists(path: string): Promise<boolean> {
1565
1692
  try {
1566
- await getHost().lstat(destination)
1567
- exists = true
1693
+ await getHost().lstat(path)
1694
+ return true
1568
1695
  } catch (error) {
1569
- if (!isHostError(error, 'NotFound')) throw error
1696
+ if (isHostError(error, 'NotFound')) return false
1697
+ throw error
1570
1698
  }
1571
- if (!exists) {
1572
- await getHost().rename(temporary, destination)
1573
- return
1699
+ }
1700
+
1701
+ async function replaceDirectory(temporary: string, destination: string): Promise<void> {
1702
+ if (!(await pathExists(destination))) {
1703
+ try {
1704
+ await getHost().rename(temporary, destination)
1705
+ return
1706
+ } catch (error) {
1707
+ // Windows reports EPERM, not EEXIST, when the destination directory is
1708
+ // already there. Fall through and replace it when that is the case.
1709
+ if (
1710
+ getHost().platform !== 'windows' || !isHostError(error, 'PermissionDenied') ||
1711
+ !(await pathExists(destination))
1712
+ ) {
1713
+ throw error
1714
+ }
1715
+ }
1574
1716
  }
1575
1717
  const backup = `${destination}.previous-${crypto.randomUUID()}`
1576
1718
  await getHost().rename(destination, backup)
@@ -0,0 +1,26 @@
1
+ // Windows MoveFileEx returns EPERM or EBUSY while a scanner still has a new
2
+ // file open, and also when a directory rename lands on an existing directory.
3
+ // A short retry covers the transient lock. The caller decides when to stop.
4
+ export async function retryWindowsLock<T>(
5
+ windows: boolean,
6
+ operation: () => Promise<T>,
7
+ retryable: (error: unknown) => boolean,
8
+ wait: (attempt: number) => number = defaultWait,
9
+ ): Promise<T> {
10
+ let attempt = 0
11
+ while (true) {
12
+ try {
13
+ return await operation()
14
+ } catch (error) {
15
+ const delay = windows && retryable(error) ? wait(attempt) : 0
16
+ if (delay <= 0) throw error
17
+ attempt++
18
+ await new Promise((resolve) => setTimeout(resolve, delay))
19
+ }
20
+ }
21
+ }
22
+
23
+ function defaultWait(attempt: number): number {
24
+ const waits = [50, 100, 150, 250, 400, 600, 800]
25
+ return waits[attempt] ?? 0
26
+ }
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url'
7
7
  import { Readable, Writable } from 'node:stream'
8
8
  import { pipeline } from 'node:stream/promises'
9
9
  import { constants as zlibConstants, createGzip } from 'node:zlib'
10
+ import { retryWindowsLock } from './fs_retry.ts'
10
11
  import { assertPathAccess } from './path_policy.ts'
11
12
  import {
12
13
  type DistributionPolicy,
@@ -173,7 +174,11 @@ export class DenoHost implements ToolHost {
173
174
  await this.assertPath(from, 'write')
174
175
  await this.assertPath(to, 'write', false)
175
176
  try {
176
- await Deno.rename(from, to)
177
+ await retryWindowsLock(
178
+ this.platform === 'windows',
179
+ () => Deno.rename(from, to),
180
+ denoSharingViolation,
181
+ )
177
182
  } catch (error) {
178
183
  throw translateDenoError(error, `${from} -> ${to}`)
179
184
  }
@@ -182,7 +187,11 @@ export class DenoHost implements ToolHost {
182
187
  async remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
183
188
  await this.assertPath(path, 'write', false)
184
189
  try {
185
- await Deno.remove(path, options)
190
+ await retryWindowsLock(
191
+ this.platform === 'windows',
192
+ () => Deno.remove(path, options),
193
+ denoSharingViolation,
194
+ )
186
195
  } catch (error) {
187
196
  throw translateDenoError(error, path)
188
197
  }
@@ -479,6 +488,12 @@ function fileInfo(value: Deno.FileInfo): HostFileInfo {
479
488
  }
480
489
  }
481
490
 
491
+ function denoSharingViolation(error: unknown): boolean {
492
+ if (error instanceof Deno.errors.PermissionDenied) return true
493
+ const busy = (Deno.errors as { Busy?: new (...args: never[]) => Error }).Busy
494
+ return typeof busy === 'function' && error instanceof busy
495
+ }
496
+
482
497
  function translateDenoError(error: unknown, path?: string): HostError {
483
498
  if (error instanceof HostError) return error
484
499
  const kind = error instanceof Deno.errors.NotFound
@@ -24,6 +24,7 @@ import { createInterface } from 'node:readline/promises'
24
24
  import { Readable } from 'node:stream'
25
25
  import { pipeline } from 'node:stream/promises'
26
26
  import { constants as zlibConstants, createGzip } from 'node:zlib'
27
+ import { retryWindowsLock } from './fs_retry.ts'
27
28
  import { assertPathAccess } from './path_policy.ts'
28
29
  import {
29
30
  type DistributionPolicy,
@@ -185,7 +186,11 @@ export class NodeHost implements ToolHost {
185
186
  await this.assertPath(from, 'write')
186
187
  await this.assertPath(to, 'write')
187
188
  try {
188
- await rename(from, to)
189
+ await retryWindowsLock(
190
+ this.platform === 'windows',
191
+ () => rename(from, to),
192
+ nodeSharingViolation,
193
+ )
189
194
  } catch (error) {
190
195
  throw translateNodeError(error, `${from} -> ${to}`)
191
196
  }
@@ -194,7 +199,11 @@ export class NodeHost implements ToolHost {
194
199
  async remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
195
200
  await this.assertPath(path, 'write', false)
196
201
  try {
197
- await rm(path, { recursive: options.recursive ?? false })
202
+ await retryWindowsLock(
203
+ this.platform === 'windows',
204
+ () => rm(path, { recursive: options.recursive ?? false }),
205
+ nodeSharingViolation,
206
+ )
198
207
  } catch (error) {
199
208
  throw translateNodeError(error, path)
200
209
  }
@@ -574,6 +583,11 @@ async function readInputChunk(): Promise<Uint8Array | null> {
574
583
  })
575
584
  }
576
585
 
586
+ function nodeSharingViolation(error: unknown): boolean {
587
+ const code = (error as { code?: string }).code
588
+ return code === 'EPERM' || code === 'EACCES' || code === 'EBUSY'
589
+ }
590
+
577
591
  function translateNodeError(error: unknown, path?: string): HostError {
578
592
  if (error instanceof HostError) return error
579
593
  const code = (error as { code?: string }).code
package/cli/version.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Generated by scripts/generate-cli-version.mjs. Do not edit.
2
- export const PACKAGE_VERSION = '0.7.177'
2
+ export const PACKAGE_VERSION = '0.7.180'
3
3
  export const TOOL_VERSION = PACKAGE_VERSION
4
4
  export const SDK_VERSION = PACKAGE_VERSION
5
5
  export const PROTOCOL_VERSION = '1'
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./content.cjs");require("./content_mime-dc80d960.js");const t=t=>e.SYSTEM_DIALOG_ERROR_CODES.includes(t)?t:"protocol",i=(e,t,i={})=>({protocol:"buckyos.app-frame",version:1,type:e,payload:t,...i}),o=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"buckyos.app-frame"===t.protocol&&1===t.version&&"string"==typeof t.type&&!!t.payload&&"object"==typeof t.payload};const n="buckyos.preview-embed",s=(e,t,i=n)=>({protocol:i,version:1,type:e,payload:t}),r=(e,t=n)=>{const i=e;return!!i&&i.protocol===t&&1===i.version&&"string"==typeof i.type&&!!i.payload&&"object"==typeof i.payload},a="/embed/preview";const l="buckyos.sysdlg-embed",d="/embed/sysdlg/select";let c=!1;function p(i,o,n={}){var a,p;if(null==(a=n.signal)?void 0:a.aborted)return Promise.reject(new e.SystemDialogError("closed"));if(c)return Promise.reject(new e.SystemDialogError("busy"));c=!0;const h=new URL(i).origin,u=n.locale??navigator.language??"en",m=n.theme??((null==(p=window.matchMedia)?void 0:p.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"),g=u.toLowerCase().startsWith("zh");return new Promise(((i,a)=>{var p;const y=document.body,f=document.documentElement,w=document.activeElement instanceof HTMLElement?document.activeElement:null,b={x:window.scrollX,y:window.scrollY},v={body:y.getAttribute("style"),html:f.getAttribute("style")},E=Array.from(y.children).filter((e=>e instanceof HTMLElement)).map((e=>({el:e,inert:e.inert,hidden:e.getAttribute("aria-hidden")}))),T=document.createElement("div");let L;T.setAttribute("data-buckyos-sysdlg","select"),T.setAttribute("role","dialog"),T.setAttribute("aria-modal","true"),T.setAttribute("aria-label",g?"文件选择器":"File picker"),T.style.cssText="position:fixed;inset:0;height:100vh;height:100dvh;z-index:2147483647;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center";let k,x="",C=!1;const O=e=>{T.contains(e.target)||(e.stopPropagation(),e.preventDefault())},A=["keydown","pointerdown","mousedown","touchstart","wheel"],S=()=>{var e;return!C&&(C=!0,c=!1,clearTimeout(k),window.removeEventListener("message",M),null==(e=n.signal)||e.removeEventListener("abort",R),"inert"in HTMLElement.prototype||A.forEach((e=>document.removeEventListener(e,O,!0))),T.remove(),E.forEach((({el:e,inert:t,hidden:i})=>{e.inert=t,null===i?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",i)})),null===v.body?y.removeAttribute("style"):y.setAttribute("style",v.body),null===v.html?f.removeAttribute("style"):f.setAttribute("style",v.html),window.scrollTo(b.x,b.y),null==w||w.focus({preventScroll:!0}),!0)},D=t=>{S()&&a(new e.SystemDialogError(t))},R=()=>D("closed"),I=()=>{null==L||L.remove(),L=void 0;const e=document.createElement("div");e.setAttribute("role","alert"),e.style.cssText=`max-width:22rem;margin:1rem;padding:1.25rem;border-radius:16px;font:14px/1.6 system-ui,sans-serif;background:${"dark"===m?"#1f2329":"#fff"};color:${"dark"===m?"#f2f3f5":"#1f2329"};box-shadow:0 24px 64px rgba(0,0,0,.24)`;const t=document.createElement("p");t.style.margin="0 0 1rem",t.textContent=g?"无法加载文件选择器":"Unable to load the file picker";const i=document.createElement("div");i.style.cssText="display:flex;gap:.5rem;justify-content:flex-end";const o=(e,t)=>{const o=document.createElement("button");return o.type="button",o.textContent=e,o.style.cssText="min-height:2.25rem;padding:0 1rem;font:inherit;border-radius:999px;border:1px solid currentColor;background:transparent;color:inherit;cursor:pointer",o.addEventListener("click",t),i.append(o),o};o(g?"取消":"Cancel",(()=>D("load_failed")));const n=o(g?"重试":"Retry",(()=>{e.remove(),U()}));e.append(t,i),T.append(e),n.focus()},U=()=>{x=crypto.randomUUID(),L=document.createElement("iframe"),L.title=g?"文件选择器":"File picker",L.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;color-scheme:normal",L.setAttribute("allowtransparency","true"),L.addEventListener("error",I),L.src=`${h}${d}#bse=${x}&po=${encodeURIComponent(window.location.origin)}`,T.append(L),k=setTimeout(I,1e4)},M=n=>{var a;if(!L||n.origin!==h||n.source!==L.contentWindow||!r(n.data,l))return;const{type:d,payload:c}=n.data;if("embed.hello"===d){if(c.nonce!==x)return;clearTimeout(k),null==(a=L.contentWindow)||a.postMessage(s("embed.init",{nonce:x,params:o,theme:m,locale:u},l),h),L.focus()}if("embed.error"===d&&D(t(c.code)),"embed.result"===d){const t=e.readSelectDialogResult(c.result,{allowLocal:!0===o.allowLocal});t?(e=>{S()&&i(e)})(t):D("protocol")}};window.addEventListener("message",M),null==(p=n.signal)||p.addEventListener("abort",R,{once:!0}),"inert"in HTMLElement.prototype?E.forEach((({el:e})=>{e.inert=!0})):(E.forEach((({el:e})=>e.setAttribute("aria-hidden","true"))),A.forEach((e=>document.addEventListener(e,O,!0)))),f.style.overflow="hidden",y.style.position="fixed",y.style.top=-b.y+"px",y.style.left=-b.x+"px",y.style.right="0",y.style.overflow="hidden",y.append(T),U()}))}exports.AppFrameClient=class{constructor(e){if(this.options=e,this.listener=e=>{this.receive(e)},this.dialogs=new Map,this.origin=new URL(e.shellOrigin).origin,this.nonce=new URLSearchParams(window.location.hash.slice(1)).get("bfp"),window.addEventListener("message",this.listener),window.parent!==window&&this.nonce){const t=()=>window.parent.postMessage(i("frame.hello",{nonce:this.nonce,appCapabilities:[...e.onOpen?["open"]:[],...e.onBeforeClose?["beforeClose"]:[],...e.onBack?["back"]:[]]}),this.origin);t(),this.helloTimer=setInterval(t,250),this.helloDeadline=setTimeout((()=>clearInterval(this.helloTimer)),1500)}}async receive(n){var s,r,a,l,d,c,p,h,u,m,g,y,f,w;if(n.source!==window.parent||n.origin!==this.origin||!o(n.data))return;const b=n.data,v=b.payload;if("frame.init"===b.type){if(!this.nonce||v.nonce!==this.nonce||"string"!=typeof v.locale||!v.theme||"string"!=typeof v.windowId||v.launch&&!e.isOpenRequest(v.launch))return;return clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),this.init=v,this.title=void 0,this.focused=void 0,void(null==(r=(s=this.options).onInit)||r.call(s,this.init))}if(!this.init)return;if("sysdlg.openResult"===b.type){const i=b.replyTo?this.dialogs.get(b.replyTo):void 0;if(!i)return;if(this.dialogs.delete(b.replyTo),!0!==v.ok)return i.reject(new e.SystemDialogError(t(v.code)));const o=e.readSelectDialogResult(v.result,{allowLocal:i.allowLocal});return void(o?i.resolve(o):i.reject(new e.SystemDialogError("protocol")))}const E=e=>window.parent.postMessage(i(b.type+"Result",e,{replyTo:b.id}),this.origin);try{"frame.open"===b.type&&e.isOpenRequest(v.request)&&E(await(null==(l=(a=this.options).onOpen)?void 0:l.call(a,v.request))??{accepted:!1}),"frame.beforeClose"===b.type&&E({decision:await(null==(c=(d=this.options).onBeforeClose)?void 0:c.call(d,v.reason))??"allow"}),"frame.back"===b.type&&E({handled:await(null==(h=(p=this.options).onBack)?void 0:h.call(p))??!1}),"frame.themeChanged"!==b.type||"dark"!==v.mode&&"light"!==v.mode||null==(m=(u=this.options).onTheme)||m.call(u,v),"frame.localeChanged"===b.type&&"string"==typeof v.locale&&(null==(y=(g=this.options).onLocale)||y.call(g,v.locale)),"frame.focusChanged"===b.type&&this.focused!==(!0===v.focused)&&(this.focused=!0===v.focused,null==(w=(f=this.options).onFocus)||w.call(f,this.focused))}catch{"frame.open"===b.type&&E({accepted:!1,fallback:"preview"}),"frame.beforeClose"===b.type&&E({decision:"deny"})}}send(e,t){this.init&&window.parent.postMessage(i(e,t),this.origin)}setTitle(e,t=!1){const i=JSON.stringify([e,t]);this.init&&i!==this.title&&(this.title=i,this.send("window.setTitle",{title:e,dirty:t}))}requestClose(){this.send("window.requestClose",{})}openContent(t,i="default",o={}){const n=o.hints??{};return this.init?(this.send("content.open",{request:t,target:i,newWindow:!0===o.newWindow,hints:n}),!0):!!this.options.systemOrigin&&(window.open(e.systemOpenUrl(this.options.systemOrigin,{request:t,target:i,hints:n,from:this.options.appId}),"_blank","noopener"),!0)}selectContent(t={},o={}){var n,s;if(this.init){if(!this.init.shellCapabilities.includes(e.SELECT_DIALOG_PATH))return Promise.reject(new e.SystemDialogError("unsupported"));if(this.dialogs.size)return Promise.reject(new e.SystemDialogError("busy"));const o=crypto.randomUUID();return new Promise(((n,s)=>{this.dialogs.set(o,{resolve:n,reject:s,allowLocal:!0===t.allowLocal}),window.parent.postMessage(i("sysdlg.open",{path:e.SELECT_DIALOG_PATH,params:t},{id:o}),this.origin)}))}if(!this.options.systemOrigin)return Promise.reject(new e.SystemDialogError("unsupported"));const r=this.embedAbort=new AbortController;return null==(n=o.signal)||n.addEventListener("abort",(()=>r.abort()),{once:!0}),(null==(s=o.signal)?void 0:s.aborted)&&r.abort(),p(this.options.systemOrigin,t,{...o,signal:r.signal})}dispose(){var t;clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),window.removeEventListener("message",this.listener),this.dialogs.forEach((t=>t.reject(new e.SystemDialogError("closed")))),this.dialogs.clear(),null==(t=this.embedAbort)||t.abort()}},exports.AppFrameHost=class{constructor(e){this.options=e,this.ready=!1,this.capabilities=[],this.pending=new Map,this.listener=e=>this.receive(e),this.opens=[],this.dialogOpen=!1,window.addEventListener("message",this.listener)}async systemDialog(t,o,n){const s=e=>{var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i("sysdlg.openResult",e,{replyTo:t}),this.options.origin))};if(!this.options.onSystemDialog||"string"!=typeof o)return s({ok:!1,code:"unsupported"});if(this.dialogOpen)return s({ok:!1,code:"busy"});this.dialogOpen=!0;try{s(await this.options.onSystemDialog(o,n))}catch(r){s({ok:!1,code:r instanceof e.SystemDialogError?r.code:"closed"})}finally{this.dialogOpen=!1}}receive(t){var i,n,s,r,a,l,d,c;if(t.source!==this.options.target()||t.origin!==this.options.origin||!o(t.data))return;const p=t.data,h=p.payload;if("frame.hello"===p.type){if(h.nonce!==this.options.init.nonce||!Array.isArray(h.appCapabilities))return;return this.ready=!0,this.capabilities=h.appCapabilities.filter((e=>"string"==typeof e)),this.send("frame.init",this.options.init),void 0!==this.focused&&this.send("frame.focusChanged",{focused:this.focused}),void(null==(n=(i=this.options).onReady)||n.call(i))}if(this.ready)if(p.replyTo){const e=this.pending.get(p.replyTo);e&&p.type===e.type+"Result"&&(clearTimeout(e.timer),this.pending.delete(p.replyTo),e.resolve(p.payload))}else if("window.setTitle"===p.type&&"string"==typeof h.title&&(null==(r=(s=this.options).onTitle)||r.call(s,h.title.slice(0,256),!0===h.dirty)),"window.requestClose"===p.type&&(null==(l=(a=this.options).onRequestClose)||l.call(a)),"sysdlg.open"===p.type&&"string"==typeof p.id&&this.systemDialog(p.id,h.path,h.params),"content.open"===p.type&&("default"===h.target||"preview"===h.target||"chooser"===h.target)){const t={...h.request,requestId:crypto.randomUUID()};if(!e.isOpenRequest(t))return;if(this.opens=this.opens.filter((e=>e>Date.now()-1e4)),this.opens.length>=5)return;this.opens.push(Date.now()),null==(c=(d=this.options).onContentOpen)||c.call(d,t,h.target,{newWindow:!0===h.newWindow,hints:e.readContentHints(h.hints)})}}update(e){this.options.init={...this.options.init,...e}}setFocused(e){this.focused!==e&&(this.focused=e,this.send("frame.focusChanged",{focused:e}))}send(e,t){var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i(e,t),this.options.origin))}request(e,t,o=3e3){if(!this.ready)return Promise.reject(new Error("App frame is not ready"));const n=crypto.randomUUID();return new Promise(((s,r)=>{var a;const l=setTimeout((()=>{this.pending.delete(n),r(new Error("App frame timed out"))}),o);this.pending.set(n,{resolve:s,reject:r,timer:l,type:e}),null==(a=this.options.target())||a.postMessage(i(e,t,{id:n}),this.options.origin)}))}async open(e){return this.capabilities.includes("open")?await this.request("frame.open",{request:e}):{accepted:!1}}async beforeClose(e="user"){if(!this.ready||!this.capabilities.includes("beforeClose"))return"allow";const t=await this.request("frame.beforeClose",{reason:e});return"allow"===t.decision||"pending"===t.decision?t.decision:"deny"}async back(){return!!this.capabilities.includes("back")&&!0===(await this.request("frame.back",{})).handled}dispose(){window.removeEventListener("message",this.listener),this.pending.forEach((e=>{clearTimeout(e.timer),e.reject(new Error("App frame disposed"))})),this.pending.clear(),this.ready=!1}},exports.PREVIEW_EMBED_PATH=a,exports.PreviewEmbed=class{constructor(e){this.options=e,this.nonce=crypto.randomUUID(),this.listener=e=>this.receive(e),this.origin=new URL(e.systemOrigin).origin,this.init=e.init,this.url=`${this.origin}${a}#bpe=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`,window.addEventListener("message",this.listener)}post(e,t){var i,o;null==(o=null==(i=this.options.frame())?void 0:i.contentWindow)||o.postMessage(s(e,t),this.origin)}receive(t){var i,o,n,s,a,l,d;if(t.origin!==this.origin||t.source!==(null==(i=this.options.frame())?void 0:i.contentWindow)||!r(t.data))return;const{type:c,payload:p}=t.data;if("embed.hello"!==c){if("embed.state"===c&&("loading"===p.status||"ready"===p.status||"error"===p.status)){const e=p.error;null==(n=(o=this.options).onState)||n.call(o,{status:p.status,error:e&&"string"==typeof e.kind&&"string"==typeof e.code?{kind:e.kind,code:e.code}:void 0,title:"string"==typeof p.title?p.title.slice(0,256):void 0,mediaType:"string"==typeof p.mediaType?p.mediaType.slice(0,128):void 0})}if("embed.openWith"===c){const t=p.request;t&&e.isTransferableRef(t.source)&&(void 0===t.session||e.isTransferableSession(t.session))&&(null==(a=(s=this.options).onOpenWith)||a.call(s,{request:{source:t.source,session:t.session},hints:e.readContentHints(p.hints)}))}"embed.exit"===c&&(null==(d=(l=this.options).onExit)||d.call(l))}else p.nonce===this.nonce&&this.post("embed.init",{...this.init,nonce:this.nonce})}update(e){this.init={...this.init,...e},this.post("embed.update",e)}dispose(){window.removeEventListener("message",this.listener)}},exports.PreviewEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bpe");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce}),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(t){var i,o;if(t.source!==window.parent||t.origin!==this.parentOrigin||!r(t.data))return;const{type:n,payload:s}=t.data;if("embed.init"===n){if(s.nonce!==this.nonce||(a=s.source,!(e.isTransferableRef(a)||a&&"object"==typeof a&&"blob"===a.kind&&"undefined"!=typeof Blob&&a.blob instanceof Blob&&"string"==typeof a.name))||void 0!==s.session&&!e.isTransferableSession(s.session)||"string"!=typeof s.locale)return;return this.ready=!0,clearInterval(this.hello),void this.options.onInit({nonce:String(s.nonce),source:s.source,session:s.session,theme:"dark"===s.theme?"dark":"light",locale:s.locale})}var a;if("embed.update"===n&&this.ready){const e={};"dark"!==s.theme&&"light"!==s.theme||(e.theme=s.theme),"string"==typeof s.locale&&(e.locale=s.locale),null==(o=(i=this.options).onUpdate)||o.call(i,e)}}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t),this.parentOrigin)}state(e){this.post("embed.state",e)}openWith(e){this.post("embed.openWith",e)}exit(){this.post("embed.exit",{})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.SELECT_EMBED_PATH=d,exports.SelectEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bse");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce},l),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(e){if(e.source!==window.parent||e.origin!==this.parentOrigin||!r(e.data,l))return;const{type:t,payload:i}=e.data;"embed.init"!==t||this.ready||i.nonce!==this.nonce||"string"!=typeof i.locale||(this.ready=!0,clearInterval(this.hello),this.options.onInit({nonce:String(i.nonce),params:i.params,theme:"dark"===i.theme?"dark":"light",locale:i.locale}))}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t,l),this.parentOrigin)}result(e){this.post("embed.result",{result:e})}error(e){this.post("embed.error",{code:e})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.embedderOrigin=function(e){var t;if(window.parent===window)return null;const i=[null==(t=window.location.ancestorOrigins)?void 0:t[0],document.referrer];for(const o of i)if(o)try{const t=new URL(o).origin;if(e(t))return t}catch{}return null},exports.openSelectEmbed=p,exports.originInZone=(e,t)=>{try{const i=new URL(e);return i.protocol===window.location.protocol&&(i.hostname===t||i.hostname.endsWith(`.${t}`))}catch{return!1}};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./content.cjs");require("./content_mime-dc80d960.js");const t=t=>e.SYSTEM_DIALOG_ERROR_CODES.includes(t)?t:"protocol",i=(e,t,i={})=>({protocol:"buckyos.app-frame",version:1,type:e,payload:t,...i}),o=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"buckyos.app-frame"===t.protocol&&1===t.version&&"string"==typeof t.type&&!!t.payload&&"object"==typeof t.payload};const n="buckyos.preview-embed",s=(e,t,i=n)=>({protocol:i,version:1,type:e,payload:t}),r=(e,t=n)=>{const i=e;return!!i&&i.protocol===t&&1===i.version&&"string"==typeof i.type&&!!i.payload&&"object"==typeof i.payload},a="/embed/preview";const l="buckyos.sysdlg-embed",d="/embed/sysdlg/select";let c=!1;function p(i,o,n={}){var a,p;if(null==(a=n.signal)?void 0:a.aborted)return Promise.reject(new e.SystemDialogError("closed"));if(c)return Promise.reject(new e.SystemDialogError("busy"));c=!0;const h=new URL(i).origin,u=n.locale??navigator.language??"en",m=n.theme??((null==(p=window.matchMedia)?void 0:p.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"),g=u.toLowerCase().startsWith("zh");return new Promise(((i,a)=>{var p;const y=document.body,f=document.documentElement,w=document.activeElement instanceof HTMLElement?document.activeElement:null,b={x:window.scrollX,y:window.scrollY},v={body:y.getAttribute("style"),html:f.getAttribute("style")},E=Array.from(y.children).filter((e=>e instanceof HTMLElement)).map((e=>({el:e,inert:e.inert,hidden:e.getAttribute("aria-hidden")}))),T=document.createElement("div");let L;T.setAttribute("data-buckyos-sysdlg","select"),T.setAttribute("role","dialog"),T.setAttribute("aria-modal","true"),T.setAttribute("aria-label",g?"文件选择器":"File picker"),T.style.cssText="position:fixed;inset:0;height:100vh;height:100dvh;z-index:2147483647;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center";let k,x="",C=!1;const O=e=>{T.contains(e.target)||(e.stopPropagation(),e.preventDefault())},A=["keydown","pointerdown","mousedown","touchstart","wheel"],S=()=>{var e;return!C&&(C=!0,c=!1,clearTimeout(k),window.removeEventListener("message",M),null==(e=n.signal)||e.removeEventListener("abort",R),"inert"in HTMLElement.prototype||A.forEach((e=>document.removeEventListener(e,O,!0))),T.remove(),E.forEach((({el:e,inert:t,hidden:i})=>{e.inert=t,null===i?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",i)})),null===v.body?y.removeAttribute("style"):y.setAttribute("style",v.body),null===v.html?f.removeAttribute("style"):f.setAttribute("style",v.html),window.scrollTo(b.x,b.y),null==w||w.focus({preventScroll:!0}),!0)},D=t=>{S()&&a(new e.SystemDialogError(t))},R=()=>D("closed"),I=()=>{null==L||L.remove(),L=void 0;const e=document.createElement("div");e.setAttribute("role","alert"),e.style.cssText=`max-width:22rem;margin:1rem;padding:1.25rem;border-radius:16px;font:14px/1.6 system-ui,sans-serif;background:${"dark"===m?"#1f2329":"#fff"};color:${"dark"===m?"#f2f3f5":"#1f2329"};box-shadow:0 24px 64px rgba(0,0,0,.24)`;const t=document.createElement("p");t.style.margin="0 0 1rem",t.textContent=g?"无法加载文件选择器":"Unable to load the file picker";const i=document.createElement("div");i.style.cssText="display:flex;gap:.5rem;justify-content:flex-end";const o=(e,t)=>{const o=document.createElement("button");return o.type="button",o.textContent=e,o.style.cssText="min-height:2.25rem;padding:0 1rem;font:inherit;border-radius:999px;border:1px solid currentColor;background:transparent;color:inherit;cursor:pointer",o.addEventListener("click",t),i.append(o),o};o(g?"取消":"Cancel",(()=>D("load_failed")));const n=o(g?"重试":"Retry",(()=>{e.remove(),U()}));e.append(t,i),T.append(e),n.focus()},U=()=>{x=crypto.randomUUID(),L=document.createElement("iframe"),L.title=g?"文件选择器":"File picker",L.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;color-scheme:normal",L.setAttribute("allowtransparency","true"),L.addEventListener("error",I),L.src=`${h}${d}#bse=${x}&po=${encodeURIComponent(window.location.origin)}`,T.append(L),k=setTimeout(I,1e4)},M=n=>{var a;if(!L||n.origin!==h||n.source!==L.contentWindow||!r(n.data,l))return;const{type:d,payload:c}=n.data;if("embed.hello"===d){if(c.nonce!==x)return;clearTimeout(k),null==(a=L.contentWindow)||a.postMessage(s("embed.init",{nonce:x,params:o,theme:m,locale:u},l),h),L.focus()}if("embed.error"===d&&D(t(c.code)),"embed.result"===d){const t=e.readSelectDialogResult(c.result,{allowLocal:!0===o.allowLocal});t?(e=>{S()&&i(e)})(t):D("protocol")}};window.addEventListener("message",M),null==(p=n.signal)||p.addEventListener("abort",R,{once:!0}),"inert"in HTMLElement.prototype?E.forEach((({el:e})=>{e.inert=!0})):(E.forEach((({el:e})=>e.setAttribute("aria-hidden","true"))),A.forEach((e=>document.addEventListener(e,O,!0)))),f.style.overflow="hidden",y.style.position="fixed",y.style.top=-b.y+"px",y.style.left=-b.x+"px",y.style.right="0",y.style.overflow="hidden",y.append(T),U()}))}exports.AppFrameClient=class{constructor(e){if(this.options=e,this.listener=e=>{this.receive(e)},this.dialogs=new Map,this.origin=new URL(e.shellOrigin).origin,this.nonce=new URLSearchParams(window.location.hash.slice(1)).get("bfp"),window.addEventListener("message",this.listener),window.parent!==window&&this.nonce){const t=()=>window.parent.postMessage(i("frame.hello",{nonce:this.nonce,appCapabilities:[...e.onOpen?["open"]:[],...e.onBeforeClose?["beforeClose"]:[],...e.onBack?["back"]:[]]}),this.origin);t(),this.helloTimer=setInterval(t,250),this.helloDeadline=setTimeout((()=>clearInterval(this.helloTimer)),1500)}}async receive(n){var s,r,a,l,d,c,p,h,u,m,g,y,f,w;if(n.source!==window.parent||n.origin!==this.origin||!o(n.data))return;const b=n.data,v=b.payload;if("frame.init"===b.type){if(!this.nonce||v.nonce!==this.nonce||"string"!=typeof v.locale||!v.theme||"string"!=typeof v.windowId||v.launch&&!e.isOpenRequest(v.launch))return;return clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),this.init=v,this.title=void 0,this.focused=void 0,void(null==(r=(s=this.options).onInit)||r.call(s,this.init))}if(!this.init)return;if("sysdlg.openResult"===b.type){const i=b.replyTo?this.dialogs.get(b.replyTo):void 0;if(!i)return;if(this.dialogs.delete(b.replyTo),!0!==v.ok)return i.reject(new e.SystemDialogError(t(v.code)));const o=e.readSelectDialogResult(v.result,{allowLocal:i.allowLocal});return void(o?i.resolve(o):i.reject(new e.SystemDialogError("protocol")))}const E=e=>window.parent.postMessage(i(b.type+"Result",e,{replyTo:b.id}),this.origin);try{"frame.open"===b.type&&e.isOpenRequest(v.request)&&E(await(null==(l=(a=this.options).onOpen)?void 0:l.call(a,v.request))??{accepted:!1}),"frame.beforeClose"===b.type&&E({decision:await(null==(c=(d=this.options).onBeforeClose)?void 0:c.call(d,v.reason))??"allow"}),"frame.back"===b.type&&E({handled:await(null==(h=(p=this.options).onBack)?void 0:h.call(p))??!1}),"frame.themeChanged"!==b.type||"dark"!==v.mode&&"light"!==v.mode||null==(m=(u=this.options).onTheme)||m.call(u,v),"frame.localeChanged"===b.type&&"string"==typeof v.locale&&(null==(y=(g=this.options).onLocale)||y.call(g,v.locale)),"frame.focusChanged"===b.type&&this.focused!==(!0===v.focused)&&(this.focused=!0===v.focused,null==(w=(f=this.options).onFocus)||w.call(f,this.focused))}catch{"frame.open"===b.type&&E({accepted:!1,fallback:"preview"}),"frame.beforeClose"===b.type&&E({decision:"deny"})}}send(e,t){this.init&&window.parent.postMessage(i(e,t),this.origin)}setTitle(e,t=!1){const i=JSON.stringify([e,t]);this.init&&i!==this.title&&(this.title=i,this.send("window.setTitle",{title:e,dirty:t}))}requestClose(){this.send("window.requestClose",{})}openContent(t,i="default",o={}){const n=o.hints??{};return this.init?(this.send("content.open",{request:t,target:i,newWindow:!0===o.newWindow,hints:n}),!0):!!this.options.systemOrigin&&(window.open(e.systemOpenUrl(this.options.systemOrigin,{request:t,target:i,hints:n,from:this.options.appId}),"_blank","noopener"),!0)}selectContent(t={},o={}){var n,s;if(this.init){if(!this.init.shellCapabilities.includes(e.SELECT_DIALOG_PATH))return Promise.reject(new e.SystemDialogError("unsupported"));if(this.dialogs.size)return Promise.reject(new e.SystemDialogError("busy"));const o=crypto.randomUUID();return new Promise(((n,s)=>{this.dialogs.set(o,{resolve:n,reject:s,allowLocal:!0===t.allowLocal}),window.parent.postMessage(i("sysdlg.open",{path:e.SELECT_DIALOG_PATH,params:t},{id:o}),this.origin)}))}if(!this.options.systemOrigin)return Promise.reject(new e.SystemDialogError("unsupported"));const r=this.embedAbort=new AbortController;return null==(n=o.signal)||n.addEventListener("abort",(()=>r.abort()),{once:!0}),(null==(s=o.signal)?void 0:s.aborted)&&r.abort(),p(this.options.systemOrigin,t,{...o,signal:r.signal})}dispose(){var t;clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),window.removeEventListener("message",this.listener),this.dialogs.forEach((t=>t.reject(new e.SystemDialogError("closed")))),this.dialogs.clear(),null==(t=this.embedAbort)||t.abort()}},exports.AppFrameHost=class{constructor(e){this.options=e,this.ready=!1,this.capabilities=[],this.pending=new Map,this.listener=e=>this.receive(e),this.opens=[],this.dialogOpen=!1,window.addEventListener("message",this.listener)}async systemDialog(t,o,n){const s=e=>{var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i("sysdlg.openResult",e,{replyTo:t}),this.options.origin))};if(!this.options.onSystemDialog||"string"!=typeof o)return s({ok:!1,code:"unsupported"});if(this.dialogOpen)return s({ok:!1,code:"busy"});this.dialogOpen=!0;try{s(await this.options.onSystemDialog(o,n))}catch(r){s({ok:!1,code:r instanceof e.SystemDialogError?r.code:"closed"})}finally{this.dialogOpen=!1}}receive(t){var i,n,s,r,a,l,d,c;if(t.source!==this.options.target()||t.origin!==this.options.origin||!o(t.data))return;const p=t.data,h=p.payload;if("frame.hello"===p.type){if(h.nonce!==this.options.init.nonce||!Array.isArray(h.appCapabilities))return;return this.ready=!0,this.capabilities=h.appCapabilities.filter((e=>"string"==typeof e)),this.send("frame.init",this.options.init),void 0!==this.focused&&this.send("frame.focusChanged",{focused:this.focused}),void(null==(n=(i=this.options).onReady)||n.call(i))}if(this.ready)if(p.replyTo){const e=this.pending.get(p.replyTo);e&&p.type===e.type+"Result"&&(clearTimeout(e.timer),this.pending.delete(p.replyTo),e.resolve(p.payload))}else if("window.setTitle"===p.type&&"string"==typeof h.title&&(null==(r=(s=this.options).onTitle)||r.call(s,h.title.slice(0,256),!0===h.dirty)),"window.requestClose"===p.type&&(null==(l=(a=this.options).onRequestClose)||l.call(a)),"sysdlg.open"===p.type&&"string"==typeof p.id&&this.systemDialog(p.id,h.path,h.params),"content.open"===p.type&&("default"===h.target||"preview"===h.target||"chooser"===h.target)){const t={...h.request,requestId:crypto.randomUUID()};if(!e.isOpenRequest(t))return;if(this.opens=this.opens.filter((e=>e>Date.now()-1e4)),this.opens.length>=5)return;this.opens.push(Date.now()),null==(c=(d=this.options).onContentOpen)||c.call(d,t,h.target,{newWindow:!0===h.newWindow,hints:e.readContentHints(h.hints)})}}update(e){this.options.init={...this.options.init,...e}}setFocused(e){this.focused!==e&&(this.focused=e,this.send("frame.focusChanged",{focused:e}))}send(e,t){var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i(e,t),this.options.origin))}request(e,t,o=3e3){if(!this.ready)return Promise.reject(new Error("App frame is not ready"));const n=crypto.randomUUID();return new Promise(((s,r)=>{var a;const l=setTimeout((()=>{this.pending.delete(n),r(new Error("App frame timed out"))}),o);this.pending.set(n,{resolve:s,reject:r,timer:l,type:e}),null==(a=this.options.target())||a.postMessage(i(e,t,{id:n}),this.options.origin)}))}async open(e){return this.capabilities.includes("open")?await this.request("frame.open",{request:e}):{accepted:!1}}async beforeClose(e="user"){if(!this.ready||!this.capabilities.includes("beforeClose"))return"allow";const t=await this.request("frame.beforeClose",{reason:e});return"allow"===t.decision||"pending"===t.decision?t.decision:"deny"}async back(){return!!this.capabilities.includes("back")&&!0===(await this.request("frame.back",{})).handled}dispose(){window.removeEventListener("message",this.listener),this.pending.forEach((e=>{clearTimeout(e.timer),e.reject(new Error("App frame disposed"))})),this.pending.clear(),this.ready=!1}},exports.PREVIEW_EMBED_PATH=a,exports.PreviewEmbed=class{constructor(e){this.options=e,this.nonce=crypto.randomUUID(),this.listener=e=>this.receive(e),this.ready=!1,this.origin=new URL(e.systemOrigin).origin,this.init=e.init,this.url=`${this.origin}${a}#bpe=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`,window.addEventListener("message",this.listener)}post(e,t){var i,o;null==(o=null==(i=this.options.frame())?void 0:i.contentWindow)||o.postMessage(s(e,t),this.origin)}receive(t){var i,o,n,s,a,l,d;if(t.origin!==this.origin||t.source!==(null==(i=this.options.frame())?void 0:i.contentWindow)||!r(t.data))return;const{type:c,payload:p}=t.data;if("embed.hello"!==c){if("embed.state"===c&&("loading"===p.status||"ready"===p.status||"error"===p.status)){const e=p.error;null==(n=(o=this.options).onState)||n.call(o,{status:p.status,error:e&&"string"==typeof e.kind&&"string"==typeof e.code?{kind:e.kind,code:e.code}:void 0,title:"string"==typeof p.title?p.title.slice(0,256):void 0,mediaType:"string"==typeof p.mediaType?p.mediaType.slice(0,128):void 0})}if("embed.openWith"===c){const t=p.request;t&&e.isTransferableRef(t.source)&&(void 0===t.session||e.isTransferableSession(t.session))&&(null==(a=(s=this.options).onOpenWith)||a.call(s,{request:{source:t.source,session:t.session},hints:e.readContentHints(p.hints)}))}"embed.exit"===c&&(null==(d=(l=this.options).onExit)||d.call(l))}else p.nonce===this.nonce&&(this.ready=!0,this.post("embed.init",{...this.init,nonce:this.nonce}))}update(e){this.init={...this.init,...e},this.ready&&this.post("embed.update",e)}dispose(){window.removeEventListener("message",this.listener)}},exports.PreviewEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bpe");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce}),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(t){var i,o;if(t.source!==window.parent||t.origin!==this.parentOrigin||!r(t.data))return;const{type:n,payload:s}=t.data;if("embed.init"===n){if(s.nonce!==this.nonce||(a=s.source,!(e.isTransferableRef(a)||a&&"object"==typeof a&&"blob"===a.kind&&"undefined"!=typeof Blob&&a.blob instanceof Blob&&"string"==typeof a.name))||void 0!==s.session&&!e.isTransferableSession(s.session)||"string"!=typeof s.locale)return;return this.ready=!0,clearInterval(this.hello),void this.options.onInit({nonce:String(s.nonce),source:s.source,session:s.session,theme:"dark"===s.theme?"dark":"light",locale:s.locale})}var a;if("embed.update"===n&&this.ready){const e={};"dark"!==s.theme&&"light"!==s.theme||(e.theme=s.theme),"string"==typeof s.locale&&(e.locale=s.locale),null==(o=(i=this.options).onUpdate)||o.call(i,e)}}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t),this.parentOrigin)}state(e){this.post("embed.state",e)}openWith(e){this.post("embed.openWith",e)}exit(){this.post("embed.exit",{})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.SELECT_EMBED_PATH=d,exports.SelectEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bse");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce},l),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(e){if(e.source!==window.parent||e.origin!==this.parentOrigin||!r(e.data,l))return;const{type:t,payload:i}=e.data;"embed.init"!==t||this.ready||i.nonce!==this.nonce||"string"!=typeof i.locale||(this.ready=!0,clearInterval(this.hello),this.options.onInit({nonce:String(i.nonce),params:i.params,theme:"dark"===i.theme?"dark":"light",locale:i.locale}))}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t,l),this.parentOrigin)}result(e){this.post("embed.result",{result:e})}error(e){this.post("embed.error",{code:e})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.embedderOrigin=function(e){var t;if(window.parent===window)return null;const i=[null==(t=window.location.ancestorOrigins)?void 0:t[0],document.referrer];for(const o of i)if(o)try{const t=new URL(o).origin;if(e(t))return t}catch{}return null},exports.openSelectEmbed=p,exports.originInZone=(e,t)=>{try{const i=new URL(e);return i.protocol===window.location.protocol&&(i.hostname===t||i.hostname.endsWith(`.${t}`))}catch{return!1}};
2
2
  //# sourceMappingURL=app-frame.cjs.map