@celobus/sdk 0.0.0-stage → 0.1.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.
Files changed (48) hide show
  1. package/LICENSE +91 -0
  2. package/README.md +38 -2
  3. package/dist/access.d.ts +141 -0
  4. package/dist/access.js +232 -0
  5. package/dist/codec.d.ts +29 -0
  6. package/dist/codec.js +361 -0
  7. package/dist/cron.d.ts +2 -0
  8. package/dist/cron.js +113 -0
  9. package/dist/ctx.d.ts +644 -0
  10. package/dist/ctx.js +657 -0
  11. package/dist/db.d.ts +234 -0
  12. package/dist/db.js +495 -0
  13. package/dist/decimal.d.ts +39 -0
  14. package/dist/decimal.js +158 -0
  15. package/dist/declare.d.ts +311 -0
  16. package/dist/declare.js +78 -0
  17. package/dist/descriptor.d.ts +229 -0
  18. package/dist/descriptor.js +899 -0
  19. package/dist/errors.d.ts +65 -0
  20. package/dist/errors.js +114 -0
  21. package/dist/index.d.ts +17 -0
  22. package/dist/index.js +34 -0
  23. package/dist/log.d.ts +39 -0
  24. package/dist/log.js +101 -0
  25. package/dist/names.d.ts +12 -0
  26. package/dist/names.js +41 -0
  27. package/dist/notify.d.ts +185 -0
  28. package/dist/notify.js +234 -0
  29. package/dist/platform.d.ts +61 -0
  30. package/dist/platform.js +47 -0
  31. package/dist/plugin.d.ts +43 -0
  32. package/dist/plugin.js +117 -0
  33. package/dist/query.d.ts +326 -0
  34. package/dist/query.js +794 -0
  35. package/dist/remote.d.ts +8 -0
  36. package/dist/remote.js +19 -0
  37. package/dist/schema.d.ts +487 -0
  38. package/dist/schema.js +405 -0
  39. package/dist/serve.d.ts +63 -0
  40. package/dist/serve.js +411 -0
  41. package/dist/sql.d.ts +13 -0
  42. package/dist/sql.js +33 -0
  43. package/dist/ui.d.ts +1867 -0
  44. package/dist/ui.js +3964 -0
  45. package/dist/viz-kinds.d.ts +12 -0
  46. package/dist/viz-kinds.js +14 -0
  47. package/package.json +33 -4
  48. package/proto/plugin.proto +994 -0
