fadodb-vm 0.0.0-stage → 4.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.
- package/LICENSE +201 -0
- package/README.md +36 -2
- package/fadodb-vm.d.ts +308 -0
- package/fadodb-vm.iife.js +1 -0
- package/fadodb-vm.js +1 -0
- package/package.json +26 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# fadodb-vm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The formula machine of [FadoDB](https://fadodb.org) for a page. A page
|
|
4
|
+
that shows a document works its formulas out itself, as the person
|
|
5
|
+
types, with the same answers the server gives. It is given each formula
|
|
6
|
+
compiled by the engine, the bytecode, and runs it; it never parses a
|
|
7
|
+
formula.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { decode, VM, number } from "fadodb-vm";
|
|
11
|
+
|
|
12
|
+
const program = decode(bytes); // the bytecode, a Uint8Array, from the server
|
|
13
|
+
const value = new VM().run(program, [number(12), number(3)], { user: "ann" });
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Or with a script tag, which defines the global `FadoDB`:
|
|
17
|
+
|
|
18
|
+
```html
|
|
19
|
+
<script src="https://cdn.jsdelivr.net/npm/fadodb-vm@4/fadodb-vm.iife.js"></script>
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- **One file, no dependency**: an ES module, a classic script and the
|
|
23
|
+
declarations for TypeScript, each well under 100 KB.
|
|
24
|
+
- **The server's answers**: plain numbers, text, logic, dates and
|
|
25
|
+
moments, exact numbers and money on `BigInt`. Every case of the
|
|
26
|
+
engine's conformance suite that a page runs passes, on every push.
|
|
27
|
+
- **Fast**: a document of 200 formulas recalculates in about 13
|
|
28
|
+
microseconds.
|
|
29
|
+
- **The version follows the bytecode**: 4.x runs the programs of
|
|
30
|
+
bytecode format 4. A page pins the major version to the format its
|
|
31
|
+
server writes, and the VM refuses a program of another format.
|
|
32
|
+
|
|
33
|
+
A formula that reads other documents is worked out by the server, and
|
|
34
|
+
the page is given its last value.
|
|
35
|
+
|
|
36
|
+
Apache License 2.0. The source, the decisions and the tests are at
|
|
37
|
+
[github.com/MojoHand70/fadodb](https://github.com/MojoHand70/fadodb/tree/main/web/vm).
|
package/fadodb-vm.d.ts
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// fadodb-vm: the formula machine of FadoDB for a page (ADR-0029).
|
|
2
|
+
// Generated from the TypeScript sources by web/vm/build.mjs.
|
|
3
|
+
|
|
4
|
+
/** The version of the bytecode this file reads. */
|
|
5
|
+
export declare const FORMAT_VERSION = 4;
|
|
6
|
+
|
|
7
|
+
/** A static type: a kind, the scale of an exact one, the element of an array. */
|
|
8
|
+
export interface Type {
|
|
9
|
+
readonly kind: KindCode;
|
|
10
|
+
readonly scale: number;
|
|
11
|
+
readonly elem: KindCode;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Reads a type as the engine writes it: number, decimal(2), array<text>. */
|
|
15
|
+
export declare function parseType(s: string): Type;
|
|
16
|
+
|
|
17
|
+
/** One variable a program reads; values are given in slot order. */
|
|
18
|
+
export interface Slot {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly type: Type;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** An exact constant: a mantissa at a scale. */
|
|
24
|
+
interface DecConst {
|
|
25
|
+
readonly mant: bigint;
|
|
26
|
+
readonly scale: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A compiled LOOKUP, or an aggregate over a class (ADR-0020, ADR-0046). The
|
|
31
|
+
* browser reads it to know the program reads other documents; the server
|
|
32
|
+
* works it out.
|
|
33
|
+
*/
|
|
34
|
+
interface QuerySlot {
|
|
35
|
+
readonly source: string;
|
|
36
|
+
readonly column: string;
|
|
37
|
+
readonly type: Type;
|
|
38
|
+
readonly order: readonly string[];
|
|
39
|
+
readonly args: readonly number[];
|
|
40
|
+
readonly argNames: readonly string[];
|
|
41
|
+
readonly cond: Program | null;
|
|
42
|
+
readonly key: Program | null;
|
|
43
|
+
readonly indexColumn: string;
|
|
44
|
+
readonly keyPart: boolean;
|
|
45
|
+
readonly agg: string;
|
|
46
|
+
readonly value: Program | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A compiled formula. */
|
|
50
|
+
export interface Program {
|
|
51
|
+
readonly nums: Float64Array;
|
|
52
|
+
readonly decs: readonly DecConst[];
|
|
53
|
+
readonly texts: readonly string[];
|
|
54
|
+
readonly slots: readonly Slot[];
|
|
55
|
+
/** The opcode of each instruction. */
|
|
56
|
+
readonly ops: Uint8Array;
|
|
57
|
+
/** The operand of each instruction. */
|
|
58
|
+
readonly args: Int32Array;
|
|
59
|
+
/** The offset in the formula's text of each instruction, or null. */
|
|
60
|
+
readonly pos: Int32Array | null;
|
|
61
|
+
readonly result: Type;
|
|
62
|
+
/** The classes of the functions it calls: pure, context, lookup. */
|
|
63
|
+
readonly classes: readonly string[];
|
|
64
|
+
readonly queries: readonly QuerySlot[];
|
|
65
|
+
/** The stack depth it needs. */
|
|
66
|
+
readonly maxStack: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Reads a program in the binary format of the engine. It refuses a program
|
|
71
|
+
* of another format version, one that ends early, and one whose operands
|
|
72
|
+
* are out of range, so that the VM can trust its tables.
|
|
73
|
+
*/
|
|
74
|
+
export declare function decode(bytes: Uint8Array): Program;
|
|
75
|
+
|
|
76
|
+
/** The codes a formula may stop with. */
|
|
77
|
+
export declare const ErrorCode: {
|
|
78
|
+
readonly DivByZero: "div_by_zero";
|
|
79
|
+
readonly NotANumber: "not_a_number";
|
|
80
|
+
readonly BadText: "bad_text";
|
|
81
|
+
readonly OutOfRange: "out_of_range";
|
|
82
|
+
readonly LengthMismatch: "length_mismatch";
|
|
83
|
+
readonly TooManyElements: "too_many_elements";
|
|
84
|
+
readonly QueryFailed: "query_failed";
|
|
85
|
+
readonly Overflow: "overflow";
|
|
86
|
+
readonly Inexact: "inexact";
|
|
87
|
+
readonly CurrencyMismatch: "currency_mismatch";
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The error a formula stopped with: its code, a message, and the offset in
|
|
92
|
+
* the formula's text of the operation that failed, -1 when not known.
|
|
93
|
+
*/
|
|
94
|
+
export declare class EvalError extends Error {
|
|
95
|
+
/** The code, one of ErrorCode. */
|
|
96
|
+
readonly code: string;
|
|
97
|
+
/** What went wrong, in words. */
|
|
98
|
+
readonly detail: string;
|
|
99
|
+
/** The offset in the formula's text of the operation that failed, -1 when not known. */
|
|
100
|
+
readonly pos: number;
|
|
101
|
+
constructor(
|
|
102
|
+
/** The code, one of ErrorCode. */
|
|
103
|
+
code: string,
|
|
104
|
+
/** What went wrong, in words. */
|
|
105
|
+
detail: string,
|
|
106
|
+
/** The offset in the formula's text of the operation that failed, -1 when not known. */
|
|
107
|
+
pos?: number);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The names of the VM's functions, in the order of the engine's table. */
|
|
111
|
+
export declare function builtinNames(): string[];
|
|
112
|
+
|
|
113
|
+
/** The value as text, as TEXT renders it. A blank is the empty text. */
|
|
114
|
+
export declare function render(v: Value): string;
|
|
115
|
+
|
|
116
|
+
/** The kinds of a value, numbered as the engine numbers them. */
|
|
117
|
+
export declare const Kind: {
|
|
118
|
+
readonly Blank: 0;
|
|
119
|
+
readonly Bool: 1;
|
|
120
|
+
readonly Number: 2;
|
|
121
|
+
readonly Decimal: 3;
|
|
122
|
+
readonly Money: 4;
|
|
123
|
+
readonly Text: 5;
|
|
124
|
+
readonly Date: 6;
|
|
125
|
+
readonly DateTime: 7;
|
|
126
|
+
readonly Ref: 8;
|
|
127
|
+
readonly JSON: 9;
|
|
128
|
+
readonly Array: 10;
|
|
129
|
+
readonly Rows: 11;
|
|
130
|
+
readonly Object: 12;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/** One of the numbers of Kind. */
|
|
134
|
+
export type KindCode = (typeof Kind)[keyof typeof Kind];
|
|
135
|
+
|
|
136
|
+
/** The names of the kinds, as the engine writes them. */
|
|
137
|
+
export declare const kindNames: readonly string[];
|
|
138
|
+
|
|
139
|
+
/** A value of a formula. */
|
|
140
|
+
export declare class Value {
|
|
141
|
+
/** What the value is, one of Kind. */
|
|
142
|
+
readonly kind: KindCode;
|
|
143
|
+
/** A number; 1 or 0 for a bool; days for a date; seconds for a datetime. */
|
|
144
|
+
readonly num: number;
|
|
145
|
+
/** A text, a ref or a json value; the currency of a money. */
|
|
146
|
+
readonly str: string;
|
|
147
|
+
/** The mantissa of a decimal or a money. */
|
|
148
|
+
readonly mant: bigint;
|
|
149
|
+
/** The digits after the point of a decimal or a money. */
|
|
150
|
+
readonly scale: number;
|
|
151
|
+
constructor(
|
|
152
|
+
/** What the value is, one of Kind. */
|
|
153
|
+
kind: KindCode,
|
|
154
|
+
/** A number; 1 or 0 for a bool; days for a date; seconds for a datetime. */
|
|
155
|
+
num: number,
|
|
156
|
+
/** A text, a ref or a json value; the currency of a money. */
|
|
157
|
+
str: string,
|
|
158
|
+
/** The mantissa of a decimal or a money. */
|
|
159
|
+
mant: bigint,
|
|
160
|
+
/** The digits after the point of a decimal or a money. */
|
|
161
|
+
scale: number);
|
|
162
|
+
/** Whether the value is blank. */
|
|
163
|
+
get isBlank(): boolean;
|
|
164
|
+
/** The value as a condition: TRUE is true, FALSE and blank are false. */
|
|
165
|
+
get truth(): boolean;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The blank value. */
|
|
169
|
+
export declare const BLANK: Value;
|
|
170
|
+
|
|
171
|
+
/** TRUE. */
|
|
172
|
+
export declare const TRUE: Value;
|
|
173
|
+
|
|
174
|
+
/** FALSE. */
|
|
175
|
+
export declare const FALSE: Value;
|
|
176
|
+
|
|
177
|
+
/** TRUE or FALSE. */
|
|
178
|
+
export declare function bool(b: boolean): Value;
|
|
179
|
+
|
|
180
|
+
/** A number. */
|
|
181
|
+
export declare function number(n: number): Value;
|
|
182
|
+
|
|
183
|
+
/** A text. */
|
|
184
|
+
export declare function text(s: string): Value;
|
|
185
|
+
|
|
186
|
+
/** A date, as days since 1970-01-01. */
|
|
187
|
+
export declare function date(days: number): Value;
|
|
188
|
+
|
|
189
|
+
/** A datetime, as seconds since 1970-01-01 00:00:00 UTC. */
|
|
190
|
+
export declare function datetime(secs: number): Value;
|
|
191
|
+
|
|
192
|
+
/** A reference to a document, in its Class:id form. */
|
|
193
|
+
export declare function ref(s: string): Value;
|
|
194
|
+
|
|
195
|
+
/** A json value, as its text. */
|
|
196
|
+
export declare function json(s: string): Value;
|
|
197
|
+
|
|
198
|
+
/** An exact number: decimal(1230n, 2) is 12.30. */
|
|
199
|
+
export declare function decimal(mant: bigint, scale: number): Value;
|
|
200
|
+
|
|
201
|
+
/** Money: a mantissa, a scale and a currency code. */
|
|
202
|
+
export declare function money(mant: bigint, scale: number, currency: string): Value;
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Whether two values are the same value of the same kind. An exact value
|
|
206
|
+
* compares by mantissa and scale, so 0.3 and 0.30 differ. It is the
|
|
207
|
+
* identity the tests use, not the = of the language.
|
|
208
|
+
*/
|
|
209
|
+
export declare function same(a: Value, b: Value): boolean;
|
|
210
|
+
|
|
211
|
+
/** The default text limit of a database: 65,536 code points (ADR-0021). */
|
|
212
|
+
export declare const DEFAULT_MAX_TEXT = 65536;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* What a document's life says of one state it has been in (ADR-0047, item
|
|
216
|
+
* 6), in the form the engine writes it: the moments in seconds, who made
|
|
217
|
+
* each move, how many times it entered, how long its stays that ended
|
|
218
|
+
* lasted, whether it is there now, and who first and last changed it
|
|
219
|
+
* there.
|
|
220
|
+
*/
|
|
221
|
+
export interface StateLife {
|
|
222
|
+
state: string;
|
|
223
|
+
/** First entered, and by whom. */
|
|
224
|
+
fe?: number;
|
|
225
|
+
feb?: string;
|
|
226
|
+
/** Last entered, and by whom. */
|
|
227
|
+
le?: number;
|
|
228
|
+
leb?: string;
|
|
229
|
+
/** First left, and by whom. */
|
|
230
|
+
fl?: number;
|
|
231
|
+
flb?: string;
|
|
232
|
+
/** Last left, and by whom. */
|
|
233
|
+
ll?: number;
|
|
234
|
+
llb?: string;
|
|
235
|
+
/** How many times it entered. */
|
|
236
|
+
n?: number;
|
|
237
|
+
/** The seconds of the stays that ended. */
|
|
238
|
+
secs?: number;
|
|
239
|
+
/** Whether the document is in the state now. */
|
|
240
|
+
here?: boolean;
|
|
241
|
+
/** Who first and last changed it in the state. */
|
|
242
|
+
fed?: string;
|
|
243
|
+
led?: string;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** What a document keeps of its life (ADR-0047), for the functions that read it. */
|
|
247
|
+
export interface Life {
|
|
248
|
+
version?: number;
|
|
249
|
+
/** Moments in seconds since the epoch, and who. */
|
|
250
|
+
created_at?: number;
|
|
251
|
+
created_by?: string;
|
|
252
|
+
updated_at?: number;
|
|
253
|
+
updated_by?: string;
|
|
254
|
+
entered_at?: number;
|
|
255
|
+
entered_by?: string;
|
|
256
|
+
entered_from?: string;
|
|
257
|
+
/** Each state it has been in, in the order it first entered them. */
|
|
258
|
+
states?: readonly StateLife[];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** What the context functions see (ADR-0015, ADR-0050, ADR-0052). */
|
|
262
|
+
export interface Context {
|
|
263
|
+
/** The id of the user the formula runs for. */
|
|
264
|
+
user?: string;
|
|
265
|
+
/** The groups the user is in. */
|
|
266
|
+
groups?: readonly string[];
|
|
267
|
+
/** The system groups the user is in. */
|
|
268
|
+
system?: readonly string[];
|
|
269
|
+
/** person, agent or service. */
|
|
270
|
+
kind?: string;
|
|
271
|
+
/** The id of whoever the user acts for. */
|
|
272
|
+
for?: string;
|
|
273
|
+
/** The moment, in seconds since the epoch, UTC; the clock when left out. */
|
|
274
|
+
now?: number;
|
|
275
|
+
/** The state of the document. */
|
|
276
|
+
state?: string;
|
|
277
|
+
/** The id of the document. */
|
|
278
|
+
id?: string;
|
|
279
|
+
/** The document's life. */
|
|
280
|
+
doc?: Life;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The options of a VM. */
|
|
284
|
+
export interface Options {
|
|
285
|
+
/** The longest text a formula may make, in code points (ADR-0021). */
|
|
286
|
+
maxText?: number;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Runs programs. One VM may run any number of programs, one at a time. */
|
|
290
|
+
export declare class VM {
|
|
291
|
+
/** The text limit, in code points. */
|
|
292
|
+
readonly maxText: number;
|
|
293
|
+
/** The context of the program being run. */
|
|
294
|
+
ctx: Context | undefined;
|
|
295
|
+
private stack;
|
|
296
|
+
private readonly tryPc;
|
|
297
|
+
private readonly trySp;
|
|
298
|
+
constructor(options?: Options);
|
|
299
|
+
/** The moment of the context in seconds, the clock when it has none. */
|
|
300
|
+
now(): number;
|
|
301
|
+
/**
|
|
302
|
+
* Runs the program over the values of its variables, one for each of
|
|
303
|
+
* its slots, in slot order, and answers its value. It throws the
|
|
304
|
+
* EvalError the formula stopped with.
|
|
305
|
+
*/
|
|
306
|
+
run(p: Program, vars: readonly Value[], ctx?: Context): Value;
|
|
307
|
+
}
|
|
308
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var FadoDB=(()=>{var Pn=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var dt=(n,e)=>{for(var t in e)Pn(n,t,{get:e[t],enumerable:!0})},bt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ft(e))!mt.call(n,o)&&o!==t&&Pn(n,o,{get:()=>e[o],enumerable:!(r=lt(e,o))||r.enumerable});return n};var gt=n=>bt(Pn({},"__esModule",{value:!0}),n);var Qt={};dt(Qt,{BLANK:()=>h,DEFAULT_MAX_TEXT:()=>ie,ErrorCode:()=>w,EvalError:()=>b,FALSE:()=>q,FORMAT_VERSION:()=>Vn,Kind:()=>c,TRUE:()=>an,VM:()=>Fn,Value:()=>B,bool:()=>V,builtinNames:()=>Wt,date:()=>j,datetime:()=>U,decimal:()=>A,decode:()=>oe,json:()=>Ae,kindNames:()=>Ne,money:()=>I,number:()=>E,parseType:()=>nn,ref:()=>En,render:()=>K,same:()=>De,text:()=>y});var w={DivByZero:"div_by_zero",NotANumber:"not_a_number",BadText:"bad_text",OutOfRange:"out_of_range",LengthMismatch:"length_mismatch",TooManyElements:"too_many_elements",QueryFailed:"query_failed",Overflow:"overflow",Inexact:"inexact",CurrencyMismatch:"currency_mismatch"},b=class extends Error{constructor(t,r,o=-1){super(o>=0?`${t}: ${r} at offset ${o}`:`${t}: ${r}`);this.code=t;this.detail=r;this.pos=o;this.name="EvalError"}},gn=new b(w.DivByZero,"/ by zero"),O=new b(w.NotANumber,"the result is not a finite number"),hn=new b(w.DivByZero,"MOD by zero"),ce=new b(w.QueryFailed,"the formula reads a table or other documents, which the server works out; the page is given its last value");function on(n){return new b(w.OutOfRange,n)}function C(){return on("the result is too long")}var Kn=22250738585072014e-324;function pn(n){let e=Math.trunc(n);return Math.abs(n-e)>=.5?e+Math.sign(n):e}var ht=(()=>{let n=new Float64Array(632);for(let e=0;e<n.length;e++)n[e]=+("1e"+(e-323));return n})();function $(n){return n<-323?0:n>308?1/0:ht[n+323]}function H(n){return n>0&&n<Kn?Math.log(n*18446744073709552e3)-64*Math.LN2:Math.log(n)}function me(n){if(n===0||!Number.isFinite(n))return[n,0];let e=0;Math.abs(n)<Kn&&(n*=4503599627370496,e=-52);let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,n);let r=t.getUint32(0);return e+=(r>>>20&2047)-1022,t.setUint32(0,r&2148532223|1022<<20),[t.getFloat64(0),e]}function pt(n,e){if(n===0||!Number.isFinite(n))return n;for(;e>1023;)if(n*=2**1023,e-=1023,!Number.isFinite(n))return n;if(e<-1022){for(;e<-1075;)if(n*=2**-1022,e+=1022,n===0)return n;return n*2**(e+53)*2**-53}return n*2**e}function $n(n,e){if(e===0||n===1)return 1;if(e===1)return n;if(Number.isNaN(n)||Number.isNaN(e))return NaN;if(n===0){let l=xt(e);if(e<0)return Object.is(n,-0)&&l?-1/0:1/0;if(e>0)return Object.is(n,-0)&&l?n:0}if(!Number.isFinite(e))return n===-1?1:Math.abs(n)<1==e>0?0:1/0;if(!Number.isFinite(n))return n<0?$n(1/n,-e):e<0?0:1/0;if(e===.5)return Math.sqrt(n);if(e===-.5)return 1/Math.sqrt(n);let t=Math.abs(e),r=Math.trunc(t),o=t-r;if(o!==0&&n<0)return NaN;if(r>=2**63)return n===-1?1:Math.abs(n)<1==e>0?0:1/0;let i=1,u=0;o!==0&&(o>.5&&(o--,r++),i=Math.exp(o*Math.log(n)));let[s,a]=me(n);for(let l=BigInt(r);l!==0n;l>>=1n){if(a<-4096||4096<a){u+=a;break}(l&1n)===1n&&(i*=s,u+=a),s*=s,a<<=1,s<.5&&(s+=s,a--)}return e<0&&(i=1/i,u=-u),pt(i,u)}function xt(n){return Math.abs(n)>=2**53?!1:Number.isInteger(n)&&Math.abs(n%2)===1}var le=134217729;function de(n,e,t){let r=le*n,o=r-(r-n),i=n-o;r=le*e;let u=r-(r-e),s=e-u,a=o*u-t+o*s+i*u+i*s;if(Number.isFinite(a))return a;let l=2**-600;return de(n*l,e,t*l)/l}function fe(n,e,t,r){let o=n*t;if(!Number.isFinite(o))return[o,0];let i=de(n,t,o)+n*r+e*t,u=o+i;return[u,i-(u-o)]}function xn(n,e){if(e===0||n===1)return 1;let t=Math.trunc(e),r=e-t;if(n<=0||!Number.isFinite(n)||Number.isNaN(e)||!Number.isFinite(e)||Math.abs(t)>2**62)return $n(n,e);let o=1;r===.5?o=Math.sqrt(n):r!==0&&(o=Math.exp(r*H(n)));let i=BigInt(t),u=i<0n;u&&(i=-i);let s=1,a=0,l=n,g=0;for(;i>0n;)if((i&1n)===1n&&([s,a]=fe(s,a,l,g)),i>>=1n,i>0n&&([l,g]=fe(l,g,l,g)),!Number.isFinite(s)||!Number.isFinite(l)||s===0)return $n(n,e);let m=s+a;return u&&(m=1/m),m*o}var yt=.3010299956639812,Et=1.4426950408889634;function kt(n){let[e,t]=me(n);return e===.5?t-1:Math.log(e)*Et+t}function be(n){let e=kt(n)*yt;n<Kn&&(e=H(n)/Math.LN10);let t=pn(e);return t!==e&&Math.abs(t)<=323&&$(t)===n?t:e}function G(n,e){let t=Math.trunc(e);if(t>300)return n;if(t<-300)return 0;let r=$(t),o=n*r;return Math.abs(o)>=2**52?n:pn(o)/r}function X(n,e,t){let r=Math.max(-300,Math.min(300,Math.trunc(e))),o=$(r),i=n*o;return Math.abs(i)>=2**52?n:t(G(i,9))/o}function L(n){let e=n.length;for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>=55296&&r<=56319&&t+1<n.length){let o=n.charCodeAt(t+1);o>=56320&&o<=57343&&(e--,t++)}}return e}function un(n,e){return n.length>e&&L(n)>e}function W(n){return Array.from(n)}function he(n,e){if(n===e)return 0;let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n.charCodeAt(r),i=e.charCodeAt(r);if(o!==i)return o>=55296&&i>=55296&&(o=o>=57344?o-2048:o+8192,i=i>=57344?i-2048:i+8192),o<i?-1:1}return n.length<e.length?-1:n.length>e.length?1:0}var pe={304:105},xe=(()=>{let n={8115:8124,8131:8140,8179:8188};for(let[e,t]of[[8064,8072],[8080,8088],[8096,8104]])for(let r=0;r<8;r++)n[e+r]=t+r;return n})();function yn(n,e,t){let r=n.codePointAt(0),o=t[r];if(o!==void 0)return String.fromCodePoint(o);let i=e(n);return i.length===1||i.length===2&&i.codePointAt(0)>65535?i:n}var ye=n=>n.toUpperCase(),Ee=n=>n.toLowerCase();function ke(n){let e="";for(let t of n)e+=yn(t,ye,xe);return e}function Me(n){let e="";for(let t of n)e+=yn(t,Ee,pe);return e}var Mt=/^\p{L}$/u;function Te(n){let e="",t=!1;for(let r of n)Mt.test(r)?(e+=t?yn(r,Ee,pe):yn(r,ye,xe),t=!0):(e+=r,t=!1);return e}var ge="[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]",Tt=new RegExp("^"+ge+"+|"+ge+"+$","g");function Y(n){return n.replace(Tt,"")}var wt=new TextEncoder;function we(n){return wt.encode(n)}var c={Blank:0,Bool:1,Number:2,Decimal:3,Money:4,Text:5,Date:6,DateTime:7,Ref:8,JSON:9,Array:10,Rows:11,Object:12},Ne=["blank","bool","number","decimal","money","text","date","datetime","ref","json","array","rows","object"],B=class{constructor(e,t,r,o,i){this.kind=e;this.num=t;this.str=r;this.mant=o;this.scale=i}get isBlank(){return this.kind===c.Blank}get truth(){return this.kind===c.Bool&&this.num!==0}},h=new B(c.Blank,0,"",0n,0),an=new B(c.Bool,1,"",0n,0),q=new B(c.Bool,0,"",0n,0);function V(n){return n?an:q}function E(n){return new B(c.Number,n,"",0n,0)}function y(n){return new B(c.Text,0,n,0n,0)}function j(n){return new B(c.Date,n,"",0n,0)}function U(n){return new B(c.DateTime,n,"",0n,0)}function En(n){return new B(c.Ref,0,n,0n,0)}function Ae(n){return new B(c.JSON,0,n,0n,0)}function A(n,e){return new B(c.Decimal,0,"",n,e)}function I(n,e,t){return new B(c.Money,0,t,n,e)}function _(n){return n===c.Decimal||n===c.Money}function De(n,e){if(n.kind!==e.kind)return!1;switch(n.kind){case c.Blank:return!0;case c.Bool:case c.Number:case c.Date:case c.DateTime:return n.num===e.num;case c.Decimal:return n.scale===e.scale&&n.mant===e.mant;case c.Money:return n.scale===e.scale&&n.mant===e.mant&&n.str===e.str;default:return n.str===e.str}}var Mn=18,Nt=4,Tn=-(2n**63n),At=2n**63n-1n,ve=2n**64n,N=new b(w.Overflow,"the exact result does not fit 18 digits"),sn=new b(w.CurrencyMismatch,"the currencies of one operation must agree"),_e=n=>n>=Tn&&n<=At,kn=n=>n<0n?-n:n,Dt=n=>n>0n?1n:n<0n?-1n:0n,Yn=n=>10n**BigInt(n);function wn(n,e){let t=n+e;return _e(t)?t:null}function Se(n,e){let t=n*e;return _e(t)?t:null}function v(n,e){return e<=0?n:e>Mn?n===0n?0n:null:Se(n,Yn(e))}function Bt(n,e){if(e===-1n)return n===Tn?null:-n;let t=n/e,r=n%e;return r!==0n&&2n*kn(r)>=kn(e)&&(t+=n<0n==e<0n?1n:-1n),t}function qn(n,e,t,r){if(t===0n)return gn;let o=Math.min(e+Nt,Mn),i=v(n,o-e+r);if(i===null)return N;let u=Bt(i,t);return u===null?N:[u,o]}function Re(n,e){if(e===0n)return hn;if(e===-1n)return 0n;let t=n%e;return t!==0n&&t<0n!=e<0n&&(t+=e),t}var M={HalfUp:0,HalfEven:1,Down:2,Up:3,Floor:4,Ceiling:5},vt={half_up:M.HalfUp,half_even:M.HalfEven,down:M.Down,up:M.Up,floor:M.Floor,ceiling:M.Ceiling};function jn(n){return(n!==void 0?vt[n]:void 0)??M.HalfUp}var Be=n=>2n*n%ve;function Jn(n,e,t,r){if(t>=e){let l=v(n,t-e);return l===null?null:[l,t]}let o=e-t,i,u,s;if(o>Mn)i=0n,u=n,s=ve-1n;else{let l=Yn(o);i=n/l,u=n%l,s=l}let a=Dt(n);switch(r){case M.HalfUp:u!==0n&&Be(kn(u))>=s&&(i+=a);break;case M.HalfEven:{let l=Be(kn(u));u!==0n&&(l>s||l===s&&(i&1n)!==0n)&&(i+=a);break}case M.Down:break;case M.Up:u!==0n&&(i+=a);break;case M.Floor:u!==0n&&n<0n&&i--;break;case M.Ceiling:u!==0n&&n>0n&&i++;break}if(t<0){let l=v(i,-t);return l===null?null:[l,0]}return[i,t]}function Oe(n,e,t){if(t>=e){let o=v(n,t-e);return o===null?N:o}let r=Yn(e-t);return n%r!==0n?new b(w.Inexact,`the value has more decimal places than ${t}`):n/r}function Ce(n){let e=()=>new b(w.BadText,"not a decimal: "+n),t=n,r=!1;t!==""&&(t[0]==="+"||t[0]==="-")&&(r=t[0]==="-",t=t.slice(1));let o="",i=t.search(/[eE]/);if(i>=0&&(o=t.slice(i+1),t=t.slice(0,i),o===""||(o[0]==="+"||o[0]==="-")&&o.length===1||!/^[+\-0-9][0-9]*$/.test(o)))return e();let u=t.indexOf("."),s=u>=0?t.slice(0,u):t,a=u>=0?t.slice(u+1):"";if(s===""&&a===""||!/^[0-9]*$/.test(s+a))return e();let l=(s+a).replace(/^0+/,"");if(l==="")return[0n,0];let g=0;if(o!==""){let d=Number(o);if(!Number.isFinite(d)||d>1e6||d<-1e6)return N;g=d}let m=a.length-g;if(m<0){if(-m>19)return N;l+="0".repeat(-m),m=0}if(m>Mn||l.length>19)return N;let p=BigInt(l);return p>2n**63n||p===2n**63n&&!r?N:[r?-p:p,m]}function Hn(n){return/^[A-Z]{3}$/.test(n)}function _t(n){let e=n.indexOf(" ");if(e<0||!Hn(n.slice(e+1)))return new b(w.BadText,"not an amount with a currency: "+n);let t=Ce(n.slice(0,e));return t instanceof b?t:[t[0],t[1],n.slice(e+1)]}function St(n){let e=Math.trunc(n),t=Math.abs(n-e);return t>.5||t===.5&&e%2!==0?e+Math.sign(n):e}function Gn(n,e,t){if(!Number.isFinite(n))return O;let r=n*$(e),o;switch(t){case M.HalfUp:o=pn(r);break;case M.HalfEven:o=St(r);break;default:{let i=G(r,9);switch(t){case M.Down:o=Math.trunc(i);break;case M.Up:o=i<0?Math.floor(i):Math.ceil(i);break;case M.Floor:o=Math.floor(i);break;default:o=Math.ceil(i)}}}return Math.abs(o)>=2**63?N:BigInt(o)}function Le(n,e){return Number(n)/$(e)}function P(n){switch(n.kind){case c.Decimal:case c.Money:return[n.mant,n.scale];case c.Bool:return[BigInt(n.num),0]}return[0n,0]}function Nn(n,e,t){return n.kind===c.Money?I(e,t,n.str):A(e,t)}function cn(n,e,t){return t!==""?I(n,e,t):A(n,e)}function Xn(n,e,t){let r=Y(n);if(r==="")return h;let o,i,u="";if(t){let a=_t(r);if(a instanceof b)return a;[o,i,u]=a}else{let a=Ce(r);if(a instanceof b)return a;[o,i]=a}let s=Oe(o,i,e);return s instanceof b?s:t?I(s,e,u):A(s,e)}var Ve=256;function Ie(n,e,t,r){let o=r&255,i=(r&Ve)!==0;if(n){if(i&&(t.kind===c.Decimal||t.kind===c.Number))return h;if(t.kind===c.Number){let s=Gn(t.num,o,M.HalfUp);return s instanceof b?s:A(s,o)}if((t.kind===c.Decimal||t.kind===c.Money)&&t.scale!==o){let s=Oe(t.mant,t.scale,o);return s instanceof b?s:Nn(t,s,o)}return t}if(t.kind===c.Blank||t.kind===c.Bool){if(i)return h;let s=BigInt(t.num);return A(e?-s:s,o)}let u=t.mant;if(e){if(u===Tn)return N;u=-u}return t.kind===c.Money?I(u,o,t.str):A(u,o)}function Fe(n,e,t){if(n.kind===c.Money&&e.kind===c.Money&&n.str!==e.str)return sn;let[r,o]=P(n),[i,u]=P(e),s=v(r,t-o),a=v(i,t-u);return s===null||a===null?N:s<a?-1:s>a?1:0}function Ue(n,e,t,r){let o=r&255,i=(r&Ve)!==0,u="";if(e.kind===c.Money&&(u=e.str),t.kind===c.Money){if(u!==""&&t.str!==u)return sn;u=t.str}let[s,a]=P(e),[l,g]=P(t),m,p;if(n<=1){let d=a<g?v(s,g-a):s,x=g<a?v(l,a-g):l;if(d===null||x===null)return N;if(p=Math.max(a,g),n===1){if(x===Tn)return N;x=-x}m=wn(d,x)}else if(n===2)m=Se(s,l),p=a+g;else{let d=qn(s,a,l,g);if(d instanceof b)return d;[m,p]=d}return m===null||p!==o&&(m=v(m,o-p),m===null)?N:i?u===""?h:I(m,o,u):A(m,o)}function Wn(n){if(n===0)return"0";if(!Number.isFinite(n))return n>0?"+Inf":n<0?"-Inf":"NaN";let[e,t]=Rt(Math.abs(n)),r=n<0?"-":"";if(e=e.replace(/0+$/,""),t<-4||t>=15){let o=e.length>1?e[0]+"."+e.slice(1):e,i=Math.abs(t);return r+o+"e"+(t<0?"-":"+")+(i<10?"0"+i:String(i))}return t<0?r+"0."+"0".repeat(-t-1)+e:e.length<=t+1?r+e+"0".repeat(t+1-e.length):r+e.slice(0,t+1)+"."+e.slice(t+1)}function Rt(n){let e=n.toExponential(20),t=e.indexOf("e"),r=e.slice(16,t);if(r.startsWith("5")&&/^50*$/.test(r))return Ot(n);let o=n.toExponential(14),i=o.indexOf("e");return[o[0]+o.slice(2,i),Number(o.slice(i+1))]}function Ot(n){let e=new DataView(new ArrayBuffer(8));e.setFloat64(0,n);let t=e.getBigUint64(0),r=Number(t>>52n&0x7ffn),o=t&0xfffffffffffffn,i;r===0?i=-1074:(o|=1n<<52n,i=r-1075);let u=o,s=1n;i>=0?u<<=BigInt(i):s<<=BigInt(-i);let a=Math.floor(Math.log10(n)),l=k=>10n**BigInt(k),g=k=>k>=0?u>=s*l(k):u*l(-k)>=s;for(;!g(a);)a--;for(;g(a+1);)a++;let m=14-a,p=m>=0?u*l(m):u,d=m>=0?s:s*l(-m),x=p/d,T=p-x*d;(T*2n>d||T*2n===d&&x%2n===1n)&&(x+=1n);let S=x.toString();return S.length>15&&(S=S.slice(0,15),a++),[S,a]}var ln=n=>n<10?"0"+n:String(n);function An(n){let e=n+719468,t=Math.floor(e/146097),r=e-t*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),i=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),u=Math.floor((5*i+2)/153),s=i-Math.floor((153*u+2)/5)+1,a=u<10?u+3:u-9;return[o+t*400+(a<=2?1:0),a,s]}function $e(n){let[e,t,r]=An(n);return String(e).padStart(4,"0")+"-"+ln(t)+"-"+ln(r)}function Ct(n){let e=Math.floor(n/86400),t=n-e*86400;return $e(e)+" "+ln(Math.floor(t/3600))+":"+ln(Math.floor(t%3600/60))+":"+ln(t%60)}function Pe(n,e){let t=(n<0n?-n:n).toString();return e>0&&(t.length<=e&&(t="0".repeat(e-t.length+1)+t),t=t.slice(0,t.length-e)+"."+t.slice(t.length-e)),n<0n?"-"+t:t}function K(n){switch(n.kind){case c.Text:case c.Ref:case c.JSON:return n.str;case c.Blank:return"";case c.Bool:return n.num!==0?"TRUE":"FALSE";case c.Number:return Wn(n.num);case c.Decimal:return Pe(n.mant,n.scale);case c.Money:return Pe(n.mant,n.scale)+" "+n.str;case c.Date:return $e(n.num);case c.DateTime:return Ct(n.num)}return""}var F=86400,Lt=-62135596800,Vt=253402300799,It=-719162,Ft=2932896,Dn=new b(w.OutOfRange,"the date is outside year 1 to year 9999");function Qn(n,e,t){n-=e<=2?1:0;let r=Math.floor(n/400),o=n-r*400,i=Math.floor((153*(e+(e>2?-3:9))+2)/5)+t-1,u=o*365+Math.floor(o/4)-Math.floor(o/100)+i;return r*146097+u-719468}function Ke(n,e){let t=e-1,r=Math.floor(t/12);return[n+r,t-r*12+1]}function Ye(n,e){return e===2?n%4===0&&n%100!==0||n%400===0?29:28:e===4||e===6||e===9||e===11?30:31}function fn(n){return n=Math.floor(n),n>=It&&n<=Ft?j(n):Dn}function Bn(n){return n=Math.floor(n),n>=Lt&&n<=Vt?U(n):Dn}function J(n){return n.kind===c.Date?n.num:Math.floor(n.num/F)}function Q(n){return An(J(n))}function qe(n,e,t){if(n=Math.trunc(n),e=Math.trunc(e),t=Math.trunc(t),Math.abs(n)>1e6||Math.abs(e)>1e7||Math.abs(t)>1e9)return Dn;let[r,o]=Ke(n,e);return fn(Qn(r,o,1)+t-1)}function Zn(n,e){if(n.kind===c.Blank)return h;let t=Math.trunc(e);if(Math.abs(t)>1e7)return Dn;let r=J(n),[o,i,u]=An(r),[s,a]=Ke(o,i+t),l=Qn(s,a,Math.min(u,Ye(s,a)));return n.kind===c.Date?fn(l):Bn(l*F+(n.num-r*F))}function Ut(n,e,t,r){let o=e;for(;o<n.length&&o-e<r&&n.charCodeAt(o)>=48&&n.charCodeAt(o)<=57;)o++;return o-e<t?null:[Number(n.slice(e,o)),o]}function je(n,e){if(!/^[0-9]{4}/.test(n))return null;let t=Number(n.slice(0,4)),r=4,o=l=>n[r]!==l?!1:(r++,!0),i=(l,g)=>{let m=Ut(n,r,l,g);return m===null?null:(r=m[1],m[0])};if(!o("-"))return null;let u=i(2,2);if(u===null||!o("-"))return null;let s=i(2,2);if(s===null)return null;let a=0;if(e){if(!o(" "))return null;let l=i(1,2);if(l===null||!o(":"))return null;let g=i(2,2);if(g===null||!o(":"))return null;let m=i(2,2);if(m===null)return null;if((n[r]==="."||n[r]===",")&&r+1<n.length&&n.charCodeAt(r+1)>=48&&n.charCodeAt(r+1)<=57)for(r++;r<n.length&&n.charCodeAt(r)>=48&&n.charCodeAt(r)<=57;)r++;if(l>23||g>59||m>59)return null;a=l*3600+g*60+m}return r!==n.length||u<1||u>12||s<1||s>Ye(t,u)?null:Qn(t,u,s)*F+a}function Je(n){let e=Y(n);if(e==="")return h;let t=je(e,!1);return t===null?new b(w.BadText,"not a date: "+e):fn(Math.floor(t/F))}function He(n){let e=Y(n);if(e==="")return h;let t=je(e,e.length>10);return t===null?new b(w.BadText,"not a datetime: "+e):Bn(t)}function R(n){return Number.isFinite(n)?E(n):O}function Cn(n,e,t){for(let r=e;r<e+t;r++)if(_(n[r].kind))return!0;return!1}var dn=(n,e,t)=>t>1?Math.trunc(n[e+1].num):0;function Ze(n,e,t){let r=Jn(n.mant,n.scale,e,t);return r===null?N:Nn(n,r[0],r[1])}function ee(n,e,t,r){let o=Number(n[e+t-1].mant),i="";for(let a=e;a<e+t-1;a++){let l=n[a];if(l.kind===c.Money){if(i!==""&&l.str!==i)return sn;i=l.str}}let u=0n,s=0;for(let a=e;a<e+t-1;a++){let l=n[a];if(l.kind===c.Blank)continue;let[g,m]=P(l),p=v(g,o-m);if(p===null)return N;if(s===0)u=p;else{let d=r(u,p);if(d===null)return N;u=d}s++}return{m:u,scale:o,cur:i,count:s}}function Pt(n,e,t){switch(t){case M.HalfUp:return G(n,e);case M.HalfEven:{let r=Math.trunc(e);if(r>300)return n;if(r<-300)return 0;let o=$(r),i=n*o;if(Math.abs(i)>=2**52)return n;let u=Math.trunc(i),s=Math.abs(i-u);return(s>.5||s===.5&&u%2!==0?u+Math.sign(i):u)/o}case M.Down:return X(n,e,Math.trunc);case M.Up:return X(n,e,r=>r<0?Math.floor(r):Math.ceil(r));case M.Floor:return X(n,e,Math.floor)}return X(n,e,Math.ceil)}var te=(n,e,t)=>t>1?n[e+1].num:0;function zn(n,e,t){return{name:n,fn:(r,o,i,u)=>_(o[i].kind)?Ze(o[i],dn(o,i,u),t):R(X(o[i].num,te(o,i,u),e))}}function Ge(n,e,t,r,o){if(Cn(n,e,t)){let s=ee(n,e,t,o);return s instanceof b?s:s.count===0?h:cn(s.m,s.scale,s.cur)}let i=0,u=!1;for(let s=e;s<e+t;s++){let a=n[s];a.kind!==c.Blank&&((!u||r(i,a.num))&&(i=a.num),u=!0)}return u?E(i):h}function Xe(n,e,t){let r=0,o=0;for(let i=e;i<e+t;i++){let u=n[i];u.kind!==c.Blank&&(o++,r+=u.num)}return[r,o]}function Z(n,e){let t=Math.trunc(n.num);return t>=0?t:on(e+" must not be negative")}var vn=(n,e)=>n>e?e:n,We=(n,e)=>Math.min(n,e.length+1)-1;function Qe(n,e){return e<0?0:L(n.slice(0,e))+1}var $t=/^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/;function Kt(n){return n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45||n===46||n===95||n===126}function Yt(n){if(!/^(0|[1-9][0-9]*)$/.test(n))return-1;let e=Number(n);return Number.isSafeInteger(e)?e:-1}function qt(n){let e="gu",t=n;for(;;){let r=/^\(\?([ims]+)\)/.exec(t);if(r===null)break;for(let o of r[1])e.includes(o)||(e+=o);t=t.slice(r[0].length)}return new RegExp(t,e)}function _n(n,e){return{name:n,fn:(t,r,o)=>{if(r[o].kind===c.Blank)return h;let[i,u,s]=Q(r[o]);return E(e(i,u,s))}}}function Sn(n,e,t){return n[e].kind===c.Blank||n[e+1].kind===c.Blank?h:t(n[e],n[e+1])}function ne(n,e){return{name:n,fn:t=>{let r=t.ctx?.doc,o=r?e(r):void 0;return o?U(o):h}}}function Rn(n,e){return{name:n,fn:t=>{let r=t.ctx?.doc,o=r?e(r):void 0;return o?y(o):h}}}function Ln(n,e){return n.ctx?.doc?.states?.find(t=>t.state===e)}function On(n,e){return{name:n,fn:(t,r,o)=>{let i=Ln(t,r[o].str),u=i?e(i):void 0;return u?U(u):h}}}function z(n,e){return{name:n,fn:(t,r,o)=>{let i=Ln(t,r[o].str),u=i?e(i):void 0;return u?y(u):h}}}var mn=n=>n?y(n):h,bn=[{name:"ISBLANK",fn:(n,e,t)=>V(e[t].kind===c.Blank)},{name:"ISNOTBLANK",fn:(n,e,t)=>V(e[t].kind!==c.Blank)},{name:"ROUND",fn:(n,e,t,r)=>{let o=e[t];if(!_(o.kind)&&r<3)return R(G(o.num,te(e,t,r)));let i=jn(r>2?e[t+2].str:void 0);return _(o.kind)?Ze(o,dn(e,t,r),i):R(Pt(o.num,te(e,t,r),i))}},zn("FLOOR",Math.floor,M.Floor),zn("CEILING",Math.ceil,M.Ceiling),zn("TRUNC",Math.trunc,M.Down),{name:"ABS",fn:(n,e,t)=>{let r=e[t];return _(r.kind)?r.mant<0n&&r.mant===-(2n**63n)?N:Nn(r,r.mant<0n?-r.mant:r.mant,r.scale):E(Math.abs(r.num))}},{name:"SIGN",fn:(n,e,t)=>{let r=e[t];return _(r.kind)?A(r.mant>0n?1n:r.mant<0n?-1n:0n,0):E(r.num>0?1:r.num<0?-1:0)}},{name:"MIN",fn:(n,e,t,r)=>Ge(e,t,r,(o,i)=>i<o,(o,i)=>i<o?i:o)},{name:"MAX",fn:(n,e,t,r)=>Ge(e,t,r,(o,i)=>i>o,(o,i)=>i>o?i:o)},{name:"SUM",fn:(n,e,t,r)=>{if(Cn(e,t,r)){let o=ee(e,t,r,wn);return o instanceof b?o:cn(o.m,o.scale,o.cur)}return R(Xe(e,t,r)[0])}},{name:"AVERAGE",fn:(n,e,t,r)=>{if(Cn(e,t,r)){let u=ee(e,t,r,wn);if(u instanceof b)return u;if(u.count===0)return h;let s=qn(u.m,u.scale,BigInt(u.count),0);return s instanceof b?s:cn(s[0],s[1],u.cur)}let[o,i]=Xe(e,t,r);return i===0?h:R(o/i)}},{name:"COUNT",fn:(n,e,t,r)=>{let o=0;for(let i=t;i<t+r;i++)e[i].kind!==c.Blank&&o++;return E(o)}},{name:"POWER",fn:(n,e,t)=>R(xn(e[t].num,e[t+1].num))},{name:"SQRT",fn:(n,e,t)=>e[t].num<0?O:E(Math.sqrt(e[t].num))},{name:"EXP",fn:(n,e,t)=>R(Math.exp(e[t].num))},{name:"LN",fn:(n,e,t)=>e[t].num<=0?O:E(H(e[t].num))},{name:"LOG",fn:(n,e,t,r)=>{let o=e[t].num,i=r>1?e[t+1].num:10;return o<=0||i<=0||i===1?O:R(i===10?be(o):H(o)/H(i))}},{name:"MOD",fn:(n,e,t,r)=>{if(Cn(e,t,r)){let u=Number(e[t+r-1].mant),s=e[t],a=e[t+1];if(s.kind===c.Money&&a.kind===c.Money&&s.str!==a.str)return sn;let[l,g]=P(s),[m,p]=P(a),d=v(l,u-g),x=v(m,u-p);if(d===null||x===null)return N;let T=Re(d,x);return T instanceof b?T:cn(T,u,s.kind===c.Money?s.str:a.kind===c.Money?a.str:"")}let o=e[t].num,i=e[t+1].num;return i===0?hn:R(o-i*Math.floor(o/i))}},{name:"DATE",fn:(n,e,t)=>qe(e[t].num,e[t+1].num,e[t+2].num)},{name:"DATEVALUE",fn:(n,e,t)=>Je(e[t].str)},_n("YEAR",n=>n),_n("MONTH",(n,e)=>e),_n("DAY",(n,e,t)=>t),_n("QUARTER",(n,e)=>Math.floor((e-1)/3)+1),{name:"DAYS",fn:(n,e,t)=>Sn(e,t,(r,o)=>E(J(r)-J(o)))},{name:"DAYSBETWEEN",fn:(n,e,t)=>Sn(e,t,(r,o)=>E(J(o)-J(r)))},{name:"MONTHSBETWEEN",fn:(n,e,t)=>Sn(e,t,(r,o)=>{let[i,u]=Q(r),[s,a]=Q(o);return E(s*12+a-(i*12+u))})},{name:"YEARSBETWEEN",fn:(n,e,t)=>Sn(e,t,(r,o)=>E(Q(o)[0]-Q(r)[0]))},{name:"ADDDAYS",fn:(n,e,t)=>{let r=e[t];return r.kind===c.Blank?h:r.kind===c.Date?fn(r.num+Math.trunc(e[t+1].num)):Bn(r.num+e[t+1].num*F)}},{name:"ADDMONTHS",fn:(n,e,t)=>Zn(e[t],e[t+1].num)},{name:"ADDYEARS",fn:(n,e,t)=>Zn(e[t],12*Math.trunc(e[t+1].num))},{name:"NOW",fn:n=>U(n.now())},{name:"TODAY",fn:n=>j(Math.floor(n.now()/86400))},{name:"USER",fn:n=>mn(n.ctx?.user)},{name:"INGROUP",fn:(n,e,t)=>{let r=n.ctx,o=e[t].str;return r?V((r.groups?.includes(o)??!1)||(r.system?.includes(o)??!1)||!!r.user&&o==="everyone"):V(!1)}},{name:"USERKIND",fn:n=>mn(n.ctx?.kind)},{name:"ACTINGFOR",fn:n=>mn(n.ctx?.for)},{name:"STATE",fn:n=>mn(n.ctx?.state)},{name:"ID",fn:n=>mn(n.ctx?.id)},{name:"LEFT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=W(e[t].str);return y(o.slice(0,vn(r,o.length)).join(""))}},{name:"RIGHT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=W(e[t].str);return y(o.slice(o.length-vn(r,o.length)).join(""))}},{name:"MID",fn:(n,e,t,r)=>{let o=Math.trunc(e[t+1].num);if(!(o>=1))return on("the position must be 1 or more");let i=W(e[t].str),u=We(o,i),s=i.length;if(r>2){let a=Z(e[t+2],"the length");if(a instanceof b)return a;s=u+vn(a,i.length-u)}return y(i.slice(u,s).join(""))}},{name:"LEN",fn:(n,e,t)=>E(L(e[t].str))},{name:"TRIM",fn:(n,e,t)=>{let r="",o=!0;for(let i of e[t].str){if(i===" "){o||(r+=" ",o=!0);continue}r+=i,o=!1}return y(r.endsWith(" ")?r.slice(0,-1):r)}},{name:"UPPER",fn:(n,e,t)=>y(ke(e[t].str))},{name:"LOWER",fn:(n,e,t)=>y(Me(e[t].str))},{name:"PROPER",fn:(n,e,t)=>y(Te(e[t].str))},{name:"REPLACE",fn:(n,e,t)=>{let r=Math.trunc(e[t+1].num);if(!(r>=1))return on("the position must be 1 or more");let o=Z(e[t+2],"the length");if(o instanceof b)return o;let i=W(e[t].str),u=We(r,i),s=u+vn(o,i.length-u),a=e[t+3].str;return i.length-(s-u)+L(a)>n.maxText?C():y(i.slice(0,u).join("")+a+i.slice(s).join(""))}},{name:"SUBSTITUTE",fn:(n,e,t)=>{let r=e[t].str,o=e[t+1].str,i=e[t+2].str;if(o==="")return y(r);let u=r.split(o).join(i);return un(u,n.maxText)?C():y(u)}},{name:"CONCAT",fn:(n,e,t,r)=>{let o="";for(let i=t;i<t+r;i++)o+=K(e[i]);return un(o,n.maxText)?C():y(o)}},{name:"REPEAT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=e[t].str;return o===""||r===0?y(""):r*o.length>n.maxText&&r*L(o)>n.maxText?C():y(o.repeat(r))}},{name:"FINDFIRST",fn:(n,e,t)=>E(Qe(e[t+1].str,e[t+1].str.indexOf(e[t].str)))},{name:"FINDLAST",fn:(n,e,t)=>E(Qe(e[t+1].str,e[t+1].str.lastIndexOf(e[t].str)))},{name:"PAD",fn:(n,e,t,r)=>{let o=Z(e[t+1],"the width");if(o instanceof b)return o;if(o>n.maxText)return C();let i=" ";r>2&&e[t+2].str!==""&&(i=W(e[t+2].str)[0]);let u=e[t].str,s=L(u);return y(s>=o?u:i.repeat(o-s)+u)}},{name:"REGEXREPLACE",fn:(n,e,t)=>{let r;try{r=qt(e[t+1].str)}catch(m){return new b(w.BadText,"invalid pattern: "+m.message)}let o=e[t].str,i=e[t+2].str,u="",s=0,a=-1,l=0,g=0;for(let m=r.exec(o);m!==null;m=r.exec(o)){let p=m.index,d=p+m[0].length;if(!(m[0].length===0&&(r.lastIndex=p+(o.codePointAt(p)>65535?2:1),p===a))&&(u+=o.slice(s,p)+i,l+=L(m[0]),g++,s=d,a=d,p>=o.length))break}return g===0?y(o):L(o)-l+g*L(i)>n.maxText?C():y(u+o.slice(s))}},{name:"TEXT",fn:(n,e,t)=>y(K(e[t]))},{name:"VALUE",fn:(n,e,t)=>{let r=Y(e[t].str);return r===""?h:$t.test(r)?R(Number(r)):new b(w.BadText,"not a number: "+r)}},{name:"JSONVALUE",fn:(n,e,t)=>{if(e[t].kind===c.Blank)return h;let r;try{r=JSON.parse(e[t].str)}catch(i){return new b(w.BadText,"invalid json: "+i.message)}let o=e[t+1].str;if(o!=="")for(let i of o.split("."))if(Array.isArray(r)){let u=Yt(i);if(u<0||u>=r.length)return h;r=r[u]}else if(r!==null&&typeof r=="object"){if(!Object.prototype.hasOwnProperty.call(r,i))return h;r=r[i]}else return h;switch(typeof r){case"string":return y(r);case"number":return y(Wn(r));case"boolean":return y(r?"TRUE":"FALSE")}return r===null?h:new b(w.BadText,"the path does not lead to a scalar")}},{name:"DECIMAL",fn:(n,e,t,r)=>{let o=e[t],i=dn(e,t,r),u=jn(r>2?e[t+2].str:void 0);if(o.kind===c.Blank)return h;if(_(o.kind)){let a=Jn(o.mant,o.scale,i,u);return a===null?N:A(a[0],a[1])}let s=Gn(o.num,i,u);return s instanceof b?s:A(s,i)}},{name:"NUMBER",fn:(n,e,t)=>{let r=e[t];return r.kind===c.Blank?h:E(_(r.kind)?Le(r.mant,r.scale):r.num)}},{name:"MONEY",fn:(n,e,t)=>{let r=e[t];if(r.kind===c.Blank)return h;let o=e[t+1].str;if(!Hn(o))return new b(w.BadText,"a currency is three upper-case letters, got "+JSON.stringify(o));let[i,u]=P(r);return I(i,u,o)}},{name:"MONEYVALUE",fn:(n,e,t,r)=>Xn(e[t].str,dn(e,t,r),!0)},{name:"DECIMALVALUE",fn:(n,e,t,r)=>Xn(e[t].str,dn(e,t,r),!1)},{name:"AMOUNT",fn:(n,e,t)=>e[t].kind===c.Blank?h:A(e[t].mant,e[t].scale)},{name:"CURRENCY",fn:(n,e,t)=>e[t].kind===c.Blank?h:y(e[t].str)},{name:"DATETIMEVALUE",fn:(n,e,t)=>He(e[t].str)},{name:"DATEOF",fn:(n,e,t)=>e[t].kind===c.Blank?h:j(Math.floor(e[t].num/F))},{name:"DATETIME",fn:(n,e,t)=>e[t].kind===c.Blank?h:U(e[t].num*F)},{name:"URLENCODE",fn:(n,e,t)=>{let r=we(e[t].str),o="",i="0123456789ABCDEF";for(let u of r)o+=Kt(u)?String.fromCharCode(u):"%"+i[u>>4]+i[u&15];return o.length>n.maxText&&o.length!==r.length?C():y(o)}},ne("CREATEDAT",n=>n.created_at),Rn("CREATEDBY",n=>n.created_by),ne("UPDATEDAT",n=>n.updated_at),Rn("UPDATEDBY",n=>n.updated_by),ne("ENTEREDAT",n=>n.entered_at),Rn("ENTEREDBY",n=>n.entered_by),Rn("ENTEREDFROM",n=>n.entered_from),{name:"VERSION",fn:n=>{let e=n.ctx?.doc?.version;return e?E(e):h}},On("FIRSTENTERED",n=>n.fe),z("FIRSTENTEREDBY",n=>n.feb),On("LASTENTERED",n=>n.le),z("LASTENTEREDBY",n=>n.leb),On("FIRSTLEFT",n=>n.fl),z("FIRSTLEFTBY",n=>n.flb),On("LASTLEFT",n=>n.ll),z("LASTLEFTBY",n=>n.llb),{name:"ENTRIES",fn:(n,e,t)=>{if(!n.ctx?.doc)return h;let r=Ln(n,e[t].str);return E(r?r.n??0:0)}},{name:"DAYSIN",fn:(n,e,t)=>{if(!n.ctx?.doc)return h;let r=Ln(n,e[t].str);if(!r)return E(0);let o=r.secs??0;return r.here&&(o+=n.now()-(r.le??0)),E(o/F)}},z("FIRSTEDITOR",n=>n.fed),z("LASTEDITOR",n=>n.led),{name:"REF",fn:(n,e,t)=>{let r=e[t+1];return r.kind===c.Blank||r.str===""?h:En(e[t].str+":"+r.str)}}];function ze(n,e){if(n.kind===c.Blank&&e.kind===c.Blank)return 0;let t=n.kind===c.Blank?e.kind:n.kind;return t===c.Text||t===c.Ref||t===c.JSON?he(n.str,e.str):n.num<e.num?-1:n.num>e.num?1:0}var Vn=4,f={Nop:0,ConstNum:1,ConstText:2,True:3,False:4,Blank:5,Load:6,Neg:7,Percent:8,Not:9,Add:10,Sub:11,Mul:12,Div:13,DivStrict:14,Pow:15,Concat:16,Eq:17,Ne:18,Lt:19,Le:20,Gt:21,Ge:22,Jump:23,JumpIfFalse:24,AndJump:25,OrJump:26,ToBool:27,Call:28,Lookup:29,Query:30,Return:31,ConstDec:32,DecNeg:33,DecPercent:34,DecAdd:35,DecSub:36,DecMul:37,DecDiv:38,DecScale:39,Try:40,EndTry:41},In=18,jt=256,Jt={bool:c.Bool,number:c.Number,text:c.Text,date:c.Date,datetime:c.DateTime,ref:c.Ref,json:c.JSON};function nn(n){let e=Jt[n];if(e!==void 0)return{kind:e,scale:0,elem:c.Blank};switch(n){case"blank":return{kind:c.Blank,scale:0,elem:c.Blank};case"rows":return{kind:c.Rows,scale:0,elem:c.Blank};case"int":return{kind:c.Decimal,scale:0,elem:c.Blank};case"decimal":return{kind:c.Decimal,scale:2,elem:c.Blank};case"money":return{kind:c.Money,scale:2,elem:c.Blank}}if(n.startsWith("array<")&&n.endsWith(">")){let t=nn(n.slice(6,-1));if(t.kind===c.Blank||t.kind>=c.Array)throw new Error(`unknown type "${n}"`);return{kind:c.Array,scale:t.scale,elem:t.kind}}for(let[t,r]of[["decimal(",c.Decimal],["money(",c.Money]])if(n.startsWith(t)&&n.endsWith(")")){let o=n.slice(t.length,-1),i=Number(o);if(!/^[0-9]+$/.test(o)||i>In)throw new Error(`type "${n}": the scale must be 0 to ${In}`);return{kind:r,scale:i,elem:c.Blank}}throw new Error(`unknown type "${n}"`)}var Ht=new TextDecoder("utf-8"),re=class{constructor(e){this.bytes=e;this.at=0;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}need(e){if(this.at+e>this.bytes.length)throw new Error("bytecode: the program ends early")}u8(){return this.need(1),this.bytes[this.at++]}u16(){this.need(2);let e=this.view.getUint16(this.at);return this.at+=2,e}u32(){this.need(4);let e=this.view.getUint32(this.at);return this.at+=4,e}i32(){this.need(4);let e=this.view.getInt32(this.at);return this.at+=4,e}f64(){this.need(8);let e=this.view.getFloat64(this.at);return this.at+=8,e}i64(){this.need(8);let e=this.view.getBigInt64(this.at);return this.at+=8,e}count(){let e=this.u32();if(e>this.bytes.length-this.at)throw new Error("bytecode: the program ends early");return e}str(){let e=this.count(),t=Ht.decode(this.bytes.subarray(this.at,this.at+e));return this.at+=e,t}program(){let e=this.count();if(e===0)return null;let t=oe(this.bytes.subarray(this.at,this.at+e));return this.at+=e,t}};function oe(n){if(n.length<8||n[0]!==70||n[1]!==65||n[2]!==68||n[3]!==79)throw new Error("bytecode: not a FadoDB program");let e=new re(n.subarray(4)),t=e.u16();if(t!==Vn)throw new Error(`bytecode: format version ${t}, this build reads ${Vn}`);e.u16();let r=new Float64Array(e.count());for(let k=0;k<r.length;k++)r[k]=e.f64();let o=[];for(let k=e.count(),D=0;D<k;D++){let en=e.i64(),tn=e.u8();if(tn>In)throw new Error(`bytecode: exact constant ${D} has scale ${tn}`);o.push({mant:en,scale:tn})}let i=[];for(let k=e.count(),D=0;D<k;D++)i.push(e.str());let u=[];for(let k=e.count(),D=0;D<k;D++){let en=e.str();u.push({name:en,type:nn(e.str())})}let s=e.count(),a=new Uint8Array(s),l=new Int32Array(s);for(let k=0;k<s;k++)a[k]=e.u8(),l[k]=e.i32();let g=null,m=e.count();if(m>0){g=new Int32Array(m);for(let k=0;k<m;k++)g[k]=e.i32()}let p=nn(e.str()),d=[];for(let k=e.count(),D=0;D<k;D++)d.push(e.str());let x=[];for(let k=e.count(),D=0;D<k;D++){let en=e.str(),tn=e.str(),rt=nn(e.str()),ue=[];for(let Un=e.count(),rn=0;rn<Un;rn++)ue.push(e.str());let ae=[],se=[];for(let Un=e.count(),rn=0;rn<Un;rn++)ae.push(e.i32()),se.push(e.str());let ot=e.program(),it=e.program(),ut=e.str(),at=e.u8()!==0,st=e.str(),ct=e.program();x.push({source:en,column:tn,type:rt,order:ue,args:ae,argNames:se,cond:ot,key:it,indexColumn:ut,keyPart:at,agg:st,value:ct})}let T=e.u32(),S={nums:r,decs:o,texts:i,slots:u,ops:a,args:l,pos:g,result:p,classes:d,queries:x,maxStack:T};return Gt(S),S}var nt=0;function et(n){nt=n}function Gt(n){let e=n.ops.length;if(e===0||n.ops[e-1]!==f.Return)throw new Error("bytecode: code must end with return");if(n.pos!==null&&n.pos.length!==e)throw new Error("bytecode: positions do not match the code");for(let t=0;t<e;t++){let r=n.args[t],o=i=>{throw new Error(`bytecode: instruction ${t}: ${i}`)};switch(n.ops[t]){case f.ConstNum:(r<0||r>=n.nums.length)&&o(`number constant ${r} out of range`);break;case f.ConstText:(r<0||r>=n.texts.length)&&o(`text constant ${r} out of range`);break;case f.ConstDec:(r<0||r>=n.decs.length)&&o(`exact constant ${r} out of range`);break;case f.Load:(r<0||r>=n.slots.length)&&o(`slot ${r} out of range`);break;case f.Jump:case f.JumpIfFalse:case f.AndJump:case f.OrJump:case f.Try:(r<0||r>=e)&&o(`jump target ${r} out of range`);break;case f.DecNeg:case f.DecPercent:case f.DecAdd:case f.DecSub:case f.DecMul:case f.DecDiv:case f.DecScale:(r<0||(r&255)>In||(r&~(255|jt))!==0)&&o(`scale ${r} out of range`);break;case f.Call:(r>>8>=nt||r<0)&&o(`unknown builtin ${r>>8}`);break;case f.Lookup:case f.Query:(r<0||r>=n.queries.length)&&o(`query slot ${r} out of range`);break;default:n.ops[t]>f.EndTry&&o(`unknown opcode ${n.ops[t]}`)}}}et(bn.length);var ie=65536,tt=16;function Xt(n,e,t){let r=e.pos!==null?e.pos[t]:-1;return new b(n.code,n.detail,r)}var Fn=class{constructor(e={}){this.stack=[];this.tryPc=new Int32Array(tt);this.trySp=new Int32Array(tt);this.maxText=e.maxText&&e.maxText>0?e.maxText:ie}now(){return this.ctx?.now?this.ctx.now:Math.floor(Date.now()/1e3)}run(e,t,r){if(t.length<e.slots.length)throw new b("query_failed",`program reads ${e.slots.length} variables, got ${t.length}`);let o=this.stack;for(;o.length<e.maxStack;)o.push(h);this.ctx=r;let i=e.ops,u=e.args,s=0,a=0,l=0;for(;;){let g=i[l],m=u[l];l++;let p=null;switch(g){case f.Nop:break;case f.ConstNum:o[a++]=E(e.nums[m]);break;case f.ConstText:o[a++]=y(e.texts[m]);break;case f.True:o[a++]=an;break;case f.False:o[a++]=q;break;case f.Blank:o[a++]=h;break;case f.Load:o[a++]=t[m];break;case f.Neg:o[a-1]=E(-o[a-1].num);break;case f.Percent:o[a-1]=E(o[a-1].num/100);break;case f.Not:o[a-1]=V(!o[a-1].truth);break;case f.Add:case f.Sub:case f.Mul:case f.Pow:{let d=o[a-2].num,x=o[a-1].num,T=g===f.Add?d+x:g===f.Sub?d-x:g===f.Mul?d*x:xn(d,x);if(!Number.isFinite(T)){p=O;break}a--,o[a-1]=E(T);break}case f.Div:case f.DivStrict:{let d=o[a-2].num,x=o[a-1].num;if(x===0){p=gn;break}let T=d/x;if(!Number.isFinite(T)){p=O;break}a--,o[a-1]=E(T);break}case f.ConstDec:{let d=e.decs[m];o[a++]=A(d.mant,d.scale);break}case f.DecNeg:case f.DecPercent:case f.DecScale:{let d=Ie(g===f.DecScale,g===f.DecNeg,o[a-1],m);if(d instanceof b){p=d;break}o[a-1]=d;break}case f.DecAdd:case f.DecSub:case f.DecMul:case f.DecDiv:{let d=Ue(g-f.DecAdd,o[a-2],o[a-1],m);if(d instanceof b){p=d;break}a--,o[a-1]=d;break}case f.Concat:{let d=K(o[a-2])+K(o[a-1]);if(un(d,this.maxText)){p=C();break}a--,o[a-1]=y(d);break}case f.Eq:case f.Ne:case f.Lt:case f.Le:case f.Gt:case f.Ge:{let d=o[a-2],x=o[a-1],T;if(_(d.kind)||_(x.kind)){let S=Fe(d,x,m);if(S instanceof b){p=S;break}T=S}else T=ze(d,x);a--,o[a-1]=V(g===f.Eq?T===0:g===f.Ne?T!==0:g===f.Lt?T<0:g===f.Le?T<=0:g===f.Gt?T>0:T>=0);break}case f.Jump:l=m;break;case f.JumpIfFalse:a--,o[a].truth||(l=m);break;case f.AndJump:o[a-1].truth?a--:(o[a-1]=q,l=m);break;case f.OrJump:o[a-1].truth?l=m:a--;break;case f.ToBool:o[a-1].kind===c.Blank&&(o[a-1]=q);break;case f.Try:this.tryPc[s]=m,this.trySp[s]=a,s++;break;case f.EndTry:s--;break;case f.Call:{let d=m&255,x=bn[m>>8].fn(this,o,a-d,d);if(x instanceof b){p=x;break}a-=d,o[a++]=x;break}case f.Lookup:case f.Query:p=ce;break;case f.Return:return o[a-1];default:p=new b("query_failed",`unknown opcode ${g}`)}if(p!==null){if(s>0){s--,a=this.trySp[s],l=this.tryPc[s];continue}throw Xt(p,e,l-1)}}}};function Wt(){return bn.map(n=>n.name)}return gt(Qt);})();
|
package/fadodb-vm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var w={DivByZero:"div_by_zero",NotANumber:"not_a_number",BadText:"bad_text",OutOfRange:"out_of_range",LengthMismatch:"length_mismatch",TooManyElements:"too_many_elements",QueryFailed:"query_failed",Overflow:"overflow",Inexact:"inexact",CurrencyMismatch:"currency_mismatch"},b=class extends Error{constructor(t,r,o=-1){super(o>=0?`${t}: ${r} at offset ${o}`:`${t}: ${r}`);this.code=t;this.detail=r;this.pos=o;this.name="EvalError"}},bn=new b(w.DivByZero,"/ by zero"),O=new b(w.NotANumber,"the result is not a finite number"),gn=new b(w.DivByZero,"MOD by zero"),ue=new b(w.QueryFailed,"the formula reads a table or other documents, which the server works out; the page is given its last value");function rn(n){return new b(w.OutOfRange,n)}function C(){return rn("the result is too long")}var Fn=22250738585072014e-324;function hn(n){let e=Math.trunc(n);return Math.abs(n-e)>=.5?e+Math.sign(n):e}var ut=(()=>{let n=new Float64Array(632);for(let e=0;e<n.length;e++)n[e]=+("1e"+(e-323));return n})();function P(n){return n<-323?0:n>308?1/0:ut[n+323]}function j(n){return n>0&&n<Fn?Math.log(n*18446744073709552e3)-64*Math.LN2:Math.log(n)}function ce(n){if(n===0||!Number.isFinite(n))return[n,0];let e=0;Math.abs(n)<Fn&&(n*=4503599627370496,e=-52);let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,n);let r=t.getUint32(0);return e+=(r>>>20&2047)-1022,t.setUint32(0,r&2148532223|1022<<20),[t.getFloat64(0),e]}function at(n,e){if(n===0||!Number.isFinite(n))return n;for(;e>1023;)if(n*=2**1023,e-=1023,!Number.isFinite(n))return n;if(e<-1022){for(;e<-1075;)if(n*=2**-1022,e+=1022,n===0)return n;return n*2**(e+53)*2**-53}return n*2**e}function In(n,e){if(e===0||n===1)return 1;if(e===1)return n;if(Number.isNaN(n)||Number.isNaN(e))return NaN;if(n===0){let l=st(e);if(e<0)return Object.is(n,-0)&&l?-1/0:1/0;if(e>0)return Object.is(n,-0)&&l?n:0}if(!Number.isFinite(e))return n===-1?1:Math.abs(n)<1==e>0?0:1/0;if(!Number.isFinite(n))return n<0?In(1/n,-e):e<0?0:1/0;if(e===.5)return Math.sqrt(n);if(e===-.5)return 1/Math.sqrt(n);let t=Math.abs(e),r=Math.trunc(t),o=t-r;if(o!==0&&n<0)return NaN;if(r>=2**63)return n===-1?1:Math.abs(n)<1==e>0?0:1/0;let i=1,u=0;o!==0&&(o>.5&&(o--,r++),i=Math.exp(o*Math.log(n)));let[s,a]=ce(n);for(let l=BigInt(r);l!==0n;l>>=1n){if(a<-4096||4096<a){u+=a;break}(l&1n)===1n&&(i*=s,u+=a),s*=s,a<<=1,s<.5&&(s+=s,a--)}return e<0&&(i=1/i,u=-u),at(i,u)}function st(n){return Math.abs(n)>=2**53?!1:Number.isInteger(n)&&Math.abs(n%2)===1}var ae=134217729;function le(n,e,t){let r=ae*n,o=r-(r-n),i=n-o;r=ae*e;let u=r-(r-e),s=e-u,a=o*u-t+o*s+i*u+i*s;if(Number.isFinite(a))return a;let l=2**-600;return le(n*l,e,t*l)/l}function se(n,e,t,r){let o=n*t;if(!Number.isFinite(o))return[o,0];let i=le(n,t,o)+n*r+e*t,u=o+i;return[u,i-(u-o)]}function pn(n,e){if(e===0||n===1)return 1;let t=Math.trunc(e),r=e-t;if(n<=0||!Number.isFinite(n)||Number.isNaN(e)||!Number.isFinite(e)||Math.abs(t)>2**62)return In(n,e);let o=1;r===.5?o=Math.sqrt(n):r!==0&&(o=Math.exp(r*j(n)));let i=BigInt(t),u=i<0n;u&&(i=-i);let s=1,a=0,l=n,g=0;for(;i>0n;)if((i&1n)===1n&&([s,a]=se(s,a,l,g)),i>>=1n,i>0n&&([l,g]=se(l,g,l,g)),!Number.isFinite(s)||!Number.isFinite(l)||s===0)return In(n,e);let m=s+a;return u&&(m=1/m),m*o}var ct=.3010299956639812,lt=1.4426950408889634;function ft(n){let[e,t]=ce(n);return e===.5?t-1:Math.log(e)*lt+t}function fe(n){let e=ft(n)*ct;n<Fn&&(e=j(n)/Math.LN10);let t=hn(e);return t!==e&&Math.abs(t)<=323&&P(t)===n?t:e}function J(n,e){let t=Math.trunc(e);if(t>300)return n;if(t<-300)return 0;let r=P(t),o=n*r;return Math.abs(o)>=2**52?n:hn(o)/r}function H(n,e,t){let r=Math.max(-300,Math.min(300,Math.trunc(e))),o=P(r),i=n*o;return Math.abs(i)>=2**52?n:t(J(i,9))/o}function L(n){let e=n.length;for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r>=55296&&r<=56319&&t+1<n.length){let o=n.charCodeAt(t+1);o>=56320&&o<=57343&&(e--,t++)}}return e}function on(n,e){return n.length>e&&L(n)>e}function G(n){return Array.from(n)}function de(n,e){if(n===e)return 0;let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n.charCodeAt(r),i=e.charCodeAt(r);if(o!==i)return o>=55296&&i>=55296&&(o=o>=57344?o-2048:o+8192,i=i>=57344?i-2048:i+8192),o<i?-1:1}return n.length<e.length?-1:n.length>e.length?1:0}var be={304:105},ge=(()=>{let n={8115:8124,8131:8140,8179:8188};for(let[e,t]of[[8064,8072],[8080,8088],[8096,8104]])for(let r=0;r<8;r++)n[e+r]=t+r;return n})();function xn(n,e,t){let r=n.codePointAt(0),o=t[r];if(o!==void 0)return String.fromCodePoint(o);let i=e(n);return i.length===1||i.length===2&&i.codePointAt(0)>65535?i:n}var he=n=>n.toUpperCase(),pe=n=>n.toLowerCase();function xe(n){let e="";for(let t of n)e+=xn(t,he,ge);return e}function ye(n){let e="";for(let t of n)e+=xn(t,pe,be);return e}var mt=/^\p{L}$/u;function Ee(n){let e="",t=!1;for(let r of n)mt.test(r)?(e+=t?xn(r,pe,be):xn(r,he,ge),t=!0):(e+=r,t=!1);return e}var me="[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]",dt=new RegExp("^"+me+"+|"+me+"+$","g");function K(n){return n.replace(dt,"")}var bt=new TextEncoder;function ke(n){return bt.encode(n)}var c={Blank:0,Bool:1,Number:2,Decimal:3,Money:4,Text:5,Date:6,DateTime:7,Ref:8,JSON:9,Array:10,Rows:11,Object:12},gt=["blank","bool","number","decimal","money","text","date","datetime","ref","json","array","rows","object"],B=class{constructor(e,t,r,o,i){this.kind=e;this.num=t;this.str=r;this.mant=o;this.scale=i}get isBlank(){return this.kind===c.Blank}get truth(){return this.kind===c.Bool&&this.num!==0}},h=new B(c.Blank,0,"",0n,0),yn=new B(c.Bool,1,"",0n,0),X=new B(c.Bool,0,"",0n,0);function I(n){return n?yn:X}function k(n){return new B(c.Number,n,"",0n,0)}function y(n){return new B(c.Text,0,n,0n,0)}function W(n){return new B(c.Date,n,"",0n,0)}function $(n){return new B(c.DateTime,n,"",0n,0)}function Un(n){return new B(c.Ref,0,n,0n,0)}function ht(n){return new B(c.JSON,0,n,0n,0)}function A(n,e){return new B(c.Decimal,0,"",n,e)}function F(n,e,t){return new B(c.Money,0,t,n,e)}function _(n){return n===c.Decimal||n===c.Money}function pt(n,e){if(n.kind!==e.kind)return!1;switch(n.kind){case c.Blank:return!0;case c.Bool:case c.Number:case c.Date:case c.DateTime:return n.num===e.num;case c.Decimal:return n.scale===e.scale&&n.mant===e.mant;case c.Money:return n.scale===e.scale&&n.mant===e.mant&&n.str===e.str;default:return n.str===e.str}}var kn=18,xt=4,Mn=-(2n**63n),yt=2n**63n-1n,Te=2n**64n,N=new b(w.Overflow,"the exact result does not fit 18 digits"),un=new b(w.CurrencyMismatch,"the currencies of one operation must agree"),we=n=>n>=Mn&&n<=yt,En=n=>n<0n?-n:n,Et=n=>n>0n?1n:n<0n?-1n:0n,Pn=n=>10n**BigInt(n);function Tn(n,e){let t=n+e;return we(t)?t:null}function Ne(n,e){let t=n*e;return we(t)?t:null}function v(n,e){return e<=0?n:e>kn?n===0n?0n:null:Ne(n,Pn(e))}function kt(n,e){if(e===-1n)return n===Mn?null:-n;let t=n/e,r=n%e;return r!==0n&&2n*En(r)>=En(e)&&(t+=n<0n==e<0n?1n:-1n),t}function $n(n,e,t,r){if(t===0n)return bn;let o=Math.min(e+xt,kn),i=v(n,o-e+r);if(i===null)return N;let u=kt(i,t);return u===null?N:[u,o]}function Ae(n,e){if(e===0n)return gn;if(e===-1n)return 0n;let t=n%e;return t!==0n&&t<0n!=e<0n&&(t+=e),t}var M={HalfUp:0,HalfEven:1,Down:2,Up:3,Floor:4,Ceiling:5},Mt={half_up:M.HalfUp,half_even:M.HalfEven,down:M.Down,up:M.Up,floor:M.Floor,ceiling:M.Ceiling};function Kn(n){return(n!==void 0?Mt[n]:void 0)??M.HalfUp}var Me=n=>2n*n%Te;function Yn(n,e,t,r){if(t>=e){let l=v(n,t-e);return l===null?null:[l,t]}let o=e-t,i,u,s;if(o>kn)i=0n,u=n,s=Te-1n;else{let l=Pn(o);i=n/l,u=n%l,s=l}let a=Et(n);switch(r){case M.HalfUp:u!==0n&&Me(En(u))>=s&&(i+=a);break;case M.HalfEven:{let l=Me(En(u));u!==0n&&(l>s||l===s&&(i&1n)!==0n)&&(i+=a);break}case M.Down:break;case M.Up:u!==0n&&(i+=a);break;case M.Floor:u!==0n&&n<0n&&i--;break;case M.Ceiling:u!==0n&&n>0n&&i++;break}if(t<0){let l=v(i,-t);return l===null?null:[l,0]}return[i,t]}function De(n,e,t){if(t>=e){let o=v(n,t-e);return o===null?N:o}let r=Pn(e-t);return n%r!==0n?new b(w.Inexact,`the value has more decimal places than ${t}`):n/r}function Be(n){let e=()=>new b(w.BadText,"not a decimal: "+n),t=n,r=!1;t!==""&&(t[0]==="+"||t[0]==="-")&&(r=t[0]==="-",t=t.slice(1));let o="",i=t.search(/[eE]/);if(i>=0&&(o=t.slice(i+1),t=t.slice(0,i),o===""||(o[0]==="+"||o[0]==="-")&&o.length===1||!/^[+\-0-9][0-9]*$/.test(o)))return e();let u=t.indexOf("."),s=u>=0?t.slice(0,u):t,a=u>=0?t.slice(u+1):"";if(s===""&&a===""||!/^[0-9]*$/.test(s+a))return e();let l=(s+a).replace(/^0+/,"");if(l==="")return[0n,0];let g=0;if(o!==""){let d=Number(o);if(!Number.isFinite(d)||d>1e6||d<-1e6)return N;g=d}let m=a.length-g;if(m<0){if(-m>19)return N;l+="0".repeat(-m),m=0}if(m>kn||l.length>19)return N;let p=BigInt(l);return p>2n**63n||p===2n**63n&&!r?N:[r?-p:p,m]}function qn(n){return/^[A-Z]{3}$/.test(n)}function Tt(n){let e=n.indexOf(" ");if(e<0||!qn(n.slice(e+1)))return new b(w.BadText,"not an amount with a currency: "+n);let t=Be(n.slice(0,e));return t instanceof b?t:[t[0],t[1],n.slice(e+1)]}function wt(n){let e=Math.trunc(n),t=Math.abs(n-e);return t>.5||t===.5&&e%2!==0?e+Math.sign(n):e}function jn(n,e,t){if(!Number.isFinite(n))return O;let r=n*P(e),o;switch(t){case M.HalfUp:o=hn(r);break;case M.HalfEven:o=wt(r);break;default:{let i=J(r,9);switch(t){case M.Down:o=Math.trunc(i);break;case M.Up:o=i<0?Math.floor(i):Math.ceil(i);break;case M.Floor:o=Math.floor(i);break;default:o=Math.ceil(i)}}}return Math.abs(o)>=2**63?N:BigInt(o)}function ve(n,e){return Number(n)/P(e)}function U(n){switch(n.kind){case c.Decimal:case c.Money:return[n.mant,n.scale];case c.Bool:return[BigInt(n.num),0]}return[0n,0]}function wn(n,e,t){return n.kind===c.Money?F(e,t,n.str):A(e,t)}function an(n,e,t){return t!==""?F(n,e,t):A(n,e)}function Jn(n,e,t){let r=K(n);if(r==="")return h;let o,i,u="";if(t){let a=Tt(r);if(a instanceof b)return a;[o,i,u]=a}else{let a=Be(r);if(a instanceof b)return a;[o,i]=a}let s=De(o,i,e);return s instanceof b?s:t?F(s,e,u):A(s,e)}var _e=256;function Se(n,e,t,r){let o=r&255,i=(r&_e)!==0;if(n){if(i&&(t.kind===c.Decimal||t.kind===c.Number))return h;if(t.kind===c.Number){let s=jn(t.num,o,M.HalfUp);return s instanceof b?s:A(s,o)}if((t.kind===c.Decimal||t.kind===c.Money)&&t.scale!==o){let s=De(t.mant,t.scale,o);return s instanceof b?s:wn(t,s,o)}return t}if(t.kind===c.Blank||t.kind===c.Bool){if(i)return h;let s=BigInt(t.num);return A(e?-s:s,o)}let u=t.mant;if(e){if(u===Mn)return N;u=-u}return t.kind===c.Money?F(u,o,t.str):A(u,o)}function Re(n,e,t){if(n.kind===c.Money&&e.kind===c.Money&&n.str!==e.str)return un;let[r,o]=U(n),[i,u]=U(e),s=v(r,t-o),a=v(i,t-u);return s===null||a===null?N:s<a?-1:s>a?1:0}function Oe(n,e,t,r){let o=r&255,i=(r&_e)!==0,u="";if(e.kind===c.Money&&(u=e.str),t.kind===c.Money){if(u!==""&&t.str!==u)return un;u=t.str}let[s,a]=U(e),[l,g]=U(t),m,p;if(n<=1){let d=a<g?v(s,g-a):s,x=g<a?v(l,a-g):l;if(d===null||x===null)return N;if(p=Math.max(a,g),n===1){if(x===Mn)return N;x=-x}m=Tn(d,x)}else if(n===2)m=Ne(s,l),p=a+g;else{let d=$n(s,a,l,g);if(d instanceof b)return d;[m,p]=d}return m===null||p!==o&&(m=v(m,o-p),m===null)?N:i?u===""?h:F(m,o,u):A(m,o)}function Hn(n){if(n===0)return"0";if(!Number.isFinite(n))return n>0?"+Inf":n<0?"-Inf":"NaN";let[e,t]=Nt(Math.abs(n)),r=n<0?"-":"";if(e=e.replace(/0+$/,""),t<-4||t>=15){let o=e.length>1?e[0]+"."+e.slice(1):e,i=Math.abs(t);return r+o+"e"+(t<0?"-":"+")+(i<10?"0"+i:String(i))}return t<0?r+"0."+"0".repeat(-t-1)+e:e.length<=t+1?r+e+"0".repeat(t+1-e.length):r+e.slice(0,t+1)+"."+e.slice(t+1)}function Nt(n){let e=n.toExponential(20),t=e.indexOf("e"),r=e.slice(16,t);if(r.startsWith("5")&&/^50*$/.test(r))return At(n);let o=n.toExponential(14),i=o.indexOf("e");return[o[0]+o.slice(2,i),Number(o.slice(i+1))]}function At(n){let e=new DataView(new ArrayBuffer(8));e.setFloat64(0,n);let t=e.getBigUint64(0),r=Number(t>>52n&0x7ffn),o=t&0xfffffffffffffn,i;r===0?i=-1074:(o|=1n<<52n,i=r-1075);let u=o,s=1n;i>=0?u<<=BigInt(i):s<<=BigInt(-i);let a=Math.floor(Math.log10(n)),l=E=>10n**BigInt(E),g=E=>E>=0?u>=s*l(E):u*l(-E)>=s;for(;!g(a);)a--;for(;g(a+1);)a++;let m=14-a,p=m>=0?u*l(m):u,d=m>=0?s:s*l(-m),x=p/d,T=p-x*d;(T*2n>d||T*2n===d&&x%2n===1n)&&(x+=1n);let S=x.toString();return S.length>15&&(S=S.slice(0,15),a++),[S,a]}var sn=n=>n<10?"0"+n:String(n);function Nn(n){let e=n+719468,t=Math.floor(e/146097),r=e-t*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),i=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),u=Math.floor((5*i+2)/153),s=i-Math.floor((153*u+2)/5)+1,a=u<10?u+3:u-9;return[o+t*400+(a<=2?1:0),a,s]}function Le(n){let[e,t,r]=Nn(n);return String(e).padStart(4,"0")+"-"+sn(t)+"-"+sn(r)}function Dt(n){let e=Math.floor(n/86400),t=n-e*86400;return Le(e)+" "+sn(Math.floor(t/3600))+":"+sn(Math.floor(t%3600/60))+":"+sn(t%60)}function Ce(n,e){let t=(n<0n?-n:n).toString();return e>0&&(t.length<=e&&(t="0".repeat(e-t.length+1)+t),t=t.slice(0,t.length-e)+"."+t.slice(t.length-e)),n<0n?"-"+t:t}function Y(n){switch(n.kind){case c.Text:case c.Ref:case c.JSON:return n.str;case c.Blank:return"";case c.Bool:return n.num!==0?"TRUE":"FALSE";case c.Number:return Hn(n.num);case c.Decimal:return Ce(n.mant,n.scale);case c.Money:return Ce(n.mant,n.scale)+" "+n.str;case c.Date:return Le(n.num);case c.DateTime:return Dt(n.num)}return""}var V=86400,Bt=-62135596800,vt=253402300799,_t=-719162,St=2932896,An=new b(w.OutOfRange,"the date is outside year 1 to year 9999");function Gn(n,e,t){n-=e<=2?1:0;let r=Math.floor(n/400),o=n-r*400,i=Math.floor((153*(e+(e>2?-3:9))+2)/5)+t-1,u=o*365+Math.floor(o/4)-Math.floor(o/100)+i;return r*146097+u-719468}function Ve(n,e){let t=e-1,r=Math.floor(t/12);return[n+r,t-r*12+1]}function Ie(n,e){return e===2?n%4===0&&n%100!==0||n%400===0?29:28:e===4||e===6||e===9||e===11?30:31}function cn(n){return n=Math.floor(n),n>=_t&&n<=St?W(n):An}function Dn(n){return n=Math.floor(n),n>=Bt&&n<=vt?$(n):An}function q(n){return n.kind===c.Date?n.num:Math.floor(n.num/V)}function Q(n){return Nn(q(n))}function Fe(n,e,t){if(n=Math.trunc(n),e=Math.trunc(e),t=Math.trunc(t),Math.abs(n)>1e6||Math.abs(e)>1e7||Math.abs(t)>1e9)return An;let[r,o]=Ve(n,e);return cn(Gn(r,o,1)+t-1)}function Xn(n,e){if(n.kind===c.Blank)return h;let t=Math.trunc(e);if(Math.abs(t)>1e7)return An;let r=q(n),[o,i,u]=Nn(r),[s,a]=Ve(o,i+t),l=Gn(s,a,Math.min(u,Ie(s,a)));return n.kind===c.Date?cn(l):Dn(l*V+(n.num-r*V))}function Rt(n,e,t,r){let o=e;for(;o<n.length&&o-e<r&&n.charCodeAt(o)>=48&&n.charCodeAt(o)<=57;)o++;return o-e<t?null:[Number(n.slice(e,o)),o]}function Ue(n,e){if(!/^[0-9]{4}/.test(n))return null;let t=Number(n.slice(0,4)),r=4,o=l=>n[r]!==l?!1:(r++,!0),i=(l,g)=>{let m=Rt(n,r,l,g);return m===null?null:(r=m[1],m[0])};if(!o("-"))return null;let u=i(2,2);if(u===null||!o("-"))return null;let s=i(2,2);if(s===null)return null;let a=0;if(e){if(!o(" "))return null;let l=i(1,2);if(l===null||!o(":"))return null;let g=i(2,2);if(g===null||!o(":"))return null;let m=i(2,2);if(m===null)return null;if((n[r]==="."||n[r]===",")&&r+1<n.length&&n.charCodeAt(r+1)>=48&&n.charCodeAt(r+1)<=57)for(r++;r<n.length&&n.charCodeAt(r)>=48&&n.charCodeAt(r)<=57;)r++;if(l>23||g>59||m>59)return null;a=l*3600+g*60+m}return r!==n.length||u<1||u>12||s<1||s>Ie(t,u)?null:Gn(t,u,s)*V+a}function Pe(n){let e=K(n);if(e==="")return h;let t=Ue(e,!1);return t===null?new b(w.BadText,"not a date: "+e):cn(Math.floor(t/V))}function $e(n){let e=K(n);if(e==="")return h;let t=Ue(e,e.length>10);return t===null?new b(w.BadText,"not a datetime: "+e):Dn(t)}function R(n){return Number.isFinite(n)?k(n):O}function On(n,e,t){for(let r=e;r<e+t;r++)if(_(n[r].kind))return!0;return!1}var fn=(n,e,t)=>t>1?Math.trunc(n[e+1].num):0;function Je(n,e,t){let r=Yn(n.mant,n.scale,e,t);return r===null?N:wn(n,r[0],r[1])}function Zn(n,e,t,r){let o=Number(n[e+t-1].mant),i="";for(let a=e;a<e+t-1;a++){let l=n[a];if(l.kind===c.Money){if(i!==""&&l.str!==i)return un;i=l.str}}let u=0n,s=0;for(let a=e;a<e+t-1;a++){let l=n[a];if(l.kind===c.Blank)continue;let[g,m]=U(l),p=v(g,o-m);if(p===null)return N;if(s===0)u=p;else{let d=r(u,p);if(d===null)return N;u=d}s++}return{m:u,scale:o,cur:i,count:s}}function Ot(n,e,t){switch(t){case M.HalfUp:return J(n,e);case M.HalfEven:{let r=Math.trunc(e);if(r>300)return n;if(r<-300)return 0;let o=P(r),i=n*o;if(Math.abs(i)>=2**52)return n;let u=Math.trunc(i),s=Math.abs(i-u);return(s>.5||s===.5&&u%2!==0?u+Math.sign(i):u)/o}case M.Down:return H(n,e,Math.trunc);case M.Up:return H(n,e,r=>r<0?Math.floor(r):Math.ceil(r));case M.Floor:return H(n,e,Math.floor)}return H(n,e,Math.ceil)}var zn=(n,e,t)=>t>1?n[e+1].num:0;function Wn(n,e,t){return{name:n,fn:(r,o,i,u)=>_(o[i].kind)?Je(o[i],fn(o,i,u),t):R(H(o[i].num,zn(o,i,u),e))}}function Ke(n,e,t,r,o){if(On(n,e,t)){let s=Zn(n,e,t,o);return s instanceof b?s:s.count===0?h:an(s.m,s.scale,s.cur)}let i=0,u=!1;for(let s=e;s<e+t;s++){let a=n[s];a.kind!==c.Blank&&((!u||r(i,a.num))&&(i=a.num),u=!0)}return u?k(i):h}function Ye(n,e,t){let r=0,o=0;for(let i=e;i<e+t;i++){let u=n[i];u.kind!==c.Blank&&(o++,r+=u.num)}return[r,o]}function Z(n,e){let t=Math.trunc(n.num);return t>=0?t:rn(e+" must not be negative")}var Bn=(n,e)=>n>e?e:n,qe=(n,e)=>Math.min(n,e.length+1)-1;function je(n,e){return e<0?0:L(n.slice(0,e))+1}var Ct=/^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/;function Lt(n){return n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45||n===46||n===95||n===126}function Vt(n){if(!/^(0|[1-9][0-9]*)$/.test(n))return-1;let e=Number(n);return Number.isSafeInteger(e)?e:-1}function It(n){let e="gu",t=n;for(;;){let r=/^\(\?([ims]+)\)/.exec(t);if(r===null)break;for(let o of r[1])e.includes(o)||(e+=o);t=t.slice(r[0].length)}return new RegExp(t,e)}function vn(n,e){return{name:n,fn:(t,r,o)=>{if(r[o].kind===c.Blank)return h;let[i,u,s]=Q(r[o]);return k(e(i,u,s))}}}function _n(n,e,t){return n[e].kind===c.Blank||n[e+1].kind===c.Blank?h:t(n[e],n[e+1])}function Qn(n,e){return{name:n,fn:t=>{let r=t.ctx?.doc,o=r?e(r):void 0;return o?$(o):h}}}function Sn(n,e){return{name:n,fn:t=>{let r=t.ctx?.doc,o=r?e(r):void 0;return o?y(o):h}}}function Cn(n,e){return n.ctx?.doc?.states?.find(t=>t.state===e)}function Rn(n,e){return{name:n,fn:(t,r,o)=>{let i=Cn(t,r[o].str),u=i?e(i):void 0;return u?$(u):h}}}function z(n,e){return{name:n,fn:(t,r,o)=>{let i=Cn(t,r[o].str),u=i?e(i):void 0;return u?y(u):h}}}var ln=n=>n?y(n):h,mn=[{name:"ISBLANK",fn:(n,e,t)=>I(e[t].kind===c.Blank)},{name:"ISNOTBLANK",fn:(n,e,t)=>I(e[t].kind!==c.Blank)},{name:"ROUND",fn:(n,e,t,r)=>{let o=e[t];if(!_(o.kind)&&r<3)return R(J(o.num,zn(e,t,r)));let i=Kn(r>2?e[t+2].str:void 0);return _(o.kind)?Je(o,fn(e,t,r),i):R(Ot(o.num,zn(e,t,r),i))}},Wn("FLOOR",Math.floor,M.Floor),Wn("CEILING",Math.ceil,M.Ceiling),Wn("TRUNC",Math.trunc,M.Down),{name:"ABS",fn:(n,e,t)=>{let r=e[t];return _(r.kind)?r.mant<0n&&r.mant===-(2n**63n)?N:wn(r,r.mant<0n?-r.mant:r.mant,r.scale):k(Math.abs(r.num))}},{name:"SIGN",fn:(n,e,t)=>{let r=e[t];return _(r.kind)?A(r.mant>0n?1n:r.mant<0n?-1n:0n,0):k(r.num>0?1:r.num<0?-1:0)}},{name:"MIN",fn:(n,e,t,r)=>Ke(e,t,r,(o,i)=>i<o,(o,i)=>i<o?i:o)},{name:"MAX",fn:(n,e,t,r)=>Ke(e,t,r,(o,i)=>i>o,(o,i)=>i>o?i:o)},{name:"SUM",fn:(n,e,t,r)=>{if(On(e,t,r)){let o=Zn(e,t,r,Tn);return o instanceof b?o:an(o.m,o.scale,o.cur)}return R(Ye(e,t,r)[0])}},{name:"AVERAGE",fn:(n,e,t,r)=>{if(On(e,t,r)){let u=Zn(e,t,r,Tn);if(u instanceof b)return u;if(u.count===0)return h;let s=$n(u.m,u.scale,BigInt(u.count),0);return s instanceof b?s:an(s[0],s[1],u.cur)}let[o,i]=Ye(e,t,r);return i===0?h:R(o/i)}},{name:"COUNT",fn:(n,e,t,r)=>{let o=0;for(let i=t;i<t+r;i++)e[i].kind!==c.Blank&&o++;return k(o)}},{name:"POWER",fn:(n,e,t)=>R(pn(e[t].num,e[t+1].num))},{name:"SQRT",fn:(n,e,t)=>e[t].num<0?O:k(Math.sqrt(e[t].num))},{name:"EXP",fn:(n,e,t)=>R(Math.exp(e[t].num))},{name:"LN",fn:(n,e,t)=>e[t].num<=0?O:k(j(e[t].num))},{name:"LOG",fn:(n,e,t,r)=>{let o=e[t].num,i=r>1?e[t+1].num:10;return o<=0||i<=0||i===1?O:R(i===10?fe(o):j(o)/j(i))}},{name:"MOD",fn:(n,e,t,r)=>{if(On(e,t,r)){let u=Number(e[t+r-1].mant),s=e[t],a=e[t+1];if(s.kind===c.Money&&a.kind===c.Money&&s.str!==a.str)return un;let[l,g]=U(s),[m,p]=U(a),d=v(l,u-g),x=v(m,u-p);if(d===null||x===null)return N;let T=Ae(d,x);return T instanceof b?T:an(T,u,s.kind===c.Money?s.str:a.kind===c.Money?a.str:"")}let o=e[t].num,i=e[t+1].num;return i===0?gn:R(o-i*Math.floor(o/i))}},{name:"DATE",fn:(n,e,t)=>Fe(e[t].num,e[t+1].num,e[t+2].num)},{name:"DATEVALUE",fn:(n,e,t)=>Pe(e[t].str)},vn("YEAR",n=>n),vn("MONTH",(n,e)=>e),vn("DAY",(n,e,t)=>t),vn("QUARTER",(n,e)=>Math.floor((e-1)/3)+1),{name:"DAYS",fn:(n,e,t)=>_n(e,t,(r,o)=>k(q(r)-q(o)))},{name:"DAYSBETWEEN",fn:(n,e,t)=>_n(e,t,(r,o)=>k(q(o)-q(r)))},{name:"MONTHSBETWEEN",fn:(n,e,t)=>_n(e,t,(r,o)=>{let[i,u]=Q(r),[s,a]=Q(o);return k(s*12+a-(i*12+u))})},{name:"YEARSBETWEEN",fn:(n,e,t)=>_n(e,t,(r,o)=>k(Q(o)[0]-Q(r)[0]))},{name:"ADDDAYS",fn:(n,e,t)=>{let r=e[t];return r.kind===c.Blank?h:r.kind===c.Date?cn(r.num+Math.trunc(e[t+1].num)):Dn(r.num+e[t+1].num*V)}},{name:"ADDMONTHS",fn:(n,e,t)=>Xn(e[t],e[t+1].num)},{name:"ADDYEARS",fn:(n,e,t)=>Xn(e[t],12*Math.trunc(e[t+1].num))},{name:"NOW",fn:n=>$(n.now())},{name:"TODAY",fn:n=>W(Math.floor(n.now()/86400))},{name:"USER",fn:n=>ln(n.ctx?.user)},{name:"INGROUP",fn:(n,e,t)=>{let r=n.ctx,o=e[t].str;return r?I((r.groups?.includes(o)??!1)||(r.system?.includes(o)??!1)||!!r.user&&o==="everyone"):I(!1)}},{name:"USERKIND",fn:n=>ln(n.ctx?.kind)},{name:"ACTINGFOR",fn:n=>ln(n.ctx?.for)},{name:"STATE",fn:n=>ln(n.ctx?.state)},{name:"ID",fn:n=>ln(n.ctx?.id)},{name:"LEFT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=G(e[t].str);return y(o.slice(0,Bn(r,o.length)).join(""))}},{name:"RIGHT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=G(e[t].str);return y(o.slice(o.length-Bn(r,o.length)).join(""))}},{name:"MID",fn:(n,e,t,r)=>{let o=Math.trunc(e[t+1].num);if(!(o>=1))return rn("the position must be 1 or more");let i=G(e[t].str),u=qe(o,i),s=i.length;if(r>2){let a=Z(e[t+2],"the length");if(a instanceof b)return a;s=u+Bn(a,i.length-u)}return y(i.slice(u,s).join(""))}},{name:"LEN",fn:(n,e,t)=>k(L(e[t].str))},{name:"TRIM",fn:(n,e,t)=>{let r="",o=!0;for(let i of e[t].str){if(i===" "){o||(r+=" ",o=!0);continue}r+=i,o=!1}return y(r.endsWith(" ")?r.slice(0,-1):r)}},{name:"UPPER",fn:(n,e,t)=>y(xe(e[t].str))},{name:"LOWER",fn:(n,e,t)=>y(ye(e[t].str))},{name:"PROPER",fn:(n,e,t)=>y(Ee(e[t].str))},{name:"REPLACE",fn:(n,e,t)=>{let r=Math.trunc(e[t+1].num);if(!(r>=1))return rn("the position must be 1 or more");let o=Z(e[t+2],"the length");if(o instanceof b)return o;let i=G(e[t].str),u=qe(r,i),s=u+Bn(o,i.length-u),a=e[t+3].str;return i.length-(s-u)+L(a)>n.maxText?C():y(i.slice(0,u).join("")+a+i.slice(s).join(""))}},{name:"SUBSTITUTE",fn:(n,e,t)=>{let r=e[t].str,o=e[t+1].str,i=e[t+2].str;if(o==="")return y(r);let u=r.split(o).join(i);return on(u,n.maxText)?C():y(u)}},{name:"CONCAT",fn:(n,e,t,r)=>{let o="";for(let i=t;i<t+r;i++)o+=Y(e[i]);return on(o,n.maxText)?C():y(o)}},{name:"REPEAT",fn:(n,e,t)=>{let r=Z(e[t+1],"the count");if(r instanceof b)return r;let o=e[t].str;return o===""||r===0?y(""):r*o.length>n.maxText&&r*L(o)>n.maxText?C():y(o.repeat(r))}},{name:"FINDFIRST",fn:(n,e,t)=>k(je(e[t+1].str,e[t+1].str.indexOf(e[t].str)))},{name:"FINDLAST",fn:(n,e,t)=>k(je(e[t+1].str,e[t+1].str.lastIndexOf(e[t].str)))},{name:"PAD",fn:(n,e,t,r)=>{let o=Z(e[t+1],"the width");if(o instanceof b)return o;if(o>n.maxText)return C();let i=" ";r>2&&e[t+2].str!==""&&(i=G(e[t+2].str)[0]);let u=e[t].str,s=L(u);return y(s>=o?u:i.repeat(o-s)+u)}},{name:"REGEXREPLACE",fn:(n,e,t)=>{let r;try{r=It(e[t+1].str)}catch(m){return new b(w.BadText,"invalid pattern: "+m.message)}let o=e[t].str,i=e[t+2].str,u="",s=0,a=-1,l=0,g=0;for(let m=r.exec(o);m!==null;m=r.exec(o)){let p=m.index,d=p+m[0].length;if(!(m[0].length===0&&(r.lastIndex=p+(o.codePointAt(p)>65535?2:1),p===a))&&(u+=o.slice(s,p)+i,l+=L(m[0]),g++,s=d,a=d,p>=o.length))break}return g===0?y(o):L(o)-l+g*L(i)>n.maxText?C():y(u+o.slice(s))}},{name:"TEXT",fn:(n,e,t)=>y(Y(e[t]))},{name:"VALUE",fn:(n,e,t)=>{let r=K(e[t].str);return r===""?h:Ct.test(r)?R(Number(r)):new b(w.BadText,"not a number: "+r)}},{name:"JSONVALUE",fn:(n,e,t)=>{if(e[t].kind===c.Blank)return h;let r;try{r=JSON.parse(e[t].str)}catch(i){return new b(w.BadText,"invalid json: "+i.message)}let o=e[t+1].str;if(o!=="")for(let i of o.split("."))if(Array.isArray(r)){let u=Vt(i);if(u<0||u>=r.length)return h;r=r[u]}else if(r!==null&&typeof r=="object"){if(!Object.prototype.hasOwnProperty.call(r,i))return h;r=r[i]}else return h;switch(typeof r){case"string":return y(r);case"number":return y(Hn(r));case"boolean":return y(r?"TRUE":"FALSE")}return r===null?h:new b(w.BadText,"the path does not lead to a scalar")}},{name:"DECIMAL",fn:(n,e,t,r)=>{let o=e[t],i=fn(e,t,r),u=Kn(r>2?e[t+2].str:void 0);if(o.kind===c.Blank)return h;if(_(o.kind)){let a=Yn(o.mant,o.scale,i,u);return a===null?N:A(a[0],a[1])}let s=jn(o.num,i,u);return s instanceof b?s:A(s,i)}},{name:"NUMBER",fn:(n,e,t)=>{let r=e[t];return r.kind===c.Blank?h:k(_(r.kind)?ve(r.mant,r.scale):r.num)}},{name:"MONEY",fn:(n,e,t)=>{let r=e[t];if(r.kind===c.Blank)return h;let o=e[t+1].str;if(!qn(o))return new b(w.BadText,"a currency is three upper-case letters, got "+JSON.stringify(o));let[i,u]=U(r);return F(i,u,o)}},{name:"MONEYVALUE",fn:(n,e,t,r)=>Jn(e[t].str,fn(e,t,r),!0)},{name:"DECIMALVALUE",fn:(n,e,t,r)=>Jn(e[t].str,fn(e,t,r),!1)},{name:"AMOUNT",fn:(n,e,t)=>e[t].kind===c.Blank?h:A(e[t].mant,e[t].scale)},{name:"CURRENCY",fn:(n,e,t)=>e[t].kind===c.Blank?h:y(e[t].str)},{name:"DATETIMEVALUE",fn:(n,e,t)=>$e(e[t].str)},{name:"DATEOF",fn:(n,e,t)=>e[t].kind===c.Blank?h:W(Math.floor(e[t].num/V))},{name:"DATETIME",fn:(n,e,t)=>e[t].kind===c.Blank?h:$(e[t].num*V)},{name:"URLENCODE",fn:(n,e,t)=>{let r=ke(e[t].str),o="",i="0123456789ABCDEF";for(let u of r)o+=Lt(u)?String.fromCharCode(u):"%"+i[u>>4]+i[u&15];return o.length>n.maxText&&o.length!==r.length?C():y(o)}},Qn("CREATEDAT",n=>n.created_at),Sn("CREATEDBY",n=>n.created_by),Qn("UPDATEDAT",n=>n.updated_at),Sn("UPDATEDBY",n=>n.updated_by),Qn("ENTEREDAT",n=>n.entered_at),Sn("ENTEREDBY",n=>n.entered_by),Sn("ENTEREDFROM",n=>n.entered_from),{name:"VERSION",fn:n=>{let e=n.ctx?.doc?.version;return e?k(e):h}},Rn("FIRSTENTERED",n=>n.fe),z("FIRSTENTEREDBY",n=>n.feb),Rn("LASTENTERED",n=>n.le),z("LASTENTEREDBY",n=>n.leb),Rn("FIRSTLEFT",n=>n.fl),z("FIRSTLEFTBY",n=>n.flb),Rn("LASTLEFT",n=>n.ll),z("LASTLEFTBY",n=>n.llb),{name:"ENTRIES",fn:(n,e,t)=>{if(!n.ctx?.doc)return h;let r=Cn(n,e[t].str);return k(r?r.n??0:0)}},{name:"DAYSIN",fn:(n,e,t)=>{if(!n.ctx?.doc)return h;let r=Cn(n,e[t].str);if(!r)return k(0);let o=r.secs??0;return r.here&&(o+=n.now()-(r.le??0)),k(o/V)}},z("FIRSTEDITOR",n=>n.fed),z("LASTEDITOR",n=>n.led),{name:"REF",fn:(n,e,t)=>{let r=e[t+1];return r.kind===c.Blank||r.str===""?h:Un(e[t].str+":"+r.str)}}];function He(n,e){if(n.kind===c.Blank&&e.kind===c.Blank)return 0;let t=n.kind===c.Blank?e.kind:n.kind;return t===c.Text||t===c.Ref||t===c.JSON?de(n.str,e.str):n.num<e.num?-1:n.num>e.num?1:0}var ne=4,f={Nop:0,ConstNum:1,ConstText:2,True:3,False:4,Blank:5,Load:6,Neg:7,Percent:8,Not:9,Add:10,Sub:11,Mul:12,Div:13,DivStrict:14,Pow:15,Concat:16,Eq:17,Ne:18,Lt:19,Le:20,Gt:21,Ge:22,Jump:23,JumpIfFalse:24,AndJump:25,OrJump:26,ToBool:27,Call:28,Lookup:29,Query:30,Return:31,ConstDec:32,DecNeg:33,DecPercent:34,DecAdd:35,DecSub:36,DecMul:37,DecDiv:38,DecScale:39,Try:40,EndTry:41},Ln=18,Ft=256,Ut={bool:c.Bool,number:c.Number,text:c.Text,date:c.Date,datetime:c.DateTime,ref:c.Ref,json:c.JSON};function dn(n){let e=Ut[n];if(e!==void 0)return{kind:e,scale:0,elem:c.Blank};switch(n){case"blank":return{kind:c.Blank,scale:0,elem:c.Blank};case"rows":return{kind:c.Rows,scale:0,elem:c.Blank};case"int":return{kind:c.Decimal,scale:0,elem:c.Blank};case"decimal":return{kind:c.Decimal,scale:2,elem:c.Blank};case"money":return{kind:c.Money,scale:2,elem:c.Blank}}if(n.startsWith("array<")&&n.endsWith(">")){let t=dn(n.slice(6,-1));if(t.kind===c.Blank||t.kind>=c.Array)throw new Error(`unknown type "${n}"`);return{kind:c.Array,scale:t.scale,elem:t.kind}}for(let[t,r]of[["decimal(",c.Decimal],["money(",c.Money]])if(n.startsWith(t)&&n.endsWith(")")){let o=n.slice(t.length,-1),i=Number(o);if(!/^[0-9]+$/.test(o)||i>Ln)throw new Error(`type "${n}": the scale must be 0 to ${Ln}`);return{kind:r,scale:i,elem:c.Blank}}throw new Error(`unknown type "${n}"`)}var Pt=new TextDecoder("utf-8"),ee=class{constructor(e){this.bytes=e;this.at=0;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}need(e){if(this.at+e>this.bytes.length)throw new Error("bytecode: the program ends early")}u8(){return this.need(1),this.bytes[this.at++]}u16(){this.need(2);let e=this.view.getUint16(this.at);return this.at+=2,e}u32(){this.need(4);let e=this.view.getUint32(this.at);return this.at+=4,e}i32(){this.need(4);let e=this.view.getInt32(this.at);return this.at+=4,e}f64(){this.need(8);let e=this.view.getFloat64(this.at);return this.at+=8,e}i64(){this.need(8);let e=this.view.getBigInt64(this.at);return this.at+=8,e}count(){let e=this.u32();if(e>this.bytes.length-this.at)throw new Error("bytecode: the program ends early");return e}str(){let e=this.count(),t=Pt.decode(this.bytes.subarray(this.at,this.at+e));return this.at+=e,t}program(){let e=this.count();if(e===0)return null;let t=Ge(this.bytes.subarray(this.at,this.at+e));return this.at+=e,t}};function Ge(n){if(n.length<8||n[0]!==70||n[1]!==65||n[2]!==68||n[3]!==79)throw new Error("bytecode: not a FadoDB program");let e=new ee(n.subarray(4)),t=e.u16();if(t!==ne)throw new Error(`bytecode: format version ${t}, this build reads ${ne}`);e.u16();let r=new Float64Array(e.count());for(let E=0;E<r.length;E++)r[E]=e.f64();let o=[];for(let E=e.count(),D=0;D<E;D++){let nn=e.i64(),en=e.u8();if(en>Ln)throw new Error(`bytecode: exact constant ${D} has scale ${en}`);o.push({mant:nn,scale:en})}let i=[];for(let E=e.count(),D=0;D<E;D++)i.push(e.str());let u=[];for(let E=e.count(),D=0;D<E;D++){let nn=e.str();u.push({name:nn,type:dn(e.str())})}let s=e.count(),a=new Uint8Array(s),l=new Int32Array(s);for(let E=0;E<s;E++)a[E]=e.u8(),l[E]=e.i32();let g=null,m=e.count();if(m>0){g=new Int32Array(m);for(let E=0;E<m;E++)g[E]=e.i32()}let p=dn(e.str()),d=[];for(let E=e.count(),D=0;D<E;D++)d.push(e.str());let x=[];for(let E=e.count(),D=0;D<E;D++){let nn=e.str(),en=e.str(),ze=dn(e.str()),re=[];for(let Vn=e.count(),tn=0;tn<Vn;tn++)re.push(e.str());let oe=[],ie=[];for(let Vn=e.count(),tn=0;tn<Vn;tn++)oe.push(e.i32()),ie.push(e.str());let nt=e.program(),et=e.program(),tt=e.str(),rt=e.u8()!==0,ot=e.str(),it=e.program();x.push({source:nn,column:en,type:ze,order:re,args:oe,argNames:ie,cond:nt,key:et,indexColumn:tt,keyPart:rt,agg:ot,value:it})}let T=e.u32(),S={nums:r,decs:o,texts:i,slots:u,ops:a,args:l,pos:g,result:p,classes:d,queries:x,maxStack:T};return $t(S),S}var Xe=0;function We(n){Xe=n}function $t(n){let e=n.ops.length;if(e===0||n.ops[e-1]!==f.Return)throw new Error("bytecode: code must end with return");if(n.pos!==null&&n.pos.length!==e)throw new Error("bytecode: positions do not match the code");for(let t=0;t<e;t++){let r=n.args[t],o=i=>{throw new Error(`bytecode: instruction ${t}: ${i}`)};switch(n.ops[t]){case f.ConstNum:(r<0||r>=n.nums.length)&&o(`number constant ${r} out of range`);break;case f.ConstText:(r<0||r>=n.texts.length)&&o(`text constant ${r} out of range`);break;case f.ConstDec:(r<0||r>=n.decs.length)&&o(`exact constant ${r} out of range`);break;case f.Load:(r<0||r>=n.slots.length)&&o(`slot ${r} out of range`);break;case f.Jump:case f.JumpIfFalse:case f.AndJump:case f.OrJump:case f.Try:(r<0||r>=e)&&o(`jump target ${r} out of range`);break;case f.DecNeg:case f.DecPercent:case f.DecAdd:case f.DecSub:case f.DecMul:case f.DecDiv:case f.DecScale:(r<0||(r&255)>Ln||(r&~(255|Ft))!==0)&&o(`scale ${r} out of range`);break;case f.Call:(r>>8>=Xe||r<0)&&o(`unknown builtin ${r>>8}`);break;case f.Lookup:case f.Query:(r<0||r>=n.queries.length)&&o(`query slot ${r} out of range`);break;default:n.ops[t]>f.EndTry&&o(`unknown opcode ${n.ops[t]}`)}}}We(mn.length);var Ze=65536,Qe=16;function Kt(n,e,t){let r=e.pos!==null?e.pos[t]:-1;return new b(n.code,n.detail,r)}var te=class{constructor(e={}){this.stack=[];this.tryPc=new Int32Array(Qe);this.trySp=new Int32Array(Qe);this.maxText=e.maxText&&e.maxText>0?e.maxText:Ze}now(){return this.ctx?.now?this.ctx.now:Math.floor(Date.now()/1e3)}run(e,t,r){if(t.length<e.slots.length)throw new b("query_failed",`program reads ${e.slots.length} variables, got ${t.length}`);let o=this.stack;for(;o.length<e.maxStack;)o.push(h);this.ctx=r;let i=e.ops,u=e.args,s=0,a=0,l=0;for(;;){let g=i[l],m=u[l];l++;let p=null;switch(g){case f.Nop:break;case f.ConstNum:o[a++]=k(e.nums[m]);break;case f.ConstText:o[a++]=y(e.texts[m]);break;case f.True:o[a++]=yn;break;case f.False:o[a++]=X;break;case f.Blank:o[a++]=h;break;case f.Load:o[a++]=t[m];break;case f.Neg:o[a-1]=k(-o[a-1].num);break;case f.Percent:o[a-1]=k(o[a-1].num/100);break;case f.Not:o[a-1]=I(!o[a-1].truth);break;case f.Add:case f.Sub:case f.Mul:case f.Pow:{let d=o[a-2].num,x=o[a-1].num,T=g===f.Add?d+x:g===f.Sub?d-x:g===f.Mul?d*x:pn(d,x);if(!Number.isFinite(T)){p=O;break}a--,o[a-1]=k(T);break}case f.Div:case f.DivStrict:{let d=o[a-2].num,x=o[a-1].num;if(x===0){p=bn;break}let T=d/x;if(!Number.isFinite(T)){p=O;break}a--,o[a-1]=k(T);break}case f.ConstDec:{let d=e.decs[m];o[a++]=A(d.mant,d.scale);break}case f.DecNeg:case f.DecPercent:case f.DecScale:{let d=Se(g===f.DecScale,g===f.DecNeg,o[a-1],m);if(d instanceof b){p=d;break}o[a-1]=d;break}case f.DecAdd:case f.DecSub:case f.DecMul:case f.DecDiv:{let d=Oe(g-f.DecAdd,o[a-2],o[a-1],m);if(d instanceof b){p=d;break}a--,o[a-1]=d;break}case f.Concat:{let d=Y(o[a-2])+Y(o[a-1]);if(on(d,this.maxText)){p=C();break}a--,o[a-1]=y(d);break}case f.Eq:case f.Ne:case f.Lt:case f.Le:case f.Gt:case f.Ge:{let d=o[a-2],x=o[a-1],T;if(_(d.kind)||_(x.kind)){let S=Re(d,x,m);if(S instanceof b){p=S;break}T=S}else T=He(d,x);a--,o[a-1]=I(g===f.Eq?T===0:g===f.Ne?T!==0:g===f.Lt?T<0:g===f.Le?T<=0:g===f.Gt?T>0:T>=0);break}case f.Jump:l=m;break;case f.JumpIfFalse:a--,o[a].truth||(l=m);break;case f.AndJump:o[a-1].truth?a--:(o[a-1]=X,l=m);break;case f.OrJump:o[a-1].truth?l=m:a--;break;case f.ToBool:o[a-1].kind===c.Blank&&(o[a-1]=X);break;case f.Try:this.tryPc[s]=m,this.trySp[s]=a,s++;break;case f.EndTry:s--;break;case f.Call:{let d=m&255,x=mn[m>>8].fn(this,o,a-d,d);if(x instanceof b){p=x;break}a-=d,o[a++]=x;break}case f.Lookup:case f.Query:p=ue;break;case f.Return:return o[a-1];default:p=new b("query_failed",`unknown opcode ${g}`)}if(p!==null){if(s>0){s--,a=this.trySp[s],l=this.tryPc[s];continue}throw Kt(p,e,l-1)}}}};function Dr(){return mn.map(n=>n.name)}export{h as BLANK,Ze as DEFAULT_MAX_TEXT,w as ErrorCode,b as EvalError,X as FALSE,ne as FORMAT_VERSION,c as Kind,yn as TRUE,te as VM,B as Value,I as bool,Dr as builtinNames,W as date,$ as datetime,A as decimal,Ge as decode,ht as json,gt as kindNames,F as money,k as number,dn as parseType,Un as ref,Y as render,pt as same,y as text};
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fadodb-vm",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "4.1.0",
|
|
4
|
+
"description": "FadoDB's formula machine for a page: it runs the formulas the engine compiled, with the server's answers, and never parses a formula.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./fadodb-vm.js",
|
|
8
|
+
"module": "./fadodb-vm.js",
|
|
9
|
+
"types": "./fadodb-vm.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./fadodb-vm.d.ts",
|
|
13
|
+
"import": "./fadodb-vm.js"
|
|
14
|
+
},
|
|
15
|
+
"./iife": "./fadodb-vm.iife.js"
|
|
16
|
+
},
|
|
17
|
+
"unpkg": "./fadodb-vm.iife.js",
|
|
18
|
+
"jsdelivr": "./fadodb-vm.iife.js",
|
|
19
|
+
"files": ["fadodb-vm.js", "fadodb-vm.iife.js", "fadodb-vm.d.ts"],
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/MojoHand70/fadodb.git",
|
|
23
|
+
"directory": "web/vm"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://fadodb.org",
|
|
26
|
+
"bugs": "https://github.com/MojoHand70/fadodb/issues",
|
|
27
|
+
"keywords": ["fadodb", "formula", "bytecode", "vm", "spreadsheet", "decimal", "money"]
|
|
28
|
+
}
|