@rocicorp/zero 1.12.0-head-e1bf42ac-20261111 → 1.13.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/out/shared/src/bigint-json.d.ts +6 -0
  2. package/out/shared/src/bigint-json.d.ts.map +1 -1
  3. package/out/shared/src/bigint-json.js +14 -1
  4. package/out/shared/src/bigint-json.js.map +1 -1
  5. package/out/shared/src/objects.d.ts +7 -0
  6. package/out/shared/src/objects.d.ts.map +1 -1
  7. package/out/shared/src/objects.js +10 -1
  8. package/out/shared/src/objects.js.map +1 -1
  9. package/out/shared/src/resolver.d.ts.map +1 -1
  10. package/out/shared/src/resolver.js +12 -1
  11. package/out/shared/src/resolver.js.map +1 -1
  12. package/out/zero/package.js +1 -1
  13. package/out/zero/package.js.map +1 -1
  14. package/out/zero-cache/src/auth/write-authorizer.js +4 -3
  15. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  16. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  17. package/out/zero-cache/src/config/normalize.js +3 -23
  18. package/out/zero-cache/src/config/normalize.js.map +1 -1
  19. package/out/zero-cache/src/config/zero-config.d.ts +1 -27
  20. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  21. package/out/zero-cache/src/config/zero-config.js +19 -47
  22. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  23. package/out/zero-cache/src/custom/fetch.js +17 -2
  24. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  25. package/out/zero-cache/src/db/create.js +45 -1
  26. package/out/zero-cache/src/db/create.js.map +1 -1
  27. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  28. package/out/zero-cache/src/db/lite-tables.js +4 -3
  29. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  30. package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
  31. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
  32. package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
  33. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  34. package/out/zero-cache/src/db/pg-to-lite.js +84 -1
  35. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  36. package/out/zero-cache/src/server/change-streamer.js +21 -30
  37. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  38. package/out/zero-cache/src/server/main.js +0 -1
  39. package/out/zero-cache/src/server/main.js.map +1 -1
  40. package/out/zero-cache/src/server/replicator.js +1 -1
  41. package/out/zero-cache/src/server/replicator.js.map +1 -1
  42. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
  43. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/change-source.js +49 -11
  45. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
  47. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  48. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
  49. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  50. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
  51. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  52. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
  53. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  54. package/out/zero-cache/src/services/change-source/pg/schema/init.js +59 -3
  55. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  56. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
  57. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
  59. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  60. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
  61. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
  63. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  64. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  68. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
  69. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  70. package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
  71. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  72. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
  73. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  74. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
  75. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  76. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
  77. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  78. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  79. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  80. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
  82. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
  83. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
  84. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
  85. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  86. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
  89. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  90. package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
  91. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  92. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
  93. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
  95. package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
  96. package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
  97. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  98. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
  99. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  100. package/out/zero-cache/src/services/replicator/change-processor.js +82 -9
  101. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  102. package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
  103. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  104. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
  105. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
  106. package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
  107. package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
  108. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  109. package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
  110. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  111. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
  112. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  113. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  114. package/out/zero-cache/src/services/statz.js +1 -1
  115. package/out/zero-cache/src/services/statz.js.map +1 -1
  116. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  117. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  118. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
  119. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
  120. package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
  121. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  122. package/out/zero-cache/src/types/lite.d.ts +7 -0
  123. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  124. package/out/zero-cache/src/types/lite.js +12 -2
  125. package/out/zero-cache/src/types/lite.js.map +1 -1
  126. package/out/zero-cache/src/types/pg-types.d.ts +2 -1
  127. package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
  128. package/out/zero-cache/src/types/pg-types.js +2 -1
  129. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  130. package/out/zero-cache/src/types/pg.d.ts +20 -0
  131. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  132. package/out/zero-cache/src/types/pg.js +64 -29
  133. package/out/zero-cache/src/types/pg.js.map +1 -1
  134. package/out/zero-cache/src/types/streams.d.ts +2 -0
  135. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  136. package/out/zero-cache/src/types/streams.js +2 -1
  137. package/out/zero-cache/src/types/streams.js.map +1 -1
  138. package/out/zero-cache/src/workers/replicator.js +7 -6
  139. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  140. package/out/zero-cache/src/workers/syncer.js +18 -1
  141. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  142. package/out/zero-client/src/client/version.js +1 -1
  143. package/package.json +1 -1
  144. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
  145. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
  146. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
  147. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
  148. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
  149. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
  150. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
  151. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