package/dist/db.js ADDED
@@ -0,0 +1,495 @@
1
+ // The repository of the plugin's own entities (`ctx.db(entity)`). The platform stores the rows; the SDK
2
+ // sends it typed requests: rows in the entity's protobuf JSON,
3
+ // filters as a tree of conditions on field handles (`note.f.title.eq('a')`, combined with `and`, `or`, `not`),
4
+ // orders (`note.f.title.desc()`). Reads return `Stored<E>`: the row and its system columns. A dependency's entity
5
+ // is read through the same calls with `dependency` set (`ctx.query(customer)`), and has no writes.
6
+ import { decodeFieldValue, decodeMessage, encodeFieldValue, encodeMessage, messageFields } from "./codec.js";
7
+ import { Decimal } from "./decimal.js";
8
+ import { RpcError, internal } from "./errors.js";
9
+ import { snake } from "./names.js";
10
+ import { Filter as FilterClass, navigations } from "./schema.js";
11
+ /** @internal The lock a read asks for, and the check that it is asked for inside a transaction. */
12
+ function wireLock(link, strength, wait) {
13
+ if (!strength) {
14
+ if (wait && wait !== "wait")
15
+ throw lockRefused("nowait() and skipLocked() go with forUpdate() or forShare()");
16
+ return {};
17
+ }
18
+ if (link.tx === "0") {
19
+ throw lockRefused("a row lock is taken inside a transaction: ctx.transaction(async (tx) => tx.db(e).get(id, { lock }))");
20
+ }
21
+ return {
22
+ lock: {
23
+ strength: strength === "update" ? "FOR_UPDATE" : "FOR_SHARE",
24
+ wait: wait === "nowait" ? "NOWAIT" : wait === "skipLocked" ? "SKIP_LOCKED" : "WAIT",
25
+ },
26
+ };
27
+ }
28
+ function lockRefused(message) {
29
+ return new RpcError(400, "invalid", message);
30
+ }
31
+ /** The names an `include` sends (snake_case) and the keys its rows come back under (as given). */
32
+ function includeNames(names) {
33
+ return { wire: names.map((n) => snake(n)), keys: [...names] };
34
+ }
35
+ function decodeRow(entity, raw) {
36
+ let json;
37
+ try {
38
+ json = JSON.parse(Buffer.from(raw).toString("utf8"));
39
+ }
40
+ catch (e) {
41
+ throw internal(e);
42
+ }
43
+ const errors = {};
44
+ const row = decodeMessage(entity, json, "", errors);
45
+ if (Object.keys(errors).length > 0)
46
+ throw internal(new Error(`the platform sent a row this plugin cannot read: ${JSON.stringify(errors)}`));
47
+ row.createdAt = new Date(String(json.createdAt));
48
+ row.updatedAt = new Date(String(json.updatedAt));
49
+ if (typeof json.deletedAt === "string")
50
+ row.deletedAt = new Date(json.deletedAt);
51
+ if (json.version !== undefined && json.version !== null)
52
+ row.version = BigInt(String(json.version));
53
+ return row;
54
+ }
55
+ /** A row an include brought: decoded as its entity's when the SDK knows it, else its JSON as is. */
56
+ function decodeAny(entity, json) {
57
+ if (!entity)
58
+ return json;
59
+ return decodeRow(entity, Buffer.from(JSON.stringify(json)));
60
+ }
61
+ /** The target an included name brings, from the navigations the plugin's description recorded. */
62
+ function includedEntity(entity, name) {
63
+ const nav = navigations.get(entity)?.get(name);
64
+ if (!nav)
65
+ return undefined;
66
+ if (nav.kind === "inverse")
67
+ return nav.source;
68
+ return nav.target;
69
+ }
70
+ function decodeIncluded(entity, raw, names) {
71
+ let json = {};
72
+ if (raw && raw.length > 0) {
73
+ try {
74
+ json = JSON.parse(Buffer.from(raw).toString("utf8"));
75
+ }
76
+ catch (e) {
77
+ throw internal(e);
78
+ }
79
+ }
80
+ const out = {};
81
+ names.wire.forEach((wire, i) => {
82
+ const key = names.keys[i];
83
+ const v = json[wire];
84
+ const target = includedEntity(entity, wire);
85
+ if (Array.isArray(v))
86
+ out[key] = v.map((x) => decodeAny(target, x));
87
+ else if (v !== undefined && v !== null)
88
+ out[key] = decodeAny(target, v);
89
+ else
90
+ out[key] = navigations.get(entity)?.get(wire)?.kind === "inverse" ? [] : undefined;
91
+ });
92
+ return out;
93
+ }
94
+ function rowsOf(entity, r, include) {
95
+ if (!r.dbRows)
96
+ throw internal(new Error("the platform answered a db call with something else"));
97
+ const included = r.dbRows.included ?? [];
98
+ const rows = (r.dbRows.rows ?? []).map((b, i) => {
99
+ const row = decodeRow(entity, b);
100
+ if (include && include.wire.length > 0)
101
+ row.included = decodeIncluded(entity, included[i], include);
102
+ return row;
103
+ });
104
+ return { rows, next: r.dbRows.nextPageToken ?? "" };
105
+ }
106
+ function oneOf(entity, r, include) {
107
+ const row = rowsOf(entity, r, include).rows[0];
108
+ if (!row)
109
+ throw internal(new Error("the platform answered without the row"));
110
+ return row;
111
+ }
112
+ /** The id the store replaces on create (`uuid` and `i64` keys); a `string` key is the row's own. */
113
+ function placeholder(entity) {
114
+ return entity.key === "i64" ? "0" : entity.key === "uuid" ? "00000000-0000-0000-0000-000000000000" : "";
115
+ }
116
+ /** A call that goes when it is awaited, after options such as `expectVersion`. */
117
+ export class Pending {
118
+ run;
119
+ constructor(run) {
120
+ this.run = run;
121
+ }
122
+ then(onOk, onErr) {
123
+ return this.run().then(onOk, onErr);
124
+ }
125
+ }
126
+ /** An update: `await db.update(id, patch).expectVersion(v)`. */
127
+ export class Update extends Pending {
128
+ expected;
129
+ constructor(send) {
130
+ super(() => send(this.expected));
131
+ }
132
+ /** Refuses the update (409 `version_conflict`) unless the row is at this version. */
133
+ expectVersion(v) {
134
+ this.expected = v === undefined ? undefined : BigInt(v);
135
+ return this;
136
+ }
137
+ }
138
+ /** A delete: `await db.delete(id).expectVersion(v)`. */
139
+ export class Delete extends Pending {
140
+ expected;
141
+ constructor(send) {
142
+ super(() => send(this.expected));
143
+ }
144
+ expectVersion(v) {
145
+ this.expected = v === undefined ? undefined : BigInt(v);
146
+ return this;
147
+ }
148
+ }
149
+ /** A query being built: `db.find(filter).orderBy(..).limit(..)`, read with `all()`, `first()` or `page()`. */
150
+ export class Find {
151
+ repo;
152
+ filter;
153
+ order = [];
154
+ size = 0;
155
+ token = "";
156
+ deleted = false;
157
+ navs = [];
158
+ /** @internal set by the lock methods of `TxFind` */
159
+ lockStrength;
160
+ /** @internal */
161
+ lockWait;
162
+ constructor(repo, filter) {
163
+ this.repo = repo;
164
+ this.filter = filter;
165
+ }
166
+ /**
167
+ * Brings each row's navigations with it, read under their targets' own rules: a forward one (a ref's `nav`, by
168
+ * default the column's name without `Id`, or the ref column itself) brings the row it names, an inverse one the
169
+ * rows that point at this one. They come back in `row.included`, under the names given here; the rows they bring
170
+ * count toward the 1,000 of a read (422 `query_rows_limit`).
171
+ */
172
+ include(...navs) {
173
+ this.navs.push(...navs);
174
+ return this;
175
+ }
176
+ /** Orders by a column; called again, by the next one (ties end by id). */
177
+ orderBy(o) {
178
+ this.order.push({ field: o.field, desc: o.desc });
179
+ return this;
180
+ }
181
+ /** Rows per page (100 at most; 100 by default). */
182
+ limit(n) {
183
+ this.size = n;
184
+ return this;
185
+ }
186
+ /** The page after the one whose `next` this is. */
187
+ pageToken(token) {
188
+ this.token = token;
189
+ return this;
190
+ }
191
+ /** Soft-deleted rows too. */
192
+ withDeleted() {
193
+ this.deleted = true;
194
+ return this;
195
+ }
196
+ send(all, limit) {
197
+ const lock = wireLock(this.repo.link, this.lockStrength, this.lockWait);
198
+ return this.repo.send({
199
+ dbFind: {
200
+ ...this.repo.head(),
201
+ ...(this.filter.node ? { filter: this.filter.node } : {}),
202
+ order: this.order,
203
+ limit,
204
+ pageToken: this.token,
205
+ withDeleted: this.deleted,
206
+ all,
207
+ include: includeNames(this.navs).wire,
208
+ ...lock,
209
+ },
210
+ });
211
+ }
212
+ /** Every matching row: more than 1,000 is 422 `query_rows_limit` (page through them instead). */
213
+ async all() {
214
+ return rowsOf(this.repo.entity, await this.send(true, 0), includeNames(this.navs)).rows;
215
+ }
216
+ async first() {
217
+ return rowsOf(this.repo.entity, await this.send(false, 1), includeNames(this.navs)).rows[0];
218
+ }
219
+ async page() {
220
+ const { rows, next } = rowsOf(this.repo.entity, await this.send(false, this.size), includeNames(this.navs));
221
+ return next ? { rows, next } : { rows };
222
+ }
223
+ }
224
+ /**
225
+ * A query in a transaction (`tx.db(e).find(f)`), which may lock the rows it reads until the transaction ends:
226
+ * `forUpdate()` or `forShare()`, then `nowait()` (409 `row_locked` at once instead of waiting) or `skipLocked()`
227
+ * (leaves out the rows another transaction holds: a work queue). Waiting counts against the transaction's 5 s.
228
+ */
229
+ export class TxFind extends Find {
230
+ /** Locks the rows read against changes (`FOR UPDATE`). */
231
+ forUpdate() {
232
+ this.lockStrength = "update";
233
+ return this;
234
+ }
235
+ /** Locks the rows read against changes by others, letting them lock for share too (`FOR SHARE`). */
236
+ forShare() {
237
+ this.lockStrength = "share";
238
+ return this;
239
+ }
240
+ /** Fails at once with 409 `row_locked` when a row is held by another transaction. */
241
+ nowait() {
242
+ this.lockWait = "nowait";
243
+ return this;
244
+ }
245
+ /** Leaves out the rows another transaction holds. */
246
+ skipLocked() {
247
+ this.lockWait = "skipLocked";
248
+ return this;
249
+ }
250
+ }
251
+ /**
252
+ * The reads of an entity: of a dependency's (`ctx.query(customer)`, which has no writes), and of the plugin's own
253
+ * (`Repository`, which adds them).
254
+ */
255
+ export class ReadRepository {
256
+ link;
257
+ entity;
258
+ name;
259
+ dependency;
260
+ constructor(
261
+ /** @internal */ link,
262
+ /** @internal */ entity,
263
+ /** @internal */ name,
264
+ /** @internal the provider whose entity this reads; "" for the plugin's own */
265
+ dependency = "") {
266
+ this.link = link;
267
+ this.entity = entity;
268
+ this.name = name;
269
+ this.dependency = dependency;
270
+ }
271
+ /** @internal */
272
+ head() {
273
+ const head = { requestId: this.link.requestId, tx: this.link.tx, entity: this.name, asSystem: this.link.asSystem };
274
+ return this.dependency ? { ...head, dependency: this.dependency } : head;
275
+ }
276
+ /** @internal */
277
+ send(call) {
278
+ return this.link.syscall(call);
279
+ }
280
+ /**
281
+ * A row by id; 404 `not_found` when there is none, or it is soft-deleted (`withDeleted` reads those too).
282
+ * `include` brings its navigations (`Find.include`).
283
+ */
284
+ async get(id, options = {}) {
285
+ // a lock outside a transaction (past the types, from JavaScript) is refused by `wireLock` before anything is sent
286
+ const { lock, wait } = options;
287
+ return this.getting(id, options, lock, wait);
288
+ }
289
+ /** @internal */
290
+ async getting(id, options, strength, wait) {
291
+ const names = includeNames(options.include ?? []);
292
+ const lock = wireLock(this.link, strength, wait);
293
+ const r = await this.send({ dbGet: { ...this.head(), id, withDeleted: !!options.withDeleted, include: names.wire, ...lock } });
294
+ return oneOf(this.entity, r, names);
295
+ }
296
+ async aggregate(query) {
297
+ const handles = this.entity.f;
298
+ const handle = (key, what) => {
299
+ const h = handles[key];
300
+ if (!h)
301
+ throw internal(new Error(`aggregate: ${key} is not a ${what} of ${this.name}`));
302
+ return h;
303
+ };
304
+ const group = query.groupBy === undefined ? undefined : handle(String(query.groupBy), "column");
305
+ const summed = query.sum === undefined ? undefined : handle(String(query.sum), "column");
306
+ if ((summed === undefined) === (query.count === undefined)) {
307
+ throw internal(new Error("aggregate: give it count: true or sum: '<column>'"));
308
+ }
309
+ const filter = query.where?.node;
310
+ const r = await this.send({
311
+ dbAggregate: {
312
+ ...this.head(),
313
+ ...(filter ? { filter } : {}),
314
+ withDeleted: !!query.withDeleted,
315
+ groupBy: group?.name ?? "",
316
+ measure: summed ? "SUM" : "COUNT",
317
+ field: summed?.name ?? "",
318
+ },
319
+ });
320
+ if (!r.dbGroups)
321
+ throw internal(new Error("the platform answered an aggregate with something else"));
322
+ return (r.dbGroups.groups ?? []).map((g) => {
323
+ const errors = {};
324
+ const parse = (b) => {
325
+ try {
326
+ return JSON.parse(Buffer.from(b).toString("utf8"));
327
+ }
328
+ catch (e) {
329
+ throw internal(e);
330
+ }
331
+ };
332
+ const out = {};
333
+ if (group && query.groupBy !== undefined) {
334
+ const key = decodeFieldValue(group.field, parse(g.key), String(query.groupBy), errors);
335
+ if (Object.keys(errors).length > 0)
336
+ throw internal(new Error(`the platform sent a group key this plugin cannot read: ${JSON.stringify(errors)}`));
337
+ out[String(query.groupBy)] = key;
338
+ }
339
+ const value = parse(g.value);
340
+ if (summed)
341
+ out.sum = sumValue(summed.field, value);
342
+ else
343
+ out.count = Number(value);
344
+ return out;
345
+ });
346
+ }
347
+ /** The rows matching `filter` (every row without one). */
348
+ find(filter = FilterClass.all()) {
349
+ return new Find(this, filter);
350
+ }
351
+ async count(filter = FilterClass.all()) {
352
+ const r = await this.send({ dbCount: { ...this.head(), ...(filter.node ? { filter: filter.node } : {}) } });
353
+ if (!r.dbCount)
354
+ throw internal(new Error("the platform answered a count with something else"));
355
+ return Number(r.dbCount.count);
356
+ }
357
+ async exists(filter) {
358
+ return (await this.find(filter).first()) !== undefined;
359
+ }
360
+ /** Every row: more than 1,000 is 422 `query_rows_limit` (page through them with `find().page()` instead). */
361
+ async all() {
362
+ return this.find().all();
363
+ }
364
+ }
365
+ /** A sum as the field's type: int32 and int64 a bigint, a decimal a `Decimal`, a double a number. */
366
+ function sumValue(field, v) {
367
+ switch (field.spec.scalar) {
368
+ case "decimal":
369
+ return Decimal.parse(String(v ?? "0"));
370
+ case "double":
371
+ return Number(v ?? 0);
372
+ default:
373
+ return BigInt(String(v ?? "0"));
374
+ }
375
+ }
376
+ /** The repository of an entity of the plugin: `ctx.db(order)` (in a transaction, `tx.db(order)`). */
377
+ export class Repository extends ReadRepository {
378
+ constructor(link, entity, name) {
379
+ super(link, entity, name);
380
+ }
381
+ /** A new row: the store makes a `uuid` or `i64` key; a `string` key is the row's `id`. */
382
+ async create(row) {
383
+ const [created] = await this.createMany([row]);
384
+ if (!created)
385
+ throw internal(new Error("the platform answered a create without the row"));
386
+ return created;
387
+ }
388
+ /** New rows, in one statement (at most 1,000). */
389
+ async createMany(rows) {
390
+ const wire = rows.map((r) => {
391
+ const value = { ...r };
392
+ if (value.id === undefined)
393
+ value.id = placeholder(this.entity);
394
+ return Buffer.from(JSON.stringify(encodeMessage(this.entity, value)));
395
+ });
396
+ return rowsOf(this.entity, await this.send({ dbCreate: { ...this.head(), rows: wire } })).rows;
397
+ }
398
+ /** Changes the fields `patch` names (`null` clears an optional one); `.expectVersion(v)` checks the row's version. */
399
+ update(id, patch) {
400
+ return new Update(async (expected) => {
401
+ const json = this.patchJson(patch, "update");
402
+ const r = await this.send({
403
+ dbUpdate: {
404
+ ...this.head(),
405
+ id,
406
+ patch: Buffer.from(JSON.stringify(json)),
407
+ ...(expected === undefined ? {} : { expectedVersion: expected.toString() }),
408
+ },
409
+ });
410
+ return oneOf(this.entity, r);
411
+ });
412
+ }
413
+ /** Deletes a row (marks it, on a soft-delete entity); `.expectVersion(v)` checks its version. */
414
+ delete(id) {
415
+ return this.deleting(id, false);
416
+ }
417
+ /** Removes a row of a soft-delete entity for good. */
418
+ deleteForce(id) {
419
+ return this.deleting(id, true);
420
+ }
421
+ /**
422
+ * Changes the fields `patch` names on every row `where` matches that the caller may read (`Filter.all()` for
423
+ * every row), in one statement: each row passes the `update` rule and the guards as `update` does (one that does
424
+ * not refuses them all: 403); `version` and `updatedAt` move on each. More than 1,000 rows is 422 `bulk_limit`,
425
+ * and nothing is written. Answers how many rows changed.
426
+ */
427
+ async updateWhere(where, patch) {
428
+ const json = this.patchJson(patch, "updateWhere");
429
+ const r = await this.send({
430
+ dbUpdateWhere: {
431
+ ...this.head(),
432
+ ...(where.node ? { filter: where.node } : {}),
433
+ patch: Buffer.from(JSON.stringify(json)),
434
+ },
435
+ });
436
+ if (!r.dbCount)
437
+ throw internal(new Error("the platform answered an updateWhere with something else"));
438
+ return Number(r.dbCount.count);
439
+ }
440
+ /**
441
+ * Creates `row`, or changes the row with the same value of the unique column `on` to it (`id` only for a
442
+ * `string` key): the new row passes the `create` rule, the changed one the `update` rule and the guards.
443
+ */
444
+ async upsert(on, row) {
445
+ const value = { ...row };
446
+ if (value.id === undefined)
447
+ value.id = placeholder(this.entity);
448
+ const wire = Buffer.from(JSON.stringify(encodeMessage(this.entity, value)));
449
+ return oneOf(this.entity, await this.send({ dbUpsert: { ...this.head(), on: snake(on), row: wire } }));
450
+ }
451
+ /** @internal A patch as the row's JSON writes it. */
452
+ patchJson(patch, what) {
453
+ const fields = new Map(messageFields(this.entity).map((f) => [f.key, f]));
454
+ const json = {};
455
+ for (const [key, v] of Object.entries(patch)) {
456
+ const f = fields.get(key);
457
+ if (!f || key === "id")
458
+ throw internal(new Error(`${what}: ${key} is not a column of ${this.name}`));
459
+ json[f.json] = v === null ? null : encodeColumn(f.field, v, key);
460
+ }
461
+ return json;
462
+ }
463
+ /** Brings a soft-deleted row back. */
464
+ async restore(id) {
465
+ return oneOf(this.entity, await this.send({ dbRestore: { ...this.head(), id } }));
466
+ }
467
+ deleting(id, force) {
468
+ return new Delete(async (expected) => {
469
+ await this.send({
470
+ dbDelete: { ...this.head(), id, force, ...(expected === undefined ? {} : { expectedVersion: expected.toString() }) },
471
+ });
472
+ });
473
+ }
474
+ }
475
+ /**
476
+ * The repository of an entity in a transaction (`tx.db(order)`): reads may lock their rows until it ends, with
477
+ * `get(id, { lock: 'update' })` and `find(f).forUpdate()`; outside a transaction they are refused (400 `invalid`).
478
+ */
479
+ export class TxRepository extends Repository {
480
+ async get(id, options = {}) {
481
+ return this.getting(id, options, options.lock, options.wait);
482
+ }
483
+ find(filter = FilterClass.all()) {
484
+ return new TxFind(this, filter);
485
+ }
486
+ }
487
+ /** One column's value as the row's JSON writes it. */
488
+ function encodeColumn(field, v, path) {
489
+ if (field.spec.kind === "array") {
490
+ if (!Array.isArray(v))
491
+ throw internal(new Error(`update: ${path} is a list`));
492
+ return v.map((x, i) => encodeFieldValue(field.spec.inner, x, `${path}[${i}]`));
493
+ }
494
+ return encodeFieldValue(field, v, path);
495
+ }
@@ -0,0 +1,39 @@
1
+ export type DecimalLike = Decimal | string | number | bigint;
2
+ export declare class Decimal {
3
+ /** the value is `coefficient × 10^-scale` */
4
+ readonly coefficient: bigint;
5
+ readonly scale: number;
6
+ static readonly ZERO: Decimal;
7
+ static readonly ONE: Decimal;
8
+ static readonly HUNDRED: Decimal;
9
+ private constructor();
10
+ /** A decimal from a string (`"12.50"`, `"-1e3"`), an integer, a finite number or a bigint. */
11
+ static from(value: DecimalLike): Decimal;
12
+ /** Parses a decimal string; throws a `SyntaxError` for anything else. */
13
+ static parse(text: string): Decimal;
14
+ /** The sum of the values (zero for none). */
15
+ static sum(values: Iterable<DecimalLike>): Decimal;
16
+ private static align;
17
+ add(other: DecimalLike): Decimal;
18
+ sub(other: DecimalLike): Decimal;
19
+ mul(other: DecimalLike): Decimal;
20
+ /** Division to 28 fractional digits, half away from zero, trailing zeros dropped; a zero divisor throws. */
21
+ div(other: DecimalLike): Decimal;
22
+ /** Rounds to `digits` fractional digits, half away from zero (`2.345` → `2.35`, `-2.345` → `-2.35`). */
23
+ round(digits?: number): Decimal;
24
+ /** Drops trailing fractional zeros, keeping at least `minScale` digits. */
25
+ normalize(minScale?: number): Decimal;
26
+ neg(): Decimal;
27
+ abs(): Decimal;
28
+ /** -1, 0 or 1. */
29
+ cmp(other: DecimalLike): number;
30
+ eq(other: DecimalLike): boolean;
31
+ lt(other: DecimalLike): boolean;
32
+ gt(other: DecimalLike): boolean;
33
+ isZero(): boolean;
34
+ /** The nearest JavaScript number (may lose precision). */
35
+ toNumber(): number;
36
+ /** Plain notation with the scale kept: `12.50`, `-0.05`, `3`. */
37
+ toString(): string;
38
+ toJSON(): string;
39
+ }
@@ -0,0 +1,158 @@
1
+ // Decimal: exact base-10 numbers (a bigint coefficient and a scale), the SDK's type of `t.decimal()`.
2
+ //
3
+ // Addition, subtraction and multiplication are exact. Division keeps up to 28 fractional digits, rounded half
4
+ // away from zero, without trailing zeros. `round(n)` is half away from zero, as in every celobus SDK. On the wire
5
+ // a decimal is a string (`"12.50"`): the scale is kept, so `12.50` stays `12.50`.
6
+ const PATTERN = /^([+-])?(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
7
+ const DIV_SCALE = 28;
8
+ function pow10(n) {
9
+ return 10n ** BigInt(n);
10
+ }
11
+ /** Divides and rounds half away from zero. */
12
+ function divRound(n, d) {
13
+ const negative = n < 0n !== d < 0n;
14
+ const an = n < 0n ? -n : n;
15
+ const ad = d < 0n ? -d : d;
16
+ let q = an / ad;
17
+ if ((an % ad) * 2n >= ad)
18
+ q += 1n;
19
+ return negative ? -q : q;
20
+ }
21
+ export class Decimal {
22
+ coefficient;
23
+ scale;
24
+ static ZERO = new Decimal(0n, 0);
25
+ static ONE = new Decimal(1n, 0);
26
+ static HUNDRED = new Decimal(100n, 0);
27
+ constructor(
28
+ /** the value is `coefficient × 10^-scale` */
29
+ coefficient, scale) {
30
+ this.coefficient = coefficient;
31
+ this.scale = scale;
32
+ }
33
+ /** A decimal from a string (`"12.50"`, `"-1e3"`), an integer, a finite number or a bigint. */
34
+ static from(value) {
35
+ if (value instanceof Decimal)
36
+ return value;
37
+ if (typeof value === "bigint")
38
+ return new Decimal(value, 0);
39
+ if (typeof value === "number") {
40
+ if (!Number.isFinite(value))
41
+ throw new RangeError(`not a finite number: ${value}`);
42
+ if (Number.isInteger(value) && Number.isSafeInteger(value))
43
+ return new Decimal(BigInt(value), 0);
44
+ return Decimal.parse(String(value));
45
+ }
46
+ if (typeof value === "string")
47
+ return Decimal.parse(value);
48
+ throw new TypeError(`not a decimal: ${String(value)}`);
49
+ }
50
+ /** Parses a decimal string; throws a `SyntaxError` for anything else. */
51
+ static parse(text) {
52
+ const m = PATTERN.exec(text.trim());
53
+ if (!m || (!m[2] && !m[3]))
54
+ throw new SyntaxError(`not a decimal: ${JSON.stringify(text)}`);
55
+ const [, sign, int = "", frac = "", exp = "0"] = m;
56
+ let coefficient = BigInt((int || "0") + frac);
57
+ if (sign === "-")
58
+ coefficient = -coefficient;
59
+ let scale = frac.length - Number(exp);
60
+ if (scale < 0) {
61
+ coefficient *= pow10(-scale);
62
+ scale = 0;
63
+ }
64
+ return new Decimal(coefficient, scale);
65
+ }
66
+ /** The sum of the values (zero for none). */
67
+ static sum(values) {
68
+ let total = Decimal.ZERO;
69
+ for (const v of values)
70
+ total = total.add(v);
71
+ return total;
72
+ }
73
+ static align(a, b) {
74
+ const scale = Math.max(a.scale, b.scale);
75
+ return [a.coefficient * pow10(scale - a.scale), b.coefficient * pow10(scale - b.scale), scale];
76
+ }
77
+ add(other) {
78
+ const [a, b, scale] = Decimal.align(this, Decimal.from(other));
79
+ return new Decimal(a + b, scale);
80
+ }
81
+ sub(other) {
82
+ const [a, b, scale] = Decimal.align(this, Decimal.from(other));
83
+ return new Decimal(a - b, scale);
84
+ }
85
+ mul(other) {
86
+ const o = Decimal.from(other);
87
+ return new Decimal(this.coefficient * o.coefficient, this.scale + o.scale);
88
+ }
89
+ /** Division to 28 fractional digits, half away from zero, trailing zeros dropped; a zero divisor throws. */
90
+ div(other) {
91
+ const o = Decimal.from(other);
92
+ if (o.coefficient === 0n)
93
+ throw new RangeError("division by zero");
94
+ // this / o = (c1 / c2) × 10^(s2 - s1); computed at DIV_SCALE fractional digits
95
+ const shift = DIV_SCALE + o.scale - this.scale;
96
+ const n = shift >= 0 ? this.coefficient * pow10(shift) : this.coefficient;
97
+ const d = shift >= 0 ? o.coefficient : o.coefficient * pow10(-shift);
98
+ return new Decimal(divRound(n, d), DIV_SCALE).normalize(Math.max(this.scale, 0));
99
+ }
100
+ /** Rounds to `digits` fractional digits, half away from zero (`2.345` → `2.35`, `-2.345` → `-2.35`). */
101
+ round(digits = 0) {
102
+ if (!Number.isInteger(digits) || digits < 0)
103
+ throw new RangeError(`bad number of digits: ${digits}`);
104
+ if (digits >= this.scale)
105
+ return new Decimal(this.coefficient * pow10(digits - this.scale), digits);
106
+ return new Decimal(divRound(this.coefficient, pow10(this.scale - digits)), digits);
107
+ }
108
+ /** Drops trailing fractional zeros, keeping at least `minScale` digits. */
109
+ normalize(minScale = 0) {
110
+ let { coefficient, scale } = this;
111
+ while (scale > minScale && coefficient % 10n === 0n) {
112
+ coefficient /= 10n;
113
+ scale -= 1;
114
+ }
115
+ return new Decimal(coefficient, scale);
116
+ }
117
+ neg() {
118
+ return new Decimal(-this.coefficient, this.scale);
119
+ }
120
+ abs() {
121
+ return this.coefficient < 0n ? this.neg() : this;
122
+ }
123
+ /** -1, 0 or 1. */
124
+ cmp(other) {
125
+ const [a, b] = Decimal.align(this, Decimal.from(other));
126
+ return a < b ? -1 : a > b ? 1 : 0;
127
+ }
128
+ eq(other) {
129
+ return this.cmp(other) === 0;
130
+ }
131
+ lt(other) {
132
+ return this.cmp(other) < 0;
133
+ }
134
+ gt(other) {
135
+ return this.cmp(other) > 0;
136
+ }
137
+ isZero() {
138
+ return this.coefficient === 0n;
139
+ }
140
+ /** The nearest JavaScript number (may lose precision). */
141
+ toNumber() {
142
+ return Number(this.toString());
143
+ }
144
+ /** Plain notation with the scale kept: `12.50`, `-0.05`, `3`. */
145
+ toString() {
146
+ const negative = this.coefficient < 0n;
147
+ const digits = (negative ? -this.coefficient : this.coefficient).toString();
148
+ if (this.scale === 0)
149
+ return (negative ? "-" : "") + digits;
150
+ const padded = digits.padStart(this.scale + 1, "0");
151
+ const int = padded.slice(0, padded.length - this.scale);
152
+ const frac = padded.slice(padded.length - this.scale);
153
+ return `${negative ? "-" : ""}${int}.${frac}`;
154
+ }
155
+ toJSON() {
156
+ return this.toString();
157
+ }
158
+ }