@velarscript/core 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2934 @@
1
+ import { optionalOf as optional, VELAR_BYTES_TYPE_IDENTITY, VELAR_FLOAT32_BUFFER_TYPE_IDENTITY, VELAR_UINT8_BUFFER_TYPE_IDENTITY, VELAR_UINT16_BUFFER_TYPE_IDENTITY, VELAR_UINT32_BUFFER_TYPE_IDENTITY, } from "@velarscript/compiler";
2
+ import { VELAR_CLASS_FIELD_MODULE, VELAR_CLASS_FIELD_MODULE_SOURCE, VELAR_COLLECTION_HOST_MODULE, VELAR_COLLECTION_HOST_MODULE_SOURCE, VELAR_COLLECTION_LOWERING_DEPENDENCIES, VELAR_COLLECTION_LOWERING_MODULE, VELAR_COLLECTION_LOWERING_MODULE_SOURCE, VELAR_ERROR_NORMALIZATION_MODULE, VELAR_ERROR_NORMALIZATION_MODULE_SOURCE, VELAR_ERROR_NORMALIZATION_RUNTIME, VELAR_NARROWING_MODULE, VELAR_NARROWING_MODULE_SOURCE, VELAR_PRIMITIVE_METHOD_MODULE, VELAR_PRIMITIVE_METHOD_MODULE_SOURCE, VELAR_PROMISE_NORMALIZATION_MODULE, VELAR_PROMISE_NORMALIZATION_MODULE_SOURCE, VELAR_REACTIVE_BRIDGE_MODULE, VELAR_NON_REACTIVE_BRIDGE_MODULE_SOURCE, VELAR_RUNTIME_REGISTRY_KEY, VELAR_RUNTIME_SCHEMA_VERSION, VELAR_STRICT_JSON_RUNTIME, VELAR_TEXT_METHOD_RUNTIME, VELAR_TYPE_REGISTRY_RUNTIME, VELAR_TYPE_VALIDATION_MODULE, VELAR_TYPE_VALIDATION_MODULE_SOURCE, VELAR_UTF8_RUNTIME, } from "@velarscript/compiler/extension";
3
+ export const CORE_WORKER_CONFIG_KEY = "velar:core-workers-v1";
4
+ export const VELAR_STANDARD_API_VERSION = "0.5";
5
+ export const VELAR_WORKER_MANIFEST_MODULE = "velar/worker-manifest";
6
+ const anyType = { kind: "any" };
7
+ const nullType = { kind: "null" };
8
+ const stringType = { kind: "string" };
9
+ const numberType = { kind: "number" };
10
+ const boolType = { kind: "bool" };
11
+ const durationType = { kind: "named", name: "Duration" };
12
+ function functionType(parameters, result, requiredParameters = parameters.length) {
13
+ return { kind: "function", parameters, requiredParameters, result };
14
+ }
15
+ function apiFunction(parameterNames, parameters, result, requiredParameters = parameters.length) {
16
+ return { kind: "function", parameterNames, parameters, requiredParameters, result };
17
+ }
18
+ function intrinsic(name, parameters, result, requiredParameters = parameters.length) {
19
+ return { kind: "intrinsic", name, parameters, requiredParameters, result };
20
+ }
21
+ function apiIntrinsic(name, parameterNames, parameters, result, requiredParameters = parameters.length) {
22
+ return { kind: "intrinsic", name, parameterNames, parameters, requiredParameters, result };
23
+ }
24
+ function promise(value) {
25
+ return { kind: "promise", value };
26
+ }
27
+ function object(fields) {
28
+ return { kind: "object", fields: new Map(Object.entries(fields)) };
29
+ }
30
+ const unknownType = { kind: "unknown" };
31
+ const errorType = { kind: "class", name: "Error" };
32
+ const cleanupType = apiFunction([], [], nullType);
33
+ const listAny = { kind: "list", element: anyType };
34
+ const listNumber = { kind: "list", element: numberType };
35
+ const listString = { kind: "list", element: stringType };
36
+ const mapAny = { kind: "map", key: anyType, value: anyType };
37
+ const mapString = (value) => ({ kind: "map", key: stringType, value });
38
+ const patternOptionsType = object({
39
+ ignoreCase: optional(boolType),
40
+ multiline: optional(boolType),
41
+ dotAll: optional(boolType),
42
+ });
43
+ const textMatchType = object({
44
+ value: stringType,
45
+ index: numberType,
46
+ groups: { kind: "list", element: optional(stringType) },
47
+ });
48
+ const textMatchArrayType = { kind: "list", element: textMatchType };
49
+ const urlInfoType = object({
50
+ href: stringType,
51
+ protocol: stringType,
52
+ host: stringType,
53
+ hostname: stringType,
54
+ port: stringType,
55
+ path: stringType,
56
+ query: { kind: "map", key: stringType, value: stringType },
57
+ hash: stringType,
58
+ origin: stringType,
59
+ });
60
+ const timePartsType = object({
61
+ year: numberType, month: numberType, day: numberType, weekday: numberType,
62
+ hour: numberType, minute: numberType, second: numberType, millisecond: numberType,
63
+ });
64
+ const logFieldsType = mapString(unknownType);
65
+ /**
66
+ * D59 rule 145.3 and D65 rule 171: `useSink` hands a record to the sink, so a
67
+ * sink written as a named `def` needs a name for that record's type. The
68
+ * fields are registered as `velar/log`'s `LogRecord` and the name is exported,
69
+ * the way `velar/serve` publishes `ServeRequest` and `velar/fs` publishes
70
+ * `FileWatchBatch`. One field map, read as the parameter type and as the
71
+ * module's named type, so the two cannot drift.
72
+ */
73
+ const logRecordFields = {
74
+ timestamp: numberType,
75
+ level: stringType,
76
+ scope: stringType,
77
+ message: stringType,
78
+ fields: logFieldsType,
79
+ error: optional(errorType),
80
+ };
81
+ const logRecordType = object(logRecordFields);
82
+ const loggerType = object({
83
+ debug: apiFunction(["message", "fields"], [stringType, logFieldsType], nullType, 1),
84
+ info: apiFunction(["message", "fields"], [stringType, logFieldsType], nullType, 1),
85
+ warn: apiFunction(["message", "fields"], [stringType, logFieldsType], nullType, 1),
86
+ error: apiFunction(["message", "error", "fields"], [stringType, errorType, logFieldsType], nullType, 1),
87
+ });
88
+ const byteOrderIdentity = "velar/binary#enum:ByteOrder";
89
+ const byteOrderMembers = new Set(["little", "big"]);
90
+ const byteOrderType = { kind: "enum", name: "ByteOrder", identity: byteOrderIdentity };
91
+ const bytesType = { kind: "named", name: "Bytes", identity: VELAR_BYTES_TYPE_IDENTITY };
92
+ const uint8BufferType = { kind: "named", name: "UInt8Buffer", identity: VELAR_UINT8_BUFFER_TYPE_IDENTITY };
93
+ const uint16BufferType = { kind: "named", name: "UInt16Buffer", identity: VELAR_UINT16_BUFFER_TYPE_IDENTITY };
94
+ const uint32BufferType = { kind: "named", name: "UInt32Buffer", identity: VELAR_UINT32_BUFFER_TYPE_IDENTITY };
95
+ const float32BufferType = { kind: "named", name: "Float32Buffer", identity: VELAR_FLOAT32_BUFFER_TYPE_IDENTITY };
96
+ const uint32BuilderType = { kind: "named", name: "UInt32Builder", identity: "velar/binary#type:UInt32Builder" };
97
+ const float32BuilderType = { kind: "named", name: "Float32Builder", identity: "velar/binary#type:Float32Builder" };
98
+ const binaryBufferFields = (type, ordered) => new Map([
99
+ ["size", numberType],
100
+ ["copy", apiFunction([], [], type)],
101
+ ["slice", apiFunction(["start", "end"], [numberType, numberType], type, 0)],
102
+ ["toBytes", ordered ? apiFunction(["order"], [byteOrderType], bytesType) : apiFunction([], [], bytesType)],
103
+ ]);
104
+ const binaryBuilderFields = (type) => new Map([
105
+ ["size", numberType],
106
+ ["maxElements", numberType],
107
+ ["push", apiFunction(["value"], [numberType], nullType)],
108
+ ["finish", apiFunction([], [], type)],
109
+ ]);
110
+ const binaryNamedTypes = new Map([
111
+ ["Bytes", new Map([
112
+ ["size", numberType],
113
+ ])],
114
+ ["UInt8Buffer", binaryBufferFields(uint8BufferType, false)],
115
+ ["UInt16Buffer", binaryBufferFields(uint16BufferType, true)],
116
+ ["UInt32Buffer", binaryBufferFields(uint32BufferType, true)],
117
+ ["Float32Buffer", binaryBufferFields(float32BufferType, true)],
118
+ ["UInt32Builder", binaryBuilderFields(uint32BufferType)],
119
+ ["Float32Builder", binaryBuilderFields(float32BufferType)],
120
+ ]);
121
+ const binaryReadonlyFields = new Map([
122
+ ["Bytes", new Set(["size"])],
123
+ ["UInt8Buffer", new Set(["size", "copy", "slice", "toBytes"])],
124
+ ["UInt16Buffer", new Set(["size", "copy", "slice", "toBytes"])],
125
+ ["UInt32Buffer", new Set(["size", "copy", "slice", "toBytes"])],
126
+ ["Float32Buffer", new Set(["size", "copy", "slice", "toBytes"])],
127
+ ["UInt32Builder", new Set(["size", "maxElements", "push", "finish"])],
128
+ ["Float32Builder", new Set(["size", "maxElements", "push", "finish"])],
129
+ ]);
130
+ const randomIdentity = "velar/random#type:Random";
131
+ const randomType = { kind: "named", name: "Random", identity: randomIdentity };
132
+ const randomSeedType = { kind: "union", members: [stringType, numberType] };
133
+ const randomElementType = { kind: "parameter", name: "T", index: 0 };
134
+ const randomNamedTypes = new Map([
135
+ ["Random", new Map([
136
+ ["number", apiFunction([], [], numberType)],
137
+ ["int", apiFunction(["start", "end"], [numberType, numberType], numberType, 1)],
138
+ ["bool", apiFunction(["probability"], [numberType], boolType, 0)],
139
+ ["pick", { kind: "function", typeParameterNames: ["T"], parameters: [{ kind: "list", element: randomElementType }], parameterNames: ["values"], requiredParameters: 1, result: randomElementType }],
140
+ ["shuffle", { kind: "function", typeParameterNames: ["T"], parameters: [{ kind: "list", element: randomElementType }], parameterNames: ["values"], requiredParameters: 1, result: { kind: "list", element: randomElementType } }],
141
+ ["fork", apiFunction(["label"], [stringType], randomType)],
142
+ ])],
143
+ ]);
144
+ const randomReadonlyFields = new Map([["Random", new Set(["number", "int", "bool", "pick", "shuffle", "fork"])]]);
145
+ const cancellationIdentity = "velar/task#type:Cancellation";
146
+ const taskIdentity = "velar/task#type:Task";
147
+ const cancellationType = { kind: "named", name: "Cancellation", identity: cancellationIdentity };
148
+ const taskElementType = { kind: "parameter", name: "T", index: 0 };
149
+ const taskOf = (value) => ({
150
+ kind: "named",
151
+ name: `Task<${value.kind === "parameter" ? value.name : "T"}>`,
152
+ identity: taskIdentity,
153
+ application: { declaration: taskIdentity, name: "Task", arguments: [value] },
154
+ });
155
+ const taskTemplate = {
156
+ identity: taskIdentity,
157
+ name: "Task",
158
+ parameterNames: ["T"],
159
+ parameterBounds: [null],
160
+ fields: new Map([
161
+ ["result", apiFunction([], [], promise(taskElementType))],
162
+ ["cancel", apiFunction(["reason"], [stringType], promise(nullType), 0)],
163
+ ["close", apiFunction([], [], promise(nullType))],
164
+ ]),
165
+ readonlyFields: new Set(["result", "cancel", "close"]),
166
+ };
167
+ const cancellationFields = new Map([
168
+ ["cancelled", boolType],
169
+ ["reason", optional(stringType)],
170
+ ["checkpoint", apiFunction([], [], promise(nullType))],
171
+ ]);
172
+ const taskErrorClass = (identity) => ({
173
+ identity,
174
+ parameters: [stringType], parameterNames: ["message"], requiredParameters: 0,
175
+ base: "Error", abstract: false,
176
+ fields: new Map(), getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
177
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
178
+ });
179
+ const cancellationErrorIdentity = "velar/task#class:CancellationError";
180
+ const taskTimeoutErrorIdentity = "velar/task#class:TaskTimeoutError";
181
+ const workerIdentity = "velar/worker#type:Worker";
182
+ const workerPoolIdentity = "velar/worker#type:WorkerPool";
183
+ const workerRequestType = { kind: "parameter", name: "Request", index: 0 };
184
+ const workerResponseType = { kind: "parameter", name: "Response", index: 1 };
185
+ const workerApplication = (identity, name, request, response) => ({
186
+ kind: "named", name: `${name}<Request, Response>`, identity,
187
+ application: { declaration: identity, name, arguments: [request, response] },
188
+ });
189
+ const workerCallFields = new Map([
190
+ ["call", { kind: "function", parameterNames: ["request", "cancellation", "timeout"], parameters: [workerRequestType, optional(cancellationType), optional(durationType)], requiredParameters: 1, result: promise(workerResponseType) }],
191
+ ["close", apiFunction([], [], promise(nullType))],
192
+ ]);
193
+ const workerTemplate = (identity, name) => ({
194
+ identity, name, parameterNames: ["Request", "Response"], parameterBounds: [null, null], fields: workerCallFields,
195
+ readonlyFields: new Set(["call", "close"]),
196
+ });
197
+ const workerErrorIdentities = new Map([
198
+ ["WorkerBackpressureError", "velar/worker#class:WorkerBackpressureError"],
199
+ ["WorkerCallError", "velar/worker#class:WorkerCallError"],
200
+ ["WorkerCrashedError", "velar/worker#class:WorkerCrashedError"],
201
+ ["WorkerClosedError", "velar/worker#class:WorkerClosedError"],
202
+ ]);
203
+ const coreModuleInterfaces = new Map([
204
+ ["velar/collections", moduleInterface(new Map([
205
+ ["range", apiIntrinsic("collections.range", ["start", "end", "step"], [numberType, numberType, numberType], listNumber, 1)],
206
+ ["enumerate", apiIntrinsic("collections.enumerate", ["values", "start"], [listAny, numberType], listAny, 1)],
207
+ ["zip", apiIntrinsic("collections.zip", ["left", "right"], [listAny, listAny], listAny)],
208
+ ["unique", apiIntrinsic("collections.unique", ["values"], [listAny], listAny)],
209
+ ["chunk", apiIntrinsic("collections.chunk", ["values", "size"], [listAny, numberType], listAny)],
210
+ ["flatten", apiIntrinsic("collections.flatten", ["values"], [listAny], listAny)],
211
+ ["compact", apiIntrinsic("collections.compact", ["values"], [listAny], listAny)],
212
+ ["reversed", apiIntrinsic("collections.reversed", ["values"], [listAny], listAny)],
213
+ ["take", apiIntrinsic("collections.take", ["values", "count"], [listAny, numberType], listAny)],
214
+ ["drop", apiIntrinsic("collections.drop", ["values", "count"], [listAny, numberType], listAny)],
215
+ ["first", apiIntrinsic("collections.first", ["values"], [listAny], anyType)],
216
+ ["last", apiIntrinsic("collections.last", ["values"], [listAny], anyType)],
217
+ ["find", apiIntrinsic("collections.find", ["values", "test"], [listAny, anyType], anyType)],
218
+ ["index", apiIntrinsic("collections.index", ["values", "value"], [listAny, anyType], optional(numberType))],
219
+ ["has", apiIntrinsic("collections.has", ["values", "value"], [listAny, anyType], boolType)],
220
+ ["count", apiIntrinsic("collections.count", ["values", "value"], [listAny, anyType], numberType)],
221
+ ["some", apiIntrinsic("collections.some", ["values", "test"], [listAny, anyType], boolType)],
222
+ ["every", apiIntrinsic("collections.every", ["values", "test"], [listAny, anyType], boolType)],
223
+ ["partition", apiIntrinsic("collections.partition", ["values", "test"], [listAny, anyType], anyType)],
224
+ ["groupBy", apiIntrinsic("collections.groupBy", ["values", "key"], [listAny, anyType], mapAny)],
225
+ ["keyBy", apiIntrinsic("collections.keyBy", ["values", "key"], [listAny, anyType], mapAny)],
226
+ ["countBy", apiIntrinsic("collections.countBy", ["values", "key"], [listAny, anyType], mapAny)],
227
+ ["sortBy", apiIntrinsic("collections.sortBy", ["values", "key", "descending"], [listAny, anyType, boolType], listAny, 2)],
228
+ ["minBy", apiIntrinsic("collections.minBy", ["values", "key"], [listAny, anyType], anyType)],
229
+ ["maxBy", apiIntrinsic("collections.maxBy", ["values", "key"], [listAny, anyType], anyType)],
230
+ ["sum", apiIntrinsic("collections.sum", ["values"], [listNumber], numberType)],
231
+ ["join", apiIntrinsic("collections.join", ["values", "separator"], [listString, stringType], stringType, 1)],
232
+ ["repeat", apiIntrinsic("collections.repeat", ["value", "count"], [anyType, numberType], listAny)],
233
+ ]))],
234
+ ["velar/text", moduleInterface(new Map([
235
+ ["trimStart", apiFunction(["value"], [stringType], stringType)],
236
+ ["trimEnd", apiFunction(["value"], [stringType], stringType)],
237
+ ["capitalize", apiFunction(["value"], [stringType], stringType)],
238
+ ["title", apiFunction(["value"], [stringType], stringType)],
239
+ ["lines", apiFunction(["value"], [stringType], listString)],
240
+ ["lineStarts", apiFunction(["value"], [stringType], listNumber)],
241
+ ["chunks", apiFunction(["value", "size"], [stringType, numberType], listString)],
242
+ ["words", apiFunction(["value"], [stringType], listString)],
243
+ ["slug", apiFunction(["value"], [stringType], stringType)],
244
+ ["normalize", apiFunction(["value", "form"], [stringType, stringType], stringType, 1)],
245
+ ["truncate", apiFunction(["value", "length", "suffix"], [stringType, numberType, stringType], stringType, 2)],
246
+ ["indent", apiFunction(["value", "prefix"], [stringType, stringType], stringType, 1)],
247
+ ["dedent", apiFunction(["value"], [stringType], stringType)],
248
+ ["normalizeWhitespace", apiFunction(["value"], [stringType], stringType)],
249
+ ["utf8Size", apiFunction(["value"], [stringType], numberType)],
250
+ ["escapeHtml", apiFunction(["value"], [stringType], stringType)],
251
+ ["codePoint", apiFunction(["value"], [stringType], optional(numberType))],
252
+ ["fromCodePoint", apiFunction(["value"], [numberType], stringType)],
253
+ ["matches", apiFunction(["value", "expression", "options"], [stringType, stringType, patternOptionsType], boolType, 2)],
254
+ ["findMatch", apiFunction(["value", "expression", "options"], [stringType, stringType, patternOptionsType], optional(textMatchType), 2)],
255
+ ["findMatches", apiFunction(["value", "expression", "options"], [stringType, stringType, patternOptionsType], textMatchArrayType, 2)],
256
+ ["replaceMatches", apiFunction(["value", "expression", "replacement", "options"], [stringType, stringType, stringType, patternOptionsType], stringType, 3)],
257
+ ["splitPattern", apiFunction(["value", "expression", "options"], [stringType, stringType, patternOptionsType], listString, 2)],
258
+ ]))],
259
+ ["velar/math", moduleInterface(new Map([
260
+ ["pi", numberType], ["e", numberType], ["tau", numberType], ["infinity", numberType],
261
+ // min and max are pure rest calls and therefore have no named rest value.
262
+ ["min", intrinsic("math.min", [numberType], numberType)],
263
+ ["max", intrinsic("math.max", [numberType], numberType)],
264
+ ["clamp", apiFunction(["value", "minimum", "maximum"], [numberType, numberType, numberType], numberType)],
265
+ ["sign", apiFunction(["value"], [numberType], numberType)],
266
+ ["trunc", apiFunction(["value"], [numberType], numberType)],
267
+ ["sqrt", apiFunction(["value"], [numberType], numberType)],
268
+ ["cbrt", apiFunction(["value"], [numberType], numberType)],
269
+ ["pow", apiFunction(["base", "exponent"], [numberType, numberType], numberType)],
270
+ ["exp", apiFunction(["value"], [numberType], numberType)],
271
+ ["log", apiFunction(["value", "base"], [numberType, numberType], numberType, 1)],
272
+ ["log2", apiFunction(["value"], [numberType], numberType)],
273
+ ["log10", apiFunction(["value"], [numberType], numberType)],
274
+ ["sin", apiFunction(["value"], [numberType], numberType)],
275
+ ["cos", apiFunction(["value"], [numberType], numberType)],
276
+ ["tan", apiFunction(["value"], [numberType], numberType)],
277
+ ["asin", apiFunction(["value"], [numberType], numberType)],
278
+ ["acos", apiFunction(["value"], [numberType], numberType)],
279
+ ["atan", apiFunction(["value"], [numberType], numberType)],
280
+ ["atan2", apiFunction(["y", "x"], [numberType, numberType], numberType)],
281
+ ["degrees", apiFunction(["radians"], [numberType], numberType)],
282
+ ["radians", apiFunction(["degrees"], [numberType], numberType)],
283
+ ["hypot", apiFunction(["x", "y"], [numberType, numberType], numberType)],
284
+ ["random", apiFunction([], [], numberType)],
285
+ // randomInt has one-bound and minimum/maximum positional forms.
286
+ ["randomInt", functionType([numberType, numberType], numberType, 1)],
287
+ ["gcd", apiFunction(["left", "right"], [numberType, numberType], numberType)],
288
+ ["lcm", apiFunction(["left", "right"], [numberType, numberType], numberType)],
289
+ ]))],
290
+ ["velar/binary", moduleInterface(new Map([
291
+ ["ByteOrder", { kind: "enumObject", name: "ByteOrder", identity: byteOrderIdentity, members: byteOrderMembers }],
292
+ ["Bytes", { kind: "typeObject", name: "Bytes", value: bytesType }],
293
+ ["UInt8Buffer", { kind: "typeObject", name: "UInt8Buffer", value: uint8BufferType }],
294
+ ["UInt16Buffer", { kind: "typeObject", name: "UInt16Buffer", value: uint16BufferType }],
295
+ ["UInt32Buffer", { kind: "typeObject", name: "UInt32Buffer", value: uint32BufferType }],
296
+ ["Float32Buffer", { kind: "typeObject", name: "Float32Buffer", value: float32BufferType }],
297
+ ["UInt32Builder", { kind: "typeObject", name: "UInt32Builder", value: uint32BuilderType }],
298
+ ["Float32Builder", { kind: "typeObject", name: "Float32Builder", value: float32BuilderType }],
299
+ ["uint8Buffer", apiFunction(["size"], [numberType], uint8BufferType)],
300
+ ["uint16Buffer", apiFunction(["size"], [numberType], uint16BufferType)],
301
+ ["uint32Buffer", apiFunction(["size"], [numberType], uint32BufferType)],
302
+ ["float32Buffer", apiFunction(["size"], [numberType], float32BufferType)],
303
+ ["uint8FromBytes", apiFunction(["snapshot"], [bytesType], uint8BufferType)],
304
+ ["uint16FromBytes", apiFunction(["snapshot", "order"], [bytesType, byteOrderType], uint16BufferType)],
305
+ ["uint32FromBytes", apiFunction(["snapshot", "order"], [bytesType, byteOrderType], uint32BufferType)],
306
+ ["float32FromBytes", apiFunction(["snapshot", "order"], [bytesType, byteOrderType], float32BufferType)],
307
+ ["uint32Builder", apiFunction(["maxElements"], [numberType], uint32BuilderType)],
308
+ ["float32Builder", apiFunction(["maxElements"], [numberType], float32BuilderType)],
309
+ ]), new Map(), binaryNamedTypes, new Map(), binaryReadonlyFields, new Map([
310
+ ["Bytes", VELAR_BYTES_TYPE_IDENTITY],
311
+ ["UInt8Buffer", VELAR_UINT8_BUFFER_TYPE_IDENTITY],
312
+ ["UInt16Buffer", VELAR_UINT16_BUFFER_TYPE_IDENTITY],
313
+ ["UInt32Buffer", VELAR_UINT32_BUFFER_TYPE_IDENTITY],
314
+ ["Float32Buffer", VELAR_FLOAT32_BUFFER_TYPE_IDENTITY],
315
+ ["UInt32Builder", "velar/binary#type:UInt32Builder"],
316
+ ["Float32Builder", "velar/binary#type:Float32Builder"],
317
+ ]), new Map([["ByteOrder", { identity: byteOrderIdentity, members: byteOrderMembers }]]))],
318
+ ["velar/random", moduleInterface(new Map([
319
+ ["Random", { kind: "typeObject", name: "Random", value: randomType }],
320
+ ["random", apiFunction(["seed"], [randomSeedType], randomType)],
321
+ ]), new Map(), randomNamedTypes, new Map(), randomReadonlyFields, new Map([["Random", randomIdentity]]))],
322
+ ["velar/task", moduleInterface(new Map([
323
+ ["Cancellation", { kind: "typeObject", name: "Cancellation", value: cancellationType }],
324
+ ["Task", { kind: "typeObject", name: "Task" }],
325
+ ["CancellationError", { kind: "classConstructor", name: "CancellationError", identity: cancellationErrorIdentity }],
326
+ ["TaskTimeoutError", { kind: "classConstructor", name: "TaskTimeoutError", identity: taskTimeoutErrorIdentity }],
327
+ ["task", { kind: "function", typeParameterNames: ["T"], parameterNames: ["work", "parent"], parameters: [
328
+ { kind: "function", parameterNames: ["cancellation"], parameters: [cancellationType], requiredParameters: 1, result: promise(taskElementType) },
329
+ optional(cancellationType),
330
+ ], requiredParameters: 1, result: taskOf(taskElementType) }],
331
+ ["withTimeout", { kind: "function", typeParameterNames: ["T"], parameterNames: ["source", "duration"], parameters: [taskOf(taskElementType), durationType], requiredParameters: 2, result: promise(taskElementType) }],
332
+ ]), new Map([
333
+ ["CancellationError", taskErrorClass(cancellationErrorIdentity)],
334
+ ["TaskTimeoutError", taskErrorClass(taskTimeoutErrorIdentity)],
335
+ ]), new Map([["Cancellation", cancellationFields]]), new Map(), new Map([["Cancellation", new Set(["cancelled", "reason", "checkpoint"])]]), new Map([["Cancellation", cancellationIdentity]]), new Map(), new Map([["Task", taskTemplate], [taskIdentity, taskTemplate]]))],
336
+ ["velar/worker", moduleInterface(new Map([
337
+ ["Worker", { kind: "typeObject", name: "Worker" }],
338
+ ["WorkerPool", { kind: "typeObject", name: "WorkerPool" }],
339
+ ...[...workerErrorIdentities].map(([name, identity]) => [name, { kind: "classConstructor", name, identity }]),
340
+ ["worker", { kind: "function", typeParameterNames: ["Request", "Response"], parameterNames: ["name", "RequestType", "ResponseType", "capacity"], parameters: [stringType, { kind: "runtimeType", value: workerRequestType }, { kind: "runtimeType", value: workerResponseType }, numberType], requiredParameters: 3, result: workerApplication(workerIdentity, "Worker", workerRequestType, workerResponseType) }],
341
+ ["workerPool", { kind: "function", typeParameterNames: ["Request", "Response"], parameterNames: ["name", "RequestType", "ResponseType", "size", "capacity"], parameters: [stringType, { kind: "runtimeType", value: workerRequestType }, { kind: "runtimeType", value: workerResponseType }, numberType, numberType], requiredParameters: 4, result: workerApplication(workerPoolIdentity, "WorkerPool", workerRequestType, workerResponseType) }],
342
+ ["serveWorker", { kind: "function", typeParameterNames: ["Request", "Response"], parameterNames: ["RequestType", "ResponseType", "handler", "capacity"], parameters: [
343
+ { kind: "runtimeType", value: workerRequestType }, { kind: "runtimeType", value: workerResponseType },
344
+ { kind: "function", parameterNames: ["request", "cancellation"], parameters: [workerRequestType, cancellationType], requiredParameters: 2, result: promise(workerResponseType) }, numberType,
345
+ ], requiredParameters: 3, result: nullType }],
346
+ ]), new Map([...workerErrorIdentities].map(([name, identity]) => [name, taskErrorClass(identity)])), new Map(), new Map(), new Map(), new Map(), new Map(), new Map([
347
+ ["Worker", workerTemplate(workerIdentity, "Worker")], [workerIdentity, workerTemplate(workerIdentity, "Worker")],
348
+ ["WorkerPool", workerTemplate(workerPoolIdentity, "WorkerPool")], [workerPoolIdentity, workerTemplate(workerPoolIdentity, "WorkerPool")],
349
+ ]))],
350
+ ["velar/json", moduleInterface(new Map([
351
+ ["parse", apiIntrinsic("json.parse", ["text", "target"], [stringType, anyType], unknownType, 1)],
352
+ ["tryParse", apiIntrinsic("json.tryParse", ["text", "target", "fallback"], [stringType, anyType, anyType], unknownType, 1)],
353
+ ["stringify", apiIntrinsic("json.stringify", ["value", "pretty"], [anyType, { kind: "union", members: [boolType, numberType] }], stringType, 1)],
354
+ ["stableStringify", apiIntrinsic("json.stableStringify", ["value", "pretty"], [anyType, { kind: "union", members: [boolType, numberType] }], stringType, 1)],
355
+ ["clone", apiIntrinsic("json.clone", ["value", "target"], [anyType, anyType], anyType, 1)],
356
+ ["isSerializable", apiFunction(["value"], [anyType], boolType)],
357
+ ]))],
358
+ ["velar/async", moduleInterface(new Map([
359
+ ["sleep", apiFunction(["duration"], [durationType], promise(nullType))],
360
+ ["all", apiIntrinsic("async.all", ["values"], [anyType], promise(anyType))],
361
+ ["race", apiIntrinsic("async.race", ["values"], [listAny], promise(anyType))],
362
+ ["timeout", apiIntrinsic("async.timeout", ["value", "duration", "message"], [promise(anyType), durationType, stringType], promise(anyType), 2)],
363
+ ["retry", apiIntrinsic("async.retry", ["task", "attempts", "delay"], [anyType, numberType, durationType], promise(anyType), 1)],
364
+ ["map", apiIntrinsic("async.map", ["values", "worker", "concurrency"], [listAny, anyType, numberType], promise(listAny), 2)],
365
+ ["series", apiIntrinsic("async.series", ["tasks"], [listAny], promise(listAny))],
366
+ ]))],
367
+ ["velar/url", moduleInterface(new Map([
368
+ ["parse", apiFunction(["value", "base"], [stringType, stringType], urlInfoType, 1)],
369
+ // join is a pure rest call, so its segments stay positional.
370
+ ["join", intrinsic("url.join", [stringType], stringType)],
371
+ ["query", apiFunction(["params"], [anyType], stringType)],
372
+ ["parseQuery", apiFunction(["value"], [stringType], { kind: "map", key: stringType, value: stringType })],
373
+ ["withQuery", apiFunction(["value", "params"], [stringType, anyType], stringType)],
374
+ ["withHash", apiFunction(["value", "hash"], [stringType, stringType], stringType)],
375
+ ["isExternal", apiFunction(["value", "base"], [stringType, stringType], boolType, 1)],
376
+ ["encode", apiFunction(["value"], [stringType], stringType)],
377
+ ["decode", apiFunction(["value"], [stringType], stringType)],
378
+ ["normalize", apiFunction(["value", "base"], [stringType, stringType], stringType, 1)],
379
+ ]))],
380
+ ["velar/time", moduleInterface(new Map([
381
+ ["now", apiFunction([], [], numberType)],
382
+ ["monotonic", apiFunction([], [], numberType)],
383
+ ["parse", apiFunction(["value"], [stringType], optional(numberType))],
384
+ ["iso", apiFunction(["value"], [numberType], stringType, 0)],
385
+ ["format", apiFunction(["value", "locale", "timeZone"], [numberType, stringType, stringType], stringType, 1)],
386
+ ["date", apiFunction(["year", "month", "day", "hour", "minute", "second"], [numberType, numberType, numberType, numberType, numberType, numberType], numberType, 3)],
387
+ ["utc", apiFunction(["year", "month", "day", "hour", "minute", "second"], [numberType, numberType, numberType, numberType, numberType, numberType], numberType, 3)],
388
+ ["parts", apiFunction(["value", "timeZone"], [numberType, stringType], timePartsType, 1)],
389
+ ]))],
390
+ ["velar/id", moduleInterface(new Map([
391
+ ["uuid", apiFunction([], [], stringType)],
392
+ ["isUuid", apiFunction(["value"], [stringType], boolType)],
393
+ ]))],
394
+ ["velar/log", moduleInterface(new Map([
395
+ ["LogRecord", { kind: "typeObject", name: "LogRecord" }],
396
+ ["log", loggerType],
397
+ ["logger", apiFunction(["scope", "fields"], [stringType, logFieldsType], loggerType, 1)],
398
+ ["level", apiFunction([], [], stringType)],
399
+ ["setLevel", apiFunction(["value"], [stringType], nullType)],
400
+ ["useSink", apiFunction(["sink"], [functionType([logRecordType], unknownType)], cleanupType)],
401
+ ]), new Map(), new Map(), new Map([["LogRecord", logRecordType]]))],
402
+ ["velar/test", moduleInterface(new Map([
403
+ ["expect", apiIntrinsic("test.expect", ["actual"], [anyType], anyType)],
404
+ ]))],
405
+ ]);
406
+ function moduleInterface(exports, classes = new Map(), namedTypes = new Map(), typeAliases = new Map(), namedTypeReadonlyFields = new Map(), namedTypeIdentities = new Map(), enums = new Map(), genericTypes = new Map()) {
407
+ return { exports, mutableExports: new Set(), reactiveExports: new Map(), reExports: new Map(), namedTypes, namedTypeReadonlyFields, namedTypeIdentities, genericTypes, typeAliases, enums, classes, tests: [], extensionExports: new Map(), extensionData: new Map() };
408
+ }
409
+ export function standardModuleInterfaces(extensions = []) {
410
+ const activeExtensions = standardExtensions(extensions);
411
+ return new Map([
412
+ ...coreModuleInterfaces,
413
+ ...combinedExtensionModules(activeExtensions, "interfaces"),
414
+ ]);
415
+ }
416
+ export function isStandardModule(source, extensions = []) {
417
+ return standardModuleInterface(source, extensions) !== null;
418
+ }
419
+ export function standardModuleInterface(source, extensions = []) {
420
+ for (const extension of standardExtensions(extensions)) {
421
+ const interface_ = extension.modules?.interfaces.get(source);
422
+ if (interface_)
423
+ return interface_;
424
+ }
425
+ return coreModuleInterfaces.get(source) ?? null;
426
+ }
427
+ /**
428
+ * The two Core comparisons, reached for rather than restated (D50 rule 97.2,
429
+ * D59 rule 141): `__velarEquals` is what `equals(a, b)` calls, and
430
+ * `__velarSameValueZero` is what `==` lowers to.
431
+ */
432
+ const collectionLoweringImport = `import { __velarEquals, __velarSameValueZero } from "${VELAR_COLLECTION_LOWERING_MODULE}";`;
433
+ // Structure walkers shared by the assertion reporter. Value and content
434
+ // comparison are both deliberately absent: D50 rule 97.2 makes `toEqual` call
435
+ // the language's own `equals` and D59 rule 141 makes `toBe` call the language's
436
+ // own `==`, so no second comparison implementation can exist here to disagree
437
+ // with either.
438
+ const testDisplayRuntime = String.raw `
439
+ const __velarDeepNativeArray = globalThis.Array;
440
+ const __velarDeepNativeMap = globalThis.Map;
441
+ const __velarDeepNativeSet = globalThis.Set;
442
+ const __velarDeepNativeWeakSet = globalThis.WeakSet;
443
+ const __velarDeepNativeObject = globalThis.Object;
444
+ const __velarDeepGetOwnPropertyDescriptor = __velarDeepNativeObject.getOwnPropertyDescriptor;
445
+ const __velarDeepGetOwnPropertyNames = __velarDeepNativeObject.getOwnPropertyNames;
446
+ const __velarDeepGetOwnPropertySymbols = __velarDeepNativeObject.getOwnPropertySymbols;
447
+ const __velarDeepGetPrototypeOf = __velarDeepNativeObject.getPrototypeOf;
448
+ const __velarDeepObjectPrototype = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeObject, "prototype")?.value;
449
+ const __velarDeepArrayIsArray = __velarDeepNativeArray.isArray;
450
+ const __velarDeepApply = __velarDeepGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
451
+ const __velarDeepArrayPrototype = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeArray, "prototype")?.value;
452
+ const __velarDeepMapPrototype = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeMap, "prototype")?.value;
453
+ const __velarDeepSetPrototype = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeSet, "prototype")?.value;
454
+ const __velarDeepWeakSetPrototype = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeWeakSet, "prototype")?.value;
455
+ const __velarDeepArraySort = __velarDeepGetOwnPropertyDescriptor(__velarDeepArrayPrototype, "sort")?.value;
456
+ const __velarDeepMapSize = __velarDeepGetOwnPropertyDescriptor(__velarDeepMapPrototype, "size")?.get;
457
+ const __velarDeepMapEntries = __velarDeepGetOwnPropertyDescriptor(__velarDeepMapPrototype, "entries")?.value;
458
+ const __velarDeepSetSize = __velarDeepGetOwnPropertyDescriptor(__velarDeepSetPrototype, "size")?.get;
459
+ const __velarDeepSetValues = __velarDeepGetOwnPropertyDescriptor(__velarDeepSetPrototype, "values")?.value;
460
+ const __velarDeepWeakSetHas = __velarDeepGetOwnPropertyDescriptor(__velarDeepWeakSetPrototype, "has")?.value;
461
+ const __velarDeepWeakSetAdd = __velarDeepGetOwnPropertyDescriptor(__velarDeepWeakSetPrototype, "add")?.value;
462
+ const __velarDeepWeakSetDelete = __velarDeepGetOwnPropertyDescriptor(__velarDeepWeakSetPrototype, "delete")?.value;
463
+ const __velarDeepMapIterator = __velarDeepApply(__velarDeepMapEntries, new __velarDeepNativeMap(), []);
464
+ const __velarDeepMapIteratorNext = __velarDeepGetOwnPropertyDescriptor(__velarDeepGetPrototypeOf(__velarDeepMapIterator), "next")?.value;
465
+ const __velarDeepSetIterator = __velarDeepApply(__velarDeepSetValues, new __velarDeepNativeSet(), []);
466
+ const __velarDeepSetIteratorNext = __velarDeepGetOwnPropertyDescriptor(__velarDeepGetPrototypeOf(__velarDeepSetIterator), "next")?.value;
467
+ function __velarDeepCall(operation, receiver, arguments_) { return __velarDeepApply(operation, receiver, arguments_); }
468
+ function __velarPlainRecord(value) { const prototype = __velarDeepGetPrototypeOf(value); return prototype === __velarDeepObjectPrototype || prototype === null; }
469
+ function __velarDenseList(value) {
470
+ if (!__velarDeepCall(__velarDeepArrayIsArray, __velarDeepNativeArray, [value]) || value.length > 1000000
471
+ || __velarDeepGetOwnPropertySymbols(value).length !== 0
472
+ || __velarDeepGetOwnPropertyNames(value).length !== value.length + 1) return false;
473
+ const lengthDescriptor = __velarDeepGetOwnPropertyDescriptor(value, "length");
474
+ if (!lengthDescriptor || !lengthDescriptor.writable || lengthDescriptor.enumerable
475
+ || lengthDescriptor.configurable || !("value" in lengthDescriptor)) return false;
476
+ for (let index = 0; index < value.length; index += 1) {
477
+ const descriptor = __velarDeepGetOwnPropertyDescriptor(value, index);
478
+ if (!descriptor?.enumerable || !descriptor.configurable || !descriptor.writable || !("value" in descriptor)) return false;
479
+ }
480
+ return true;
481
+ }
482
+ function __velarMapSize(value) { try { return __velarDeepCall(__velarDeepMapSize, value, []); } catch { return null; } }
483
+ function __velarSetSize(value) { try { return __velarDeepCall(__velarDeepSetSize, value, []); } catch { return null; } }
484
+ function __velarDataRecordKeys(value) {
485
+ if (!__velarPlainRecord(value) || __velarDeepGetOwnPropertySymbols(value).length > 0) return null;
486
+ const keys = __velarDeepGetOwnPropertyNames(value);
487
+ for (let index = 0; index < keys.length; index += 1) {
488
+ const descriptor = __velarDeepGetOwnPropertyDescriptor(value, keys[index]);
489
+ if (!descriptor?.enumerable || !("value" in descriptor)) return null;
490
+ }
491
+ __velarDeepCall(__velarDeepArraySort, keys, []);
492
+ return keys;
493
+ }
494
+ function __velarDeepIteratorValue(iterator, next) { const step = __velarDeepCall(next, iterator, []); const done = __velarDeepGetOwnPropertyDescriptor(step, "done"); if (!done || !("value" in done) || typeof done.value !== "boolean") return { invalid: true }; if (done.value) return null; const value = __velarDeepGetOwnPropertyDescriptor(step, "value"); return !value || !("value" in value) ? { invalid: true } : { invalid: false, value: value.value }; }
495
+ `.trimStart();
496
+ const listRuntime = String.raw `
497
+ const __velarMaxListItems = 1000000;
498
+ const __velarListArray = Array;
499
+ const __velarListArrayIsArray = Array.isArray;
500
+ const __velarListGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
501
+ const __velarListGetOwnPropertyNames = Object.getOwnPropertyNames;
502
+ const __velarListGetOwnPropertySymbols = Object.getOwnPropertySymbols;
503
+ const __velarListSymbolFor = Symbol.for;
504
+ const __velarListTypeError = TypeError;
505
+ const __velarListRangeError = RangeError;
506
+ function __velarListReactiveRuntime() {
507
+ const descriptor = __velarListGetOwnPropertyDescriptor(globalThis, __velarListSymbolFor(${JSON.stringify(VELAR_RUNTIME_REGISTRY_KEY)}));
508
+ const runtime = descriptor && "value" in descriptor ? descriptor.value : null;
509
+ return runtime && runtime.version === ${JSON.stringify(VELAR_RUNTIME_SCHEMA_VERSION)} && typeof runtime.toRaw === "function"
510
+ && typeof runtime.collectionRead === "function" ? runtime : null;
511
+ }
512
+ function __velarRequireList(value, name) {
513
+ const reactive = __velarListReactiveRuntime();
514
+ if (reactive) value = reactive.toRaw(value);
515
+ if (!__velarListArrayIsArray(value)) throw new __velarListTypeError(name + " requires a List");
516
+ if (value.length > __velarMaxListItems) throw new __velarListRangeError(name + " cannot exceed " + __velarMaxListItems + " items");
517
+ if (__velarListGetOwnPropertySymbols(value).length > 0
518
+ || __velarListGetOwnPropertyNames(value).length !== value.length + 1) {
519
+ throw new __velarListTypeError(name + " requires a dense List without extra fields");
520
+ }
521
+ const lengthDescriptor = __velarListGetOwnPropertyDescriptor(value, "length");
522
+ if (!lengthDescriptor || !lengthDescriptor.writable || lengthDescriptor.enumerable
523
+ || lengthDescriptor.configurable || !("value" in lengthDescriptor)) {
524
+ throw new __velarListTypeError(name + " requires an ordinary mutable List length");
525
+ }
526
+ const output = new __velarListArray(value.length);
527
+ for (let index = 0; index < value.length; index += 1) {
528
+ const descriptor = __velarListGetOwnPropertyDescriptor(value, index);
529
+ if (!descriptor?.enumerable || !descriptor.configurable || !descriptor.writable || !("value" in descriptor)) {
530
+ throw new __velarListTypeError(name + " requires ordinary mutable List elements");
531
+ }
532
+ output[index] = reactive ? reactive.collectionRead(value, __velarListSymbolFor("velar.reactive.iterate.v1"), descriptor.value) : descriptor.value;
533
+ }
534
+ return output;
535
+ }
536
+ `.trimStart();
537
+ const runtimeTypeRuntime = VELAR_TYPE_REGISTRY_RUNTIME;
538
+ const coreModuleSources = new Map([
539
+ [VELAR_WORKER_MANIFEST_MODULE, "export const workerEntries = Object.freeze({});\n"],
540
+ [VELAR_CLASS_FIELD_MODULE, VELAR_CLASS_FIELD_MODULE_SOURCE],
541
+ [VELAR_COLLECTION_HOST_MODULE, VELAR_COLLECTION_HOST_MODULE_SOURCE],
542
+ [VELAR_COLLECTION_LOWERING_MODULE, VELAR_COLLECTION_LOWERING_MODULE_SOURCE],
543
+ [VELAR_ERROR_NORMALIZATION_MODULE, VELAR_ERROR_NORMALIZATION_MODULE_SOURCE],
544
+ [VELAR_NARROWING_MODULE, VELAR_NARROWING_MODULE_SOURCE],
545
+ [VELAR_PRIMITIVE_METHOD_MODULE, VELAR_PRIMITIVE_METHOD_MODULE_SOURCE],
546
+ [VELAR_PROMISE_NORMALIZATION_MODULE, VELAR_PROMISE_NORMALIZATION_MODULE_SOURCE],
547
+ [VELAR_REACTIVE_BRIDGE_MODULE, VELAR_NON_REACTIVE_BRIDGE_MODULE_SOURCE],
548
+ [VELAR_TYPE_VALIDATION_MODULE, VELAR_TYPE_VALIDATION_MODULE_SOURCE],
549
+ ["velar/collections", String.raw `
550
+ ${listRuntime}
551
+ const maxCollectionTextCodeUnits = 16 * 1024 * 1024;
552
+ const __velarCollectionsNativeArray = globalThis.Array;
553
+ const __velarCollectionsNativeMap = globalThis.Map;
554
+ const __velarCollectionsNativeSet = globalThis.Set;
555
+ const __velarCollectionsNativeObject = globalThis.Object;
556
+ const __velarCollectionsNativeNumber = globalThis.Number;
557
+ const __velarCollectionsNativeMath = globalThis.Math;
558
+ const __velarCollectionsNativeTypeError = globalThis.TypeError;
559
+ const __velarCollectionsNativeRangeError = globalThis.RangeError;
560
+ const __velarCollectionsGetOwnPropertyDescriptor = __velarCollectionsNativeObject.getOwnPropertyDescriptor;
561
+ const __velarCollectionsApply = __velarCollectionsGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
562
+ const __velarCollectionsArrayPrototype = __velarCollectionsGetOwnPropertyDescriptor(__velarCollectionsNativeArray, "prototype")?.value;
563
+ const __velarCollectionsMapPrototype = __velarCollectionsGetOwnPropertyDescriptor(__velarCollectionsNativeMap, "prototype")?.value;
564
+ const __velarCollectionsSetPrototype = __velarCollectionsGetOwnPropertyDescriptor(__velarCollectionsNativeSet, "prototype")?.value;
565
+ function __velarCollectionsHostOperation(owner, key) { const descriptor = __velarCollectionsGetOwnPropertyDescriptor(owner, key); if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "function") throw new __velarCollectionsNativeTypeError("The JavaScript " + key + " collection API is unavailable"); return descriptor.value; }
566
+ const __velarCollectionsArrayJoin = __velarCollectionsHostOperation(__velarCollectionsArrayPrototype, "join");
567
+ const __velarCollectionsArraySort = __velarCollectionsHostOperation(__velarCollectionsArrayPrototype, "sort");
568
+ const __velarCollectionsMapGet = __velarCollectionsHostOperation(__velarCollectionsMapPrototype, "get");
569
+ const __velarCollectionsMapSet = __velarCollectionsHostOperation(__velarCollectionsMapPrototype, "set");
570
+ const __velarCollectionsSetHas = __velarCollectionsHostOperation(__velarCollectionsSetPrototype, "has");
571
+ const __velarCollectionsSetAdd = __velarCollectionsHostOperation(__velarCollectionsSetPrototype, "add");
572
+ const __velarCollectionsObjectDefineProperty = __velarCollectionsHostOperation(__velarCollectionsNativeObject, "defineProperty");
573
+ const __velarCollectionsObjectFreeze = __velarCollectionsHostOperation(__velarCollectionsNativeObject, "freeze");
574
+ const __velarCollectionsObjectIs = __velarCollectionsHostOperation(__velarCollectionsNativeObject, "is");
575
+ const __velarCollectionsNumberIsFinite = __velarCollectionsHostOperation(__velarCollectionsNativeNumber, "isFinite");
576
+ const __velarCollectionsNumberIsNaN = __velarCollectionsHostOperation(__velarCollectionsNativeNumber, "isNaN");
577
+ const __velarCollectionsNumberIsSafeInteger = __velarCollectionsHostOperation(__velarCollectionsNativeNumber, "isSafeInteger");
578
+ const __velarCollectionsMathMin = __velarCollectionsHostOperation(__velarCollectionsNativeMath, "min");
579
+ const __velarCollectionsMathMax = __velarCollectionsHostOperation(__velarCollectionsNativeMath, "max");
580
+ const __velarCollectionsMathFloor = __velarCollectionsHostOperation(__velarCollectionsNativeMath, "floor");
581
+ if (typeof __velarCollectionsApply !== "function") throw new __velarCollectionsNativeTypeError("The JavaScript Reflect.apply collection API is unavailable");
582
+ function __velarCollectionsCall(operation, receiver, arguments_) { return __velarCollectionsApply(operation, receiver, arguments_); }
583
+ function __velarCollectionsFreeze(value) { return __velarCollectionsCall(__velarCollectionsObjectFreeze, __velarCollectionsNativeObject, [value]); }
584
+ function __velarCollectionsSame(left, right) { return left === right || __velarCollectionsCall(__velarCollectionsObjectIs, __velarCollectionsNativeObject, [left, right]); }
585
+ // TXT-D1: string keys order by code point (= UTF-8 binary order), matching
586
+ // every other ordered surface. Surrogate-free operands keep the native path.
587
+ const __velarCollectionsNativeString = globalThis.String;
588
+ const __velarCollectionsStringPrototype = __velarCollectionsGetOwnPropertyDescriptor(__velarCollectionsNativeString, "prototype")?.value;
589
+ const __velarCollectionsCharCodeAt = __velarCollectionsHostOperation(__velarCollectionsStringPrototype, "charCodeAt");
590
+ const __velarCollectionsSurrogatePattern = /[\uD800-\uDFFF]/;
591
+ const __velarCollectionsRegExpPrototype = __velarCollectionsHostOperation(__velarCollectionsNativeObject, "getPrototypeOf")(__velarCollectionsSurrogatePattern);
592
+ const __velarCollectionsSurrogateExec = __velarCollectionsHostOperation(__velarCollectionsRegExpPrototype, "exec");
593
+ function __velarCollectionsCharCode(value, index) { return __velarCollectionsCall(__velarCollectionsCharCodeAt, value, [index]); }
594
+ function __velarCollectionsHasSurrogate(value) { return __velarCollectionsCall(__velarCollectionsSurrogateExec, __velarCollectionsSurrogatePattern, [value]) !== null; }
595
+ function __velarCollectionsCodePointCompare(left, right) {
596
+ if (left === right) return 0;
597
+ if (!__velarCollectionsHasSurrogate(left) && !__velarCollectionsHasSurrogate(right)) return left < right ? -1 : 1;
598
+ let leftOffset = 0;
599
+ let rightOffset = 0;
600
+ while (leftOffset < left.length && rightOffset < right.length) {
601
+ let first = __velarCollectionsCharCode(left, leftOffset);
602
+ let firstUnits = 1;
603
+ if (first >= 0xD800 && first <= 0xDBFF && leftOffset + 1 < left.length) {
604
+ const trail = __velarCollectionsCharCode(left, leftOffset + 1);
605
+ if (trail >= 0xDC00 && trail <= 0xDFFF) { first = (first - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; firstUnits = 2; }
606
+ }
607
+ let second = __velarCollectionsCharCode(right, rightOffset);
608
+ let secondUnits = 1;
609
+ if (second >= 0xD800 && second <= 0xDBFF && rightOffset + 1 < right.length) {
610
+ const trail = __velarCollectionsCharCode(right, rightOffset + 1);
611
+ if (trail >= 0xDC00 && trail <= 0xDFFF) { second = (second - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; secondUnits = 2; }
612
+ }
613
+ if (first !== second) return first < second ? -1 : 1;
614
+ leftOffset += firstUnits;
615
+ rightOffset += secondUnits;
616
+ }
617
+ return leftOffset < left.length ? 1 : rightOffset < right.length ? -1 : 0;
618
+ }
619
+ function __velarCollectionsOrderedCompare(kind, left, right) {
620
+ if (kind === "string") return __velarCollectionsCodePointCompare(left, right);
621
+ return left < right ? -1 : left > right ? 1 : 0;
622
+ }
623
+ function requireList(value, name) {
624
+ return __velarRequireList(value, name);
625
+ }
626
+
627
+ function requireCount(value, name, positive = false) {
628
+ if (!__velarCollectionsCall(__velarCollectionsNumberIsSafeInteger, __velarCollectionsNativeNumber, [value]) || (positive ? value <= 0 : value < 0)) {
629
+ throw new __velarCollectionsNativeRangeError(name + " requires " + (positive ? "a positive" : "a non-negative") + " integer");
630
+ }
631
+ return value;
632
+ }
633
+
634
+ function requireCallback(value, name) {
635
+ if (typeof value !== "function") throw new __velarCollectionsNativeTypeError(name + " requires a function");
636
+ return value;
637
+ }
638
+
639
+ function predicate(callback, value, name) {
640
+ const result = requireCallback(callback, name)(value);
641
+ if (typeof result !== "boolean") throw new __velarCollectionsNativeTypeError(name + " predicate must return bool");
642
+ return result;
643
+ }
644
+
645
+ function comparable(value, name, expected = null) {
646
+ const type = typeof value;
647
+ if ((type !== "string" && type !== "number") || (type === "number" && __velarCollectionsCall(__velarCollectionsNumberIsNaN, __velarCollectionsNativeNumber, [value]))) {
648
+ throw new __velarCollectionsNativeTypeError(name + " key must be a string or non-NaN number");
649
+ }
650
+ if (expected !== null && type !== expected) throw new __velarCollectionsNativeTypeError(name + " keys must all have the same type");
651
+ return type;
652
+ }
653
+
654
+ export function range(start, stop = null, step = 1) {
655
+ if (stop === null) { stop = start; start = 0; }
656
+ if (!__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [start]) || !__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [stop]) || !__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [step]) || step === 0) throw new __velarCollectionsNativeRangeError("range requires finite numbers and a non-zero step");
657
+ const output = new __velarCollectionsNativeArray();
658
+ if (step > 0) for (let value = start; value < stop;) {
659
+ if (output.length >= __velarMaxListItems) throw new __velarCollectionsNativeRangeError("range cannot produce more than " + __velarMaxListItems + " items");
660
+ output[output.length] = value; const next = value + step;
661
+ if (next === value) throw new __velarCollectionsNativeRangeError("range step is too small to advance at this magnitude");
662
+ value = next;
663
+ } else for (let value = start; value > stop;) {
664
+ if (output.length >= __velarMaxListItems) throw new __velarCollectionsNativeRangeError("range cannot produce more than " + __velarMaxListItems + " items");
665
+ output[output.length] = value; const next = value + step;
666
+ if (next === value) throw new __velarCollectionsNativeRangeError("range step is too small to advance at this magnitude");
667
+ value = next;
668
+ }
669
+ return output;
670
+ }
671
+
672
+ // Compiler-only entry point for a direct counted range loop. Validation
673
+ // deliberately completes before the loop body starts, matching range()'s
674
+ // eager errors without allocating the produced List.
675
+ function __velarCountedRange(start, stop = null, step = 1) {
676
+ if (stop === null) { stop = start; start = 0; }
677
+ if (!__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [start]) || !__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [stop]) || !__velarCollectionsCall(__velarCollectionsNumberIsFinite, __velarCollectionsNativeNumber, [step]) || step === 0) throw new __velarCollectionsNativeRangeError("range requires finite numbers and a non-zero step");
678
+ let count = 0;
679
+ if (step > 0) for (let value = start; value < stop;) {
680
+ if (count >= __velarMaxListItems) throw new __velarCollectionsNativeRangeError("range cannot produce more than " + __velarMaxListItems + " items");
681
+ count += 1; const next = value + step;
682
+ if (next === value) throw new __velarCollectionsNativeRangeError("range step is too small to advance at this magnitude");
683
+ value = next;
684
+ } else for (let value = start; value > stop;) {
685
+ if (count >= __velarMaxListItems) throw new __velarCollectionsNativeRangeError("range cannot produce more than " + __velarMaxListItems + " items");
686
+ count += 1; const next = value + step;
687
+ if (next === value) throw new __velarCollectionsNativeRangeError("range step is too small to advance at this magnitude");
688
+ value = next;
689
+ }
690
+ return __velarCollectionsFreeze([start, stop, step]);
691
+ }
692
+ __velarCollectionsCall(__velarCollectionsObjectDefineProperty, __velarCollectionsNativeObject, [range, "__velarCounted", {
693
+ value: __velarCountedRange,
694
+ enumerable: false,
695
+ configurable: false,
696
+ writable: false,
697
+ }]);
698
+
699
+ export function enumerate(values, start = 0) {
700
+ values = requireList(values, "enumerate");
701
+ if (!__velarCollectionsCall(__velarCollectionsNumberIsSafeInteger, __velarCollectionsNativeNumber, [start]) || (values.length > 0 && !__velarCollectionsCall(__velarCollectionsNumberIsSafeInteger, __velarCollectionsNativeNumber, [start + values.length - 1]))) throw new __velarCollectionsNativeRangeError("enumerate indexes must be safe integers");
702
+ const output = new __velarCollectionsNativeArray(values.length);
703
+ for (let index = 0; index < values.length; index += 1) output[index] = __velarCollectionsFreeze({ index: start + index, value: values[index] });
704
+ return output;
705
+ }
706
+
707
+ export function zip(left, right) {
708
+ left = requireList(left, "zip"); right = requireList(right, "zip");
709
+ const length = __velarCollectionsCall(__velarCollectionsMathMin, __velarCollectionsNativeMath, [left.length, right.length]);
710
+ const output = new __velarCollectionsNativeArray(length);
711
+ for (let index = 0; index < length; index += 1) output[index] = __velarCollectionsFreeze({ first: left[index], second: right[index] });
712
+ return output;
713
+ }
714
+
715
+ export function unique(values) { values = requireList(values, "unique"); const seen = new __velarCollectionsNativeSet(); const output = new __velarCollectionsNativeArray(); for (let index = 0; index < values.length; index += 1) { const value = values[index]; if (__velarCollectionsCall(__velarCollectionsSetHas, seen, [value])) continue; __velarCollectionsCall(__velarCollectionsSetAdd, seen, [value]); output[output.length] = value; } return output; }
716
+
717
+ export function chunk(values, size) {
718
+ values = requireList(values, "chunk"); requireCount(size, "chunk size", true);
719
+ const output = new __velarCollectionsNativeArray();
720
+ for (let index = 0; index < values.length; index += size) { const length = __velarCollectionsCall(__velarCollectionsMathMin, __velarCollectionsNativeMath, [size, values.length - index]); const part = new __velarCollectionsNativeArray(length); for (let offset = 0; offset < length; offset += 1) part[offset] = values[index + offset]; output[output.length] = part; }
721
+ return output;
722
+ }
723
+
724
+ export function flatten(values) {
725
+ values = requireList(values, "flatten");
726
+ const output = new __velarCollectionsNativeArray();
727
+ for (let outer = 0; outer < values.length; outer += 1) {
728
+ const nested = requireList(values[outer], "flatten");
729
+ if (output.length + nested.length > __velarMaxListItems) throw new __velarCollectionsNativeRangeError("flatten cannot produce more than " + __velarMaxListItems + " items");
730
+ for (let inner = 0; inner < nested.length; inner += 1) output[output.length] = nested[inner];
731
+ }
732
+ return output;
733
+ }
734
+
735
+ export function compact(values) { values = requireList(values, "compact"); const output = new __velarCollectionsNativeArray(); for (let index = 0; index < values.length; index += 1) if (values[index] != null) output[output.length] = values[index]; return output; }
736
+ export function reversed(values) { values = requireList(values, "reversed"); const output = new __velarCollectionsNativeArray(values.length); for (let index = 0; index < values.length; index += 1) output[index] = values[values.length - index - 1]; return output; }
737
+ export function take(values, count) { values = requireList(values, "take"); count = __velarCollectionsCall(__velarCollectionsMathMin, __velarCollectionsNativeMath, [values.length, requireCount(count, "take count")]); const output = new __velarCollectionsNativeArray(count); for (let index = 0; index < count; index += 1) output[index] = values[index]; return output; }
738
+ export function drop(values, count) { values = requireList(values, "drop"); count = __velarCollectionsCall(__velarCollectionsMathMin, __velarCollectionsNativeMath, [values.length, requireCount(count, "drop count")]); const output = new __velarCollectionsNativeArray(values.length - count); for (let index = count; index < values.length; index += 1) output[index - count] = values[index]; return output; }
739
+ export function first(values) { values = requireList(values, "first"); return values.length ? values[0] : null; }
740
+ export function last(values) { values = requireList(values, "last"); return values.length ? values[values.length - 1] : null; }
741
+ export function find(values, callback) { values = requireList(values, "find"); for (let index = 0; index < values.length; index += 1) if (predicate(callback, values[index], "find")) return values[index]; return null; }
742
+ export function index(values, item) { values = requireList(values, "index"); for (let index = 0; index < values.length; index += 1) if (__velarCollectionsSame(values[index], item)) return index; return null; }
743
+ export function has(values, value) { return index(values, value) !== null; }
744
+ export function count(values, value) { values = requireList(values, "count"); let total = 0; for (let index = 0; index < values.length; index += 1) if (__velarCollectionsSame(values[index], value)) total += 1; return total; }
745
+ export function some(values, callback) { values = requireList(values, "some"); for (let index = 0; index < values.length; index += 1) if (predicate(callback, values[index], "some")) return true; return false; }
746
+ export function every(values, callback) { values = requireList(values, "every"); for (let index = 0; index < values.length; index += 1) if (!predicate(callback, values[index], "every")) return false; return true; }
747
+
748
+ export function partition(values, callback) {
749
+ values = requireList(values, "partition");
750
+ const matches = new __velarCollectionsNativeArray(), rest = new __velarCollectionsNativeArray();
751
+ for (let index = 0; index < values.length; index += 1) { const output = predicate(callback, values[index], "partition") ? matches : rest; output[output.length] = values[index]; }
752
+ return __velarCollectionsFreeze({ matches, rest });
753
+ }
754
+
755
+ export function groupBy(values, key) {
756
+ values = requireList(values, "groupBy");
757
+ requireCallback(key, "groupBy");
758
+ const output = new __velarCollectionsNativeMap();
759
+ for (let index = 0; index < values.length; index += 1) {
760
+ const value = values[index], name = key(value) ?? null;
761
+ const group = __velarCollectionsCall(__velarCollectionsMapGet, output, [name]);
762
+ if (group) group[group.length] = value; else __velarCollectionsCall(__velarCollectionsMapSet, output, [name, [value]]);
763
+ }
764
+ return output;
765
+ }
766
+
767
+ export function keyBy(values, key) {
768
+ values = requireList(values, "keyBy");
769
+ requireCallback(key, "keyBy");
770
+ const output = new __velarCollectionsNativeMap();
771
+ for (let index = 0; index < values.length; index += 1) __velarCollectionsCall(__velarCollectionsMapSet, output, [key(values[index]) ?? null, values[index]]);
772
+ return output;
773
+ }
774
+
775
+ export function countBy(values, key) {
776
+ values = requireList(values, "countBy");
777
+ requireCallback(key, "countBy");
778
+ const output = new __velarCollectionsNativeMap();
779
+ for (let index = 0; index < values.length; index += 1) { const name = key(values[index]) ?? null; __velarCollectionsCall(__velarCollectionsMapSet, output, [name, (__velarCollectionsCall(__velarCollectionsMapGet, output, [name]) || 0) + 1]); }
780
+ return output;
781
+ }
782
+
783
+ export function sortBy(values, key, descending = false) {
784
+ values = requireList(values, "sortBy"); requireCallback(key, "sortBy");
785
+ if (typeof descending !== "boolean") throw new __velarCollectionsNativeTypeError("sortBy descending must be bool");
786
+ let keyType = null;
787
+ const decorated = new __velarCollectionsNativeArray(values.length);
788
+ for (let index = 0; index < values.length; index += 1) {
789
+ const value = values[index];
790
+ const result = key(value);
791
+ const type = comparable(result, "sortBy", keyType);
792
+ if (keyType === null) keyType = type;
793
+ decorated[index] = { value, index, key: result };
794
+ }
795
+ __velarCollectionsCall(__velarCollectionsArraySort, decorated, [(left, right) => {
796
+ const order = __velarCollectionsOrderedCompare(keyType, left.key, right.key);
797
+ return order === 0 ? left.index - right.index : descending ? -order : order;
798
+ }]);
799
+ const output = new __velarCollectionsNativeArray(decorated.length);
800
+ for (let index = 0; index < decorated.length; index += 1) output[index] = decorated[index].value;
801
+ return output;
802
+ }
803
+
804
+ function extremeBy(values, key, direction, name) {
805
+ values = requireList(values, name); requireCallback(key, name);
806
+ if (!values.length) return null;
807
+ let selected = values[0], selectedKey = key(selected), keyType = comparable(selectedKey, name);
808
+ for (let index = 1; index < values.length; index += 1) {
809
+ const candidate = key(values[index]);
810
+ comparable(candidate, name, keyType);
811
+ const order = __velarCollectionsOrderedCompare(keyType, candidate, selectedKey);
812
+ if ((direction < 0 && order < 0) || (direction > 0 && order > 0)) {
813
+ selected = values[index]; selectedKey = candidate;
814
+ }
815
+ }
816
+ return selected;
817
+ }
818
+
819
+ export function minBy(values, key) { return extremeBy(values, key, -1, "minBy"); }
820
+ export function maxBy(values, key) { return extremeBy(values, key, 1, "maxBy"); }
821
+ export function sum(values) { values = requireList(values, "sum"); let total = 0; for (let index = 0; index < values.length; index += 1) { if (typeof values[index] !== "number") throw new __velarCollectionsNativeTypeError("sum requires numbers"); total += values[index]; } return total; }
822
+ export function join(values, separator = "") {
823
+ if (typeof separator !== "string") throw new __velarCollectionsNativeTypeError("join separator must be a string");
824
+ values = requireList(values, "join");
825
+ let outputCodeUnits = 0;
826
+ for (let index = 0; index < values.length; index += 1) {
827
+ const value = values[index];
828
+ if (typeof value !== "string") throw new __velarCollectionsNativeTypeError("join requires strings");
829
+ if (value.length > maxCollectionTextCodeUnits - outputCodeUnits) {
830
+ throw new __velarCollectionsNativeRangeError("join output cannot exceed 16 MiB");
831
+ }
832
+ outputCodeUnits += value.length;
833
+ }
834
+ const separatorCount = __velarCollectionsCall(__velarCollectionsMathMax, __velarCollectionsNativeMath, [0, values.length - 1]);
835
+ if (separatorCount > 0
836
+ && separator.length > __velarCollectionsCall(__velarCollectionsMathFloor, __velarCollectionsNativeMath, [(maxCollectionTextCodeUnits - outputCodeUnits) / separatorCount])) {
837
+ throw new __velarCollectionsNativeRangeError("join output cannot exceed 16 MiB");
838
+ }
839
+ return __velarCollectionsCall(__velarCollectionsArrayJoin, values, [separator]);
840
+ }
841
+ export function repeat(value, count) { count = requireCount(count, "repeat count"); if (count > __velarMaxListItems) throw new __velarCollectionsNativeRangeError("repeat cannot produce more than " + __velarMaxListItems + " items"); const output = new __velarCollectionsNativeArray(count); for (let index = 0; index < count; index += 1) output[index] = value; return output; }
842
+ `.trimStart()],
843
+ ["velar/text", String.raw `
844
+ ${VELAR_TEXT_METHOD_RUNTIME}
845
+ ${VELAR_UTF8_RUNTIME}
846
+ const maxTextCodeUnits = __velarMaxTextCodeUnits;
847
+ const maxTextItems = __velarMaxTextItems;
848
+ const __velarTextGetOwnPropertyNames = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "getOwnPropertyNames")?.value;
849
+ const __velarTextGetOwnPropertySymbols = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "getOwnPropertySymbols")?.value;
850
+ const __velarTextGetPrototypeOf = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "getPrototypeOf")?.value;
851
+ const __velarTextObjectPrototype = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "prototype")?.value;
852
+ const __velarTextObjectCreate = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "create")?.value;
853
+ const __velarTextObjectFreeze = __velarTextGetOwnPropertyDescriptor(__velarTextNativeObject, "freeze")?.value;
854
+ const __velarTextArrayPrototype = __velarTextGetOwnPropertyDescriptor(__velarTextNativeArray, "prototype")?.value;
855
+ const __velarTextArrayJoin = __velarTextGetOwnPropertyDescriptor(__velarTextArrayPrototype, "join")?.value;
856
+ const __velarTextStringTrimStart = __velarTextGetOwnPropertyDescriptor(__velarTextStringPrototype, "trimStart")?.value;
857
+ const __velarTextStringTrimEnd = __velarTextGetOwnPropertyDescriptor(__velarTextStringPrototype, "trimEnd")?.value;
858
+ const __velarTextStringNormalize = __velarTextGetOwnPropertyDescriptor(__velarTextStringPrototype, "normalize")?.value;
859
+ const nativeRegExpPrototype = __velarTextGetPrototypeOf(/(?:)/u);
860
+ const NativeRegExp = __velarTextGetOwnPropertyDescriptor(nativeRegExpPrototype, "constructor")?.value;
861
+ const nativeRegExpExec = __velarTextGetOwnPropertyDescriptor(nativeRegExpPrototype, "exec")?.value;
862
+ const nativeStringReplaceAll = __velarNativeStringReplaceAll;
863
+ const __velarTextStringCodePointAt = __velarTextGetOwnPropertyDescriptor(__velarTextStringPrototype, "codePointAt")?.value;
864
+ const __velarTextStringFromCodePoint = __velarTextGetOwnPropertyDescriptor(__velarTextNativeString, "fromCodePoint")?.value;
865
+ const __velarTextTitleSeparators = /[_\-/]+/gu;
866
+ const __velarTextTitleWords = /(^|\s)([\p{L}\p{N}])/gu;
867
+ const __velarTextLines = /\r?\n/gu;
868
+ const __velarTextWords = /\s+/gu;
869
+ const __velarTextMarks = /\p{M}/gu;
870
+ const __velarTextSlugSeparators = /[^\p{L}\p{N}]+/gu;
871
+ const __velarTextSlugEdges = /^-+|-+$/gu;
872
+ const __velarTextWhitespace = /\s+/gu;
873
+ function __velarTextAppend(values, value) { values[values.length] = value; }
874
+ function __velarTextJoin(values, separator) { return __velarTextCall(__velarTextArrayJoin, values, [separator]); }
875
+ function __velarTextRegexReplace(value, pattern, replacement) {
876
+ pattern.lastIndex = 0;
877
+ const output = []; let end = 0, units = 0;
878
+ while (true) {
879
+ const raw = __velarTextCall(nativeRegExpExec, pattern, [value]);
880
+ if (raw === null) break;
881
+ const match = checkedMatchValue(raw, value);
882
+ const before = __velarTextCall(__velarNativeStringSlice, value, [end, match.unitIndex]);
883
+ const next = typeof replacement === "function" ? replacement(match) : replacement;
884
+ if (typeof next !== "string") throw new __velarTextNativeTypeError("Text replacement must produce a string");
885
+ units += before.length + next.length;
886
+ if (units > maxTextCodeUnits) throw new __velarTextNativeRangeError("Text replacement output cannot exceed 16 MiB");
887
+ __velarTextAppend(output, before); __velarTextAppend(output, next);
888
+ end = match.unitIndex + match.value.length;
889
+ if (match.value === "") pattern.lastIndex = nextTextIndex(value, pattern.lastIndex);
890
+ }
891
+ const tail = __velarTextCall(__velarNativeStringSlice, value, [end]);
892
+ if (units + tail.length > maxTextCodeUnits) throw new __velarTextNativeRangeError("Text replacement output cannot exceed 16 MiB");
893
+ __velarTextAppend(output, tail); pattern.lastIndex = 0;
894
+ return __velarTextJoin(output, "");
895
+ }
896
+ function __velarTextRegexSplit(value, pattern, limit) {
897
+ pattern.lastIndex = 0;
898
+ const output = []; let end = 0;
899
+ while (output.length + 1 < limit) {
900
+ const raw = __velarTextCall(nativeRegExpExec, pattern, [value]);
901
+ if (raw === null) break;
902
+ const match = checkedMatchValue(raw, value);
903
+ __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [end, match.unitIndex]));
904
+ end = match.unitIndex + match.value.length;
905
+ if (match.value === "") pattern.lastIndex = nextTextIndex(value, pattern.lastIndex);
906
+ }
907
+ if (output.length < limit) __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [end]));
908
+ pattern.lastIndex = 0;
909
+ return output;
910
+ }
911
+ function valueOf(value) { return __velarTextArgument(value, "velar/text value"); }
912
+ function textOutput(value, name) { return __velarTextOutput(value, name); }
913
+ function textCount(value, name) { return __velarTextCount(value, name); }
914
+ function textList(values, name) { return __velarTextList(values, name); }
915
+ function htmlOutputUnits(value) {
916
+ let units = value.length;
917
+ for (let index = 0; index < value.length; index += 1) {
918
+ const character = value[index];
919
+ if (character === "&" || character === "'") units += 4;
920
+ else if (character === "<" || character === ">") units += 3;
921
+ else if (character === '"') units += 5;
922
+ if (units > maxTextCodeUnits) return units;
923
+ }
924
+ return units;
925
+ }
926
+ const codePointLength = __velarTextCodePointLength;
927
+ const codePointPrefix = __velarTextCodePointPrefix;
928
+ function patternOptions(value) {
929
+ if (value == null) return {};
930
+ const prototype = typeof value === "object" && value !== null ? __velarTextGetPrototypeOf(value) : undefined;
931
+ if (typeof value !== "object" || value === null || __velarTextCall(__velarTextArrayIsArray, __velarTextNativeArray, [value]) || (prototype !== __velarTextObjectPrototype && prototype !== null)) throw new __velarTextNativeTypeError("text pattern options must be a record");
932
+ if (__velarTextGetOwnPropertySymbols(value).length > 0) throw new __velarTextNativeTypeError("text pattern options cannot contain symbol fields");
933
+ const output = __velarTextCall(__velarTextObjectCreate, __velarTextNativeObject, [null]);
934
+ const names = __velarTextGetOwnPropertyNames(value);
935
+ for (let index = 0; index < names.length; index += 1) {
936
+ const name = names[index];
937
+ const descriptor = __velarTextGetOwnPropertyDescriptor(value, name);
938
+ if (!descriptor?.enumerable || !("value" in descriptor)) throw new __velarTextNativeTypeError("Text pattern option '" + name + "' must be an enumerable data field");
939
+ if (name !== "ignoreCase" && name !== "multiline" && name !== "dotAll") throw new __velarTextNativeTypeError("Unknown text pattern option '" + name + "'");
940
+ const option = descriptor.value;
941
+ if (option != null && typeof option !== "boolean") throw new __velarTextNativeTypeError("Text pattern option '" + name + "' must be bool");
942
+ output[name] = option;
943
+ }
944
+ return output;
945
+ }
946
+ function patternOf(expression, options, global = false) {
947
+ expression = valueOf(expression); options = patternOptions(options);
948
+ if (expression.length > 4096) throw new __velarTextNativeRangeError("text patterns cannot exceed 4096 code units");
949
+ let flags = "u";
950
+ if (global) flags += "g";
951
+ if (options.ignoreCase === true) flags += "i";
952
+ if (options.multiline === true) flags += "m";
953
+ if (options.dotAll === true) flags += "s";
954
+ try { return new NativeRegExp(expression, flags); }
955
+ catch { throw new __velarTextNativeTypeError("Invalid text pattern"); }
956
+ }
957
+ function checkedMatchValue(match, input) {
958
+ if (!__velarTextCall(__velarTextArrayIsArray, __velarTextNativeArray, [match]) || match.length < 1 || match.length > 4097) throw new __velarTextNativeTypeError("The regular expression engine returned an invalid match");
959
+ const groups = new __velarTextNativeArray(match.length - 1);
960
+ for (let index = 0; index < match.length; index += 1) {
961
+ const descriptor = __velarTextGetOwnPropertyDescriptor(match, index);
962
+ if (!descriptor || !("value" in descriptor)) throw new __velarTextNativeTypeError("Regular expression matches must contain data values");
963
+ const value = descriptor.value;
964
+ if (value !== undefined && typeof value !== "string") throw new __velarTextNativeTypeError("Regular expression match values must be strings");
965
+ if (index === 0) {
966
+ if (typeof value !== "string") throw new __velarTextNativeTypeError("A regular expression match requires full text");
967
+ } else groups[index - 1] = value === undefined ? null : value;
968
+ }
969
+ const indexDescriptor = __velarTextGetOwnPropertyDescriptor(match, "index");
970
+ if (!indexDescriptor || !("value" in indexDescriptor) || !__velarTextCall(__velarTextNumberIsSafeInteger, __velarTextNativeNumber, [indexDescriptor.value]) || indexDescriptor.value < 0 || indexDescriptor.value > input.length) throw new __velarTextNativeTypeError("A regular expression match requires a valid index");
971
+ return { value: __velarTextGetOwnPropertyDescriptor(match, 0).value, groups, unitIndex: indexDescriptor.value };
972
+ }
973
+ function publicMatchValue(checked, input, index = null) {
974
+ if (index === null) index = __velarTextCodePointIndex(input, checked.unitIndex);
975
+ if (index === null) throw new __velarTextNativeTypeError("A regular expression match must begin at a Unicode code-point boundary");
976
+ return __velarTextCall(__velarTextObjectFreeze, __velarTextNativeObject, [{ value: checked.value, index, groups: checked.groups }]);
977
+ }
978
+ function nextTextIndex(value, index) {
979
+ return index >= value.length ? index + 1 : __velarTextNextCodePointOffset(value, index);
980
+ }
981
+ function eachMatch(value, pattern, visit) {
982
+ let count = 0, units = 0, previousUnitIndex = 0, previousCodePointIndex = 0;
983
+ while (true) {
984
+ const raw = __velarTextCall(nativeRegExpExec, pattern, [value]);
985
+ if (raw === null) return;
986
+ if (count >= maxTextItems) throw new __velarTextNativeRangeError("Text patterns cannot produce more than " + maxTextItems + " matches");
987
+ count += 1;
988
+ const checked = checkedMatchValue(raw, value);
989
+ const distance = __velarTextCodePointDistance(value, previousUnitIndex, checked.unitIndex);
990
+ if (distance === null) throw new __velarTextNativeTypeError("A regular expression match must begin at a Unicode code-point boundary");
991
+ const match = publicMatchValue(checked, value, previousCodePointIndex + distance);
992
+ previousUnitIndex = checked.unitIndex;
993
+ previousCodePointIndex = match.index;
994
+ units += match.value.length;
995
+ for (let index = 0; index < match.groups.length; index += 1) { const group = match.groups[index]; if (group !== null) units += group.length; }
996
+ if (units > maxTextCodeUnits) throw new __velarTextNativeRangeError("Text pattern results cannot exceed 16 MiB");
997
+ visit(match, checked.unitIndex);
998
+ if (match.value === "") pattern.lastIndex = nextTextIndex(value, pattern.lastIndex);
999
+ }
1000
+ }
1001
+ export function trimStart(value) { return __velarTextCall(__velarTextStringTrimStart, valueOf(value), []); }
1002
+ export function trimEnd(value) { return __velarTextCall(__velarTextStringTrimEnd, valueOf(value), []); }
1003
+ export function capitalize(value) { value = valueOf(value); if (!value) return ""; const end = __velarTextNextCodePointOffset(value, 0); const first = __velarTextCall(__velarNativeStringSlice, value, [0, end]); const tail = __velarTextCall(__velarNativeStringSlice, value, [end]); return textOutput(__velarTextCall(__velarNativeStringUpper, first, []) + __velarTextCall(__velarNativeStringLower, tail, []), "capitalize"); }
1004
+ export function title(value) { let output = __velarTextCall(__velarNativeStringLower, valueOf(value), []); output = __velarTextRegexReplace(output, __velarTextTitleSeparators, " "); output = __velarTextRegexReplace(output, __velarTextTitleWords, match => match.groups[0] + __velarTextCall(__velarNativeStringUpper, match.groups[1], [])); return textOutput(output, "title"); }
1005
+ export function lines(value) { return textList(__velarTextRegexSplit(valueOf(value), __velarTextLines, maxTextItems + 1), "lines"); }
1006
+ export function lineStarts(value) {
1007
+ value = valueOf(value);
1008
+ const output = [0];
1009
+ let unitOffset = 0, codePointOffset = 0;
1010
+ while (unitOffset < value.length) {
1011
+ const nextUnitOffset = __velarTextNextCodePointOffset(value, unitOffset);
1012
+ if (__velarTextCall(__velarNativeStringCharCodeAt, value, [unitOffset]) === 10) __velarTextAppend(output, codePointOffset + 1);
1013
+ unitOffset = nextUnitOffset;
1014
+ codePointOffset += 1;
1015
+ }
1016
+ return textList(output, "lineStarts");
1017
+ }
1018
+ export function chunks(value, size) {
1019
+ value = valueOf(value);
1020
+ size = textCount(size, "chunks size");
1021
+ if (size === 0) throw new __velarTextNativeRangeError("chunks size must be greater than zero");
1022
+ if (value.length === 0) return [];
1023
+ const output = [];
1024
+ let start = 0, offset = 0, count = 0;
1025
+ while (offset < value.length) {
1026
+ offset = __velarTextNextCodePointOffset(value, offset);
1027
+ count += 1;
1028
+ if (count === size) {
1029
+ if (output.length >= maxTextItems) throw new __velarTextNativeRangeError("chunks cannot produce more than " + maxTextItems + " items");
1030
+ __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [start, offset]));
1031
+ start = offset;
1032
+ count = 0;
1033
+ }
1034
+ }
1035
+ if (start < value.length) {
1036
+ if (output.length >= maxTextItems) throw new __velarTextNativeRangeError("chunks cannot produce more than " + maxTextItems + " items");
1037
+ __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [start]));
1038
+ }
1039
+ return textList(output, "chunks");
1040
+ }
1041
+ export function words(value) { const cleaned = __velarTextCall(__velarNativeStringTrim, valueOf(value), []); return cleaned ? textList(__velarTextRegexSplit(cleaned, __velarTextWords, maxTextItems + 1), "words") : []; }
1042
+ export function slug(value) { let output = __velarTextCall(__velarTextStringNormalize, valueOf(value), ["NFKD"]); output = __velarTextRegexReplace(output, __velarTextMarks, ""); output = __velarTextCall(__velarNativeStringLower, output, []); output = __velarTextCall(__velarNativeStringTrim, output, []); output = __velarTextRegexReplace(output, __velarTextSlugSeparators, "-"); output = __velarTextRegexReplace(output, __velarTextSlugEdges, ""); return textOutput(output, "slug"); }
1043
+ // TXT-U3: text equality is code-point-sequence identity, so "café" typed on a
1044
+ // keyboard (NFC) and the same name read back from a macOS filename (NFD) are
1045
+ // different values with different sizes. This is the boundary tool that makes
1046
+ // them one value; the four Unicode forms are the only accepted spellings.
1047
+ export function normalize(value, form = "NFC") {
1048
+ value = valueOf(value);
1049
+ form = valueOf(form);
1050
+ if (form !== "NFC" && form !== "NFD" && form !== "NFKC" && form !== "NFKD") {
1051
+ throw new __velarTextNativeRangeError("normalize form must be NFC, NFD, NFKC, or NFKD");
1052
+ }
1053
+ return textOutput(__velarTextCall(__velarTextStringNormalize, value, [form]), "normalize");
1054
+ }
1055
+ export function truncate(value, length, suffix = "…") { value = valueOf(value); suffix = valueOf(suffix); length = textCount(length, "truncate length"); const valueLength = codePointLength(value); if (valueLength <= length) return value; const suffixLength = codePointLength(suffix); if (suffixLength >= length) return codePointPrefix(suffix, length); return codePointPrefix(value, length - suffixLength) + suffix; }
1056
+ export function indent(value, prefix = " ") {
1057
+ const rows = lines(valueOf(value)); prefix = valueOf(prefix);
1058
+ let units = __velarTextCall(__velarTextMathMax, __velarTextNativeMath, [0, rows.length - 1]);
1059
+ const output = new __velarTextNativeArray(rows.length);
1060
+ for (let index = 0; index < rows.length; index += 1) {
1061
+ units += prefix.length + rows[index].length;
1062
+ if (units > maxTextCodeUnits) throw new __velarTextNativeRangeError("indent output cannot exceed 16 MiB");
1063
+ output[index] = prefix + rows[index];
1064
+ }
1065
+ return __velarTextJoin(output, "\n");
1066
+ }
1067
+ export function dedent(value) { const rows = lines(valueOf(value)); let width = null; for (let index = 0; index < rows.length; index += 1) { const line = rows[index]; if (__velarTextCall(__velarNativeStringTrim, line, [])) { let current = 0; while (current < line.length && (line[current] === " " || line[current] === "\t")) current += 1; width = width === null ? current : __velarTextCall(__velarTextMathMin, __velarTextNativeMath, [width, current]); } } const output = new __velarTextNativeArray(rows.length); for (let index = 0; index < rows.length; index += 1) output[index] = __velarTextCall(__velarNativeStringSlice, rows[index], [width ?? 0]); return __velarTextJoin(output, "\n"); }
1068
+ export function normalizeWhitespace(value) { return __velarTextRegexReplace(__velarTextCall(__velarNativeStringTrim, valueOf(value), []), __velarTextWhitespace, " "); }
1069
+ export function utf8Size(value) { return __velarUtf8ByteLength(valueOf(value)); }
1070
+ export function escapeHtml(value) {
1071
+ value = valueOf(value);
1072
+ if (htmlOutputUnits(value) > maxTextCodeUnits) throw new __velarTextNativeRangeError("escapeHtml output cannot exceed 16 MiB");
1073
+ const replacements = [["&", "&amp;"], ["<", "&lt;"], [">", "&gt;"], ['"', "&quot;"], ["'", "&#39;"]];
1074
+ for (let index = 0; index < replacements.length; index += 1) {
1075
+ const pair = replacements[index];
1076
+ value = __velarTextCall(nativeStringReplaceAll, value, [pair[0], pair[1]]);
1077
+ }
1078
+ return value;
1079
+ }
1080
+ // TXT-U4 (D50 rule 90 item 4): one character in, one code point out. Anything
1081
+ // that is not exactly one code point — empty text, several characters, or a
1082
+ // lone surrogate half — answers null rather than a partial reading, and the
1083
+ // inverse refuses to build a surrogate half that could never stand alone.
1084
+ export function codePoint(value) {
1085
+ value = valueOf(value);
1086
+ if (value.length === 0 || __velarTextNextCodePointOffset(value, 0) !== value.length) return null;
1087
+ const point = __velarTextCall(__velarTextStringCodePointAt, value, [0]);
1088
+ if (typeof point !== "number" || point >= 0xD800 && point <= 0xDFFF) return null;
1089
+ return point;
1090
+ }
1091
+ export function fromCodePoint(value) {
1092
+ if (!__velarTextCall(__velarTextNumberIsSafeInteger, __velarTextNativeNumber, [value]) || value < 0 || value > 0x10FFFF) {
1093
+ throw new __velarTextNativeRangeError("fromCodePoint requires a code point from 0 through 1114111");
1094
+ }
1095
+ if (value >= 0xD800 && value <= 0xDFFF) throw new __velarTextNativeRangeError("fromCodePoint refuses surrogate halves; they are not characters on their own");
1096
+ return __velarTextCall(__velarTextStringFromCodePoint, __velarTextNativeString, [value]);
1097
+ }
1098
+ export function matches(value, expression, options = {}) { value = valueOf(value); return __velarTextCall(nativeRegExpExec, patternOf(expression, options), [value]) !== null; }
1099
+ export function findMatch(value, expression, options = {}) { value = valueOf(value); const match = __velarTextCall(nativeRegExpExec, patternOf(expression, options), [value]); return match === null ? null : publicMatchValue(checkedMatchValue(match, value), value); }
1100
+ export function findMatches(value, expression, options = {}) { value = valueOf(value); const output = []; eachMatch(value, patternOf(expression, options, true), match => __velarTextAppend(output, match)); return output; }
1101
+ export function replaceMatches(value, expression, replacement, options = {}) {
1102
+ value = valueOf(value); replacement = valueOf(replacement);
1103
+ const output = []; let end = 0, units = 0;
1104
+ eachMatch(value, patternOf(expression, options, true), (match, unitIndex) => {
1105
+ const before = __velarTextCall(__velarNativeStringSlice, value, [end, unitIndex]);
1106
+ units += before.length + replacement.length;
1107
+ if (units > maxTextCodeUnits) throw new __velarTextNativeRangeError("replaceMatches output cannot exceed 16 MiB");
1108
+ __velarTextAppend(output, before); __velarTextAppend(output, replacement);
1109
+ end = unitIndex + match.value.length;
1110
+ });
1111
+ const tail = __velarTextCall(__velarNativeStringSlice, value, [end]);
1112
+ if (units + tail.length > maxTextCodeUnits) throw new __velarTextNativeRangeError("replaceMatches output cannot exceed 16 MiB");
1113
+ __velarTextAppend(output, tail);
1114
+ return __velarTextJoin(output, "");
1115
+ }
1116
+ export function splitPattern(value, expression, options = {}) {
1117
+ value = valueOf(value); const output = []; let end = 0;
1118
+ eachMatch(value, patternOf(expression, options, true), (match, unitIndex) => { if (output.length >= maxTextItems) throw new __velarTextNativeRangeError("splitPattern cannot produce more than " + maxTextItems + " items"); __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [end, unitIndex])); end = unitIndex + match.value.length; });
1119
+ __velarTextAppend(output, __velarTextCall(__velarNativeStringSlice, value, [end])); return output;
1120
+ }
1121
+ `.trimStart()],
1122
+ ["velar/math", String.raw `
1123
+ const __velarMathNativeMath = globalThis.Math;
1124
+ const __velarMathNativeNumber = globalThis.Number;
1125
+ const __velarMathNativeTypeError = globalThis.TypeError;
1126
+ const __velarMathNativeRangeError = globalThis.RangeError;
1127
+ const __velarMathGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
1128
+ const __velarMathApply = __velarMathGetOwnPropertyDescriptor(Reflect, "apply")?.value;
1129
+ function __velarMathHostData(owner, key, kind) {
1130
+ const descriptor = __velarMathGetOwnPropertyDescriptor(owner, key);
1131
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== kind) throw new __velarMathNativeTypeError("The JavaScript " + key + " math API is unavailable");
1132
+ return descriptor.value;
1133
+ }
1134
+ function __velarMathHostOperation(owner, key) { return __velarMathHostData(owner, key, "function"); }
1135
+ const __velarMathMin = __velarMathHostOperation(__velarMathNativeMath, "min");
1136
+ const __velarMathMax = __velarMathHostOperation(__velarMathNativeMath, "max");
1137
+ const __velarMathSign = __velarMathHostOperation(__velarMathNativeMath, "sign");
1138
+ const __velarMathTrunc = __velarMathHostOperation(__velarMathNativeMath, "trunc");
1139
+ const __velarMathSqrt = __velarMathHostOperation(__velarMathNativeMath, "sqrt");
1140
+ const __velarMathCbrt = __velarMathHostOperation(__velarMathNativeMath, "cbrt");
1141
+ const __velarMathPow = __velarMathHostOperation(__velarMathNativeMath, "pow");
1142
+ const __velarMathExp = __velarMathHostOperation(__velarMathNativeMath, "exp");
1143
+ const __velarMathLog = __velarMathHostOperation(__velarMathNativeMath, "log");
1144
+ const __velarMathLog2 = __velarMathHostOperation(__velarMathNativeMath, "log2");
1145
+ const __velarMathLog10 = __velarMathHostOperation(__velarMathNativeMath, "log10");
1146
+ const __velarMathSin = __velarMathHostOperation(__velarMathNativeMath, "sin");
1147
+ const __velarMathCos = __velarMathHostOperation(__velarMathNativeMath, "cos");
1148
+ const __velarMathTan = __velarMathHostOperation(__velarMathNativeMath, "tan");
1149
+ const __velarMathAsin = __velarMathHostOperation(__velarMathNativeMath, "asin");
1150
+ const __velarMathAcos = __velarMathHostOperation(__velarMathNativeMath, "acos");
1151
+ const __velarMathAtan = __velarMathHostOperation(__velarMathNativeMath, "atan");
1152
+ const __velarMathAtan2 = __velarMathHostOperation(__velarMathNativeMath, "atan2");
1153
+ const __velarMathHypot = __velarMathHostOperation(__velarMathNativeMath, "hypot");
1154
+ const __velarMathRandom = __velarMathHostOperation(__velarMathNativeMath, "random");
1155
+ const __velarMathFloor = __velarMathHostOperation(__velarMathNativeMath, "floor");
1156
+ const __velarMathAbs = __velarMathHostOperation(__velarMathNativeMath, "abs");
1157
+ const __velarMathNumberIsFinite = __velarMathHostOperation(__velarMathNativeNumber, "isFinite");
1158
+ const __velarMathNumberIsInteger = __velarMathHostOperation(__velarMathNativeNumber, "isInteger");
1159
+ const __velarMathNumberIsSafeInteger = __velarMathHostOperation(__velarMathNativeNumber, "isSafeInteger");
1160
+ if (typeof __velarMathApply !== "function") throw new __velarMathNativeTypeError("The JavaScript Reflect.apply math API is unavailable");
1161
+ function __velarMathCall(operation, arguments_) { return __velarMathApply(operation, undefined, arguments_); }
1162
+ function requireNumber(value, name) { if (typeof value !== "number") throw new __velarMathNativeTypeError(name + " requires numbers"); return value; }
1163
+ function unary(value, operation, name) { return __velarMathCall(operation, [requireNumber(value, name)]); }
1164
+ function binary(left, right, operation, name) { return __velarMathCall(operation, [requireNumber(left, name), requireNumber(right, name)]); }
1165
+ export const pi = __velarMathHostData(__velarMathNativeMath, "PI", "number");
1166
+ export const e = __velarMathHostData(__velarMathNativeMath, "E", "number");
1167
+ export const tau = pi * 2;
1168
+ export const infinity = __velarMathHostData(__velarMathNativeNumber, "POSITIVE_INFINITY", "number");
1169
+ export function min(...values) { if (!values.length) throw new __velarMathNativeRangeError("min requires at least one number"); let result = requireNumber(values[0], "min"); for (let index = 1; index < values.length; index += 1) result = __velarMathCall(__velarMathMin, [result, requireNumber(values[index], "min")]); return result; }
1170
+ export function max(...values) { if (!values.length) throw new __velarMathNativeRangeError("max requires at least one number"); let result = requireNumber(values[0], "max"); for (let index = 1; index < values.length; index += 1) result = __velarMathCall(__velarMathMax, [result, requireNumber(values[index], "max")]); return result; }
1171
+ export function clamp(value, minimum, maximum) { value = requireNumber(value, "clamp"); minimum = requireNumber(minimum, "clamp"); maximum = requireNumber(maximum, "clamp"); if (minimum > maximum) throw new __velarMathNativeRangeError("clamp minimum cannot exceed maximum"); return __velarMathCall(__velarMathMin, [maximum, __velarMathCall(__velarMathMax, [minimum, value])]); }
1172
+ export function sign(value) { return unary(value, __velarMathSign, "sign"); }
1173
+ export function trunc(value) { return unary(value, __velarMathTrunc, "trunc"); }
1174
+ export function sqrt(value) { return unary(value, __velarMathSqrt, "sqrt"); }
1175
+ export function cbrt(value) { return unary(value, __velarMathCbrt, "cbrt"); }
1176
+ export function pow(left, right) { return binary(left, right, __velarMathPow, "pow"); }
1177
+ export function exp(value) { return unary(value, __velarMathExp, "exp"); }
1178
+ export function log(value, base = e) { return unary(value, __velarMathLog, "log") / unary(base, __velarMathLog, "log"); }
1179
+ export function log2(value) { return unary(value, __velarMathLog2, "log2"); }
1180
+ export function log10(value) { return unary(value, __velarMathLog10, "log10"); }
1181
+ export function sin(value) { return unary(value, __velarMathSin, "sin"); }
1182
+ export function cos(value) { return unary(value, __velarMathCos, "cos"); }
1183
+ export function tan(value) { return unary(value, __velarMathTan, "tan"); }
1184
+ export function asin(value) { return unary(value, __velarMathAsin, "asin"); }
1185
+ export function acos(value) { return unary(value, __velarMathAcos, "acos"); }
1186
+ export function atan(value) { return unary(value, __velarMathAtan, "atan"); }
1187
+ export function atan2(left, right) { return binary(left, right, __velarMathAtan2, "atan2"); }
1188
+ export function degrees(value) { return requireNumber(value, "degrees") * 180 / pi; }
1189
+ export function radians(value) { return requireNumber(value, "radians") * pi / 180; }
1190
+ export function hypot(left, right) { return binary(left, right, __velarMathHypot, "hypot"); }
1191
+ export function random() { const value = __velarMathCall(__velarMathRandom, []); if (typeof value !== "number" || !__velarMathCall(__velarMathNumberIsFinite, [value])) throw new __velarMathNativeTypeError("The host random source must return a finite number"); if (value < 0 || value >= 1) throw new __velarMathNativeRangeError("The host random source must return a number from 0 up to but excluding 1"); return value; }
1192
+ export function randomInt(minimum, maximum = null) { if (maximum === null) { maximum = minimum; minimum = 0; } const width = maximum - minimum; if (!__velarMathCall(__velarMathNumberIsSafeInteger, [minimum]) || !__velarMathCall(__velarMathNumberIsSafeInteger, [maximum]) || !__velarMathCall(__velarMathNumberIsSafeInteger, [width]) || width <= 0) throw new __velarMathNativeRangeError("randomInt requires an increasing safe-integer range"); return __velarMathCall(__velarMathFloor, [random() * width]) + minimum; }
1193
+ export function gcd(left, right) { if (!__velarMathCall(__velarMathNumberIsSafeInteger, [left]) || !__velarMathCall(__velarMathNumberIsSafeInteger, [right])) throw new __velarMathNativeTypeError("gcd requires safe integers"); left = __velarMathCall(__velarMathAbs, [left]); right = __velarMathCall(__velarMathAbs, [right]); while (right) [left, right] = [right, left % right]; return left; }
1194
+ export function lcm(left, right) { if (!__velarMathCall(__velarMathNumberIsSafeInteger, [left]) || !__velarMathCall(__velarMathNumberIsSafeInteger, [right])) throw new __velarMathNativeTypeError("lcm requires safe integers"); if (left === 0 || right === 0) return 0; const result = __velarMathCall(__velarMathAbs, [(left / gcd(left, right)) * right]); if (!__velarMathCall(__velarMathNumberIsSafeInteger, [result])) throw new __velarMathNativeRangeError("lcm result is outside the safe-integer range"); return result; }
1195
+ `.trimStart()],
1196
+ ["velar/binary", String.raw `
1197
+ import { __VelarIndexError } from ${JSON.stringify(VELAR_COLLECTION_LOWERING_MODULE)};
1198
+ ${VELAR_TYPE_REGISTRY_RUNTIME}
1199
+
1200
+ const __velarBinaryNativeObject = globalThis.Object;
1201
+ const __velarBinaryNativeNumber = globalThis.Number;
1202
+ const __velarBinaryNativeUint8Array = globalThis.Uint8Array;
1203
+ const __velarBinaryNativeUint16Array = globalThis.Uint16Array;
1204
+ const __velarBinaryNativeUint32Array = globalThis.Uint32Array;
1205
+ const __velarBinaryNativeFloat32Array = globalThis.Float32Array;
1206
+ const __velarBinaryNativeDataView = globalThis.DataView;
1207
+ const __velarBinaryNativeWeakMap = globalThis.WeakMap;
1208
+ const __velarBinaryNativeTypeError = globalThis.TypeError;
1209
+ const __velarBinaryNativeRangeError = globalThis.RangeError;
1210
+ const __velarBinaryGetOwnPropertyDescriptor = __velarBinaryNativeObject.getOwnPropertyDescriptor;
1211
+ const __velarBinaryGetPrototypeOf = __velarBinaryNativeObject.getPrototypeOf;
1212
+ const __velarBinaryFreeze = __velarBinaryNativeObject.freeze;
1213
+ const __velarBinaryApply = __velarBinaryGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
1214
+ const __velarBinaryNumberIsInteger = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryNativeNumber, "isInteger")?.value;
1215
+ const __velarBinaryNumberIsSafeInteger = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryNativeNumber, "isSafeInteger")?.value;
1216
+ const __velarBinaryNumberIsFinite = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryNativeNumber, "isFinite")?.value;
1217
+ const __velarBinaryTypedArrayPrototype = __velarBinaryGetPrototypeOf(__velarBinaryNativeUint8Array.prototype);
1218
+ const __velarBinaryTypedArrayTag = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryTypedArrayPrototype, globalThis.Symbol.toStringTag)?.get;
1219
+ const __velarBinaryTypedArrayLength = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryTypedArrayPrototype, "length")?.get;
1220
+ const __velarBinaryTypedArraySet = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryTypedArrayPrototype, "set")?.value;
1221
+ if (typeof __velarBinaryApply !== "function" || typeof __velarBinaryNumberIsInteger !== "function"
1222
+ || typeof __velarBinaryNumberIsSafeInteger !== "function" || typeof __velarBinaryTypedArrayTag !== "function"
1223
+ || typeof __velarBinaryNumberIsFinite !== "function" || typeof __velarBinaryTypedArrayLength !== "function"
1224
+ || typeof __velarBinaryTypedArraySet !== "function" || typeof __velarBinaryNativeDataView !== "function"
1225
+ || typeof __velarBinaryNativeWeakMap !== "function") {
1226
+ throw new __velarBinaryNativeTypeError("The JavaScript typed-array runtime is unavailable");
1227
+ }
1228
+ function __velarBinaryCall(operation, receiver, arguments_) { return __velarBinaryApply(operation, receiver, arguments_); }
1229
+ function __velarBinaryKind(value) {
1230
+ try { return __velarBinaryCall(__velarBinaryTypedArrayTag, value, []); }
1231
+ catch { return null; }
1232
+ }
1233
+ function __velarBinaryLength(value, expected, name) {
1234
+ if (__velarBinaryKind(value) !== expected) throw new __velarBinaryNativeTypeError(name + " requires " + expected);
1235
+ return __velarBinaryCall(__velarBinaryTypedArrayLength, value, []);
1236
+ }
1237
+ function __velarBinaryOrder(order) {
1238
+ if (order !== "little" && order !== "big") throw new __velarBinaryNativeTypeError("Byte order must be ByteOrder.little or ByteOrder.big");
1239
+ return order;
1240
+ }
1241
+ function __velarBinaryCheckedIndex(value, index, expected, name) {
1242
+ const length = __velarBinaryLength(value, expected, name);
1243
+ if (!__velarBinaryCall(__velarBinaryNumberIsInteger, __velarBinaryNativeNumber, [index]) || index < 0 || index >= length) {
1244
+ throw new __VelarIndexError(name + " index must be an integer from 0 up to but excluding size");
1245
+ }
1246
+ return index;
1247
+ }
1248
+ function __velarBinarySnapshot(value, expected, Constructor, name) {
1249
+ const length = __velarBinaryLength(value, expected, name);
1250
+ const bytes = expected === "Uint8Array" ? 1 : expected === "Uint16Array" ? 2 : 4;
1251
+ __velarBinarySizeLimit(length, bytes, name);
1252
+ const output = new Constructor(length);
1253
+ __velarBinaryCall(__velarBinaryTypedArraySet, output, [value]);
1254
+ return output;
1255
+ }
1256
+ function __velarBinaryWithinLimit(value, expected, bytes) {
1257
+ return __velarBinaryKind(value) === expected
1258
+ && __velarBinaryCall(__velarBinaryTypedArrayLength, value, []) <= (64 * 1024 * 1024) / bytes;
1259
+ }
1260
+ function __velarBinarySpec(value, name = "Binary buffer") {
1261
+ switch (__velarBinaryKind(value)) {
1262
+ case "Uint8Array": return { name: "UInt8Buffer", bytes: 1, Constructor: __velarBinaryNativeUint8Array, minimum: 0, maximum: 255, integer: true };
1263
+ case "Uint16Array": return { name: "UInt16Buffer", bytes: 2, Constructor: __velarBinaryNativeUint16Array, minimum: 0, maximum: 65535, integer: true };
1264
+ case "Uint32Array": return { name: "UInt32Buffer", bytes: 4, Constructor: __velarBinaryNativeUint32Array, minimum: 0, maximum: 4294967295, integer: true };
1265
+ case "Float32Array": return { name: "Float32Buffer", bytes: 4, Constructor: __velarBinaryNativeFloat32Array, minimum: -3.4028234663852886e38, maximum: 3.4028234663852886e38, integer: false };
1266
+ default: throw new __velarBinaryNativeTypeError(name + " requires a supported fixed numeric buffer");
1267
+ }
1268
+ }
1269
+ function __velarBinarySizeLimit(size, bytes, name) {
1270
+ if (!__velarBinaryCall(__velarBinaryNumberIsSafeInteger, __velarBinaryNativeNumber, [size]) || size < 0 || size > (64 * 1024 * 1024) / bytes) {
1271
+ throw new __velarBinaryNativeRangeError(name + " size exceeds the 64 MiB binary-memory limit");
1272
+ }
1273
+ return size;
1274
+ }
1275
+ function __velarBinaryAllocate(Constructor, bytes, size, name) { return new Constructor(__velarBinarySizeLimit(size, bytes, name)); }
1276
+ function __velarBinaryValue(spec, value) {
1277
+ const valid = typeof value === "number" && __velarBinaryCall(__velarBinaryNumberIsFinite, __velarBinaryNativeNumber, [value])
1278
+ && value >= spec.minimum && value <= spec.maximum
1279
+ && (!spec.integer || __velarBinaryCall(__velarBinaryNumberIsInteger, __velarBinaryNativeNumber, [value]));
1280
+ if (!valid) throw new __velarBinaryNativeRangeError(spec.name + " value is outside its supported numeric range");
1281
+ return value;
1282
+ }
1283
+
1284
+ export const ByteOrder = __velarRegisterRuntimeType(__velarBinaryFreeze({
1285
+ little: "little",
1286
+ big: "big",
1287
+ is(value) { return value === "little" || value === "big"; },
1288
+ parse(value) {
1289
+ if (!ByteOrder.is(value)) throw new __velarBinaryNativeTypeError("Value does not match ByteOrder");
1290
+ return value;
1291
+ },
1292
+ values() { return ["little", "big"]; },
1293
+ }));
1294
+ export const Bytes = __velarRegisterRuntimeType(__velarBinaryFreeze({
1295
+ is(value) { return __velarBinaryWithinLimit(value, "Uint8Array", 1); },
1296
+ parse(value) { return __velarBinarySnapshot(value, "Uint8Array", __velarBinaryNativeUint8Array, "Bytes.parse"); },
1297
+ __velarSize(value) { return __velarBinarySize(value); },
1298
+ __velarIndex(value, index) { return __velarBytesIndex(value, index); },
1299
+ __velarSetIndex(value, index, next) { return __velarBytesSetIndex(value, index, next); },
1300
+ __velarUInt8Index(value, index) { return __velarUInt8Index(value, index); },
1301
+ __velarUInt8SetIndex(value, index, next) { return __velarUInt8SetIndex(value, index, next); },
1302
+ __velarUInt16Index(value, index) { return __velarUInt16Index(value, index); },
1303
+ __velarUInt16SetIndex(value, index, next) { return __velarUInt16SetIndex(value, index, next); },
1304
+ __velarUInt32Index(value, index) { return __velarUInt32Index(value, index); },
1305
+ __velarUInt32SetIndex(value, index, next) { return __velarUInt32SetIndex(value, index, next); },
1306
+ __velarFloat32Index(value, index) { return __velarFloat32Index(value, index); },
1307
+ __velarFloat32SetIndex(value, index, next) { return __velarFloat32SetIndex(value, index, next); },
1308
+ __velarBufferCopy(value) { return __velarBufferCopy(value); },
1309
+ __velarBufferSlice(value, start, end) { return __velarBufferSlice(value, start, end); },
1310
+ __velarBufferToBytes(value, order) { return __velarBufferToBytes(value, order); },
1311
+ }));
1312
+ export const UInt8Buffer = __velarRegisterRuntimeType(__velarBinaryFreeze({
1313
+ is(value) { return __velarBinaryWithinLimit(value, "Uint8Array", 1); },
1314
+ parse(value) { return __velarBinarySnapshot(value, "Uint8Array", __velarBinaryNativeUint8Array, "UInt8Buffer.parse"); },
1315
+ }));
1316
+ export const UInt16Buffer = __velarRegisterRuntimeType(__velarBinaryFreeze({
1317
+ is(value) { return __velarBinaryWithinLimit(value, "Uint16Array", 2); },
1318
+ parse(value) { return __velarBinarySnapshot(value, "Uint16Array", __velarBinaryNativeUint16Array, "UInt16Buffer.parse"); },
1319
+ }));
1320
+ export const UInt32Buffer = __velarRegisterRuntimeType(__velarBinaryFreeze({
1321
+ is(value) { return __velarBinaryWithinLimit(value, "Uint32Array", 4); },
1322
+ parse(value) { return __velarBinarySnapshot(value, "Uint32Array", __velarBinaryNativeUint32Array, "UInt32Buffer.parse"); },
1323
+ }));
1324
+ export const Float32Buffer = __velarRegisterRuntimeType(__velarBinaryFreeze({
1325
+ is(value) { return __velarBinaryFloat32Is(value); },
1326
+ parse(value) { return __velarBinaryFloat32Snapshot(value, "Float32Buffer.parse"); },
1327
+ }));
1328
+
1329
+ export function uint8Buffer(size) { return __velarBinaryAllocate(__velarBinaryNativeUint8Array, 1, size, "uint8Buffer"); }
1330
+ export function uint16Buffer(size) { return __velarBinaryAllocate(__velarBinaryNativeUint16Array, 2, size, "uint16Buffer"); }
1331
+ export function uint32Buffer(size) { return __velarBinaryAllocate(__velarBinaryNativeUint32Array, 4, size, "uint32Buffer"); }
1332
+ export function float32Buffer(size) { return __velarBinaryAllocate(__velarBinaryNativeFloat32Array, 4, size, "float32Buffer"); }
1333
+ export function uint8FromBytes(snapshot) { return __velarBinarySnapshot(snapshot, "Uint8Array", __velarBinaryNativeUint8Array, "uint8FromBytes"); }
1334
+ export function uint16FromBytes(snapshot, order) {
1335
+ return __velarBufferFromBytes(snapshot, order, __velarBinaryNativeUint16Array, 2, "uint16FromBytes", "getUint16");
1336
+ }
1337
+ export function uint32FromBytes(snapshot, order) { return __velarBufferFromBytes(snapshot, order, __velarBinaryNativeUint32Array, 4, "uint32FromBytes", "getUint32"); }
1338
+ export function float32FromBytes(snapshot, order) { return __velarBufferFromBytes(snapshot, order, __velarBinaryNativeFloat32Array, 4, "float32FromBytes", "getFloat32", __velarBinaryFloat32Value); }
1339
+ function __velarBinarySize(value) {
1340
+ const kind = __velarBinaryKind(value);
1341
+ if (kind !== "Uint8Array" && kind !== "Uint16Array" && kind !== "Uint32Array" && kind !== "Float32Array") throw new __velarBinaryNativeTypeError("Binary size requires Bytes or a fixed numeric buffer");
1342
+ return __velarBinaryCall(__velarBinaryTypedArrayLength, value, []);
1343
+ }
1344
+ function __velarBytesIndex(value, index) {
1345
+ return value[__velarBinaryCheckedIndex(value, index, "Uint8Array", "Bytes")];
1346
+ }
1347
+ function __velarBytesSetIndex() {
1348
+ throw new __velarBinaryNativeTypeError("Bytes is a read-only binary snapshot");
1349
+ }
1350
+ function __velarBinaryIntegerValue(value, minimum, maximum, name) {
1351
+ if (!__velarBinaryCall(__velarBinaryNumberIsInteger, __velarBinaryNativeNumber, [value]) || value < minimum || value > maximum) throw new __velarBinaryNativeRangeError(name + " value is outside its supported integer range");
1352
+ return value;
1353
+ }
1354
+ function __velarBinaryFloat32Value(value) {
1355
+ if (typeof value !== "number" || !__velarBinaryCall(__velarBinaryNumberIsFinite, __velarBinaryNativeNumber, [value]) || value < -3.4028234663852886e38 || value > 3.4028234663852886e38) throw new __velarBinaryNativeRangeError("Float32Buffer value is outside its supported finite range");
1356
+ return value;
1357
+ }
1358
+ function __velarBinaryFloat32Is(value) {
1359
+ if (__velarBinaryKind(value) !== "Float32Array") return false;
1360
+ const length = __velarBinaryCall(__velarBinaryTypedArrayLength, value, []);
1361
+ if (length > (64 * 1024 * 1024) / 4) return false;
1362
+ for (let index = 0; index < length; index += 1) {
1363
+ const item = value[index];
1364
+ if (typeof item !== "number" || !__velarBinaryCall(__velarBinaryNumberIsFinite, __velarBinaryNativeNumber, [item])) return false;
1365
+ }
1366
+ return true;
1367
+ }
1368
+ function __velarBinaryFloat32Snapshot(value, name) {
1369
+ const length = __velarBinaryLength(value, "Float32Array", name);
1370
+ __velarBinarySizeLimit(length, 4, name);
1371
+ const output = new __velarBinaryNativeFloat32Array(length);
1372
+ for (let index = 0; index < length; index += 1) output[index] = __velarBinaryFloat32Value(value[index]);
1373
+ return output;
1374
+ }
1375
+ function __velarUInt8Index(value, index) { return value[__velarBinaryCheckedIndex(value, index, "Uint8Array", "UInt8Buffer")]; }
1376
+ function __velarUInt8SetIndex(value, index, next) {
1377
+ index = __velarBinaryCheckedIndex(value, index, "Uint8Array", "UInt8Buffer");
1378
+ value[index] = __velarBinaryIntegerValue(next, 0, 255, "UInt8Buffer");
1379
+ return next;
1380
+ }
1381
+ function __velarUInt16Index(value, index) { return value[__velarBinaryCheckedIndex(value, index, "Uint16Array", "UInt16Buffer")]; }
1382
+ function __velarUInt16SetIndex(value, index, next) {
1383
+ index = __velarBinaryCheckedIndex(value, index, "Uint16Array", "UInt16Buffer");
1384
+ value[index] = __velarBinaryIntegerValue(next, 0, 65535, "UInt16Buffer");
1385
+ return next;
1386
+ }
1387
+ function __velarUInt32Index(value, index) { return value[__velarBinaryCheckedIndex(value, index, "Uint32Array", "UInt32Buffer")]; }
1388
+ function __velarUInt32SetIndex(value, index, next) {
1389
+ index = __velarBinaryCheckedIndex(value, index, "Uint32Array", "UInt32Buffer");
1390
+ value[index] = __velarBinaryIntegerValue(next, 0, 4294967295, "UInt32Buffer");
1391
+ return next;
1392
+ }
1393
+ function __velarFloat32Index(value, index) { return value[__velarBinaryCheckedIndex(value, index, "Float32Array", "Float32Buffer")]; }
1394
+ function __velarFloat32SetIndex(value, index, next) {
1395
+ index = __velarBinaryCheckedIndex(value, index, "Float32Array", "Float32Buffer");
1396
+ value[index] = __velarBinaryFloat32Value(next);
1397
+ return next;
1398
+ }
1399
+ function __velarBufferCopy(value) { return __velarBufferSlice(value, 0, __velarBinarySize(value)); }
1400
+ function __velarBufferSlice(value, start = 0, end = __velarBinarySize(value)) {
1401
+ const spec = __velarBinarySpec(value);
1402
+ const length = __velarBinarySize(value);
1403
+ if (!__velarBinaryCall(__velarBinaryNumberIsSafeInteger, __velarBinaryNativeNumber, [start]) || !__velarBinaryCall(__velarBinaryNumberIsSafeInteger, __velarBinaryNativeNumber, [end]) || start < 0 || end < start || end > length) {
1404
+ throw new __velarBinaryNativeRangeError(spec.name + ".slice requires 0 <= start <= end <= size");
1405
+ }
1406
+ const output = new spec.Constructor(end - start);
1407
+ for (let index = start; index < end; index += 1) output[index - start] = value[index];
1408
+ return output;
1409
+ }
1410
+ function __velarBufferToBytes(value, order = null) {
1411
+ const spec = __velarBinarySpec(value);
1412
+ const length = __velarBinarySize(value);
1413
+ if (spec.bytes === 1) return __velarBinarySnapshot(value, "Uint8Array", __velarBinaryNativeUint8Array, "UInt8Buffer.toBytes");
1414
+ order = __velarBinaryOrder(order);
1415
+ const output = new __velarBinaryNativeUint8Array(length * spec.bytes);
1416
+ const view = new __velarBinaryNativeDataView(output.buffer);
1417
+ const operation = spec.name === "UInt16Buffer" ? "setUint16" : spec.name === "UInt32Buffer" ? "setUint32" : "setFloat32";
1418
+ const setter = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryNativeDataView.prototype, operation)?.value;
1419
+ if (typeof setter !== "function") throw new __velarBinaryNativeTypeError("DataView " + operation + " is unavailable");
1420
+ for (let index = 0; index < length; index += 1) {
1421
+ __velarBinaryCall(setter, view, [index * spec.bytes, value[index], order === "little"]);
1422
+ }
1423
+ return output;
1424
+ }
1425
+ function __velarBufferFromBytes(snapshot, order, Constructor, bytes, name, operation, validate = null) {
1426
+ const length = __velarBinaryLength(snapshot, "Uint8Array", name);
1427
+ __velarBinarySizeLimit(length, 1, name);
1428
+ order = __velarBinaryOrder(order);
1429
+ if (length % bytes !== 0) throw new __velarBinaryNativeRangeError(name + " requires a byte length divisible by " + bytes);
1430
+ const output = __velarBinaryAllocate(Constructor, bytes, length / bytes, name);
1431
+ const view = new __velarBinaryNativeDataView(snapshot.buffer, snapshot.byteOffset, snapshot.byteLength);
1432
+ const getter = __velarBinaryGetOwnPropertyDescriptor(__velarBinaryNativeDataView.prototype, operation)?.value;
1433
+ if (typeof getter !== "function") throw new __velarBinaryNativeTypeError("DataView " + operation + " is unavailable");
1434
+ for (let index = 0; index < output.length; index += 1) {
1435
+ const item = __velarBinaryCall(getter, view, [index * bytes, order === "little"]);
1436
+ output[index] = validate === null ? item : validate(item);
1437
+ }
1438
+ return output;
1439
+ }
1440
+ const __velarBinaryBuilders = new __velarBinaryNativeWeakMap();
1441
+ const __velarBinaryBuilderPrototype = __velarBinaryFreeze({
1442
+ get size() { const state = __velarBinaryBuilders.get(this); if (!state) throw new __velarBinaryNativeTypeError("Builder size requires a binary builder"); return state.size; },
1443
+ get maxElements() { const state = __velarBinaryBuilders.get(this); if (!state) throw new __velarBinaryNativeTypeError("Builder maxElements requires a binary builder"); return state.maximum; },
1444
+ push(value) {
1445
+ const state = __velarBinaryBuilders.get(this); if (!state || state.finished) throw new __velarBinaryNativeTypeError("Binary builder is finished");
1446
+ if (state.size >= state.maximum) throw new __velarBinaryNativeRangeError(state.spec.name + " builder exceeds maxElements");
1447
+ if (state.size === state.storage.length) { let capacity = state.storage.length * 2; if (capacity < 8) capacity = 8; if (capacity > state.maximum) capacity = state.maximum; const storage = new state.spec.Constructor(capacity); __velarBinaryCall(__velarBinaryTypedArraySet, storage, [state.storage]); state.storage = storage; }
1448
+ state.storage[state.size] = __velarBinaryValue(state.spec, value); state.size += 1; return null;
1449
+ },
1450
+ finish() {
1451
+ const state = __velarBinaryBuilders.get(this); if (!state || state.finished) throw new __velarBinaryNativeTypeError("Binary builder is finished");
1452
+ const output = new state.spec.Constructor(state.size); for (let index = 0; index < state.size; index += 1) output[index] = state.storage[index]; state.finished = true; state.storage = null; return output;
1453
+ },
1454
+ });
1455
+ function __velarBinaryBuilder(maximum, Constructor, bytes, name) {
1456
+ maximum = __velarBinarySizeLimit(maximum, bytes, name);
1457
+ const value = __velarBinaryFreeze(__velarBinaryNativeObject.create(__velarBinaryBuilderPrototype));
1458
+ const empty = new Constructor(maximum < 256 ? maximum : 256);
1459
+ __velarBinaryBuilders.set(value, { maximum, size: 0, storage: empty, spec: __velarBinarySpec(empty), finished: false });
1460
+ return value;
1461
+ }
1462
+ function __velarBinaryBuilderType(name, Constructor) { return __velarRegisterRuntimeType(__velarBinaryFreeze({ is(value) { const state = __velarBinaryBuilders.get(value); return !!state && state.spec.Constructor === Constructor && !state.finished; }, parse(value) { if (!this.is(value)) throw new __velarBinaryNativeTypeError("Value does not match " + name); return value; } })); }
1463
+ export const UInt32Builder = __velarBinaryBuilderType("UInt32Builder", __velarBinaryNativeUint32Array);
1464
+ export const Float32Builder = __velarBinaryBuilderType("Float32Builder", __velarBinaryNativeFloat32Array);
1465
+ export function uint32Builder(maxElements) { return __velarBinaryBuilder(maxElements, __velarBinaryNativeUint32Array, 4, "uint32Builder"); }
1466
+ export function float32Builder(maxElements) { return __velarBinaryBuilder(maxElements, __velarBinaryNativeFloat32Array, 4, "float32Builder"); }
1467
+ `.trimStart()],
1468
+ ["velar/random", String.raw `
1469
+ ${VELAR_TYPE_REGISTRY_RUNTIME}
1470
+ const __velarRandomNativeObject = globalThis.Object;
1471
+ const __velarRandomNativeNumber = globalThis.Number;
1472
+ const __velarRandomNativeArray = globalThis.Array;
1473
+ const __velarRandomNativeWeakMap = globalThis.WeakMap;
1474
+ const __velarRandomNativeTypeError = globalThis.TypeError;
1475
+ const __velarRandomNativeRangeError = globalThis.RangeError;
1476
+ const __velarRandomNativeMath = globalThis.Math;
1477
+ const __velarRandomGetOwnPropertyDescriptor = __velarRandomNativeObject.getOwnPropertyDescriptor;
1478
+ const __velarRandomFreeze = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeObject, "freeze")?.value;
1479
+ const __velarRandomCreate = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeObject, "create")?.value;
1480
+ const __velarRandomApply = __velarRandomGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
1481
+ const __velarRandomNumberIsSafeInteger = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeNumber, "isSafeInteger")?.value;
1482
+ const __velarRandomArrayIsArray = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeArray, "isArray")?.value;
1483
+ const __velarRandomMathImul = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeMath, "imul")?.value;
1484
+ const __velarRandomMathFloor = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeMath, "floor")?.value;
1485
+ const __velarRandomStringPrototype = __velarRandomGetOwnPropertyDescriptor(globalThis.String, "prototype")?.value;
1486
+ const __velarRandomStringCharCodeAt = __velarRandomGetOwnPropertyDescriptor(__velarRandomStringPrototype, "charCodeAt")?.value;
1487
+ const __velarRandomWeakMapPrototype = __velarRandomGetOwnPropertyDescriptor(__velarRandomNativeWeakMap, "prototype")?.value;
1488
+ const __velarRandomWeakMapGet = __velarRandomGetOwnPropertyDescriptor(__velarRandomWeakMapPrototype, "get")?.value;
1489
+ const __velarRandomWeakMapHas = __velarRandomGetOwnPropertyDescriptor(__velarRandomWeakMapPrototype, "has")?.value;
1490
+ const __velarRandomWeakMapSet = __velarRandomGetOwnPropertyDescriptor(__velarRandomWeakMapPrototype, "set")?.value;
1491
+ if (typeof __velarRandomFreeze !== "function" || typeof __velarRandomCreate !== "function" || typeof __velarRandomApply !== "function"
1492
+ || typeof __velarRandomNumberIsSafeInteger !== "function" || typeof __velarRandomArrayIsArray !== "function"
1493
+ || typeof __velarRandomMathImul !== "function" || typeof __velarRandomMathFloor !== "function"
1494
+ || typeof __velarRandomStringCharCodeAt !== "function" || typeof __velarRandomWeakMapGet !== "function"
1495
+ || typeof __velarRandomWeakMapHas !== "function" || typeof __velarRandomWeakMapSet !== "function") {
1496
+ throw new __velarRandomNativeTypeError("The deterministic random runtime is unavailable");
1497
+ }
1498
+ function __velarRandomCall(operation, receiver, arguments_) { return __velarRandomApply(operation, receiver, arguments_); }
1499
+ function __velarRandomImul(left, right) { return __velarRandomCall(__velarRandomMathImul, __velarRandomNativeMath, [left, right]); }
1500
+ function __velarRandomRotl(value, count) { return (value << count | value >>> (32 - count)) >>> 0; }
1501
+ function __velarRandomHash(text) {
1502
+ let value = (1779033703 ^ text.length) >>> 0;
1503
+ for (let index = 0; index < text.length; index += 1) {
1504
+ value = __velarRandomImul(value ^ __velarRandomCall(__velarRandomStringCharCodeAt, text, [index]), 3432918353);
1505
+ value = __velarRandomRotl(value, 13);
1506
+ }
1507
+ const output = new __velarRandomNativeArray(4);
1508
+ for (let index = 0; index < 4; index += 1) {
1509
+ value = __velarRandomImul(value ^ value >>> 16, 2246822507);
1510
+ value = __velarRandomImul(value ^ value >>> 13, 3266489909);
1511
+ value = (value ^ value >>> 16) >>> 0;
1512
+ output[index] = value;
1513
+ }
1514
+ if ((output[0] | output[1] | output[2] | output[3]) === 0) output[0] = 1;
1515
+ return output;
1516
+ }
1517
+ function __velarRandomSeed(seed) {
1518
+ if (typeof seed === "string") return __velarRandomHash("s:" + seed);
1519
+ if (typeof seed !== "number" || !__velarRandomCall(__velarRandomNumberIsSafeInteger, __velarRandomNativeNumber, [seed])) {
1520
+ throw new __velarRandomNativeTypeError("random seed must be a string or safe integer");
1521
+ }
1522
+ return __velarRandomHash("n:" + seed);
1523
+ }
1524
+ const __velarRandomStates = new __velarRandomNativeWeakMap();
1525
+ function __velarRandomState(value) {
1526
+ const state = __velarRandomCall(__velarRandomWeakMapGet, __velarRandomStates, [value]);
1527
+ if (state === undefined) throw new __velarRandomNativeTypeError("Random method requires a Random receiver");
1528
+ return state;
1529
+ }
1530
+ function __velarRandomNext(receiver) {
1531
+ const state = __velarRandomState(receiver).state;
1532
+ const result = __velarRandomImul(__velarRandomRotl(__velarRandomImul(state[1], 5) >>> 0, 7), 9) >>> 0;
1533
+ const temporary = state[1] << 9;
1534
+ state[2] ^= state[0]; state[3] ^= state[1]; state[1] ^= state[2]; state[0] ^= state[3]; state[2] ^= temporary;
1535
+ state[3] = __velarRandomRotl(state[3], 11);
1536
+ state[0] >>>= 0; state[1] >>>= 0; state[2] >>>= 0;
1537
+ return result;
1538
+ }
1539
+ function __velarRandomRange(start, end) {
1540
+ if (end === null) { end = start; start = 0; }
1541
+ const width = end - start;
1542
+ if (!__velarRandomCall(__velarRandomNumberIsSafeInteger, __velarRandomNativeNumber, [start])
1543
+ || !__velarRandomCall(__velarRandomNumberIsSafeInteger, __velarRandomNativeNumber, [end])
1544
+ || !__velarRandomCall(__velarRandomNumberIsSafeInteger, __velarRandomNativeNumber, [width])
1545
+ || width <= 0 || width > 4294967296) {
1546
+ throw new __velarRandomNativeRangeError("Random.int requires an increasing safe-integer range no wider than 2^32");
1547
+ }
1548
+ return [start, width];
1549
+ }
1550
+ const __velarRandomPrototype = {
1551
+ number() { return __velarRandomNext(this) / 4294967296; },
1552
+ int(start, end = null) {
1553
+ const range = __velarRandomRange(start, end);
1554
+ const limit = __velarRandomCall(__velarRandomMathFloor, __velarRandomNativeMath, [4294967296 / range[1]]) * range[1];
1555
+ let value; do { value = __velarRandomNext(this); } while (value >= limit);
1556
+ return range[0] + value % range[1];
1557
+ },
1558
+ bool(probability = 0.5) {
1559
+ if (typeof probability !== "number" || probability < 0 || probability > 1 || probability !== probability) throw new __velarRandomNativeRangeError("Random.bool probability must be a number from 0 through 1");
1560
+ if (probability === 0) return false;
1561
+ if (probability === 1) return true;
1562
+ return this.number() < probability;
1563
+ },
1564
+ pick(values) {
1565
+ if (!__velarRandomCall(__velarRandomArrayIsArray, __velarRandomNativeArray, [values])) throw new __velarRandomNativeTypeError("Random.pick requires a List");
1566
+ if (values.length === 0) throw new __velarRandomNativeRangeError("Random.pick requires a non-empty List");
1567
+ return values[this.int(values.length)];
1568
+ },
1569
+ shuffle(values) {
1570
+ if (!__velarRandomCall(__velarRandomArrayIsArray, __velarRandomNativeArray, [values])) throw new __velarRandomNativeTypeError("Random.shuffle requires a List");
1571
+ const output = new __velarRandomNativeArray(values.length);
1572
+ for (let index = 0; index < values.length; index += 1) output[index] = values[index];
1573
+ for (let index = output.length - 1; index > 0; index -= 1) { const other = this.int(index + 1); const value = output[index]; output[index] = output[other]; output[other] = value; }
1574
+ return output;
1575
+ },
1576
+ fork(label) {
1577
+ if (typeof label !== "string") throw new __velarRandomNativeTypeError("Random.fork label must be a string");
1578
+ const key = __velarRandomState(this).key;
1579
+ return __velarRandomMake(__velarRandomHash("f:" + key[0] + ":" + key[1] + ":" + key[2] + ":" + key[3] + ":" + label));
1580
+ },
1581
+ };
1582
+ __velarRandomFreeze(__velarRandomPrototype);
1583
+ function __velarRandomMake(key) {
1584
+ const value = __velarRandomCreate(__velarRandomPrototype);
1585
+ __velarRandomCall(__velarRandomWeakMapSet, __velarRandomStates, [value, { key: [key[0], key[1], key[2], key[3]], state: [key[0], key[1], key[2], key[3]] }]);
1586
+ return __velarRandomFreeze(value);
1587
+ }
1588
+ export const Random = __velarRegisterRuntimeType(__velarRandomFreeze({
1589
+ is(value) { return (typeof value === "object" || typeof value === "function") && value !== null && __velarRandomCall(__velarRandomWeakMapHas, __velarRandomStates, [value]); },
1590
+ parse(value) { if (!Random.is(value)) throw new __velarRandomNativeTypeError("Value does not match Random"); return value; },
1591
+ }));
1592
+ export function random(seed) { return __velarRandomMake(__velarRandomSeed(seed)); }
1593
+ `.trimStart()],
1594
+ ["velar/task", String.raw `
1595
+ ${VELAR_TYPE_REGISTRY_RUNTIME}
1596
+ const __velarTaskNativeObject = globalThis.Object;
1597
+ const __velarTaskNativeNumber = globalThis.Number;
1598
+ const __velarTaskNativePromise = globalThis.Promise;
1599
+ const __velarTaskNativeWeakMap = globalThis.WeakMap;
1600
+ const __velarTaskNativeSet = globalThis.Set;
1601
+ const __velarTaskNativeError = globalThis.Error;
1602
+ const __velarTaskNativeTypeError = globalThis.TypeError;
1603
+ const __velarTaskNativeRangeError = globalThis.RangeError;
1604
+ const __velarTaskGlobal = globalThis;
1605
+ const __velarTaskSetTimeout = globalThis.setTimeout;
1606
+ const __velarTaskClearTimeout = globalThis.clearTimeout;
1607
+ const __velarTaskGetOwnPropertyDescriptor = __velarTaskNativeObject.getOwnPropertyDescriptor;
1608
+ const __velarTaskFreeze = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeObject, "freeze")?.value;
1609
+ const __velarTaskCreate = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeObject, "create")?.value;
1610
+ const __velarTaskDefineProperties = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeObject, "defineProperties")?.value;
1611
+ const __velarTaskApply = __velarTaskGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
1612
+ const __velarTaskNumberIsFinite = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeNumber, "isFinite")?.value;
1613
+ const __velarTaskPromiseThen = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativePromise.prototype, "then")?.value;
1614
+ const __velarTaskWeakMapPrototype = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeWeakMap, "prototype")?.value;
1615
+ const __velarTaskWeakMapGet = __velarTaskGetOwnPropertyDescriptor(__velarTaskWeakMapPrototype, "get")?.value;
1616
+ const __velarTaskWeakMapHas = __velarTaskGetOwnPropertyDescriptor(__velarTaskWeakMapPrototype, "has")?.value;
1617
+ const __velarTaskWeakMapSet = __velarTaskGetOwnPropertyDescriptor(__velarTaskWeakMapPrototype, "set")?.value;
1618
+ const __velarTaskSetPrototype = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeSet, "prototype")?.value;
1619
+ const __velarTaskSetAdd = __velarTaskGetOwnPropertyDescriptor(__velarTaskSetPrototype, "add")?.value;
1620
+ const __velarTaskSetDelete = __velarTaskGetOwnPropertyDescriptor(__velarTaskSetPrototype, "delete")?.value;
1621
+ const __velarTaskSetValues = __velarTaskGetOwnPropertyDescriptor(__velarTaskSetPrototype, "values")?.value;
1622
+ const __velarTaskSetIterator = __velarTaskApply(__velarTaskSetValues, new __velarTaskNativeSet(), []);
1623
+ const __velarTaskSetIteratorNext = __velarTaskGetOwnPropertyDescriptor(__velarTaskNativeObject.getPrototypeOf(__velarTaskSetIterator), "next")?.value;
1624
+ const __velarTaskRegExpExec = __velarTaskGetOwnPropertyDescriptor(globalThis.RegExp.prototype, "exec")?.value;
1625
+ const __velarTaskDurationPattern = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(ms|s)$/;
1626
+ if (typeof __velarTaskFreeze !== "function" || typeof __velarTaskCreate !== "function" || typeof __velarTaskDefineProperties !== "function"
1627
+ || typeof __velarTaskApply !== "function" || typeof __velarTaskPromiseThen !== "function" || typeof __velarTaskSetTimeout !== "function"
1628
+ || typeof __velarTaskClearTimeout !== "function" || typeof __velarTaskWeakMapGet !== "function" || typeof __velarTaskWeakMapHas !== "function"
1629
+ || typeof __velarTaskWeakMapSet !== "function" || typeof __velarTaskSetAdd !== "function" || typeof __velarTaskSetDelete !== "function"
1630
+ || typeof __velarTaskSetValues !== "function" || typeof __velarTaskSetIteratorNext !== "function" || typeof __velarTaskRegExpExec !== "function") {
1631
+ throw new __velarTaskNativeTypeError("The structured task runtime is unavailable");
1632
+ }
1633
+ function __velarTaskCall(operation, receiver, arguments_) { return __velarTaskApply(operation, receiver, arguments_); }
1634
+ export class CancellationError extends __velarTaskNativeError {
1635
+ constructor(message = "Task cancelled") { super(message); this.name = "CancellationError"; }
1636
+ }
1637
+ export class TaskTimeoutError extends __velarTaskNativeError {
1638
+ constructor(message = "Task timed out") { super(message); this.name = "TaskTimeoutError"; }
1639
+ }
1640
+ const __velarCancellationStates = new __velarTaskNativeWeakMap();
1641
+ const __velarTaskStates = new __velarTaskNativeWeakMap();
1642
+ function __velarCancellationState(value) {
1643
+ const state = __velarTaskCall(__velarTaskWeakMapGet, __velarCancellationStates, [value]);
1644
+ if (state === undefined) throw new __velarTaskNativeTypeError("Cancellation method requires a Cancellation receiver");
1645
+ return state;
1646
+ }
1647
+ function __velarOwnedTaskState(value) {
1648
+ const state = __velarTaskCall(__velarTaskWeakMapGet, __velarTaskStates, [value]);
1649
+ if (state === undefined) throw new __velarTaskNativeTypeError("Task method requires a Task receiver");
1650
+ return state;
1651
+ }
1652
+ function __velarCancelToken(token, reason) {
1653
+ const state = __velarCancellationState(token);
1654
+ if (state.cancelled) return;
1655
+ state.cancelled = true;
1656
+ state.reason = reason;
1657
+ const iterator = __velarTaskCall(__velarTaskSetValues, state.children, []);
1658
+ while (true) {
1659
+ const next = __velarTaskCall(__velarTaskSetIteratorNext, iterator, []);
1660
+ if (next.done) break;
1661
+ __velarCancelToken(next.value, reason);
1662
+ }
1663
+ const listeners = __velarTaskCall(__velarTaskSetValues, state.listeners, []);
1664
+ while (true) { const next = __velarTaskCall(__velarTaskSetIteratorNext, listeners, []); if (next.done) break; next.value(reason); }
1665
+ }
1666
+ const __velarCancellationPrototype = {};
1667
+ __velarTaskDefineProperties(__velarCancellationPrototype, {
1668
+ cancelled: { enumerable: true, get() { return __velarCancellationState(this).cancelled; } },
1669
+ reason: { enumerable: true, get() { return __velarCancellationState(this).reason; } },
1670
+ checkpoint: { enumerable: true, value() {
1671
+ const receiver = this;
1672
+ __velarCancellationState(receiver);
1673
+ return new __velarTaskNativePromise((resolve, reject) => {
1674
+ __velarTaskCall(__velarTaskSetTimeout, __velarTaskGlobal, [() => {
1675
+ const state = __velarCancellationState(receiver);
1676
+ if (state.cancelled) reject(new CancellationError(state.reason ?? "Task cancelled"));
1677
+ else resolve(null);
1678
+ }, 0]);
1679
+ });
1680
+ } },
1681
+ });
1682
+ __velarTaskFreeze(__velarCancellationPrototype);
1683
+ function __velarMakeCancellation(parent) {
1684
+ if (parent !== null && !Cancellation.is(parent)) throw new __velarTaskNativeTypeError("task parent must be a Cancellation value or null");
1685
+ const value = __velarTaskCreate(__velarCancellationPrototype);
1686
+ const state = { cancelled: false, reason: null, parent, children: new __velarTaskNativeSet(), listeners: new __velarTaskNativeSet() };
1687
+ __velarTaskCall(__velarTaskWeakMapSet, __velarCancellationStates, [value, state]);
1688
+ if (parent !== null) {
1689
+ const parentState = __velarCancellationState(parent);
1690
+ __velarTaskCall(__velarTaskSetAdd, parentState.children, [value]);
1691
+ if (parentState.cancelled) __velarCancelToken(value, parentState.reason);
1692
+ }
1693
+ return __velarTaskFreeze(value);
1694
+ }
1695
+ function __velarDetachCancellation(token) {
1696
+ const state = __velarCancellationState(token);
1697
+ if (state.parent !== null) __velarTaskCall(__velarTaskSetDelete, __velarCancellationState(state.parent).children, [token]);
1698
+ }
1699
+ function __velarCreateCancellation(parent = null) { return __velarMakeCancellation(parent); }
1700
+ function __velarCancelCancellation(token, reason = "Task cancelled") {
1701
+ if (typeof reason !== "string") throw new __velarTaskNativeTypeError("Cancellation reason must be a string");
1702
+ __velarCancelToken(token, reason);
1703
+ return null;
1704
+ }
1705
+ function __velarOnCancellation(token, callback) {
1706
+ const state = __velarCancellationState(token);
1707
+ if (typeof callback !== "function") throw new __velarTaskNativeTypeError("Cancellation listener must be a function");
1708
+ if (state.cancelled) { callback(state.reason); return () => null; }
1709
+ __velarTaskCall(__velarTaskSetAdd, state.listeners, [callback]);
1710
+ return () => { __velarTaskCall(__velarTaskSetDelete, state.listeners, [callback]); return null; };
1711
+ }
1712
+ function __velarSettleCancellation(token, callback, value) { __velarDetachCancellation(token); return callback(value); }
1713
+ function __velarAwaitStop(state) {
1714
+ return new __velarTaskNativePromise((resolve, reject) => {
1715
+ __velarTaskCall(__velarTaskPromiseThen, state.promise, [() => resolve(null), failure => failure instanceof CancellationError ? resolve(null) : reject(failure)]);
1716
+ });
1717
+ }
1718
+ const __velarTaskPrototype = {
1719
+ result() { return __velarOwnedTaskState(this).promise; },
1720
+ cancel(reason = "Task cancelled") {
1721
+ if (typeof reason !== "string") throw new __velarTaskNativeTypeError("Task.cancel reason must be a string");
1722
+ const state = __velarOwnedTaskState(this); __velarCancelToken(state.cancellation, reason); return __velarAwaitStop(state);
1723
+ },
1724
+ close() { const state = __velarOwnedTaskState(this); __velarCancelToken(state.cancellation, "Task scope ended"); return __velarAwaitStop(state); },
1725
+ };
1726
+ __velarTaskFreeze(__velarTaskPrototype);
1727
+ function __velarMakeTask(work, parent) {
1728
+ if (typeof work !== "function") throw new __velarTaskNativeTypeError("task requires an async function");
1729
+ const cancellation = __velarMakeCancellation(parent);
1730
+ const value = __velarTaskCreate(__velarTaskPrototype);
1731
+ let startResolve;
1732
+ const start = new __velarTaskNativePromise(resolve => { startResolve = resolve; });
1733
+ const state = { cancellation, promise: null };
1734
+ __velarTaskCall(__velarTaskWeakMapSet, __velarTaskStates, [value, state]);
1735
+ state.promise = __velarTaskCall(__velarTaskPromiseThen, start, [() => work(cancellation)]);
1736
+ state.promise = __velarTaskCall(__velarTaskPromiseThen, state.promise, [
1737
+ result => __velarSettleCancellation(cancellation, value => value, result === undefined ? null : result),
1738
+ failure => __velarSettleCancellation(cancellation, value => { throw value; }, failure),
1739
+ ]);
1740
+ startResolve(null);
1741
+ return __velarTaskFreeze(value);
1742
+ }
1743
+ function __velarTaskDuration(value) {
1744
+ if (typeof value !== "string") throw new __velarTaskNativeTypeError("withTimeout requires Duration; write a value such as 200ms or 2s");
1745
+ const match = __velarTaskCall(__velarTaskRegExpExec, __velarTaskDurationPattern, [value]);
1746
+ if (!match) throw new __velarTaskNativeTypeError("withTimeout requires Duration; write a value such as 200ms or 2s");
1747
+ const milliseconds = __velarTaskNativeNumber(match[1]) * (match[2] === "s" ? 1000 : 1);
1748
+ if (!__velarTaskCall(__velarTaskNumberIsFinite, __velarTaskNativeNumber, [milliseconds]) || milliseconds < 0 || milliseconds > 2147483647) throw new __velarTaskNativeRangeError("withTimeout duration must be from 0ms through 2147483647ms");
1749
+ return milliseconds;
1750
+ }
1751
+ export const Cancellation = __velarRegisterRuntimeType(__velarTaskFreeze({
1752
+ is(value) { return value !== null && (typeof value === "object" || typeof value === "function") && __velarTaskCall(__velarTaskWeakMapHas, __velarCancellationStates, [value]); },
1753
+ parse(value) { if (!Cancellation.is(value)) throw new __velarTaskNativeTypeError("Value does not match Cancellation"); return value; },
1754
+ __velarCreate(parent = null) { return __velarCreateCancellation(parent); },
1755
+ __velarCancel(token, reason = "Task cancelled") { return __velarCancelCancellation(token, reason); },
1756
+ __velarOn(token, callback) { return __velarOnCancellation(token, callback); },
1757
+ }));
1758
+ const __velarTaskType = __velarTaskFreeze({
1759
+ is(value) { return value !== null && (typeof value === "object" || typeof value === "function") && __velarTaskCall(__velarTaskWeakMapHas, __velarTaskStates, [value]); },
1760
+ parse(value) { if (!__velarTaskType.is(value)) throw new __velarTaskNativeTypeError("Value does not match Task"); return value; },
1761
+ });
1762
+ export const Task = __velarRegisterRuntimeType(__velarTaskFreeze({ ...__velarTaskType, of() { return __velarTaskType; } }));
1763
+ export function task(work, parent = null) { return __velarMakeTask(work, parent); }
1764
+ export function withTimeout(source, duration) {
1765
+ const state = __velarOwnedTaskState(source);
1766
+ const milliseconds = __velarTaskDuration(duration);
1767
+ return new __velarTaskNativePromise((resolve, reject) => {
1768
+ let settled = false;
1769
+ const timer = __velarTaskCall(__velarTaskSetTimeout, __velarTaskGlobal, [() => {
1770
+ if (settled) return;
1771
+ settled = true;
1772
+ __velarCancelToken(state.cancellation, "Task timed out");
1773
+ __velarTaskCall(__velarTaskPromiseThen, state.promise, [
1774
+ () => reject(new TaskTimeoutError("Task timed out after " + duration)),
1775
+ () => reject(new TaskTimeoutError("Task timed out after " + duration)),
1776
+ ]);
1777
+ }, milliseconds]);
1778
+ __velarTaskCall(__velarTaskPromiseThen, state.promise, [
1779
+ value => { if (!settled) { settled = true; __velarTaskCall(__velarTaskClearTimeout, __velarTaskGlobal, [timer]); resolve(value); } },
1780
+ failure => { if (!settled) { settled = true; __velarTaskCall(__velarTaskClearTimeout, __velarTaskGlobal, [timer]); reject(failure); } },
1781
+ ]);
1782
+ });
1783
+ }
1784
+ `.trimStart()],
1785
+ ["velar/json", String.raw `
1786
+ ${VELAR_STRICT_JSON_RUNTIME}
1787
+ ${runtimeTypeRuntime}
1788
+ function runtimeType(Type) { return __velarRequireRuntimeType(Type, "JSON validation", true); }
1789
+ export function parse(text, Type = null) { if (typeof text !== "string") throw new __velarJsonNativeTypeError("json.parse requires a string"); Type = runtimeType(Type); const value = __velarJsonParse(text); return Type ? Type.parse(value) : value; }
1790
+ export function tryParse(text, Type = null, fallback = null) { Type = runtimeType(Type); try { return parse(text, Type); } catch { return fallback; } }
1791
+ export function stringify(value, pretty = false) { return __velarJsonStringify(value, pretty); }
1792
+ function sorted(value) {
1793
+ if (value === null || typeof value !== "object") return value;
1794
+ if (__velarJsonApply(__velarJsonArrayIsArray, __velarJsonNativeArray, [value], "Array.isArray")) {
1795
+ const output = new __velarJsonNativeArray(value.length);
1796
+ for (let index = 0; index < value.length; index += 1) output[index] = sorted(__velarJsonGetOwnPropertyDescriptor(value, index).value);
1797
+ return output;
1798
+ }
1799
+ const result = __velarJsonApply(__velarJsonCreate, __velarJsonNativeObject, [null], "Object.create");
1800
+ const keys = __velarJsonGetOwnPropertyNames(value);
1801
+ __velarJsonApply(__velarJsonArraySort, keys, [], "Array.sort");
1802
+ for (let index = 0; index < keys.length; index += 1) { const key = keys[index]; __velarJsonApply(__velarJsonDefineProperty, __velarJsonNativeObject, [result, key, { value: sorted(__velarJsonGetOwnPropertyDescriptor(value, key).value), enumerable: true, configurable: true, writable: true }], "Object.defineProperty"); }
1803
+ return result;
1804
+ }
1805
+ export function stableStringify(value, pretty = false) { return __velarJsonStringify(sorted(__velarJsonSnapshot(value).value), pretty); }
1806
+ export function clone(value, Type = null) { Type = runtimeType(Type); const cloned = __velarJsonClone(value); return Type ? Type.parse(cloned) : cloned; }
1807
+ export function isSerializable(value) { try { __velarAssertJson(value); return true; } catch { return false; } }
1808
+ `.trimStart()],
1809
+ ["velar/async", String.raw `
1810
+ ${listRuntime}
1811
+ const __velarMaxTimerMilliseconds = 2147483647;
1812
+ const __velarMaxAsyncFanout = 10000;
1813
+ const __velarAsyncGlobal = globalThis;
1814
+ const __velarAsyncApply = Reflect.apply;
1815
+ const __velarAsyncPromise = Promise;
1816
+ const __velarAsyncPromiseThen = Promise.prototype.then;
1817
+ const __velarAsyncSetTimeout = globalThis.setTimeout;
1818
+ const __velarAsyncClearTimeout = globalThis.clearTimeout;
1819
+ const __velarAsyncNumber = Number;
1820
+ const __velarAsyncNumberIsFinite = Number.isFinite;
1821
+ const __velarAsyncNumberIsSafeInteger = Number.isSafeInteger;
1822
+ const __velarAsyncRegExpExec = RegExp.prototype.exec;
1823
+ const __velarAsyncDurationPattern = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(ms|s)$/;
1824
+ const __velarAsyncGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
1825
+ // D51 rule 103: the same list the \`try\` expression refuses to swallow. A
1826
+ // combinator that turns a failure into a value — or retries past it — must not
1827
+ // hide the language saying "this program has a bug".
1828
+ function __velarAsyncIsIntegrityFailure(value) {
1829
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return false;
1830
+ const descriptor = __velarAsyncGetOwnPropertyDescriptor(value, "name");
1831
+ if (!descriptor || !("value" in descriptor)) return false;
1832
+ const name = descriptor.value;
1833
+ return name === "AssertionError" || name === "NarrowingError" || name === "IndexError";
1834
+ }
1835
+ const __velarAsyncGetOwnPropertyNames = Object.getOwnPropertyNames;
1836
+ const __velarAsyncGetOwnPropertySymbols = Object.getOwnPropertySymbols;
1837
+ const __velarAsyncGetPrototypeOf = Object.getPrototypeOf;
1838
+ const __velarAsyncCreate = Object.create;
1839
+ const __velarAsyncDefineProperty = Object.defineProperty;
1840
+ const __velarAsyncTypeError = TypeError;
1841
+ const __velarAsyncRangeError = RangeError;
1842
+ const __velarAsyncError = Error;
1843
+ const __velarAsyncDetachedRegistryKey = Symbol.for(${JSON.stringify(VELAR_RUNTIME_REGISTRY_KEY)});
1844
+ const __velarAsyncConsole = globalThis.console;
1845
+ const __velarAsyncConsoleError = __velarAsyncConsole ? __velarAsyncConsole.error : null;
1846
+ function asyncFanout(values, name) { values = __velarRequireList(values, name); if (values.length > __velarMaxAsyncFanout) throw new __velarAsyncRangeError(name + " cannot start more than 10000 operations at once"); return values; }
1847
+ function durationMilliseconds(value, name) { if (typeof value !== "string") throw new __velarAsyncTypeError(name + " requires Duration; write a value such as 200ms or 2s"); const match = __velarAsyncApply(__velarAsyncRegExpExec, __velarAsyncDurationPattern, [value]); if (!match) throw new __velarAsyncTypeError(name + " requires Duration; write a value such as 200ms or 2s"); const milliseconds = __velarAsyncNumber(match[1]) * (match[2] === "s" ? 1000 : 1); if (!__velarAsyncNumberIsFinite(milliseconds) || milliseconds < 0 || milliseconds > __velarMaxTimerMilliseconds) throw new __velarAsyncRangeError(name + " requires a Duration from 0ms through 2147483647ms"); return milliseconds; }
1848
+ export function sleep(duration) { const milliseconds = durationMilliseconds(duration, "sleep"); return new __velarAsyncPromise((resolve) => __velarAsyncApply(__velarAsyncSetTimeout, __velarAsyncGlobal, [() => resolve(null), milliseconds])); }
1849
+ function normalize(value) { return value === undefined ? null : value; }
1850
+ function reportAsyncLoser(failure) { try { const runtime = globalThis[__velarAsyncDetachedRegistryKey]; if (runtime && typeof runtime.report === "function") { runtime.report(failure, { phase: "detached", detail: "async combinator loser", unhandled: true }); return null; } if (typeof __velarAsyncConsoleError === "function") __velarAsyncApply(__velarAsyncConsoleError, __velarAsyncConsole, ["Detached async task failed: " + (failure && failure.stack ? failure.stack : String(failure))]); } catch {} return null; }
1851
+ function actualPromise(value, name) { try { return __velarAsyncApply(__velarAsyncPromiseThen, value, [normalize]); } catch { throw new __velarAsyncTypeError(name + " requires actual Promises"); } }
1852
+ function optionalActualPromise(value) { try { return __velarAsyncApply(__velarAsyncPromiseThen, value, [normalize]); } catch { return null; } }
1853
+ function promiseList(values, name) { const output = new __velarListArray(values.length); for (let index = 0; index < values.length; index += 1) output[index] = actualPromise(values[index], name); return output; }
1854
+ function promiseAll(values) {
1855
+ return new __velarAsyncPromise((resolve, reject) => {
1856
+ const output = new __velarListArray(values.length);
1857
+ if (values.length === 0) { resolve(output); return; }
1858
+ let remaining = values.length;
1859
+ let settled = false;
1860
+ for (let index = 0; index < values.length; index += 1) {
1861
+ try {
1862
+ __velarAsyncApply(__velarAsyncPromiseThen, values[index], [
1863
+ (value) => { output[index] = value; remaining -= 1; if (remaining === 0 && !settled) { settled = true; resolve(output); } },
1864
+ (failure) => { if (settled) reportAsyncLoser(failure); else { settled = true; reject(failure); } },
1865
+ ]);
1866
+ } catch (error) { if (settled) reportAsyncLoser(error); else { settled = true; reject(error); } }
1867
+ }
1868
+ });
1869
+ }
1870
+ function promiseRace(values) {
1871
+ return new __velarAsyncPromise((resolve, reject) => {
1872
+ let settled = false;
1873
+ for (let index = 0; index < values.length; index += 1) {
1874
+ try { __velarAsyncApply(__velarAsyncPromiseThen, values[index], [(value) => { if (!settled) { settled = true; resolve(value); } }, (failure) => { if (settled) reportAsyncLoser(failure); else { settled = true; reject(failure); } }]); }
1875
+ catch (error) { if (settled) reportAsyncLoser(error); else { settled = true; reject(error); } }
1876
+ }
1877
+ });
1878
+ }
1879
+ function requireSafePromiseResult(value, name) {
1880
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return value;
1881
+ let owner = value;
1882
+ for (let depth = 0; owner !== null && depth < 128; depth += 1) {
1883
+ let descriptor;
1884
+ try { descriptor = __velarAsyncGetOwnPropertyDescriptor(owner, "then"); }
1885
+ catch { throw new __velarAsyncTypeError(name + " result must not expose a callable 'then' or a 'then' getter"); }
1886
+ if (descriptor) {
1887
+ if (!("value" in descriptor) || typeof descriptor.value === "function") throw new __velarAsyncTypeError(name + " result must not expose a callable 'then' or a 'then' getter");
1888
+ return value;
1889
+ }
1890
+ try { owner = __velarAsyncGetPrototypeOf(owner); }
1891
+ catch { throw new __velarAsyncTypeError(name + " result must have an inspectable prototype chain"); }
1892
+ }
1893
+ if (owner !== null) throw new __velarAsyncTypeError(name + " result prototype chain is too deep");
1894
+ return value;
1895
+ }
1896
+ function promiseRecord(value, name) { if (value === null || typeof value !== "object" || __velarListArrayIsArray(value) || __velarAsyncGetOwnPropertySymbols(value).length > 0) throw new __velarAsyncTypeError(name + " requires a List or record of Promises"); const names = __velarAsyncGetOwnPropertyNames(value); if (names.length > __velarMaxAsyncFanout) throw new __velarAsyncRangeError(name + " cannot start more than 10000 operations at once"); const promises = new __velarListArray(names.length); for (let index = 0; index < names.length; index += 1) { const descriptor = __velarAsyncGetOwnPropertyDescriptor(value, names[index]); if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) throw new __velarAsyncTypeError(name + " record fields must be enumerable data values"); promises[index] = actualPromise(descriptor.value, name); } return __velarAsyncApply(__velarAsyncPromiseThen, promiseAll(promises), [(results) => { const output = __velarAsyncCreate(null); for (let index = 0; index < names.length; index += 1) __velarAsyncDefineProperty(output, names[index], { value: results[index], enumerable: true, configurable: true, writable: true }); return output; }]); }
1897
+ export async function all(values) { if (__velarListArrayIsArray(values)) { values = asyncFanout(values, "async.all"); return promiseAll(promiseList(values, "async.all")); } return promiseRecord(values, "async.all"); }
1898
+ export async function race(values) { values = asyncFanout(values, "async.race"); if (values.length === 0) throw new __velarAsyncRangeError("race requires at least one Promise"); return promiseRace(promiseList(values, "async.race")); }
1899
+ export async function timeout(value, duration, message = "Operation timed out") { value = actualPromise(value, "async.timeout"); const milliseconds = durationMilliseconds(duration, "timeout"); if (typeof message !== "string") throw new __velarAsyncTypeError("timeout message must be a string"); if (message.length > 65536) throw new __velarAsyncRangeError("timeout messages cannot exceed 64 KiB"); let timer; const timeoutPromise = new __velarAsyncPromise((_, reject) => { timer = __velarAsyncApply(__velarAsyncSetTimeout, __velarAsyncGlobal, [() => reject(new __velarAsyncError(message)), milliseconds]); }); try { return normalize(await promiseRace([value, timeoutPromise])); } finally { if (timer !== undefined) __velarAsyncApply(__velarAsyncClearTimeout, __velarAsyncGlobal, [timer]); } }
1900
+ export async function retry(task, attempts = 3, delay = "0ms") { if (typeof task !== "function") throw new __velarAsyncTypeError("retry requires a function"); if (!__velarAsyncNumberIsSafeInteger(attempts) || attempts < 1 || attempts > 10000) throw new __velarAsyncRangeError("retry attempts must be an integer from 1 through 10000"); durationMilliseconds(delay, "retry delay"); let last; for (let attempt = 0; attempt < attempts; attempt += 1) { try { const candidate = normalize(__velarAsyncApply(task, undefined, [])); const pending = optionalActualPromise(candidate); return pending ? await pending : requireSafePromiseResult(candidate, "async.retry"); } catch (error) { if (__velarAsyncIsIntegrityFailure(error)) throw error; last = error; if (attempt + 1 < attempts && delay !== "0ms") await sleep(delay); } } throw last; }
1901
+ export async function map(values, worker, concurrency = 4) { values = __velarRequireList(values, "async.map"); if (typeof worker !== "function") throw new __velarAsyncTypeError("async.map requires a worker"); if (!__velarAsyncNumberIsSafeInteger(concurrency) || concurrency < 1 || concurrency > 1024) throw new __velarAsyncRangeError("async.map concurrency must be an integer from 1 through 1024"); const output = new __velarListArray(values.length); let cursor = 0, stopped = false; async function run() { try { while (!stopped) { const index = cursor++; if (index >= values.length) return null; const candidate = normalize(__velarAsyncApply(worker, undefined, [values[index]])); const pending = optionalActualPromise(candidate); output[index] = pending ? await pending : candidate; } return null; } catch (failure) { stopped = true; throw failure; } } const workerCount = concurrency < values.length ? concurrency : values.length; const workers = new __velarListArray(workerCount); for (let index = 0; index < workerCount; index += 1) workers[index] = run(); await promiseAll(workers); return output; }
1902
+ export async function series(tasks) { tasks = __velarRequireList(tasks, "async.series"); const output = new __velarListArray(tasks.length); for (let index = 0; index < tasks.length; index += 1) { const task = tasks[index]; if (typeof task !== "function") throw new __velarAsyncTypeError("series requires a List of functions"); const candidate = normalize(__velarAsyncApply(task, undefined, [])); const pending = optionalActualPromise(candidate); output[index] = pending ? await pending : candidate; } return output; }
1903
+ `.trimStart()],
1904
+ ["velar/url", String.raw `
1905
+ ${listRuntime}
1906
+ const fallbackBase = "https://velar.invalid/";
1907
+ const maxUrlCodeUnits = 2 * 1024 * 1024;
1908
+ const __velarUrlNativeObject = globalThis.Object;
1909
+ const __velarUrlNativeMap = globalThis.Map;
1910
+ const __velarUrlNativeNumber = globalThis.Number;
1911
+ const __velarUrlNativeString = globalThis.String;
1912
+ const __velarUrlNativeUrl = globalThis.URL;
1913
+ const __velarUrlNativeSearchParams = globalThis.URLSearchParams;
1914
+ const __velarUrlNativeTypeError = globalThis.TypeError;
1915
+ const __velarUrlNativeRangeError = globalThis.RangeError;
1916
+ const __velarUrlNativeUriError = globalThis.URIError;
1917
+ const __velarUrlGetOwnPropertyDescriptor = __velarUrlNativeObject.getOwnPropertyDescriptor;
1918
+ const __velarUrlGetOwnPropertyNames = __velarUrlNativeObject.getOwnPropertyNames;
1919
+ const __velarUrlGetOwnPropertySymbols = __velarUrlNativeObject.getOwnPropertySymbols;
1920
+ const __velarUrlGetPrototypeOf = __velarUrlNativeObject.getPrototypeOf;
1921
+ const __velarUrlApply = __velarUrlGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
1922
+ function __velarUrlHostData(owner, key, kind) {
1923
+ const descriptor = __velarUrlGetOwnPropertyDescriptor(owner, key);
1924
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== kind) throw new __velarUrlNativeTypeError("The JavaScript " + key + " URL API is unavailable");
1925
+ return descriptor.value;
1926
+ }
1927
+ function __velarUrlHostOperation(owner, key) { return __velarUrlHostData(owner, key, "function"); }
1928
+ function __velarUrlHostAccessor(owner, key, setter = false) {
1929
+ for (let depth = 0; owner !== null && depth < 32; depth += 1) {
1930
+ const descriptor = __velarUrlGetOwnPropertyDescriptor(owner, key);
1931
+ if (descriptor) {
1932
+ const operation = descriptor[setter ? "set" : "get"];
1933
+ if (typeof operation !== "function") throw new __velarUrlNativeTypeError("The JavaScript " + key + " URL API must be an accessor");
1934
+ return operation;
1935
+ }
1936
+ owner = __velarUrlGetPrototypeOf(owner);
1937
+ }
1938
+ throw new __velarUrlNativeTypeError("The JavaScript " + key + " URL API is unavailable");
1939
+ }
1940
+ function __velarUrlInheritedDescriptor(owner, key) {
1941
+ for (let depth = 0; owner !== null && depth < 32; depth += 1) {
1942
+ const descriptor = __velarUrlGetOwnPropertyDescriptor(owner, key);
1943
+ if (descriptor) return descriptor;
1944
+ owner = __velarUrlGetPrototypeOf(owner);
1945
+ }
1946
+ return null;
1947
+ }
1948
+ function __velarUrlInheritedOperation(owner, key) {
1949
+ const descriptor = __velarUrlInheritedDescriptor(owner, key);
1950
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "function") throw new __velarUrlNativeTypeError("The JavaScript " + key + " URL API must be a data function");
1951
+ return descriptor.value;
1952
+ }
1953
+ const __velarUrlObjectPrototype = __velarUrlHostData(__velarUrlNativeObject, "prototype", "object");
1954
+ const __velarUrlStringPrototype = __velarUrlHostData(__velarUrlNativeString, "prototype", "object");
1955
+ const __velarUrlUrlPrototype = __velarUrlHostData(__velarUrlNativeUrl, "prototype", "object");
1956
+ const __velarUrlSearchParamsPrototype = __velarUrlHostData(__velarUrlNativeSearchParams, "prototype", "object");
1957
+ const __velarUrlMapPrototype = __velarUrlHostData(__velarUrlNativeMap, "prototype", "object");
1958
+ const __velarUrlEncodeURIComponent = globalThis.encodeURIComponent;
1959
+ const __velarUrlDecodeURIComponent = globalThis.decodeURIComponent;
1960
+ const __velarUrlNumberIsFinite = __velarUrlHostOperation(__velarUrlNativeNumber, "isFinite");
1961
+ const __velarUrlObjectFreeze = __velarUrlHostOperation(__velarUrlNativeObject, "freeze");
1962
+ const __velarUrlStringCharCodeAt = __velarUrlHostOperation(__velarUrlStringPrototype, "charCodeAt");
1963
+ const __velarUrlStringEndsWith = __velarUrlHostOperation(__velarUrlStringPrototype, "endsWith");
1964
+ const __velarUrlStringSlice = __velarUrlHostOperation(__velarUrlStringPrototype, "slice");
1965
+ const __velarUrlStringStartsWith = __velarUrlHostOperation(__velarUrlStringPrototype, "startsWith");
1966
+ const __velarUrlRegExpPattern = /^[a-z][a-z\d+.-]*:/iu;
1967
+ const __velarUrlHttpPattern = /^https?:$/u;
1968
+ const __velarUrlRegExpTest = __velarUrlInheritedOperation(__velarUrlRegExpPattern, "test");
1969
+ const __velarUrlSearchParamsAppend = __velarUrlHostOperation(__velarUrlSearchParamsPrototype, "append");
1970
+ const __velarUrlSearchParamsEntries = __velarUrlHostOperation(__velarUrlSearchParamsPrototype, "entries");
1971
+ const __velarUrlSearchParamsToString = __velarUrlHostOperation(__velarUrlSearchParamsPrototype, "toString");
1972
+ const __velarUrlMapEntries = __velarUrlHostOperation(__velarUrlMapPrototype, "entries");
1973
+ const __velarUrlMapSet = __velarUrlHostOperation(__velarUrlMapPrototype, "set");
1974
+ const __velarUrlMapSize = __velarUrlHostAccessor(__velarUrlMapPrototype, "size");
1975
+ const __velarUrlHref = __velarUrlHostAccessor(__velarUrlUrlPrototype, "href");
1976
+ const __velarUrlProtocol = __velarUrlHostAccessor(__velarUrlUrlPrototype, "protocol");
1977
+ const __velarUrlHost = __velarUrlHostAccessor(__velarUrlUrlPrototype, "host");
1978
+ const __velarUrlHostname = __velarUrlHostAccessor(__velarUrlUrlPrototype, "hostname");
1979
+ const __velarUrlPort = __velarUrlHostAccessor(__velarUrlUrlPrototype, "port");
1980
+ const __velarUrlPathname = __velarUrlHostAccessor(__velarUrlUrlPrototype, "pathname");
1981
+ const __velarUrlSearch = __velarUrlHostAccessor(__velarUrlUrlPrototype, "search");
1982
+ const __velarUrlSetSearch = __velarUrlHostAccessor(__velarUrlUrlPrototype, "search", true);
1983
+ const __velarUrlHash = __velarUrlHostAccessor(__velarUrlUrlPrototype, "hash");
1984
+ const __velarUrlSetHash = __velarUrlHostAccessor(__velarUrlUrlPrototype, "hash", true);
1985
+ const __velarUrlOrigin = __velarUrlHostAccessor(__velarUrlUrlPrototype, "origin");
1986
+ const __velarUrlSearchIterator = __velarUrlApply(__velarUrlSearchParamsEntries, new __velarUrlNativeSearchParams(), []);
1987
+ const __velarUrlSearchIteratorNext = __velarUrlInheritedOperation(__velarUrlSearchIterator, "next");
1988
+ const __velarUrlMapIterator = __velarUrlApply(__velarUrlMapEntries, new __velarUrlNativeMap(), []);
1989
+ const __velarUrlMapIteratorNext = __velarUrlInheritedOperation(__velarUrlMapIterator, "next");
1990
+ const __velarUrlLocation = globalThis.location;
1991
+ const __velarUrlLocationHrefDescriptor = __velarUrlLocation && (typeof __velarUrlLocation === "object" || typeof __velarUrlLocation === "function") ? __velarUrlInheritedDescriptor(__velarUrlLocation, "href") : null;
1992
+ const __velarUrlLocationHrefGetter = __velarUrlLocationHrefDescriptor && typeof __velarUrlLocationHrefDescriptor.get === "function" ? __velarUrlLocationHrefDescriptor.get : null;
1993
+ const __velarUrlLocationHrefData = __velarUrlLocationHrefDescriptor && "value" in __velarUrlLocationHrefDescriptor ? __velarUrlLocationHrefDescriptor.value : null;
1994
+ if (typeof __velarUrlApply !== "function" || typeof __velarUrlEncodeURIComponent !== "function" || typeof __velarUrlDecodeURIComponent !== "function") throw new __velarUrlNativeTypeError("The JavaScript URL host API is unavailable");
1995
+ function __velarUrlCall(operation, receiver, arguments_) { return __velarUrlApply(operation, receiver, arguments_); }
1996
+ function urlText(value, name = "velar/url") { if (typeof value !== "string") throw new __velarUrlNativeTypeError(name + " requires a string"); if (value.length > maxUrlCodeUnits) throw new __velarUrlNativeRangeError(name + " cannot exceed 2 MiB"); return value; }
1997
+ function ownData(container, key, name) { if (container === null || typeof container !== "object") throw new __velarUrlNativeTypeError(name + " must belong to an object"); const descriptor = __velarUrlGetOwnPropertyDescriptor(container, key); if (!descriptor || !("value" in descriptor)) throw new __velarUrlNativeTypeError(name + " must be an own data field"); return descriptor.value; }
1998
+ function encodedComponentUnits(value) {
1999
+ let units = 0;
2000
+ for (let index = 0; index < value.length; index += 1) {
2001
+ const code = __velarUrlCall(__velarUrlStringCharCodeAt, value, [index]);
2002
+ if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57)
2003
+ || code === 45 || code === 95 || code === 46 || code === 33 || code === 126
2004
+ || code === 42 || code === 39 || code === 40 || code === 41) units += 1;
2005
+ else if (code < 0x80) units += 3;
2006
+ else if (code < 0x800) units += 6;
2007
+ else if (code >= 0xD800 && code <= 0xDBFF) {
2008
+ const next = __velarUrlCall(__velarUrlStringCharCodeAt, value, [index + 1]);
2009
+ if (next < 0xDC00 || next > 0xDFFF) throw new __velarUrlNativeUriError("URI malformed");
2010
+ units += 12;
2011
+ index += 1;
2012
+ } else if (code >= 0xDC00 && code <= 0xDFFF) throw new __velarUrlNativeUriError("URI malformed");
2013
+ else units += 9;
2014
+ if (units > maxUrlCodeUnits) return units;
2015
+ }
2016
+ return units;
2017
+ }
2018
+ function baseOf(base) { if (base !== "") return urlText(base, "URL base"); if (!__velarUrlLocationHrefDescriptor) return fallbackBase; const href = __velarUrlLocationHrefGetter ? __velarUrlCall(__velarUrlLocationHrefGetter, __velarUrlLocation, []) : __velarUrlLocationHrefData; return urlText(href, "Browser URL base"); }
2019
+ function urlOf(value, base = "") { return new __velarUrlNativeUrl(urlText(value), baseOf(base)); }
2020
+ function urlField(url, operation, name) { return urlText(__velarUrlCall(operation, url, []), name); }
2021
+ function urlSnapshot(url) {
2022
+ const search = urlField(url, __velarUrlSearch, "URL query");
2023
+ return __velarUrlCall(__velarUrlObjectFreeze, __velarUrlNativeObject, [{
2024
+ href: urlField(url, __velarUrlHref, "URL href"), protocol: urlField(url, __velarUrlProtocol, "URL protocol"), host: urlField(url, __velarUrlHost, "URL host"),
2025
+ hostname: urlField(url, __velarUrlHostname, "URL hostname"), port: urlField(url, __velarUrlPort, "URL port"), path: urlField(url, __velarUrlPathname, "URL path"),
2026
+ query: queryMap(search, "URL query"), hash: urlField(url, __velarUrlHash, "URL hash"), origin: urlField(url, __velarUrlOrigin, "URL origin"),
2027
+ }]);
2028
+ }
2029
+ function joinedUrlOutput(parts) {
2030
+ let units = 0;
2031
+ for (let index = 0; index < parts.length; index += 1) {
2032
+ const part = parts[index];
2033
+ if (part.length > maxUrlCodeUnits - units) throw new __velarUrlNativeRangeError("URL output cannot exceed 2 MiB");
2034
+ units += part.length;
2035
+ }
2036
+ let output = "";
2037
+ for (let index = 0; index < parts.length; index += 1) output += parts[index];
2038
+ return output;
2039
+ }
2040
+ function restore(original, url) {
2041
+ const href = urlField(url, __velarUrlHref, "URL href"), host = urlField(url, __velarUrlHost, "URL host"), path = urlField(url, __velarUrlPathname, "URL path");
2042
+ const search = urlField(url, __velarUrlSearch, "URL query"), hash = urlField(url, __velarUrlHash, "URL hash");
2043
+ if (__velarUrlCall(__velarUrlRegExpTest, __velarUrlRegExpPattern, [original])) return href;
2044
+ return __velarUrlCall(__velarUrlStringStartsWith, original, ["//"]) ? joinedUrlOutput(["//", host, path, search, hash]) : joinedUrlOutput([path, search, hash]);
2045
+ }
2046
+ function nextEntry(iterator, operation, name) { const step = __velarUrlCall(operation, iterator, []); const done = ownData(step, "done", name + " iterator result"); if (typeof done !== "boolean") throw new __velarUrlNativeTypeError(name + " iterator must return a boolean done field"); if (done) return null; const pair = ownData(step, "value", name + " iterator result"); if (!__velarUrlCall(__velarListArrayIsArray, __velarListArray, [pair]) || pair.length !== 2) throw new __velarUrlNativeTypeError(name + " iterator must return key/value pairs"); return [ownData(pair, 0, name + " key"), ownData(pair, 1, name + " value")]; }
2047
+ function queryMap(search, name) {
2048
+ search = urlText(search, name);
2049
+ const output = new __velarUrlNativeMap();
2050
+ const iterator = __velarUrlCall(__velarUrlSearchParamsEntries, new __velarUrlNativeSearchParams(search), []);
2051
+ let count = 0;
2052
+ let codeUnits = 0;
2053
+ while (true) {
2054
+ const entry = nextEntry(iterator, __velarUrlSearchIteratorNext, name);
2055
+ if (entry === null) break;
2056
+ const key = entry[0], value = entry[1];
2057
+ count += 1;
2058
+ if (count > 100000) throw new __velarUrlNativeRangeError(name + " cannot exceed 100000 fields");
2059
+ if (typeof key !== "string" || typeof value !== "string") throw new __velarUrlNativeTypeError(name + " must contain string fields");
2060
+ codeUnits += key.length + value.length;
2061
+ if (codeUnits > 2 * 1024 * 1024) throw new __velarUrlNativeRangeError(name + " cannot exceed 2 MiB");
2062
+ __velarUrlCall(__velarUrlMapSet, output, [key, value]);
2063
+ }
2064
+ return output;
2065
+ }
2066
+ function appendQueryValue(output, name, value, budget) {
2067
+ if (value == null) return;
2068
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new __velarUrlNativeTypeError("URL query value '" + name + "' must be a string, number, bool, null, or List of those values");
2069
+ if (typeof value === "number" && !__velarUrlCall(__velarUrlNumberIsFinite, __velarUrlNativeNumber, [value])) throw new __velarUrlNativeTypeError("URL query numbers must be finite");
2070
+ const text = __velarUrlCall(__velarUrlNativeString, undefined, [value]);
2071
+ budget.units += (name.length + text.length) * 9 + 2;
2072
+ if (budget.units > 2 * 1024 * 1024) throw new __velarUrlNativeRangeError("URL query output cannot exceed 2 MiB");
2073
+ __velarUrlCall(__velarUrlSearchParamsAppend, output, [name, text]);
2074
+ }
2075
+ function appendNamedValue(output, name, value, budget) { if (typeof name !== "string") throw new __velarUrlNativeTypeError("URL query names must be strings"); if (__velarUrlCall(__velarListArrayIsArray, __velarListArray, [value])) { const values = __velarRequireList(value, "URL query list"); for (let index = 0; index < values.length; index += 1) appendQueryValue(output, name, values[index], budget); } else appendQueryValue(output, name, value, budget); }
2076
+ function appendParams(params, output) {
2077
+ let mapSize = null;
2078
+ try { mapSize = __velarUrlCall(__velarUrlMapSize, params, []); } catch {}
2079
+ const budget = { units: 0 };
2080
+ if (mapSize !== null) {
2081
+ if (mapSize > 100000) throw new __velarUrlNativeRangeError("URL query values cannot exceed 100000 fields");
2082
+ const iterator = __velarUrlCall(__velarUrlMapEntries, params, []);
2083
+ for (let index = 0; index < mapSize; index += 1) {
2084
+ const entry = nextEntry(iterator, __velarUrlMapIteratorNext, "URL query Map");
2085
+ if (entry === null) throw new __velarUrlNativeTypeError("URL query Map ended before its size");
2086
+ appendNamedValue(output, entry[0], entry[1], budget);
2087
+ }
2088
+ if (nextEntry(iterator, __velarUrlMapIteratorNext, "URL query Map") !== null) throw new __velarUrlNativeTypeError("URL query Map exceeded its size");
2089
+ } else if (params && typeof params === "object" && !__velarUrlCall(__velarListArrayIsArray, __velarListArray, [params])
2090
+ && (__velarUrlGetPrototypeOf(params) === __velarUrlObjectPrototype || __velarUrlGetPrototypeOf(params) === null)
2091
+ && __velarUrlGetOwnPropertySymbols(params).length === 0) {
2092
+ const names = __velarUrlGetOwnPropertyNames(params);
2093
+ if (names.length > 100000) throw new __velarUrlNativeRangeError("URL query values cannot exceed 100000 fields");
2094
+ for (let index = 0; index < names.length; index += 1) {
2095
+ const name = names[index];
2096
+ const descriptor = __velarUrlGetOwnPropertyDescriptor(params, name);
2097
+ if (!descriptor?.enumerable || !("value" in descriptor)) throw new __velarUrlNativeTypeError("URL query record fields must be enumerable data values");
2098
+ appendNamedValue(output, name, descriptor.value, budget);
2099
+ }
2100
+ } else throw new __velarUrlNativeTypeError("URL query values require a Map or record");
2101
+ }
2102
+ export function parse(value, base = "") { return urlSnapshot(urlOf(value, base)); }
2103
+ export function join(...parts) {
2104
+ if (!parts.length) throw new __velarUrlNativeRangeError("url.join requires at least one part");
2105
+ let output = urlText(parts[0], "url.join");
2106
+ for (let index = 1; index < parts.length; index += 1) {
2107
+ const value = urlText(parts[index], "url.join");
2108
+ if (!value) continue;
2109
+ let start = 0, end = value.length;
2110
+ while (start < end && value[start] === "/") start += 1;
2111
+ while (end > start && value[end - 1] === "/") end -= 1;
2112
+ const segment = __velarUrlCall(__velarUrlStringSlice, value, [start, end]);
2113
+ const scheme = __velarUrlCall(__velarUrlStringEndsWith, output, ["://"]);
2114
+ let prefixEnd = output.length;
2115
+ while (!scheme && prefixEnd > 0 && output[prefixEnd - 1] === "/") prefixEnd -= 1;
2116
+ const prefix = scheme ? output : __velarUrlCall(__velarUrlStringSlice, output, [0, prefixEnd]);
2117
+ const separator = scheme ? "" : "/";
2118
+ if (separator.length + segment.length > maxUrlCodeUnits - prefix.length) {
2119
+ throw new __velarUrlNativeRangeError("url.join output cannot exceed 2 MiB");
2120
+ }
2121
+ output = prefix + separator + segment;
2122
+ }
2123
+ return output;
2124
+ }
2125
+ export function query(params) { const output = new __velarUrlNativeSearchParams(); appendParams(params, output); return urlText(__velarUrlCall(__velarUrlSearchParamsToString, output, []), "URL query output"); }
2126
+ export function parseQuery(value) { value = urlText(value, "parseQuery"); if (value[0] === "?") value = __velarUrlCall(__velarUrlStringSlice, value, [1]); return queryMap(value, "URL query"); }
2127
+ export function withQuery(value, params) { const url = urlOf(value); const searchParams = new __velarUrlNativeSearchParams(); appendParams(params, searchParams); const search = urlText(__velarUrlCall(__velarUrlSearchParamsToString, searchParams, []), "URL query output"); __velarUrlCall(__velarUrlSetSearch, url, [search ? "?" + search : ""]); return restore(value, url); }
2128
+ export function withHash(value, hash) { const url = urlOf(value); hash = urlText(hash, "withHash"); if (hash[0] === "#") hash = __velarUrlCall(__velarUrlStringSlice, hash, [1]); __velarUrlCall(__velarUrlSetHash, url, [hash ? "#" + hash : ""]); return restore(value, url); }
2129
+ export function isExternal(value, base = "") { value = urlText(value, "isExternal"); if (base) urlText(base, "URL base"); try { const url = urlOf(value, base); const baseUrl = new __velarUrlNativeUrl(baseOf(base)); const origin = urlField(baseUrl, __velarUrlOrigin, "URL origin"); return urlField(url, __velarUrlOrigin, "URL origin") !== origin || !__velarUrlCall(__velarUrlRegExpTest, __velarUrlHttpPattern, [urlField(url, __velarUrlProtocol, "URL protocol")]); } catch { return true; } }
2130
+ export function encode(value) { value = urlText(value, "encode"); if (encodedComponentUnits(value) > maxUrlCodeUnits) throw new __velarUrlNativeRangeError("encode output cannot exceed 2 MiB"); return urlText(__velarUrlCall(__velarUrlEncodeURIComponent, globalThis, [value]), "encode output"); }
2131
+ export function decode(value) { return urlText(__velarUrlCall(__velarUrlDecodeURIComponent, globalThis, [urlText(value, "decode")]), "decode output"); }
2132
+ export function normalize(value, base = "") { const url = urlOf(value, base); return restore(value, url); }
2133
+ `.trimStart()],
2134
+ ["velar/time", String.raw `
2135
+ const maximumDateMilliseconds = 8_640_000_000_000_000;
2136
+ const __velarTimeNativeObject = globalThis.Object;
2137
+ const __velarTimeNativeArray = globalThis.Array;
2138
+ const __velarTimeNativeNumber = globalThis.Number;
2139
+ const __velarTimeNativeString = globalThis.String;
2140
+ const __velarTimeNativeMath = globalThis.Math;
2141
+ const __velarTimeNativeDate = globalThis.Date;
2142
+ const __velarTimeNativeTypeError = globalThis.TypeError;
2143
+ const __velarTimeNativeRangeError = globalThis.RangeError;
2144
+ const __velarTimeGetOwnPropertyDescriptor = __velarTimeNativeObject.getOwnPropertyDescriptor;
2145
+ const __velarTimeGetPrototypeOf = __velarTimeNativeObject.getPrototypeOf;
2146
+ const __velarTimeApply = __velarTimeGetOwnPropertyDescriptor(globalThis.Reflect, "apply")?.value;
2147
+ function __velarTimeHostData(owner, key, kind) {
2148
+ const descriptor = __velarTimeGetOwnPropertyDescriptor(owner, key);
2149
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== kind) throw new __velarTimeNativeTypeError("The JavaScript " + key + " time API is unavailable");
2150
+ return descriptor.value;
2151
+ }
2152
+ function __velarTimeHostOperation(owner, key) { return __velarTimeHostData(owner, key, "function"); }
2153
+ function __velarTimeHostGetter(owner, key) {
2154
+ const descriptor = __velarTimeGetOwnPropertyDescriptor(owner, key);
2155
+ if (!descriptor || typeof descriptor.get !== "function") throw new __velarTimeNativeTypeError("The JavaScript " + key + " time API is unavailable");
2156
+ return descriptor.get;
2157
+ }
2158
+ function __velarTimeInheritedOperation(owner, key) {
2159
+ for (let depth = 0; owner !== null && depth < 32; depth += 1) {
2160
+ const descriptor = __velarTimeGetOwnPropertyDescriptor(owner, key);
2161
+ if (descriptor) {
2162
+ if (!("value" in descriptor) || typeof descriptor.value !== "function") throw new __velarTimeNativeTypeError("The JavaScript " + key + " time API must be a data function");
2163
+ return descriptor.value;
2164
+ }
2165
+ owner = __velarTimeGetPrototypeOf(owner);
2166
+ }
2167
+ throw new __velarTimeNativeTypeError("The JavaScript " + key + " time API is unavailable");
2168
+ }
2169
+ const __velarTimeDatePrototype = __velarTimeHostData(__velarTimeNativeDate, "prototype", "object");
2170
+ const __velarTimeIntl = __velarTimeHostData(globalThis, "Intl", "object");
2171
+ const __velarTimeDateTimeFormat = __velarTimeHostOperation(__velarTimeIntl, "DateTimeFormat");
2172
+ const __velarTimeDateTimeFormatPrototype = __velarTimeHostData(__velarTimeDateTimeFormat, "prototype", "object");
2173
+ const __velarTimeRegExpPattern = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2}))?$/u;
2174
+ const __velarTimeDigitsPattern = /^\d{1,6}$/u;
2175
+ const __velarTimeRegExpPrototype = __velarTimeGetPrototypeOf(__velarTimeRegExpPattern);
2176
+ const __velarTimeDateNow = __velarTimeHostOperation(__velarTimeNativeDate, "now");
2177
+ const __velarTimeMathAbs = __velarTimeHostOperation(__velarTimeNativeMath, "abs");
2178
+ const __velarTimeNumberIsFinite = __velarTimeHostOperation(__velarTimeNativeNumber, "isFinite");
2179
+ const __velarTimeNumberIsInteger = __velarTimeHostOperation(__velarTimeNativeNumber, "isInteger");
2180
+ const __velarTimeNumberIsSafeInteger = __velarTimeHostOperation(__velarTimeNativeNumber, "isSafeInteger");
2181
+ const __velarTimeArrayIsArray = __velarTimeHostOperation(__velarTimeNativeArray, "isArray");
2182
+ const __velarTimeObjectFreeze = __velarTimeHostOperation(__velarTimeNativeObject, "freeze");
2183
+ const __velarTimeStringPadEnd = __velarTimeHostOperation(__velarTimeHostData(__velarTimeNativeString, "prototype", "object"), "padEnd");
2184
+ const __velarTimeStringSlice = __velarTimeHostOperation(__velarTimeHostData(__velarTimeNativeString, "prototype", "object"), "slice");
2185
+ const __velarTimeRegExpExec = __velarTimeHostOperation(__velarTimeRegExpPrototype, "exec");
2186
+ const __velarTimeFormatGetter = __velarTimeHostGetter(__velarTimeDateTimeFormatPrototype, "format");
2187
+ const __velarTimeFormatToParts = __velarTimeHostOperation(__velarTimeDateTimeFormatPrototype, "formatToParts");
2188
+ const __velarTimeSetUTCFullYear = __velarTimeHostOperation(__velarTimeDatePrototype, "setUTCFullYear");
2189
+ const __velarTimeSetUTCHours = __velarTimeHostOperation(__velarTimeDatePrototype, "setUTCHours");
2190
+ const __velarTimeSetFullYear = __velarTimeHostOperation(__velarTimeDatePrototype, "setFullYear");
2191
+ const __velarTimeSetHours = __velarTimeHostOperation(__velarTimeDatePrototype, "setHours");
2192
+ const __velarTimeGetUTCFullYear = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCFullYear");
2193
+ const __velarTimeGetUTCMonth = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCMonth");
2194
+ const __velarTimeGetUTCDate = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCDate");
2195
+ const __velarTimeGetUTCHours = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCHours");
2196
+ const __velarTimeGetUTCMinutes = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCMinutes");
2197
+ const __velarTimeGetUTCSeconds = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCSeconds");
2198
+ const __velarTimeGetUTCMilliseconds = __velarTimeHostOperation(__velarTimeDatePrototype, "getUTCMilliseconds");
2199
+ const __velarTimeGetFullYear = __velarTimeHostOperation(__velarTimeDatePrototype, "getFullYear");
2200
+ const __velarTimeGetMonth = __velarTimeHostOperation(__velarTimeDatePrototype, "getMonth");
2201
+ const __velarTimeGetDate = __velarTimeHostOperation(__velarTimeDatePrototype, "getDate");
2202
+ const __velarTimeGetDay = __velarTimeHostOperation(__velarTimeDatePrototype, "getDay");
2203
+ const __velarTimeGetHours = __velarTimeHostOperation(__velarTimeDatePrototype, "getHours");
2204
+ const __velarTimeGetMinutes = __velarTimeHostOperation(__velarTimeDatePrototype, "getMinutes");
2205
+ const __velarTimeGetSeconds = __velarTimeHostOperation(__velarTimeDatePrototype, "getSeconds");
2206
+ const __velarTimeGetMilliseconds = __velarTimeHostOperation(__velarTimeDatePrototype, "getMilliseconds");
2207
+ const __velarTimeGetTime = __velarTimeHostOperation(__velarTimeDatePrototype, "getTime");
2208
+ const __velarTimeToISOString = __velarTimeHostOperation(__velarTimeDatePrototype, "toISOString");
2209
+ const __velarTimePerformanceCandidate = globalThis.performance;
2210
+ const __velarTimePerformance = typeof __velarTimePerformanceCandidate === "object" && __velarTimePerformanceCandidate !== null ? __velarTimePerformanceCandidate : null;
2211
+ const __velarTimePerformanceNow = __velarTimePerformance === null ? null : __velarTimeInheritedOperation(__velarTimePerformance, "now");
2212
+ if (typeof __velarTimeApply !== "function") throw new __velarTimeNativeTypeError("The JavaScript Reflect.apply time API is unavailable");
2213
+ function __velarTimeCall(operation, receiver, arguments_) { return __velarTimeApply(operation, receiver, arguments_); }
2214
+ function __velarTimeNumber(value) { return __velarTimeCall(__velarTimeNativeNumber, undefined, [value]); }
2215
+ function __velarTimeFreeze(value) { return __velarTimeCall(__velarTimeObjectFreeze, __velarTimeNativeObject, [value]); }
2216
+ function weekdayOf(value) {
2217
+ if (value === "Sun") return 0;
2218
+ if (value === "Mon") return 1;
2219
+ if (value === "Tue") return 2;
2220
+ if (value === "Wed") return 3;
2221
+ if (value === "Thu") return 4;
2222
+ if (value === "Fri") return 5;
2223
+ if (value === "Sat") return 6;
2224
+ return null;
2225
+ }
2226
+ function finiteNumber(value, name) { if (!__velarTimeCall(__velarTimeNumberIsFinite, __velarTimeNativeNumber, [value])) throw new __velarTimeNativeTypeError(name + " must be a finite number"); return value; }
2227
+ function valid(value) { finiteNumber(value, "velar/time timestamp"); if (__velarTimeCall(__velarTimeMathAbs, __velarTimeNativeMath, [value]) > maximumDateMilliseconds) throw new __velarTimeNativeRangeError("velar/time timestamp is outside the JavaScript date range"); return value; }
2228
+ function timeText(value, name) { if (typeof value !== "string") throw new __velarTimeNativeTypeError(name + " must be a string"); if (value.length > 1024) throw new __velarTimeNativeRangeError(name + " cannot exceed 1024 characters"); return value; }
2229
+ function timeResultText(value, name, maximum = 65536) { if (typeof value !== "string") throw new __velarTimeNativeTypeError(name + " must return a string"); if (value.length > maximum) throw new __velarTimeNativeRangeError(name + " returned too much text"); return value; }
2230
+ function ownData(container, key, name) {
2231
+ if (container === null || typeof container !== "object") throw new __velarTimeNativeTypeError(name + " must belong to an object");
2232
+ const descriptor = __velarTimeGetOwnPropertyDescriptor(container, key);
2233
+ if (!descriptor || !("value" in descriptor)) throw new __velarTimeNativeTypeError(name + " must be an own data field");
2234
+ return descriptor.value;
2235
+ }
2236
+ function boundedInteger(value, name, minimum, maximum) {
2237
+ if (!__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [value])) throw new __velarTimeNativeTypeError(name + " must be an integer");
2238
+ if (value < minimum || value > maximum) throw new __velarTimeNativeRangeError(name + " is out of range");
2239
+ return value;
2240
+ }
2241
+ function partInteger(value, name, minimum, maximum) {
2242
+ if (typeof value !== "string" || !__velarTimeCall(__velarTimeRegExpExec, __velarTimeDigitsPattern, [value])) throw new __velarTimeNativeTypeError("Time " + name + " part must be decimal text");
2243
+ return boundedInteger(__velarTimeNumber(value), "Time " + name + " part", minimum, maximum);
2244
+ }
2245
+ function daysInMonth(year, month) {
2246
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
2247
+ return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
2248
+ }
2249
+ function zonedParts(date, timeZone) {
2250
+ const formatter = new __velarTimeDateTimeFormat("en-CA", { timeZone, year: "numeric", month: "numeric", day: "numeric", weekday: "short", hour: "numeric", minute: "numeric", second: "numeric", era: "short", hourCycle: "h23" });
2251
+ const parts = __velarTimeCall(__velarTimeFormatToParts, formatter, [date]);
2252
+ if (!__velarTimeCall(__velarTimeArrayIsArray, __velarTimeNativeArray, [parts])) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat.formatToParts must return a List");
2253
+ const partCount = parts.length;
2254
+ if (!__velarTimeCall(__velarTimeNumberIsSafeInteger, __velarTimeNativeNumber, [partCount]) || partCount < 0) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned an invalid time part count");
2255
+ if (partCount > 32) throw new __velarTimeNativeRangeError("Intl.DateTimeFormat returned too many time parts");
2256
+ let yearText = null, monthText = null, dayText = null, weekdayText = null;
2257
+ let hourText = null, minuteText = null, secondText = null, era = null;
2258
+ for (let index = 0; index < partCount; index += 1) {
2259
+ const part = ownData(parts, index, "Intl time part");
2260
+ const type = ownData(part, "type", "Intl time part type");
2261
+ const value = ownData(part, "value", "Intl time part value");
2262
+ timeResultText(type, "Intl time part type", 32);
2263
+ timeResultText(value, "Intl time part value", 64);
2264
+ if (type === "literal") continue;
2265
+ if (type === "year") { if (yearText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate year part"); yearText = value; }
2266
+ else if (type === "month") { if (monthText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate month part"); monthText = value; }
2267
+ else if (type === "day") { if (dayText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate day part"); dayText = value; }
2268
+ else if (type === "weekday") { if (weekdayText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate weekday part"); weekdayText = value; }
2269
+ else if (type === "hour") { if (hourText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate hour part"); hourText = value; }
2270
+ else if (type === "minute") { if (minuteText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate minute part"); minuteText = value; }
2271
+ else if (type === "second") { if (secondText !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate second part"); secondText = value; }
2272
+ else if (type === "era") { if (era !== null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned a duplicate era part"); era = value; }
2273
+ else throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned an unsupported time part");
2274
+ }
2275
+ if (yearText === null || monthText === null || dayText === null || weekdayText === null || hourText === null || minuteText === null || secondText === null || era === null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat omitted a required time part");
2276
+ if (era !== "AD" && era !== "BC") throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned an unsupported era");
2277
+ const displayedYear = partInteger(yearText, "year", 1, 999999);
2278
+ const year = era === "BC" ? 1 - displayedYear : displayedYear;
2279
+ const month = partInteger(monthText, "month", 1, 12);
2280
+ const day = partInteger(dayText, "day", 1, 31);
2281
+ if (day > daysInMonth(year, month)) throw new __velarTimeNativeRangeError("Intl.DateTimeFormat returned an impossible calendar date");
2282
+ const weekday = weekdayOf(weekdayText);
2283
+ if (weekday === null) throw new __velarTimeNativeTypeError("Intl.DateTimeFormat returned an unsupported weekday");
2284
+ return __velarTimeFreeze({
2285
+ year,
2286
+ month,
2287
+ day,
2288
+ weekday,
2289
+ hour: partInteger(hourText, "hour", 0, 23),
2290
+ minute: partInteger(minuteText, "minute", 0, 59),
2291
+ second: partInteger(secondText, "second", 0, 59),
2292
+ millisecond: boundedInteger(__velarTimeCall(__velarTimeGetUTCMilliseconds, date, []), "Time millisecond part", 0, 999),
2293
+ });
2294
+ }
2295
+ function calendarParts(year, month, day, hour = 0, minute = 0, second = 0, millisecond = 0) {
2296
+ if (!__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [year])
2297
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [month])
2298
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [day])
2299
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [hour])
2300
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [minute])
2301
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [second])
2302
+ || !__velarTimeCall(__velarTimeNumberIsInteger, __velarTimeNativeNumber, [millisecond])) throw new __velarTimeNativeTypeError("velar/time date parts must be integers");
2303
+ if (year < 0 || year > 9999) throw new __velarTimeNativeRangeError("velar/time year must be from 0 through 9999");
2304
+ if (month < 1 || month > 12) throw new __velarTimeNativeRangeError("velar/time month must be from 1 through 12");
2305
+ if (day < 1 || day > 31) throw new __velarTimeNativeRangeError("velar/time day is outside the selected month");
2306
+ if (hour < 0 || hour > 23) throw new __velarTimeNativeRangeError("velar/time hour must be from 0 through 23");
2307
+ if (minute < 0 || minute > 59 || second < 0 || second > 59) throw new __velarTimeNativeRangeError("velar/time minute and second must be from 0 through 59");
2308
+ if (millisecond < 0 || millisecond > 999) throw new __velarTimeNativeRangeError("velar/time millisecond must be from 0 through 999");
2309
+ return [year, month, day, hour, minute, second, millisecond];
2310
+ }
2311
+ function build(utc, year, month, day, hour = 0, minute = 0, second = 0, millisecond = 0) {
2312
+ calendarParts(year, month, day, hour, minute, second, millisecond);
2313
+ const value = new __velarTimeNativeDate(0);
2314
+ if (utc) {
2315
+ __velarTimeCall(__velarTimeSetUTCFullYear, value, [year, month - 1, day]);
2316
+ __velarTimeCall(__velarTimeSetUTCHours, value, [hour, minute, second, millisecond]);
2317
+ if (__velarTimeCall(__velarTimeGetUTCFullYear, value, []) !== year || __velarTimeCall(__velarTimeGetUTCMonth, value, []) !== month - 1 || __velarTimeCall(__velarTimeGetUTCDate, value, []) !== day
2318
+ || __velarTimeCall(__velarTimeGetUTCHours, value, []) !== hour || __velarTimeCall(__velarTimeGetUTCMinutes, value, []) !== minute || __velarTimeCall(__velarTimeGetUTCSeconds, value, []) !== second || __velarTimeCall(__velarTimeGetUTCMilliseconds, value, []) !== millisecond) {
2319
+ throw new __velarTimeNativeRangeError("velar/time date parts do not form a real UTC date");
2320
+ }
2321
+ } else {
2322
+ __velarTimeCall(__velarTimeSetFullYear, value, [year, month - 1, day]);
2323
+ __velarTimeCall(__velarTimeSetHours, value, [hour, minute, second, millisecond]);
2324
+ if (__velarTimeCall(__velarTimeGetFullYear, value, []) !== year || __velarTimeCall(__velarTimeGetMonth, value, []) !== month - 1 || __velarTimeCall(__velarTimeGetDate, value, []) !== day
2325
+ || __velarTimeCall(__velarTimeGetHours, value, []) !== hour || __velarTimeCall(__velarTimeGetMinutes, value, []) !== minute || __velarTimeCall(__velarTimeGetSeconds, value, []) !== second || __velarTimeCall(__velarTimeGetMilliseconds, value, []) !== millisecond) {
2326
+ throw new __velarTimeNativeRangeError("velar/time date parts do not form a real local date");
2327
+ }
2328
+ }
2329
+ return valid(__velarTimeCall(__velarTimeGetTime, value, []));
2330
+ }
2331
+ export function now() { return valid(__velarTimeCall(__velarTimeDateNow, __velarTimeNativeDate, [])); }
2332
+ export function monotonic() { return __velarTimePerformance === null ? now() : finiteNumber(__velarTimeCall(__velarTimePerformanceNow, __velarTimePerformance, []), "velar/time monotonic clock"); }
2333
+ export function parse(value) {
2334
+ if (typeof value !== "string") throw new __velarTimeNativeTypeError("velar/time parse requires an ISO string");
2335
+ if (value.length > 64) return null;
2336
+ const match = __velarTimeCall(__velarTimeRegExpExec, __velarTimeRegExpPattern, [value]);
2337
+ if (!match) return null;
2338
+ try {
2339
+ const year = __velarTimeNumber(match[1]), month = __velarTimeNumber(match[2]), day = __velarTimeNumber(match[3]);
2340
+ if (!match[4]) return build(true, year, month, day);
2341
+ const hour = __velarTimeNumber(match[4]), minute = __velarTimeNumber(match[5]), second = __velarTimeNumber(match[6] ?? 0);
2342
+ const millisecond = __velarTimeNumber(__velarTimeCall(__velarTimeStringPadEnd, match[7] ?? "", [3, "0"]) || 0);
2343
+ const zone = match[8];
2344
+ let offset = 0;
2345
+ if (zone !== "Z") {
2346
+ const sign = zone[0] === "+" ? 1 : -1;
2347
+ const offsetHour = __velarTimeNumber(__velarTimeCall(__velarTimeStringSlice, zone, [1, 3]));
2348
+ const offsetMinute = __velarTimeNumber(__velarTimeCall(__velarTimeStringSlice, zone, [4, 6]));
2349
+ if (offsetHour > 23 || offsetMinute > 59) return null;
2350
+ offset = sign * (offsetHour * 60 + offsetMinute);
2351
+ }
2352
+ return valid(build(true, year, month, day, hour, minute, second, millisecond) - offset * 60_000);
2353
+ } catch { return null; }
2354
+ }
2355
+ export function iso(value = now()) { const date = new __velarTimeNativeDate(valid(value)); return timeResultText(__velarTimeCall(__velarTimeToISOString, date, []), "Date.toISOString", 64); }
2356
+ export function format(value, locale = "", timeZone = "") { locale = timeText(locale, "Time locale"); timeZone = timeText(timeZone, "Time zone"); const formatter = new __velarTimeDateTimeFormat(locale || undefined, timeZone ? { dateStyle: "medium", timeStyle: "medium", timeZone } : { dateStyle: "medium", timeStyle: "medium" }); const boundFormat = __velarTimeCall(__velarTimeFormatGetter, formatter, []); if (typeof boundFormat !== "function") throw new __velarTimeNativeTypeError("Intl.DateTimeFormat.format must be a function"); const output = __velarTimeCall(boundFormat, undefined, [new __velarTimeNativeDate(valid(value))]); return timeResultText(output, "Intl.DateTimeFormat.format"); }
2357
+ export function date(year, month, day, hour = 0, minute = 0, second = 0) { return build(false, year, month, day, hour, minute, second); }
2358
+ export function utc(year, month, day, hour = 0, minute = 0, second = 0) { return build(true, year, month, day, hour, minute, second); }
2359
+ export function parts(value, timeZone = "") {
2360
+ const date = new __velarTimeNativeDate(valid(value));
2361
+ timeZone = timeText(timeZone, "Time zone");
2362
+ if (!timeZone) return __velarTimeFreeze({
2363
+ year: boundedInteger(__velarTimeCall(__velarTimeGetFullYear, date, []), "Time year part", -271821, 275760),
2364
+ month: boundedInteger(__velarTimeCall(__velarTimeGetMonth, date, []) + 1, "Time month part", 1, 12),
2365
+ day: boundedInteger(__velarTimeCall(__velarTimeGetDate, date, []), "Time day part", 1, 31),
2366
+ weekday: boundedInteger(__velarTimeCall(__velarTimeGetDay, date, []), "Time weekday part", 0, 6),
2367
+ hour: boundedInteger(__velarTimeCall(__velarTimeGetHours, date, []), "Time hour part", 0, 23),
2368
+ minute: boundedInteger(__velarTimeCall(__velarTimeGetMinutes, date, []), "Time minute part", 0, 59),
2369
+ second: boundedInteger(__velarTimeCall(__velarTimeGetSeconds, date, []), "Time second part", 0, 59),
2370
+ millisecond: boundedInteger(__velarTimeCall(__velarTimeGetMilliseconds, date, []), "Time millisecond part", 0, 999),
2371
+ });
2372
+ return zonedParts(date, timeZone);
2373
+ }
2374
+ `.trimStart()],
2375
+ ["velar/id", String.raw `
2376
+ ${VELAR_ERROR_NORMALIZATION_RUNTIME}
2377
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
2378
+ const __velarIdNativeTypeError = globalThis.TypeError;
2379
+ const __velarIdGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2380
+ const __velarIdGetPrototypeOf = Object.getPrototypeOf;
2381
+ const __velarIdRegExpPrototype = __velarIdGetPrototypeOf(uuidPattern);
2382
+ const __velarIdRegExpTest = __velarIdGetOwnPropertyDescriptor(__velarIdRegExpPrototype, "test")?.value;
2383
+ const __velarIdCrypto = globalThis.crypto;
2384
+ let __velarIdRandomUuid = null;
2385
+ let __velarIdCapabilityFailure = null;
2386
+
2387
+ if (!__velarIdCrypto || typeof __velarIdCrypto !== "object") {
2388
+ __velarIdCapabilityFailure = new __velarErrorNativeError("Secure UUID generation is unavailable in this JavaScript host");
2389
+ } else {
2390
+ let owner = __velarIdCrypto;
2391
+ for (let depth = 0; owner !== null && depth < 32; depth += 1) {
2392
+ const descriptor = __velarIdGetOwnPropertyDescriptor(owner, "randomUUID");
2393
+ if (descriptor) {
2394
+ if (!("value" in descriptor) || typeof descriptor.value !== "function") {
2395
+ __velarIdCapabilityFailure = new __velarIdNativeTypeError("crypto.randomUUID must be a data function");
2396
+ } else __velarIdRandomUuid = descriptor.value;
2397
+ break;
2398
+ }
2399
+ owner = __velarIdGetPrototypeOf(owner);
2400
+ }
2401
+ if (!__velarIdRandomUuid && !__velarIdCapabilityFailure) {
2402
+ __velarIdCapabilityFailure = new __velarErrorNativeError("Secure UUID generation is unavailable in this JavaScript host");
2403
+ }
2404
+ }
2405
+
2406
+ export function uuid() {
2407
+ if (__velarIdCapabilityFailure) throw __velarIdCapabilityFailure;
2408
+ let value;
2409
+ try { value = __velarErrorApply(__velarIdRandomUuid, __velarIdCrypto, [], "crypto.randomUUID"); }
2410
+ catch (failure) { if (__velarIsError(failure)) throw failure; throw new __velarErrorNativeError("Secure UUID generation failed", { cause: failure }); }
2411
+ if (!isUuid(value)) throw new __velarErrorNativeError("Secure UUID generation returned an invalid UUID");
2412
+ return value;
2413
+ }
2414
+
2415
+ export function isUuid(value) {
2416
+ return typeof value === "string" && value.length === 36
2417
+ && __velarErrorApply(__velarIdRegExpTest, uuidPattern, [value], "RegExp.test");
2418
+ }
2419
+ `.trimStart()],
2420
+ ["velar/log", String.raw `
2421
+ ${VELAR_ERROR_NORMALIZATION_RUNTIME}
2422
+ const __velarLogNativeMap = globalThis.Map;
2423
+ const __velarLogNativeSet = globalThis.Set;
2424
+ const __velarLogNativeObject = globalThis.Object;
2425
+ const __velarLogNativeDate = globalThis.Date;
2426
+ const __velarLogNativeNumber = globalThis.Number;
2427
+ const __velarLogNativeMath = globalThis.Math;
2428
+ const __velarLogNativeTypeError = globalThis.TypeError;
2429
+ const __velarLogNativeRangeError = globalThis.RangeError;
2430
+ const __velarLogGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2431
+ const __velarLogGetPrototypeOf = Object.getPrototypeOf;
2432
+ const __velarLogDefineProperty = Object.defineProperty;
2433
+ const __velarLogCreateObject = Object.create;
2434
+ const __velarLogObjectPrototype = Object.prototype;
2435
+ const __velarLogFreeze = __velarLogGetOwnPropertyDescriptor(Object, "freeze")?.value;
2436
+ const __velarLogDateNow = __velarLogGetOwnPropertyDescriptor(Date, "now")?.value;
2437
+ const __velarLogNumberIsFinite = __velarLogGetOwnPropertyDescriptor(Number, "isFinite")?.value;
2438
+ const __velarLogMathAbs = __velarLogGetOwnPropertyDescriptor(Math, "abs")?.value;
2439
+ const __velarLogStringTrim = __velarLogGetOwnPropertyDescriptor(String.prototype, "trim")?.value;
2440
+ const __velarLogStringToLowerCase = __velarLogGetOwnPropertyDescriptor(String.prototype, "toLowerCase")?.value;
2441
+ const __velarLogPromiseThen = __velarLogGetOwnPropertyDescriptor(Promise.prototype, "then")?.value;
2442
+ const __velarLogMapSize = __velarLogGetOwnPropertyDescriptor(__velarLogNativeMap.prototype, "size")?.get;
2443
+ const __velarLogMapEntries = __velarLogGetOwnPropertyDescriptor(__velarLogNativeMap.prototype, "entries")?.value;
2444
+ const __velarLogMapHas = __velarLogGetOwnPropertyDescriptor(__velarLogNativeMap.prototype, "has")?.value;
2445
+ const __velarLogMapSet = __velarLogGetOwnPropertyDescriptor(__velarLogNativeMap.prototype, "set")?.value;
2446
+ const __velarLogSetSize = __velarLogGetOwnPropertyDescriptor(__velarLogNativeSet.prototype, "size")?.get;
2447
+ const __velarLogSetValues = __velarLogGetOwnPropertyDescriptor(__velarLogNativeSet.prototype, "values")?.value;
2448
+ const __velarLogSetHas = __velarLogGetOwnPropertyDescriptor(__velarLogNativeSet.prototype, "has")?.value;
2449
+ const __velarLogSetAdd = __velarLogGetOwnPropertyDescriptor(__velarLogNativeSet.prototype, "add")?.value;
2450
+ const __velarLogSetDelete = __velarLogGetOwnPropertyDescriptor(__velarLogNativeSet.prototype, "delete")?.value;
2451
+ const __velarLogMapIteratorNext = __velarLogGetOwnPropertyDescriptor(__velarLogGetPrototypeOf(__velarErrorApply(__velarLogMapEntries, new __velarLogNativeMap(), [], "Map.entries")), "next")?.value;
2452
+ const __velarLogSetIteratorNext = __velarLogGetOwnPropertyDescriptor(__velarLogGetPrototypeOf(__velarErrorApply(__velarLogSetValues, new __velarLogNativeSet(), [], "Set.values")), "next")?.value;
2453
+ const __velarLogConsoleDescriptor = __velarLogGetOwnPropertyDescriptor(globalThis, "console");
2454
+ const __velarLogConsoleTarget = __velarLogConsoleDescriptor && "value" in __velarLogConsoleDescriptor
2455
+ && __velarLogConsoleDescriptor.value !== null && typeof __velarLogConsoleDescriptor.value === "object"
2456
+ ? __velarLogConsoleDescriptor.value : null;
2457
+ const __velarLogConsoleMethods = __velarLogConsoleTarget === null ? null : __velarLogFreezeValue({
2458
+ debug: __velarLogHostMethod(__velarLogConsoleTarget, "debug"),
2459
+ info: __velarLogHostMethod(__velarLogConsoleTarget, "info"),
2460
+ warn: __velarLogHostMethod(__velarLogConsoleTarget, "warn"),
2461
+ error: __velarLogHostMethod(__velarLogConsoleTarget, "error"),
2462
+ log: __velarLogHostMethod(__velarLogConsoleTarget, "log"),
2463
+ });
2464
+ let threshold = "info";
2465
+ const sinks = new __velarLogNativeSet();
2466
+ const maxLogFields = 1000;
2467
+ const maxLogSinks = 1000;
2468
+ const maximumLogTimestamp = 8_640_000_000_000_000;
2469
+
2470
+ function __velarLogApply(operation, receiver, arguments_, label) { return __velarErrorApply(operation, receiver, arguments_, label); }
2471
+ function __velarLogFreezeValue(value) { return __velarLogApply(__velarLogFreeze, __velarLogNativeObject, [value], "Object.freeze"); }
2472
+ function __velarLogMapValue(map, operation, arguments_, label) { return __velarLogApply(operation, map, arguments_, label); }
2473
+ function __velarLogSetValue(set, operation, arguments_, label) { return __velarLogApply(operation, set, arguments_, label); }
2474
+ function __velarLogCreateMap() { return new __velarLogNativeMap(); }
2475
+ function __velarLogMapCount(map) { return __velarLogMapValue(map, __velarLogMapSize, [], "Map.size"); }
2476
+ function __velarLogMapItems(map) {
2477
+ const iterator = __velarLogMapValue(map, __velarLogMapEntries, [], "Map.entries");
2478
+ const output = [];
2479
+ while (true) {
2480
+ const step = __velarLogApply(__velarLogMapIteratorNext, iterator, [], "Map iterator next");
2481
+ if (step.done) return output;
2482
+ output[output.length] = step.value;
2483
+ }
2484
+ }
2485
+ function __velarLogSetItems(set) {
2486
+ const iterator = __velarLogSetValue(set, __velarLogSetValues, [], "Set.values");
2487
+ const output = [];
2488
+ while (true) {
2489
+ const step = __velarLogApply(__velarLogSetIteratorNext, iterator, [], "Set iterator next");
2490
+ if (step.done) return output;
2491
+ output[output.length] = step.value;
2492
+ }
2493
+ }
2494
+ function __velarLogCloneMap(value) {
2495
+ const output = __velarLogCreateMap();
2496
+ const items = __velarLogMapItems(value);
2497
+ for (let index = 0; index < items.length; index += 1) {
2498
+ const pair = items[index];
2499
+ __velarLogMapValue(output, __velarLogMapSet, [pair[0], pair[1]], "Map.set");
2500
+ }
2501
+ return output;
2502
+ }
2503
+ function __velarLogHostMethod(target, name) {
2504
+ let owner = target;
2505
+ for (let depth = 0; owner !== null && depth < 32; depth += 1) {
2506
+ const descriptor = __velarLogGetOwnPropertyDescriptor(owner, name);
2507
+ if (descriptor) {
2508
+ if (!("value" in descriptor) || typeof descriptor.value !== "function") throw new __velarLogNativeTypeError("Host console method " + name + " must be a data function");
2509
+ return descriptor.value;
2510
+ }
2511
+ owner = __velarLogGetPrototypeOf(owner);
2512
+ }
2513
+ return null;
2514
+ }
2515
+ function __velarLogFieldsObject(fields) {
2516
+ const output = __velarLogApply(__velarLogCreateObject, __velarLogNativeObject, [__velarLogObjectPrototype], "Object.create");
2517
+ const items = __velarLogMapItems(fields);
2518
+ for (let index = 0; index < items.length; index += 1) {
2519
+ const pair = items[index];
2520
+ __velarLogApply(__velarLogDefineProperty, __velarLogNativeObject, [output, pair[0], { value: pair[1], enumerable: true, configurable: true, writable: true }], "Object.defineProperty");
2521
+ }
2522
+ return output;
2523
+ }
2524
+ function logText(value, name, maximum = 65536) { if (typeof value !== "string") throw new __velarLogNativeTypeError(name + " must be a string"); if (value.length > maximum) throw new __velarLogNativeRangeError(name + " is too long"); return value; }
2525
+ function logTimestamp() {
2526
+ const value = __velarLogApply(__velarLogDateNow, __velarLogNativeDate, [], "Date.now");
2527
+ if (!__velarLogApply(__velarLogNumberIsFinite, __velarLogNativeNumber, [value], "Number.isFinite")) throw new __velarLogNativeTypeError("The host clock must return a finite timestamp");
2528
+ if (__velarLogApply(__velarLogMathAbs, __velarLogNativeMath, [value], "Math.abs") > maximumLogTimestamp) throw new __velarLogNativeRangeError("The host clock returned a timestamp outside the JavaScript date range");
2529
+ return value;
2530
+ }
2531
+
2532
+ function fieldsOf(value) {
2533
+ if (value == null) return __velarLogCreateMap();
2534
+ let size;
2535
+ try { size = __velarLogMapCount(value); }
2536
+ catch { throw new __velarLogNativeTypeError("VelarScript log fields must be a Map"); }
2537
+ if (size > maxLogFields) throw new __velarLogNativeRangeError("VelarScript log fields cannot exceed 1000 entries");
2538
+ const fields = __velarLogCreateMap();
2539
+ const items = __velarLogMapItems(value);
2540
+ for (let index = 0; index < items.length; index += 1) {
2541
+ const pair = items[index];
2542
+ const key = pair[0];
2543
+ if (typeof key !== "string") throw new __velarLogNativeTypeError("VelarScript log field names must be strings");
2544
+ if (key.length > 1024) throw new __velarLogNativeRangeError("VelarScript log field names cannot exceed 1024 characters");
2545
+ __velarLogMapValue(fields, __velarLogMapSet, [key, pair[1]], "Map.set");
2546
+ }
2547
+ return fields;
2548
+ }
2549
+
2550
+ function defaultSink(record) {
2551
+ if (!__velarLogConsoleDescriptor) return;
2552
+ if (__velarLogConsoleTarget === null) throw new __velarLogNativeTypeError("Host console must be an own data object");
2553
+ const write = __velarLogConsoleMethods[record.level] ?? __velarLogConsoleMethods.log;
2554
+ if (!write) throw new __velarLogNativeTypeError("Host console must provide a callable log method");
2555
+ __velarLogApply(write, __velarLogConsoleTarget, [record.scope ? "[" + record.scope + "] " + record.message : record.message, __velarLogFieldsObject(record.fields), record.error ?? ""], "console writer");
2556
+ }
2557
+
2558
+ function sinkFailure(value) {
2559
+ const error = __velarNormalizeError(value);
2560
+ defaultSink(__velarLogFreezeValue({ timestamp: logTimestamp(), level: "error", scope: "velar/log", message: "Log sink failed", fields: __velarLogCreateMap(), error }));
2561
+ }
2562
+ function observeSinkResult(value) {
2563
+ try { __velarLogApply(__velarLogPromiseThen, value, [undefined, sinkFailure], "Promise.then"); }
2564
+ catch { /* Non-Promise sink results are intentionally ignored. */ }
2565
+ }
2566
+
2567
+ function emit(scope, level, message, fields, error = null) {
2568
+ message = logText(message, "Log message");
2569
+ fields = fieldsOf(fields);
2570
+ if (error != null && !__velarIsError(error)) throw new __velarLogNativeTypeError("Logger error must be an Error");
2571
+ if (__velarLogRank(level) < __velarLogRank(threshold)) return null;
2572
+ const record = __velarLogFreezeValue({ timestamp: logTimestamp(), level, scope, message, fields, error });
2573
+ if (__velarLogSetValue(sinks, __velarLogSetSize, [], "Set.size") === 0) defaultSink(record);
2574
+ else {
2575
+ const activeSinks = __velarLogSetItems(sinks);
2576
+ for (let index = 0; index < activeSinks.length; index += 1) {
2577
+ const sink = activeSinks[index];
2578
+ try {
2579
+ const delivered = __velarLogFreezeValue({ timestamp: record.timestamp, level: record.level, scope: record.scope, message: record.message, fields: __velarLogCloneMap(record.fields), error: record.error });
2580
+ const result = sink(delivered);
2581
+ observeSinkResult(result);
2582
+ } catch (failure) { sinkFailure(failure); }
2583
+ }
2584
+ }
2585
+ return null;
2586
+ }
2587
+
2588
+ function __velarLogRank(value) {
2589
+ if (value === "debug") return 10;
2590
+ if (value === "info") return 20;
2591
+ if (value === "warn") return 30;
2592
+ if (value === "error") return 40;
2593
+ if (value === "silent") return 100;
2594
+ return 100;
2595
+ }
2596
+ function createLogger(scope, base = null) {
2597
+ const context = fieldsOf(base);
2598
+ const merged = (fields) => {
2599
+ const output = __velarLogCloneMap(context);
2600
+ const items = __velarLogMapItems(fieldsOf(fields));
2601
+ for (let index = 0; index < items.length; index += 1) {
2602
+ const pair = items[index];
2603
+ const key = pair[0];
2604
+ if (!__velarLogMapValue(output, __velarLogMapHas, [key], "Map.has") && __velarLogMapCount(output) >= maxLogFields) throw new __velarLogNativeRangeError("Merged log fields cannot exceed 1000 entries");
2605
+ __velarLogMapValue(output, __velarLogMapSet, [key, pair[1]], "Map.set");
2606
+ }
2607
+ return output;
2608
+ };
2609
+ return __velarLogFreezeValue({
2610
+ debug(message, fields = null) { return emit(scope, "debug", message, merged(fields)); },
2611
+ info(message, fields = null) { return emit(scope, "info", message, merged(fields)); },
2612
+ warn(message, fields = null) { return emit(scope, "warn", message, merged(fields)); },
2613
+ error(message, error = null, fields = null) { return emit(scope, "error", message, merged(fields), error); },
2614
+ });
2615
+ }
2616
+
2617
+ function __velarLogRecordField(value, name) {
2618
+ const descriptor = __velarLogGetOwnPropertyDescriptor(value, name);
2619
+ if (!descriptor?.enumerable || !("value" in descriptor)) throw new __velarLogNativeTypeError("Value does not match LogRecord");
2620
+ return descriptor.value;
2621
+ }
2622
+ function __velarLogRecordValue(value) {
2623
+ if (!value || typeof value !== "object" || __velarLogGetPrototypeOf(value) !== __velarLogObjectPrototype) {
2624
+ throw new __velarLogNativeTypeError("Value does not match LogRecord");
2625
+ }
2626
+ const timestamp = __velarLogRecordField(value, "timestamp");
2627
+ if (typeof timestamp !== "number"
2628
+ || !__velarLogApply(__velarLogNumberIsFinite, __velarLogNativeNumber, [timestamp], "Number.isFinite")
2629
+ || __velarLogApply(__velarLogMathAbs, __velarLogNativeMath, [timestamp], "Math.abs") > maximumLogTimestamp) {
2630
+ throw new __velarLogNativeTypeError("Value does not match LogRecord");
2631
+ }
2632
+ const level = __velarLogRecordField(value, "level");
2633
+ if (level !== "debug" && level !== "info" && level !== "warn" && level !== "error") {
2634
+ throw new __velarLogNativeTypeError("Value does not match LogRecord");
2635
+ }
2636
+ logText(__velarLogRecordField(value, "scope"), "LogRecord scope", 1024);
2637
+ logText(__velarLogRecordField(value, "message"), "LogRecord message");
2638
+ const error = __velarLogRecordField(value, "error");
2639
+ if (error !== null && !__velarIsError(error)) throw new __velarLogNativeTypeError("Value does not match LogRecord");
2640
+ const fields = __velarLogRecordField(value, "fields");
2641
+ if (fields == null) throw new __velarLogNativeTypeError("Value does not match LogRecord");
2642
+ fieldsOf(fields);
2643
+ return value;
2644
+ }
2645
+
2646
+ // D59 rule 145.3 and D65 rule 171: the record 'useSink' hands to a sink now
2647
+ // has a published name, so a sink can be a named 'def' with an annotated
2648
+ // parameter. An exported type name is a runtime value in VelarScript — the
2649
+ // emitter proves it for every 'export type' — so the name ships the same
2650
+ // frozen 'is'/'parse' pair 'velar/fs' publishes for FileWatchBatch.
2651
+ export const LogRecord = __velarLogFreezeValue({
2652
+ is(value) { try { __velarLogRecordValue(value); return true; } catch { return false; } },
2653
+ parse(value) { return __velarLogRecordValue(value); },
2654
+ });
2655
+
2656
+ export const log = createLogger("");
2657
+ export function logger(scope, fields = null) {
2658
+ const name = __velarLogApply(__velarLogStringTrim, logText(scope, "Logger scope", 1024), [], "String.trim");
2659
+ if (!name) throw new __velarLogNativeTypeError("A VelarScript logger requires a non-empty scope");
2660
+ return createLogger(name, fields);
2661
+ }
2662
+ export function level() { return threshold; }
2663
+ export function setLevel(value) {
2664
+ const next = __velarLogApply(__velarLogStringToLowerCase, logText(value, "Log level"), [], "String.toLowerCase");
2665
+ if (next !== "debug" && next !== "info" && next !== "warn" && next !== "error" && next !== "silent") throw new __velarLogNativeTypeError("Log level must be debug, info, warn, error, or silent");
2666
+ threshold = next;
2667
+ return null;
2668
+ }
2669
+ export function useSink(sink) {
2670
+ if (typeof sink !== "function") throw new __velarLogNativeTypeError("A VelarScript log sink must be callable");
2671
+ if (!__velarLogSetValue(sinks, __velarLogSetHas, [sink], "Set.has") && __velarLogSetValue(sinks, __velarLogSetSize, [], "Set.size") >= maxLogSinks) throw new __velarLogNativeRangeError("VelarScript logging cannot install more than 1000 sinks");
2672
+ __velarLogSetValue(sinks, __velarLogSetAdd, [sink], "Set.add");
2673
+ return () => { __velarLogSetValue(sinks, __velarLogSetDelete, [sink], "Set.delete"); return null; };
2674
+ }
2675
+ `.trimStart()],
2676
+ ["velar/test", String.raw `
2677
+ ${collectionLoweringImport}
2678
+ ${testDisplayRuntime}
2679
+ const __velarTestNativeString = globalThis.String;
2680
+ const __velarTestNativeNumber = globalThis.Number;
2681
+ const __velarTestNativePromise = globalThis.Promise;
2682
+ const __velarTestNativeJSON = globalThis.JSON;
2683
+ const __velarTestNativeMath = globalThis.Math;
2684
+ const __velarTestNativeError = globalThis.Error;
2685
+ const __velarTestNativeTypeError = globalThis.TypeError;
2686
+ const __velarTestNativeRangeError = globalThis.RangeError;
2687
+ const __velarTestFreeze = __velarDeepGetOwnPropertyDescriptor(__velarDeepNativeObject, "freeze")?.value;
2688
+ const __velarTestStringPrototype = __velarDeepGetOwnPropertyDescriptor(__velarTestNativeString, "prototype")?.value;
2689
+ const __velarTestStringSlice = __velarDeepGetOwnPropertyDescriptor(__velarTestStringPrototype, "slice")?.value;
2690
+ const __velarTestStringIncludes = __velarDeepGetOwnPropertyDescriptor(__velarTestStringPrototype, "includes")?.value;
2691
+ const __velarTestArrayJoin = __velarDeepGetOwnPropertyDescriptor(__velarDeepArrayPrototype, "join")?.value;
2692
+ const __velarTestNumberIsSafeInteger = __velarDeepGetOwnPropertyDescriptor(__velarTestNativeNumber, "isSafeInteger")?.value;
2693
+ const __velarTestJsonStringify = __velarDeepGetOwnPropertyDescriptor(__velarTestNativeJSON, "stringify")?.value;
2694
+ const __velarTestMathMin = __velarDeepGetOwnPropertyDescriptor(__velarTestNativeMath, "min")?.value;
2695
+ const __velarTestPromisePrototype = __velarDeepGetOwnPropertyDescriptor(__velarTestNativePromise, "prototype")?.value;
2696
+ const __velarTestPromiseThen = __velarDeepGetOwnPropertyDescriptor(__velarTestPromisePrototype, "then")?.value;
2697
+ const __velarTestRegExpPrototype = __velarDeepGetPrototypeOf(/(?:)/u);
2698
+ const __velarTestNativeRegExp = __velarDeepGetOwnPropertyDescriptor(__velarTestRegExpPrototype, "constructor")?.value;
2699
+ const __velarTestRegExpExec = __velarDeepGetOwnPropertyDescriptor(__velarTestRegExpPrototype, "exec")?.value;
2700
+ function __velarTestAppend(items, value) { items[items.length] = value; }
2701
+ function __velarTestJoin(items) { return __velarDeepCall(__velarTestArrayJoin, items, [", "]); }
2702
+ function __velarTestString(value) { return __velarDeepCall(__velarTestNativeString, undefined, [value]); }
2703
+ function display(value, state = null) {
2704
+ state ??= { active: new __velarDeepNativeWeakSet(), nodes: 0, depth: 0 };
2705
+ state.nodes += 1;
2706
+ if (state.nodes > 1000) return "…";
2707
+ if (value === null) return "null";
2708
+ if (typeof value === "string") return __velarDeepCall(__velarTestJsonStringify, __velarTestNativeJSON, [value.length > 256 ? __velarDeepCall(__velarTestStringSlice, value, [0, 256]) + "…" : value]);
2709
+ if (typeof value === "function") return "[function]";
2710
+ if (typeof value === "undefined") return "undefined";
2711
+ if (typeof value === "symbol") return "[symbol]";
2712
+ if (typeof value !== "object") return __velarTestString(value);
2713
+ if (__velarDeepCall(__velarDeepWeakSetHas, state.active, [value])) return "[cycle]";
2714
+ if (state.depth >= 16) return "[depth]";
2715
+ __velarDeepCall(__velarDeepWeakSetAdd, state.active, [value]);
2716
+ state.depth += 1;
2717
+ try {
2718
+ if (__velarDeepCall(__velarDeepArrayIsArray, __velarDeepNativeArray, [value])) {
2719
+ if (!__velarDenseList(value)) return "[invalid List]";
2720
+ const items = [];
2721
+ const limit = __velarDeepCall(__velarTestMathMin, __velarTestNativeMath, [value.length, 50]);
2722
+ for (let index = 0; index < limit; index += 1) __velarTestAppend(items, display(__velarDeepGetOwnPropertyDescriptor(value, index).value, state));
2723
+ if (value.length > limit) __velarTestAppend(items, "…");
2724
+ return "[" + __velarTestJoin(items) + "]";
2725
+ }
2726
+ if (__velarMapSize(value) !== null) {
2727
+ const items = [];
2728
+ const iterator = __velarDeepCall(__velarDeepMapEntries, value, []);
2729
+ while (true) {
2730
+ const entry = __velarDeepIteratorValue(iterator, __velarDeepMapIteratorNext);
2731
+ if (entry === null) break;
2732
+ if (entry.invalid || !__velarDenseList(entry.value) || entry.value.length !== 2) return "[invalid Map]";
2733
+ if (items.length >= 50) { __velarTestAppend(items, "…"); break; }
2734
+ __velarTestAppend(items, display(__velarDeepGetOwnPropertyDescriptor(entry.value, 0).value, state) + " => " + display(__velarDeepGetOwnPropertyDescriptor(entry.value, 1).value, state));
2735
+ }
2736
+ return "Map(" + __velarTestJoin(items) + ")";
2737
+ }
2738
+ if (__velarSetSize(value) !== null) {
2739
+ const items = [];
2740
+ const iterator = __velarDeepCall(__velarDeepSetValues, value, []);
2741
+ while (true) {
2742
+ const item = __velarDeepIteratorValue(iterator, __velarDeepSetIteratorNext);
2743
+ if (item === null) break;
2744
+ if (item.invalid) return "[invalid Set]";
2745
+ if (items.length >= 50) { __velarTestAppend(items, "…"); break; }
2746
+ __velarTestAppend(items, display(item.value, state));
2747
+ }
2748
+ return "Set(" + __velarTestJoin(items) + ")";
2749
+ }
2750
+ const keys = __velarDataRecordKeys(value);
2751
+ if (keys) {
2752
+ const displayed = [];
2753
+ const limit = __velarDeepCall(__velarTestMathMin, __velarTestNativeMath, [keys.length, 50]);
2754
+ for (let index = 0; index < limit; index += 1) {
2755
+ const key = __velarDeepGetOwnPropertyDescriptor(keys, index).value;
2756
+ __velarTestAppend(displayed, __velarDeepCall(__velarTestJsonStringify, __velarTestNativeJSON, [key]) + ": " + display(__velarDeepGetOwnPropertyDescriptor(value, key).value, state));
2757
+ }
2758
+ if (keys.length > 50) __velarTestAppend(displayed, "…");
2759
+ return "{" + __velarTestJoin(displayed) + "}";
2760
+ }
2761
+ const prototype = __velarDeepGetPrototypeOf(value);
2762
+ const constructor = prototype && __velarDeepGetOwnPropertyDescriptor(prototype, "constructor")?.value;
2763
+ const name = typeof constructor === "function" ? __velarDeepGetOwnPropertyDescriptor(constructor, "name")?.value : null;
2764
+ return "[" + (typeof name === "string" && name ? name : "object") + "]";
2765
+ } finally {
2766
+ state.depth -= 1;
2767
+ __velarDeepCall(__velarDeepWeakSetDelete, state.active, [value]);
2768
+ }
2769
+ }
2770
+ export function expect(actual) {
2771
+ return __velarDeepCall(__velarTestFreeze, __velarDeepNativeObject, [{
2772
+ // D59 rule 141: the assertion asks the language, so 'toBe' and '==' can
2773
+ // never give different answers. Native '!==' made this the one comparison
2774
+ // in the language that disagreed with the language, and NaN was where it
2775
+ // showed.
2776
+ toBe(expected) { if (!__velarSameValueZero(actual, expected)) throw new __velarTestNativeError("Expected " + display(actual) + " to be " + display(expected)); },
2777
+ // D50 rule 97.2: the assertion asks the language, so 'toEqual' and
2778
+ // 'equals(a, b)' can never give different answers.
2779
+ toEqual(expected) { if (!__velarEquals(actual, expected)) throw new __velarTestNativeError("Expected " + display(actual) + " to deeply equal " + display(expected)); },
2780
+ toBeTruthy() { if (actual !== true) throw new __velarTestNativeError("Expected bool true but received " + display(actual)); },
2781
+ toBeFalsy() { if (actual !== false) throw new __velarTestNativeError("Expected bool false but received " + display(actual)); },
2782
+ // D59 rule 141.1: the List branch asks the language too, so 'toContain'
2783
+ // and 'values.has(item)' can never give different answers. Native '==='
2784
+ // made this the last comparison in the language that disagreed with the
2785
+ // language once 'toBe' was repaired, and NaN was again where it showed.
2786
+ // The text branch stays 'String.includes': code-point identity is what
2787
+ // containment in text means, not a value comparison.
2788
+ toContain(expected) {
2789
+ let contains = typeof actual === "string" && typeof expected === "string" && __velarDeepCall(__velarTestStringIncludes, actual, [expected]);
2790
+ if (__velarDeepCall(__velarDeepArrayIsArray, __velarDeepNativeArray, [actual]) && __velarDenseList(actual)) {
2791
+ contains = false;
2792
+ for (let index = 0; index < actual.length; index += 1) {
2793
+ if (__velarSameValueZero(__velarDeepGetOwnPropertyDescriptor(actual, index).value, expected)) { contains = true; break; }
2794
+ }
2795
+ }
2796
+ if (!contains) throw new __velarTestNativeError("Expected " + display(actual) + " to contain " + display(expected));
2797
+ },
2798
+ toMatch(expected) {
2799
+ if (typeof actual !== "string" || typeof expected !== "string") throw new __velarTestNativeTypeError("toMatch requires text and a string pattern");
2800
+ if (expected.length > 4096) throw new __velarTestNativeRangeError("toMatch patterns cannot exceed 4096 code units");
2801
+ let pattern;
2802
+ try { pattern = new __velarTestNativeRegExp(expected, "u"); } catch { throw new __velarTestNativeTypeError("Invalid toMatch pattern"); }
2803
+ if (__velarDeepCall(__velarTestRegExpExec, pattern, [actual]) === null) throw new __velarTestNativeError("Expected " + display(actual) + " to match " + display(expected));
2804
+ },
2805
+ toHaveLength(expected) {
2806
+ if (!__velarDeepCall(__velarTestNumberIsSafeInteger, __velarTestNativeNumber, [expected]) || expected < 0) throw new __velarTestNativeRangeError("Expected length must be a non-negative safe integer");
2807
+ const length = typeof actual === "string" ? actual.length : __velarDeepCall(__velarDeepArrayIsArray, __velarDeepNativeArray, [actual]) && __velarDenseList(actual) ? actual.length : null;
2808
+ if (length === null) throw new __velarTestNativeTypeError("toHaveLength requires text or a dense List");
2809
+ if (length !== expected) throw new __velarTestNativeError("Expected length " + expected + " but received " + length);
2810
+ },
2811
+ toThrow() {
2812
+ if (typeof actual !== "function") throw new __velarTestNativeTypeError("toThrow requires a function");
2813
+ let threw = false; try { actual(); } catch { threw = true; }
2814
+ if (!threw) throw new __velarTestNativeError("Expected function to throw");
2815
+ },
2816
+ async toReject() {
2817
+ let result;
2818
+ if (typeof actual === "function") {
2819
+ try { result = actual(); }
2820
+ catch (error) { throw new __velarTestNativeError("Expected function to return a rejecting Promise, but it threw synchronously: " + display(error)); }
2821
+ } else result = actual;
2822
+ let promise;
2823
+ try { promise = __velarDeepCall(__velarTestPromiseThen, result, [value => value]); }
2824
+ catch { throw new __velarTestNativeTypeError("toReject requires a Promise or a function returning one"); }
2825
+ try { await promise; } catch { return null; }
2826
+ throw new __velarTestNativeError("Expected Promise to reject");
2827
+ },
2828
+ }]);
2829
+ }
2830
+ `.trimStart()],
2831
+ ]);
2832
+ /**
2833
+ * Implementation-only edges onto compiler-owned JavaScript modules. Public
2834
+ * ModuleInterface dependencies remain source-level VelarScript imports; this
2835
+ * graph only guarantees that unbundled targets materialize every hidden
2836
+ * runtime module a generated or standard module reaches for. A standard
2837
+ * module may appear on the left when it reuses a Core runtime algorithm
2838
+ * rather than restating it.
2839
+ */
2840
+ const coreModuleDependencies = new Map([
2841
+ [VELAR_COLLECTION_LOWERING_MODULE, VELAR_COLLECTION_LOWERING_DEPENDENCIES],
2842
+ ["velar/binary", [VELAR_COLLECTION_LOWERING_MODULE]],
2843
+ // D50 rule 97.2: 'toEqual' is the language's own equals(a, b).
2844
+ ["velar/test", [VELAR_COLLECTION_LOWERING_MODULE]],
2845
+ ]);
2846
+ export const STANDARD_MODULE_ADAPTER_DEPENDENCIES = new Map();
2847
+ export function standardModuleSources(extensions = []) {
2848
+ const activeExtensions = standardExtensions(extensions);
2849
+ return new Map([
2850
+ ...coreModuleSources,
2851
+ ...combinedExtensionModules(activeExtensions, "sources"),
2852
+ ]);
2853
+ }
2854
+ export function standardModuleRoute(source) {
2855
+ return `/@velar/${source.slice("velar/".length)}.js`;
2856
+ }
2857
+ export function standardModuleApi(extensions = []) {
2858
+ const activeExtensions = standardExtensions(extensions);
2859
+ const interfaces = standardModuleInterfaces(activeExtensions);
2860
+ return {
2861
+ standardVersion: VELAR_STANDARD_API_VERSION,
2862
+ extensions: Object.fromEntries(activeExtensions.map((extension) => [extension.id, extension.modules?.apiVersion ?? "unknown"])),
2863
+ modules: Object.fromEntries([...interfaces].map(([source, interface_]) => [source, [...interface_.exports.keys()].sort()])),
2864
+ };
2865
+ }
2866
+ export function standardModuleSource(source, projectConfig = { base: "/" }, extensions = []) {
2867
+ if (source === VELAR_WORKER_MANIFEST_MODULE) {
2868
+ const configured = projectConfig instanceof Map ? projectConfig.get(CORE_WORKER_CONFIG_KEY) : undefined;
2869
+ const entries = configured && typeof configured === "object" && !Array.isArray(configured)
2870
+ ? Object.fromEntries(Object.entries(configured)
2871
+ .filter(([name, path]) => /^[a-z][a-z0-9_-]{0,63}$/u.test(name) && typeof path === "string")
2872
+ .map(([name, path]) => [name, path]))
2873
+ : {};
2874
+ return `export const workerEntries = Object.freeze(${JSON.stringify(entries)});\n`;
2875
+ }
2876
+ for (const extension of standardExtensions(extensions)) {
2877
+ const extensionConfig = projectConfig instanceof Map ? projectConfig.get(extension.id) : projectConfig;
2878
+ const framework = extension.modules?.source?.(source, extensionConfig) ?? extension.modules?.sources.get(source) ?? null;
2879
+ if (framework !== null)
2880
+ return framework;
2881
+ }
2882
+ return coreModuleSources.get(source) ?? null;
2883
+ }
2884
+ export function standardModuleDependencies(source, projectConfig = { base: "/" }, extensions = []) {
2885
+ for (const extension of standardExtensions(extensions)) {
2886
+ const extensionConfig = projectConfig instanceof Map ? projectConfig.get(extension.id) : projectConfig;
2887
+ const moduleSource = extension.modules?.source?.(source, extensionConfig) ?? extension.modules?.sources.get(source) ?? null;
2888
+ if (moduleSource !== null)
2889
+ return extension.modules?.dependencies?.get(source) ?? [];
2890
+ }
2891
+ return coreModuleSources.has(source) ? coreModuleDependencies.get(source) ?? [] : null;
2892
+ }
2893
+ export function standardModuleClosure(roots, projectConfig = { base: "/" }, extensions = []) {
2894
+ const modules = new Set();
2895
+ const visit = (source, owner) => {
2896
+ if (modules.has(source))
2897
+ return;
2898
+ const dependencies = standardModuleDependencies(source, projectConfig, extensions);
2899
+ if (dependencies === null) {
2900
+ throw new Error(owner === null
2901
+ ? `Unknown VelarScript standard module '${source}'`
2902
+ : `VelarScript standard module '${owner}' depends on unknown module '${source}'`);
2903
+ }
2904
+ modules.add(source);
2905
+ for (const dependency of dependencies)
2906
+ visit(dependency, source);
2907
+ };
2908
+ for (const root of roots)
2909
+ visit(root, null);
2910
+ return modules;
2911
+ }
2912
+ function standardExtensions(extensions) {
2913
+ return [...extensions];
2914
+ }
2915
+ function combinedExtensionModules(extensions, field) {
2916
+ const combined = new Map();
2917
+ for (const extension of [...extensions].reverse()) {
2918
+ const modules = extension.modules?.[field];
2919
+ if (!modules)
2920
+ continue;
2921
+ for (const [source, value] of modules) {
2922
+ // A higher-priority, explicitly selected target owns both the contract
2923
+ // and source when two platforms intentionally share a module name.
2924
+ combined.delete(source);
2925
+ combined.set(source, value);
2926
+ }
2927
+ }
2928
+ return combined;
2929
+ }
2930
+ export function standardModuleAsset(pathname, projectConfig = { base: "/" }, extensions = []) {
2931
+ const match = /^\/@velar\/([a-z0-9-]+)\.js$/u.exec(pathname);
2932
+ return match ? standardModuleSource(`velar/${match[1]}`, projectConfig, extensions) : null;
2933
+ }
2934
+ //# sourceMappingURL=index.js.map