@dxos/effect 0.8.4-main.fffef41 → 0.8.4-staging.ac66bdf99f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/lib/browser/chunk-CGS2ULMK.mjs +11 -0
  2. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +445 -230
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing.mjs +39 -0
  7. package/dist/lib/browser/testing.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  9. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +445 -230
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing.mjs +39 -0
  14. package/dist/lib/node-esm/testing.mjs.map +7 -0
  15. package/dist/types/src/Performance.d.ts +25 -0
  16. package/dist/types/src/Performance.d.ts.map +1 -0
  17. package/dist/types/src/RuntimeProvider.d.ts +21 -0
  18. package/dist/types/src/RuntimeProvider.d.ts.map +1 -0
  19. package/dist/types/src/ast.d.ts +34 -21
  20. package/dist/types/src/ast.d.ts.map +1 -1
  21. package/dist/types/src/async-task-tagging.d.ts +6 -0
  22. package/dist/types/src/async-task-tagging.d.ts.map +1 -0
  23. package/dist/types/src/atom-kvs.d.ts +19 -0
  24. package/dist/types/src/atom-kvs.d.ts.map +1 -0
  25. package/dist/types/src/dynamic-runtime.d.ts +56 -0
  26. package/dist/types/src/dynamic-runtime.d.ts.map +1 -0
  27. package/dist/types/src/dynamic-runtime.test.d.ts +2 -0
  28. package/dist/types/src/dynamic-runtime.test.d.ts.map +1 -0
  29. package/dist/types/src/errors.d.ts +12 -0
  30. package/dist/types/src/errors.d.ts.map +1 -1
  31. package/dist/types/src/index.d.ts +7 -3
  32. package/dist/types/src/index.d.ts.map +1 -1
  33. package/dist/types/src/{jsonPath.d.ts → json-path.d.ts} +11 -3
  34. package/dist/types/src/json-path.d.ts.map +1 -0
  35. package/dist/types/src/json-path.test.d.ts +2 -0
  36. package/dist/types/src/json-path.test.d.ts.map +1 -0
  37. package/dist/types/src/testing.d.ts +4 -3
  38. package/dist/types/src/testing.d.ts.map +1 -1
  39. package/dist/types/tsconfig.tsbuildinfo +1 -1
  40. package/package.json +30 -11
  41. package/src/Performance.ts +45 -0
  42. package/src/RuntimeProvider.ts +35 -0
  43. package/src/ast.test.ts +35 -8
  44. package/src/ast.ts +95 -91
  45. package/src/async-task-tagging.ts +47 -0
  46. package/src/atom-kvs.ts +35 -0
  47. package/src/dynamic-runtime.test.ts +465 -0
  48. package/src/dynamic-runtime.ts +195 -0
  49. package/src/errors.ts +69 -8
  50. package/src/index.ts +7 -3
  51. package/src/interrupt.test.ts +3 -1
  52. package/src/{jsonPath.test.ts → json-path.test.ts} +47 -8
  53. package/src/{jsonPath.ts → json-path.ts} +26 -3
  54. package/src/layers.test.ts +4 -2
  55. package/src/resource.ts +2 -2
  56. package/src/sanity.test.ts +6 -4
  57. package/src/testing.ts +6 -4
  58. package/dist/types/src/jsonPath.d.ts.map +0 -1
  59. package/dist/types/src/jsonPath.test.d.ts +0 -2
  60. package/dist/types/src/jsonPath.test.d.ts.map +0 -1
@@ -1,4 +1,7 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+ import {
3
+ __export
4
+ } from "./chunk-HSLMI22Q.mjs";
2
5
 
3
6
  // src/ast.ts
4
7
  import * as Function from "effect/Function";
@@ -8,65 +11,59 @@ import * as SchemaAST from "effect/SchemaAST";
8
11
  import { invariant } from "@dxos/invariant";
9
12
  import { isNonNullable } from "@dxos/util";
10
13
  var __dxlog_file = "/__w/dxos/dxos/packages/common/effect/src/ast.ts";
