@noy-db/to-icloud 0.2.0-pre.30 → 0.2.0-pre.32

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.
package/README.md CHANGED
@@ -24,8 +24,8 @@ iCloud Drive bundle store for noy-db — macOS-aware persistence that detects ev
24
24
 
25
25
  See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup, examples, and the full subsystem catalog.
26
26
 
27
- - Source — [`packages/to-icloud`](https://github.com/vLannaAi/noy-db/tree/main/packages/to-icloud)
28
- - Issues — [github.com/vLannaAi/noy-db/issues](https://github.com/vLannaAi/noy-db/issues)
27
+ - Source — [`to-icloud`](https://github.com/vLannaAi/noy-db-to/tree/main/to-icloud)
28
+ - Issues — [github.com/vLannaAi/noy-db-to/issues](https://github.com/vLannaAi/noy-db-to/issues)
29
29
  - Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db/blob/main/SPEC.md)
30
30
 
31
31
  ## License
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { NoydbBundleStore } from '@noy-db/hub';
1
+ import { NoydbPodStore } from '@noy-db/hub/to';
2
2
 
3
3
  /**
4
4
  * **@noy-db/to-icloud** — iCloud Drive bundle store for noy-db.
@@ -20,7 +20,7 @@ import { NoydbBundleStore } from '@noy-db/hub';
20
20
  * macOS), and retries.
21
21
  * 2. **Conflict files.** Parallel writes from two devices create
22
22
  * `name (device conflicted copy DATE).noydb`. This store detects
23
- * those files and raises `BundleVersionConflictError`, giving the
23
+ * those files and raises `PodVersionConflictError`, giving the
24
24
  * caller a chance to merge deliberately.
25
25
  * 3. **Sync-not-yet-complete writes.** A completed `writeFile()` does
26
26
  * not mean the bytes are on Apple's servers. `ping()` reports
@@ -63,10 +63,10 @@ interface ICloudStoreOptions {
63
63
  readonly suffix?: string;
64
64
  }
65
65
  /**
66
- * Build a `NoydbBundleStore` over an iCloud Drive folder. Wrap with
66
+ * Build a `NoydbPodStore` over an iCloud Drive folder. Wrap with
67
67
  * `wrapBundleStore()` to consume via `createNoydb({ store })`.
68
68
  */
69
- declare function icloud(options: ICloudStoreOptions): NoydbBundleStore;
69
+ declare function icloud(options: ICloudStoreOptions): NoydbPodStore;
70
70
  /**
71
71
  * Wire a Node `fs/promises` implementation as an `ICloudFs`. Dynamic
72
72
  * import keeps the package browser-loadable (the caller's bundler
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { BundleVersionConflictError } from "@noy-db/hub";
2
+ import { PodVersionConflictError } from "@noy-db/hub/to";
3
3
  var DEFAULT_FOLDER = "NoyDB";
4
4
  function fileName(vault, suffix) {
5
5
  return `${vault}${suffix}`;
@@ -65,7 +65,7 @@ function icloud(options) {
65
65
  async writeBundle(vaultId, bytes, expectedVersion) {
66
66
  const conflict = await detectConflict(vaultId);
67
67
  if (conflict) {
68
- throw new BundleVersionConflictError(
68
+ throw new PodVersionConflictError(
69
69
  `iCloud conflict file detected alongside "${vaultId}${suffix}": "${conflict}". Open iCloud Drive, resolve the conflict, then retry.`
70
70
  );
71
71
  }
@@ -73,7 +73,7 @@ function icloud(options) {
73
73
  const stat = await fs.stat(path);
74
74
  const current = stat ? versionOf(stat) : null;
75
75
  if (expectedVersion !== null && current !== null && expectedVersion !== current) {
76
- throw new BundleVersionConflictError(
76
+ throw new PodVersionConflictError(
77
77
  `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`
78
78
  );
79
79
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-icloud** — iCloud Drive bundle store for noy-db.\n *\n * Treats each vault as a single `.noydb` bundle stored under\n * `~/Library/Mobile Documents/…` (or any user-chosen iCloud path).\n * Pair with `wrapBundleStore()` from `@noy-db/hub` to get the\n * standard six-method `NoydbStore` surface.\n *\n * ## Why a dedicated package if `to-file` \"works\"?\n *\n * `@noy-db/to-file` pointed at an iCloud Drive directory technically\n * works — until one of three iCloud-specific behaviors bites you:\n *\n * 1. **On-demand eviction.** iCloud may evict the file to cloud-only\n * storage, leaving a `.icloud` stub. `readFile()` on the stub\n * either throws ENOENT or returns stub metadata. This store\n * detects the stub, nudges the OS to redownload (via `xattr` on\n * macOS), and retries.\n * 2. **Conflict files.** Parallel writes from two devices create\n * `name (device conflicted copy DATE).noydb`. This store detects\n * those files and raises `BundleVersionConflictError`, giving the\n * caller a chance to merge deliberately.\n * 3. **Sync-not-yet-complete writes.** A completed `writeFile()` does\n * not mean the bytes are on Apple's servers. `ping()` reports\n * on upload status so callers can wait before considering a\n * write durable.\n *\n * ## Scope\n *\n * - **Node (macOS) only for v1.** Browser / iOS consumers go through\n * CloudKit JS — a separate package will ship as `@noy-db/to-cloudkit`.\n * - **Bundle granularity** — whole vault in one file. Pair with\n * `syncPolicy: { push: { mode: 'debounce', 30_000 } }` so every\n * record mutation doesn't trigger a full bundle upload.\n * - **No extra auth** — iCloud syncs via the user's signed-in Apple ID;\n * the store never sees credentials.\n *\n * @packageDocumentation\n */\n\nimport type { NoydbBundleStore } from '@noy-db/hub'\nimport { BundleVersionConflictError } from '@noy-db/hub'\n\n/** Default iCloud Drive folder name inside a user's mobile-documents tree. */\nexport const DEFAULT_FOLDER = 'NoyDB'\n\nexport interface ICloudFs {\n readFile(path: string): Promise<Uint8Array | Buffer | null>\n writeFile(path: string, data: Uint8Array): Promise<void>\n unlink(path: string): Promise<void>\n readdir(path: string): Promise<string[]>\n stat(path: string): Promise<{ mtimeMs: number; size: number } | null>\n /** macOS-only: force iCloud to materialise an evicted `.icloud` stub. */\n triggerDownload?(path: string): Promise<void>\n}\n\nexport interface ICloudStoreOptions {\n /** Absolute path to the iCloud Drive folder that holds bundles. */\n readonly folder: string\n /** File-system facade — swap in a mock or a cross-platform shim. */\n readonly fs: ICloudFs\n /** Bundle filename suffix. Default `'.noydb'`. */\n readonly suffix?: string\n}\n\nfunction fileName(vault: string, suffix: string): string {\n return `${vault}${suffix}`\n}\n\nfunction isStub(name: string): boolean {\n // macOS writes `<name>.icloud` stubs when offloading files.\n return name.endsWith('.icloud')\n}\n\nfunction isConflictCopy(name: string, expected: string): boolean {\n // Canonical shape: `foo (device conflicted copy DATE).noydb`\n return name.includes(\"'s conflicted copy\") ||\n (name.includes('(conflicted copy') && name.endsWith(expected.slice(expected.lastIndexOf('.'))))\n}\n\n/**\n * Build a `NoydbBundleStore` over an iCloud Drive folder. Wrap with\n * `wrapBundleStore()` to consume via `createNoydb({ store })`.\n */\nexport function icloud(options: ICloudStoreOptions): NoydbBundleStore {\n const suffix = options.suffix ?? '.noydb'\n const dir = options.folder.replace(/\\/+$/, '')\n const { fs } = options\n\n async function pathFor(vault: string): Promise<string> {\n return `${dir}/${fileName(vault, suffix)}`\n }\n\n async function stubAwareRead(path: string): Promise<Uint8Array | null> {\n // Direct read first.\n let bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n\n // Check for an adjacent `.icloud` stub and try to materialise it.\n const stubPath = `${path}.icloud`\n const stubExists = await fs.stat(stubPath)\n if (!stubExists) return null\n if (fs.triggerDownload) {\n await fs.triggerDownload(stubPath)\n bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n }\n // Still offloaded. Surface a clean error so the caller can retry\n // or invite the user to open iCloud.\n throw new Error(\n `iCloud file \"${path}\" is offloaded. Open the file in Finder to trigger a download, ` +\n `or install an OS-level trigger (\\`brctl download \"${path}\"\\`).`,\n )\n }\n\n async function detectConflict(vault: string): Promise<string | null> {\n const target = fileName(vault, suffix)\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n for (const entry of entries) {\n if (isConflictCopy(entry, target)) return entry\n }\n return null\n }\n\n function versionOf(stat: { mtimeMs: number; size: number }): string {\n // mtime-based opaque token — sufficient for OCC within a single\n // syncing agent. iCloud's native conflict file machinery provides\n // the cross-agent guard.\n return `${stat.mtimeMs}-${stat.size}`\n }\n\n return {\n kind: 'bundle',\n name: 'icloud',\n\n async readBundle(vaultId) {\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n if (!stat) {\n // Perhaps only a stub exists — detect and trigger.\n const stubStat = await fs.stat(`${path}.icloud`)\n if (!stubStat) return null\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n const redoStat = await fs.stat(path)\n if (!redoStat) throw new Error(`icloud: file vanished after download at ${path}`)\n return { bytes, version: versionOf(redoStat) }\n }\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n return { bytes, version: versionOf(stat) }\n },\n\n async writeBundle(vaultId, bytes, expectedVersion) {\n // Conflict file present → refuse; caller merges.\n const conflict = await detectConflict(vaultId)\n if (conflict) {\n throw new BundleVersionConflictError(\n `iCloud conflict file detected alongside \"${vaultId}${suffix}\": \"${conflict}\". ` +\n `Open iCloud Drive, resolve the conflict, then retry.`,\n )\n }\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n const current = stat ? versionOf(stat) : null\n if (expectedVersion !== null && current !== null && expectedVersion !== current) {\n throw new BundleVersionConflictError(\n `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`,\n )\n }\n await fs.writeFile(path, bytes)\n const newStat = await fs.stat(path)\n if (!newStat) throw new Error(`icloud: write reported success but stat failed at ${path}`)\n return { version: versionOf(newStat) }\n },\n\n async deleteBundle(vaultId) {\n const path = await pathFor(vaultId)\n try {\n await fs.unlink(path)\n } catch {\n // Idempotent\n }\n },\n\n async listBundles() {\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n const out: Array<{ vaultId: string; version: string; size: number }> = []\n for (const entry of entries) {\n if (!entry.endsWith(suffix) || isStub(entry)) continue\n const vaultId = entry.slice(0, -suffix.length)\n const stat = await fs.stat(`${dir}/${entry}`)\n if (!stat) continue\n out.push({ vaultId, version: versionOf(stat), size: stat.size })\n }\n return out\n },\n }\n}\n\n/**\n * Wire a Node `fs/promises` implementation as an `ICloudFs`. Dynamic\n * import keeps the package browser-loadable (the caller's bundler\n * prunes the Node path).\n */\nexport async function nodeFs(): Promise<ICloudFs> {\n const fs = await import('node:fs/promises')\n const { spawn } = await import('node:child_process')\n return {\n async readFile(path) {\n try {\n return await fs.readFile(path)\n } catch {\n return null\n }\n },\n async writeFile(path, data) {\n await fs.writeFile(path, data)\n },\n async unlink(path) {\n await fs.unlink(path).catch(() => undefined)\n },\n async readdir(path) {\n return fs.readdir(path)\n },\n async stat(path) {\n try {\n const s = await fs.stat(path)\n return { mtimeMs: s.mtimeMs, size: s.size }\n } catch {\n return null\n }\n },\n async triggerDownload(path) {\n // macOS: `brctl download` forces iCloud to materialise a stub.\n await new Promise<void>((resolve) => {\n const child = spawn('brctl', ['download', path.replace(/\\.icloud$/, '')])\n child.on('close', () => resolve())\n child.on('error', () => resolve())\n })\n },\n }\n}\n"],"mappings":";AAyCA,SAAS,kCAAkC;AAGpC,IAAM,iBAAiB;AAqB9B,SAAS,SAAS,OAAe,QAAwB;AACvD,SAAO,GAAG,KAAK,GAAG,MAAM;AAC1B;AAEA,SAAS,OAAO,MAAuB;AAErC,SAAO,KAAK,SAAS,SAAS;AAChC;AAEA,SAAS,eAAe,MAAc,UAA2B;AAE/D,SAAO,KAAK,SAAS,oBAAoB,KACjC,KAAK,SAAS,kBAAkB,KAAK,KAAK,SAAS,SAAS,MAAM,SAAS,YAAY,GAAG,CAAC,CAAC;AACtG;AAMO,SAAS,OAAO,SAA+C;AACpE,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,MAAM,QAAQ,OAAO,QAAQ,QAAQ,EAAE;AAC7C,QAAM,EAAE,GAAG,IAAI;AAEf,iBAAe,QAAQ,OAAgC;AACrD,WAAO,GAAG,GAAG,IAAI,SAAS,OAAO,MAAM,CAAC;AAAA,EAC1C;AAEA,iBAAe,cAAc,MAA0C;AAErE,QAAI,QAAQ,MAAM,GAAG,SAAS,IAAI;AAClC,QAAI,UAAU,KAAM,QAAO,iBAAiB,aAAa,QAAQ,IAAI,WAAW,KAAK;AAGr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AAC,KAAM;AACX,YAAI,KAAK,EAAE,SAAS,SAAS,UAAU,IAAI,GAAG,MAAM,KAAK,KAAK,CAAC;AAAA,MACjE;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOA,eAAsB,SAA4B;AAChD,QAAM,KAAK,MAAM,OAAO,aAAkB;AAC1C,QAAM,EAAE,MAAM,IAAI,MAAM,OAAO,eAAoB;AACnD,SAAO;AAAA,IACL,MAAM,SAAS,MAAM;AACnB,UAAI;AACF,eAAO,MAAM,GAAG,SAAS,IAAI;AAAA,MAC/B,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,MAAM,UAAU,MAAM,MAAM;AAC1B,YAAM,GAAG,UAAU,MAAM,IAAI;AAAA,IAC/B;AAAA,IACA,MAAM,OAAO,MAAM;AACjB,YAAM,GAAG,OAAO,IAAI,EAAE,MAAM,MAAM,MAAS;AAAA,IAC7C;AAAA,IACA,MAAM,QAAQ,MAAM;AAClB,aAAO,GAAG,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA,MAAM,KAAK,MAAM;AACf,UAAI;AACF,cAAM,IAAI,MAAM,GAAG,KAAK,IAAI;AAC5B,eAAO,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,KAAK;AAAA,MAC5C,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,MAAM,gBAAgB,MAAM;AAE1B,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,cAAM,QAAQ,MAAM,SAAS,CAAC,YAAY,KAAK,QAAQ,aAAa,EAAE,CAAC,CAAC;AACxE,cAAM,GAAG,SAAS,MAAM,QAAQ,CAAC;AACjC,cAAM,GAAG,SAAS,MAAM,QAAQ,CAAC;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["bytes"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-icloud** — iCloud Drive bundle store for noy-db.\n *\n * Treats each vault as a single `.noydb` bundle stored under\n * `~/Library/Mobile Documents/…` (or any user-chosen iCloud path).\n * Pair with `wrapBundleStore()` from `@noy-db/hub` to get the\n * standard six-method `NoydbStore` surface.\n *\n * ## Why a dedicated package if `to-file` \"works\"?\n *\n * `@noy-db/to-file` pointed at an iCloud Drive directory technically\n * works — until one of three iCloud-specific behaviors bites you:\n *\n * 1. **On-demand eviction.** iCloud may evict the file to cloud-only\n * storage, leaving a `.icloud` stub. `readFile()` on the stub\n * either throws ENOENT or returns stub metadata. This store\n * detects the stub, nudges the OS to redownload (via `xattr` on\n * macOS), and retries.\n * 2. **Conflict files.** Parallel writes from two devices create\n * `name (device conflicted copy DATE).noydb`. This store detects\n * those files and raises `PodVersionConflictError`, giving the\n * caller a chance to merge deliberately.\n * 3. **Sync-not-yet-complete writes.** A completed `writeFile()` does\n * not mean the bytes are on Apple's servers. `ping()` reports\n * on upload status so callers can wait before considering a\n * write durable.\n *\n * ## Scope\n *\n * - **Node (macOS) only for v1.** Browser / iOS consumers go through\n * CloudKit JS — a separate package will ship as `@noy-db/to-cloudkit`.\n * - **Bundle granularity** — whole vault in one file. Pair with\n * `syncPolicy: { push: { mode: 'debounce', 30_000 } }` so every\n * record mutation doesn't trigger a full bundle upload.\n * - **No extra auth** — iCloud syncs via the user's signed-in Apple ID;\n * the store never sees credentials.\n *\n * @packageDocumentation\n */\n\nimport type { NoydbPodStore } from '@noy-db/hub/to'\nimport { PodVersionConflictError } from '@noy-db/hub/to'\n\n/** Default iCloud Drive folder name inside a user's mobile-documents tree. */\nexport const DEFAULT_FOLDER = 'NoyDB'\n\nexport interface ICloudFs {\n readFile(path: string): Promise<Uint8Array | Buffer | null>\n writeFile(path: string, data: Uint8Array): Promise<void>\n unlink(path: string): Promise<void>\n readdir(path: string): Promise<string[]>\n stat(path: string): Promise<{ mtimeMs: number; size: number } | null>\n /** macOS-only: force iCloud to materialise an evicted `.icloud` stub. */\n triggerDownload?(path: string): Promise<void>\n}\n\nexport interface ICloudStoreOptions {\n /** Absolute path to the iCloud Drive folder that holds bundles. */\n readonly folder: string\n /** File-system facade — swap in a mock or a cross-platform shim. */\n readonly fs: ICloudFs\n /** Bundle filename suffix. Default `'.noydb'`. */\n readonly suffix?: string\n}\n\nfunction fileName(vault: string, suffix: string): string {\n return `${vault}${suffix}`\n}\n\nfunction isStub(name: string): boolean {\n // macOS writes `<name>.icloud` stubs when offloading files.\n return name.endsWith('.icloud')\n}\n\nfunction isConflictCopy(name: string, expected: string): boolean {\n // Canonical shape: `foo (device conflicted copy DATE).noydb`\n return name.includes(\"'s conflicted copy\") ||\n (name.includes('(conflicted copy') && name.endsWith(expected.slice(expected.lastIndexOf('.'))))\n}\n\n/**\n * Build a `NoydbPodStore` over an iCloud Drive folder. Wrap with\n * `wrapBundleStore()` to consume via `createNoydb({ store })`.\n */\nexport function icloud(options: ICloudStoreOptions): NoydbPodStore {\n const suffix = options.suffix ?? '.noydb'\n const dir = options.folder.replace(/\\/+$/, '')\n const { fs } = options\n\n async function pathFor(vault: string): Promise<string> {\n return `${dir}/${fileName(vault, suffix)}`\n }\n\n async function stubAwareRead(path: string): Promise<Uint8Array | null> {\n // Direct read first.\n let bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n\n // Check for an adjacent `.icloud` stub and try to materialise it.\n const stubPath = `${path}.icloud`\n const stubExists = await fs.stat(stubPath)\n if (!stubExists) return null\n if (fs.triggerDownload) {\n await fs.triggerDownload(stubPath)\n bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n }\n // Still offloaded. Surface a clean error so the caller can retry\n // or invite the user to open iCloud.\n throw new Error(\n `iCloud file \"${path}\" is offloaded. Open the file in Finder to trigger a download, ` +\n `or install an OS-level trigger (\\`brctl download \"${path}\"\\`).`,\n )\n }\n\n async function detectConflict(vault: string): Promise<string | null> {\n const target = fileName(vault, suffix)\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n for (const entry of entries) {\n if (isConflictCopy(entry, target)) return entry\n }\n return null\n }\n\n function versionOf(stat: { mtimeMs: number; size: number }): string {\n // mtime-based opaque token — sufficient for OCC within a single\n // syncing agent. iCloud's native conflict file machinery provides\n // the cross-agent guard.\n return `${stat.mtimeMs}-${stat.size}`\n }\n\n return {\n kind: 'bundle',\n name: 'icloud',\n\n async readBundle(vaultId) {\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n if (!stat) {\n // Perhaps only a stub exists — detect and trigger.\n const stubStat = await fs.stat(`${path}.icloud`)\n if (!stubStat) return null\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n const redoStat = await fs.stat(path)\n if (!redoStat) throw new Error(`icloud: file vanished after download at ${path}`)\n return { bytes, version: versionOf(redoStat) }\n }\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n return { bytes, version: versionOf(stat) }\n },\n\n async writeBundle(vaultId, bytes, expectedVersion) {\n // Conflict file present → refuse; caller merges.\n const conflict = await detectConflict(vaultId)\n if (conflict) {\n throw new PodVersionConflictError(\n `iCloud conflict file detected alongside \"${vaultId}${suffix}\": \"${conflict}\". ` +\n `Open iCloud Drive, resolve the conflict, then retry.`,\n )\n }\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n const current = stat ? versionOf(stat) : null\n if (expectedVersion !== null && current !== null && expectedVersion !== current) {\n throw new PodVersionConflictError(\n `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`,\n )\n }\n await fs.writeFile(path, bytes)\n const newStat = await fs.stat(path)\n if (!newStat) throw new Error(`icloud: write reported success but stat failed at ${path}`)\n return { version: versionOf(newStat) }\n },\n\n async deleteBundle(vaultId) {\n const path = await pathFor(vaultId)\n try {\n await fs.unlink(path)\n } catch {\n // Idempotent\n }\n },\n\n async listBundles() {\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n const out: Array<{ vaultId: string; version: string; size: number }> = []\n for (const entry of entries) {\n if (!entry.endsWith(suffix) || isStub(entry)) continue\n const vaultId = entry.slice(0, -suffix.length)\n const stat = await fs.stat(`${dir}/${entry}`)\n if (!stat) continue\n out.push({ vaultId, version: versionOf(stat), size: stat.size })\n }\n return out\n },\n }\n}\n\n/**\n * Wire a Node `fs/promises` implementation as an `ICloudFs`. Dynamic\n * import keeps the package browser-loadable (the caller's bundler\n * prunes the Node path).\n */\nexport async function nodeFs(): Promise<ICloudFs> {\n const fs = await import('node:fs/promises')\n const { spawn } = await import('node:child_process')\n return {\n async readFile(path) {\n try {\n return await fs.readFile(path)\n } catch {\n return null\n }\n },\n async writeFile(path, data) {\n await fs.writeFile(path, data)\n },\n async unlink(path) {\n await fs.unlink(path).catch(() => undefined)\n },\n async readdir(path) {\n return fs.readdir(path)\n },\n async stat(path) {\n try {\n const s = await fs.stat(path)\n return { mtimeMs: s.mtimeMs, size: s.size }\n } catch {\n return null\n }\n },\n async triggerDownload(path) {\n // macOS: `brctl download` forces iCloud to materialise a stub.\n await new Promise<void>((resolve) => {\n const child = spawn('brctl', ['download', path.replace(/\\.icloud$/, '')])\n child.on('close', () => resolve())\n child.on('error', () => resolve())\n })\n },\n }\n}\n"],"mappings":";AAyCA,SAAS,+BAA+B;AAGjC,IAAM,iBAAiB;AAqB9B,SAAS,SAAS,OAAe,QAAwB;AACvD,SAAO,GAAG,KAAK,GAAG,MAAM;AAC1B;AAEA,SAAS,OAAO,MAAuB;AAErC,SAAO,KAAK,SAAS,SAAS;AAChC;AAEA,SAAS,eAAe,MAAc,UAA2B;AAE/D,SAAO,KAAK,SAAS,oBAAoB,KACjC,KAAK,SAAS,kBAAkB,KAAK,KAAK,SAAS,SAAS,MAAM,SAAS,YAAY,GAAG,CAAC,CAAC;AACtG;AAMO,SAAS,OAAO,SAA4C;AACjE,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,MAAM,QAAQ,OAAO,QAAQ,QAAQ,EAAE;AAC7C,QAAM,EAAE,GAAG,IAAI;AAEf,iBAAe,QAAQ,OAAgC;AACrD,WAAO,GAAG,GAA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AAS,MAAM,QAAQ,CAAC;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["bytes"]}
package/package.json CHANGED
@@ -1,33 +1,25 @@
1
1
  {
2
2
  "name": "@noy-db/to-icloud",
3
- "version": "0.2.0-pre.30",
3
+ "version": "0.2.0-pre.32",
4
4
  "description": "iCloud Drive bundle store for noy-db — macOS-aware persistence that detects eviction stubs (.icloud) and conflict files automatically. Treats each vault as a single .noydb bundle, safe for the Apple ecosystem.",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
7
- "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/to-icloud#readme",
7
+ "homepage": "https://github.com/vLannaAi/noy-db-to/tree/main/to-icloud#readme",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/vLannaAi/noy-db.git",
11
- "directory": "packages/to-icloud"
10
+ "url": "git+https://github.com/vLannaAi/noy-db-to.git"
12
11
  },
13
12
  "bugs": {
14
- "url": "https://github.com/vLannaAi/noy-db/issues"
13
+ "url": "https://github.com/vLannaAi/noy-db-to/issues"
15
14
  },
16
15
  "type": "module",
17
16
  "sideEffects": false,
18
17
  "exports": {
19
18
  ".": {
20
- "import": {
21
- "types": "./dist/index.d.ts",
22
- "default": "./dist/index.js"
23
- },
24
- "require": {
25
- "types": "./dist/index.d.cts",
26
- "default": "./dist/index.cjs"
27
- }
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
28
21
  }
29
22
  },
30
- "main": "./dist/index.cjs",
31
23
  "module": "./dist/index.js",
32
24
  "types": "./dist/index.d.ts",
33
25
  "files": [
@@ -36,14 +28,14 @@
36
28
  "LICENSE"
37
29
  ],
38
30
  "engines": {
39
- "node": ">=18.0.0"
31
+ "node": ">=22.0.0"
40
32
  },
41
33
  "peerDependencies": {
42
- "@noy-db/hub": "0.2.0-pre.30"
34
+ "@noy-db/hub": "^0.3.0-pre.1"
43
35
  },
44
36
  "devDependencies": {
45
- "@types/node": "^22.0.0",
46
- "@noy-db/hub": "0.2.0-pre.30"
37
+ "@noy-db/hub": "0.3.0-pre.7",
38
+ "@types/node": "^22.0.0"
47
39
  },
48
40
  "keywords": [
49
41
  "noy-db",
package/dist/index.cjs DELETED
@@ -1,185 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- DEFAULT_FOLDER: () => DEFAULT_FOLDER,
34
- icloud: () => icloud,
35
- nodeFs: () => nodeFs
36
- });
37
- module.exports = __toCommonJS(index_exports);
38
- var import_hub = require("@noy-db/hub");
39
- var DEFAULT_FOLDER = "NoyDB";
40
- function fileName(vault, suffix) {
41
- return `${vault}${suffix}`;
42
- }
43
- function isStub(name) {
44
- return name.endsWith(".icloud");
45
- }
46
- function isConflictCopy(name, expected) {
47
- return name.includes("'s conflicted copy") || name.includes("(conflicted copy") && name.endsWith(expected.slice(expected.lastIndexOf(".")));
48
- }
49
- function icloud(options) {
50
- const suffix = options.suffix ?? ".noydb";
51
- const dir = options.folder.replace(/\/+$/, "");
52
- const { fs } = options;
53
- async function pathFor(vault) {
54
- return `${dir}/${fileName(vault, suffix)}`;
55
- }
56
- async function stubAwareRead(path) {
57
- let bytes = await fs.readFile(path);
58
- if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
59
- const stubPath = `${path}.icloud`;
60
- const stubExists = await fs.stat(stubPath);
61
- if (!stubExists) return null;
62
- if (fs.triggerDownload) {
63
- await fs.triggerDownload(stubPath);
64
- bytes = await fs.readFile(path);
65
- if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
66
- }
67
- throw new Error(
68
- `iCloud file "${path}" is offloaded. Open the file in Finder to trigger a download, or install an OS-level trigger (\`brctl download "${path}"\`).`
69
- );
70
- }
71
- async function detectConflict(vault) {
72
- const target = fileName(vault, suffix);
73
- const entries = await fs.readdir(dir).catch(() => []);
74
- for (const entry of entries) {
75
- if (isConflictCopy(entry, target)) return entry;
76
- }
77
- return null;
78
- }
79
- function versionOf(stat) {
80
- return `${stat.mtimeMs}-${stat.size}`;
81
- }
82
- return {
83
- kind: "bundle",
84
- name: "icloud",
85
- async readBundle(vaultId) {
86
- const path = await pathFor(vaultId);
87
- const stat = await fs.stat(path);
88
- if (!stat) {
89
- const stubStat = await fs.stat(`${path}.icloud`);
90
- if (!stubStat) return null;
91
- const bytes2 = await stubAwareRead(path);
92
- if (!bytes2) return null;
93
- const redoStat = await fs.stat(path);
94
- if (!redoStat) throw new Error(`icloud: file vanished after download at ${path}`);
95
- return { bytes: bytes2, version: versionOf(redoStat) };
96
- }
97
- const bytes = await stubAwareRead(path);
98
- if (!bytes) return null;
99
- return { bytes, version: versionOf(stat) };
100
- },
101
- async writeBundle(vaultId, bytes, expectedVersion) {
102
- const conflict = await detectConflict(vaultId);
103
- if (conflict) {
104
- throw new import_hub.BundleVersionConflictError(
105
- `iCloud conflict file detected alongside "${vaultId}${suffix}": "${conflict}". Open iCloud Drive, resolve the conflict, then retry.`
106
- );
107
- }
108
- const path = await pathFor(vaultId);
109
- const stat = await fs.stat(path);
110
- const current = stat ? versionOf(stat) : null;
111
- if (expectedVersion !== null && current !== null && expectedVersion !== current) {
112
- throw new import_hub.BundleVersionConflictError(
113
- `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`
114
- );
115
- }
116
- await fs.writeFile(path, bytes);
117
- const newStat = await fs.stat(path);
118
- if (!newStat) throw new Error(`icloud: write reported success but stat failed at ${path}`);
119
- return { version: versionOf(newStat) };
120
- },
121
- async deleteBundle(vaultId) {
122
- const path = await pathFor(vaultId);
123
- try {
124
- await fs.unlink(path);
125
- } catch {
126
- }
127
- },
128
- async listBundles() {
129
- const entries = await fs.readdir(dir).catch(() => []);
130
- const out = [];
131
- for (const entry of entries) {
132
- if (!entry.endsWith(suffix) || isStub(entry)) continue;
133
- const vaultId = entry.slice(0, -suffix.length);
134
- const stat = await fs.stat(`${dir}/${entry}`);
135
- if (!stat) continue;
136
- out.push({ vaultId, version: versionOf(stat), size: stat.size });
137
- }
138
- return out;
139
- }
140
- };
141
- }
142
- async function nodeFs() {
143
- const fs = await import("fs/promises");
144
- const { spawn } = await import("child_process");
145
- return {
146
- async readFile(path) {
147
- try {
148
- return await fs.readFile(path);
149
- } catch {
150
- return null;
151
- }
152
- },
153
- async writeFile(path, data) {
154
- await fs.writeFile(path, data);
155
- },
156
- async unlink(path) {
157
- await fs.unlink(path).catch(() => void 0);
158
- },
159
- async readdir(path) {
160
- return fs.readdir(path);
161
- },
162
- async stat(path) {
163
- try {
164
- const s = await fs.stat(path);
165
- return { mtimeMs: s.mtimeMs, size: s.size };
166
- } catch {
167
- return null;
168
- }
169
- },
170
- async triggerDownload(path) {
171
- await new Promise((resolve) => {
172
- const child = spawn("brctl", ["download", path.replace(/\.icloud$/, "")]);
173
- child.on("close", () => resolve());
174
- child.on("error", () => resolve());
175
- });
176
- }
177
- };
178
- }
179
- // Annotate the CommonJS export names for ESM import in node:
180
- 0 && (module.exports = {
181
- DEFAULT_FOLDER,
182
- icloud,
183
- nodeFs
184
- });
185
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-icloud** — iCloud Drive bundle store for noy-db.\n *\n * Treats each vault as a single `.noydb` bundle stored under\n * `~/Library/Mobile Documents/…` (or any user-chosen iCloud path).\n * Pair with `wrapBundleStore()` from `@noy-db/hub` to get the\n * standard six-method `NoydbStore` surface.\n *\n * ## Why a dedicated package if `to-file` \"works\"?\n *\n * `@noy-db/to-file` pointed at an iCloud Drive directory technically\n * works — until one of three iCloud-specific behaviors bites you:\n *\n * 1. **On-demand eviction.** iCloud may evict the file to cloud-only\n * storage, leaving a `.icloud` stub. `readFile()` on the stub\n * either throws ENOENT or returns stub metadata. This store\n * detects the stub, nudges the OS to redownload (via `xattr` on\n * macOS), and retries.\n * 2. **Conflict files.** Parallel writes from two devices create\n * `name (device conflicted copy DATE).noydb`. This store detects\n * those files and raises `BundleVersionConflictError`, giving the\n * caller a chance to merge deliberately.\n * 3. **Sync-not-yet-complete writes.** A completed `writeFile()` does\n * not mean the bytes are on Apple's servers. `ping()` reports\n * on upload status so callers can wait before considering a\n * write durable.\n *\n * ## Scope\n *\n * - **Node (macOS) only for v1.** Browser / iOS consumers go through\n * CloudKit JS — a separate package will ship as `@noy-db/to-cloudkit`.\n * - **Bundle granularity** — whole vault in one file. Pair with\n * `syncPolicy: { push: { mode: 'debounce', 30_000 } }` so every\n * record mutation doesn't trigger a full bundle upload.\n * - **No extra auth** — iCloud syncs via the user's signed-in Apple ID;\n * the store never sees credentials.\n *\n * @packageDocumentation\n */\n\nimport type { NoydbBundleStore } from '@noy-db/hub'\nimport { BundleVersionConflictError } from '@noy-db/hub'\n\n/** Default iCloud Drive folder name inside a user's mobile-documents tree. */\nexport const DEFAULT_FOLDER = 'NoyDB'\n\nexport interface ICloudFs {\n readFile(path: string): Promise<Uint8Array | Buffer | null>\n writeFile(path: string, data: Uint8Array): Promise<void>\n unlink(path: string): Promise<void>\n readdir(path: string): Promise<string[]>\n stat(path: string): Promise<{ mtimeMs: number; size: number } | null>\n /** macOS-only: force iCloud to materialise an evicted `.icloud` stub. */\n triggerDownload?(path: string): Promise<void>\n}\n\nexport interface ICloudStoreOptions {\n /** Absolute path to the iCloud Drive folder that holds bundles. */\n readonly folder: string\n /** File-system facade — swap in a mock or a cross-platform shim. */\n readonly fs: ICloudFs\n /** Bundle filename suffix. Default `'.noydb'`. */\n readonly suffix?: string\n}\n\nfunction fileName(vault: string, suffix: string): string {\n return `${vault}${suffix}`\n}\n\nfunction isStub(name: string): boolean {\n // macOS writes `<name>.icloud` stubs when offloading files.\n return name.endsWith('.icloud')\n}\n\nfunction isConflictCopy(name: string, expected: string): boolean {\n // Canonical shape: `foo (device conflicted copy DATE).noydb`\n return name.includes(\"'s conflicted copy\") ||\n (name.includes('(conflicted copy') && name.endsWith(expected.slice(expected.lastIndexOf('.'))))\n}\n\n/**\n * Build a `NoydbBundleStore` over an iCloud Drive folder. Wrap with\n * `wrapBundleStore()` to consume via `createNoydb({ store })`.\n */\nexport function icloud(options: ICloudStoreOptions): NoydbBundleStore {\n const suffix = options.suffix ?? '.noydb'\n const dir = options.folder.replace(/\\/+$/, '')\n const { fs } = options\n\n async function pathFor(vault: string): Promise<string> {\n return `${dir}/${fileName(vault, suffix)}`\n }\n\n async function stubAwareRead(path: string): Promise<Uint8Array | null> {\n // Direct read first.\n let bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n\n // Check for an adjacent `.icloud` stub and try to materialise it.\n const stubPath = `${path}.icloud`\n const stubExists = await fs.stat(stubPath)\n if (!stubExists) return null\n if (fs.triggerDownload) {\n await fs.triggerDownload(stubPath)\n bytes = await fs.readFile(path)\n if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n }\n // Still offloaded. Surface a clean error so the caller can retry\n // or invite the user to open iCloud.\n throw new Error(\n `iCloud file \"${path}\" is offloaded. Open the file in Finder to trigger a download, ` +\n `or install an OS-level trigger (\\`brctl download \"${path}\"\\`).`,\n )\n }\n\n async function detectConflict(vault: string): Promise<string | null> {\n const target = fileName(vault, suffix)\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n for (const entry of entries) {\n if (isConflictCopy(entry, target)) return entry\n }\n return null\n }\n\n function versionOf(stat: { mtimeMs: number; size: number }): string {\n // mtime-based opaque token — sufficient for OCC within a single\n // syncing agent. iCloud's native conflict file machinery provides\n // the cross-agent guard.\n return `${stat.mtimeMs}-${stat.size}`\n }\n\n return {\n kind: 'bundle',\n name: 'icloud',\n\n async readBundle(vaultId) {\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n if (!stat) {\n // Perhaps only a stub exists — detect and trigger.\n const stubStat = await fs.stat(`${path}.icloud`)\n if (!stubStat) return null\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n const redoStat = await fs.stat(path)\n if (!redoStat) throw new Error(`icloud: file vanished after download at ${path}`)\n return { bytes, version: versionOf(redoStat) }\n }\n const bytes = await stubAwareRead(path)\n if (!bytes) return null\n return { bytes, version: versionOf(stat) }\n },\n\n async writeBundle(vaultId, bytes, expectedVersion) {\n // Conflict file present → refuse; caller merges.\n const conflict = await detectConflict(vaultId)\n if (conflict) {\n throw new BundleVersionConflictError(\n `iCloud conflict file detected alongside \"${vaultId}${suffix}\": \"${conflict}\". ` +\n `Open iCloud Drive, resolve the conflict, then retry.`,\n )\n }\n const path = await pathFor(vaultId)\n const stat = await fs.stat(path)\n const current = stat ? versionOf(stat) : null\n if (expectedVersion !== null && current !== null && expectedVersion !== current) {\n throw new BundleVersionConflictError(\n `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`,\n )\n }\n await fs.writeFile(path, bytes)\n const newStat = await fs.stat(path)\n if (!newStat) throw new Error(`icloud: write reported success but stat failed at ${path}`)\n return { version: versionOf(newStat) }\n },\n\n async deleteBundle(vaultId) {\n const path = await pathFor(vaultId)\n try {\n await fs.unlink(path)\n } catch {\n // Idempotent\n }\n },\n\n async listBundles() {\n const entries = await fs.readdir(dir).catch(() => [] as string[])\n const out: Array<{ vaultId: string; version: string; size: number }> = []\n for (const entry of entries) {\n if (!entry.endsWith(suffix) || isStub(entry)) continue\n const vaultId = entry.slice(0, -suffix.length)\n const stat = await fs.stat(`${dir}/${entry}`)\n if (!stat) continue\n out.push({ vaultId, version: versionOf(stat), size: stat.size })\n }\n return out\n },\n }\n}\n\n/**\n * Wire a Node `fs/promises` implementation as an `ICloudFs`. Dynamic\n * import keeps the package browser-loadable (the caller's bundler\n * prunes the Node path).\n */\nexport async function nodeFs(): Promise<ICloudFs> {\n const fs = await import('node:fs/promises')\n const { spawn } = await import('node:child_process')\n return {\n async readFile(path) {\n try {\n return await fs.readFile(path)\n } catch {\n return null\n }\n },\n async writeFile(path, data) {\n await fs.writeFile(path, data)\n },\n async unlink(path) {\n await fs.unlink(path).catch(() => undefined)\n },\n async readdir(path) {\n return fs.readdir(path)\n },\n async stat(path) {\n try {\n const s = await fs.stat(path)\n return { mtimeMs: s.mtimeMs, size: s.size }\n } catch {\n return null\n }\n },\n async triggerDownload(path) {\n // macOS: `brctl download` forces iCloud to materialise a stub.\n await new Promise<void>((resolve) => {\n const child = spawn('brctl', ['download', path.replace(/\\.icloud$/, '')])\n child.on('close', () => resolve())\n child.on('error', () => resolve())\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyCA,iBAA2C;AAGpC,IAAM,iBAAiB;AAqB9B,SAAS,SAAS,OA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AAM,QAAQ,MAAM;AAClB,aAAO,GAAG,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA,MAAM,KAAK,MAAM;AACf,UAAI;AACF,cAAM,IAAI,MAAM,GAAG,KAAK,IAAI;AAC5B,eAAO,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,KAAK;AAAA,MAC5C,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,MAAM,gBAAgB,MAAM;AAE1B,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,cAAM,QAAQ,MAAM,SAAS,CAAC,YAAY,KAAK,QAAQ,aAAa,EAAE,CAAC,CAAC;AACxE,cAAM,GAAG,SAAS,MAAM,QAAQ,CAAC;AACjC,cAAM,GAAG,SAAS,MAAM,QAAQ,CAAC;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["bytes"]}
package/dist/index.d.cts DELETED
@@ -1,77 +0,0 @@
1
- import { NoydbBundleStore } from '@noy-db/hub';
2
-
3
- /**
4
- * **@noy-db/to-icloud** — iCloud Drive bundle store for noy-db.
5
- *
6
- * Treats each vault as a single `.noydb` bundle stored under
7
- * `~/Library/Mobile Documents/…` (or any user-chosen iCloud path).
8
- * Pair with `wrapBundleStore()` from `@noy-db/hub` to get the
9
- * standard six-method `NoydbStore` surface.
10
- *
11
- * ## Why a dedicated package if `to-file` "works"?
12
- *
13
- * `@noy-db/to-file` pointed at an iCloud Drive directory technically
14
- * works — until one of three iCloud-specific behaviors bites you:
15
- *
16
- * 1. **On-demand eviction.** iCloud may evict the file to cloud-only
17
- * storage, leaving a `.icloud` stub. `readFile()` on the stub
18
- * either throws ENOENT or returns stub metadata. This store
19
- * detects the stub, nudges the OS to redownload (via `xattr` on
20
- * macOS), and retries.
21
- * 2. **Conflict files.** Parallel writes from two devices create
22
- * `name (device conflicted copy DATE).noydb`. This store detects
23
- * those files and raises `BundleVersionConflictError`, giving the
24
- * caller a chance to merge deliberately.
25
- * 3. **Sync-not-yet-complete writes.** A completed `writeFile()` does
26
- * not mean the bytes are on Apple's servers. `ping()` reports
27
- * on upload status so callers can wait before considering a
28
- * write durable.
29
- *
30
- * ## Scope
31
- *
32
- * - **Node (macOS) only for v1.** Browser / iOS consumers go through
33
- * CloudKit JS — a separate package will ship as `@noy-db/to-cloudkit`.
34
- * - **Bundle granularity** — whole vault in one file. Pair with
35
- * `syncPolicy: { push: { mode: 'debounce', 30_000 } }` so every
36
- * record mutation doesn't trigger a full bundle upload.
37
- * - **No extra auth** — iCloud syncs via the user's signed-in Apple ID;
38
- * the store never sees credentials.
39
- *
40
- * @packageDocumentation
41
- */
42
-
43
- /** Default iCloud Drive folder name inside a user's mobile-documents tree. */
44
- declare const DEFAULT_FOLDER = "NoyDB";
45
- interface ICloudFs {
46
- readFile(path: string): Promise<Uint8Array | Buffer | null>;
47
- writeFile(path: string, data: Uint8Array): Promise<void>;
48
- unlink(path: string): Promise<void>;
49
- readdir(path: string): Promise<string[]>;
50
- stat(path: string): Promise<{
51
- mtimeMs: number;
52
- size: number;
53
- } | null>;
54
- /** macOS-only: force iCloud to materialise an evicted `.icloud` stub. */
55
- triggerDownload?(path: string): Promise<void>;
56
- }
57
- interface ICloudStoreOptions {
58
- /** Absolute path to the iCloud Drive folder that holds bundles. */
59
- readonly folder: string;
60
- /** File-system facade — swap in a mock or a cross-platform shim. */
61
- readonly fs: ICloudFs;
62
- /** Bundle filename suffix. Default `'.noydb'`. */
63
- readonly suffix?: string;
64
- }
65
- /**
66
- * Build a `NoydbBundleStore` over an iCloud Drive folder. Wrap with
67
- * `wrapBundleStore()` to consume via `createNoydb({ store })`.
68
- */
69
- declare function icloud(options: ICloudStoreOptions): NoydbBundleStore;
70
- /**
71
- * Wire a Node `fs/promises` implementation as an `ICloudFs`. Dynamic
72
- * import keeps the package browser-loadable (the caller's bundler
73
- * prunes the Node path).
74
- */
75
- declare function nodeFs(): Promise<ICloudFs>;
76
-
77
- export { DEFAULT_FOLDER, type ICloudFs, type ICloudStoreOptions, icloud, nodeFs };