@noy-db/to-icloud 0.1.0-pre.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vLannaAi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # @noy-db/to-icloud
2
+
3
+ [![npm](https://img.shields.io/npm/v/%40noy-db/to-icloud.svg)](https://www.npmjs.com/package/@noy-db/to-icloud)
4
+
5
+ > iCloud Drive bundle store for noy-db
6
+
7
+ Part of [**`@noy-db/hub`**](https://www.npmjs.com/package/@noy-db/hub) — the zero-knowledge, offline-first, encrypted document store.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @noy-db/hub @noy-db/to-icloud
13
+ ```
14
+
15
+ ## What it is
16
+
17
+ 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.
18
+
19
+ ## Status
20
+
21
+ **Pre-release** (`0.1.0-pre.1`). API may change before `1.0`.
22
+
23
+ ## Documentation
24
+
25
+ See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup, examples, and the full subsystem catalog.
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)
29
+ - Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db/blob/main/SPEC.md)
30
+
31
+ ## License
32
+
33
+ [MIT](./LICENSE) © vLannaAi
package/dist/index.cjs ADDED
@@ -0,0 +1,185 @@
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
@@ -0,0 +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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyCA,iBAA2C;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;AAGrF,UAAM,WAAW,GAAG,IAAI;AACxB,UAAM,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,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"]}
@@ -0,0 +1,77 @@
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 };
@@ -0,0 +1,77 @@
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 };
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ // src/index.ts
2
+ import { BundleVersionConflictError } from "@noy-db/hub";
3
+ var DEFAULT_FOLDER = "NoyDB";
4
+ function fileName(vault, suffix) {
5
+ return `${vault}${suffix}`;
6
+ }
7
+ function isStub(name) {
8
+ return name.endsWith(".icloud");
9
+ }
10
+ function isConflictCopy(name, expected) {
11
+ return name.includes("'s conflicted copy") || name.includes("(conflicted copy") && name.endsWith(expected.slice(expected.lastIndexOf(".")));
12
+ }
13
+ function icloud(options) {
14
+ const suffix = options.suffix ?? ".noydb";
15
+ const dir = options.folder.replace(/\/+$/, "");
16
+ const { fs } = options;
17
+ async function pathFor(vault) {
18
+ return `${dir}/${fileName(vault, suffix)}`;
19
+ }
20
+ async function stubAwareRead(path) {
21
+ let bytes = await fs.readFile(path);
22
+ if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
23
+ const stubPath = `${path}.icloud`;
24
+ const stubExists = await fs.stat(stubPath);
25
+ if (!stubExists) return null;
26
+ if (fs.triggerDownload) {
27
+ await fs.triggerDownload(stubPath);
28
+ bytes = await fs.readFile(path);
29
+ if (bytes !== null) return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
30
+ }
31
+ throw new Error(
32
+ `iCloud file "${path}" is offloaded. Open the file in Finder to trigger a download, or install an OS-level trigger (\`brctl download "${path}"\`).`
33
+ );
34
+ }
35
+ async function detectConflict(vault) {
36
+ const target = fileName(vault, suffix);
37
+ const entries = await fs.readdir(dir).catch(() => []);
38
+ for (const entry of entries) {
39
+ if (isConflictCopy(entry, target)) return entry;
40
+ }
41
+ return null;
42
+ }
43
+ function versionOf(stat) {
44
+ return `${stat.mtimeMs}-${stat.size}`;
45
+ }
46
+ return {
47
+ kind: "bundle",
48
+ name: "icloud",
49
+ async readBundle(vaultId) {
50
+ const path = await pathFor(vaultId);
51
+ const stat = await fs.stat(path);
52
+ if (!stat) {
53
+ const stubStat = await fs.stat(`${path}.icloud`);
54
+ if (!stubStat) return null;
55
+ const bytes2 = await stubAwareRead(path);
56
+ if (!bytes2) return null;
57
+ const redoStat = await fs.stat(path);
58
+ if (!redoStat) throw new Error(`icloud: file vanished after download at ${path}`);
59
+ return { bytes: bytes2, version: versionOf(redoStat) };
60
+ }
61
+ const bytes = await stubAwareRead(path);
62
+ if (!bytes) return null;
63
+ return { bytes, version: versionOf(stat) };
64
+ },
65
+ async writeBundle(vaultId, bytes, expectedVersion) {
66
+ const conflict = await detectConflict(vaultId);
67
+ if (conflict) {
68
+ throw new BundleVersionConflictError(
69
+ `iCloud conflict file detected alongside "${vaultId}${suffix}": "${conflict}". Open iCloud Drive, resolve the conflict, then retry.`
70
+ );
71
+ }
72
+ const path = await pathFor(vaultId);
73
+ const stat = await fs.stat(path);
74
+ const current = stat ? versionOf(stat) : null;
75
+ if (expectedVersion !== null && current !== null && expectedVersion !== current) {
76
+ throw new BundleVersionConflictError(
77
+ `iCloud bundle version mismatch: expected ${expectedVersion}, found ${current}`
78
+ );
79
+ }
80
+ await fs.writeFile(path, bytes);
81
+ const newStat = await fs.stat(path);
82
+ if (!newStat) throw new Error(`icloud: write reported success but stat failed at ${path}`);
83
+ return { version: versionOf(newStat) };
84
+ },
85
+ async deleteBundle(vaultId) {
86
+ const path = await pathFor(vaultId);
87
+ try {
88
+ await fs.unlink(path);
89
+ } catch {
90
+ }
91
+ },
92
+ async listBundles() {
93
+ const entries = await fs.readdir(dir).catch(() => []);
94
+ const out = [];
95
+ for (const entry of entries) {
96
+ if (!entry.endsWith(suffix) || isStub(entry)) continue;
97
+ const vaultId = entry.slice(0, -suffix.length);
98
+ const stat = await fs.stat(`${dir}/${entry}`);
99
+ if (!stat) continue;
100
+ out.push({ vaultId, version: versionOf(stat), size: stat.size });
101
+ }
102
+ return out;
103
+ }
104
+ };
105
+ }
106
+ async function nodeFs() {
107
+ const fs = await import("fs/promises");
108
+ const { spawn } = await import("child_process");
109
+ return {
110
+ async readFile(path) {
111
+ try {
112
+ return await fs.readFile(path);
113
+ } catch {
114
+ return null;
115
+ }
116
+ },
117
+ async writeFile(path, data) {
118
+ await fs.writeFile(path, data);
119
+ },
120
+ async unlink(path) {
121
+ await fs.unlink(path).catch(() => void 0);
122
+ },
123
+ async readdir(path) {
124
+ return fs.readdir(path);
125
+ },
126
+ async stat(path) {
127
+ try {
128
+ const s = await fs.stat(path);
129
+ return { mtimeMs: s.mtimeMs, size: s.size };
130
+ } catch {
131
+ return null;
132
+ }
133
+ },
134
+ async triggerDownload(path) {
135
+ await new Promise((resolve) => {
136
+ const child = spawn("brctl", ["download", path.replace(/\.icloud$/, "")]);
137
+ child.on("close", () => resolve());
138
+ child.on("error", () => resolve());
139
+ });
140
+ }
141
+ };
142
+ }
143
+ export {
144
+ DEFAULT_FOLDER,
145
+ icloud,
146
+ nodeFs
147
+ };
148
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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;AAGrF,UAAM,WAAW,GAAG,IAAI;AACxB,UAAM,aAAa,MAAM,GAAG,KAAK,QAAQ;AACzC,QAAI,CAAC,WAAY,QAAO;AACxB,QAAI,GAAG,iBAAiB;AACtB,YAAM,GAAG,gBAAgB,QAAQ;AACjC,cAAQ,MAAM,GAAG,SAAS,IAAI;AAC9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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"]}
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@noy-db/to-icloud",
3
+ "version": "0.1.0-pre.3",
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
+ "license": "MIT",
6
+ "author": "vLannaAi <vicio@lanna.ai>",
7
+ "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/to-icloud#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vLannaAi/noy-db.git",
11
+ "directory": "packages/to-icloud"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/vLannaAi/noy-db/issues"
15
+ },
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
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
+ }
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "engines": {
39
+ "node": ">=18.0.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@noy-db/hub": "0.1.0-pre.3"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^22.0.0",
46
+ "@noy-db/hub": "0.1.0-pre.3"
47
+ },
48
+ "keywords": [
49
+ "noy-db",
50
+ "to-icloud",
51
+ "icloud",
52
+ "apple",
53
+ "macos",
54
+ "bundle",
55
+ "storage"
56
+ ],
57
+ "publishConfig": {
58
+ "access": "public",
59
+ "tag": "latest"
60
+ },
61
+ "scripts": {
62
+ "build": "tsup",
63
+ "test": "vitest run",
64
+ "lint": "eslint src/",
65
+ "typecheck": "tsc --noEmit"
66
+ }
67
+ }