@winche-technologies/admin 0.0.0-stage → 3.0.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/dist/index.js ADDED
@@ -0,0 +1,1434 @@
1
+ // @ts-self-types="./index.d.ts"
2
+ // src/admin.ts
3
+ var GeoPoint = class _GeoPoint {
4
+ latitude;
5
+ longitude;
6
+ constructor(latitude, longitude) {
7
+ this.latitude = latitude;
8
+ this.longitude = longitude;
9
+ }
10
+ isEqual(other) {
11
+ return other instanceof _GeoPoint && other.latitude === this.latitude && other.longitude === this.longitude;
12
+ }
13
+ };
14
+ var Link = class _Link {
15
+ kind;
16
+ target;
17
+ resolved;
18
+ /** @internal */
19
+ constructor(kind, target, resolved = null) {
20
+ this.kind = kind;
21
+ this.target = target;
22
+ this.resolved = resolved;
23
+ }
24
+ static document(path) {
25
+ return new _Link("document", trimSlashes(path));
26
+ }
27
+ static file(path) {
28
+ return new _Link("file", trimSlashes(path));
29
+ }
30
+ static user(uid) {
31
+ return new _Link("user", uid);
32
+ }
33
+ /** What it points to, when the read expanded it and the target exists; null otherwise. */
34
+ data() {
35
+ return this.resolved?.() ?? null;
36
+ }
37
+ isEqual(other) {
38
+ return other instanceof _Link && other.kind === this.kind && other.target === this.target;
39
+ }
40
+ toString() {
41
+ return `${this.kind}:${this.target}`;
42
+ }
43
+ };
44
+ var FieldValue = class _FieldValue {
45
+ kind;
46
+ operand;
47
+ constructor(kind, operand) {
48
+ this.kind = kind;
49
+ this.operand = operand;
50
+ }
51
+ /** Removes the field (update, or set with merge / mergeFields). */
52
+ static delete() {
53
+ return new _FieldValue("delete");
54
+ }
55
+ /** The write's commit time. */
56
+ static serverTimestamp() {
57
+ return new _FieldValue("serverTimestamp");
58
+ }
59
+ /** Adds n (integers stay integers; a double makes a double). A missing or non-number field becomes n. */
60
+ static increment(n) {
61
+ return new _FieldValue("increment", n);
62
+ }
63
+ /** Keeps the larger of the field and n. */
64
+ static maximum(n) {
65
+ return new _FieldValue("maximum", n);
66
+ }
67
+ /** Keeps the smaller of the field and n. */
68
+ static minimum(n) {
69
+ return new _FieldValue("minimum", n);
70
+ }
71
+ /** Appends the elements not already in the array. */
72
+ static arrayUnion(...elements) {
73
+ return new _FieldValue("arrayUnion", elements);
74
+ }
75
+ /** Removes every element equal to one of these. */
76
+ static arrayRemove(...elements) {
77
+ return new _FieldValue("arrayRemove", elements);
78
+ }
79
+ };
80
+ var base64 = {
81
+ encode(bytes) {
82
+ let s = "";
83
+ for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode(...bytes.subarray(i, i + 32768));
84
+ return btoa(s);
85
+ },
86
+ decode(text) {
87
+ return Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
88
+ }
89
+ };
90
+ var wireTime = (d) => {
91
+ if (isNaN(d.getTime())) throw new Error("An invalid Date can't be stored.");
92
+ return d.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
93
+ };
94
+ var NO_EXPANSION = {
95
+ included: {},
96
+ resolved: {}
97
+ };
98
+ function encodeValue(v) {
99
+ if (v === null || v === void 0) return {
100
+ nullValue: null
101
+ };
102
+ if (typeof v === "boolean") return {
103
+ booleanValue: v
104
+ };
105
+ if (typeof v === "bigint") return {
106
+ integerValue: v.toString()
107
+ };
108
+ if (typeof v === "number") {
109
+ if (Number.isNaN(v)) return {
110
+ doubleValue: "NaN"
111
+ };
112
+ if (v === Infinity) return {
113
+ doubleValue: "Infinity"
114
+ };
115
+ if (v === -Infinity) return {
116
+ doubleValue: "-Infinity"
117
+ };
118
+ return Number.isInteger(v) && Number.isSafeInteger(v) ? {
119
+ integerValue: String(v)
120
+ } : {
121
+ doubleValue: v
122
+ };
123
+ }
124
+ if (typeof v === "string") return {
125
+ stringValue: v
126
+ };
127
+ if (v instanceof Date) return {
128
+ timestampValue: wireTime(v)
129
+ };
130
+ if (v instanceof Uint8Array) return {
131
+ bytesValue: base64.encode(v)
132
+ };
133
+ if (v instanceof GeoPoint) return {
134
+ geoPointValue: {
135
+ latitude: v.latitude,
136
+ longitude: v.longitude
137
+ }
138
+ };
139
+ if (v instanceof Link) return v.kind === "document" ? {
140
+ documentReferenceValue: v.target
141
+ } : v.kind === "file" ? {
142
+ fileReferenceValue: v.target
143
+ } : {
144
+ userReferenceValue: v.target
145
+ };
146
+ if (v instanceof DocumentReference) return {
147
+ documentReferenceValue: v.path
148
+ };
149
+ if (v instanceof ChildReference) return {
150
+ fileReferenceValue: v.path
151
+ };
152
+ if (v instanceof UserReference) return {
153
+ userReferenceValue: v.uid
154
+ };
155
+ if (v instanceof FieldValue) throw new Error(`FieldValue.${v.kind}() can't be used here (only as a field of set or update, not inside an array).`);
156
+ if (Array.isArray(v)) return {
157
+ arrayValue: {
158
+ values: v.map(encodeValue)
159
+ }
160
+ };
161
+ if (typeof v === "object") return {
162
+ mapValue: {
163
+ fields: encodeFields(v)
164
+ }
165
+ };
166
+ throw new Error(`A ${typeof v} can't be stored in a document.`);
167
+ }
168
+ function encodeFields(fields) {
169
+ const out = {};
170
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) out[k] = encodeValue(v);
171
+ return out;
172
+ }
173
+ function decodeValue(t, x = NO_EXPANSION) {
174
+ if (!t || typeof t !== "object") return null;
175
+ if ("nullValue" in t) return null;
176
+ if ("booleanValue" in t) return t.booleanValue;
177
+ if ("integerValue" in t) {
178
+ const n = Number(t.integerValue);
179
+ return Number.isSafeInteger(n) ? n : BigInt(t.integerValue);
180
+ }
181
+ if ("doubleValue" in t) return typeof t.doubleValue === "number" ? t.doubleValue : Number(t.doubleValue);
182
+ if ("stringValue" in t) return t.stringValue;
183
+ if ("timestampValue" in t) return new Date(t.timestampValue);
184
+ if ("bytesValue" in t) return base64.decode(t.bytesValue);
185
+ if ("geoPointValue" in t) return new GeoPoint(t.geoPointValue.latitude, t.geoPointValue.longitude);
186
+ if ("documentReferenceValue" in t) {
187
+ const path = t.documentReferenceValue;
188
+ return new Link("document", path, () => x.included[path] ? decodeFields(x.included[path].fields, x) : null);
189
+ }
190
+ if ("fileReferenceValue" in t) {
191
+ const path = t.fileReferenceValue;
192
+ return new Link("file", path, () => x.resolved[`file:${path}`] ? fileData(x.resolved[`file:${path}`]) : null);
193
+ }
194
+ if ("userReferenceValue" in t) {
195
+ const uid = t.userReferenceValue;
196
+ return new Link("user", uid, () => x.resolved[`user:${uid}`] ? userData(x.resolved[`user:${uid}`]) : null);
197
+ }
198
+ if ("arrayValue" in t) return (t.arrayValue?.values ?? []).map((v) => decodeValue(v, x));
199
+ if ("mapValue" in t) return decodeFields(t.mapValue?.fields ?? {}, x);
200
+ return null;
201
+ }
202
+ function decodeFields(fields, x = NO_EXPANSION) {
203
+ const out = {};
204
+ for (const [k, v] of Object.entries(fields ?? {})) out[k] = decodeValue(v, x);
205
+ return out;
206
+ }
207
+ var isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
208
+ function writeFields(data, dotted) {
209
+ const transforms = [];
210
+ const walk = (obj, prefix) => {
211
+ const out = {};
212
+ for (const [k, v] of Object.entries(obj)) {
213
+ if (v === void 0) continue;
214
+ const path = prefix ? `${prefix}.${k}` : k;
215
+ if (v instanceof FieldValue) {
216
+ if (v.kind === "delete") out[k] = {
217
+ deleteField: true
218
+ };
219
+ else transforms.push(v.kind === "serverTimestamp" ? {
220
+ field: path,
221
+ kind: v.kind
222
+ } : {
223
+ field: path,
224
+ kind: v.kind,
225
+ operand: v.kind === "arrayUnion" || v.kind === "arrayRemove" ? encodeValue(v.operand) : encodeValue(v.operand)
226
+ });
227
+ } else if (isPlainObject(v)) {
228
+ const inner = walk(v, path);
229
+ if (Object.keys(inner).length > 0 || Object.keys(v).length === 0) out[k] = {
230
+ mapValue: {
231
+ fields: inner
232
+ }
233
+ };
234
+ } else out[k] = encodeValue(v);
235
+ }
236
+ return out;
237
+ };
238
+ if (!dotted) return {
239
+ fields: walk(data, ""),
240
+ transforms
241
+ };
242
+ const fields = {};
243
+ for (const [k, v] of Object.entries(data)) {
244
+ if (v === void 0) continue;
245
+ if (v instanceof FieldValue) {
246
+ if (v.kind === "delete") fields[k] = {
247
+ deleteField: true
248
+ };
249
+ else transforms.push(v.kind === "serverTimestamp" ? {
250
+ field: k,
251
+ kind: v.kind
252
+ } : {
253
+ field: k,
254
+ kind: v.kind,
255
+ operand: encodeValue(v.operand)
256
+ });
257
+ } else if (isPlainObject(v)) {
258
+ const inner = walk(v, k);
259
+ fields[k] = {
260
+ mapValue: {
261
+ fields: inner
262
+ }
263
+ };
264
+ } else fields[k] = encodeValue(v);
265
+ }
266
+ return {
267
+ fields,
268
+ transforms
269
+ };
270
+ }
271
+ var trimSlashes = (p) => p.replace(/^\/+|\/+$/g, "");
272
+ var segments = (p) => trimSlashes(p).split("/").filter((s) => s.length > 0);
273
+ var PROTOCOL = 1;
274
+ var WincheError = class extends Error {
275
+ code;
276
+ constructor(code, message) {
277
+ super(message), this.code = code;
278
+ this.name = "WincheError";
279
+ }
280
+ };
281
+ var OPS = {
282
+ "==": "eq",
283
+ "!=": "ne",
284
+ "<": "lt",
285
+ "<=": "lte",
286
+ ">": "gt",
287
+ ">=": "gte",
288
+ "in": "in",
289
+ "not-in": "notIn",
290
+ "array-contains": "arrayContains",
291
+ "array-contains-any": "arrayContainsAny",
292
+ "array-contains-all": "arrayContainsAll",
293
+ "contains": "contains",
294
+ "starts-with": "startsWith",
295
+ "ends-with": "endsWith",
296
+ "matches": "regex"
297
+ };
298
+ var Filter = class _Filter {
299
+ wire;
300
+ constructor(wire) {
301
+ this.wire = wire;
302
+ }
303
+ static where(field, op, value) {
304
+ if (!(op in OPS)) throw new Error(`'${op}' isn't an operator (${Object.keys(OPS).join(", ")}).`);
305
+ return new _Filter({
306
+ field,
307
+ op: OPS[op],
308
+ value: encodeValue(value)
309
+ });
310
+ }
311
+ static and(...filters) {
312
+ return new _Filter({
313
+ and: filters.map((f) => f.wire)
314
+ });
315
+ }
316
+ static or(...filters) {
317
+ return new _Filter({
318
+ or: filters.map((f) => f.wire)
319
+ });
320
+ }
321
+ static not(filter) {
322
+ return new _Filter({
323
+ not: filter.wire
324
+ });
325
+ }
326
+ /** The field is null. */
327
+ static isNull(field) {
328
+ return new _Filter({
329
+ unary: "isNull",
330
+ field
331
+ });
332
+ }
333
+ /** The field is NaN. */
334
+ static isNan(field) {
335
+ return new _Filter({
336
+ unary: "isNan",
337
+ field
338
+ });
339
+ }
340
+ /** The field is there (any value, null included). */
341
+ static exists(field) {
342
+ return new _Filter({
343
+ unary: "exists",
344
+ field
345
+ });
346
+ }
347
+ };
348
+ var Aggregate = {
349
+ count: () => ({
350
+ kind: "count"
351
+ }),
352
+ sum: (field) => ({
353
+ kind: "sum",
354
+ field
355
+ }),
356
+ average: (field) => ({
357
+ kind: "average",
358
+ field
359
+ })
360
+ };
361
+ var Query = class _Query {
362
+ call;
363
+ state;
364
+ /** @internal */
365
+ constructor(call, state) {
366
+ this.call = call;
367
+ this.state = state;
368
+ }
369
+ with(change) {
370
+ return new _Query(this.call, {
371
+ ...this.state,
372
+ ...change
373
+ });
374
+ }
375
+ where(a, op, value) {
376
+ const f = a instanceof Filter ? a : Filter.where(a, op, value);
377
+ return this.with({
378
+ filters: [
379
+ ...this.state.filters,
380
+ f.wire
381
+ ]
382
+ });
383
+ }
384
+ orderBy(field, direction = "asc") {
385
+ return this.with({
386
+ orderBy: [
387
+ ...this.state.orderBy,
388
+ {
389
+ field,
390
+ direction
391
+ }
392
+ ]
393
+ });
394
+ }
395
+ limit(n) {
396
+ return this.with({
397
+ limit: n,
398
+ limitToLast: void 0
399
+ });
400
+ }
401
+ /** The last n of an ordered query (in order). */
402
+ limitToLast(n) {
403
+ return this.with({
404
+ limitToLast: n,
405
+ limit: void 0
406
+ });
407
+ }
408
+ offset(n) {
409
+ return this.with({
410
+ offset: n
411
+ });
412
+ }
413
+ /** Cursors: the orderBy fields' values, or a snapshot (its values for them, and its path). */
414
+ startAt(...at) {
415
+ return this.with({
416
+ start: {
417
+ values: cursor(at),
418
+ before: true
419
+ }
420
+ });
421
+ }
422
+ startAfter(...at) {
423
+ return this.with({
424
+ start: {
425
+ values: cursor(at),
426
+ before: false
427
+ }
428
+ });
429
+ }
430
+ endAt(...at) {
431
+ return this.with({
432
+ end: {
433
+ values: cursor(at),
434
+ before: false
435
+ }
436
+ });
437
+ }
438
+ endBefore(...at) {
439
+ return this.with({
440
+ end: {
441
+ values: cursor(at),
442
+ before: true
443
+ }
444
+ });
445
+ }
446
+ /** Only these fields in the results (the server leaves the rest out). */
447
+ select(...fields) {
448
+ return this.with({
449
+ select: fields
450
+ });
451
+ }
452
+ /** Follow these reference fields: their Links' data() is what they point to. */
453
+ expand(paths) {
454
+ return this.with({
455
+ expand: paths
456
+ });
457
+ }
458
+ /** @internal The query in the wire format. */
459
+ toWire() {
460
+ const s = this.state;
461
+ const cursorWire = (c) => {
462
+ if (!c) return void 0;
463
+ if (c.values instanceof DocumentSnapshot) {
464
+ const snap = c.values;
465
+ const values = s.orderBy.map((o) => encodeValue(snap.get(o.field)));
466
+ values.push({
467
+ documentReferenceValue: snap.reference.path
468
+ });
469
+ return {
470
+ values,
471
+ before: c.before
472
+ };
473
+ }
474
+ return {
475
+ values: c.values.map(encodeValue),
476
+ before: c.before
477
+ };
478
+ };
479
+ return {
480
+ collection: s.collection,
481
+ ...s.group ? {
482
+ collectionGroup: true
483
+ } : {},
484
+ ...s.filters.length === 1 ? {
485
+ where: s.filters[0]
486
+ } : s.filters.length > 1 ? {
487
+ where: {
488
+ and: s.filters
489
+ }
490
+ } : {},
491
+ ...s.orderBy.length ? {
492
+ orderBy: s.orderBy
493
+ } : {},
494
+ ...s.limit !== void 0 ? {
495
+ limit: s.limit
496
+ } : {},
497
+ ...s.limitToLast !== void 0 ? {
498
+ limitToLast: s.limitToLast
499
+ } : {},
500
+ ...s.offset !== void 0 ? {
501
+ offset: s.offset
502
+ } : {},
503
+ ...s.start ? {
504
+ start: cursorWire(s.start)
505
+ } : {},
506
+ ...s.end ? {
507
+ end: cursorWire(s.end)
508
+ } : {},
509
+ ...s.select ? {
510
+ select: s.select
511
+ } : {}
512
+ };
513
+ }
514
+ async get() {
515
+ const r = await this.call("db.query", {
516
+ query: this.toWire(),
517
+ ...this.state.expand ? {
518
+ expand: this.state.expand
519
+ } : {}
520
+ });
521
+ const x = {
522
+ included: r.included ?? {},
523
+ resolved: r.resolved ?? {}
524
+ };
525
+ return new QuerySnapshot((r.documents ?? []).map((d) => DocumentSnapshot.of(this.call, d, x)), r.hasMore === true);
526
+ }
527
+ /** How many documents match (no limit). */
528
+ async count() {
529
+ return (await this.call("db.count", {
530
+ query: this.toWire()
531
+ })).count;
532
+ }
533
+ /** The sum of a numeric field over the matches. */
534
+ async sum(field) {
535
+ return (await this.aggregate({
536
+ v: Aggregate.sum(field)
537
+ })).v;
538
+ }
539
+ /** The average of a numeric field over the matches (null when none). */
540
+ async average(field) {
541
+ return (await this.aggregate({
542
+ v: Aggregate.average(field)
543
+ })).v;
544
+ }
545
+ /** Several at once: `aggregate({ n: Aggregate.count(), total: Aggregate.sum("amount") })`. */
546
+ async aggregate(aggregates) {
547
+ const r = await this.call("db.aggregate", {
548
+ query: this.toWire(),
549
+ aggregations: Object.entries(aggregates).map(([alias, a]) => ({
550
+ alias,
551
+ ...a
552
+ }))
553
+ });
554
+ return decodeFields(r.result);
555
+ }
556
+ };
557
+ var cursor = (at) => at.length === 1 && at[0] instanceof DocumentSnapshot ? at[0] : at;
558
+ var CollectionReference = class extends Query {
559
+ path;
560
+ /** @internal */
561
+ constructor(call, path) {
562
+ super(call, {
563
+ collection: path,
564
+ group: false,
565
+ filters: [],
566
+ orderBy: []
567
+ }), this.path = path;
568
+ }
569
+ get id() {
570
+ return this.path.slice(this.path.lastIndexOf("/") + 1);
571
+ }
572
+ /** The document this collection is under (null at the top). */
573
+ get parent() {
574
+ const i = this.path.lastIndexOf("/");
575
+ return i < 0 ? null : new DocumentReference(this.call, this.path.slice(0, i));
576
+ }
577
+ /** A document in it; without an id, a new random one. */
578
+ doc(id) {
579
+ return new DocumentReference(this.call, `${this.path}/${id ?? newId()}`);
580
+ }
581
+ /** Adds a document with a new id. */
582
+ async add(data) {
583
+ const r = await this.call("db.add", {
584
+ collection: this.path,
585
+ fields: encodeFields(data)
586
+ });
587
+ return new DocumentReference(this.call, r.document.path);
588
+ }
589
+ };
590
+ var ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
591
+ var newId = () => [
592
+ ...crypto.getRandomValues(new Uint8Array(20))
593
+ ].map((b) => ID_CHARS[b % 62]).join("");
594
+ var DocumentReference = class _DocumentReference {
595
+ call;
596
+ path;
597
+ expandPaths;
598
+ /** @internal */
599
+ constructor(call, path, expandPaths) {
600
+ this.call = call;
601
+ this.path = path;
602
+ this.expandPaths = expandPaths;
603
+ }
604
+ get id() {
605
+ return this.path.slice(this.path.lastIndexOf("/") + 1);
606
+ }
607
+ get parent() {
608
+ return new CollectionReference(this.call, this.path.slice(0, this.path.lastIndexOf("/")));
609
+ }
610
+ collection(path) {
611
+ return new CollectionReference(this.call, `${this.path}/${trimSlashes(path)}`);
612
+ }
613
+ /** Follow these reference fields on get(): their Links' data() is what they point to. */
614
+ expand(paths) {
615
+ return new _DocumentReference(this.call, this.path, paths);
616
+ }
617
+ async get() {
618
+ const r = await this.call("db.get", {
619
+ path: this.path,
620
+ ...this.expandPaths ? {
621
+ expand: this.expandPaths
622
+ } : {}
623
+ });
624
+ return r.document ? DocumentSnapshot.of(this.call, r.document, {
625
+ included: r.included ?? {},
626
+ resolved: r.resolved ?? {}
627
+ }) : new DocumentSnapshot(this, false, null, null);
628
+ }
629
+ /** Replaces the document (or merges into it, or writes the mergeFields only). */
630
+ async set(data, options) {
631
+ await commit(this.call, [
632
+ setWrite(this.path, data, options)
633
+ ]);
634
+ }
635
+ /** Changes these fields (dotted paths reach into maps) of an existing document. */
636
+ async update(data, options) {
637
+ await commit(this.call, [
638
+ updateWrite(this.path, data, options?.precondition)
639
+ ]);
640
+ }
641
+ /** Deletes it; with cascade, everything under it too (in one write: for big trees, use documents.recursiveDelete). */
642
+ async delete(options) {
643
+ await commit(this.call, [
644
+ deleteWrite(this.path, options)
645
+ ]);
646
+ }
647
+ isEqual(other) {
648
+ return other instanceof _DocumentReference && other.path === this.path;
649
+ }
650
+ };
651
+ var setWrite = (path, data, o) => {
652
+ const { fields, transforms } = writeFields(data, false);
653
+ return {
654
+ set: {
655
+ path,
656
+ fields,
657
+ ...o?.merge ? {
658
+ merge: true
659
+ } : {},
660
+ ...o?.mergeFields ? {
661
+ mergeFields: o.mergeFields
662
+ } : {},
663
+ ...transforms.length ? {
664
+ transforms
665
+ } : {},
666
+ ...o?.precondition ? {
667
+ precondition: o.precondition
668
+ } : {}
669
+ }
670
+ };
671
+ };
672
+ var updateWrite = (path, data, precondition) => {
673
+ const { fields, transforms } = writeFields(data, true);
674
+ return {
675
+ update: {
676
+ path,
677
+ fields,
678
+ ...transforms.length ? {
679
+ transforms
680
+ } : {},
681
+ ...precondition ? {
682
+ precondition
683
+ } : {}
684
+ }
685
+ };
686
+ };
687
+ var deleteWrite = (path, o) => ({
688
+ delete: {
689
+ path,
690
+ ...o?.cascade ? {
691
+ cascade: true
692
+ } : {},
693
+ ...o?.precondition ? {
694
+ precondition: o.precondition
695
+ } : {}
696
+ }
697
+ });
698
+ var commit = (call, writes) => call("db.write", {
699
+ writes
700
+ });
701
+ var DocumentSnapshot = class _DocumentSnapshot {
702
+ reference;
703
+ exists;
704
+ fields;
705
+ meta;
706
+ /** @internal */
707
+ constructor(reference, exists, fields, meta) {
708
+ this.reference = reference;
709
+ this.exists = exists;
710
+ this.fields = fields;
711
+ this.meta = meta;
712
+ }
713
+ /** @internal From the wire (with the read's expansion for its links). */
714
+ static of(call, d, x = NO_EXPANSION) {
715
+ return new _DocumentSnapshot(new DocumentReference(call, d.path), true, decodeFields(d.fields, x), {
716
+ createTime: d.createTime,
717
+ updateTime: d.updateTime,
718
+ version: d.version
719
+ });
720
+ }
721
+ get id() {
722
+ return this.reference.id;
723
+ }
724
+ /** The fields (undefined when it doesn't exist). */
725
+ data() {
726
+ return this.fields ?? void 0;
727
+ }
728
+ /** One field, by dotted path ("address.city"); undefined when it isn't there. */
729
+ get(fieldPath) {
730
+ let v = this.fields;
731
+ for (const k of fieldPath.split(".")) {
732
+ if (v === null || typeof v !== "object" || !(k in v)) return void 0;
733
+ v = v[k];
734
+ }
735
+ return v;
736
+ }
737
+ get createTime() {
738
+ return this.meta ? new Date(this.meta.createTime) : null;
739
+ }
740
+ get updateTime() {
741
+ return this.meta ? new Date(this.meta.updateTime) : null;
742
+ }
743
+ /** The update time exactly as the server has it (microseconds), for `precondition: { updateTime }`. */
744
+ get updateTimeRaw() {
745
+ return this.meta?.updateTime ?? null;
746
+ }
747
+ get version() {
748
+ return this.meta?.version ?? null;
749
+ }
750
+ };
751
+ var QuerySnapshot = class {
752
+ docs;
753
+ hasMore;
754
+ /** @internal */
755
+ constructor(docs, hasMore) {
756
+ this.docs = docs;
757
+ this.hasMore = hasMore;
758
+ }
759
+ get size() {
760
+ return this.docs.length;
761
+ }
762
+ get empty() {
763
+ return this.docs.length === 0;
764
+ }
765
+ forEach(fn) {
766
+ this.docs.forEach(fn);
767
+ }
768
+ };
769
+ var WriteBatch = class {
770
+ call;
771
+ writes;
772
+ /** @internal */
773
+ constructor(call) {
774
+ this.call = call;
775
+ this.writes = [];
776
+ }
777
+ set(ref, data, options) {
778
+ this.writes.push(setWrite(ref.path, data, options));
779
+ return this;
780
+ }
781
+ update(ref, data, options) {
782
+ this.writes.push(updateWrite(ref.path, data, options?.precondition));
783
+ return this;
784
+ }
785
+ delete(ref, options) {
786
+ this.writes.push(deleteWrite(ref.path, options));
787
+ return this;
788
+ }
789
+ get size() {
790
+ return this.writes.length;
791
+ }
792
+ async commit() {
793
+ if (this.writes.length > 0) await commit(this.call, this.writes);
794
+ }
795
+ };
796
+ var Transaction = class {
797
+ call;
798
+ writes;
799
+ /** @internal path → updateTimeRaw (null: it didn't exist) */
800
+ seen;
801
+ /** @internal */
802
+ constructor(call) {
803
+ this.call = call;
804
+ this.writes = [];
805
+ this.seen = /* @__PURE__ */ new Map();
806
+ }
807
+ async get(ref) {
808
+ if (this.writes.length > 0) throw new Error("In a transaction, read before you write.");
809
+ const snap = await ref.get();
810
+ this.seen.set(ref.path, snap.updateTimeRaw);
811
+ return snap;
812
+ }
813
+ guard(path, given) {
814
+ if (given) return given;
815
+ if (!this.seen.has(path)) return void 0;
816
+ const at = this.seen.get(path);
817
+ return at === null ? {
818
+ exists: false
819
+ } : {
820
+ updateTime: at
821
+ };
822
+ }
823
+ set(ref, data, options) {
824
+ this.writes.push(setWrite(ref.path, data, {
825
+ ...options,
826
+ precondition: this.guard(ref.path, options?.precondition)
827
+ }));
828
+ return this;
829
+ }
830
+ update(ref, data, options) {
831
+ this.writes.push(updateWrite(ref.path, data, this.guard(ref.path, options?.precondition)));
832
+ return this;
833
+ }
834
+ delete(ref, options) {
835
+ this.writes.push(deleteWrite(ref.path, {
836
+ precondition: this.guard(ref.path, options?.precondition)
837
+ }));
838
+ return this;
839
+ }
840
+ /** @internal */
841
+ async commit() {
842
+ if (this.writes.length > 0) await commit(this.call, this.writes);
843
+ }
844
+ };
845
+ var Documents = class {
846
+ call;
847
+ /** @internal */
848
+ constructor(call) {
849
+ this.call = call;
850
+ }
851
+ /** A collection by path ("patients", "patients/p1/visits"). */
852
+ collection(path) {
853
+ if (segments(path).length % 2 !== 1) throw new Error(`'${path}' isn't a collection path (an odd number of parts).`);
854
+ return new CollectionReference(this.call, segments(path).join("/"));
855
+ }
856
+ /** A document by path ("patients/p1"). */
857
+ doc(path) {
858
+ if (segments(path).length % 2 !== 0 || segments(path).length === 0) throw new Error(`'${path}' isn't a document path (an even number of parts).`);
859
+ return new DocumentReference(this.call, segments(path).join("/"));
860
+ }
861
+ /** Every collection with this id, under any parent ("sessionHistory"). */
862
+ collectionGroup(id) {
863
+ return new Query(this.call, {
864
+ collection: id,
865
+ group: true,
866
+ filters: [],
867
+ orderBy: []
868
+ });
869
+ }
870
+ /** Several documents in one call, in order. */
871
+ async getAll(refs) {
872
+ const r = await this.call("db.getAll", {
873
+ paths: refs.map((ref) => ref.path)
874
+ });
875
+ return r.documents.map((d, i) => d ? DocumentSnapshot.of(this.call, d) : new DocumentSnapshot(refs[i], false, null, null));
876
+ }
877
+ batch() {
878
+ return new WriteBatch(this.call);
879
+ }
880
+ /** Deletes a document and everything under it, in batches (any size); how many documents went. */
881
+ async recursiveDelete(ref) {
882
+ return await this.call("db.deleteTree", {
883
+ path: ref.path
884
+ });
885
+ }
886
+ /** Runs `fn` with a transaction and commits it; runs it again when something it read changed meanwhile. */
887
+ async runTransaction(fn, options) {
888
+ const attempts = options?.maxAttempts ?? 5;
889
+ for (let i = 1; ; i++) {
890
+ const tx = new Transaction(this.call);
891
+ const result = await fn(tx);
892
+ try {
893
+ await tx.commit();
894
+ return result;
895
+ } catch (e) {
896
+ const code = e?.code;
897
+ if (i >= attempts || !(code === "failed-precondition" || code === "already-exists" || code === "not-found" || code === "aborted")) throw e;
898
+ }
899
+ }
900
+ }
901
+ };
902
+ function fileData(r) {
903
+ return {
904
+ id: r.id,
905
+ path: r.path,
906
+ directory: r.directory,
907
+ mimeType: r.mimeType,
908
+ sizeBytes: r.sizeBytes,
909
+ uploadStatus: typeof r.uploadStatus === "string" ? r.uploadStatus.toLowerCase() : r.uploadStatus === 1 ? "complete" : "pending",
910
+ contentDisposition: r.contentDisposition ?? null,
911
+ cacheControl: r.cacheControl ?? null,
912
+ contentHash: r.contentHash ?? null,
913
+ metadata: r.metadata ?? {},
914
+ version: r.version,
915
+ createdAt: new Date(r.createdAt),
916
+ updatedAt: new Date(r.updatedAt)
917
+ };
918
+ }
919
+ var ChildReference = class _ChildReference {
920
+ call;
921
+ path;
922
+ /** @internal */
923
+ constructor(call, path) {
924
+ this.call = call;
925
+ this.path = path;
926
+ }
927
+ /** The last part of the path. */
928
+ get name() {
929
+ return this.path.slice(this.path.lastIndexOf("/") + 1);
930
+ }
931
+ get parent() {
932
+ const i = this.path.lastIndexOf("/");
933
+ return this.path === "" ? null : new _ChildReference(this.call, i < 0 ? "" : this.path.slice(0, i));
934
+ }
935
+ child(path) {
936
+ return new _ChildReference(this.call, segments(`${this.path}/${path}`).join("/"));
937
+ }
938
+ /** The file's record; `exists` is false when there's none. */
939
+ async getSnapshot() {
940
+ const r = await this.call("files.get", {
941
+ path: this.path
942
+ });
943
+ return new FileSnapshot(this, r ? fileData(r) : null);
944
+ }
945
+ /** The bytes (up to 32 MB), or null when there's no file. */
946
+ async getData() {
947
+ const r = await this.call("files.read", {
948
+ path: this.path
949
+ });
950
+ return r === null ? null : base64.decode(r.base64);
951
+ }
952
+ /** The contents as UTF-8 text, or null. */
953
+ async getText() {
954
+ const bytes = await this.getData();
955
+ return bytes === null ? null : new TextDecoder().decode(bytes);
956
+ }
957
+ /** Writes the file (new or replacing one), up to 32 MB; its triggers and hooks run as for an upload. */
958
+ async putData(data, options) {
959
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
960
+ const r = await this.call("files.write", {
961
+ path: this.path,
962
+ base64: base64.encode(bytes),
963
+ mimeType: options?.mimeType ?? (typeof data === "string" ? "text/plain; charset=utf-8" : null),
964
+ metadata: options?.metadata ?? null,
965
+ contentDisposition: options?.contentDisposition ?? null,
966
+ cacheControl: options?.cacheControl ?? null
967
+ });
968
+ return new FileSnapshot(this, fileData(r));
969
+ }
970
+ /**
971
+ * Writes the file from a URL (a GET with these headers), up to 5 GB: the bytes go from the URL to storage on the
972
+ * server, never through the function. The type is the one given, else the response's.
973
+ */
974
+ async putFromUrl(url, options) {
975
+ const r = await this.call("files.copyFromUrl", {
976
+ path: this.path,
977
+ url,
978
+ headers: options?.headers ?? null,
979
+ mimeType: options?.mimeType ?? null,
980
+ metadata: options?.metadata ?? null,
981
+ contentDisposition: options?.contentDisposition ?? null,
982
+ cacheControl: options?.cacheControl ?? null
983
+ });
984
+ return new FileSnapshot(this, fileData(r));
985
+ }
986
+ /** One page of the folder: files and sub-folders in name order. */
987
+ async list(options) {
988
+ const r = await this.call("files.page", {
989
+ folder: this.path,
990
+ maxResults: options?.maxResults ?? null,
991
+ pageToken: options?.pageToken ?? null,
992
+ mimeType: options?.mimeType ?? null
993
+ });
994
+ return new DirectorySnapshot(this, (r.items ?? []).map((f) => new FileSnapshot(new _ChildReference(this.call, f.path), fileData(f))), (r.prefixes ?? []).map((p) => new _ChildReference(this.call, p)), r.nextPageToken ?? null);
995
+ }
996
+ /** Every file and sub-folder of the folder (all pages). */
997
+ async listChildren(options) {
998
+ const files2 = [], folders = [];
999
+ let token;
1000
+ do {
1001
+ const page = await this.list({
1002
+ maxResults: 1e3,
1003
+ pageToken: token,
1004
+ mimeType: options?.mimeType
1005
+ });
1006
+ files2.push(...page.files);
1007
+ folders.push(...page.folders);
1008
+ token = page.nextPageToken ?? void 0;
1009
+ } while (token);
1010
+ return new DirectorySnapshot(this, files2, folders, null);
1011
+ }
1012
+ /** Merges metadata (null removes a key); optionally changes the download headers ("" clears one), only at ifVersion. */
1013
+ async updateMetadata(metadata, options) {
1014
+ const r = await this.call("files.updateMetadata", {
1015
+ path: this.path,
1016
+ metadata,
1017
+ contentDisposition: options?.contentDisposition ?? null,
1018
+ cacheControl: options?.cacheControl ?? null,
1019
+ ifVersion: options?.ifVersion ?? null
1020
+ });
1021
+ return new FileSnapshot(this, fileData(r));
1022
+ }
1023
+ /** Deletes the file, or everything under the folder. False when nothing was there. */
1024
+ async delete() {
1025
+ let one = false, refused = null;
1026
+ try {
1027
+ one = await this.call("files.delete", {
1028
+ path: this.path
1029
+ }) === true;
1030
+ } catch (e) {
1031
+ if (e?.code !== "permission-denied") throw e;
1032
+ refused = e;
1033
+ }
1034
+ const under = await this.call("files.deleteUnder", {
1035
+ folder: this.path
1036
+ });
1037
+ if (refused && !(under > 0)) throw refused;
1038
+ return one || under > 0;
1039
+ }
1040
+ /** A link anyone holding it can download the file with, until expiresAt. */
1041
+ async downloadUrl() {
1042
+ const r = await this.call("files.downloadUrl", {
1043
+ path: this.path
1044
+ });
1045
+ return {
1046
+ url: r.url,
1047
+ expiresAt: new Date(r.expiresAt)
1048
+ };
1049
+ }
1050
+ isEqual(other) {
1051
+ return other instanceof _ChildReference && other.path === this.path;
1052
+ }
1053
+ };
1054
+ var FileSnapshot = class {
1055
+ reference;
1056
+ data;
1057
+ /** @internal */
1058
+ constructor(reference, data) {
1059
+ this.reference = reference;
1060
+ this.data = data;
1061
+ }
1062
+ get exists() {
1063
+ return this.data !== null;
1064
+ }
1065
+ };
1066
+ var DirectorySnapshot = class {
1067
+ reference;
1068
+ files;
1069
+ folders;
1070
+ nextPageToken;
1071
+ /** @internal */
1072
+ constructor(reference, files2, folders, nextPageToken) {
1073
+ this.reference = reference;
1074
+ this.files = files2;
1075
+ this.folders = folders;
1076
+ this.nextPageToken = nextPageToken;
1077
+ }
1078
+ };
1079
+ var Files = class {
1080
+ call;
1081
+ /** @internal */
1082
+ constructor(call) {
1083
+ this.call = call;
1084
+ }
1085
+ /** A file or folder by path; "" is the top. */
1086
+ child(path) {
1087
+ return new ChildReference(this.call, segments(path).join("/"));
1088
+ }
1089
+ };
1090
+ function userData(u) {
1091
+ return {
1092
+ uid: u.uid,
1093
+ email: u.email ?? null,
1094
+ emailVerified: u.emailVerified === true,
1095
+ displayName: u.displayName ?? null,
1096
+ photoUrl: u.photoUrl ?? null,
1097
+ isAnonymous: u.isAnonymous === true,
1098
+ disabled: u.disabled === true,
1099
+ mfaEnabled: u.mfaEnabled === true,
1100
+ providers: u.providers ?? [],
1101
+ customClaims: u.customClaims ?? {},
1102
+ createdAt: u.createdAt ? new Date(u.createdAt) : null,
1103
+ lastSignInAt: u.lastSignInAt ? new Date(u.lastSignInAt) : null
1104
+ };
1105
+ }
1106
+ var UserReference = class _UserReference {
1107
+ call;
1108
+ uid;
1109
+ /** @internal */
1110
+ constructor(call, uid) {
1111
+ this.call = call;
1112
+ this.uid = uid;
1113
+ }
1114
+ /** Their account; `exists` is false when there's no such user. */
1115
+ async get() {
1116
+ const r = await this.call("users.get", {
1117
+ uid: this.uid
1118
+ });
1119
+ return new UserSnapshot(this, r ? userData(r) : null);
1120
+ }
1121
+ /** Their custom claims ({} when none). Throws not-found when there's no such user. */
1122
+ async getCustomClaims() {
1123
+ const r = await this.call("users.get", {
1124
+ uid: this.uid
1125
+ });
1126
+ if (!r) throw new WincheError("not-found", `There's no user ${this.uid}.`);
1127
+ return r.customClaims ?? {};
1128
+ }
1129
+ /** Replaces their custom claims (null clears them); they're in the user's next token. */
1130
+ async setCustomClaims(claims) {
1131
+ await this.call("users.setClaims", {
1132
+ uid: this.uid,
1133
+ claims
1134
+ });
1135
+ }
1136
+ isEqual(other) {
1137
+ return other instanceof _UserReference && other.uid === this.uid;
1138
+ }
1139
+ };
1140
+ var UserSnapshot = class {
1141
+ reference;
1142
+ data;
1143
+ /** @internal */
1144
+ constructor(reference, data) {
1145
+ this.reference = reference;
1146
+ this.data = data;
1147
+ }
1148
+ get uid() {
1149
+ return this.reference.uid;
1150
+ }
1151
+ get exists() {
1152
+ return this.data !== null;
1153
+ }
1154
+ /** Their custom claims ({} when none, or no user). */
1155
+ get customClaims() {
1156
+ return this.data?.customClaims ?? {};
1157
+ }
1158
+ };
1159
+ var Auth = class {
1160
+ call;
1161
+ /** @internal */
1162
+ constructor(call) {
1163
+ this.call = call;
1164
+ }
1165
+ user(uid) {
1166
+ return new UserReference(this.call, uid);
1167
+ }
1168
+ };
1169
+ var AssetFileReference = class {
1170
+ call;
1171
+ release;
1172
+ path;
1173
+ /** @internal */
1174
+ constructor(call, release, path) {
1175
+ this.call = call;
1176
+ this.release = release;
1177
+ this.path = path;
1178
+ }
1179
+ /** Its bytes (up to 32 MB: larger ones through downloadUrl). */
1180
+ async bytes() {
1181
+ const r = await this.call("assets.read", {
1182
+ release: this.release,
1183
+ path: this.path
1184
+ });
1185
+ if (!r) throw new WincheError("not-found", `There's no ${this.path} in release ${this.release}.`);
1186
+ return base64.decode(r.base64);
1187
+ }
1188
+ /** Its contents as UTF-8 text. */
1189
+ async text() {
1190
+ return new TextDecoder().decode(await this.bytes());
1191
+ }
1192
+ /** Its contents decoded from JSON. */
1193
+ async json() {
1194
+ return JSON.parse(await this.text());
1195
+ }
1196
+ /** A short-lived link to its bytes (to hand to someone, or to fetch a large one). */
1197
+ async downloadUrl() {
1198
+ const r = await this.call("assets.downloadUrl", {
1199
+ release: this.release,
1200
+ path: this.path
1201
+ });
1202
+ return {
1203
+ url: r.url,
1204
+ expiresAt: new Date(r.expiresAt)
1205
+ };
1206
+ }
1207
+ };
1208
+ var AssetRelease = class _AssetRelease {
1209
+ call;
1210
+ number;
1211
+ note;
1212
+ by;
1213
+ at;
1214
+ files;
1215
+ /** @internal */
1216
+ constructor(call, number, note, by, at, files2) {
1217
+ this.call = call;
1218
+ this.number = number;
1219
+ this.note = note;
1220
+ this.by = by;
1221
+ this.at = at;
1222
+ this.files = files2;
1223
+ }
1224
+ /** @internal */
1225
+ static of(call, r) {
1226
+ return new _AssetRelease(call, r.number, r.note ?? null, r.by ?? null, new Date(r.at), r.files ?? []);
1227
+ }
1228
+ /** Whether it has a file at path. */
1229
+ has(path) {
1230
+ return this.files.some((f) => f.path === path);
1231
+ }
1232
+ /** The paths under a folder ("translations"), or all of them. */
1233
+ paths(folder) {
1234
+ const prefix = folder ? trimSlashes(folder) + "/" : "";
1235
+ return this.files.map((f) => f.path).filter((p) => p.startsWith(prefix));
1236
+ }
1237
+ /** A file of this release (reading one it hasn't throws not-found). */
1238
+ file(path) {
1239
+ return new AssetFileReference(this.call, this.number, trimSlashes(path));
1240
+ }
1241
+ };
1242
+ var AssetChannelReference = class {
1243
+ call;
1244
+ name;
1245
+ /** @internal */
1246
+ constructor(call, name) {
1247
+ this.call = call;
1248
+ this.name = name;
1249
+ }
1250
+ /** The release it points at now, or null when there's no such channel. */
1251
+ async get() {
1252
+ const r = await this.call("assets.channel", {
1253
+ name: this.name
1254
+ });
1255
+ return r ? AssetRelease.of(this.call, r) : null;
1256
+ }
1257
+ };
1258
+ var Assets = class {
1259
+ call;
1260
+ /** @internal */
1261
+ constructor(call) {
1262
+ this.call = call;
1263
+ }
1264
+ /** A channel by name ("production"). */
1265
+ channel(name) {
1266
+ return new AssetChannelReference(this.call, name);
1267
+ }
1268
+ /** A release by number, or null. */
1269
+ async release(number) {
1270
+ const r = await this.call("assets.release", {
1271
+ number
1272
+ });
1273
+ return r ? AssetRelease.of(this.call, r) : null;
1274
+ }
1275
+ /** The channels and the release each points at. */
1276
+ async channels() {
1277
+ return (await this.call("assets.channels", {})).map((c) => ({
1278
+ name: c.name,
1279
+ release: c.release,
1280
+ updatedAt: new Date(c.updatedAt),
1281
+ by: c.by ?? null
1282
+ }));
1283
+ }
1284
+ /** The releases, newest first, without their files. */
1285
+ async releases(limit = 50) {
1286
+ return (await this.call("assets.releases", {
1287
+ limit
1288
+ })).map((r) => ({
1289
+ ...r,
1290
+ at: new Date(r.at)
1291
+ }));
1292
+ }
1293
+ };
1294
+ var Functions = class {
1295
+ send;
1296
+ /** @internal */
1297
+ constructor(send) {
1298
+ this.send = send;
1299
+ }
1300
+ /** Runs the callable `name` with `data` and returns what it returns (its HttpsError as a WincheError with its code). */
1301
+ async call(name, data) {
1302
+ return await this.send("functions.call", {
1303
+ name,
1304
+ data: data === void 0 ? null : data
1305
+ });
1306
+ }
1307
+ };
1308
+ var Admin = class _Admin {
1309
+ transport;
1310
+ documents;
1311
+ files;
1312
+ auth;
1313
+ assets;
1314
+ functions;
1315
+ /** @internal */
1316
+ constructor(transport) {
1317
+ this.transport = transport;
1318
+ this.documents = new Documents(transport);
1319
+ this.files = new Files(transport);
1320
+ this.auth = new Auth(transport);
1321
+ this.assets = new Assets(transport);
1322
+ this.functions = new Functions(transport);
1323
+ }
1324
+ /**
1325
+ * The same API acting as one of the app's users (`ctx.caller` in a callable): every documents and files call is
1326
+ * checked against the project's access rules for them, and refused with permission-denied as an app would be.
1327
+ * Auth, assets and functions calls are refused (rules don't cover them).
1328
+ */
1329
+ as(user) {
1330
+ if (!user || typeof user.uid !== "string" || !user.uid) throw new WincheError("invalid-argument", "as(user): give a user with a uid (e.g. ctx.caller).");
1331
+ const who = {
1332
+ uid: user.uid,
1333
+ token: user.token ?? {}
1334
+ };
1335
+ return new _Admin((op, args) => this.transport(op, {
1336
+ ...args,
1337
+ as: who
1338
+ }));
1339
+ }
1340
+ };
1341
+ function initializeAdmin(options) {
1342
+ const server = (options?.server ?? "").replace(/\/+$/, "");
1343
+ if (!/^https?:\/\//.test(server)) throw new WincheError("invalid-argument", "initializeAdmin: give the server's address, e.g. https://winche.example.com.");
1344
+ if (!options.project) throw new WincheError("invalid-argument", "initializeAdmin: give the project's id.");
1345
+ if (!options.token) throw new WincheError("invalid-argument", "initializeAdmin: give a token.");
1346
+ const url = `${server}/console/v1/projects/${encodeURIComponent(options.project)}/admin`;
1347
+ const send = options.fetch ?? fetch;
1348
+ return new Admin(async (op, args) => {
1349
+ const token = typeof options.token === "function" ? await options.token() : options.token;
1350
+ let response;
1351
+ try {
1352
+ response = await send(url, {
1353
+ method: "POST",
1354
+ headers: {
1355
+ "content-type": "application/json",
1356
+ authorization: `Bearer ${token}`,
1357
+ "x-winche-protocol": String(PROTOCOL)
1358
+ },
1359
+ body: JSON.stringify({
1360
+ op,
1361
+ args
1362
+ })
1363
+ });
1364
+ } catch (e) {
1365
+ throw new WincheError("unavailable", `Couldn't reach ${server}: ${e?.message ?? e}`);
1366
+ }
1367
+ const body = await response.json().catch(() => null);
1368
+ if (!response.ok || body?.error) {
1369
+ const error = body?.error ?? {};
1370
+ throw new WincheError(error.code ?? (response.status === 401 ? "unauthenticated" : response.status === 403 ? "permission-denied" : "internal"), error.message ?? `The server answered ${response.status}.`);
1371
+ }
1372
+ return body?.result ?? null;
1373
+ });
1374
+ }
1375
+ var ambient = (op, args) => {
1376
+ const g = globalThis;
1377
+ const run = g[Symbol.for("winche.run")]?.() ?? g[Symbol.for("winche.test")]?.();
1378
+ if (run?.protocol !== void 0 && run.protocol !== PROTOCOL) return Promise.reject(mismatch(run.protocol));
1379
+ if (run?.call) return run.call(op, args);
1380
+ const page = g[Symbol.for("winche.page")];
1381
+ if (typeof page === "function") return page(op, args, PROTOCOL);
1382
+ return Promise.reject(new WincheError("failed-precondition", run ? "This test gave no server: use withServer(...) from @winche/functions/testing to reach one." : "@winche/admin isn't signed in here. Functions and console pages are signed in already (call it while a function runs, not at a module's top level); anywhere else use initializeAdmin({ server, project, token })."));
1383
+ };
1384
+ var mismatch = (server) => new WincheError("failed-precondition", `This @winche/admin speaks protocol ${PROTOCOL}; the server speaks ${server}: use the @winche/admin version made for it.`);
1385
+ var signedIn = new Admin(ambient);
1386
+ var documents = signedIn.documents;
1387
+ var files = signedIn.files;
1388
+ var auth = signedIn.auth;
1389
+ var assets = signedIn.assets;
1390
+ var functions = signedIn.functions;
1391
+ var as = (user) => signedIn.as(user);
1392
+ export {
1393
+ Admin,
1394
+ Aggregate,
1395
+ AssetChannelReference,
1396
+ AssetFileReference,
1397
+ AssetRelease,
1398
+ Assets,
1399
+ Auth,
1400
+ ChildReference,
1401
+ CollectionReference,
1402
+ DirectorySnapshot,
1403
+ DocumentReference,
1404
+ DocumentSnapshot,
1405
+ Documents,
1406
+ FieldValue,
1407
+ FileSnapshot,
1408
+ Files,
1409
+ Filter,
1410
+ Functions,
1411
+ GeoPoint,
1412
+ Link,
1413
+ PROTOCOL,
1414
+ Query,
1415
+ QuerySnapshot,
1416
+ Transaction,
1417
+ UserReference,
1418
+ UserSnapshot,
1419
+ WincheError,
1420
+ WriteBatch,
1421
+ as,
1422
+ assets,
1423
+ auth,
1424
+ decodeFields,
1425
+ decodeValue,
1426
+ documents,
1427
+ encodeFields,
1428
+ encodeValue,
1429
+ fileData,
1430
+ files,
1431
+ functions,
1432
+ initializeAdmin,
1433
+ userData
1434
+ };