pikelet-wasm 0.16.0 → 0.17.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.
@@ -191,75 +191,11 @@ export async function createInlineTransformerEmbedder({ declaration, vocabText,
191
191
  return { vector: pooled, text, windows };
192
192
  }
193
193
 
194
- // Per-word vectors from the same forward pass embed() already runs — the
195
- // kernel's outHidden buffer holds every token's final-layer hidden state
196
- // (encoder.cpp's encoder_forward does no pooling itself; JS pools it),
197
- // so this is not a second, slower embedding path: it is the same
198
- // forward pass, with the per-token buffer copied out and pooled per
199
- // WORD (via encodeWithWordMap's word alignment, merging WordPiece
200
- // sub-tokens like "quant"+"##ization" into one vector) instead of
201
- // discarded after sentence-level pooling. Used for MaxSim-style
202
- // token-level grounding (complete/retrieval-abstention.mjs, calibrate.
203
- // mjs), an alternative to coverage1's exact/stemmed word match that
204
- // measures semantic closeness instead of lexical identity — so a query
205
- // and passage that use different words for the same idea can still
206
- // ground each other, the case coverage1 structurally cannot handle.
207
- // Windowing/CLS-pooling limits mirror embed(): a word that falls past
208
- // the first window under CLS pooling, or past the last window under
209
- // mean pooling's cap, has no vector and is left out of the result.
210
- async function embedWords(text) {
211
- const { ids: allIds, wordOf: allWordOf, words } = tokenizer.encodeWithWordMap(String(text || ''));
212
- const interior = allIds.slice(1, -1);
213
- const interiorWordOf = allWordOf.slice(1, -1);
214
- const windowLen = maxSeq - 2;
215
- const windows = Math.max(1, Math.ceil(interior.length / windowLen));
216
- const windowsToEncode = usesClsPooling ? 1 : windows;
217
- // Accumulate per-word sums, then average — a word split into several
218
- // WordPiece pieces gets one vector, not several.
219
- const wordSums = words.map(() => new Float64Array(dim));
220
- const wordCounts = words.map(() => 0);
221
- for (let w = 0; w < windowsToEncode; w++) {
222
- const idSlice = interior.slice(w * windowLen, (w + 1) * windowLen);
223
- const wordOfSlice = interiorWordOf.slice(w * windowLen, (w + 1) * windowLen);
224
- const tokenIds = [allIds[0], ...idSlice, allIds[allIds.length - 1]];
225
- // The windowing above must never produce more tokens than the buffers
226
- // were sized for; fail closed instead of writing past them.
227
- if (tokenIds.length > maxSeq) {
228
- throw new Error(`inline encoder window is ${tokenIds.length} tokens for a ${maxSeq}-token buffer`);
229
- }
230
- new Int32Array(EM.HEAP32.buffer, idsPtr, tokenIds.length).set(tokenIds);
231
- const rc = EM._encoder_forward(blobPtr, idsPtr, tokenIds.length, hiddenPtr, 0, layers, bits);
232
- if (rc !== tokenIds.length) throw new Error(`inline encoder failed: ${rc}`);
233
- const hidden = new Float32Array(EM.HEAPF32.buffer, hiddenPtr, tokenIds.length * dim);
234
- // Offset by 1: tokenIds[0] is [CLS], so idSlice's tokens start at
235
- // hidden row 1, matching wordOfSlice's own indexing into idSlice.
236
- for (let t = 0; t < wordOfSlice.length; t++) {
237
- const wi = wordOfSlice[t];
238
- if (wi === -1) continue;
239
- const row = (t + 1) * dim;
240
- for (let d = 0; d < dim; d++) wordSums[wi][d] += hidden[row + d];
241
- wordCounts[wi]++;
242
- }
243
- }
244
- const vectors = new Map();
245
- for (let wi = 0; wi < words.length; wi++) {
246
- if (wordCounts[wi] === 0) continue;
247
- const v = new Float32Array(dim);
248
- let norm = 0;
249
- for (let d = 0; d < dim; d++) { v[d] = wordSums[wi][d] / wordCounts[wi]; norm += v[d] ** 2; }
250
- norm = Math.sqrt(norm) || 1;
251
- for (let d = 0; d < dim; d++) v[d] /= norm;
252
- vectors.set(words[wi], v);
253
- }
254
- return vectors;
255
- }
256
-
257
194
  const embedder = {
258
195
  declaration,
259
196
  dim,
260
197
  maxSeq,
261
198
  embed,
262
- embedWords,
263
199
  dispose() {
264
200
  EM._free(hiddenPtr);
265
201
  EM._free(idsPtr);
@@ -9,12 +9,9 @@
9
9
  //
10
10
  // 1. An encoder that can embed PASSAGES. A kind-3 base carries the teacher,
11
11
  // so a pack is sufficient to compile its own successors. A kind-2 base
12
- // names its encoder and the host supplies it. A KIND-1 base carries a
13
- // corpus-distilled QUERY encoder whose passages were embedded by a teacher
14
- // the artifact neither carries nor verifies — so a kind-1 base is readable
15
- // but NOT appendable, and append MUST refuse it.
16
- // 2. An ingestion declaration, because record granularity is part of what the
17
- // calibration saw and MUST NOT change mid-chain. A base compiled after
12
+ // names its encoder and the host supplies it.
13
+ // 2. An ingestion declaration, because record granularity is part of what
14
+ // the base's records mean and MUST NOT change mid-chain. A base compiled after
18
15
  // this profile carries `corpus.ingest`; an older one does not, and append
19
16
  // MUST refuse unless the operator asserts one.
20
17
  //
@@ -41,9 +38,6 @@ export const FORMAT_MAX_DEPTH = 16;
41
38
  * @returns {{appendable: true, encoderSource: 'pack'|'host', ingest: object, ingestAsserted: boolean}}
42
39
  */
43
40
  export function planAppendability({ qiKind, corpusIngest = null, assertIngest = null }) {
44
- if (qiKind === 1) {
45
- throw new Error('a kind-1 base carries a corpus-distilled query encoder whose passages were embedded by a teacher the artifact does not carry: readable, but not appendable (6.1)');
46
- }
47
41
  if (qiKind === 4) {
48
42
  throw new Error('a layer is not a base: append to the chain\'s head, whose base supplies the encoder (4.5)');
49
43
  }
@@ -176,18 +170,14 @@ export function planLayer({
176
170
  * The caller supplies the index/corpus/lexical segment bytes, since building
177
171
  * those is the existing builder's job.
178
172
  */
179
- export function buildLayerSegments({ plan, baseIdentity, parentIdentity, baseQueryInterpSha256, parentLocator = null, ingest, ingestAsserted, dim, metric, encoder, corpus, layerBloom = null }) {
173
+ export function buildLayerSegments({ plan, baseIdentity, parentIdentity, baseQueryInterpSha256, parentLocator = null, ingest, ingestAsserted, dim, metric, encoder, corpus }) {
180
174
  const tombstones = buildTombstoneSegment({
181
175
  rowBase: plan.rowBase,
182
176
  tombstonedIds: idsSetIn(plan.bitset, plan.rowBase),
183
177
  supersessions: plan.supersessions,
184
178
  records: plan.records,
185
179
  });
186
- const queryInterp = buildInheritedQuerySegment({
187
- baseIdentity, queryInterpSha256: baseQueryInterpSha256,
188
- vocabBloom: layerBloom ? layerBloom.geometry : null,
189
- vocabBloomBytes: layerBloom ? layerBloom.bytes : null,
190
- });
180
+ const queryInterp = buildInheritedQuerySegment({ baseIdentity, queryInterpSha256: baseQueryInterpSha256 });
191
181
  const manifestFields = {
192
182
  profile: 'pikelet-layer-v1',
193
183
  dim, metric, encoder,
@@ -216,22 +206,6 @@ export function buildLayerSegments({ plan, baseIdentity, parentIdentity, baseQue
216
206
  return { manifestFields, tombstones, queryInterp };
217
207
  }
218
208
 
219
- /**
220
- * The drift an append would produce, and whether the producer may emit it.
221
- * 6.1: append MUST refuse a layer whose drift would exceed the chain's
222
- * effective limit unless --allow-drift is given.
223
- */
224
- export function checkAppendDrift({ baseRecords, appendedBefore, newRecords, headTombstones, effectiveLimit, allowDrift = false }) {
225
- if (!Number.isSafeInteger(baseRecords) || baseRecords <= 0) {
226
- throw new Error('drift needs a base with at least one record');
227
- }
228
- const drift = (appendedBefore + newRecords + headTombstones) / baseRecords;
229
- if (drift > effectiveLimit && !allowDrift) {
230
- throw new Error(`this append would take calibrationDrift to ${drift.toFixed(4)}, past the chain's effective limit ${effectiveLimit}; pass --allow-drift to emit it anyway (the chain then serves unscored) (6.1)`);
231
- }
232
- return { drift, exceedsLimit: drift > effectiveLimit };
233
- }
234
-
235
209
  /** Every id set in a bitset, ascending. */
236
210
  export function idsSetIn(bitset, rowBase) {
237
211
  const out = [];
@@ -1,9 +1,9 @@
1
- // Chain state — LAYERED_PROFILE.md 5.1 (steps 4-5), 5.2, 5.3, 5.5, 5.6.
1
+ // Chain state — LAYERED_PROFILE.md 5.1 (steps 4-5), 5.2, 5.3, 5.4, 5.6.
2
2
  //
3
3
  // Everything a mounted chain needs that is not bytes: the ordered interval
4
4
  // table of search tiers, id ownership, the head mask projected onto each tier's
5
- // local range, the union supersession map, calibration drift, and the ancestry
6
- // used to scope citations.
5
+ // local range, the union supersession map, global lexical statistics, and the
6
+ // ancestry used to scope citations.
7
7
  //
8
8
  // Pure: the caller supplies already-verified per-member facts. That keeps the
9
9
  // whole of 5.2/5.3/5.6 testable without building files, and keeps the sharp
@@ -172,61 +172,15 @@ export function resolveSupersession(map, id) {
172
172
  return { immediate, all, current };
173
173
  }
174
174
 
175
- /**
176
- * Calibration drift (3.1):
177
- * (sum of layer records for depth >= 1 + head tombstones) / base records
178
- *
179
- * It counts HISTORY, not current divergence: a record appended and later
180
- * tombstoned counts twice, and a supersession counts as one append plus one
181
- * tombstone. Intentionally conservative — the fit's population lost a member it
182
- * had seen and gained one it had not.
183
- */
184
- export function calibrationDrift(members, headTombstoneCount) {
185
- const base = members[0];
186
- if (!base || base.depth !== 0) throw new Error('calibrationDrift needs the base as the first member');
187
- if (!Number.isSafeInteger(base.records) || base.records <= 0) {
188
- throw new Error('calibrationDrift needs a base with at least one record');
189
- }
190
- let appended = 0;
191
- for (const m of members) if (m.depth >= 1) appended += m.records;
192
- return (appended + (headTombstoneCount || 0)) / base.records;
193
- }
194
-
195
- /**
196
- * Calibration status (5.5). The effective limit is
197
- * `min(producerEnvelope, readerLimit)`: a host can always be stricter than the
198
- * artifact, and an artifact can never make a host less strict.
199
- *
200
- * An absent producer envelope is +Infinity (no claim is no constraint), and the
201
- * reader's limit MUST be finite, so an artifact that declares nothing is still
202
- * gated.
203
- */
204
- export function calibrationStatus({ drift, producerEnvelope, readerLimit, baseHasFit, everyLayerShipsBloom }) {
205
- if (!Number.isFinite(readerLimit)) {
206
- throw new Error('readerLimit MUST be finite (5.5)');
207
- }
208
- const envelope = Number.isFinite(producerEnvelope) ? producerEnvelope : Infinity;
209
- const effectiveLimit = Math.min(envelope, readerLimit);
210
- if (!baseHasFit) {
211
- return { status: 'none', drift, effectiveLimit, producerEnvelope: envelope, readerLimit };
212
- }
213
- // A layer WITH RECORDS whose calibration region is `none` while the base
214
- // carries a fit degrades the chain to unscored (4.5, 5.5). The caller
215
- // leaves tombstone-only layers out of everyLayerShipsBloom: they have no
216
- // vocabulary for a bloom to carry.
217
- const status = (drift <= effectiveLimit && everyLayerShipsBloom) ? 'inherited' : 'drift-exceeded';
218
- return { status, drift, effectiveLimit, producerEnvelope: envelope, readerLimit };
219
- }
220
-
221
175
  /**
222
176
  * Global lexical statistics over search tiers (5.4). Tombstoned records are
223
177
  * counted in N, avgdl and df: removing them would require reading every posting
224
178
  * list at mount.
225
179
  *
226
- * The resulting scores differ from a from-scratch build over the live set. The
227
- * drift gate of 5.5 is a change-volume gate and implies no bound on that
228
- * difference; 13.3 measured it at under 0.005 nDCG@10 up to 25% drift on two
229
- * BEIR datasets, which is why no correction table ships. A reader MUST report
180
+ * The resulting scores differ from a from-scratch build over the live set;
181
+ * 13.3 measured the difference at under 0.005 nDCG@10 with up to 25% of the
182
+ * base appended or tombstoned, on two BEIR datasets, which is why no
183
+ * correction table ships. A reader MUST report
230
184
  * `statsIncludeTombstoned: true`.
231
185
  */
232
186
  export function globalLexicalStats(perTier) {
@@ -2,10 +2,9 @@
2
2
  //
3
3
  // Compaction is SEMANTIC maintenance, not only physical consolidation. It is the
4
4
  // step that restores every exact property the layers approximated: exact lexical
5
- // statistics over the live set (5.4), a vocabulary bloom over the live
6
- // vocabulary only (4.5), a calibration fit against the corpus actually served
7
- // (5.5), no tombstones, no supersession walks, depth zero, and reclaimed id
8
- // space (3.3). The drift and depth limits exist to force it to happen.
5
+ // statistics over the live set (5.4), no tombstones, no supersession walks,
6
+ // depth zero, and reclaimed id space (3.3). The depth limit exists to force it
7
+ // to happen.
9
8
  //
10
9
  // What it preserves, and what it deliberately does not:
11
10
  //
@@ -7,8 +7,8 @@
7
7
  // inheritFrom MUST equal manifest layer.baseIdentity
8
8
  // queryInterpSha256 MUST equal the base manifest's segments[kind=query-interp].sha256
9
9
  //
10
- // Those two together bind the base's encoder bytes AND its calibration under
11
- // the base's identity, which the layer's baseIdentity in turn commits to. So a
10
+ // Those two together bind the base's whole query-interp segment under the
11
+ // base's identity, which the layer's baseIdentity in turn commits to. So a
12
12
  // layer cannot substitute an encoder, and cannot point at a different base's
13
13
  // encoder, without breaking a digest the head's identity covers.
14
14
  //
@@ -18,12 +18,12 @@
18
18
  // [0,4) u32 version = 1
19
19
  // [4,8) u32 kind = 4
20
20
  // [8,12) u32 encoderLen the inherited-v1 JSON below
21
- // [12,16) u32 calibrationLen layer-vocab-v1 JSON, or {"kind":"none"}
21
+ // [12,16) u32 calibrationLen {"kind":"none"}
22
22
  //
23
- // The calibration region is this layer's own vocabulary bloom, built with the
24
- // base's geometry so the union of 4.5 is an exact bitwise OR. A layer whose
25
- // region is `{"kind":"none"}` while the base carries a fit degrades the chain
26
- // to `unscored` (5.5), so a producer SHOULD always ship the bloom.
23
+ // The calibration region is reserved. Producers before 0.17 could put a
24
+ // layer-vocab-v1 vocabulary bloom there for the base's fitted matchQuality
25
+ // model; that model is gone, so this producer writes {"kind":"none"} and the
26
+ // reader ignores the region's contents (the layout check still covers it).
27
27
 
28
28
  const encoder = new TextEncoder();
29
29
  const decoder = new TextDecoder();
@@ -31,45 +31,19 @@ const decoder = new TextDecoder();
31
31
  export const QI_HEADER_BYTES = 16;
32
32
  export const QI_KIND_INHERITED = 4;
33
33
  export const INHERITED_VERSION = 1;
34
- export const LAYER_VOCAB_KIND = 'layer-vocab-v1';
35
34
 
36
35
  const isHex64 = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
37
36
 
38
37
  /**
39
38
  * Build a kind-4 query-interp segment.
40
39
  *
41
- * @param {{baseIdentity: string, queryInterpSha256: string,
42
- * vocabBloom?: {bits: number, hashes: string[]}|null,
43
- * vocabBloomBytes?: Uint8Array|null}} spec
44
- * Omitting the bloom writes `{"kind":"none"}`, which is legal but degrades a
45
- * scored chain to unscored — the caller is expected to know that.
40
+ * @param {{baseIdentity: string, queryInterpSha256: string}} spec
46
41
  */
47
- export function buildInheritedQuerySegment({ baseIdentity, queryInterpSha256, vocabBloom = null, vocabBloomBytes = null }) {
42
+ export function buildInheritedQuerySegment({ baseIdentity, queryInterpSha256 }) {
48
43
  if (!isHex64(baseIdentity)) throw new Error('inherited-v1: baseIdentity must be 64 lowercase hex characters');
49
44
  if (!isHex64(queryInterpSha256)) throw new Error('inherited-v1: queryInterpSha256 must be 64 lowercase hex characters');
50
45
  const encoderJson = encoder.encode(JSON.stringify({ inheritFrom: baseIdentity, queryInterpSha256 }));
51
-
52
- let calibrationJson;
53
- if (vocabBloom && vocabBloomBytes) {
54
- if (!Number.isSafeInteger(vocabBloom.bits) || vocabBloom.bits <= 0 || vocabBloom.bits % 8 !== 0) {
55
- throw new Error('inherited-v1: vocabBloom.bits must be a positive multiple of 8');
56
- }
57
- if (vocabBloomBytes.length * 8 !== vocabBloom.bits) {
58
- throw new Error(`inherited-v1: bloom is ${vocabBloomBytes.length * 8} bits but vocabBloom.bits says ${vocabBloom.bits}`);
59
- }
60
- if (!Array.isArray(vocabBloom.hashes) || vocabBloom.hashes.length === 0) {
61
- throw new Error('inherited-v1: vocabBloom.hashes must be a non-empty array');
62
- }
63
- calibrationJson = encoder.encode(JSON.stringify({
64
- kind: LAYER_VOCAB_KIND,
65
- vocabBloom: { bits: vocabBloom.bits, hashes: vocabBloom.hashes },
66
- vocabBloomBase64: base64FromBytes(vocabBloomBytes),
67
- }));
68
- } else if (vocabBloom || vocabBloomBytes) {
69
- throw new Error('inherited-v1: vocabBloom and vocabBloomBytes must be supplied together');
70
- } else {
71
- calibrationJson = encoder.encode(JSON.stringify({ kind: 'none' }));
72
- }
46
+ const calibrationJson = encoder.encode(JSON.stringify({ kind: 'none' }));
73
47
 
74
48
  const out = new Uint8Array(QI_HEADER_BYTES + encoderJson.length + calibrationJson.length);
75
49
  const view = new DataView(out.buffer);
@@ -87,10 +61,9 @@ export function buildInheritedQuerySegment({ baseIdentity, queryInterpSha256, vo
87
61
  * base a reader actually opened.
88
62
  *
89
63
  * @param {Uint8Array} bytes
90
- * @param {{layerBaseIdentity: string, baseQueryInterpSha256: string,
91
- * baseBloom?: {bits: number, hashes: string[]}|null}} expect
92
- * `layerBaseIdentity` comes from the layer's own manifest; the other two come
93
- * from the BASE's manifest. Passing them separately is the point: the check
64
+ * @param {{layerBaseIdentity: string, baseQueryInterpSha256: string}} expect
65
+ * `layerBaseIdentity` comes from the layer's own manifest;
66
+ * `baseQueryInterpSha256` from the BASE's manifest. Passing them separately is the point: the check
94
67
  * is that the layer's claim matches the base actually resolved, so neither
95
68
  * side can be supplied by the other.
96
69
  */
@@ -128,96 +101,17 @@ export function parseInheritedQuerySegment(bytes, expect) {
128
101
  throw new Error(`inherited-v1: inheritFrom ${decl.inheritFrom.slice(0, 12)}… does not equal the manifest's layer.baseIdentity ${String(expect.layerBaseIdentity).slice(0, 12)}…`);
129
102
  }
130
103
  // MUST equal the base manifest's query-interp segment digest (4.5). This is
131
- // the encoder invariant: it binds the base's encoder bytes and calibration
132
- // together, so a layer cannot load a different encoder.
104
+ // the encoder invariant: it binds the base's encoder bytes, so a layer
105
+ // cannot load a different encoder.
133
106
  if (decl.queryInterpSha256 !== expect.baseQueryInterpSha256) {
134
107
  throw new Error(`inherited-v1: queryInterpSha256 ${decl.queryInterpSha256.slice(0, 12)}… does not match the base's query-interp digest ${String(expect.baseQueryInterpSha256).slice(0, 12)}…`);
135
108
  }
136
109
 
137
- let calibration;
138
- try {
139
- calibration = JSON.parse(decoder.decode(bytes.subarray(QI_HEADER_BYTES + encoderLen)));
140
- } catch (err) {
141
- throw new Error('inherited-v1: calibration region is not valid JSON', { cause: err });
142
- }
143
- if (!calibration || typeof calibration !== 'object' || Array.isArray(calibration)) {
144
- throw new Error('inherited-v1: calibration region must be a JSON object');
145
- }
146
-
147
- let bloomBytes = null;
148
- if (calibration.kind === LAYER_VOCAB_KIND) {
149
- const geom = calibration.vocabBloom;
150
- if (!geom || typeof geom !== 'object') throw new Error('inherited-v1: layer-vocab-v1 needs a vocabBloom object');
151
- if (typeof calibration.vocabBloomBase64 !== 'string') {
152
- throw new Error('inherited-v1: layer-vocab-v1 needs vocabBloomBase64');
153
- }
154
- bloomBytes = bytesFromBase64(calibration.vocabBloomBase64);
155
- if (bloomBytes.length * 8 !== geom.bits) {
156
- throw new Error(`inherited-v1: bloom decodes to ${bloomBytes.length * 8} bits but vocabBloom.bits says ${geom.bits}`);
157
- }
158
- // The geometry MUST match the base asset's, which is what makes the
159
- // union of 4.5 an exact bitwise OR rather than an approximation.
160
- if (expect.baseBloom) {
161
- if (geom.bits !== expect.baseBloom.bits) {
162
- throw new Error(`inherited-v1: layer bloom is ${geom.bits} bits but the base's is ${expect.baseBloom.bits}; the union would not be exact`);
163
- }
164
- const a = JSON.stringify(geom.hashes);
165
- const b = JSON.stringify(expect.baseBloom.hashes);
166
- if (a !== b) {
167
- throw new Error(`inherited-v1: layer bloom hashes ${a} differ from the base's ${b}`);
168
- }
169
- }
170
- } else if (calibration.kind !== 'none') {
171
- throw new Error(`inherited-v1: calibration kind must be ${LAYER_VOCAB_KIND} or "none", got ${JSON.stringify(calibration.kind)}`);
172
- }
173
-
110
+ // The calibration region is reserved (see the header comment): its
111
+ // contents are not read.
174
112
  return {
175
113
  version, kind,
176
114
  inheritFrom: decl.inheritFrom,
177
115
  queryInterpSha256: decl.queryInterpSha256,
178
- calibrationKind: calibration.kind,
179
- bloomBytes,
180
- bloomGeometry: bloomBytes ? { bits: calibration.vocabBloom.bits, hashes: calibration.vocabBloom.hashes } : null,
181
116
  };
182
117
  }
183
-
184
- /**
185
- * The union bloom of 4.5: the bitwise OR of the base's and every layer's. The
186
- * identical geometry makes it exact. A reader MUST compute this before scoring
187
- * — without it the known-token signal under-reads every query about a layer's
188
- * content, and the scorer abstains on exactly the records the layer added.
189
- *
190
- * Note what the union means: it covers the vocabulary of every record EVER
191
- * appended, live or tombstoned. Nothing can be removed from a bloom, so this
192
- * is not, and cannot be made, a bloom over the live vocabulary. Section 13.2
193
- * measured the consequence.
194
- */
195
- export function unionBloom(blooms) {
196
- const present = blooms.filter(Boolean);
197
- if (!present.length) return null;
198
- const bytes = present[0].length;
199
- for (const b of present) {
200
- if (b.length !== bytes) {
201
- throw new Error(`unionBloom: geometry mismatch — ${b.length} bytes against ${bytes}; every layer's bloom must use the base's bits`);
202
- }
203
- }
204
- const out = new Uint8Array(bytes);
205
- out.set(present[0]);
206
- for (let i = 1; i < present.length; i++) {
207
- const b = present[i];
208
- for (let j = 0; j < bytes; j++) out[j] |= b[j];
209
- }
210
- return out;
211
- }
212
-
213
- function base64FromBytes(bytes) {
214
- if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
215
- let s = '';
216
- for (const b of bytes) s += String.fromCharCode(b);
217
- return btoa(s);
218
- }
219
-
220
- function bytesFromBase64(text) {
221
- if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(text, 'base64'));
222
- return Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
223
- }