@@ -28,6 +28,12 @@ export declare function parse(str: string, reviver?: (k: string, v: unknown) =>
28
28
  * handle bigints passed to downstream logic.
29
29
  */
30
30
  export declare function stringify(obj: unknown, replacer?: (string | number)[] | ((key: string, value: unknown) => unknown) | null, indent?: string | number): string;
31
+ /**
32
+ * {@link stringify} that keeps infinite numbers, which it would otherwise turn
33
+ * into `null`. This is for data read back with {@link parse} between server
34
+ * components, and not for data sent to clients.
35
+ */
36
+ export declare function stringifyWithInfinity(obj: unknown): string;
31
37
  export declare const BigIntJSON: {
32
38
  readonly parse: typeof parse;
33
39
  readonly stringify: typeof stringify;
@@ -1 +1 @@
1
- {"version":3,"file":"bigint-json.d.ts","sourceRoot":"","sources":["../../../../shared/src/bigint-json.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,CAAC,MAAM,aAAa,CAAC;AAYjC,MAAM,MAAM,SAAS,GACjB,IAAI,GACJ,MAAM,GACN,MAAM,GACN,MAAM,GACN,OAAO,GACP,SAAS,SAAS,EAAE,GACpB,UAAU,CAAC;AAEf,MAAM,MAAM,UAAU,GAAG;IAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAAA;CAAC,CAAC;AAE1E,eAAO,MAAM,eAAe,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAY5C,CAAC;AAEH,eAAO,MAAM,gBAAgB,6CAAwC,CAAC;AAUtE;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO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AAG,EAAE,OAAO,EACZ,QAAQ,CAAC,EACL,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,GACnB,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,GAC1C,IAAI,EACR,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,UAGzB;AAcD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAE1D;AAED,eAAO,MAAM,UAAU;;;CAGb,CAAC"}
@@ -64,11 +64,24 @@ function customSerializer(_, v, type) {
64
64
  function stringify$1(obj, replacer, indent) {
65
65
  return stringify(obj, replacer, indent, customSerializer);
66
66
  }
67
+ var INFINITY_JSON = "1e999";
68
+ function infinitySerializer(k, v, type) {
69
+ if (type === "number" && Math.abs(v) === Infinity) return v > 0 ? INFINITY_JSON : `-${INFINITY_JSON}`;
70
+ return customSerializer(k, v, type);
71
+ }
72
+ /**
73
+ * {@link stringify} that keeps infinite numbers, which it would otherwise turn
74
+ * into `null`. This is for data read back with {@link parse} between server
75
+ * components, and not for data sent to clients.
76
+ */
77
+ function stringifyWithInfinity(obj) {
78
+ return stringify(obj, void 0, void 0, infinitySerializer);
79
+ }
67
80
  var BigIntJSON = {
68
81
  parse: parse$1,
69
82
  stringify: stringify$1
70
83
  };
71
84
  //#endregion
72
- export { BigIntJSON, hasUnsafeIntegerDigits, jsonObjectSchema, jsonValueSchema, parse$1 as parse, stringify$1 as stringify };
85
+ export { BigIntJSON, hasUnsafeIntegerDigits, jsonObjectSchema, jsonValueSchema, parse$1 as parse, stringify$1 as stringify, stringifyWithInfinity };
73
86
 
74
87
  //# sourceMappingURL=bigint-json.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bigint-json.js","names":["v","v.readonly","parse","customParse","stringify","customStringify"],"sources":["../../../../shared/src/bigint-json.ts"],"sourcesContent":["/**\n * Background for using `json-custom-numbers`:\n *\n * https://neon.tech/blog/parsing-json-from-postgres-in-js\n */\nimport {\n parse as customParse,\n stringify as customStringify,\n} from 'json-custom-numbers';\nimport * as v from './valita.ts';\n\nfunction numberParser(_: unknown, v: string) {\n const n = +v;\n if (n >= Number.MIN_SAFE_INTEGER && n <= Number.MAX_SAFE_INTEGER) return n;\n if (v.includes('.') || v.includes('e') || v.includes('E')) {\n return n;\n }\n return BigInt(v);\n}\n\n// Variant of postgres.JSONValue adapted to include bigints\nexport type JSONValue =\n | null\n | string\n | number\n | bigint\n | boolean\n | readonly JSONValue[]\n | JSONObject;\n\nexport type JSONObject = {readonly [prop: string]: JSONValue | undefined};\n\nexport const jsonValueSchema: v.Type<JSONValue> = v.lazy(() => {\n const jsonObjectSchema = v.readonly(v.record(jsonValueSchema));\n\n return v.union(\n v.null(),\n v.string(),\n v.number(),\n v.bigint(),\n v.boolean(),\n v.readonly(v.array(jsonValueSchema)),\n jsonObjectSchema,\n );\n});\n\nexport const jsonObjectSchema = v.readonly(v.record(jsonValueSchema));\n\n// Integers of up to 15 digits are safe, so only a run of 16 or more digits can\n// be an integer that needs the (much slower) custom number parsing.\nconst UNSAFE_INTEGER_DIGITS = 16;\n\nfunction isDigit(c: number): boolean {\n return c >= 48 && c <= 57;\n}\n\n/**\n * Whether `str` has a run of 16 or more digits. Every such run covers one of\n * every 16 consecutive indices, so only every 16th char needs to be checked and\n * a digit there is expanded to its full run. This is several times faster than\n * `/\\d{16}/`, which restarts at every digit of a shorter run.\n *\n * A run inside a JSON string also matches; that merely takes the slow path.\n */\nexport function hasUnsafeIntegerDigits(str: string): boolean {\n const n = str.length;\n for (let i = UNSAFE_INTEGER_DIGITS - 1; i < n; i += UNSAFE_INTEGER_DIGITS) {\n if (!isDigit(str.charCodeAt(i))) {\n continue;\n }\n let start = i;\n while (start > 0 && isDigit(str.charCodeAt(start - 1))) {\n start--;\n }\n let end = i + 1;\n while (end < n && isDigit(str.charCodeAt(end))) {\n end++;\n }\n if (end - start >= UNSAFE_INTEGER_DIGITS) {\n return true;\n }\n // The next run starts after `end`, and covers one of every 16 indices from\n // there on.\n i = end - 1;\n }\n return false;\n}\n\n/**\n * Parses JSON strings that may contain arbitrarily large integers. Integers\n * larger than {@link Number.MAX_SAFE_INTEGER} are deserialized as a `bigint`.\n */\nexport function parse(\n str: string,\n reviver?: (k: string, v: unknown) => unknown,\n): JSONValue {\n return hasUnsafeIntegerDigits(str)\n ? customParse(str, reviver, numberParser)\n : JSON.parse(str, reviver);\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction customSerializer(_: string, v: any, type: string) {\n if (type === 'bigint') return v.toString();\n // An integer beyond the safe range is a rounded double if it is a number, so\n // it is written in a form that parse() keeps as a number. As digits it would\n // come back as a bigint, and not even the same value, since a double prints\n // only the digits that identify it: 2^62 is 4611686018427388000.\n if (type === 'number' && Number.isInteger(v) && !Number.isSafeInteger(v)) {\n return v.toExponential();\n }\n}\n\n/**\n * Stringifies objects to JSON, supporting objects containing bigint values.\n * Note that the resulting JSON string may not be deserializable by\n * all environments, but it is supported by Postgres. The string should be\n * deserialized with the corresponding {@link parse} method that will represent\n * large numbers as bigints. From there it is up to the application to suitably\n * handle bigints passed to downstream logic.\n */\nexport function stringify(\n obj: unknown,\n replacer?:\n | (string | number)[]\n | ((key: string, value: unknown) => unknown)\n | null,\n indent?: string | number,\n) {\n return customStringify(obj, replacer, indent, customSerializer);\n}\n\nexport const BigIntJSON = {\n parse,\n stringify,\n} as const;\n"],"mappings":";;;;;;;;AAWA,SAAS,aAAa,GAAY,GAAW;CAC3C,MAAM,IAAI,CAAC;CACX,IAAI,KAAK,OAAO,oBAAoB,KAAK,OAAO,kBAAkB,OAAO;CACzE,IAAI,EAAE,SAAS,GAAG,KAAK,EAAE,SAAS,GAAG,KAAK,EAAE,SAAS,GAAG,GACtD,OAAO;CAET,OAAO,OAAO,CAAC;AACjB;AAcA,IAAa,kBAAqCA,eAAE,WAAW;CAC7D,MAAM,mBAAmBC,SAAWD,eAAE,OAAO,eAAe,CAAC;CAE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ly","parse","customParse","stringify","customStringify"],"sources":["../../../../shared/src/bigint-json.ts"],"sourcesContent":["/**\n * Background for using `json-custom-numbers`:\n *\n * https://neon.tech/blog/parsing-json-from-postgres-in-js\n */\nimport {\n parse as customParse,\n stringify as customStringify,\n} from 'json-custom-numbers';\nimport * as v from './valita.ts';\n\nfunction numberParser(_: unknown, v: string) {\n const n = +v;\n if (n >= Number.MIN_SAFE_INTEGER && n <= Number.MAX_SAFE_INTEGER) return n;\n if (v.includes('.') || v.includes('e') || v.includes('E')) {\n return n;\n }\n return BigInt(v);\n}\n\n// Variant of postgres.JSONValue adapted to include bigints\nexport type JSONValue =\n | null\n | string\n | number\n | bigint\n | boolean\n | readonly JSONValue[]\n | JSONObject;\n\nexport type JSONObject = {readonly [prop: string]: JSONValue | undefined};\n\nexport const jsonValueSchema: v.Type<JSONValue> = v.lazy(() => {\n const jsonObjectSchema = v.readonly(v.record(jsonValueSchema));\n\n return v.union(\n v.null(),\n v.string(),\n v.number(),\n v.bigint(),\n v.boolean(),\n v.readonly(v.array(jsonValueSchema)),\n jsonObjectSchema,\n );\n});\n\nexport const jsonObjectSchema = v.readonly(v.record(jsonValueSchema));\n\n// Integers of up to 15 digits are safe, so only a run of 16 or more digits can\n// be an integer that needs the (much slower) custom number parsing.\nconst UNSAFE_INTEGER_DIGITS = 16;\n\nfunction isDigit(c: number): boolean {\n return c >= 48 && c <= 57;\n}\n\n/**\n * Whether `str` has a run of 16 or more digits. Every such run covers one of\n * every 16 consecutive indices, so only every 16th char needs to be checked and\n * a digit there is expanded to its full run. This is several times faster than\n * `/\\d{16}/`, which restarts at every digit of a shorter run.\n *\n * A run inside a JSON string also matches; that merely takes the slow path.\n */\nexport function hasUnsafeIntegerDigits(str: string): boolean {\n const n = str.length;\n for (let i = UNSAFE_INTEGER_DIGITS - 1; i < n; i += UNSAFE_INTEGER_DIGITS) {\n if (!isDigit(str.charCodeAt(i))) {\n continue;\n }\n let start = i;\n while (start > 0 && isDigit(str.charCodeAt(start - 1))) {\n start--;\n }\n let end = i + 1;\n while (end < n && isDigit(str.charCodeAt(end))) {\n end++;\n }\n if (end - start >= UNSAFE_INTEGER_DIGITS) {\n return true;\n }\n // The next run starts after `end`, and covers one of every 16 indices from\n // there on.\n i = end - 1;\n }\n return false;\n}\n\n/**\n * Parses JSON strings that may contain arbitrarily large integers. Integers\n * larger than {@link Number.MAX_SAFE_INTEGER} are deserialized as a `bigint`.\n */\nexport function parse(\n str: string,\n reviver?: (k: string, v: unknown) => unknown,\n): JSONValue {\n return hasUnsafeIntegerDigits(str)\n ? customParse(str, reviver, numberParser)\n : JSON.parse(str, reviver);\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction customSerializer(_: string, v: any, type: string) {\n if (type === 'bigint') return v.toString();\n // An integer beyond the safe range is a rounded double if it is a number, so\n // it is written in a form that parse() keeps as a number. As digits it would\n // come back as a bigint, and not even the same value, since a double prints\n // only the digits that identify it: 2^62 is 4611686018427388000.\n if (type === 'number' && Number.isInteger(v) && !Number.isSafeInteger(v)) {\n return v.toExponential();\n }\n}\n\n/**\n * Stringifies objects to JSON, supporting objects containing bigint values.\n * Note that the resulting JSON string may not be deserializable by\n * all environments, but it is supported by Postgres. The string should be\n * deserialized with the corresponding {@link parse} method that will represent\n * large numbers as bigints. From there it is up to the application to suitably\n * handle bigints passed to downstream logic.\n */\nexport function stringify(\n obj: unknown,\n replacer?:\n | (string | number)[]\n | ((key: string, value: unknown) => unknown)\n | null,\n indent?: string | number,\n) {\n return customStringify(obj, replacer, indent, customSerializer);\n}\n\n// JSON has no literal for Infinity, but it can spell a number too large for a\n// double, which every JSON parser reads back as Infinity.\nconst INFINITY_JSON = '1e999';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction infinitySerializer(k: string, v: any, type: string) {\n if (type === 'number' && Math.abs(v) === Infinity) {\n return v > 0 ? INFINITY_JSON : `-${INFINITY_JSON}`;\n }\n return customSerializer(k, v, type);\n}\n\n/**\n * {@link stringify} that keeps infinite numbers, which it would otherwise turn\n * into `null`. This is for data read back with {@link parse} between server\n * components, and not for data sent to clients.\n */\nexport function stringifyWithInfinity(obj: unknown): string {\n return customStringify(obj, undefined, undefined, infinitySerializer);\n}\n\nexport const BigIntJSON = {\n parse,\n stringify,\n} as const;\n"],"mappings":";;;;;;;;AAWA,SAAS,aAAa,GAAY,GAAW;CAC3C,MAAM,IAAI,CAAC;CACX,IAAI,KAAK,OAAO,oBAAoB,KAAK,OAAO,kBAAkB,OAAO;CACzE,IAAI,EAAE,SAAS,GAAG,KAAK,EAAE,SAAS,GAAG,KAAK,EAAE,SAAS,GAAG,GACtD,OAAO;CAET,OAAO,OAAO,CAAC;AACjB;AAcA,IAAa,kBAAqCA,eAAE,WAAW;CAC7D,MAAM,mBAAmBC,SAAWD,eAAE,OAAO,eAAe,CAAC;CAE7D,OAAOA,eAAE,MACPA,eAAE,KAAK,GACPA,eAAE,OAAO,GACTA,eAAE,OAAO,GACTA,eAAE,OAAO,GACTA,eAAE,QAAQ,GACVC,SAAWD,eAAE,MAAM,eAAe,CAAC,GACnC,gBACF;AACF,CAAC;AAED,IAAa,mBAAmBC,SAAWD,eAAE,OAAO,eAAe,CAAC;AAIpE,IAAM,wBAAwB;AAE9B,SAAS,QAAQ,GAAoB;CACnC,OAAO,KAAK,MAAM,KAAK;AACzB;;;;;;;;;AAUA,SAAgB,uBAAuB,KAAsB;CAC3D,MAAM,IAAI,IAAI;CACd,KAAK,IAAI,IAAI,IAA2B,IAAI,GAAG,KAAK,uBAAuB;EACzE,IAAI,CAAC,QAAQ,IAAI,WAAW,CAAC,CAAC,GAC5B;EAEF,IAAI,QAAQ;EACZ,OAAO,QAAQ,KAAK,QAAQ,IAAI,WAAW,QAAQ,CAAC,CAAC,GACnD;EAEF,IAAI,MAAM,IAAI;EACd,OAAO,MAAM,KAAK,QAAQ,IAAI,WAAW,GAAG,CAAC,GAC3C;EAEF,IAAI,MAAM,SAAS,uBACjB,OAAO;EAIT,IAAI,MAAM;CACZ;CACA,OAAO;AACT;;;;;AAMA,SAAgBE,QACd,KACA,SACW;CACX,OAAO,uBAAuB,GAAG,IAC7BC,MAAY,KAAK,SAAS,YAAY,IACtC,KAAK,MAAM,KAAK,OAAO;AAC7B;AAGA,SAAS,iBAAiB,GAAW,GAAQ,MAAc;CACzD,IAAI,SAAS,UAAU,OAAO,EAAE,SAAS;CAKzC,IAAI,SAAS,YAAY,OAAO,UAAU,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,GACrE,OAAO,EAAE,cAAc;AAE3B;;;;;;;;;AAUA,SAAgBC,YACd,KACA,UAIA,QACA;CACA,OAAOC,UAAgB,KAAK,UAAU,QAAQ,gBAAgB;AAChE;AAIA,IAAM,gBAAgB;AAGtB,SAAS,mBAAmB,GAAW,GAAQ,MAAc;CAC3D,IAAI,SAAS,YAAY,KAAK,IAAI,CAAC,MAAM,UACvC,OAAO,IAAI,IAAI,gBAAgB,IAAI;CAErC,OAAO,iBAAiB,GAAG,GAAG,IAAI;AACpC;;;;;;AAOA,SAAgB,sBAAsB,KAAsB;CAC1D,OAAOA,UAAgB,KAAK,KAAA,GAAW,KAAA,GAAW,kBAAkB;AACtE;AAEA,IAAa,aAAa;CACxB,OAAA;CACA,WAAA;AACF"}
@@ -6,6 +6,13 @@ export declare function mapValues<T extends Record<string, unknown>, U>(input: T
6
6
  * `__proto__` setter. This is used to avoid prototype pollution attacks.
7
7
  */
8
8
  export declare function assignProperty<K extends string | number | symbol, T>(object: Record<K, T>, key: K, value: T): void;
9
+ /**
10
+ * Reads an own property of `object`, or `undefined` when `object` has no own
11
+ * property named `key`. A plain `object[key]` also finds inherited
12
+ * properties, so `object['__proto__']` is `Object.prototype` on an object
13
+ * with no such property of its own.
14
+ */
15
+ export declare function getOwnProperty<T>(object: Readonly<Record<string, T>>, key: string): T | undefined;
9
16
  export declare function mapEntries<T, U>(input: Record<string, T>, mapper: (key: string, val: T) => [key: string, val: U]): Record<string, U>;
10
17
  export declare function mapAllEntries<T, U>(input: Record<string, T>, mapper: (entries: [key: string, val: T][]) => [key: string, val: U][]): Record<string, U>;
11
18
  //# sourceMappingURL=objects.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"objects.d.ts","sourceRoot":"","sources":["../../../../shared/src/objects.ts"],"names":[],"mappings":"AAAA,wBAAgB,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAC5D,KAAK,EAAE,CAAC,EACR,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,MAAM,KAAK,CAAC,GACtD;KAAE,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC;CAAC,CAWrB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC,EAClE,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACpB,GAAG,EAAE,CAAC,EACN,KAAK,EAAE,CAAC,GACP,IAAI,CAeN;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,EAC7B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EACxB,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,GACrD,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CASnB;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,CAAC,EAChC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EACxB,MAAM,EAAE,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,GACpE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AE,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,GACpE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAQnB"}
@@ -17,6 +17,15 @@ function assignProperty(object, key, value) {
17
17
  });
18
18
  object[key] = value;
19
19
  }
20
+ /**
21
+ * Reads an own property of `object`, or `undefined` when `object` has no own
22
+ * property named `key`. A plain `object[key]` also finds inherited
23
+ * properties, so `object['__proto__']` is `Object.prototype` on an object
24
+ * with no such property of its own.
25
+ */
26
+ function getOwnProperty(object, key) {
27
+ return Object.hasOwn(object, key) ? object[key] : void 0;
28
+ }
20
29
  function mapEntries(input, mapper) {
21
30
  const output = {};
22
31
  for (const entry of Object.entries(input)) {
@@ -31,6 +40,6 @@ function mapAllEntries(input, mapper) {
31
40
  return output;
32
41
  }
33
42
  //#endregion
34
- export { assignProperty, mapAllEntries, mapEntries, mapValues };
43
+ export { assignProperty, getOwnProperty, mapAllEntries, mapEntries, mapValues };
35
44
 
36
45
  //# sourceMappingURL=objects.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"objects.js","names":[],"sources":["../../../../shared/src/objects.ts"],"sourcesContent":["export function mapValues<T extends Record<string, unknown>, U>(\n input: T,\n mapper: (value: T[keyof T], key: keyof T & string) => U,\n): {[K in keyof T]: U} {\n const output = {} as {[K in keyof T]: U};\n\n for (const entry of Object.entries(input) as [\n keyof T & string,\n T[keyof T],\n ][]) {\n assignProperty(output, entry[0], mapper(entry[1], entry[0]));\n }\n\n return output;\n}\n\n/**\n * Safe function of `[[Set]]`/assign that prevents invoking the legacy\n * `__proto__` setter. This is used to avoid prototype pollution attacks.\n */\nexport function assignProperty<K extends string | number | symbol, T>(\n object: Record<K, T>,\n key: K,\n value: T,\n): void {\n if (key === '__proto__') {\n // Shadow the `__proto__` property on the object to prevent prototype\n // pollution.\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n // fall through to the normal assignment to ensure that potentional Proxy\n // traps are invoked.\n }\n\n object[key] = value;\n}\n\nexport function mapEntries<T, U>(\n input: Record<string, T>,\n mapper: (key: string, val: T) => [key: string, val: U],\n): Record<string, U> {\n const output: Record<string, U> = {};\n\n for (const entry of Object.entries(input)) {\n const mapped = mapper(entry[0], entry[1]);\n assignProperty(output, mapped[0], mapped[1]);\n }\n\n return output;\n}\n\nexport function mapAllEntries<T, U>(\n input: Record<string, T>,\n mapper: (entries: [key: string, val: T][]) => [key: string, val: U][],\n): Record<string, U> {\n const output: Record<string, U> = {};\n\n for (const [key, val] of mapper(Object.entries(input))) {\n assignProperty(output, key, val);\n }\n\n return output;\n}\n"],"mappings":";AAAA,SAAgB,UACd,OACA,QACqB;CACrB,MAAM,SAAS,CAAC;CAEhB,KAAK,MAAM,SAAS,OAAO,QAAQ,KAAK,GAItC,eAAe,QAAQ,MAAM,IAAI,OAAO,MAAM,IAAI,MAAM,EAAE,CAAC;CAG7D,OAAO;AACT;;;;;AAMA,SAAgB,eACd,QACA,KACA,OACM;CACN,IAAI,QAAQ,aAGV,OAAO,eAAe,QAAQ,KAAK;EACjC;EACA,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CAKH,OAAO,OAAO;AAChB;AAEA,SAAgB,WACd,OACA,QACmB;CACnB,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,SAAS,OAAO,QAAQ,KAAK,GAAG;EACzC,MAAM,SAAS,OAAO,MAAM,IAAI,MAAM,EAAE;EACxC,eAAe,QAAQ,OAAO,IAAI,OAAO,EAAE;CAC7C;CAEA,OAAO;AACT;AAEA,SAAgB,cACd,OACA,QACmB;CACnB,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,OAAO,QAAQ,KAAK,CAAC,GACnD,eAAe,QAAQ,KAAK,GAAG;CAGjC,OAAO;AACT"}
1
+ {"version":3,"file":"objects.js","names":[],"sources":["../../../../shared/src/objects.ts"],"sourcesContent":["export function mapValues<T extends Record<string, unknown>, U>(\n input: T,\n mapper: (value: T[keyof T], key: keyof T & string) => U,\n): {[K in keyof T]: U} {\n const output = {} as {[K in keyof T]: U};\n\n for (const entry of Object.entries(input) as [\n keyof T & string,\n T[keyof T],\n ][]) {\n assignProperty(output, entry[0], mapper(entry[1], entry[0]));\n }\n\n return output;\n}\n\n/**\n * Safe function of `[[Set]]`/assign that prevents invoking the legacy\n * `__proto__` setter. This is used to avoid prototype pollution attacks.\n */\nexport function assignProperty<K extends string | number | symbol, T>(\n object: Record<K, T>,\n key: K,\n value: T,\n): void {\n if (key === '__proto__') {\n // Shadow the `__proto__` property on the object to prevent prototype\n // pollution.\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n // fall through to the normal assignment to ensure that potentional Proxy\n // traps are invoked.\n }\n\n object[key] = value;\n}\n\n/**\n * Reads an own property of `object`, or `undefined` when `object` has no own\n * property named `key`. A plain `object[key]` also finds inherited\n * properties, so `object['__proto__']` is `Object.prototype` on an object\n * with no such property of its own.\n */\nexport function getOwnProperty<T>(\n object: Readonly<Record<string, T>>,\n key: string,\n): T | undefined {\n return Object.hasOwn(object, key) ? object[key] : undefined;\n}\n\nexport function mapEntries<T, U>(\n input: Record<string, T>,\n mapper: (key: string, val: T) => [key: string, val: U],\n): Record<string, U> {\n const output: Record<string, U> = {};\n\n for (const entry of Object.entries(input)) {\n const mapped = mapper(entry[0], entry[1]);\n assignProperty(output, mapped[0], mapped[1]);\n }\n\n return output;\n}\n\nexport function mapAllEntries<T, U>(\n input: Record<string, T>,\n mapper: (entries: [key: string, val: T][]) => [key: string, val: U][],\n): Record<string, U> {\n const output: Record<string, U> = {};\n\n for (const [key, val] of mapper(Object.entries(input))) {\n assignProperty(output, key, val);\n }\n\n return output;\n}\n"],"mappings":";AAAA,SAAgB,UACd,OACA,QACqB;CACrB,MAAM,SAAS,CAAC;CAEhB,KAAK,MAAM,SAAS,OAAO,QAAQ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M,QAAQ,EAAE,aAA6C,CAAC"}
1
+ {"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../../../shared/src/resolver.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,QAAQ,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,OAAO;IAC7C,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC;IAC1B,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC;CAC1B;AAED,KAAK,aAAa,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,OAAO,OAAO,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjE,eAAO,MAAM,QAAQ,EAAE,aAWhB,CAAC"}
@@ -1,5 +1,16 @@
1
1
  //#region ../shared/src/resolver.ts
2
- var resolver = () => Promise.withResolvers();
2
+ var resolver = typeof Promise.withResolvers === "function" ? () => Promise.withResolvers() : () => {
3
+ let resolve;
4
+ let reject;
5
+ return {
6
+ promise: new Promise((res, rej) => {
7
+ resolve = res;
8
+ reject = rej;
9
+ }),
10
+ resolve,
11
+ reject
12
+ };
13
+ };
3
14
  //#endregion
4
15
  export { resolver };
5
16
 
@@ -1 +1 @@
1
- {"version":3,"file":"resolver.js","names":[],"sources":["../../../../shared/src/resolver.ts"],"sourcesContent":["export interface Resolver<R = void, E = unknown> {\n promise: Promise<R>;\n resolve: (res: R) => void;\n reject: (err: E) => void;\n}\n\ntype WithResolvers = <R = void, E = unknown>() => Resolver<R, E>;\n\nexport const resolver: WithResolvers = () => Promise.withResolvers();\n"],"mappings":";AAQA,IAAa,iBAAgC,QAAQ,cAAc"}
1
+ {"version":3,"file":"resolver.js","names":[],"sources":["../../../../shared/src/resolver.ts"],"sourcesContent":["export interface Resolver<R = void, E = unknown> {\n promise: Promise<R>;\n resolve: (res: R) => void;\n reject: (err: E) => void;\n}\n\ntype WithResolvers = <R = void, E = unknown>() => Resolver<R, E>;\n\nexport const resolver: WithResolvers =\n typeof Promise.withResolvers === 'function'\n ? () => Promise.withResolvers()\n : <R = void, E = unknown>() => {\n let resolve!: (res: R) => void;\n let reject!: (err: E) => void;\n const promise = new Promise<R>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return {promise, resolve, reject};\n };\n"],"mappings":";AAQA,IAAa,WACX,OAAO,QAAQ,kBAAkB,mBACvB,QAAQ,cAAc,UACC;CAC3B,IAAI;CACJ,IAAI;CAKJ,OAAO;EAAC,SAAA,IAJY,SAAY,KAAK,QAAQ;GAC3C,UAAU;GACV,SAAS;EACX,CACQ;EAAS;EAAS;CAAM;AAClC"}
@@ -1,6 +1,6 @@
1
1
  //#region package.json
2
2
  var name = "@rocicorp/zero";
3
- var version = "1.12.0-head-e1bf42ac-20261111";
3
+ var version = "1.13.0-canary.0";
4
4
  var description = "Zero is a web framework for serverless web development.";
5
5
  var homepage = "https://zero.rocicorp.dev";
6
6
  var bugs = { "url": "https://bugs.rocicorp.dev" };
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.12.0-head-e1bf42ac-20261111\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --quiet --config ../../oxlint.config.ts src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.5.5\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.66.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.1.0\",\n \"@fastify/websocket\": \"^11.2.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"1.9.1\",\n \"@opentelemetry/api-logs\": \"0.223.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"0.81.2\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"0.223.0\",\n \"@opentelemetry/resources\": \"2.12.0\",\n \"@opentelemetry/sdk-metrics\": \"2.12.0\",\n \"@opentelemetry/sdk-node\": \"0.223.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.12.0\",\n \"@opentelemetry/semantic-conventions\": \"1.43.0\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^2.0.1\",\n \"@rocicorp/logger\": \"^6.1.0\",\n \"@rocicorp/zero-sqlite3\": \"^1.1.7\",\n \"@standard-schema/spec\": \"^1.1.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.18.1\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.2\",\n \"chokidar\": \"^4.0.3\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.2\",\n \"command-line-usage\": \"^7.0.4\",\n \"compare-utf8\": \"^0.2.3\",\n \"defu\": \"^6.1.7\",\n \"eventemitter3\": \"^5.0.4\",\n \"fastify\": \"^5.12.7\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.10.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.2\",\n \"nanoid\": \"^5.1.16\",\n \"oxc-parser\": \"^0.129.0\",\n \"oxfmt\": \"^0.74.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.8.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.22.0\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \"^18.2.5\",\n \"analyze-query\": \"workspace:*\",\n \"ast-to-zql\": \"workspace:*\",\n \"expo\": \"^58.0.14\",\n \"expo-sqlite\": \"^58.0.13\",\n \"react-native\": \"^0.88.0\",\n \"replicache\": \"workspace:*\",\n \"shared\": \"workspace:*\",\n \"syncpack\": \"^14.3.1\",\n \"typedoc\": \"^0.28.19\",\n \"typescript\": \"~7.0.2\",\n \"vite\": \"^8.3.4\",\n \"vitest\": \"^5.0.5\",\n \"zero-cache\": \"workspace:*\",\n \"zero-client\": \"workspace:*\",\n \"zero-pg\": \"workspace:*\",\n \"zero-react\": \"workspace:*\",\n \"zero-server\": \"workspace:*\",\n \"zero-solid\": \"workspace:*\",\n \"zqlite\": \"workspace:*\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"packageManager\": \"pnpm@11.11.0\"\n}\n"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.13.0-canary.0\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --quiet --config ../../oxlint.config.ts src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.5.5\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.66.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.1.0\",\n \"@fastify/websocket\": \"^11.2.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"1.9.1\",\n \"@opentelemetry/api-logs\": \"0.223.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"0.81.2\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"0.223.0\",\n \"@opentelemetry/resources\": \"2.12.0\",\n \"@opentelemetry/sdk-metrics\": \"2.12.0\",\n \"@opentelemetry/sdk-node\": \"0.223.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.12.0\",\n \"@opentelemetry/semantic-conventions\": \"1.43.0\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^2.0.1\",\n \"@rocicorp/logger\": \"^6.1.0\",\n \"@rocicorp/zero-sqlite3\": \"^1.1.7\",\n \"@standard-schema/spec\": \"^1.1.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.18.1\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.2\",\n \"chokidar\": \"^4.0.3\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.2\",\n \"command-line-usage\": \"^7.0.4\",\n \"compare-utf8\": \"^0.2.3\",\n \"defu\": \"^6.1.7\",\n \"eventemitter3\": \"^5.0.4\",\n \"fastify\": \"^5.12.7\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.10.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.2\",\n \"nanoid\": \"^5.1.16\",\n \"oxc-parser\": \"^0.129.0\",\n \"oxfmt\": \"^0.74.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.8.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.22.0\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \"^18.2.5\",\n \"analyze-query\": \"workspace:*\",\n \"ast-to-zql\": \"workspace:*\",\n \"expo\": \"^58.0.14\",\n \"expo-sqlite\": \"^58.0.13\",\n \"react-native\": \"^0.88.0\",\n \"replicache\": \"workspace:*\",\n \"shared\": \"workspace:*\",\n \"syncpack\": \"^14.3.1\",\n \"typedoc\": \"^0.28.19\",\n \"typescript\": \"~7.0.2\",\n \"vite\": \"^8.3.4\",\n \"vitest\": \"^5.0.5\",\n \"zero-cache\": \"workspace:*\",\n \"zero-client\": \"workspace:*\",\n \"zero-pg\": \"workspace:*\",\n \"zero-react\": \"workspace:*\",\n \"zero-server\": \"workspace:*\",\n \"zero-solid\": \"workspace:*\",\n \"zqlite\": \"workspace:*\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"packageManager\": \"pnpm@11.11.0\"\n}\n"],"mappings":""}
@@ -1,6 +1,7 @@
1
1
  import { assert } from "../../../shared/src/asserts.js";
2
2
  import { parse } from "../../../shared/src/valita.js";
3
3
  import { must } from "../../../shared/src/must.js";
4
+ import { assignProperty, getOwnProperty } from "../../../shared/src/objects.js";
4
5
  import { consume } from "../../../zql/src/ivm/stream.js";
5
6
  import { simplifyCondition } from "../../../zql/src/query/expression.js";
6
7
  import { asQueryInternals } from "../../../zql/src/query/query-internals.js";
@@ -154,9 +155,9 @@ var WriteAuthorizerImpl = class {
154
155
  const columns = tableSpec.tableSpec.primaryKey;
155
156
  const values = {};
156
157
  for (const col of columns) {
157
- const val = opValue[col];
158
+ const val = getOwnProperty(opValue, col);
158
159
  if (val === void 0) throw new Error(`Primary key column '${col}' is missing from operation value for table ${tableName}`);
159
- values[col] = val;
160
+ assignProperty(values, col, val);
160
161
  }
161
162
  return values;
162
163
  }
@@ -209,7 +210,7 @@ var WriteAuthorizerImpl = class {
209
210
  const cellPolicies = rules?.cell;
210
211
  const applicableCellPolicies = [];
211
212
  if (cellPolicies) for (const [column, policy] of Object.entries(cellPolicies)) {
212
- if (action === "update" && op.value[column] === void 0) continue;
213
+ if (action === "update" && getOwnProperty(op.value, column) === void 0) continue;
213
214
  switch (action) {
214
215
  case "insert":
215
216
  if (policy.insert && phase === "postMutation") applicableCellPolicies.push(policy.insert);
@@ -1 +1 @@
1
- {"version":3,"file":"write-authorizer.js","names":["v.parse"],"sources":["../../../../../zero-cache/src/auth/write-authorizer.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {MaybePromise} from '@opentelemetry/resources';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {Condition} from '../../../zero-protocol/src/ast.ts';\nimport type {\n CRUDOp,\n DeleteOp,\n InsertOp,\n UpdateOp,\n UpsertOp,\n} from '../../../zero-protocol/src/mutation.ts';\nimport {\n primaryKeyValueSchema,\n type PrimaryKeyValue,\n} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Policy} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {BuilderDelegate} from '../../../zql/src/builder/builder.ts';\nimport {\n bindStaticParameters,\n buildPipeline,\n} from '../../../zql/src/builder/builder.ts';\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {Query} from '../../../zql/src/query/query.ts';\nimport {newStaticQuery} from '../../../zql/src/query/static-query.ts';\nimport type {\n ClientGroupStorage,\n DatabaseStorage,\n} from '../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {compile, sql} from '../../../zqlite/src/internal/sql.ts';\nimport {\n fromSQLiteTypes,\n TableSource,\n} from '../../../zqlite/src/table-source.ts';\nimport type {LogConfig, ZeroConfig} from '../config/zero-config.ts';\nimport {computeZqlSpecs} from '../db/lite-tables.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {mapLiteDataTypeToZqlSchemaValue} from '../types/lite.ts';\nimport {\n getSchema,\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from './load-permissions.ts';\n\ntype Phase = 'preMutation' | 'postMutation';\n\nexport interface WriteAuthorizer {\n canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n reloadPermissions(): void;\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[];\n\n /**\n * Validates that all table names in the operations exist in the schema and\n * returns the operations with `primaryKey` replaced by the table's primary\n * key from the replica. The client-supplied `primaryKey` is not trusted: the\n * authorizer checks the row identified by the replica's primary key, so the\n * writes must target that same row.\n * @throws Error if any table name is invalid\n */\n validateOps(ops: CRUDOp[]): CRUDOp[];\n}\n\nexport class WriteAuthorizerImpl implements WriteAuthorizer {\n readonly #schema: Schema;\n readonly #replica: Database;\n readonly #builderDelegate: BuilderDelegate;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #tables = new Map<string, TableSource>();\n readonly #statementRunner: StatementRunner;\n readonly #lc: LogContext;\n readonly #appID: string;\n readonly #logConfig: LogConfig;\n readonly #cgStorage: ClientGroupStorage;\n readonly #config: ZeroConfig;\n\n #loadedPermissions: LoadedPermissions | null = null;\n\n constructor(\n lc: LogContext,\n config: ZeroConfig,\n replica: Database,\n appID: string,\n cgID: string,\n writeAuthzStorage: DatabaseStorage,\n ) {\n this.#appID = appID;\n this.#config = config;\n this.#lc = lc.withContext('class', 'WriteAuthorizerImpl');\n this.#logConfig = config.log;\n this.#schema = getSchema(this.#lc, replica);\n this.#replica = replica;\n this.#cgStorage = writeAuthzStorage.createClientGroupStorage(cgID);\n this.#builderDelegate = {\n disableCorrelatedPredicatePushdown:\n config.enableCorrelatedPredicatePushdown === false,\n getSource: name => this.#getSource(name),\n createStorage: () => this.#cgStorage.createStorage(),\n decorateSourceInput: input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n };\n this.#tableSpecs = computeZqlSpecs(this.#lc, replica, {\n includeBackfillingColumns: false,\n });\n this.#statementRunner = new StatementRunner(replica);\n this.reloadPermissions();\n }\n\n reloadPermissions() {\n this.#loadedPermissions = reloadPermissionsIfChanged(\n this.#lc,\n this.#statementRunner,\n this.#appID,\n this.#loadedPermissions,\n this.#config,\n ).permissions;\n }\n\n destroy() {\n this.#cgStorage.destroy();\n }\n\n async canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n // insert does not run pre-mutation checks\n break;\n case 'update':\n if (!(await this.#canUpdate('preMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n if (!(await this.#canDelete('preMutation', authData, op))) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n\n async canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n this.#statementRunner.beginConcurrent();\n let opError: unknown;\n try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(source.push(makeSourceChangeAdd(op.value)));\n break;\n }\n // TODO(mlaw): what if someone updates the same thing twice?\n // TODO(aa): It seems like it will just work? source.push()\n // is going to push the row into the table source, and then the\n // next requirePreMutationRow will just return the row that was\n // pushed in.\n case 'update': {\n consume(\n source.push(\n makeSourceChangeEdit(op.value, this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push(\n makeSourceChangeRemove(this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n }\n }\n\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n if (!(await this.#canInsert('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'update':\n if (!(await this.#canUpdate('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n // delete does not run post-mutation checks.\n break;\n }\n }\n } catch (e) {\n opError = e;\n throw e;\n } finally {\n try {\n this.#statementRunner.rollback();\n } catch (rollbackError) {\n if (opError !== undefined) {\n const combinedError = new Error(\n `canPostMutation failed and rollback also failed: operation error = ${String(opError)}; rollback error = ${String(rollbackError)}`,\n );\n combinedError.cause = opError;\n throw combinedError;\n }\n throw rollbackError;\n }\n }\n\n return true;\n }\n\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[] {\n return ops.map(op => {\n if (op.op === 'upsert') {\n const preMutationRow = this.#getPreMutationRow(op);\n if (preMutationRow) {\n return {\n op: 'update',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return {\n op: 'insert',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return op;\n });\n }\n\n validateOps(ops: CRUDOp[]): CRUDOp[] {\n return ops.map(op => {\n const tableSpec = this.#tableSpecs.get(op.tableName);\n if (!tableSpec) {\n throw new Error(`Table '${op.tableName}' is not a valid table.`);\n }\n return {...op, primaryKey: tableSpec.tableSpec.primaryKey};\n });\n }\n\n #canInsert(phase: Phase, authData: JWTPayload | undefined, op: InsertOp) {\n return this.#timedCanDo(phase, 'insert', authData, op);\n }\n\n #canUpdate(phase: Phase, authData: JWTPayload | undefined, op: UpdateOp) {\n return this.#timedCanDo(phase, 'update', authData, op);\n }\n\n #canDelete(phase: Phase, authData: JWTPayload | undefined, op: DeleteOp) {\n return this.#timedCanDo(phase, 'delete', authData, op);\n }\n\n /**\n * Gets schema-defined primary key and validates that operation contains required PK values.\n *\n * @returns Record where keys are column names and values are client-provided values\n * @throws Error if operation value is missing required primary key columns\n */\n #getPrimaryKey(\n tableName: string,\n opValue: Record<string, ReadonlyJSONValue | undefined>,\n ): Record<string, ReadonlyJSONValue> {\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const columns = tableSpec.tableSpec.primaryKey;\n\n // Extract primary key values from operation value and validate they exist\n const values: Record<string, ReadonlyJSONValue> = {};\n for (const col of columns) {\n const val = opValue[col];\n if (val === undefined) {\n throw new Error(\n `Primary key column '${col}' is missing from operation value for table ${tableName}`,\n );\n }\n values[col] = val;\n }\n\n return values;\n }\n\n #getSource(tableName: string) {\n let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const {columns, primaryKey} = tableSpec.tableSpec;\n assert(\n primaryKey.length,\n () => `Table ${tableName} must have a primary key`,\n );\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n this.#replica,\n tableName,\n Object.fromEntries(\n Object.entries(columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n [primaryKey[0], ...primaryKey.slice(1)],\n );\n this.#tables.set(tableName, source);\n\n return source;\n }\n\n async #timedCanDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const start = performance.now();\n try {\n const ret = await this.#canDo(phase, action, authData, op);\n return ret;\n } finally {\n this.#lc.info?.(\n 'action:',\n action,\n 'duration:',\n performance.now() - start,\n 'tableName:',\n op.tableName,\n 'primaryKey:',\n op.primaryKey,\n );\n }\n }\n\n /**\n * Evaluation order is from static to dynamic, broad to specific.\n * table -> column -> row -> cell.\n *\n * If any step fails, the entire operation is denied.\n *\n * That is, table rules supersede column rules, which supersede row rules,\n *\n * All steps must allow for the operation to be allowed.\n */\n async #canDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const rules = must(this.#loadedPermissions)?.permissions?.tables?.[\n op.tableName\n ];\n const rowPolicies = rules?.row;\n let rowQuery = newStaticQuery(this.#schema, op.tableName);\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, op.value);\n\n for (const pk in primaryKeyValues) {\n rowQuery = rowQuery.where(pk, '=', primaryKeyValues[pk]);\n }\n\n let applicableRowPolicy: Policy | undefined;\n switch (action) {\n case 'insert':\n if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.insert;\n }\n break;\n case 'update':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.update?.preMutation;\n } else if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.update?.postMutation;\n }\n break;\n case 'delete':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.delete;\n }\n break;\n }\n\n const cellPolicies = rules?.cell;\n const applicableCellPolicies: Policy[] = [];\n if (cellPolicies) {\n for (const [column, policy] of Object.entries(cellPolicies)) {\n if (action === 'update' && op.value[column] === undefined) {\n // If the cell is not being updated, we do not need to check\n // the cell rules.\n continue;\n }\n switch (action) {\n case 'insert':\n if (policy.insert && phase === 'postMutation') {\n applicableCellPolicies.push(policy.insert);\n }\n break;\n case 'update':\n if (phase === 'preMutation' && policy.update?.preMutation) {\n applicableCellPolicies.push(policy.update.preMutation);\n }\n if (phase === 'postMutation' && policy.update?.postMutation) {\n applicableCellPolicies.push(policy.update.postMutation);\n }\n break;\n case 'delete':\n if (policy.delete && phase === 'preMutation') {\n applicableCellPolicies.push(policy.delete);\n }\n break;\n }\n }\n }\n\n if (\n !(await this.#passesPolicyGroup(\n applicableRowPolicy,\n applicableCellPolicies,\n authData,\n rowQuery,\n ))\n ) {\n // `op.value` is the row being written and `authData` is the decoded\n // JWT payload, so neither can go into the log. Column names and policy\n // counts are enough to debug a failed permission check.\n this.#lc.warn?.('Permission check failed', {\n action,\n phase,\n tableName: op.tableName,\n columns: Object.keys(op.value),\n rowPolicy: applicableRowPolicy !== undefined,\n cellPolicyCount: applicableCellPolicies.length,\n });\n return false;\n }\n\n return true;\n }\n\n #getPreMutationRow(op: UpsertOp | UpdateOp | DeleteOp) {\n const {value} = op;\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, value);\n\n const spec = this.#tableSpecs.get(op.tableName);\n if (!spec) {\n throw new Error(`Table ${op.tableName} not found`);\n }\n\n const conditions: SQLQuery[] = [];\n const values: PrimaryKeyValue[] = [];\n for (const pk in primaryKeyValues) {\n conditions.push(sql`${sql.ident(pk)}=?`);\n values.push(v.parse(primaryKeyValues[pk], primaryKeyValueSchema));\n }\n\n const ret = this.#statementRunner.get(\n compile(\n sql`SELECT ${sql.join(\n Object.keys(spec.zqlSpec).map(c => sql.ident(c)),\n sql`,`,\n )} FROM ${sql.ident(op.tableName)} WHERE ${sql.join(\n conditions,\n sql` AND `,\n )}`,\n ),\n ...values,\n );\n if (ret === undefined) {\n return ret;\n }\n return fromSQLiteTypes(spec.zqlSpec, ret, op.tableName);\n }\n\n #requirePreMutationRow(op: UpdateOp | DeleteOp) {\n const ret = this.#getPreMutationRow(op);\n assert(\n ret !== undefined,\n () => `Pre-mutation row not found for ${JSON.stringify(op.value)}`,\n );\n return ret;\n }\n\n async #passesPolicyGroup(\n applicableRowPolicy: Policy | undefined,\n applicableCellPolicies: Policy[],\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ) {\n if (!(await this.#passesPolicy(applicableRowPolicy, authData, rowQuery))) {\n return false;\n }\n\n for (const policy of applicableCellPolicies) {\n if (!(await this.#passesPolicy(policy, authData, rowQuery))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Defaults to *false* if the policy is empty. At least one rule has to pass\n * for the policy to pass.\n */\n #passesPolicy(\n policy: Policy | undefined,\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ): MaybePromise<boolean> {\n if (policy === undefined) {\n return false;\n }\n if (policy.length === 0) {\n return false;\n }\n let rowQueryAst = asQueryInternals(rowQuery).ast;\n rowQueryAst = bindStaticParameters(\n {\n ...rowQueryAst,\n where: updateWhere(rowQueryAst.where, policy),\n },\n {\n authData: authData as Record<string, JSONValue>,\n preMutationRow: undefined,\n },\n );\n\n // call the compiler directly\n // run the sql against upstream.\n // remove the collecting into json? just need to know if a row comes back.\n\n const input = buildPipeline(rowQueryAst, this.#builderDelegate, 'query-id');\n try {\n const res = input.fetch({});\n for (const _ of res) {\n // if any row is returned at all, the\n // rule passes.\n return true;\n }\n } finally {\n input.destroy();\n }\n\n // no rows returned by any rules? The policy fails.\n return false;\n }\n}\n\nfunction updateWhere(where: Condition | undefined, policy: Policy) {\n assert(where, 'A where condition must exist for RowQuery');\n\n return simplifyCondition({\n type: 'and',\n conditions: [\n where,\n {\n type: 'or',\n conditions: policy.map(([action, rule]) => {\n assert(action, 'action must be defined in policy');\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAmFA,IAAa,sBAAb,MAA4D;CAC1D;CACA;CACA;CACA;CACA,0BAAmB,IAAI,IAAyB;CAChD;CACA;CACA;CACA;CACA;CACA;CAEA,qBAA+C;CAE/C,YACE,IACA,QACA,SACA,OACA,MACA,mBACA;EACA,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,MAAM,GAAG,YAAY,SAAS,qBAAqB;EACxD,KAAK,aAAa,OAAO;EACzB,KAAK,UAAU,UAAU,KAAK,KAAK,OAAO;EAC1C,KAAK,WAAW;EAChB,KAAK,aAAa,kBAAkB,yBAAyB,IAAI;EACjE,KAAK,mBAAmB;GACtB,oCACE,OAAO,sCAAsC;GAC/C,YAAW,SAAQ,KAAK,WAAW,IAAI;GACvC,qBAAqB,KAAK,WAAW,cAAc;GACnD,sBAAqB,UAAS;GAC9B,gBAAe,UAAS;GACxB,UAAU,CAAC;GACX,sBAAqB,UAAS;EAChC;EACA,KAAK,cAAc,gBAAgB,KAAK,KAAK,SAAS,EACpD,2BAA2B,MAC7B,CAAC;EACD,KAAK,mBAAmB,IAAI,gBAAgB,OAAO;EACnD,KAAK,kBAAkB;CACz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1E,IAAI;GACF,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;GAC1B,KAAK,MAAM,KAAK,KAGd,OAAO;EAEX,UAAU;GACR,MAAM,QAAQ;EAChB;EAGA,OAAO;CACT;AACF;AAEA,SAAS,YAAY,OAA8B,QAAgB;CACjE,OAAO,OAAO,2CAA2C;CAEzD,OAAO,kBAAkB;EACvB,MAAM;EACN,YAAY,CACV,OACA;GACE,MAAM;GACN,YAAY,OAAO,KAAK,CAAC,QAAQ,UAAU;IACzC,OAAO,QAAQ,kCAAkC;IACjD,OAAO;GACT,CAAC;EACH,CACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"write-authorizer.js","names":["v.parse"],"sources":["../../../../../zero-cache/src/auth/write-authorizer.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {MaybePromise} from '@opentelemetry/resources';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {assignProperty, getOwnProperty} from '../../../shared/src/objects.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {Condition} from '../../../zero-protocol/src/ast.ts';\nimport type {\n CRUDOp,\n DeleteOp,\n InsertOp,\n UpdateOp,\n UpsertOp,\n} from '../../../zero-protocol/src/mutation.ts';\nimport {\n primaryKeyValueSchema,\n type PrimaryKeyValue,\n} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Policy} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {BuilderDelegate} from '../../../zql/src/builder/builder.ts';\nimport {\n bindStaticParameters,\n buildPipeline,\n} from '../../../zql/src/builder/builder.ts';\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {Query} from '../../../zql/src/query/query.ts';\nimport {newStaticQuery} from '../../../zql/src/query/static-query.ts';\nimport type {\n ClientGroupStorage,\n DatabaseStorage,\n} from '../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {compile, sql} from '../../../zqlite/src/internal/sql.ts';\nimport {\n fromSQLiteTypes,\n TableSource,\n} from '../../../zqlite/src/table-source.ts';\nimport type {LogConfig, ZeroConfig} from '../config/zero-config.ts';\nimport {computeZqlSpecs} from '../db/lite-tables.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {mapLiteDataTypeToZqlSchemaValue} from '../types/lite.ts';\nimport {\n getSchema,\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from './load-permissions.ts';\n\ntype Phase = 'preMutation' | 'postMutation';\n\nexport interface WriteAuthorizer {\n canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n reloadPermissions(): void;\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[];\n\n /**\n * Validates that all table names in the operations exist in the schema and\n * returns the operations with `primaryKey` replaced by the table's primary\n * key from the replica. The client-supplied `primaryKey` is not trusted: the\n * authorizer checks the row identified by the replica's primary key, so the\n * writes must target that same row.\n * @throws Error if any table name is invalid\n */\n validateOps(ops: CRUDOp[]): CRUDOp[];\n}\n\nexport class WriteAuthorizerImpl implements WriteAuthorizer {\n readonly #schema: Schema;\n readonly #replica: Database;\n readonly #builderDelegate: BuilderDelegate;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #tables = new Map<string, TableSource>();\n readonly #statementRunner: StatementRunner;\n readonly #lc: LogContext;\n readonly #appID: string;\n readonly #logConfig: LogConfig;\n readonly #cgStorage: ClientGroupStorage;\n readonly #config: ZeroConfig;\n\n #loadedPermissions: LoadedPermissions | null = null;\n\n constructor(\n lc: LogContext,\n config: ZeroConfig,\n replica: Database,\n appID: string,\n cgID: string,\n writeAuthzStorage: DatabaseStorage,\n ) {\n this.#appID = appID;\n this.#config = config;\n this.#lc = lc.withContext('class', 'WriteAuthorizerImpl');\n this.#logConfig = config.log;\n this.#schema = getSchema(this.#lc, replica);\n this.#replica = replica;\n this.#cgStorage = writeAuthzStorage.createClientGroupStorage(cgID);\n this.#builderDelegate = {\n disableCorrelatedPredicatePushdown:\n config.enableCorrelatedPredicatePushdown === false,\n getSource: name => this.#getSource(name),\n createStorage: () => this.#cgStorage.createStorage(),\n decorateSourceInput: input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n };\n this.#tableSpecs = computeZqlSpecs(this.#lc, replica, {\n includeBackfillingColumns: false,\n });\n this.#statementRunner = new StatementRunner(replica);\n this.reloadPermissions();\n }\n\n reloadPermissions() {\n this.#loadedPermissions = reloadPermissionsIfChanged(\n this.#lc,\n this.#statementRunner,\n this.#appID,\n this.#loadedPermissions,\n this.#config,\n ).permissions;\n }\n\n destroy() {\n this.#cgStorage.destroy();\n }\n\n async canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n // insert does not run pre-mutation checks\n break;\n case 'update':\n if (!(await this.#canUpdate('preMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n if (!(await this.#canDelete('preMutation', authData, op))) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n\n async canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n this.#statementRunner.beginConcurrent();\n let opError: unknown;\n try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(source.push(makeSourceChangeAdd(op.value)));\n break;\n }\n // TODO(mlaw): what if someone updates the same thing twice?\n // TODO(aa): It seems like it will just work? source.push()\n // is going to push the row into the table source, and then the\n // next requirePreMutationRow will just return the row that was\n // pushed in.\n case 'update': {\n consume(\n source.push(\n makeSourceChangeEdit(op.value, this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push(\n makeSourceChangeRemove(this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n }\n }\n\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n if (!(await this.#canInsert('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'update':\n if (!(await this.#canUpdate('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n // delete does not run post-mutation checks.\n break;\n }\n }\n } catch (e) {\n opError = e;\n throw e;\n } finally {\n try {\n this.#statementRunner.rollback();\n } catch (rollbackError) {\n if (opError !== undefined) {\n const combinedError = new Error(\n `canPostMutation failed and rollback also failed: operation error = ${String(opError)}; rollback error = ${String(rollbackError)}`,\n );\n combinedError.cause = opError;\n throw combinedError;\n }\n throw rollbackError;\n }\n }\n\n return true;\n }\n\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[] {\n return ops.map(op => {\n if (op.op === 'upsert') {\n const preMutationRow = this.#getPreMutationRow(op);\n if (preMutationRow) {\n return {\n op: 'update',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return {\n op: 'insert',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return op;\n });\n }\n\n validateOps(ops: CRUDOp[]): CRUDOp[] {\n return ops.map(op => {\n const tableSpec = this.#tableSpecs.get(op.tableName);\n if (!tableSpec) {\n throw new Error(`Table '${op.tableName}' is not a valid table.`);\n }\n return {...op, primaryKey: tableSpec.tableSpec.primaryKey};\n });\n }\n\n #canInsert(phase: Phase, authData: JWTPayload | undefined, op: InsertOp) {\n return this.#timedCanDo(phase, 'insert', authData, op);\n }\n\n #canUpdate(phase: Phase, authData: JWTPayload | undefined, op: UpdateOp) {\n return this.#timedCanDo(phase, 'update', authData, op);\n }\n\n #canDelete(phase: Phase, authData: JWTPayload | undefined, op: DeleteOp) {\n return this.#timedCanDo(phase, 'delete', authData, op);\n }\n\n /**\n * Gets schema-defined primary key and validates that operation contains required PK values.\n *\n * @returns Record where keys are column names and values are client-provided values\n * @throws Error if operation value is missing required primary key columns\n */\n #getPrimaryKey(\n tableName: string,\n opValue: Record<string, ReadonlyJSONValue | undefined>,\n ): Record<string, ReadonlyJSONValue> {\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const columns = tableSpec.tableSpec.primaryKey;\n\n // Extract primary key values from operation value and validate they exist\n const values: Record<string, ReadonlyJSONValue> = {};\n for (const col of columns) {\n // Only own properties are values: every object inherits a `__proto__`.\n const val = getOwnProperty(opValue, col);\n if (val === undefined) {\n throw new Error(\n `Primary key column '${col}' is missing from operation value for table ${tableName}`,\n );\n }\n // A plain assignment to `__proto__` would not add a property.\n assignProperty(values, col, val);\n }\n\n return values;\n }\n\n #getSource(tableName: string) {\n let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const {columns, primaryKey} = tableSpec.tableSpec;\n assert(\n primaryKey.length,\n () => `Table ${tableName} must have a primary key`,\n );\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n this.#replica,\n tableName,\n Object.fromEntries(\n Object.entries(columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n [primaryKey[0], ...primaryKey.slice(1)],\n );\n this.#tables.set(tableName, source);\n\n return source;\n }\n\n async #timedCanDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const start = performance.now();\n try {\n const ret = await this.#canDo(phase, action, authData, op);\n return ret;\n } finally {\n this.#lc.info?.(\n 'action:',\n action,\n 'duration:',\n performance.now() - start,\n 'tableName:',\n op.tableName,\n 'primaryKey:',\n op.primaryKey,\n );\n }\n }\n\n /**\n * Evaluation order is from static to dynamic, broad to specific.\n * table -> column -> row -> cell.\n *\n * If any step fails, the entire operation is denied.\n *\n * That is, table rules supersede column rules, which supersede row rules,\n *\n * All steps must allow for the operation to be allowed.\n */\n async #canDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const rules = must(this.#loadedPermissions)?.permissions?.tables?.[\n op.tableName\n ];\n const rowPolicies = rules?.row;\n let rowQuery = newStaticQuery(this.#schema, op.tableName);\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, op.value);\n\n for (const pk in primaryKeyValues) {\n rowQuery = rowQuery.where(pk, '=', primaryKeyValues[pk]);\n }\n\n let applicableRowPolicy: Policy | undefined;\n switch (action) {\n case 'insert':\n if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.insert;\n }\n break;\n case 'update':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.update?.preMutation;\n } else if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.update?.postMutation;\n }\n break;\n case 'delete':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.delete;\n }\n break;\n }\n\n const cellPolicies = rules?.cell;\n const applicableCellPolicies: Policy[] = [];\n if (cellPolicies) {\n for (const [column, policy] of Object.entries(cellPolicies)) {\n if (\n action === 'update' &&\n getOwnProperty(op.value, column) === undefined\n ) {\n // If the cell is not being updated, we do not need to check\n // the cell rules.\n continue;\n }\n switch (action) {\n case 'insert':\n if (policy.insert && phase === 'postMutation') {\n applicableCellPolicies.push(policy.insert);\n }\n break;\n case 'update':\n if (phase === 'preMutation' && policy.update?.preMutation) {\n applicableCellPolicies.push(policy.update.preMutation);\n }\n if (phase === 'postMutation' && policy.update?.postMutation) {\n applicableCellPolicies.push(policy.update.postMutation);\n }\n break;\n case 'delete':\n if (policy.delete && phase === 'preMutation') {\n applicableCellPolicies.push(policy.delete);\n }\n break;\n }\n }\n }\n\n if (\n !(await this.#passesPolicyGroup(\n applicableRowPolicy,\n applicableCellPolicies,\n authData,\n rowQuery,\n ))\n ) {\n // `op.value` is the row being written and `authData` is the decoded\n // JWT payload, so neither can go into the log. Column names and policy\n // counts are enough to debug a failed permission check.\n this.#lc.warn?.('Permission check failed', {\n action,\n phase,\n tableName: op.tableName,\n columns: Object.keys(op.value),\n rowPolicy: applicableRowPolicy !== undefined,\n cellPolicyCount: applicableCellPolicies.length,\n });\n return false;\n }\n\n return true;\n }\n\n #getPreMutationRow(op: UpsertOp | UpdateOp | DeleteOp) {\n const {value} = op;\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, value);\n\n const spec = this.#tableSpecs.get(op.tableName);\n if (!spec) {\n throw new Error(`Table ${op.tableName} not found`);\n }\n\n const conditions: SQLQuery[] = [];\n const values: PrimaryKeyValue[] = [];\n for (const pk in primaryKeyValues) {\n conditions.push(sql`${sql.ident(pk)}=?`);\n values.push(v.parse(primaryKeyValues[pk], primaryKeyValueSchema));\n }\n\n const ret = this.#statementRunner.get(\n compile(\n sql`SELECT ${sql.join(\n Object.keys(spec.zqlSpec).map(c => sql.ident(c)),\n sql`,`,\n )} FROM ${sql.ident(op.tableName)} WHERE ${sql.join(\n conditions,\n sql` AND `,\n )}`,\n ),\n ...values,\n );\n if (ret === undefined) {\n return ret;\n }\n return fromSQLiteTypes(spec.zqlSpec, ret, op.tableName);\n }\n\n #requirePreMutationRow(op: UpdateOp | DeleteOp) {\n const ret = this.#getPreMutationRow(op);\n assert(\n ret !== undefined,\n () => `Pre-mutation row not found for ${JSON.stringify(op.value)}`,\n );\n return ret;\n }\n\n async #passesPolicyGroup(\n applicableRowPolicy: Policy | undefined,\n applicableCellPolicies: Policy[],\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ) {\n if (!(await this.#passesPolicy(applicableRowPolicy, authData, rowQuery))) {\n return false;\n }\n\n for (const policy of applicableCellPolicies) {\n if (!(await this.#passesPolicy(policy, authData, rowQuery))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Defaults to *false* if the policy is empty. At least one rule has to pass\n * for the policy to pass.\n */\n #passesPolicy(\n policy: Policy | undefined,\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ): MaybePromise<boolean> {\n if (policy === undefined) {\n return false;\n }\n if (policy.length === 0) {\n return false;\n }\n let rowQueryAst = asQueryInternals(rowQuery).ast;\n rowQueryAst = bindStaticParameters(\n {\n ...rowQueryAst,\n where: updateWhere(rowQueryAst.where, policy),\n },\n {\n authData: authData as Record<string, JSONValue>,\n preMutationRow: undefined,\n },\n );\n\n // call the compiler directly\n // run the sql against upstream.\n // remove the collecting into json? just need to know if a row comes back.\n\n const input = buildPipeline(rowQueryAst, this.#builderDelegate, 'query-id');\n try {\n const res = input.fetch({});\n for (const _ of res) {\n // if any row is returned at all, the\n // rule passes.\n return true;\n }\n } finally {\n input.destroy();\n }\n\n // no rows returned by any rules? The policy fails.\n return false;\n }\n}\n\nfunction updateWhere(where: Condition | undefined, policy: Policy) {\n assert(where, 'A where condition must exist for RowQuery');\n\n return simplifyCondition({\n type: 'and',\n conditions: [\n where,\n {\n type: 'or',\n conditions: policy.map(([action, rule]) => {\n assert(action, 'action must be defined in policy');\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoFA,IAAa,sBAAb,MAA4D;CAC1D;CACA;CACA;CACA;CACA,0BAAmB,IAAI,IAAyB;CAChD;CACA;CACA;CACA;CACA;CACA;CAEA,qBAA+C;CAE/C,YACE,IACA,QACA,SACA,OAC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kCAAkC,KAAK,UAAU,GAAG,KAAK,GACjE;EACA,OAAO;CACT;CAEA,MAAM,mBACJ,qBACA,wBACA,UACA,UACA;EACA,IAAI,CAAE,MAAM,KAAK,cAAc,qBAAqB,UAAU,QAAQ,GACpE,OAAO;EAGT,KAAK,MAAM,UAAU,wBACnB,IAAI,CAAE,MAAM,KAAK,cAAc,QAAQ,UAAU,QAAQ,GACvD,OAAO;EAIX,OAAO;CACT;;;;;CAMA,cACE,QACA,UACA,UACuB;EACvB,IAAI,WAAW,KAAA,GACb,OAAO;EAET,IAAI,OAAO,WAAW,GACpB,OAAO;EAET,IAAI,cAAc,iBAAiB,QAAQ,CAAC,CAAC;EAC7C,cAAc,qBACZ;GACE,GAAG;GACH,OAAO,YAAY,YAAY,OAAO,MAAM;EAC9C,GACA;GACY;GACV,gBAAgB,KAAA;EAClB,CACF;EAMA,MAAM,QAAQ,cAAc,aAAa,KAAK,kBAAkB,UAAU;EAC1E,IAAI;GACF,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;GAC1B,KAAK,MAAM,KAAK,KAGd,OAAO;EAEX,UAAU;GACR,MAAM,QAAQ;EAChB;EAGA,OAAO;CACT;AACF;AAEA,SAAS,YAAY,OAA8B,QAAgB;CACjE,OAAO,OAAO,2CAA2C;CAEzD,OAAO,kBAAkB;EACvB,MAAM;EACN,YAAY,CACV,OACA;GACE,MAAM;GACN,YAAY,OAAO,KAAK,CAAC,QAAQ,UAAU;IACzC,OAAO,QAAQ,kCAAkC;IACjD,OAAO;GACT,CAAC;EACH,CACF;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/normalize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE;QACd,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,GAAG,EAAE;QACH,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,UAAU,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;QACb,oBAAoB,EAAE,MAAM,CAAC;KAC9B,CAAC;IACF,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,oBAAoB,CAAC,YAAY,CAAC,CAAC;AAElE,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AA8BD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAG9D;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,MAAM,IAAI,oBAAoB,CAkHxC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,MAAM,CAAC,UAAU,EACtB,aAAa,CAAC,EAAE,MAAM,GACrB,oBAAoB,CAqHtB"}
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/normalize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE;QACd,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,GAAG,EAAE;QACH,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,UAAU,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;QACb,oBAAoB,EAAE,MAAM,CAAC;KAC9B,CAAC;IACF,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,oBAAoB,CAAC,YAAY,CAAC,CAAC;AAElE,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AA8BD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAG9D;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,MAAM,IAAI,oBAAoB,CA6DxC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,MAAM,CAAC,UAAU,EACtB,aAAa,CAAC,EAAE,MAAM,GACrB,oBAAoB,CAyGtB"}
@@ -35,20 +35,8 @@ function assertNormalized(config) {
35
35
  assert(config.changeStreamer.port, "missing --change-streamer-port");
36
36
  assert(config.changeStreamer.address, "missing --change-streamer-address");
37
37
  const { pgReplicationSlotPerReplica } = config.upstream;
38
- const { pgChangeLogEnabled, sqliteChangeLogMode, sqliteChangeLogReadPercent, sqliteChangeLogColdReadPercent, sqliteChangeLogComparePercent, sqliteChangeLogRetentionMs, sqliteChangeLogReadBatchRows, sqliteChangeLogPurgeBatchRows, sqliteChangeLogBarrierTimeoutMs } = config.changeStreamer;
39
- assert(Number.isSafeInteger(sqliteChangeLogReadPercent) && sqliteChangeLogReadPercent >= 0 && sqliteChangeLogReadPercent <= 100, "--change-streamer-sqlite-change-log-read-percent must be an integer between 0 and 100");
40
- assert(Number.isSafeInteger(sqliteChangeLogColdReadPercent) && sqliteChangeLogColdReadPercent >= 0 && sqliteChangeLogColdReadPercent <= 100, "--change-streamer-sqlite-change-log-cold-read-percent must be an integer between 0 and 100");
41
- assert(Number.isSafeInteger(sqliteChangeLogComparePercent) && sqliteChangeLogComparePercent >= 0 && sqliteChangeLogComparePercent <= 100, "--change-streamer-sqlite-change-log-compare-percent must be an integer between 0 and 100");
42
- assert(sqliteChangeLogMode === "serve" || sqliteChangeLogReadPercent === 0, "--change-streamer-sqlite-change-log-read-percent must be 0 unless --change-streamer-sqlite-change-log-mode=serve");
43
- assert(sqliteChangeLogMode === "serve" || sqliteChangeLogColdReadPercent === 0, "--change-streamer-sqlite-change-log-cold-read-percent must be 0 unless --change-streamer-sqlite-change-log-mode=serve");
44
- assert(sqliteChangeLogReadPercent > 0 || sqliteChangeLogColdReadPercent === 0, "--change-streamer-sqlite-change-log-cold-read-percent must be 0 when --change-streamer-sqlite-change-log-read-percent is 0");
38
+ const { sqliteChangeLogRetentionMs, sqliteChangeLogReadBatchRows, sqliteChangeLogPurgeBatchRows, sqliteChangeLogBarrierTimeoutMs } = config.changeStreamer;
45
39
  if (pgReplicationSlotPerReplica) assert(config.litestream.backupUsingV5 || !config.litestream.backupURL, "--upstream-pg-replication-slot-per-replica requires a litestream v5 backup");
46
- if (!pgChangeLogEnabled) {
47
- assert(sqliteChangeLogMode === "serve", "--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-mode=serve");
48
- assert(sqliteChangeLogReadPercent === 100, "--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-read-percent=100");
49
- assert(sqliteChangeLogColdReadPercent === 100, "--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-cold-read-percent=100");
50
- assert(config.litestream.backupUsingV5 || !config.litestream.backupURL, "--change-streamer-pg-change-log-enabled=false requires a litestream v5 backup");
51
- }
52
40
  for (const [flag, value] of [
53
41
  ["retention-ms", sqliteChangeLogRetentionMs],
54
42
  ["read-batch-rows", sqliteChangeLogReadBatchRows],
@@ -58,7 +46,7 @@ function assertNormalized(config) {
58
46
  assert(config.litestream.port, "missing --litestream-port");
59
47
  assertNotUndefined(config.litestream.multipartConcurrency, "missing --litestream-multipart-concurrency");
60
48
  assert(!config.litestream.backupUsingV5 || config.litestream.restoreUsingV5, "--litestream-backup-using-v5 requires --litestream-restore-using-v5");
61
- assert(!config.litestream.backupURL || config.litestream.executableV5 || !(config.litestream.restoreUsingV5 || config.litestream.backupUsingV5), "--litestream-restore-using-v5 and --litestream-backup-using-v5 require --litestream-executable-v5 to be specified");
49
+ assert(!config.litestream.backupURL || config.litestream.executableV5 || !(config.litestream.restoreUsingV5 || config.litestream.backupUsingV5), "--litestream-restore-using-v5 and --litestream-backup-using-v5 require --litestream-executable-v5 to be specified" + (config.upstream.pgHighAvailabilityReplication ? ". Both are implied by ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION, which is on by default. Set ZERO_LITESTREAM_EXECUTABLE_V5 (included in the rocicorp/zero Docker image), or set ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION=false to opt out." : ""));
62
50
  assert(config.change.db, "missing --change-db");
63
51
  assert(config.cvr.db, "missing --cvr-db");
64
52
  assertNotUndefined(config.numSyncWorkers, "missing --num-sync-workers");
@@ -123,16 +111,8 @@ function normalizeZeroConfig(lc, config, env, defaultTaskID) {
123
111
  config.litestream.backupUsingV5 = true;
124
112
  env["ZERO_LITESTREAM_RESTORE_USING_V5"] = "true";
125
113
  env["ZERO_LITESTREAM_BACKUP_USING_V5"] = "true";
126
- config.changeStreamer.sqliteChangeLogMode = "serve";
127
- env["ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_MODE"] = "serve";
128
- config.changeStreamer.sqliteChangeLogReadPercent = 100;
129
- config.changeStreamer.sqliteChangeLogColdReadPercent = 100;
130
- env["ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_READ_PERCENT"] = "100";
131
- env["ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_COLD_READ_PERCENT"] = "100";
132
- config.changeStreamer.pgChangeLogEnabled = false;
133
- env["ZERO_CHANGE_STREAMER_PG_CHANGE_LOG_ENABLED"] = "false";
114
+ assert(config.changeStreamer.mode !== "discover", "Change streamer \"discover\" mode is deprecated and not supported with ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION, which is on by default. Set ZERO_CHANGE_STREAMER_URI on view-syncers instead, or set ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION=false to keep using \"discover\" mode until it is removed.");
134
115
  }
135
- if (!config.changeStreamer.pgChangeLogEnabled) assert(config.changeStreamer.mode !== "discover", "Change streamer \"discover\" mode is deprecated and not supported when the PG change log is disabled (e.g. with ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION). Set ZERO_CHANGE_STREAMER_URI on view-syncers instead.");
136
116
  lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);
137
117
  return {
138
118
  ...config,
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.js","names":[],"sources":["../../../../../zero-cache/src/config/normalize.ts"],"sourcesContent":["import {availableParallelism, totalmem} from 'node:os';\nimport type {LogContext} from '@rocicorp/logger';\nimport {nanoid} from 'nanoid';\nimport {assert, assertNotUndefined} from '../../../shared/src/asserts.ts';\nimport {getHostIp} from './network.ts';\nimport type {ZeroConfig} from './zero-config.ts';\n\n/** {@link ZeroConfig} with defaults set per option documentation. */\nexport type NormalizedZeroConfig = ZeroConfig & {\n taskID: string;\n changeStreamer: {\n port: number;\n address: string;\n };\n change: {\n db: string;\n };\n cvr: {\n db: string;\n };\n litestream: {\n port: number;\n multipartConcurrency: number;\n };\n numSyncWorkers: number;\n};\n\nexport type LitestreamConfig = NormalizedZeroConfig['litestream'];\n\nexport function isDevelopmentMode(): boolean {\n return process.env.NODE_ENV === 'development';\n}\n\nfunction isRunningInECS(): boolean {\n // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-environment-variables.html\n return process.env.ECS_CONTAINER_METADATA_URI_V4 !== undefined;\n}\n\nconst DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS = 20_000;\n\nconst MAX_DEFAULT_MULTIPART_CONCURRENCY = 48;\n\n/**\n * Litestream buffers each multipart part in memory, in a process that shares\n * the container's memory limit. Keep the default concurrency's parts within a\n * quarter of that limit, which, for 16 MiB parts, allows the maximum in 3 GiB\n * and 16 parts in 1 GiB.\n */\nfunction defaultMultipartConcurrency(multipartSize: number): number {\n // 0 means no known limit. A limit can also exceed the host's memory.\n const limit = process.constrainedMemory() || Infinity;\n const memory = Math.min(limit, totalmem());\n return Math.max(\n 1, // streams downloads without buffering parts\n Math.min(\n MAX_DEFAULT_MULTIPART_CONCURRENCY,\n Math.floor(memory / 4 / multipartSize),\n ),\n );\n}\n\n/**\n * Whether this process tree runs the change-streamer, as opposed to connecting\n * to one that another task runs.\n */\nexport function runsChangeStreamer(config: ZeroConfig): boolean {\n const {mode, uri} = config.changeStreamer;\n return mode === 'dedicated' && uri === undefined;\n}\n\nexport function assertNormalized(\n config: ZeroConfig,\n): asserts config is NormalizedZeroConfig {\n assert(config.taskID, 'missing --task-id');\n assert(config.changeStreamer.port, 'missing --change-streamer-port');\n assert(config.changeStreamer.address, 'missing --change-streamer-address');\n const {pgReplicationSlotPerReplica} = config.upstream;\n const {\n pgChangeLogEnabled,\n sqliteChangeLogMode,\n sqliteChangeLogReadPercent,\n sqliteChangeLogColdReadPercent,\n sqliteChangeLogComparePercent,\n sqliteChangeLogRetentionMs,\n sqliteChangeLogReadBatchRows,\n sqliteChangeLogPurgeBatchRows,\n sqliteChangeLogBarrierTimeoutMs,\n } = config.changeStreamer;\n assert(\n Number.isSafeInteger(sqliteChangeLogReadPercent) &&\n sqliteChangeLogReadPercent >= 0 &&\n sqliteChangeLogReadPercent <= 100,\n '--change-streamer-sqlite-change-log-read-percent must be an integer between 0 and 100',\n );\n assert(\n Number.isSafeInteger(sqliteChangeLogColdReadPercent) &&\n sqliteChangeLogColdReadPercent >= 0 &&\n sqliteChangeLogColdReadPercent <= 100,\n '--change-streamer-sqlite-change-log-cold-read-percent must be an integer between 0 and 100',\n );\n // This setting has no mode restriction. Comparison starts in `compare` mode.\n assert(\n Number.isSafeInteger(sqliteChangeLogComparePercent) &&\n sqliteChangeLogComparePercent >= 0 &&\n sqliteChangeLogComparePercent <= 100,\n '--change-streamer-sqlite-change-log-compare-percent must be an integer between 0 and 100',\n );\n assert(\n sqliteChangeLogMode === 'serve' || sqliteChangeLogReadPercent === 0,\n '--change-streamer-sqlite-change-log-read-percent must be 0 unless --change-streamer-sqlite-change-log-mode=serve',\n );\n assert(\n sqliteChangeLogMode === 'serve' || sqliteChangeLogColdReadPercent === 0,\n '--change-streamer-sqlite-change-log-cold-read-percent must be 0 unless --change-streamer-sqlite-change-log-mode=serve',\n );\n // The cold gate only admits a task to the read gate; it never serves one on\n // its own. A nonzero cold percentage with a zero read percentage is a\n // silent no-op, which is the shape of a rollout that looks enabled and\n // serves nothing.\n assert(\n sqliteChangeLogReadPercent > 0 || sqliteChangeLogColdReadPercent === 0,\n '--change-streamer-sqlite-change-log-cold-read-percent must be 0 when --change-streamer-sqlite-change-log-read-percent is 0',\n );\n if (pgReplicationSlotPerReplica) {\n assert(\n // Only require backupUsingV5 if a backupURL is set (e.g. replication-manager).\n config.litestream.backupUsingV5 || !config.litestream.backupURL,\n '--upstream-pg-replication-slot-per-replica requires a litestream v5 backup',\n );\n }\n if (!pgChangeLogEnabled) {\n assert(\n sqliteChangeLogMode === 'serve',\n '--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-mode=serve',\n );\n assert(\n sqliteChangeLogReadPercent === 100,\n '--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-read-percent=100',\n );\n assert(\n sqliteChangeLogColdReadPercent === 100,\n '--change-streamer-pg-change-log-enabled=false requires --change-streamer-sqlite-change-log-cold-read-percent=100',\n );\n assert(\n // Only require backupUsingV5 if a backupURL is set (e.g. replication-manager).\n config.litestream.backupUsingV5 || !config.litestream.backupURL,\n '--change-streamer-pg-change-log-enabled=false requires a litestream v5 backup',\n );\n }\n for (const [flag, value] of [\n ['retention-ms', sqliteChangeLogRetentionMs],\n ['read-batch-rows', sqliteChangeLogReadBatchRows],\n ['purge-batch-rows', sqliteChangeLogPurgeBatchRows],\n ['barrier-timeout-ms', sqliteChangeLogBarrierTimeoutMs],\n ] as const) {\n assert(\n Number.isSafeInteger(value) && value > 0,\n `--change-streamer-sqlite-change-log-${flag} must be a positive integer`,\n );\n }\n assert(config.litestream.port, 'missing --litestream-port');\n assertNotUndefined(\n config.litestream.multipartConcurrency,\n 'missing --litestream-multipart-concurrency',\n );\n assert(\n !config.litestream.backupUsingV5 || config.litestream.restoreUsingV5,\n '--litestream-backup-using-v5 requires --litestream-restore-using-v5',\n );\n assert(\n !config.litestream.backupURL ||\n config.litestream.executableV5 ||\n !(config.litestream.restoreUsingV5 || config.litestream.backupUsingV5),\n '--litestream-restore-using-v5 and --litestream-backup-using-v5 ' +\n 'require --litestream-executable-v5 to be specified',\n );\n assert(config.change.db, 'missing --change-db');\n assert(config.cvr.db, 'missing --cvr-db');\n assertNotUndefined(config.numSyncWorkers, 'missing --num-sync-workers');\n\n if (!isDevelopmentMode()) {\n assert(\n config.adminPassword,\n 'missing --admin-password: required in production mode',\n );\n }\n}\n\n/**\n * Normalizes the parsed `config` by setting defaults from the environment\n * or from other options as documented. When defaults are applied, the\n * corresponding `env` variable is updated so that the settings are propagated\n * to spawned child workers. Child workers can then call\n * {@link assertNormalized} to verify that the expected defaults have been set.\n */\nexport function normalizeZeroConfig(\n lc: LogContext,\n config: ZeroConfig,\n env: NodeJS.ProcessEnv,\n defaultTaskID?: string,\n): NormalizedZeroConfig {\n if (!config.taskID) {\n const taskID = defaultTaskID ?? nanoid();\n config.taskID = taskID;\n env['ZERO_TASK_ID'] = taskID;\n }\n if (!config.changeStreamer.port) {\n const port = config.port + 1;\n config.changeStreamer.port = port;\n env['ZERO_CHANGE_STREAMER_PORT'] = String(port);\n }\n if (!config.litestream.port) {\n const port = config.port + 2;\n config.litestream.port = port;\n env['ZERO_LITESTREAM_PORT'] = String(port);\n }\n if (config.numSyncWorkers === undefined) {\n // Reserve 1 core for the replicator. The change-streamer is not CPU heavy.\n const numSyncers = Math.max(1, availableParallelism() - 1);\n config.numSyncWorkers = numSyncers;\n env['ZERO_NUM_SYNC_WORKERS'] = String(numSyncers);\n }\n if (config.litestream.multipartConcurrency === undefined) {\n const concurrency = defaultMultipartConcurrency(\n config.litestream.multipartSize,\n );\n config.litestream.multipartConcurrency = concurrency;\n env['ZERO_LITESTREAM_MULTIPART_CONCURRENCY'] = String(concurrency);\n }\n\n const hostIP = getHostIp(\n lc,\n config.changeStreamer.discoveryInterfacePreferences,\n );\n if (!config.changeStreamer.address) {\n const {port} = config.changeStreamer;\n const address = `${hostIP}:${port}`;\n config.changeStreamer.address = address;\n env['ZERO_CHANGE_STREAMER_ADDRESS'] = address;\n }\n\n if (!config.change.db) {\n config.change.db = config.upstream.db;\n env['ZERO_CHANGE_DB'] = config.upstream.db;\n }\n\n if (!config.cvr.db) {\n config.cvr.db = config.upstream.db;\n env['ZERO_CVR_DB'] = config.upstream.db;\n }\n\n if (!config.keepaliveTimeoutMs && isRunningInECS()) {\n config.keepaliveTimeoutMs = DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS;\n env['ZERO_KEEPALIVE_TIMEOUT_MS'] = String(DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS);\n }\n\n if (config.upstream.pgHighAvailabilityReplication) {\n config.upstream.pgReplicationSlotPerReplica = true;\n env['ZERO_UPSTREAM_PG_REPLICATION_SLOT_PER_REPLICA'] = 'true';\n\n config.litestream.restoreUsingV5 = true;\n config.litestream.backupUsingV5 = true;\n env['ZERO_LITESTREAM_RESTORE_USING_V5'] = 'true';\n env['ZERO_LITESTREAM_BACKUP_USING_V5'] = 'true';\n\n config.changeStreamer.sqliteChangeLogMode = 'serve';\n env['ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_MODE'] = 'serve';\n\n config.changeStreamer.sqliteChangeLogReadPercent = 100;\n config.changeStreamer.sqliteChangeLogColdReadPercent = 100;\n env['ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_READ_PERCENT'] = '100';\n env['ZERO_CHANGE_STREAMER_SQLITE_CHANGE_LOG_COLD_READ_PERCENT'] = '100';\n\n config.changeStreamer.pgChangeLogEnabled = false;\n env['ZERO_CHANGE_STREAMER_PG_CHANGE_LOG_ENABLED'] = 'false';\n }\n\n if (!config.changeStreamer.pgChangeLogEnabled) {\n assert(\n config.changeStreamer.mode !== 'discover',\n 'Change streamer \"discover\" mode is deprecated and not supported when ' +\n 'the PG change log is disabled (e.g. with ' +\n 'ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION). ' +\n 'Set ZERO_CHANGE_STREAMER_URI on view-syncers instead.',\n );\n }\n\n lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);\n\n return {\n ...config,\n taskID: config.taskID,\n\n changeStreamer: {\n ...config.changeStreamer,\n port: config.changeStreamer.port,\n address: config.changeStreamer.address,\n },\n\n litestream: {\n ...config.litestream,\n port: config.litestream.port,\n multipartConcurrency: config.litestream.multipartConcurrency,\n },\n\n change: {\n ...config.change,\n db: config.change.db,\n },\n\n cvr: {\n ...config.cvr,\n db: config.cvr.db,\n },\n\n numSyncWorkers: config.numSyncWorkers,\n };\n}\n"],"mappings":";;;;;AA6BA,SAAgB,oBAA6B;CAC3C,OAAA,QAAA,IAAA,aAAgC;AAClC;AAEA,SAAS,iBAA0B;CAEjC,OAAO,QAAQ,IAAI,kCAAkC,KAAA;AACvD;AAEA,IAAM,mCAAmC;AAEzC,IAAM,oCAAoC;;;;;;;AAQ1C,SAAS,4BAA4B,eAA+B;CAElE,MAAM,QAAQ,QAAQ,kBAAkB,KAAK;CAC7C,MAAM,SAAS,KAAK,IAAI,OAAO,SAAS,CAAC;CACzC,OAAO,KAAK,IACV,GACA,KAAK,IACH,mCACA,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EAEA,KAAK;GACH,GAAG,OAAO;GACV,IAAI,OAAO,IAAI;EACjB;EAEA,gBAAgB,OAAO;CACzB;AACF"}
1
+ {"version":3,"file":"normalize.js","names":[],"sources":["../../../../../zero-cache/src/config/normalize.ts"],"sourcesContent":["import {availableParallelism, totalmem} from 'node:os';\nimport type {LogContext} from '@rocicorp/logger';\nimport {nanoid} from 'nanoid';\nimport {assert, assertNotUndefined} from '../../../shared/src/asserts.ts';\nimport {getHostIp} from './network.ts';\nimport type {ZeroConfig} from './zero-config.ts';\n\n/** {@link ZeroConfig} with defaults set per option documentation. */\nexport type NormalizedZeroConfig = ZeroConfig & {\n taskID: string;\n changeStreamer: {\n port: number;\n address: string;\n };\n change: {\n db: string;\n };\n cvr: {\n db: string;\n };\n litestream: {\n port: number;\n multipartConcurrency: number;\n };\n numSyncWorkers: number;\n};\n\nexport type LitestreamConfig = NormalizedZeroConfig['litestream'];\n\nexport function isDevelopmentMode(): boolean {\n return process.env.NODE_ENV === 'development';\n}\n\nfunction isRunningInECS(): boolean {\n // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-environment-variables.html\n return process.env.ECS_CONTAINER_METADATA_URI_V4 !== undefined;\n}\n\nconst DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS = 20_000;\n\nconst MAX_DEFAULT_MULTIPART_CONCURRENCY = 48;\n\n/**\n * Litestream buffers each multipart part in memory, in a process that shares\n * the container's memory limit. Keep the default concurrency's parts within a\n * quarter of that limit, which, for 16 MiB parts, allows the maximum in 3 GiB\n * and 16 parts in 1 GiB.\n */\nfunction defaultMultipartConcurrency(multipartSize: number): number {\n // 0 means no known limit. A limit can also exceed the host's memory.\n const limit = process.constrainedMemory() || Infinity;\n const memory = Math.min(limit, totalmem());\n return Math.max(\n 1, // streams downloads without buffering parts\n Math.min(\n MAX_DEFAULT_MULTIPART_CONCURRENCY,\n Math.floor(memory / 4 / multipartSize),\n ),\n );\n}\n\n/**\n * Whether this process tree runs the change-streamer, as opposed to connecting\n * to one that another task runs.\n */\nexport function runsChangeStreamer(config: ZeroConfig): boolean {\n const {mode, uri} = config.changeStreamer;\n return mode === 'dedicated' && uri === undefined;\n}\n\nexport function assertNormalized(\n config: ZeroConfig,\n): asserts config is NormalizedZeroConfig {\n assert(config.taskID, 'missing --task-id');\n assert(config.changeStreamer.port, 'missing --change-streamer-port');\n assert(config.changeStreamer.address, 'missing --change-streamer-address');\n const {pgReplicationSlotPerReplica} = config.upstream;\n const {\n sqliteChangeLogRetentionMs,\n sqliteChangeLogReadBatchRows,\n sqliteChangeLogPurgeBatchRows,\n sqliteChangeLogBarrierTimeoutMs,\n } = config.changeStreamer;\n if (pgReplicationSlotPerReplica) {\n assert(\n // Only require backupUsingV5 if a backupURL is set (e.g. replication-manager).\n config.litestream.backupUsingV5 || !config.litestream.backupURL,\n '--upstream-pg-replication-slot-per-replica requires a litestream v5 backup',\n );\n }\n for (const [flag, value] of [\n ['retention-ms', sqliteChangeLogRetentionMs],\n ['read-batch-rows', sqliteChangeLogReadBatchRows],\n ['purge-batch-rows', sqliteChangeLogPurgeBatchRows],\n ['barrier-timeout-ms', sqliteChangeLogBarrierTimeoutMs],\n ] as const) {\n assert(\n Number.isSafeInteger(value) && value > 0,\n `--change-streamer-sqlite-change-log-${flag} must be a positive integer`,\n );\n }\n assert(config.litestream.port, 'missing --litestream-port');\n assertNotUndefined(\n config.litestream.multipartConcurrency,\n 'missing --litestream-multipart-concurrency',\n );\n assert(\n !config.litestream.backupUsingV5 || config.litestream.restoreUsingV5,\n '--litestream-backup-using-v5 requires --litestream-restore-using-v5',\n );\n assert(\n !config.litestream.backupURL ||\n config.litestream.executableV5 ||\n !(config.litestream.restoreUsingV5 || config.litestream.backupUsingV5),\n '--litestream-restore-using-v5 and --litestream-backup-using-v5 ' +\n 'require --litestream-executable-v5 to be specified' +\n (config.upstream.pgHighAvailabilityReplication\n ? '. Both are implied by ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION, ' +\n 'which is on by default. Set ZERO_LITESTREAM_EXECUTABLE_V5 (included ' +\n 'in the rocicorp/zero Docker image), or set ' +\n 'ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION=false to opt out.'\n : ''),\n );\n assert(config.change.db, 'missing --change-db');\n assert(config.cvr.db, 'missing --cvr-db');\n assertNotUndefined(config.numSyncWorkers, 'missing --num-sync-workers');\n\n if (!isDevelopmentMode()) {\n assert(\n config.adminPassword,\n 'missing --admin-password: required in production mode',\n );\n }\n}\n\n/**\n * Normalizes the parsed `config` by setting defaults from the environment\n * or from other options as documented. When defaults are applied, the\n * corresponding `env` variable is updated so that the settings are propagated\n * to spawned child workers. Child workers can then call\n * {@link assertNormalized} to verify that the expected defaults have been set.\n */\nexport function normalizeZeroConfig(\n lc: LogContext,\n config: ZeroConfig,\n env: NodeJS.ProcessEnv,\n defaultTaskID?: string,\n): NormalizedZeroConfig {\n if (!config.taskID) {\n const taskID = defaultTaskID ?? nanoid();\n config.taskID = taskID;\n env['ZERO_TASK_ID'] = taskID;\n }\n if (!config.changeStreamer.port) {\n const port = config.port + 1;\n config.changeStreamer.port = port;\n env['ZERO_CHANGE_STREAMER_PORT'] = String(port);\n }\n if (!config.litestream.port) {\n const port = config.port + 2;\n config.litestream.port = port;\n env['ZERO_LITESTREAM_PORT'] = String(port);\n }\n if (config.numSyncWorkers === undefined) {\n // Reserve 1 core for the replicator. The change-streamer is not CPU heavy.\n const numSyncers = Math.max(1, availableParallelism() - 1);\n config.numSyncWorkers = numSyncers;\n env['ZERO_NUM_SYNC_WORKERS'] = String(numSyncers);\n }\n if (config.litestream.multipartConcurrency === undefined) {\n const concurrency = defaultMultipartConcurrency(\n config.litestream.multipartSize,\n );\n config.litestream.multipartConcurrency = concurrency;\n env['ZERO_LITESTREAM_MULTIPART_CONCURRENCY'] = String(concurrency);\n }\n\n const hostIP = getHostIp(\n lc,\n config.changeStreamer.discoveryInterfacePreferences,\n );\n if (!config.changeStreamer.address) {\n const {port} = config.changeStreamer;\n const address = `${hostIP}:${port}`;\n config.changeStreamer.address = address;\n env['ZERO_CHANGE_STREAMER_ADDRESS'] = address;\n }\n\n if (!config.change.db) {\n config.change.db = config.upstream.db;\n env['ZERO_CHANGE_DB'] = config.upstream.db;\n }\n\n if (!config.cvr.db) {\n config.cvr.db = config.upstream.db;\n env['ZERO_CVR_DB'] = config.upstream.db;\n }\n\n if (!config.keepaliveTimeoutMs && isRunningInECS()) {\n config.keepaliveTimeoutMs = DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS;\n env['ZERO_KEEPALIVE_TIMEOUT_MS'] = String(DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS);\n }\n\n if (config.upstream.pgHighAvailabilityReplication) {\n config.upstream.pgReplicationSlotPerReplica = true;\n env['ZERO_UPSTREAM_PG_REPLICATION_SLOT_PER_REPLICA'] = 'true';\n\n config.litestream.restoreUsingV5 = true;\n config.litestream.backupUsingV5 = true;\n env['ZERO_LITESTREAM_RESTORE_USING_V5'] = 'true';\n env['ZERO_LITESTREAM_BACKUP_USING_V5'] = 'true';\n\n assert(\n config.changeStreamer.mode !== 'discover',\n 'Change streamer \"discover\" mode is deprecated and not supported with ' +\n 'ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION, which is on by default. ' +\n 'Set ZERO_CHANGE_STREAMER_URI on view-syncers instead, or set ' +\n 'ZERO_UPSTREAM_PG_HIGH_AVAILABILITY_REPLICATION=false to keep using ' +\n '\"discover\" mode until it is removed.',\n );\n }\n\n lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);\n\n return {\n ...config,\n taskID: config.taskID,\n\n changeStreamer: {\n ...config.changeStreamer,\n port: config.changeStreamer.port,\n address: config.changeStreamer.address,\n },\n\n litestream: {\n ...config.litestream,\n port: config.litestream.port,\n multipartConcurrency: config.litestream.multipartConcurrency,\n },\n\n change: {\n ...config.change,\n db: config.change.db,\n },\n\n cvr: {\n ...config.cvr,\n db: config.cvr.db,\n },\n\n numSyncWor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,OAAO,IAAI;EACrB,OAAO,OAAO,KAAK,OAAO,SAAS;EACnC,IAAI,oBAAoB,OAAO,SAAS;CAC1C;CAEA,IAAI,CAAC,OAAO,IAAI,IAAI;EAClB,OAAO,IAAI,KAAK,OAAO,SAAS;EAChC,IAAI,iBAAiB,OAAO,SAAS;CACvC;CAEA,IAAI,CAAC,OAAO,sBAAsB,eAAe,GAAG;EAClD,OAAO,qBAAqB;EAC5B,IAAI,+BAA+B,OAAO,gCAAgC;CAC5E;CAEA,IAAI,OAAO,SAAS,+BAA+B;EACjD,OAAO,SAAS,8BAA8B;EAC9C,IAAI,mDAAmD;EAEvD,OAAO,WAAW,iBAAiB;EACnC,OAAO,WAAW,gBAAgB;EAClC,IAAI,sCAAsC;EAC1C,IAAI,qCAAqC;EAEzC,OACE,OAAO,eAAe,SAAS,YAC/B,uTAKF;CACF;CAEA,GAAG,OAAO,uBAAuB,OAAO,OAAO,WAAW,QAAQ;CAElE,OAAO;EACL,GAAG;EACH,QAAQ,OAAO;EAEf,gBAAgB;GACd,GAAG,OAAO;GACV,MAAM,OAAO,eAAe;GAC5B,SAAS,OAAO,eAAe;EACjC;EAEA,YAAY;GACV,GAAG,OAAO;GACV,MAAM,OAAO,WAAW;GACxB,sBAAsB,OAAO,WAAW;EAC1C;EAEA,QAAQ;GACN,GAAG,OAAO;GACV,IAAI,OAAO,OAAO;EACpB;EAEA,KAAK;GACH,GAAG,OAAO;GACV,IAAI,OAAO,IAAI;EACjB;EAEA,gBAAgB,OAAO;CACzB;AACF"}
@@ -109,9 +109,8 @@ export declare const zeroOptions: {
109
109
  desc: string[];
110
110
  };
111
111
  pgHighAvailabilityReplication: {
112
- type: v.Optional<boolean>;
112
+ type: v.Type<boolean>;
113
113
  desc: string[];
114
- hidden: boolean;
115
114
  };
116
115
  pgResumeOrphanedSlotGracePeriodMs: {
117
116
  type: v.Type<number>;
@@ -546,31 +545,6 @@ export declare const zeroOptions: {
546
545
  type: v.Type<number>;
547
546
  desc: string[];
548
547
  };
549
- sqliteChangeLogMode: {
550
- type: v.Type<"compare" | "off" | "serve" | "write">;
551
- desc: string[];
552
- hidden: boolean;
553
- };
554
- pgChangeLogEnabled: {
555
- type: v.Type<boolean>;
556
- desc: string[];
557
- hidden: boolean;
558
- };
559
- sqliteChangeLogReadPercent: {
560
- type: v.Type<number>;
561
- desc: string[];
562
- hidden: boolean;
563
- };
564
- sqliteChangeLogColdReadPercent: {
565
- type: v.Type<number>;
566
- desc: string[];
567
- hidden: boolean;
568
- };
569
- sqliteChangeLogComparePercent: {
570
- type: v.Type<number>;
571
- desc: string[];
572
- hidden: boolean;
573
- };
574
548
  sqliteChangeLogRetentionMs: {
575
549
  type: v.Type<number>;
576
550
  desc: string[];