11
- var isTupleType2 = (node) => {
12
- return SchemaAST.isTupleType(node) && node.elements.length > 0;
13
- };
14
- var getSimpleType = (node) => {
15
- if (SchemaAST.isDeclaration(node) || SchemaAST.isObjectKeyword(node) || SchemaAST.isTypeLiteral(node) || // TODO(wittjosiah): Tuples are actually arrays.
16
- isTupleType2(node) || isDiscriminatedUnion(node)) {
17
- return "object";
18
- }
19
- if (SchemaAST.isStringKeyword(node)) {
20
- return "string";
21
- }
22
- if (SchemaAST.isNumberKeyword(node)) {
23
- return "number";
24
- }
25
- if (SchemaAST.isBooleanKeyword(node)) {
26
- return "boolean";
27
- }
28
- if (SchemaAST.isEnums(node)) {
29
- return "enum";
30
- }
31
- if (SchemaAST.isLiteral(node)) {
32
- return "literal";
14
+ var reduceRefinements = (type, refinements = []) => {
15
+ if (SchemaAST.isRefinement(type)) {
16
+ const filter = type.filter;
17
+ const nextType = {
18
+ ...type.from,
19
+ annotations: {
20
+ ...type.from.annotations,
21
+ ...type.annotations
22
+ }
23
+ };
24
+ return reduceRefinements(nextType, [
25
+ ...refinements,
26
+ filter
27
+ ]);
33
28
  }
29
+ return {
30
+ type,
31
+ refinements
32
+ };
34
33
  };
35
- var isSimpleType = (node) => !!getSimpleType(node);
36
- (function(SimpleType2) {
37
- SimpleType2.getDefaultValue = (type) => {
38
- switch (type) {
39
- case "string": {
40
- return "";
41
- }
42
- case "number": {
43
- return 0;
44
- }
45
- case "boolean": {
46
- return false;
47
- }
48
- case "object": {
49
- return {};
50
- }
51
- default: {
52
- throw new Error(`Unsupported type for default value: ${type}`);
34
+ var getBaseType = (prop) => {
35
+ const encoded = SchemaAST.encodedBoundAST(prop.type);
36
+ const unwrapped = prop.isOptional && encoded._tag === "Union" ? encoded.types[0] : encoded;
37
+ return reduceRefinements(unwrapped);
38
+ };
39
+ var getProperties = (ast) => {
40
+ const properties = SchemaAST.getPropertySignatures(ast);
41
+ return properties.map((prop) => {
42
+ const { type, refinements } = getBaseType(prop);
43
+ const mergedType = prop.annotations && Reflect.ownKeys(prop.annotations).length > 0 ? {
44
+ ...type,
45
+ annotations: {
46
+ ...type.annotations,
47
+ ...prop.annotations
53
48
  }
54
- }
55
- };
56
- })(SimpleType || (SimpleType = {}));
49
+ } : type;
50
+ return {
51
+ type: mergedType,
52
+ refinements,
53
+ name: prop.name,
54
+ isOptional: prop.isOptional,
55
+ isReadonly: prop.isReadonly
56
+ };
57
+ });
58
+ };
57
59
  var VisitResult = /* @__PURE__ */ (function(VisitResult2) {
58
60
  VisitResult2[VisitResult2["CONTINUE"] = 0] = "CONTINUE";
59
61
  VisitResult2[VisitResult2["SKIP"] = 1] = "SKIP";
60
62
  VisitResult2[VisitResult2["EXIT"] = 2] = "EXIT";
61
63
  return VisitResult2;
62
64
  })({});
63
- var defaultTest = isSimpleType;
64
65
  var visit = (node, testOrVisitor, visitor) => {
65
- if (!visitor) {
66
- visitNode(node, defaultTest, testOrVisitor);
67
- } else {
68
- visitNode(node, testOrVisitor, visitor);
69
- }
66
+ visitNode(node, testOrVisitor, visitor);
70
67
  };
71
68
  var visitNode = (node, test, visitor, path = [], depth = 0) => {
72
69
  const $result = test?.(node, path, depth);
@@ -156,7 +153,7 @@ var findProperty = (schema, path) => {
156
153
  const typeNode = findNode(node, SchemaAST.isTypeLiteral);
157
154
  invariant(typeNode, void 0, {
158
155
  F: __dxlog_file,
159
- L: 265,
156
+ L: 247,
160
157
  S: void 0,
161
158
  A: [
162
159
  "typeNode",
@@ -176,10 +173,10 @@ var findProperty = (schema, path) => {
176
173
  return getProp(schema.ast, path.split("."));
177
174
  };
178
175
  var defaultAnnotations = {
179
- ["ObjectKeyword"]: SchemaAST.objectKeyword,
180
- ["StringKeyword"]: SchemaAST.stringKeyword,
181
- ["NumberKeyword"]: SchemaAST.numberKeyword,
182
- ["BooleanKeyword"]: SchemaAST.booleanKeyword
176
+ ObjectKeyword: SchemaAST.objectKeyword,
177
+ StringKeyword: SchemaAST.stringKeyword,
178
+ NumberKeyword: SchemaAST.numberKeyword,
179
+ BooleanKeyword: SchemaAST.booleanKeyword
183
180
  };
184
181
  var getAnnotation2 = (annotationId, noDefault = true) => (node) => {
185
182
  const id = Function.pipe(SchemaAST.getIdentifierAnnotation(node), Option.getOrUndefined);
@@ -210,13 +207,22 @@ var isOption = (node) => {
210
207
  var isLiteralUnion = (node) => {
211
208
  return SchemaAST.isUnion(node) && node.types.every(SchemaAST.isLiteral);
212
209
  };
210
+ var isArrayType = (node) => {
211
+ return SchemaAST.isTupleType(node) && node.elements.length === 0 && node.rest.length === 1;
212
+ };
213
+ var getArrayElementType = (node) => {
214
+ return isArrayType(node) ? node.rest.at(0)?.type : void 0;
215
+ };
216
+ var isTupleType2 = (node) => {
217
+ return SchemaAST.isTupleType(node) && node.elements.length > 0;
218
+ };
213
219
  var isDiscriminatedUnion = (node) => {
214
220
  return SchemaAST.isUnion(node) && !!getDiscriminatingProps(node)?.length;
215
221
  };
216
222
  var getDiscriminatingProps = (node) => {
217
223
  invariant(SchemaAST.isUnion(node), void 0, {
218
224
  F: __dxlog_file,
219
- L: 362,
225
+ L: 365,
220
226
  S: void 0,
221
227
  A: [
222
228
  "SchemaAST.isUnion(node)",
@@ -234,7 +240,7 @@ var getDiscriminatingProps = (node) => {
234
240
  var getDiscriminatedType = (node, value = {}) => {
235
241
  invariant(SchemaAST.isUnion(node), void 0, {
236
242
  F: __dxlog_file,
237
- L: 386,
243
+ L: 389,
238
244
  S: void 0,
239
245
  A: [
240
246
  "SchemaAST.isUnion(node)",
@@ -243,7 +249,7 @@ var getDiscriminatedType = (node, value = {}) => {
243
249
  });
244
250
  invariant(value, void 0, {
245
251
  F: __dxlog_file,
246
- L: 387,
252
+ L: 390,
247
253
  S: void 0,
248
254
  A: [
249
255
  "value",
@@ -258,7 +264,7 @@ var getDiscriminatedType = (node, value = {}) => {
258
264
  const match = SchemaAST.getPropertySignatures(type).filter((prop) => props?.includes(prop.name.toString())).every((prop) => {
259
265
  invariant(SchemaAST.isLiteral(prop.type), void 0, {
260
266
  F: __dxlog_file,
261
- L: 398,
267
+ L: 401,
262
268
  S: void 0,
263
269
  A: [
264
270
  "SchemaAST.isLiteral(prop.type)",
@@ -276,7 +282,7 @@ var getDiscriminatedType = (node, value = {}) => {
276
282
  const literal = SchemaAST.getPropertySignatures(type).find((p) => p.name.toString() === prop);
277
283
  invariant(SchemaAST.isLiteral(literal.type), void 0, {
278
284
  F: __dxlog_file,
279
- L: 416,
285
+ L: 419,
280
286
  S: void 0,
281
287
  A: [
282
288
  "SchemaAST.isLiteral(literal.type)",
@@ -293,6 +299,10 @@ var getDiscriminatedType = (node, value = {}) => {
293
299
  const schema = Schema.Struct(fields);
294
300
  return schema.ast;
295
301
  };
302
+ var isNestedType = (node) => {
303
+ return SchemaAST.isDeclaration(node) || SchemaAST.isObjectKeyword(node) || SchemaAST.isTypeLiteral(node) || // TODO(wittjosiah): Tuples are actually arrays.
304
+ isTupleType2(node) || isDiscriminatedUnion(node);
305
+ };
296
306
  var mapAst = (ast, f) => {
297
307
  switch (ast._tag) {
298
308
  case "TypeLiteral": {
@@ -313,9 +323,6 @@ var mapAst = (ast, f) => {
313
323
  }
314
324
  }
315
325
  };
316
- var isArrayType = (node) => {
317
- return SchemaAST.isTupleType(node) || SchemaAST.isUnion(node) && node.types.some(isArrayType) && node.types.some(SchemaAST.isUndefinedKeyword) && node.types.length === 2;
318
- };
319
326
  var getIndexSignatures = (ast) => {
320
327
  const annotation = SchemaAST.getSurrogateAnnotation(ast);
321
328
  if (Option.isSome(annotation)) {
@@ -331,157 +338,64 @@ var getIndexSignatures = (ast) => {
331
338
  }
332
339
  return [];
333
340
  };
334
- var SimpleType;
335
-
336
- // src/jsonPath.ts
337
- import * as Option2 from "effect/Option";
338
- import * as Schema2 from "effect/Schema";
339
- import { JSONPath } from "jsonpath-plus";
340
- import { invariant as invariant2 } from "@dxos/invariant";
341
- var __dxlog_file2 = "/__w/dxos/dxos/packages/common/effect/src/jsonPath.ts";
342
- var PATH_REGEX = /^($|[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*|\[\d+\](?:\.)?)*$)/;
343
- var PROP_REGEX = /^\w+$/;
344
- var JsonPath = Schema2.String.pipe(Schema2.pattern(PATH_REGEX)).annotations({
345
- title: "JSON path",
346
- description: "JSON path to a property"
347
- });
348
- var JsonProp = Schema2.NonEmptyString.pipe(Schema2.pattern(PROP_REGEX, {
349
- message: () => "Property name must contain only letters, numbers, and underscores"
350
- }));
351
- var isJsonPath = (value) => {
352
- return Option2.isSome(Schema2.validateOption(JsonPath)(value));
353
- };
354
- var createJsonPath = (path) => {
355
- const candidatePath = path.map((p, i) => {
356
- if (typeof p === "number") {
357
- return `[${p}]`;
358
- } else {
359
- return i === 0 ? p : `.${p}`;
360
- }
361
- }).join("");
362
- invariant2(isJsonPath(candidatePath), `Invalid JsonPath: ${candidatePath}`, {
363
- F: __dxlog_file2,
364
- L: 65,
365
- S: void 0,
366
- A: [
367
- "isJsonPath(candidatePath)",
368
- "`Invalid JsonPath: ${candidatePath}`"
369
- ]
370
- });
371
- return candidatePath;
372
- };
373
- var fromEffectValidationPath = (effectPath) => {
374
- const jsonPath = effectPath.replace(/\.\[(\d+)\]/g, "[$1]");
375
- invariant2(isJsonPath(jsonPath), `Invalid JsonPath: ${jsonPath}`, {
376
- F: __dxlog_file2,
377
- L: 76,
378
- S: void 0,
379
- A: [
380
- "isJsonPath(jsonPath)",
381
- "`Invalid JsonPath: ${jsonPath}`"
382
- ]
383
- });
384
- return jsonPath;
385
- };
386
- var splitJsonPath = (path) => {
387
- if (!isJsonPath(path)) {
388
- return [];
389
- }
390
- return path.match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)?.map((part) => part.startsWith("[") ? part.replace(/[[\]]/g, "") : part) ?? [];
391
- };
392
- var getField = (object, path) => {
393
- return JSONPath({
394
- path,
395
- json: object
396
- })[0];
397
- };
398
341
 
399
- // src/url.ts
400
- import * as Function2 from "effect/Function";
401
- import * as Option3 from "effect/Option";
402
- import * as SchemaAST2 from "effect/SchemaAST";
403
- import { decamelize } from "@dxos/util";
404
- var ParamKeyAnnotationId = Symbol.for("@dxos/schema/annotation/ParamKey");
405
- var getParamKeyAnnotation = SchemaAST2.getAnnotation(ParamKeyAnnotationId);
406
- var ParamKeyAnnotation = (value) => (self) => self.annotations({
407
- [ParamKeyAnnotationId]: value
408
- });
409
- var UrlParser = class {
410
- _schema;
411
- constructor(_schema) {
412
- this._schema = _schema;
413
- }
414
- /**
415
- * Parse URL params.
416
- */
417
- parse(_url) {
418
- const url = new URL(_url);
419
- return Object.entries(this._schema.fields).reduce((params, [key, type]) => {
420
- let value = url.searchParams.get(decamelize(key));
421
- if (value == null) {
422
- value = url.searchParams.get(key);
423
- }
424
- if (value != null) {
425
- if (SchemaAST2.isNumberKeyword(type.ast)) {
426
- params[key] = parseInt(value);
427
- } else if (SchemaAST2.isBooleanKeyword(type.ast)) {
428
- params[key] = value === "true" || value === "1";
429
- } else {
430
- params[key] = value;
431
- }
432
- }
433
- return params;
434
- }, {});
435
- }
436
- /**
437
- * Return URL with encoded params.
438
- */
439
- create(_url, params) {
440
- const url = new URL(_url);
441
- Object.entries(params).forEach(([key, value]) => {
442
- if (value !== void 0) {
443
- const field = this._schema.fields[key];
444
- if (field) {
445
- const { key: serializedKey } = Function2.pipe(getParamKeyAnnotation(field.ast), Option3.getOrElse(() => ({
446
- key: decamelize(key)
447
- })));
448
- url.searchParams.set(serializedKey, String(value));
449
- }
450
- }
451
- });
452
- return url;
453
- }
342
+ // src/atom-kvs.ts
343
+ import { Atom } from "@effect-atom/atom-react";
344
+ import * as BrowserKeyValueStore from "@effect/platform-browser/BrowserKeyValueStore";
345
+ var defaultRuntime = Atom.runtime(BrowserKeyValueStore.layerLocalStorage);
346
+ var createKvsStore = (options) => {
347
+ const runtime2 = options.runtime ?? defaultRuntime;
348
+ return Atom.kvs({
349
+ runtime: runtime2,
350
+ key: options.key,
351
+ schema: options.schema,
352
+ defaultValue: options.defaultValue
353
+ }).pipe(Atom.keepAlive);
454
354
  };
455
355
 
456
356
  // src/context.ts
457
357
  import * as Effect from "effect/Effect";
458
358
  import { Context } from "@dxos/context";
459
- var __dxlog_file3 = "/__w/dxos/dxos/packages/common/effect/src/context.ts";
359
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/common/effect/src/context.ts";
460
360
  var contextFromScope = () => Effect.gen(function* () {
461
361
  const ctx = new Context(void 0, {
462
- F: __dxlog_file3,
362
+ F: __dxlog_file2,
463
363
  L: 13
464
364
  });
465
365
  yield* Effect.addFinalizer(() => Effect.promise(() => ctx.dispose()));
466
366
  return ctx;
467
367
  });
468
368
 
369
+ // src/dynamic-runtime.ts
370
+ var dynamic_runtime_exports = {};
371
+ __export(dynamic_runtime_exports, {
372
+ make: () => make
373
+ });
374
+ import * as Context2 from "effect/Context";
375
+ import * as Effect3 from "effect/Effect";
376
+ import * as Exit2 from "effect/Exit";
377
+ import * as Option3 from "effect/Option";
378
+ import * as Runtime2 from "effect/Runtime";
379
+
469
380
  // src/errors.ts
470
381
  import * as Cause from "effect/Cause";
471
382
  import * as Chunk from "effect/Chunk";
472
383
  import * as Effect2 from "effect/Effect";
473
384
  import * as Exit from "effect/Exit";
474
385
  import * as GlobalValue from "effect/GlobalValue";
475
- import * as Option4 from "effect/Option";
476
- var spanSymbol = Symbol.for("effect/SpanAnnotation");
477
- var originalSymbol = Symbol.for("effect/OriginalAnnotation");
386
+ import * as Option2 from "effect/Option";
387
+ import * as Runtime from "effect/Runtime";
388
+ var spanSymbol = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
478
389
  var spanToTrace = GlobalValue.globalValue("effect/Tracer/spanToTrace", () => /* @__PURE__ */ new WeakMap());
479
390
  var locationRegex = /\((.*)\)/g;
480
391
  var prettyErrorStack = (error, appendStacks = []) => {
392
+ if (typeof error !== "object" || error === null) {
393
+ return error;
394
+ }
481
395
  const span = error[spanSymbol];
482
396
  const lines = typeof error.stack === "string" ? error.stack.split("\n") : [];
483
397
  const out = [];
484
- let atStack = false;
398
+ let atStack = false, inCore = false, passedScheduler = false;
485
399
  for (let i = 0; i < lines.length; i++) {
486
400
  if (!atStack && !lines[i].startsWith(" at ")) {
487
401
  out.push(lines[i]);
@@ -498,6 +412,26 @@ var prettyErrorStack = (error, appendStacks = []) => {
498
412
  if (lines[i].includes("effect_internal_function")) {
499
413
  break;
500
414
  }
415
+ const filename = lines[i].match(/\/([a-zA-Z0-9_\-.]+):\d+:\d+\)$/)?.[1];
416
+ if (!inCore && [
417
+ "core-effect.ts"
418
+ ].includes(filename)) {
419
+ inCore = true;
420
+ }
421
+ if (inCore && !passedScheduler && [
422
+ "Scheduler.ts"
423
+ ].includes(filename)) {
424
+ passedScheduler = true;
425
+ continue;
426
+ }
427
+ if (passedScheduler && ![
428
+ "Scheduler.ts"
429
+ ].includes(filename)) {
430
+ inCore = false;
431
+ }
432
+ if (inCore) {
433
+ continue;
434
+ }
501
435
  out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>").replace(/at Arguments\./, "at "));
502
436
  }
503
437
  if (span) {
@@ -523,14 +457,12 @@ var prettyErrorStack = (error, appendStacks = []) => {
523
457
  } else {
524
458
  out.push(` at ${current.name}`);
525
459
  }
526
- current = Option4.getOrUndefined(current.parent);
460
+ current = Option2.getOrUndefined(current.parent);
527
461
  i++;
528
462
  }
529
463
  }
530
464
  out.push(...appendStacks);
531
- if (error[originalSymbol]) {
532
- error = error[originalSymbol];
533
- }
465
+ error = Cause.originalError(error);
534
466
  if (error.cause) {
535
467
  error.cause = prettyErrorStack(error.cause);
536
468
  }
@@ -553,8 +485,8 @@ var causeToError = (cause) => {
553
485
  ...Chunk.toArray(Cause.defects(cause))
554
486
  ];
555
487
  const getStackFrames = () => {
556
- const o = {};
557
- Error.captureStackTrace(o, getStackFrames);
488
+ const o = new Error();
489
+ Error.captureStackTrace(o, causeToError);
558
490
  return o.stack.split("\n").slice(1);
559
491
  };
560
492
  const stackFrames = getStackFrames();
@@ -569,15 +501,30 @@ var causeToError = (cause) => {
569
501
  var throwCause = (cause) => {
570
502
  throw causeToError(cause);
571
503
  };
572
- var unwrapExit = (exit) => {
573
- if (Exit.isSuccess(exit)) {
574
- return exit.value;
504
+ var unwrapExit = (exit2) => {
505
+ if (Exit.isSuccess(exit2)) {
506
+ return exit2.value;
575
507
  }
576
- return throwCause(exit.cause);
508
+ return throwCause(exit2.cause);
577
509
  };
578
510
  var runAndForwardErrors = async (effect, options) => {
579
- const exit = await Effect2.runPromiseExit(effect, options);
580
- return unwrapExit(exit);
511
+ const exit2 = await Effect2.runPromiseExit(effect, options);
512
+ return unwrapExit(exit2);
513
+ };
514
+ var runInRuntime = (...args) => {
515
+ if (args.length === 1) {
516
+ const [runtime2] = args;
517
+ return async (effect, options) => {
518
+ const exit2 = await Runtime.runPromiseExit(runtime2, effect, options);
519
+ return unwrapExit(exit2);
520
+ };
521
+ } else {
522
+ const [runtime2, effect, options] = args;
523
+ return (async () => {
524
+ const exit2 = await Runtime.runPromiseExit(runtime2, effect, options);
525
+ return unwrapExit(exit2);
526
+ })();
527
+ }
581
528
  };
582
529
  var promiseWithCauseCapture = (evaluate) => Effect2.promise(async (signal) => {
583
530
  try {
@@ -588,82 +535,350 @@ var promiseWithCauseCapture = (evaluate) => Effect2.promise(async (signal) => {
588
535
  }
589
536
  }).pipe(Effect2.flatten);
590
537
 
591
- // src/testing.ts
592
- import * as Context2 from "effect/Context";
593
- import * as Effect3 from "effect/Effect";
594
- (function(TestHelpers2) {
595
- TestHelpers2.runIf = (condition) => (effect, ctx) => Effect3.gen(function* () {
596
- if (!condition) {
597
- ctx.skip();
598
- } else {
599
- return yield* effect;
538
+ // src/dynamic-runtime.ts
539
+ var validateTags = (context, tags) => Effect3.gen(function* () {
540
+ const missingTags = [];
541
+ for (const tag of tags) {
542
+ const option = Context2.getOption(context, tag);
543
+ if (Option3.isNone(option)) {
544
+ missingTags.push(tag.key);
600
545
  }
601
- });
602
- TestHelpers2.skipIf = (condition) => (effect, ctx) => Effect3.gen(function* () {
603
- if (condition) {
604
- ctx.skip();
605
- } else {
606
- return yield* effect;
546
+ }
547
+ if (missingTags.length > 0) {
548
+ return yield* Effect3.die(new Error(`Missing required tags in runtime: ${missingTags.join(", ")}`));
549
+ }
550
+ });
551
+ function make(managedRuntime, tags) {
552
+ const managedRuntimeAny = managedRuntime;
553
+ let cachedRuntime;
554
+ let validatedRuntimePromise;
555
+ const getValidatedRuntimeAsync = async () => {
556
+ if (!validatedRuntimePromise) {
557
+ validatedRuntimePromise = managedRuntimeAny.runPromise(Effect3.gen(function* () {
558
+ const rt = yield* managedRuntimeAny.runtimeEffect;
559
+ yield* validateTags(rt.context, tags);
560
+ return rt;
561
+ }));
607
562
  }
608
- });
609
- TestHelpers2.taggedTest = (tag) => (effect, ctx) => Effect3.gen(function* () {
610
- if (!process.env.DX_TEST_TAGS?.includes(tag)) {
611
- ctx.skip();
563
+ return validatedRuntimePromise;
564
+ };
565
+ const getValidatedRuntime = () => {
566
+ const validationExit = managedRuntimeAny.runSyncExit(Effect3.gen(function* () {
567
+ const rt = yield* managedRuntimeAny.runtimeEffect;
568
+ yield* validateTags(rt.context, tags);
569
+ return rt;
570
+ }));
571
+ return unwrapExit(validationExit);
572
+ };
573
+ return {
574
+ managedRuntime: managedRuntimeAny,
575
+ runPromise: async (effect) => {
576
+ const runtime2 = await getValidatedRuntimeAsync();
577
+ return Runtime2.runPromise(runtime2)(effect);
578
+ },
579
+ runSync: (effect) => {
580
+ const runtime2 = getValidatedRuntime();
581
+ return Runtime2.runSync(runtime2)(effect);
582
+ },
583
+ runSyncExit: (effect) => {
584
+ const validationExit = managedRuntimeAny.runSyncExit(Effect3.gen(function* () {
585
+ const rt = yield* managedRuntimeAny.runtimeEffect;
586
+ yield* validateTags(rt.context, tags);
587
+ return rt;
588
+ }));
589
+ if (Exit2.isSuccess(validationExit)) {
590
+ const runtime2 = validationExit.value;
591
+ return Runtime2.runSyncExit(runtime2)(effect);
592
+ }
593
+ return validationExit;
594
+ },
595
+ runPromiseExit: async (effect) => {
596
+ try {
597
+ const runtime2 = await getValidatedRuntimeAsync();
598
+ return Runtime2.runPromiseExit(runtime2)(effect);
599
+ } catch (error) {
600
+ return Exit2.die(error);
601
+ }
602
+ },
603
+ runFork: (effect) => {
604
+ const runtime2 = getValidatedRuntime();
605
+ return Runtime2.runFork(runtime2)(effect);
606
+ },
607
+ runtimeEffect: Effect3.gen(function* () {
608
+ if (cachedRuntime) {
609
+ return cachedRuntime;
610
+ }
611
+ const rt = yield* managedRuntimeAny.runtimeEffect;
612
+ yield* validateTags(rt.context, tags);
613
+ const runtime2 = rt;
614
+ cachedRuntime = runtime2;
615
+ return runtime2;
616
+ }).pipe(Effect3.catchAll(() => (
617
+ // This should never happen since validateTags uses Effect.die
618
+ Effect3.die(new Error("Unexpected error in runtimeEffect validation"))
619
+ ))),
620
+ dispose: async () => {
621
+ await managedRuntimeAny.dispose();
622
+ }
623
+ };
624
+ }
625
+
626
+ // src/json-path.ts
627
+ import * as Option4 from "effect/Option";
628
+ import * as Schema2 from "effect/Schema";
629
+ import { JSONPath } from "jsonpath-plus";
630
+ import { invariant as invariant2 } from "@dxos/invariant";
631
+ import { getDeep, setDeep } from "@dxos/util";
632
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/common/effect/src/json-path.ts";
633
+ var PATH_REGEX = /^($|[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*|\[\d+\](?:\.)?)*$)/;
634
+ var PROP_REGEX = /^\w+$/;
635
+ var JsonPath = Schema2.String.pipe(Schema2.pattern(PATH_REGEX)).annotations({
636
+ title: "JSON path",
637
+ description: "JSON path to a property"
638
+ });
639
+ var JsonProp = Schema2.NonEmptyString.pipe(Schema2.pattern(PROP_REGEX, {
640
+ message: () => "Property name must contain only letters, numbers, and underscores"
641
+ }));
642
+ var isJsonPath = (value) => {
643
+ return Option4.isSome(Schema2.validateOption(JsonPath)(value));
644
+ };
645
+ var createJsonPath = (path) => {
646
+ const candidatePath = path.map((p, i) => {
647
+ if (typeof p === "number") {
648
+ return `[${p}]`;
612
649
  } else {
613
- return yield* effect;
650
+ return i === 0 ? p : `.${p}`;
614
651
  }
652
+ }).join("");
653
+ invariant2(isJsonPath(candidatePath), `Invalid JsonPath: ${candidatePath}`, {
654
+ F: __dxlog_file3,
655
+ L: 69,
656
+ S: void 0,
657
+ A: [
658
+ "isJsonPath(candidatePath)",
659
+ "`Invalid JsonPath: ${candidatePath}`"
660
+ ]
661
+ });
662
+ return candidatePath;
663
+ };
664
+ var fromEffectValidationPath = (effectPath) => {
665
+ const jsonPath = effectPath.replace(/\.\[(\d+)\]/g, "[$1]");
666
+ invariant2(isJsonPath(jsonPath), `Invalid JsonPath: ${jsonPath}`, {
667
+ F: __dxlog_file3,
668
+ L: 80,
669
+ S: void 0,
670
+ A: [
671
+ "isJsonPath(jsonPath)",
672
+ "`Invalid JsonPath: ${jsonPath}`"
673
+ ]
615
674
  });
616
- TestHelpers2.provideTestContext = (effect, ctx) => Effect3.provideService(effect, TestContextService, ctx);
617
- })(TestHelpers || (TestHelpers = {}));
618
- var TestContextService = class extends Context2.Tag("@dxos/effect/TestContextService")() {
675
+ return jsonPath;
676
+ };
677
+ var splitJsonPath = (path) => {
678
+ if (!isJsonPath(path)) {
679
+ return [];
680
+ }
681
+ return path.match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)?.map((part) => part.replace(/[[\]]/g, "")).map((part) => {
682
+ const parsed = Number.parseInt(part, 10);
683
+ return Number.isNaN(parsed) ? part : parsed;
684
+ }) ?? [];
685
+ };
686
+ var getField = (object, path) => {
687
+ return JSONPath({
688
+ path,
689
+ json: object
690
+ })[0];
691
+ };
692
+ var getValue = (obj, path) => {
693
+ return getDeep(obj, splitJsonPath(path));
694
+ };
695
+ var setValue = (obj, path, value) => {
696
+ return setDeep(obj, splitJsonPath(path), value);
619
697
  };
620
- var TestHelpers;
621
698
 
622
699
  // src/resource.ts
623
700
  import * as Effect4 from "effect/Effect";
624
701
  var acquireReleaseResource = (getResource) => Effect4.acquireRelease(Effect4.gen(function* () {
625
702
  const resource = getResource();
626
703
  yield* Effect4.promise(async () => {
627
- resource.open?.();
704
+ await resource.open?.();
628
705
  return void 0;
629
706
  });
630
707
  return resource;
631
708
  }), (resource) => Effect4.promise(async () => {
632
- resource.close?.();
709
+ await resource.close?.();
633
710
  return void 0;
634
711
  }));
712
+
713
+ // src/url.ts
714
+ import * as Function2 from "effect/Function";
715
+ import * as Option5 from "effect/Option";
716
+ import * as SchemaAST2 from "effect/SchemaAST";
717
+ import { decamelize } from "@dxos/util";
718
+ var ParamKeyAnnotationId = /* @__PURE__ */ Symbol.for("@dxos/schema/annotation/ParamKey");
719
+ var getParamKeyAnnotation = SchemaAST2.getAnnotation(ParamKeyAnnotationId);
720
+ var ParamKeyAnnotation = (value) => (self) => self.annotations({
721
+ [ParamKeyAnnotationId]: value
722
+ });
723
+ var UrlParser = class {
724
+ _schema;
725
+ constructor(_schema) {
726
+ this._schema = _schema;
727
+ }
728
+ /**
729
+ * Parse URL params.
730
+ */
731
+ parse(_url) {
732
+ const url = new URL(_url);
733
+ return Object.entries(this._schema.fields).reduce((params, [key, type]) => {
734
+ let value = url.searchParams.get(decamelize(key));
735
+ if (value == null) {
736
+ value = url.searchParams.get(key);
737
+ }
738
+ if (value != null) {
739
+ if (SchemaAST2.isNumberKeyword(type.ast)) {
740
+ params[key] = parseInt(value);
741
+ } else if (SchemaAST2.isBooleanKeyword(type.ast)) {
742
+ params[key] = value === "true" || value === "1";
743
+ } else {
744
+ params[key] = value;
745
+ }
746
+ }
747
+ return params;
748
+ }, {});
749
+ }
750
+ /**
751
+ * Return URL with encoded params.
752
+ */
753
+ create(_url, params) {
754
+ const url = new URL(_url);
755
+ Object.entries(params).forEach(([key, value]) => {
756
+ if (value !== void 0) {
757
+ const field = this._schema.fields[key];
758
+ if (field) {
759
+ const { key: serializedKey } = Function2.pipe(getParamKeyAnnotation(field.ast), Option5.getOrElse(() => ({
760
+ key: decamelize(key)
761
+ })));
762
+ url.searchParams.set(serializedKey, String(value));
763
+ }
764
+ }
765
+ });
766
+ return url;
767
+ }
768
+ };
769
+
770
+ // src/RuntimeProvider.ts
771
+ var RuntimeProvider_exports = {};
772
+ __export(RuntimeProvider_exports, {
773
+ currentRuntime: () => currentRuntime,
774
+ provide: () => provide2,
775
+ runPromise: () => runPromise2
776
+ });
777
+ import * as Effect5 from "effect/Effect";
778
+ import * as Runtime3 from "effect/Runtime";
779
+ var currentRuntime = () => Effect5.runtime().pipe(Effect5.map(Effect5.succeed));
780
+ var runPromise2 = (provider) => async (effect) => {
781
+ const runtime2 = await runAndForwardErrors(provider);
782
+ return unwrapExit(await effect.pipe(Runtime3.runPromiseExit(runtime2)));
783
+ };
784
+ var provide2 = (runtimeProvider) => (effect) => Effect5.flatMap(runtimeProvider, (runtime2) => Effect5.provide(effect, runtime2));
785
+
786
+ // src/Performance.ts
787
+ var Performance_exports = {};
788
+ __export(Performance_exports, {
789
+ addTrackEntry: () => addTrackEntry
790
+ });
791
+ import * as Effect6 from "effect/Effect";
792
+ var addTrackEntry = (options) => (effect) => Effect6.gen(function* () {
793
+ const start = performance.now();
794
+ const exit2 = yield* Effect6.exit(effect);
795
+ const resolvedOptions = typeof options === "function" ? options(exit2) : options;
796
+ performance.measure(resolvedOptions.name, {
797
+ start,
798
+ detail: {
799
+ ...resolvedOptions.detail,
800
+ devtools: resolvedOptions.devtools
801
+ }
802
+ });
803
+ return yield* exit2;
804
+ });
805
+
806
+ // src/async-task-tagging.ts
807
+ import * as Context3 from "effect/Context";
808
+ import * as Effect7 from "effect/Effect";
809
+ import { pipe as pipe3 } from "effect/Function";
810
+ import * as Layer from "effect/Layer";
811
+ import * as Predicate from "effect/Predicate";
812
+ import * as Tracer from "effect/Tracer";
813
+ var runInTask = /* @__PURE__ */ Symbol("runInTask");
814
+ var asyncTaskTaggingLayer = () => {
815
+ if (Predicate.hasProperty(console, "createTask") === false) {
816
+ return Layer.empty;
817
+ }
818
+ const makeTracer = Effect7.gen(function* () {
819
+ const oldTracer = yield* Effect7.tracer;
820
+ return Tracer.make({
821
+ span: (name, ...args) => {
822
+ const span = oldTracer.span(name, ...args);
823
+ const trace = console.createTask(name);
824
+ span[runInTask] = (f) => trace.run(f);
825
+ return span;
826
+ },
827
+ context: (f, fiber) => {
828
+ const maybeParentSpan = Context3.getOption(Tracer.ParentSpan)(fiber.currentContext);
829
+ if (maybeParentSpan._tag === "None") return oldTracer.context(f, fiber);
830
+ const parentSpan = maybeParentSpan.value;
831
+ if (parentSpan._tag === "ExternalSpan") return oldTracer.context(f, fiber);
832
+ const span = parentSpan;
833
+ if (runInTask in span && typeof span[runInTask] === "function") {
834
+ return span[runInTask](() => oldTracer.context(f, fiber));
835
+ }
836
+ return oldTracer.context(f, fiber);
837
+ }
838
+ });
839
+ });
840
+ return pipe3(makeTracer, Effect7.map(Layer.setTracer), Layer.unwrapEffect);
841
+ };
635
842
  export {
843
+ dynamic_runtime_exports as DynamicRuntime,
636
844
  JsonPath,
637
845
  JsonProp,
638
846
  ParamKeyAnnotation,
639
- SimpleType,
640
- TestContextService,
641
- TestHelpers,
847
+ Performance_exports as Performance,
848
+ RuntimeProvider_exports as RuntimeProvider,
642
849
  UrlParser,
643
850
  VisitResult,
644
851
  acquireReleaseResource,
852
+ asyncTaskTaggingLayer,
645
853
  causeToError,
646
854
  contextFromScope,
647
855
  createJsonPath,
856
+ createKvsStore,
648
857
  findAnnotation,
649
858
  findNode,
650
859
  findProperty,
651
860
  fromEffectValidationPath,
652
861
  getAnnotation2 as getAnnotation,
862
+ getArrayElementType,
863
+ getBaseType,
653
864
  getDiscriminatedType,
654
865
  getDiscriminatingProps,
655
866
  getField,
656
867
  getParamKeyAnnotation,
657
- getSimpleType,
868
+ getProperties,
869
+ getValue,
658
870
  isArrayType,
659
871
  isDiscriminatedUnion,
660
872
  isJsonPath,
661
873
  isLiteralUnion,
874
+ isNestedType,
662
875
  isOption,
663
- isSimpleType,
876
+ isTupleType2 as isTupleType,
664
877
  mapAst,
665
878
  promiseWithCauseCapture,
666
879
  runAndForwardErrors,
880
+ runInRuntime,
881
+ setValue,
667
882
  splitJsonPath,
668
883
  throwCause,
669
884
  unwrapExit,