@noy-db/as-blob 0.7.0 → 0.8.0-pre.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
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.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 vLannaAi
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1 @@
1
+ noy-db — Copyright 2026 vLannaAi
package/README.md CHANGED
@@ -5,7 +5,7 @@ a record's `BlobSet` as its native MIME bytes — PDF, JPEG, `.eml`,
5
5
  anything you stored via `collection.blob(id).put(slot, bytes, …)`.
6
6
 
7
7
  Part of the `@noy-db/as-*` portable-artefact family, plaintext tier,
8
- document sub-family. See [`docs/packages-exports.md#authorization-model`](https://github.com/vLannaAi/noy-db/blob/main/docs/packages-exports.md#authorization-model)
8
+ document sub-family. See [`docs/packages-exports.md#authorization-model`](https://github.com/noy-db/core/blob/main/docs/packages-exports.md#authorization-model)
9
9
  for the four-tier model and authorisation matrix.
10
10
 
11
11
  ## Install
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ import { Vault } from '@noy-db/hub';
20
20
  * **Scope.** One blob per call. Multi-record / multi-blob archive →
21
21
  * use `@noy-db/as-zip`.
22
22
  *
23
- * See [`docs/patterns/as-exports.md`](https://github.com/vLannaAi/noy-db/blob/main/docs/patterns/as-exports.md).
23
+ * See [`docs/patterns/as-exports.md`](https://github.com/noy-db/core/blob/main/docs/patterns/as-exports.md).
24
24
  *
25
25
  * @packageDocumentation
26
26
  */
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/as-blob** — single-attachment plaintext export for noy-db.\n *\n * Extracts one blob from a record's `BlobSet` as its native MIME\n * bytes. Part of the `@noy-db/as-*` portable-artefact family —\n * plaintext tier, document sub-family. Handles the \"download this\n * PDF\" / \"export this scan\" primitive that a record-formatter\n * (`as-csv`, `as-xlsx`) can't cover — structured data vs binary\n * bytes are different shapes with the same egress gate.\n *\n * **Authorization.** Every call is gated by the invoking keyring's\n * `assertCanExport('plaintext', …)` gate with format `'blob'`.\n * Decrypted bytes crossing the plaintext boundary require an\n * explicit grant from the vault owner; the package calls\n * `vault.assertCanExport('plaintext', 'blob')` before loading any\n * chunks from the store.\n *\n * **Scope.** One blob per call. Multi-record / multi-blob archive →\n * use `@noy-db/as-zip`.\n *\n * See [`docs/patterns/as-exports.md`](https://github.com/vLannaAi/noy-db/blob/main/docs/patterns/as-exports.md).\n *\n * @packageDocumentation\n */\n\nimport type { Vault } from '@noy-db/hub'\n\n/** Inputs shared by every `as-blob` entry point. */\nexport interface AsBlobOptions {\n /** Collection the record lives in. Must be in the caller's read ACL. */\n readonly collection: string\n /** Record id. */\n readonly id: string\n /**\n * Slot name within the record's `BlobSet`. Defaults to `'raw'` —\n * the convention used by scan/attachment workflows where each\n * record has a single primary blob.\n */\n readonly slot?: string\n}\n\n/** Options for `download()` — adds an optional filename override. */\nexport interface AsBlobDownloadOptions extends AsBlobOptions {\n /**\n * Filename offered to the browser download prompt. When omitted,\n * falls back to the `SlotRecord.filename` stored at upload time,\n * then to `<slotName>.bin`.\n */\n readonly filename?: string\n}\n\n/** Options for `write()` — requires explicit risk acknowledgement. */\nexport interface AsBlobWriteOptions extends AsBlobOptions {\n /**\n * Required for Node file-write calls — consumer acknowledgement\n * that plaintext bytes will persist on disk past the current\n * process lifetime (Tier 3 risk per `docs/patterns/as-exports.md`).\n */\n readonly acknowledgeRisks: true\n}\n\n/** Return shape from `toBytes()` — raw bytes plus the inferred MIME + filename. */\nexport interface AsBlobResult {\n /** Decrypted blob bytes in their native MIME form. */\n readonly bytes: Uint8Array\n /** MIME type, or `'application/octet-stream'` if none was stored. */\n readonly mime: string\n /** Filename stored at upload time, or `<slotName>.bin`. */\n readonly filename: string\n}\n\n/**\n * Thrown when the requested record or slot isn't found in the vault.\n * Distinct from the hub's `NotFoundError` so callers can match the\n * export-path specifically.\n */\nexport class AsBlobNotFoundError extends Error {\n readonly collection: string\n readonly id: string\n readonly slot: string\n\n constructor(collection: string, id: string, slot: string) {\n super(\n `as-blob: no blob at ${collection}/${id}[slot=${slot}]. Record may not ` +\n `exist, slot may be unset, or the caller's ACL may not include this collection.`,\n )\n this.name = 'AsBlobNotFoundError'\n this.collection = collection\n this.id = id\n this.slot = slot\n }\n}\n\nconst DEFAULT_SLOT = 'raw'\n\n/**\n * Decrypt and return the blob bytes plus MIME + filename metadata.\n * Pure — no I/O beyond the authorization check, slot lookup, and\n * chunk fetch. The caller decides where the bytes go.\n */\nexport async function toBytes(\n vault: Vault,\n options: AsBlobOptions,\n): Promise<AsBlobResult> {\n vault.assertCanExport('plaintext', 'blob')\n\n const slotName = options.slot ?? DEFAULT_SLOT\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const collection = vault.collection<any>(options.collection)\n const blobSet = collection.blob(options.id)\n\n // Look up slot metadata FIRST so we can surface a precise error\n // without triggering an extra chunk fetch for the missing case.\n const slots = await blobSet.list()\n const slot = slots.find((s) => s.name === slotName)\n if (!slot) {\n throw new AsBlobNotFoundError(options.collection, options.id, slotName)\n }\n\n const bytes = await blobSet.get(slotName)\n if (!bytes) {\n throw new AsBlobNotFoundError(options.collection, options.id, slotName)\n }\n\n return {\n bytes,\n mime: slot.mimeType ?? 'application/octet-stream',\n filename: slot.filename ?? `${slotName}.bin`,\n }\n}\n\n/**\n * Browser download — wraps `toBytes()` in a `Blob` and triggers the\n * browser's download prompt. Tier 2 egress per the pattern doc:\n * plaintext bytes leave memory, but the lifetime is scoped to the\n * user's chosen destination (usually the OS download folder).\n *\n * Requires a browser-like environment with `URL.createObjectURL`\n * and `document.createElement`. Throws on headless runtimes — use\n * `toBytes()` there and pipe the bytes wherever you need.\n */\nexport async function download(\n vault: Vault,\n options: AsBlobDownloadOptions,\n): Promise<void> {\n const { bytes, mime, filename } = await toBytes(vault, options)\n const finalName = options.filename ?? filename\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const blob = new Blob([bytes as any], { type: mime })\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = finalName\n a.click()\n URL.revokeObjectURL(url)\n}\n\n/**\n * Node file-write — persists the blob bytes to the filesystem.\n * Requires explicit `acknowledgeRisks: true` because the plaintext\n * file outlives the current process (Tier 3 egress). The\n * authorization check still runs even when the consumer\n * acknowledges — capability bits aren't bypassable.\n */\nexport async function write(\n vault: Vault,\n path: string,\n options: AsBlobWriteOptions,\n): Promise<void> {\n if (options.acknowledgeRisks !== true) {\n throw new Error(\n 'as-blob.write: acknowledgeRisks: true is required for on-disk plaintext output. ' +\n 'This call creates a persistent plaintext copy of the blob outside noy-db\\'s ' +\n 'encrypted storage — see docs/patterns/as-exports.md §\"The three tiers of \\\\\"plaintext out\\\\\"\"',\n )\n }\n const { bytes } = await toBytes(vault, options)\n // Defer the node:fs import so this package remains browser-safe.\n const { writeFile } = await import('node:fs/promises')\n await writeFile(path, bytes)\n}\n\n// ─── Reader ──────────────────────────────────\n\n/**\n * `merge` has no meaning for a single-slot write — only `replace`\n * (overwrite if present) and `insert-only` (refuse if present) make\n * sense. Default is `replace`.\n */\nexport type AsBlobImportPolicy = 'replace' | 'insert-only'\n\nexport interface AsBlobImportOptions {\n /** Collection the target record lives in. */\n readonly collection: string\n /** Record id. The record must already exist. */\n readonly id: string\n /** Slot name. Defaults to `'raw'` (matches `toBytes`). */\n readonly slot?: string\n /** Default `'replace'`. */\n readonly policy?: AsBlobImportPolicy\n /**\n * Optional MIME hint stored on the slot. When omitted the blob layer\n * sniffs the magic bytes — same fallback as a direct `blob.put()`.\n */\n readonly mimeType?: string\n /** Optional filename stored on the slot. */\n readonly filename?: string\n}\n\nexport interface AsBlobImportPlan {\n /** Whether the slot was empty (`'added'`) or already populated (`'modified'`). */\n readonly status: 'added' | 'modified'\n /** Pre-existing eTag when `status === 'modified'`, otherwise undefined. */\n readonly priorETag?: string\n readonly collection: string\n readonly id: string\n readonly slot: string\n /** Plaintext byte count of the incoming blob. */\n readonly bytes: number\n readonly policy: AsBlobImportPolicy\n apply(): Promise<void>\n}\n\n/**\n * Build an import plan for a single attachment. Returns a plan that\n * surfaces whether the target slot exists today (`status: 'added' |\n * 'modified'`); calling `apply()` performs the write.\n *\n * Authorization: gated by `assertCanImport('plaintext', 'blob')`.\n *\n * Errors:\n * - `ImportCapabilityError` — keyring lacks the import capability.\n * - `Error('as-blob.fromBytes: record ... not found')` — the target\n * record id does not exist in the collection. We refuse to attach\n * to a phantom record because the slot index would orphan.\n * - `Error('as-blob.fromBytes: insert-only ...')` — `policy:\n * 'insert-only'` and the slot is already populated.\n */\nexport async function fromBytes(\n vault: Vault,\n bytes: Uint8Array,\n options: AsBlobImportOptions,\n): Promise<AsBlobImportPlan> {\n vault.assertCanImport('plaintext', 'blob')\n\n const slotName = options.slot ?? DEFAULT_SLOT\n const policy: AsBlobImportPolicy = options.policy ?? 'replace'\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const collection = vault.collection<any>(options.collection)\n\n // Refuse to attach to a non-existent record — would leave an orphan\n // slot entry pointing at no record.\n const record = await collection.get(options.id)\n if (record === null) {\n throw new Error(\n `as-blob.fromBytes: record ${options.collection}/${options.id} not found. ` +\n 'The target record must exist before attaching a blob.',\n )\n }\n\n const blobSet = collection.blob(options.id)\n const slots = await blobSet.list()\n const existing = slots.find((s) => s.name === slotName)\n const status: 'added' | 'modified' = existing ? 'modified' : 'added'\n\n if (policy === 'insert-only' && existing) {\n throw new Error(\n `as-blob.fromBytes: insert-only refused — slot ${slotName} on ` +\n `${options.collection}/${options.id} is already populated. ` +\n \"Pass `policy: 'replace'` to overwrite.\",\n )\n }\n\n return {\n status,\n ...(existing?.eTag !== undefined ? { priorETag: existing.eTag } : {}),\n collection: options.collection,\n id: options.id,\n slot: slotName,\n bytes: bytes.byteLength,\n policy,\n async apply(): Promise<void> {\n const writeOpts: { mimeType?: string; filename?: string } = {}\n if (options.mimeType !== undefined) writeOpts.mimeType = options.mimeType\n if (options.filename !== undefined) writeOpts.filename = options.filename\n await blobSet.put(slotName, bytes, writeOpts)\n },\n }\n}\n"],"mappings":";AA4EO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,YAAoB,IAAY,MAAc;AACxD;AAAA,MACE,uBAAuB,UAAU,IAAI,EAAE,SAAS,IAAI;AAAA,IAEtD;AACA,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,KAAK;AACV,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,eAAe;AAOrB,eAAsB,QACpB,OACA,SACuB;AACvB,QAAM,gBAAgB,aAAa,MAAM;AAEzC,QAAM,WAAW,QAAQ,QAAQ;AAEjC,QAAM,aAAa,MAAM,WAAgB,QAAQ,UAAU;AAC3D,QAAM,UAA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AGrD,QAAM,aAAa,MAAM,WAAgB,QAAQ,UAAU;AAI3D,QAAM,SAAS,MAAM,WAAW,IAAI,QAAQ,EAAE;AAC9C,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI;AAAA,MACR,6BAA6B,QAAQ,UAAU,IAAI,QAAQ,EAAE;AAAA,IAE/D;AAAA,EACF;AAEA,QAAM,UAAU,WAAW,KAAK,QAAQ,EAAE;AAC1C,QAAM,QAAQ,MAAM,QAAQ,KAAK;AACjC,QAAM,WAAW,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,QAAQ;AACtD,QAAM,SAA+B,WAAW,aAAa;AAE7D,MAAI,WAAW,iBAAiB,UAAU;AACxC,UAAM,IAAI;AAAA,MACR,sDAAiD,QAAQ,OACpD,QAAQ,UAAU,IAAI,QAAQ,EAAE;AAAA,IAEvC;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,GAAI,UAAU,SAAS,SAAY,EAAE,WAAW,SAAS,KAAK,IAAI,CAAC;AAAA,IACnE,YAAY,QAAQ;AAAA,IACpB,IAAI,QAAQ;AAAA,IACZ,MAAM;AAAA,IACN,OAAO,MAAM;AAAA,IACb;AAAA,IACA,MAAM,QAAuB;AAC3B,YAAM,YAAsD,CAAC;AAC7D,UAAI,QAAQ,aAAa,OAAW,WAAU,WAAW,QAAQ;AACjE,UAAI,QAAQ,aAAa,OAAW,WAAU,WAAW,QAAQ;AACjE,YAAM,QAAQ,IAAI,UAAU,OAAO,SAAS;AAAA,IAC9C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/as-blob** — single-attachment plaintext export for noy-db.\n *\n * Extracts one blob from a record's `BlobSet` as its native MIME\n * bytes. Part of the `@noy-db/as-*` portable-artefact family —\n * plaintext tier, document sub-family. Handles the \"download this\n * PDF\" / \"export this scan\" primitive that a record-formatter\n * (`as-csv`, `as-xlsx`) can't cover — structured data vs binary\n * bytes are different shapes with the same egress gate.\n *\n * **Authorization.** Every call is gated by the invoking keyring's\n * `assertCanExport('plaintext', …)` gate with format `'blob'`.\n * Decrypted bytes crossing the plaintext boundary require an\n * explicit grant from the vault owner; the package calls\n * `vault.assertCanExport('plaintext', 'blob')` before loading any\n * chunks from the store.\n *\n * **Scope.** One blob per call. Multi-record / multi-blob archive →\n * use `@noy-db/as-zip`.\n *\n * See [`docs/patterns/as-exports.md`](https://github.com/noy-db/core/blob/main/docs/patterns/as-exports.md).\n *\n * @packageDocumentation\n */\n\nimport type { Vault } from '@noy-db/hub'\n\n/** Inputs shared by every `as-blob` entry point. */\nexport interface AsBlobOptions {\n /** Collection the record lives in. Must be in the caller's read ACL. */\n readonly collection: string\n /** Record id. */\n readonly id: string\n /**\n * Slot name within the record's `BlobSet`. Defaults to `'raw'` —\n * the convention used by scan/attachment workflows where each\n * record has a single primary blob.\n */\n readonly slot?: string\n}\n\n/** Options for `download()` — adds an optional filename override. */\nexport interface AsBlobDownloadOptions extends AsBlobOptions {\n /**\n * Filename offered to the browser download prompt. When omitted,\n * falls back to the `SlotRecord.filename` stored at upload time,\n * then to `<slotName>.bin`.\n */\n readonly filename?: string\n}\n\n/** Options for `write()` — requires explicit risk acknowledgement. */\nexport interface AsBlobWriteOptions extends AsBlobOptions {\n /**\n * Required for Node file-write calls — consumer acknowledgement\n * that plaintext bytes will persist on disk past the current\n * process lifetime (Tier 3 risk per `docs/patterns/as-exports.md`).\n */\n readonly acknowledgeRisks: true\n}\n\n/** Return shape from `toBytes()` — raw bytes plus the inferred MIME + filename. */\nexport interface AsBlobResult {\n /** Decrypted blob bytes in their native MIME form. */\n readonly bytes: Uint8Array\n /** MIME type, or `'application/octet-stream'` if none was stored. */\n readonly mime: string\n /** Filename stored at upload time, or `<slotName>.bin`. */\n readonly filename: string\n}\n\n/**\n * Thrown when the requested record or slot isn't found in the vault.\n * Distinct from the hub's `NotFoundError` so callers can match the\n * export-path specifically.\n */\nexport class AsBlobNotFoundError extends Error {\n readonly collection: string\n readonly id: string\n readonly slot: string\n\n constructor(collection: string, id: string, slot: string) {\n super(\n `as-blob: no blob at ${collection}/${id}[slot=${slot}]. Record may not ` +\n `exist, slot may be unset, or the caller's ACL may not include this collection.`,\n )\n this.name = 'AsBlobNotFoundError'\n this.collection = collection\n this.id = id\n this.slot = slot\n }\n}\n\nconst DEFAULT_SLOT = 'raw'\n\n/**\n * Decrypt and return the blob bytes plus MIME + filename metadata.\n * Pure — no I/O beyond the authorization check, slot lookup, and\n * chunk fetch. The caller decides where the bytes go.\n */\nexport async function toBytes(\n vault: Vault,\n options: AsBlobOptions,\n): Promise<AsBlobResult> {\n vault.assertCanExport('plaintext', 'blob')\n\n const slotName = options.slot ?? DEFAULT_SLOT\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const collection = vault.collection<any>(options.collection)\n const blobSet = collection.blob(options.id)\n\n // Look up slot metadata FIRST so we can surface a precise error\n // without triggering an extra chunk fetch for the missing case.\n const slots = await blobSet.list()\n const slot = slots.find((s) => s.name === slotName)\n if (!slot) {\n throw new AsBlobNotFoundError(options.collection, options.id, slotName)\n }\n\n const bytes = await blobSet.get(slotName)\n if (!bytes) {\n throw new AsBlobNotFoundError(options.collection, options.id, slotName)\n }\n\n return {\n bytes,\n mime: slot.mimeType ?? 'application/octet-stream',\n filename: slot.filename ?? `${slotName}.bin`,\n }\n}\n\n/**\n * Browser download — wraps `toBytes()` in a `Blob` and triggers the\n * browser's download prompt. Tier 2 egress per the pattern doc:\n * plaintext bytes leave memory, but the lifetime is scoped to the\n * user's chosen destination (usually the OS download folder).\n *\n * Requires a browser-like environment with `URL.createObjectURL`\n * and `document.createElement`. Throws on headless runtimes — use\n * `toBytes()` there and pipe the bytes wherever you need.\n */\nexport async function download(\n vault: Vault,\n options: AsBlobDownloadOptions,\n): Promise<void> {\n const { bytes, mime, filename } = await toBytes(vault, options)\n const finalName = options.filename ?? filename\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const blob = new Blob([bytes as any], { type: mime })\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = finalName\n a.click()\n URL.revokeObjectURL(url)\n}\n\n/**\n * Node file-write — persists the blob bytes to the filesystem.\n * Requires explicit `acknowledgeRisks: true` because the plaintext\n * file outlives the current process (Tier 3 egress). The\n * authorization check still runs even when the consumer\n * acknowledges — capability bits aren't bypassable.\n */\nexport async function write(\n vault: Vault,\n path: string,\n options: AsBlobWriteOptions,\n): Promise<void> {\n if (options.acknowledgeRisks !== true) {\n throw new Error(\n 'as-blob.write: acknowledgeRisks: true is required for on-disk plaintext output. ' +\n 'This call creates a persistent plaintext copy of the blob outside noy-db\\'s ' +\n 'encrypted storage — see docs/patterns/as-exports.md §\"The three tiers of \\\\\"plaintext out\\\\\"\"',\n )\n }\n const { bytes } = await toBytes(vault, options)\n // Defer the node:fs import so this package remains browser-safe.\n const { writeFile } = await import('node:fs/promises')\n await writeFile(path, bytes)\n}\n\n// ─── Reader ──────────────────────────────────\n\n/**\n * `merge` has no meaning for a single-slot write — only `replace`\n * (overwrite if present) and `insert-only` (refuse if present) make\n * sense. Default is `replace`.\n */\nexport type AsBlobImportPolicy = 'replace' | 'insert-only'\n\nexport interface AsBlobImportOptions {\n /** Collection the target record lives in. */\n readonly collection: string\n /** Record id. The record must already exist. */\n readonly id: string\n /** Slot name. Defaults to `'raw'` (matches `toBytes`). */\n readonly slot?: string\n /** Default `'replace'`. */\n readonly policy?: AsBlobImportPolicy\n /**\n * Optional MIME hint stored on the slot. When omitted the blob layer\n * sniffs the magic bytes — same fallback as a direct `blob.put()`.\n */\n readonly mimeType?: string\n /** Optional filename stored on the slot. */\n readonly filename?: string\n}\n\nexport interface AsBlobImportPlan {\n /** Whether the slot was empty (`'added'`) or already populated (`'modified'`). */\n readonly status: 'added' | 'modified'\n /** Pre-existing eTag when `status === 'modified'`, otherwise undefined. */\n readonly priorETag?: string\n readonly collection: string\n readonly id: string\n readonly slot: string\n /** Plaintext byte count of the incoming blob. */\n readonly bytes: number\n readonly policy: AsBlobImportPolicy\n apply(): Promise<void>\n}\n\n/**\n * Build an import plan for a single attachment. Returns a plan that\n * surfaces whether the target slot exists today (`status: 'added' |\n * 'modified'`); calling `apply()` performs the write.\n *\n * Authorization: gated by `assertCanImport('plaintext', 'blob')`.\n *\n * Errors:\n * - `ImportCapabilityError` — keyring lacks the import capability.\n * - `Error('as-blob.fromBytes: record ... not found')` — the target\n * record id does not exist in the collection. We refuse to attach\n * to a phantom record because the slot index would orphan.\n * - `Error('as-blob.fromBytes: insert-only ...')` — `policy:\n * 'insert-only'` and the slot is already populated.\n */\nexport async function fromBytes(\n vault: Vault,\n bytes: Uint8Array,\n options: AsBlobImportOptions,\n): Promise<AsBlobImportPlan> {\n vault.assertCanImport('plaintext', 'blob')\n\n const slotName = options.slot ?? DEFAULT_SLOT\n const policy: AsBlobImportPolicy = options.policy ?? 'replace'\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const collection = vault.collection<any>(options.collection)\n\n // Refuse to attach to a non-existent record — would leave an orphan\n // slot entry pointing at no record.\n const record = await collection.get(options.id)\n if (record === null) {\n throw new Error(\n `as-blob.fromBytes: record ${options.collection}/${options.id} not found. ` +\n 'The target record must exist before attaching a blob.',\n )\n }\n\n const blobSet = collection.blob(options.id)\n const slots = await blobSet.list()\n const existing = slots.find((s) => s.name === slotName)\n const status: 'added' | 'modified' = existing ? 'modified' : 'added'\n\n if (policy === 'insert-only' && existing) {\n throw new Error(\n `as-blob.fromBytes: insert-only refused — slot ${slotName} on ` +\n `${options.collection}/${options.id} is already populated. ` +\n \"Pass `policy: 'replace'` to overwrite.\",\n )\n }\n\n return {\n status,\n ...(existing?.eTag !== undefined ? { priorETag: existing.eTag } : {}),\n collection: options.collection,\n id: options.id,\n slot: slotName,\n bytes: bytes.byteLength,\n policy,\n async apply(): Promise<void> {\n const writeOpts: { mimeType?: string; filename?: string } = {}\n if (options.mimeType !== undefined) writeOpts.mimeType = options.mimeType\n if (options.filename !== undefined) write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,IACA,MAAM,QAAuB;AAC3B,YAAM,YAAsD,CAAC;AAC7D,UAAI,QAAQ,aAAa,OAAW,WAAU,WAAW,QAAQ;AACjE,UAAI,QAAQ,aAAa,OAAW,WAAU,WAAW,QAAQ;AACjE,YAAM,QAAQ,IAAI,UAAU,OAAO,SAAS;AAAA,IAC9C;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@noy-db/as-blob",
3
- "version": "0.7.0",
3
+ "version": "0.8.0-pre.0",
4
4
  "description": "Single-attachment plaintext export for noy-db — extracts one blob from BlobSet as native MIME bytes. Gated by the RFC #249 `assertCanExport('plaintext', …)` gate; writes an audit-ledger entry on every call. Part of the @noy-db/as-* portable-artefact family (plaintext tier, document sub-family).",
5
- "license": "MIT",
5
+ "license": "Apache-2.0",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
7
- "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/as-blob#readme",
7
+ "homepage": "https://github.com/noy-db/as/tree/main/as-blob#readme",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/vLannaAi/noy-db.git",
11
- "directory": "packages/as-blob"
10
+ "url": "git+https://github.com/noy-db/as.git",
11
+ "directory": "as-blob"
12
12
  },
13
13
  "bugs": {
14
- "url": "https://github.com/vLannaAi/noy-db/issues"
14
+ "url": "https://github.com/noy-db/as/issues"
15
15
  },
16
16
  "type": "module",
17
17
  "sideEffects": false,
@@ -26,20 +26,21 @@
26
26
  "files": [
27
27
  "dist",
28
28
  "README.md",
29
- "LICENSE"
29
+ "LICENSE",
30
+ "NOTICE"
30
31
  ],
31
32
  "engines": {
32
33
  "node": ">=22.0.0"
33
34
  },
34
35
  "peerDependencies": {
35
- "@noy-db/hub": "^0.7.0"
36
+ "@noy-db/hub": "^0.7.0 || ^0.7.1-pre.0 || ^0.8.0-pre.0"
36
37
  },
37
38
  "devDependencies": {
39
+ "@noy-db/hub": "0.8.0-pre.0",
40
+ "@noy-db/test-format-conformance": "0.8.0-pre.0",
41
+ "@noy-db/to-memory": "0.8.0-pre.0",
38
42
  "@types/node": "^22.0.0",
39
- "happy-dom": "^18.0.0",
40
- "@noy-db/hub": "0.7.0",
41
- "@noy-db/to-memory": "0.7.0",
42
- "@noy-db/test-format-conformance": "0.7.0"
43
+ "happy-dom": "^18.0.0"
43
44
  },
44
45
  "keywords": [
45
46
  "noy-db",