@gusto/baerly-storage 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +93 -52
- package/dist/API.md +151 -109
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +40 -29
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
package/dist/baerly.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baerly.js","names":["parseArgs$1","parseArgs","pc"],"sources":["../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/_chunks/libs/scule.mjs","../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/index.mjs","../packages/protocol/src/errors.ts","../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/cli/src/output.ts","../packages/cli/src/bin-runner.ts","../packages/cli/src/baerly.ts"],"sourcesContent":["//#region node_modules/.pnpm/scule@1.3.0/node_modules/scule/dist/index.mjs\nconst NUMBER_CHAR_RE = /\\d/;\nconst STR_SPLITTERS = [\n\t\"-\",\n\t\"_\",\n\t\"/\",\n\t\".\"\n];\nfunction isUppercase(char = \"\") {\n\tif (NUMBER_CHAR_RE.test(char)) return;\n\treturn char !== char.toLowerCase();\n}\nfunction splitByCase(str, separators) {\n\tconst splitters = separators ?? STR_SPLITTERS;\n\tconst parts = [];\n\tif (!str || typeof str !== \"string\") return parts;\n\tlet buff = \"\";\n\tlet previousUpper;\n\tlet previousSplitter;\n\tfor (const char of str) {\n\t\tconst isSplitter = splitters.includes(char);\n\t\tif (isSplitter === true) {\n\t\t\tparts.push(buff);\n\t\t\tbuff = \"\";\n\t\t\tpreviousUpper = void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst isUpper = isUppercase(char);\n\t\tif (previousSplitter === false) {\n\t\t\tif (previousUpper === false && isUpper === true) {\n\t\t\t\tparts.push(buff);\n\t\t\t\tbuff = char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previousUpper === true && isUpper === false && buff.length > 1) {\n\t\t\t\tconst lastChar = buff.at(-1);\n\t\t\t\tparts.push(buff.slice(0, Math.max(0, buff.length - 1)));\n\t\t\t\tbuff = lastChar + char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tbuff += char;\n\t\tpreviousUpper = isUpper;\n\t\tpreviousSplitter = isSplitter;\n\t}\n\tparts.push(buff);\n\treturn parts;\n}\nfunction upperFirst(str) {\n\treturn str ? str[0].toUpperCase() + str.slice(1) : \"\";\n}\nfunction lowerFirst(str) {\n\treturn str ? str[0].toLowerCase() + str.slice(1) : \"\";\n}\nfunction pascalCase(str, opts) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join(\"\") : \"\";\n}\nfunction camelCase(str, opts) {\n\treturn lowerFirst(pascalCase(str || \"\", opts));\n}\nfunction kebabCase(str, joiner) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? \"-\") : \"\";\n}\nfunction snakeCase(str) {\n\treturn kebabCase(str || \"\", \"_\");\n}\n//#endregion\nexport { kebabCase as n, snakeCase as r, camelCase as t };\n","import { n as kebabCase, r as snakeCase, t as camelCase } from \"./_chunks/libs/scule.mjs\";\nimport { parseArgs as parseArgs$1 } from \"node:util\";\n//#region src/_utils.ts\nfunction toArray(val) {\n\tif (Array.isArray(val)) return val;\n\treturn val === void 0 ? [] : [val];\n}\nfunction formatLineColumns(lines, linePrefix = \"\") {\n\tconst maxLength = [];\n\tfor (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);\n\treturn lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? \"padStart\" : \"padEnd\"](maxLength[i])).join(\" \")).join(\"\\n\");\n}\nfunction resolveValue(input) {\n\treturn typeof input === \"function\" ? input() : input;\n}\nvar CLIError = class extends Error {\n\tcode;\n\tconstructor(message, code) {\n\t\tsuper(message);\n\t\tthis.name = \"CLIError\";\n\t\tthis.code = code;\n\t}\n};\n//#endregion\n//#region src/_parser.ts\nfunction parseRawArgs(args = [], opts = {}) {\n\tconst booleans = new Set(opts.boolean || []);\n\tconst strings = new Set(opts.string || []);\n\tconst aliasMap = opts.alias || {};\n\tconst defaults = opts.default || {};\n\tconst aliasToMain = /* @__PURE__ */ new Map();\n\tconst mainToAliases = /* @__PURE__ */ new Map();\n\tfor (const [key, value] of Object.entries(aliasMap)) {\n\t\tconst targets = value;\n\t\tfor (const target of targets) {\n\t\t\taliasToMain.set(key, target);\n\t\t\tif (!mainToAliases.has(target)) mainToAliases.set(target, []);\n\t\t\tmainToAliases.get(target).push(key);\n\t\t\taliasToMain.set(target, key);\n\t\t\tif (!mainToAliases.has(key)) mainToAliases.set(key, []);\n\t\t\tmainToAliases.get(key).push(target);\n\t\t}\n\t}\n\tconst options = {};\n\tfunction getType(name) {\n\t\tif (booleans.has(name)) return \"boolean\";\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (booleans.has(alias)) return \"boolean\";\n\t\treturn \"string\";\n\t}\n\tfunction isStringType(name) {\n\t\tif (strings.has(name)) return true;\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (strings.has(alias)) return true;\n\t\treturn false;\n\t}\n\tconst allOptions = new Set([\n\t\t...booleans,\n\t\t...strings,\n\t\t...Object.keys(aliasMap),\n\t\t...Object.values(aliasMap).flat(),\n\t\t...Object.keys(defaults)\n\t]);\n\tfor (const name of allOptions) if (!options[name]) options[name] = {\n\t\ttype: getType(name),\n\t\tdefault: defaults[name]\n\t};\n\tfor (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;\n\tconst processedArgs = [];\n\tconst negatedFlags = {};\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg === \"--\") {\n\t\t\tprocessedArgs.push(...args.slice(i));\n\t\t\tbreak;\n\t\t}\n\t\tif (arg.startsWith(\"--no-\")) {\n\t\t\tconst flagName = arg.slice(5);\n\t\t\tnegatedFlags[flagName] = true;\n\t\t\tcontinue;\n\t\t}\n\t\tprocessedArgs.push(arg);\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = parseArgs$1({\n\t\t\targs: processedArgs,\n\t\t\toptions: Object.keys(options).length > 0 ? options : void 0,\n\t\t\tallowPositionals: true,\n\t\t\tstrict: false\n\t\t});\n\t} catch {\n\t\tparsed = {\n\t\t\tvalues: {},\n\t\t\tpositionals: processedArgs\n\t\t};\n\t}\n\tconst out = { _: [] };\n\tout._ = parsed.positionals;\n\tfor (const [key, value] of Object.entries(parsed.values)) {\n\t\tlet coerced = value;\n\t\tif (getType(key) === \"boolean\" && typeof value === \"string\") coerced = value !== \"false\";\n\t\telse if (isStringType(key) && typeof value === \"boolean\") coerced = \"\";\n\t\tout[key] = coerced;\n\t}\n\tfor (const [name] of Object.entries(negatedFlags)) {\n\t\tout[name] = false;\n\t\tconst mainName = aliasToMain.get(name);\n\t\tif (mainName) out[mainName] = false;\n\t\tconst aliases = mainToAliases.get(name);\n\t\tif (aliases) for (const alias of aliases) out[alias] = false;\n\t}\n\tfor (const [alias, main] of aliasToMain.entries()) {\n\t\tif (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];\n\t\tif (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];\n\t\tif (out[alias] !== out[main] && defaults[main] === out[main]) out[main] = out[alias];\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/_color.ts\nconst noColor = /* @__PURE__ */ (() => {\n\tconst env = globalThis.process?.env ?? {};\n\treturn env.NO_COLOR === \"1\" || env.TERM === \"dumb\" || env.TEST || env.CI;\n})();\nconst _c = (c, r = 39) => (t) => noColor ? t : `\\u001B[${c}m${t}\\u001B[${r}m`;\nconst bold = /* @__PURE__ */ _c(1, 22);\nconst cyan = /* @__PURE__ */ _c(36);\nconst gray = /* @__PURE__ */ _c(90);\nconst underline = /* @__PURE__ */ _c(4, 24);\n//#endregion\n//#region src/args.ts\nfunction parseArgs(rawArgs, argsDef) {\n\tconst parseOptions = {\n\t\tboolean: [],\n\t\tstring: [],\n\t\talias: {},\n\t\tdefault: {}\n\t};\n\tconst args = resolveArgs(argsDef);\n\tfor (const arg of args) {\n\t\tif (arg.type === \"positional\") continue;\n\t\tif (arg.type === \"string\" || arg.type === \"enum\") parseOptions.string.push(arg.name);\n\t\telse if (arg.type === \"boolean\") parseOptions.boolean.push(arg.name);\n\t\tif (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;\n\t\tif (arg.alias) parseOptions.alias[arg.name] = arg.alias;\n\t\tconst camelName = camelCase(arg.name);\n\t\tconst kebabName = kebabCase(arg.name);\n\t\tif (camelName !== arg.name || kebabName !== arg.name) {\n\t\t\tconst existingAliases = toArray(parseOptions.alias[arg.name] || []);\n\t\t\tif (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);\n\t\t\tif (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);\n\t\t\tif (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;\n\t\t}\n\t}\n\tconst parsed = parseRawArgs(rawArgs, parseOptions);\n\tconst [ ...positionalArguments] = parsed._;\n\tconst parsedArgsProxy = new Proxy(parsed, { get(target, prop) {\n\t\treturn target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];\n\t} });\n\tfor (const [, arg] of args.entries()) if (arg.type === \"positional\") {\n\t\tconst nextPositionalArgument = positionalArguments.shift();\n\t\tif (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;\n\t\telse if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, \"EARG\");\n\t\telse parsedArgsProxy[arg.name] = arg.default;\n\t} else if (arg.type === \"enum\") {\n\t\tconst argument = parsedArgsProxy[arg.name];\n\t\tconst options = arg.options || [];\n\t\tif (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(\", \")}.`, \"EARG\");\n\t} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, \"EARG\");\n\treturn parsedArgsProxy;\n}\nfunction resolveArgs(argsDef) {\n\tconst args = [];\n\tfor (const [name, argDef] of Object.entries(argsDef || {})) args.push({\n\t\t...argDef,\n\t\tname,\n\t\talias: toArray(argDef.alias)\n\t});\n\treturn args;\n}\n//#endregion\n//#region src/plugin.ts\nfunction defineCittyPlugin(plugin) {\n\treturn plugin;\n}\nasync function resolvePlugins(plugins) {\n\treturn Promise.all(plugins.map((p) => resolveValue(p)));\n}\n//#endregion\n//#region src/command.ts\nfunction defineCommand(def) {\n\treturn def;\n}\nasync function runCommand(cmd, opts) {\n\tconst cmdArgs = await resolveValue(cmd.args || {});\n\tconst parsedArgs = parseArgs(opts.rawArgs, cmdArgs);\n\tconst context = {\n\t\trawArgs: opts.rawArgs,\n\t\targs: parsedArgs,\n\t\tdata: opts.data,\n\t\tcmd\n\t};\n\tconst plugins = await resolvePlugins(cmd.plugins ?? []);\n\tlet result;\n\tlet runError;\n\ttry {\n\t\tfor (const plugin of plugins) await plugin.setup?.(context);\n\t\tif (typeof cmd.setup === \"function\") await cmd.setup(context);\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\t\tconst subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);\n\t\t\tconst explicitName = opts.rawArgs[subCommandArgIndex];\n\t\t\tif (explicitName) {\n\t\t\t\tconst subCommand = await _findSubCommand(subCommands, explicitName);\n\t\t\t\tif (!subCommand) throw new CLIError(`Unknown command ${cyan(explicitName)}`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });\n\t\t\t} else {\n\t\t\t\tconst defaultSubCommand = await resolveValue(cmd.default);\n\t\t\t\tif (defaultSubCommand) {\n\t\t\t\t\tif (cmd.run) throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`, \"E_DEFAULT_CONFLICT\");\n\t\t\t\t\tconst subCommand = await _findSubCommand(subCommands, defaultSubCommand);\n\t\t\t\t\tif (!subCommand) throw new CLIError(`Default sub command ${cyan(defaultSubCommand)} not found in subCommands.`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs });\n\t\t\t\t} else if (!cmd.run) throw new CLIError(`No command specified.`, \"E_NO_COMMAND\");\n\t\t\t}\n\t\t}\n\t\tif (typeof cmd.run === \"function\") result = await cmd.run(context);\n\t} catch (error) {\n\t\trunError = error;\n\t}\n\tconst cleanupErrors = [];\n\tif (typeof cmd.cleanup === \"function\") try {\n\t\tawait cmd.cleanup(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tfor (const plugin of [...plugins].reverse()) try {\n\t\tawait plugin.cleanup?.(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tif (runError) throw runError;\n\tif (cleanupErrors.length === 1) throw cleanupErrors[0];\n\tif (cleanupErrors.length > 1) throw new Error(\"Multiple cleanup errors\", { cause: cleanupErrors });\n\treturn { result };\n}\nasync function resolveSubCommand(cmd, rawArgs, parent) {\n\tconst subCommands = await resolveValue(cmd.subCommands);\n\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\tconst subCommandArgIndex = findSubCommandIndex(rawArgs, await resolveValue(cmd.args || {}));\n\t\tconst subCommandName = rawArgs[subCommandArgIndex];\n\t\tconst subCommand = await _findSubCommand(subCommands, subCommandName);\n\t\tif (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);\n\t}\n\treturn [cmd, parent];\n}\nasync function _findSubCommand(subCommands, name) {\n\tif (name in subCommands) return resolveValue(subCommands[name]);\n\tfor (const sub of Object.values(subCommands)) {\n\t\tconst resolved = await resolveValue(sub);\n\t\tconst meta = await resolveValue(resolved?.meta);\n\t\tif (meta?.alias) {\n\t\t\tif (toArray(meta.alias).includes(name)) return resolved;\n\t\t}\n\t}\n}\nfunction findSubCommandIndex(rawArgs, argsDef) {\n\tfor (let i = 0; i < rawArgs.length; i++) {\n\t\tconst arg = rawArgs[i];\n\t\tif (arg === \"--\") return -1;\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tif (!arg.includes(\"=\") && _isValueFlag(arg, argsDef)) i++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn i;\n\t}\n\treturn -1;\n}\nfunction _isValueFlag(flag, argsDef) {\n\tconst name = flag.replace(/^-{1,2}/, \"\");\n\tconst normalized = camelCase(name);\n\tfor (const [key, def] of Object.entries(argsDef)) {\n\t\tif (def.type !== \"string\" && def.type !== \"enum\") continue;\n\t\tif (normalized === camelCase(key)) return true;\n\t\tif ((Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []).includes(name)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/usage.ts\nasync function showUsage(cmd, parent) {\n\ttry {\n\t\tconsole.log(await renderUsage(cmd, parent) + \"\\n\");\n\t} catch (error) {\n\t\tconsole.error(error);\n\t}\n}\nconst negativePrefixRe = /^no[-A-Z]/;\nasync function renderUsage(cmd, parent) {\n\tconst cmdMeta = await resolveValue(cmd.meta || {});\n\tconst cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));\n\tconst parentMeta = await resolveValue(parent?.meta || {});\n\tconst commandName = `${parentMeta.name ? `${parentMeta.name} ` : \"\"}` + (cmdMeta.name || process.argv[1]);\n\tconst argLines = [];\n\tconst posLines = [];\n\tconst commandsLines = [];\n\tconst usageLine = [];\n\tfor (const arg of cmdArgs) if (arg.type === \"positional\") {\n\t\tconst name = arg.name.toUpperCase();\n\t\tconst isRequired = arg.required !== false && arg.default === void 0;\n\t\tposLines.push([cyan(name + renderValueHint(arg)), renderDescription(arg, isRequired)]);\n\t\tusageLine.push(isRequired ? `<${name}>` : `[${name}]`);\n\t} else {\n\t\tconst isRequired = arg.required === true && arg.default === void 0;\n\t\tconst argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(\", \") + renderValueHint(arg);\n\t\targLines.push([cyan(argStr), renderDescription(arg, isRequired)]);\n\t\t/**\n\t\t* print negative boolean arg variant usage when\n\t\t* - enabled by default or has `negativeDescription`\n\t\t* - not prefixed with `no-` or `no[A-Z]`\n\t\t*/\n\t\tif (arg.type === \"boolean\" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {\n\t\t\tconst negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(\", \");\n\t\t\targLines.push([cyan(negativeArgStr), [arg.negativeDescription, isRequired ? gray(\"(Required)\") : \"\"].filter(Boolean).join(\" \")]);\n\t\t}\n\t\tif (isRequired) usageLine.push(`--${arg.name}` + renderValueHint(arg));\n\t}\n\tif (cmd.subCommands) {\n\t\tconst commandNames = [];\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tfor (const [name, sub] of Object.entries(subCommands)) {\n\t\t\tconst meta = await resolveValue((await resolveValue(sub))?.meta);\n\t\t\tif (meta?.hidden) continue;\n\t\t\tconst aliases = toArray(meta?.alias);\n\t\t\tconst label = [name, ...aliases].join(\", \");\n\t\t\tcommandsLines.push([cyan(label), meta?.description || \"\"]);\n\t\t\tcommandNames.push(name, ...aliases);\n\t\t}\n\t\tusageLine.push(commandNames.join(\"|\"));\n\t}\n\tconst usageLines = [];\n\tconst version = cmdMeta.version || parentMeta.version;\n\tusageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : \"\")})`), \"\");\n\tconst hasOptions = argLines.length > 0 || posLines.length > 0;\n\tusageLines.push(`${underline(bold(\"USAGE\"))} ${cyan(`${commandName}${hasOptions ? \" [OPTIONS]\" : \"\"} ${usageLine.join(\" \")}`)}`, \"\");\n\tif (posLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"ARGUMENTS\")), \"\");\n\t\tusageLines.push(formatLineColumns(posLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (argLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"OPTIONS\")), \"\");\n\t\tusageLines.push(formatLineColumns(argLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (commandsLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"COMMANDS\")), \"\");\n\t\tusageLines.push(formatLineColumns(commandsLines, \" \"));\n\t\tusageLines.push(\"\", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);\n\t}\n\treturn usageLines.filter((l) => typeof l === \"string\").join(\"\\n\");\n}\nfunction renderValueHint(arg) {\n\tconst valueHint = arg.valueHint ? `=<${arg.valueHint}>` : \"\";\n\tconst fallbackValueHint = valueHint || `=<${snakeCase(arg.name)}>`;\n\tif (!arg.type || arg.type === \"positional\" || arg.type === \"boolean\") return valueHint;\n\tif (arg.type === \"enum\" && arg.options?.length) return `=<${arg.options.join(\"|\")}>`;\n\treturn fallbackValueHint;\n}\nfunction renderDescription(arg, required) {\n\tconst requiredHint = required ? gray(\"(Required)\") : \"\";\n\tconst defaultHint = arg.default === void 0 ? \"\" : gray(`(Default: ${arg.default})`);\n\treturn [\n\t\targ.description,\n\t\trequiredHint,\n\t\tdefaultHint\n\t].filter(Boolean).join(\" \");\n}\n//#endregion\n//#region src/main.ts\nasync function runMain(cmd, opts = {}) {\n\tconst rawArgs = opts.rawArgs || process.argv.slice(2);\n\tconst showUsage$1 = opts.showUsage || showUsage;\n\ttry {\n\t\tconst builtinFlags = await _resolveBuiltinFlags(cmd);\n\t\tif (builtinFlags.help.length > 0 && rawArgs.some((arg) => builtinFlags.help.includes(arg))) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tprocess.exit(0);\n\t\t} else if (rawArgs.length === 1 && builtinFlags.version.includes(rawArgs[0])) {\n\t\t\tconst meta = typeof cmd.meta === \"function\" ? await cmd.meta() : await cmd.meta;\n\t\t\tif (!meta?.version) throw new CLIError(\"No version specified\", \"E_NO_VERSION\");\n\t\t\tconsole.log(meta.version);\n\t\t} else await runCommand(cmd, { rawArgs });\n\t} catch (error) {\n\t\tif (error instanceof CLIError) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tconsole.error(error.message);\n\t\t} else console.error(error, \"\\n\");\n\t\tprocess.exit(1);\n\t}\n}\nfunction createMain(cmd) {\n\treturn (opts = {}) => runMain(cmd, opts);\n}\nasync function _resolveBuiltinFlags(cmd) {\n\tconst argsDef = await resolveValue(cmd.args || {});\n\tconst userNames = /* @__PURE__ */ new Set();\n\tconst userAliases = /* @__PURE__ */ new Set();\n\tfor (const [name, def] of Object.entries(argsDef)) {\n\t\tuserNames.add(name);\n\t\tfor (const alias of toArray(def.alias)) userAliases.add(alias);\n\t}\n\treturn {\n\t\thelp: _getBuiltinFlags(\"help\", \"h\", userNames, userAliases),\n\t\tversion: _getBuiltinFlags(\"version\", \"v\", userNames, userAliases)\n\t};\n}\nfunction _getBuiltinFlags(long, short, userNames, userAliases) {\n\tif (userNames.has(long) || userAliases.has(long)) return [];\n\tif (userNames.has(short) || userAliases.has(short)) return [`--${long}`];\n\treturn [`--${long}`, `-${short}`];\n}\n//#endregion\nexport { createMain, defineCittyPlugin, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };\n","/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 422.\n */\n | \"SchemaError\"\n /**\n * CAS lost on `current.json`. Caller decides whether to retry.\n * Surfaces in the collection API and HTTP layer.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * The single error class thrown by Baerly. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // ... CAS lost; retry\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n","var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","/**\n * Output contract for `baerly`. Two modes:\n *\n * - text (default): preserves the legacy `baerly <cmd>: <code>:\n * <msg>\\n` shape on stderr (asserted by `copy.test.ts`); stdout\n * stays silent on success.\n * - JSON (`--json`): one structured envelope per invocation —\n * `{result,...}` on stdout for success, `{error:{code,message,\n * command}}` on stderr for failure. Picked up by agents that\n * drive the CLI programmatically.\n *\n * Detection of `--json` happens twice — once in `baerly.ts` before\n * `runMain` (so a parse-time error from citty also honors the flag)\n * and once inside each subcommand's `run` handler (so programmatic\n * `runCopy` callers like `copy.test.ts` work without going through\n * the entry).\n */\n\nimport pc from \"picocolors\";\n\nlet jsonMode = false;\n\n/** Toggle JSON-envelope output mode. Called from `baerly.ts` and each subcommand. */\nexport const setJsonMode = (v: boolean): void => {\n jsonMode = v;\n};\n\nexport const isJsonMode = (): boolean => jsonMode;\n\n/**\n * Color helpers — no-ops in JSON mode (so emitted JSON stays\n * machine-parseable) and when `picocolors` detects a non-TTY or\n * `NO_COLOR`.\n */\nexport const color = {\n red: (s: string): string => (jsonMode ? s : pc.red(s)),\n yellow: (s: string): string => (jsonMode ? s : pc.yellow(s)),\n dim: (s: string): string => (jsonMode ? s : pc.dim(s)),\n};\n\n/**\n * Emit an error. Text mode preserves the legacy `baerly <cmd>:\n * <code>: <msg>\\n` shape that `copy.test.ts` (transitively) and any\n * scripts piping stderr already expect.\n *\n * Two corner cases the brand prefix needs to handle:\n * - When the runBin shim catches a top-level error it passes\n * `command === \"baerly\"` (or `\"create-baerly-storage\"`); doubling the\n * brand (`baerly baerly: …`) is ugly. Collapse to just\n * `baerly: <code>: <msg>` in that case.\n * - When `command` is empty (top-level parse errors that haven't\n * matched a subcommand), drop the trailing space and emit\n * `baerly: <code>: <msg>`.\n *\n * JSON-mode envelope is untouched — it carries `command` as a\n * structured field, no double-prefix problem.\n */\nexport const emitError = (command: string, code: string, message: string): void => {\n if (jsonMode) {\n process.stderr.write(`${JSON.stringify({ error: { code, message, command } })}\\n`);\n return;\n }\n let prefix: string;\n if (command === \"\" || command === \"baerly\") {\n prefix = \"baerly\";\n } else if (command === \"create-baerly-storage\") {\n prefix = \"create-baerly-storage\";\n } else {\n prefix = `baerly ${command}`;\n }\n process.stderr.write(`${prefix}: ${code}: ${message}\\n`);\n};\n\n/**\n * Emit a success result. No-op in text mode (subcommands stay silent\n * on success, matching the existing contract); in JSON mode writes\n * one structured envelope to stdout.\n */\nexport const emitSuccess = (data: Record<string, unknown>): void => {\n if (jsonMode) {\n process.stdout.write(`${JSON.stringify({ result: data })}\\n`);\n }\n};\n","/**\n * `runBin` — bin-entry shim around citty 0.2.2's `runCommand`.\n *\n * Why this exists: citty's own `runMain` does not give us enough\n * control over the failure surface. In particular:\n *\n * 1. citty 0.2.2's `runCommand` does NOT intercept `--help` or\n * `--version` on a parent command that has `subCommands`. A bare\n * `baerly --help` invocation tries to *dispatch* (and fails on\n * \"no subcommand\").\n * 2. `runMain` translates the internal `CLIError` (the one thrown\n * for unknown flags, invalid enum values, missing required\n * flags) into a bare `process.stderr.write` + `process.exit(1)`.\n * We want every error path to flow through {@link emitError}\n * so `--json` envelopes work even on parse-time failures, and\n * the brand-prefix collapse for top-level errors stays\n * consistent.\n *\n * Behavior:\n * - Sets `setJsonMode(argv.includes(\"--json\"))` as the first\n * action so parse-time errors still emit a JSON envelope.\n * - Walks `cmd.subCommands` to handle `--help` / `-h` and\n * `--version` / `-v` at any nesting depth.\n * - Translates citty `CLIError`s into `BaerlyError(\"InvalidConfig\",\n * …)` semantics.\n * - Maps `BaerlyError.code` through the same 3-bucket exit-code\n * table the per-subcommand wrappers use (`InvalidConfig → 1`,\n * `Conflict|Internal|InvalidResponse → 3`, else 2).\n */\n\nimport {\n type CommandDef,\n type SubCommandsDef,\n type CommandMeta,\n type Resolvable,\n runCommand,\n showUsage,\n} from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst resolve = async <T>(v: Resolvable<T>): Promise<T> => {\n if (typeof v === \"function\") {\n return (v as () => T | Promise<T>)();\n }\n return v;\n};\n\n/**\n * Walk `cmd.subCommands` along the leading positional args to find\n * the deepest matched subcommand. Returns `cmd` itself when no\n * positional matches, so `<bin> --help` (no subcommand) still\n * resolves to the top-level command.\n */\nconst resolveTarget = async (\n cmd: CommandDef,\n positional: readonly string[],\n): Promise<CommandDef> => {\n let cur: CommandDef = cmd;\n for (const arg of positional) {\n const subs = cur.subCommands;\n if (subs === undefined) {\n break;\n }\n const subsResolved = (await resolve(subs)) as SubCommandsDef;\n const next = subsResolved[arg];\n if (next === undefined) {\n break;\n }\n cur = (await resolve(next)) as CommandDef;\n }\n return cur;\n};\n\n/** Return the leading positional args (everything before the first `--flag`). */\nconst leadingPositionals = (argv: readonly string[]): readonly string[] => {\n const out: string[] = [];\n for (const a of argv) {\n if (a.startsWith(\"-\")) {\n break;\n }\n out.push(a);\n }\n return out;\n};\n\n/**\n * Bin-entry runner. Returns a promise that never resolves on\n * success (it calls `process.exit(0)`); on error it `process.exit`s\n * with the mapped code.\n *\n * `brand` controls the {@link emitError} prefix on top-level\n * failures — `\"baerly\"` for the main CLI, `\"create-baerly-storage\"` for\n * the scaffolder.\n */\nexport const runBin = async (\n cmd: CommandDef,\n argv: readonly string[],\n brand: \"baerly\" | \"create-baerly-storage\" = \"baerly\",\n): Promise<void> => {\n setJsonMode(argv.includes(\"--json\"));\n\n // Intercept --help / -h before runCommand. citty 0.2.2 does NOT\n // handle these on a parent command with subcommands.\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n const target = await resolveTarget(cmd, leadingPositionals(argv));\n await showUsage(target);\n process.exit(0);\n }\n\n // Intercept --version / -v.\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n const meta = (await resolve(cmd.meta as Resolvable<CommandMeta>)) ?? {};\n const version = meta.version;\n if (typeof version !== \"string\" || version.length === 0) {\n emitError(brand, \"InvalidConfig\", \"no version declared on this command\");\n process.exit(1);\n }\n process.stdout.write(`${version}\\n`);\n process.exit(0);\n }\n\n try {\n await runCommand(cmd, { rawArgs: [...argv] });\n process.exit(0);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(brand, error.code, error.message);\n process.exit(errorToExitCode(error.code));\n }\n // citty CLIError (unknown flag, invalid enum value, missing\n // required flag) — translate to InvalidConfig.\n const message = error instanceof Error ? error.message : String(error);\n emitError(brand, \"InvalidConfig\", message);\n process.exit(1);\n }\n};\n","/**\n * `baerly` — vendorless document database CLI. Entry point bundled\n * to `dist/baerly.js` by `rolldown.config.ts` with a `#!/usr/bin/env\n * node` banner.\n *\n * Subcommands live in their own modules and register via citty's\n * `defineCommand`. Adding a new subcommand: write its module, export\n * a `defineCommand` block, drop it into `subCommands` below as a\n * lazy `() => import(\"./x.ts\").then(m => m.x)` factory. citty 0.2.2\n * supports `Resolvable<CommandDef>` in `subCommands`, so the factory\n * shape is type-correct and only the dispatched module's transitive\n * imports are evaluated at startup.\n *\n * Exit codes are documented in `packages/cli/README.md` and per-\n * subcommand in each module's docstring.\n */\nimport { defineCommand } from \"citty\";\nimport { runBin } from \"./bin-runner.ts\";\n\n/**\n * `baerly admin <command>` — operator-side reconciliation, inspection,\n * data-shovel, and maintenance tools. Today: `rebuild-index`, `dump`,\n * `restore`, `fsck`, `usage`.\n */\nconst admin = defineCommand({\n meta: {\n name: \"admin\",\n description: \"Operator commands — reconciliation and inspection.\",\n },\n subCommands: {\n \"rebuild-index\": () => import(\"./admin/rebuild-index.ts\").then((m) => m.rebuildIndexCmd),\n dump: () => import(\"./admin/dump.ts\").then((m) => m.dumpCmd),\n restore: () => import(\"./admin/restore.ts\").then((m) => m.restoreCmd),\n fsck: () => import(\"./admin/fsck.ts\").then((m) => m.fsckCmd),\n usage: () => import(\"./admin/usage.ts\").then((m) => m.usageCmd),\n },\n});\n\nconst main = defineCommand({\n meta: {\n name: \"baerly\",\n version: \"0.0.0\",\n description: \"Vendorless document database CLI.\",\n },\n // Order matters: citty renders --help in declaration order.\n // Day-1 verbs (deploy) come first, then operator reads\n // (doctor → inspect → export → cost), then `admin`. Scaffolding +\n // bolt-on into an existing wrangler project both live in the\n // `@gusto/create-baerly-storage` package — invoke via\n // `pnpm create @gusto/baerly-storage@latest` /\n // `pnpm create @gusto/baerly-storage@latest .`, not a `baerly` subcommand.\n subCommands: {\n deploy: () => import(\"./deploy.ts\").then((m) => m.deploy),\n doctor: () => import(\"./doctor.ts\").then((m) => m.doctor),\n inspect: () => import(\"./inspect.ts\").then((m) => m.inspect),\n export: () => import(\"./export.ts\").then((m) => m.exportCmd),\n cost: () => import(\"./cost.ts\").then((m) => m.cost),\n admin,\n },\n});\n\nvoid runBin(main, process.argv.slice(2), \"baerly\");\n"],"x_google_ignoreList":[0,1,3],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;CACrB;CACA;CACA;CACA;AACD;AACA,SAAS,YAAY,OAAO,IAAI;CAC/B,IAAI,eAAe,KAAK,IAAI,GAAG;CAC/B,OAAO,SAAS,KAAK,YAAY;AAClC;AACA,SAAS,YAAY,KAAK,YAAY;CACrC,MAAM,YAAY,cAAc;CAChC,MAAM,QAAQ,CAAC;CACf,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,IAAI,OAAO;CACX,IAAI;CACJ,IAAI;CACJ,KAAK,MAAM,QAAQ,KAAK;EACvB,MAAM,aAAa,UAAU,SAAS,IAAI;EAC1C,IAAI,eAAe,MAAM;GACxB,MAAM,KAAK,IAAI;GACf,OAAO;GACP,gBAAgB,KAAK;GACrB;EACD;EACA,MAAM,UAAU,YAAY,IAAI;EAChC,IAAI,qBAAqB,OAAO;GAC/B,IAAI,kBAAkB,SAAS,YAAY,MAAM;IAChD,MAAM,KAAK,IAAI;IACf,OAAO;IACP,gBAAgB;IAChB;GACD;GACA,IAAI,kBAAkB,QAAQ,YAAY,SAAS,KAAK,SAAS,GAAG;IACnE,MAAM,WAAW,KAAK,GAAG,EAAE;IAC3B,MAAM,KAAK,KAAK,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC;IACtD,OAAO,WAAW;IAClB,gBAAgB;IAChB;GACD;EACD;EACA,QAAQ;EACR,gBAAgB;EAChB,mBAAmB;CACpB;CACA,MAAM,KAAK,IAAI;CACf,OAAO;AACR;AACA,SAAS,WAAW,KAAK;CACxB,OAAO,MAAM,IAAI,GAAG,YAAY,IAAI,IAAI,MAAM,CAAC,IAAI;AACpD;AACA,SAAS,WAAW,KAAK;CACxB,OAAO,MAAM,IAAI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uBAAoB,MAAM,MAAM,EAAE,QAAQ;GAChE;EACF,CAqBQ;CACN;AACF,CAEe,GAAG,QAAQ,KAAK,MAAM,CAAC,GAAG,QAAQ"}
|
|
1
|
+
{"version":3,"file":"baerly.js","names":["parseArgs$1","parseArgs","pc"],"sources":["../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/_chunks/libs/scule.mjs","../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/index.mjs","../packages/protocol/src/errors.ts","../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/cli/src/output.ts","../packages/cli/src/bin-runner.ts","../packages/cli/src/baerly.ts"],"sourcesContent":["//#region node_modules/.pnpm/scule@1.3.0/node_modules/scule/dist/index.mjs\nconst NUMBER_CHAR_RE = /\\d/;\nconst STR_SPLITTERS = [\n\t\"-\",\n\t\"_\",\n\t\"/\",\n\t\".\"\n];\nfunction isUppercase(char = \"\") {\n\tif (NUMBER_CHAR_RE.test(char)) return;\n\treturn char !== char.toLowerCase();\n}\nfunction splitByCase(str, separators) {\n\tconst splitters = separators ?? STR_SPLITTERS;\n\tconst parts = [];\n\tif (!str || typeof str !== \"string\") return parts;\n\tlet buff = \"\";\n\tlet previousUpper;\n\tlet previousSplitter;\n\tfor (const char of str) {\n\t\tconst isSplitter = splitters.includes(char);\n\t\tif (isSplitter === true) {\n\t\t\tparts.push(buff);\n\t\t\tbuff = \"\";\n\t\t\tpreviousUpper = void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst isUpper = isUppercase(char);\n\t\tif (previousSplitter === false) {\n\t\t\tif (previousUpper === false && isUpper === true) {\n\t\t\t\tparts.push(buff);\n\t\t\t\tbuff = char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previousUpper === true && isUpper === false && buff.length > 1) {\n\t\t\t\tconst lastChar = buff.at(-1);\n\t\t\t\tparts.push(buff.slice(0, Math.max(0, buff.length - 1)));\n\t\t\t\tbuff = lastChar + char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tbuff += char;\n\t\tpreviousUpper = isUpper;\n\t\tpreviousSplitter = isSplitter;\n\t}\n\tparts.push(buff);\n\treturn parts;\n}\nfunction upperFirst(str) {\n\treturn str ? str[0].toUpperCase() + str.slice(1) : \"\";\n}\nfunction lowerFirst(str) {\n\treturn str ? str[0].toLowerCase() + str.slice(1) : \"\";\n}\nfunction pascalCase(str, opts) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join(\"\") : \"\";\n}\nfunction camelCase(str, opts) {\n\treturn lowerFirst(pascalCase(str || \"\", opts));\n}\nfunction kebabCase(str, joiner) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? \"-\") : \"\";\n}\nfunction snakeCase(str) {\n\treturn kebabCase(str || \"\", \"_\");\n}\n//#endregion\nexport { kebabCase as n, snakeCase as r, camelCase as t };\n","import { n as kebabCase, r as snakeCase, t as camelCase } from \"./_chunks/libs/scule.mjs\";\nimport { parseArgs as parseArgs$1 } from \"node:util\";\n//#region src/_utils.ts\nfunction toArray(val) {\n\tif (Array.isArray(val)) return val;\n\treturn val === void 0 ? [] : [val];\n}\nfunction formatLineColumns(lines, linePrefix = \"\") {\n\tconst maxLength = [];\n\tfor (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);\n\treturn lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? \"padStart\" : \"padEnd\"](maxLength[i])).join(\" \")).join(\"\\n\");\n}\nfunction resolveValue(input) {\n\treturn typeof input === \"function\" ? input() : input;\n}\nvar CLIError = class extends Error {\n\tcode;\n\tconstructor(message, code) {\n\t\tsuper(message);\n\t\tthis.name = \"CLIError\";\n\t\tthis.code = code;\n\t}\n};\n//#endregion\n//#region src/_parser.ts\nfunction parseRawArgs(args = [], opts = {}) {\n\tconst booleans = new Set(opts.boolean || []);\n\tconst strings = new Set(opts.string || []);\n\tconst aliasMap = opts.alias || {};\n\tconst defaults = opts.default || {};\n\tconst aliasToMain = /* @__PURE__ */ new Map();\n\tconst mainToAliases = /* @__PURE__ */ new Map();\n\tfor (const [key, value] of Object.entries(aliasMap)) {\n\t\tconst targets = value;\n\t\tfor (const target of targets) {\n\t\t\taliasToMain.set(key, target);\n\t\t\tif (!mainToAliases.has(target)) mainToAliases.set(target, []);\n\t\t\tmainToAliases.get(target).push(key);\n\t\t\taliasToMain.set(target, key);\n\t\t\tif (!mainToAliases.has(key)) mainToAliases.set(key, []);\n\t\t\tmainToAliases.get(key).push(target);\n\t\t}\n\t}\n\tconst options = {};\n\tfunction getType(name) {\n\t\tif (booleans.has(name)) return \"boolean\";\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (booleans.has(alias)) return \"boolean\";\n\t\treturn \"string\";\n\t}\n\tfunction isStringType(name) {\n\t\tif (strings.has(name)) return true;\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (strings.has(alias)) return true;\n\t\treturn false;\n\t}\n\tconst allOptions = new Set([\n\t\t...booleans,\n\t\t...strings,\n\t\t...Object.keys(aliasMap),\n\t\t...Object.values(aliasMap).flat(),\n\t\t...Object.keys(defaults)\n\t]);\n\tfor (const name of allOptions) if (!options[name]) options[name] = {\n\t\ttype: getType(name),\n\t\tdefault: defaults[name]\n\t};\n\tfor (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;\n\tconst processedArgs = [];\n\tconst negatedFlags = {};\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg === \"--\") {\n\t\t\tprocessedArgs.push(...args.slice(i));\n\t\t\tbreak;\n\t\t}\n\t\tif (arg.startsWith(\"--no-\")) {\n\t\t\tconst flagName = arg.slice(5);\n\t\t\tnegatedFlags[flagName] = true;\n\t\t\tcontinue;\n\t\t}\n\t\tprocessedArgs.push(arg);\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = parseArgs$1({\n\t\t\targs: processedArgs,\n\t\t\toptions: Object.keys(options).length > 0 ? options : void 0,\n\t\t\tallowPositionals: true,\n\t\t\tstrict: false\n\t\t});\n\t} catch {\n\t\tparsed = {\n\t\t\tvalues: {},\n\t\t\tpositionals: processedArgs\n\t\t};\n\t}\n\tconst out = { _: [] };\n\tout._ = parsed.positionals;\n\tfor (const [key, value] of Object.entries(parsed.values)) {\n\t\tlet coerced = value;\n\t\tif (getType(key) === \"boolean\" && typeof value === \"string\") coerced = value !== \"false\";\n\t\telse if (isStringType(key) && typeof value === \"boolean\") coerced = \"\";\n\t\tout[key] = coerced;\n\t}\n\tfor (const [name] of Object.entries(negatedFlags)) {\n\t\tout[name] = false;\n\t\tconst mainName = aliasToMain.get(name);\n\t\tif (mainName) out[mainName] = false;\n\t\tconst aliases = mainToAliases.get(name);\n\t\tif (aliases) for (const alias of aliases) out[alias] = false;\n\t}\n\tfor (const [alias, main] of aliasToMain.entries()) {\n\t\tif (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];\n\t\tif (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];\n\t\tif (out[alias] !== out[main] && defaults[main] === out[main]) out[main] = out[alias];\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/_color.ts\nconst noColor = /* @__PURE__ */ (() => {\n\tconst env = globalThis.process?.env ?? {};\n\treturn env.NO_COLOR === \"1\" || env.TERM === \"dumb\" || env.TEST || env.CI;\n})();\nconst _c = (c, r = 39) => (t) => noColor ? t : `\\u001B[${c}m${t}\\u001B[${r}m`;\nconst bold = /* @__PURE__ */ _c(1, 22);\nconst cyan = /* @__PURE__ */ _c(36);\nconst gray = /* @__PURE__ */ _c(90);\nconst underline = /* @__PURE__ */ _c(4, 24);\n//#endregion\n//#region src/args.ts\nfunction parseArgs(rawArgs, argsDef) {\n\tconst parseOptions = {\n\t\tboolean: [],\n\t\tstring: [],\n\t\talias: {},\n\t\tdefault: {}\n\t};\n\tconst args = resolveArgs(argsDef);\n\tfor (const arg of args) {\n\t\tif (arg.type === \"positional\") continue;\n\t\tif (arg.type === \"string\" || arg.type === \"enum\") parseOptions.string.push(arg.name);\n\t\telse if (arg.type === \"boolean\") parseOptions.boolean.push(arg.name);\n\t\tif (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;\n\t\tif (arg.alias) parseOptions.alias[arg.name] = arg.alias;\n\t\tconst camelName = camelCase(arg.name);\n\t\tconst kebabName = kebabCase(arg.name);\n\t\tif (camelName !== arg.name || kebabName !== arg.name) {\n\t\t\tconst existingAliases = toArray(parseOptions.alias[arg.name] || []);\n\t\t\tif (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);\n\t\t\tif (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);\n\t\t\tif (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;\n\t\t}\n\t}\n\tconst parsed = parseRawArgs(rawArgs, parseOptions);\n\tconst [ ...positionalArguments] = parsed._;\n\tconst parsedArgsProxy = new Proxy(parsed, { get(target, prop) {\n\t\treturn target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];\n\t} });\n\tfor (const [, arg] of args.entries()) if (arg.type === \"positional\") {\n\t\tconst nextPositionalArgument = positionalArguments.shift();\n\t\tif (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;\n\t\telse if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, \"EARG\");\n\t\telse parsedArgsProxy[arg.name] = arg.default;\n\t} else if (arg.type === \"enum\") {\n\t\tconst argument = parsedArgsProxy[arg.name];\n\t\tconst options = arg.options || [];\n\t\tif (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(\", \")}.`, \"EARG\");\n\t} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, \"EARG\");\n\treturn parsedArgsProxy;\n}\nfunction resolveArgs(argsDef) {\n\tconst args = [];\n\tfor (const [name, argDef] of Object.entries(argsDef || {})) args.push({\n\t\t...argDef,\n\t\tname,\n\t\talias: toArray(argDef.alias)\n\t});\n\treturn args;\n}\n//#endregion\n//#region src/plugin.ts\nfunction defineCittyPlugin(plugin) {\n\treturn plugin;\n}\nasync function resolvePlugins(plugins) {\n\treturn Promise.all(plugins.map((p) => resolveValue(p)));\n}\n//#endregion\n//#region src/command.ts\nfunction defineCommand(def) {\n\treturn def;\n}\nasync function runCommand(cmd, opts) {\n\tconst cmdArgs = await resolveValue(cmd.args || {});\n\tconst parsedArgs = parseArgs(opts.rawArgs, cmdArgs);\n\tconst context = {\n\t\trawArgs: opts.rawArgs,\n\t\targs: parsedArgs,\n\t\tdata: opts.data,\n\t\tcmd\n\t};\n\tconst plugins = await resolvePlugins(cmd.plugins ?? []);\n\tlet result;\n\tlet runError;\n\ttry {\n\t\tfor (const plugin of plugins) await plugin.setup?.(context);\n\t\tif (typeof cmd.setup === \"function\") await cmd.setup(context);\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\t\tconst subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);\n\t\t\tconst explicitName = opts.rawArgs[subCommandArgIndex];\n\t\t\tif (explicitName) {\n\t\t\t\tconst subCommand = await _findSubCommand(subCommands, explicitName);\n\t\t\t\tif (!subCommand) throw new CLIError(`Unknown command ${cyan(explicitName)}`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });\n\t\t\t} else {\n\t\t\t\tconst defaultSubCommand = await resolveValue(cmd.default);\n\t\t\t\tif (defaultSubCommand) {\n\t\t\t\t\tif (cmd.run) throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`, \"E_DEFAULT_CONFLICT\");\n\t\t\t\t\tconst subCommand = await _findSubCommand(subCommands, defaultSubCommand);\n\t\t\t\t\tif (!subCommand) throw new CLIError(`Default sub command ${cyan(defaultSubCommand)} not found in subCommands.`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs });\n\t\t\t\t} else if (!cmd.run) throw new CLIError(`No command specified.`, \"E_NO_COMMAND\");\n\t\t\t}\n\t\t}\n\t\tif (typeof cmd.run === \"function\") result = await cmd.run(context);\n\t} catch (error) {\n\t\trunError = error;\n\t}\n\tconst cleanupErrors = [];\n\tif (typeof cmd.cleanup === \"function\") try {\n\t\tawait cmd.cleanup(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tfor (const plugin of [...plugins].reverse()) try {\n\t\tawait plugin.cleanup?.(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tif (runError) throw runError;\n\tif (cleanupErrors.length === 1) throw cleanupErrors[0];\n\tif (cleanupErrors.length > 1) throw new Error(\"Multiple cleanup errors\", { cause: cleanupErrors });\n\treturn { result };\n}\nasync function resolveSubCommand(cmd, rawArgs, parent) {\n\tconst subCommands = await resolveValue(cmd.subCommands);\n\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\tconst subCommandArgIndex = findSubCommandIndex(rawArgs, await resolveValue(cmd.args || {}));\n\t\tconst subCommandName = rawArgs[subCommandArgIndex];\n\t\tconst subCommand = await _findSubCommand(subCommands, subCommandName);\n\t\tif (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);\n\t}\n\treturn [cmd, parent];\n}\nasync function _findSubCommand(subCommands, name) {\n\tif (name in subCommands) return resolveValue(subCommands[name]);\n\tfor (const sub of Object.values(subCommands)) {\n\t\tconst resolved = await resolveValue(sub);\n\t\tconst meta = await resolveValue(resolved?.meta);\n\t\tif (meta?.alias) {\n\t\t\tif (toArray(meta.alias).includes(name)) return resolved;\n\t\t}\n\t}\n}\nfunction findSubCommandIndex(rawArgs, argsDef) {\n\tfor (let i = 0; i < rawArgs.length; i++) {\n\t\tconst arg = rawArgs[i];\n\t\tif (arg === \"--\") return -1;\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tif (!arg.includes(\"=\") && _isValueFlag(arg, argsDef)) i++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn i;\n\t}\n\treturn -1;\n}\nfunction _isValueFlag(flag, argsDef) {\n\tconst name = flag.replace(/^-{1,2}/, \"\");\n\tconst normalized = camelCase(name);\n\tfor (const [key, def] of Object.entries(argsDef)) {\n\t\tif (def.type !== \"string\" && def.type !== \"enum\") continue;\n\t\tif (normalized === camelCase(key)) return true;\n\t\tif ((Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []).includes(name)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/usage.ts\nasync function showUsage(cmd, parent) {\n\ttry {\n\t\tconsole.log(await renderUsage(cmd, parent) + \"\\n\");\n\t} catch (error) {\n\t\tconsole.error(error);\n\t}\n}\nconst negativePrefixRe = /^no[-A-Z]/;\nasync function renderUsage(cmd, parent) {\n\tconst cmdMeta = await resolveValue(cmd.meta || {});\n\tconst cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));\n\tconst parentMeta = await resolveValue(parent?.meta || {});\n\tconst commandName = `${parentMeta.name ? `${parentMeta.name} ` : \"\"}` + (cmdMeta.name || process.argv[1]);\n\tconst argLines = [];\n\tconst posLines = [];\n\tconst commandsLines = [];\n\tconst usageLine = [];\n\tfor (const arg of cmdArgs) if (arg.type === \"positional\") {\n\t\tconst name = arg.name.toUpperCase();\n\t\tconst isRequired = arg.required !== false && arg.default === void 0;\n\t\tposLines.push([cyan(name + renderValueHint(arg)), renderDescription(arg, isRequired)]);\n\t\tusageLine.push(isRequired ? `<${name}>` : `[${name}]`);\n\t} else {\n\t\tconst isRequired = arg.required === true && arg.default === void 0;\n\t\tconst argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(\", \") + renderValueHint(arg);\n\t\targLines.push([cyan(argStr), renderDescription(arg, isRequired)]);\n\t\t/**\n\t\t* print negative boolean arg variant usage when\n\t\t* - enabled by default or has `negativeDescription`\n\t\t* - not prefixed with `no-` or `no[A-Z]`\n\t\t*/\n\t\tif (arg.type === \"boolean\" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {\n\t\t\tconst negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(\", \");\n\t\t\targLines.push([cyan(negativeArgStr), [arg.negativeDescription, isRequired ? gray(\"(Required)\") : \"\"].filter(Boolean).join(\" \")]);\n\t\t}\n\t\tif (isRequired) usageLine.push(`--${arg.name}` + renderValueHint(arg));\n\t}\n\tif (cmd.subCommands) {\n\t\tconst commandNames = [];\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tfor (const [name, sub] of Object.entries(subCommands)) {\n\t\t\tconst meta = await resolveValue((await resolveValue(sub))?.meta);\n\t\t\tif (meta?.hidden) continue;\n\t\t\tconst aliases = toArray(meta?.alias);\n\t\t\tconst label = [name, ...aliases].join(\", \");\n\t\t\tcommandsLines.push([cyan(label), meta?.description || \"\"]);\n\t\t\tcommandNames.push(name, ...aliases);\n\t\t}\n\t\tusageLine.push(commandNames.join(\"|\"));\n\t}\n\tconst usageLines = [];\n\tconst version = cmdMeta.version || parentMeta.version;\n\tusageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : \"\")})`), \"\");\n\tconst hasOptions = argLines.length > 0 || posLines.length > 0;\n\tusageLines.push(`${underline(bold(\"USAGE\"))} ${cyan(`${commandName}${hasOptions ? \" [OPTIONS]\" : \"\"} ${usageLine.join(\" \")}`)}`, \"\");\n\tif (posLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"ARGUMENTS\")), \"\");\n\t\tusageLines.push(formatLineColumns(posLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (argLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"OPTIONS\")), \"\");\n\t\tusageLines.push(formatLineColumns(argLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (commandsLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"COMMANDS\")), \"\");\n\t\tusageLines.push(formatLineColumns(commandsLines, \" \"));\n\t\tusageLines.push(\"\", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);\n\t}\n\treturn usageLines.filter((l) => typeof l === \"string\").join(\"\\n\");\n}\nfunction renderValueHint(arg) {\n\tconst valueHint = arg.valueHint ? `=<${arg.valueHint}>` : \"\";\n\tconst fallbackValueHint = valueHint || `=<${snakeCase(arg.name)}>`;\n\tif (!arg.type || arg.type === \"positional\" || arg.type === \"boolean\") return valueHint;\n\tif (arg.type === \"enum\" && arg.options?.length) return `=<${arg.options.join(\"|\")}>`;\n\treturn fallbackValueHint;\n}\nfunction renderDescription(arg, required) {\n\tconst requiredHint = required ? gray(\"(Required)\") : \"\";\n\tconst defaultHint = arg.default === void 0 ? \"\" : gray(`(Default: ${arg.default})`);\n\treturn [\n\t\targ.description,\n\t\trequiredHint,\n\t\tdefaultHint\n\t].filter(Boolean).join(\" \");\n}\n//#endregion\n//#region src/main.ts\nasync function runMain(cmd, opts = {}) {\n\tconst rawArgs = opts.rawArgs || process.argv.slice(2);\n\tconst showUsage$1 = opts.showUsage || showUsage;\n\ttry {\n\t\tconst builtinFlags = await _resolveBuiltinFlags(cmd);\n\t\tif (builtinFlags.help.length > 0 && rawArgs.some((arg) => builtinFlags.help.includes(arg))) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tprocess.exit(0);\n\t\t} else if (rawArgs.length === 1 && builtinFlags.version.includes(rawArgs[0])) {\n\t\t\tconst meta = typeof cmd.meta === \"function\" ? await cmd.meta() : await cmd.meta;\n\t\t\tif (!meta?.version) throw new CLIError(\"No version specified\", \"E_NO_VERSION\");\n\t\t\tconsole.log(meta.version);\n\t\t} else await runCommand(cmd, { rawArgs });\n\t} catch (error) {\n\t\tif (error instanceof CLIError) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tconsole.error(error.message);\n\t\t} else console.error(error, \"\\n\");\n\t\tprocess.exit(1);\n\t}\n}\nfunction createMain(cmd) {\n\treturn (opts = {}) => runMain(cmd, opts);\n}\nasync function _resolveBuiltinFlags(cmd) {\n\tconst argsDef = await resolveValue(cmd.args || {});\n\tconst userNames = /* @__PURE__ */ new Set();\n\tconst userAliases = /* @__PURE__ */ new Set();\n\tfor (const [name, def] of Object.entries(argsDef)) {\n\t\tuserNames.add(name);\n\t\tfor (const alias of toArray(def.alias)) userAliases.add(alias);\n\t}\n\treturn {\n\t\thelp: _getBuiltinFlags(\"help\", \"h\", userNames, userAliases),\n\t\tversion: _getBuiltinFlags(\"version\", \"v\", userNames, userAliases)\n\t};\n}\nfunction _getBuiltinFlags(long, short, userNames, userAliases) {\n\tif (userNames.has(long) || userAliases.has(long)) return [];\n\tif (userNames.has(short) || userAliases.has(short)) return [`--${long}`];\n\treturn [`--${long}`, `-${short}`];\n}\n//#endregion\nexport { createMain, defineCittyPlugin, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };\n","/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * CAS lost on `current.json`. Caller decides whether to retry.\n * Surfaces in the collection API and HTTP layer.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * The single error class thrown by Baerly. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // ... CAS lost; retry\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n","var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","/**\n * Output contract for `baerly`. Two modes:\n *\n * - text (default): preserves the legacy `baerly <cmd>: <code>:\n * <msg>\\n` shape on stderr (asserted by `copy.test.ts`); stdout\n * stays silent on success.\n * - JSON (`--json`): one structured envelope per invocation —\n * `{result,...}` on stdout for success, `{error:{code,message,\n * command}}` on stderr for failure. Picked up by agents that\n * drive the CLI programmatically.\n *\n * Detection of `--json` happens twice — once in `baerly.ts` before\n * `runMain` (so a parse-time error from citty also honors the flag)\n * and once inside each subcommand's `run` handler (so programmatic\n * `runCopy` callers like `copy.test.ts` work without going through\n * the entry).\n */\n\nimport pc from \"picocolors\";\n\nlet jsonMode = false;\n\n/** Toggle JSON-envelope output mode. Called from `baerly.ts` and each subcommand. */\nexport const setJsonMode = (v: boolean): void => {\n jsonMode = v;\n};\n\nexport const isJsonMode = (): boolean => jsonMode;\n\n/**\n * Color helpers — no-ops in JSON mode (so emitted JSON stays\n * machine-parseable) and when `picocolors` detects a non-TTY or\n * `NO_COLOR`.\n */\nexport const color = {\n red: (s: string): string => (jsonMode ? s : pc.red(s)),\n yellow: (s: string): string => (jsonMode ? s : pc.yellow(s)),\n dim: (s: string): string => (jsonMode ? s : pc.dim(s)),\n};\n\n/**\n * Emit an error. Text mode preserves the legacy `baerly <cmd>:\n * <code>: <msg>\\n` shape that `copy.test.ts` (transitively) and any\n * scripts piping stderr already expect.\n *\n * Two corner cases the brand prefix needs to handle:\n * - When the runBin shim catches a top-level error it passes\n * `command === \"baerly\"` (or `\"create-baerly-storage\"`); doubling the\n * brand (`baerly baerly: …`) is ugly. Collapse to just\n * `baerly: <code>: <msg>` in that case.\n * - When `command` is empty (top-level parse errors that haven't\n * matched a subcommand), drop the trailing space and emit\n * `baerly: <code>: <msg>`.\n *\n * JSON-mode envelope is untouched — it carries `command` as a\n * structured field, no double-prefix problem.\n */\nexport const emitError = (command: string, code: string, message: string): void => {\n if (jsonMode) {\n process.stderr.write(`${JSON.stringify({ error: { code, message, command } })}\\n`);\n return;\n }\n let prefix: string;\n if (command === \"\" || command === \"baerly\") {\n prefix = \"baerly\";\n } else if (command === \"create-baerly-storage\") {\n prefix = \"create-baerly-storage\";\n } else {\n prefix = `baerly ${command}`;\n }\n process.stderr.write(`${prefix}: ${code}: ${message}\\n`);\n};\n\n/**\n * Emit a success result. No-op in text mode (subcommands stay silent\n * on success, matching the existing contract); in JSON mode writes\n * one structured envelope to stdout.\n */\nexport const emitSuccess = (data: Record<string, unknown>): void => {\n if (jsonMode) {\n process.stdout.write(`${JSON.stringify({ result: data })}\\n`);\n }\n};\n","/**\n * `runBin` — bin-entry shim around citty 0.2.2's `runCommand`.\n *\n * Why this exists: citty's own `runMain` does not give us enough\n * control over the failure surface. In particular:\n *\n * 1. citty 0.2.2's `runCommand` does NOT intercept `--help` or\n * `--version` on a parent command that has `subCommands`. A bare\n * `baerly --help` invocation tries to *dispatch* (and fails on\n * \"no subcommand\").\n * 2. `runMain` translates the internal `CLIError` (the one thrown\n * for unknown flags, invalid enum values, missing required\n * flags) into a bare `process.stderr.write` + `process.exit(1)`.\n * We want every error path to flow through {@link emitError}\n * so `--json` envelopes work even on parse-time failures, and\n * the brand-prefix collapse for top-level errors stays\n * consistent.\n *\n * Behavior:\n * - Sets `setJsonMode(argv.includes(\"--json\"))` as the first\n * action so parse-time errors still emit a JSON envelope.\n * - Walks `cmd.subCommands` to handle `--help` / `-h` and\n * `--version` / `-v` at any nesting depth.\n * - Translates citty `CLIError`s into `BaerlyError(\"InvalidConfig\",\n * …)` semantics.\n * - Maps `BaerlyError.code` through the same 3-bucket exit-code\n * table the per-subcommand wrappers use (`InvalidConfig → 1`,\n * `Conflict|Internal|InvalidResponse → 3`, else 2).\n */\n\nimport {\n type CommandDef,\n type SubCommandsDef,\n type CommandMeta,\n type Resolvable,\n runCommand,\n showUsage,\n} from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst resolve = async <T>(v: Resolvable<T>): Promise<T> => {\n if (typeof v === \"function\") {\n return (v as () => T | Promise<T>)();\n }\n return v;\n};\n\n/**\n * Walk `cmd.subCommands` along the leading positional args to find\n * the deepest matched subcommand. Returns `cmd` itself when no\n * positional matches, so `<bin> --help` (no subcommand) still\n * resolves to the top-level command.\n */\nconst resolveTarget = async (\n cmd: CommandDef,\n positional: readonly string[],\n): Promise<CommandDef> => {\n let cur: CommandDef = cmd;\n for (const arg of positional) {\n const subs = cur.subCommands;\n if (subs === undefined) {\n break;\n }\n const subsResolved = (await resolve(subs)) as SubCommandsDef;\n const next = subsResolved[arg];\n if (next === undefined) {\n break;\n }\n cur = (await resolve(next)) as CommandDef;\n }\n return cur;\n};\n\n/** Return the leading positional args (everything before the first `--flag`). */\nconst leadingPositionals = (argv: readonly string[]): readonly string[] => {\n const out: string[] = [];\n for (const a of argv) {\n if (a.startsWith(\"-\")) {\n break;\n }\n out.push(a);\n }\n return out;\n};\n\n/**\n * Bin-entry runner. Returns a promise that never resolves on\n * success (it calls `process.exit(0)`); on error it `process.exit`s\n * with the mapped code.\n *\n * `brand` controls the {@link emitError} prefix on top-level\n * failures — `\"baerly\"` for the main CLI, `\"create-baerly-storage\"` for\n * the scaffolder.\n */\nexport const runBin = async (\n cmd: CommandDef,\n argv: readonly string[],\n brand: \"baerly\" | \"create-baerly-storage\" = \"baerly\",\n): Promise<void> => {\n setJsonMode(argv.includes(\"--json\"));\n\n // Intercept --help / -h before runCommand. citty 0.2.2 does NOT\n // handle these on a parent command with subcommands.\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n const target = await resolveTarget(cmd, leadingPositionals(argv));\n await showUsage(target);\n process.exit(0);\n }\n\n // Intercept --version / -v.\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n const meta = (await resolve(cmd.meta as Resolvable<CommandMeta>)) ?? {};\n const version = meta.version;\n if (typeof version !== \"string\" || version.length === 0) {\n emitError(brand, \"InvalidConfig\", \"no version declared on this command\");\n process.exit(1);\n }\n process.stdout.write(`${version}\\n`);\n process.exit(0);\n }\n\n try {\n await runCommand(cmd, { rawArgs: [...argv] });\n process.exit(0);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(brand, error.code, error.message);\n process.exit(errorToExitCode(error.code));\n }\n // citty CLIError (unknown flag, invalid enum value, missing\n // required flag) — translate to InvalidConfig.\n const message = error instanceof Error ? error.message : String(error);\n emitError(brand, \"InvalidConfig\", message);\n process.exit(1);\n }\n};\n","/**\n * `baerly` — vendorless document database CLI. Entry point bundled\n * to `dist/baerly.js` by `rolldown.config.ts` with a `#!/usr/bin/env\n * node` banner.\n *\n * Subcommands live in their own modules and register via citty's\n * `defineCommand`. Adding a new subcommand: write its module, export\n * a `defineCommand` block, drop it into `subCommands` below as a\n * lazy `() => import(\"./x.ts\").then(m => m.x)` factory. citty 0.2.2\n * supports `Resolvable<CommandDef>` in `subCommands`, so the factory\n * shape is type-correct and only the dispatched module's transitive\n * imports are evaluated at startup.\n *\n * Exit codes are documented in `packages/cli/README.md` and per-\n * subcommand in each module's docstring.\n */\nimport { defineCommand } from \"citty\";\nimport { runBin } from \"./bin-runner.ts\";\n\n/**\n * `baerly admin <command>` — operator-side reconciliation, inspection,\n * data-shovel, and maintenance tools. Today: `rebuild-index`, `dump`,\n * `restore`, `fsck`, `usage`.\n */\nconst admin = defineCommand({\n meta: {\n name: \"admin\",\n description: \"Operator commands — reconciliation and inspection.\",\n },\n subCommands: {\n \"rebuild-index\": () => import(\"./admin/rebuild-index.ts\").then((m) => m.rebuildIndexCmd),\n dump: () => import(\"./admin/dump.ts\").then((m) => m.dumpCmd),\n restore: () => import(\"./admin/restore.ts\").then((m) => m.restoreCmd),\n fsck: () => import(\"./admin/fsck.ts\").then((m) => m.fsckCmd),\n usage: () => import(\"./admin/usage.ts\").then((m) => m.usageCmd),\n },\n});\n\nconst main = defineCommand({\n meta: {\n name: \"baerly\",\n version: \"0.0.0\",\n description: \"Vendorless document database CLI.\",\n },\n // Order matters: citty renders --help in declaration order.\n // Day-1 verbs (deploy) come first, then operator reads\n // (doctor → inspect → export → cost), then `admin`. Scaffolding +\n // bolt-on into an existing wrangler project both live in the\n // `@gusto/create-baerly-storage` package — invoke via\n // `pnpm create @gusto/baerly-storage@latest` /\n // `pnpm create @gusto/baerly-storage@latest .`, not a `baerly` subcommand.\n subCommands: {\n deploy: () => import(\"./deploy.ts\").then((m) => m.deploy),\n doctor: () => import(\"./doctor.ts\").then((m) => m.doctor),\n inspect: () => import(\"./inspect.ts\").then((m) => m.inspect),\n export: () => import(\"./export.ts\").then((m) => m.exportCmd),\n cost: () => import(\"./cost.ts\").then((m) => m.cost),\n admin,\n },\n});\n\nvoid runBin(main, process.argv.slice(2), \"baerly\");\n"],"x_google_ignoreList":[0,1,3],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;CACrB;CACA;CACA;CACA;AACD;AACA,SAAS,YAAY,OAAO,IAAI;CAC/B,IAAI,eAAe,KAAK,IAAI,GAAG;CAC/B,OAAO,SAAS,KAAK,YAAY;AAClC;AACA,SAAS,YAAY,KAAK,YAAY;CACrC,MAAM,YAAY,cAAc;CAChC,MAAM,QAAQ,CAAC;CACf,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,IAAI,OAAO;CACX,IAAI;CACJ,IAAI;CACJ,KAAK,MAAM,QAAQ,KAAK;EACvB,MAAM,aAAa,UAAU,SAAS,IAAI;EAC1C,IAAI,eAAe,MAAM;GACxB,MAAM,KAAK,IAAI;GACf,OAAO;GACP,gBAAgB,KAAK;GACrB;EACD;EACA,MAAM,UAAU,YAAY,IAAI;EAChC,IAAI,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AAC;EAC1C;EAIA,UAAU,OAAO,iBADD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAC5B;EACzC,QAAQ,KAAK,CAAC;CAChB;AACF;;;;;;;;;;;;;;;;;;;ACrFK,OAvBQ,cAAc;CACzB,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf;CAQA,aAAa;EACX,cAAc,OAAO,uBAAc,CAAC,MAAM,MAAM,EAAE,MAAM;EACxD,cAAc,OAAO,uBAAc,CAAC,MAAM,MAAM,EAAE,MAAM;EACxD,eAAe,OAAO,wBAAe,CAAC,MAAM,MAAM,EAAE,OAAO;EAC3D,cAAc,OAAO,uBAAc,CAAC,MAAM,MAAM,EAAE,SAAS;EAC3D,YAAY,OAAO,qBAAY,CAAC,MAAM,MAAM,EAAE,IAAI;EAClD,OAjCU,cAAc;GAC1B,MAAM;IACJ,MAAM;IACN,aAAa;GACf;GACA,aAAa;IACX,uBAAuB,OAAO,8BAA2B,CAAC,MAAM,MAAM,EAAE,eAAe;IACvF,YAAY,OAAO,qBAAkB,CAAC,MAAM,MAAM,EAAE,OAAO;IAC3D,eAAe,OAAO,wBAAqB,CAAC,MAAM,MAAM,EAAE,UAAU;IACpE,YAAY,OAAO,qBAAkB,CAAC,MAAM,MAAM,EAAE,OAAO;IAC3D,aAAa,OAAO,sBAAmB,CAAC,MAAM,MAAM,EAAE,QAAQ;GAChE;EACF,CAqBQ;CACN;AACF,CAEe,GAAG,QAAQ,KAAK,MAAM,CAAC,GAAG,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bytes-BXdamO3L.js","names":[],"sources":["../packages/protocol/src/bytes.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n"],"mappings":";;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,
|
|
1
|
+
{"version":3,"file":"bytes-BXdamO3L.js","names":[],"sources":["../packages/protocol/src/bytes.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n"],"mappings":";;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC;AAEhD,MAAa,mBAAgC,UAC3C,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as CollectionNames, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig } from "./app-config-
|
|
2
|
-
import { f as PredicateArg, l as OrderSpec } from "./index-
|
|
1
|
+
import { a as CollectionNames, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { f as PredicateArg, l as OrderSpec } from "./index-DW7GT6M2.js";
|
|
3
3
|
|
|
4
4
|
//#region packages/client/src/request.d.ts
|
|
5
5
|
/**
|
|
@@ -187,13 +187,13 @@ interface ClientQuery<T extends DocumentData = DocumentData> {
|
|
|
187
187
|
/**
|
|
188
188
|
* Returned by {@link createBaerlyClient}. The typed entry point.
|
|
189
189
|
*
|
|
190
|
-
* `BaerlyClient`
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
* If you need
|
|
195
|
-
* level RPC on the server that
|
|
196
|
-
* process.
|
|
190
|
+
* `BaerlyClient` is read + single-write RPC: reads and by-id
|
|
191
|
+
* mutations (`insert` / `update` / `replace` / `delete`), one
|
|
192
|
+
* document per call. There is no multi-document atomic write — the
|
|
193
|
+
* document is the atomic unit, and the server exposes no batch route.
|
|
194
|
+
* If you need to fan a write across several documents server-side,
|
|
195
|
+
* expose a business-level RPC on the server that drives
|
|
196
|
+
* `db.collection(...)` in-process.
|
|
197
197
|
*
|
|
198
198
|
* @example
|
|
199
199
|
* ```ts
|
|
@@ -230,4 +230,4 @@ interface BaerlyClient<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
230
230
|
declare const createBaerlyClient: <TConfig extends BaerlyConfig = UnboundConfig>(options: BaerlyClientOptions<TConfig>) => BaerlyClient<TConfig>;
|
|
231
231
|
//#endregion
|
|
232
232
|
export { TerminalOptions as a, ClientQuery as i, BaerlyClientOptions as n, createBaerlyClient as o, ClientCollection as r, Fetcher as s, BaerlyClient as t };
|
|
233
|
-
//# sourceMappingURL=client-
|
|
233
|
+
//# sourceMappingURL=client-BJXF3XJA.d.ts.map
|
package/dist/client-react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { r as BaerlyConfig, s as UnboundConfig } from "./app-config-
|
|
2
|
-
import { o as BaerlyError } from "./index-
|
|
3
|
-
import { t as BaerlyClient } from "./client-
|
|
1
|
+
import { r as BaerlyConfig, s as UnboundConfig } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { o as BaerlyError } from "./index-DW7GT6M2.js";
|
|
3
|
+
import { t as BaerlyClient } from "./client-BJXF3XJA.js";
|
|
4
4
|
import { ReactNode } from "react";
|
|
5
5
|
|
|
6
6
|
//#region packages/client/src/react/use-mutation.d.ts
|
package/dist/client-react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-react.js","names":[],"sources":["../packages/client/src/react/provider.ts","../packages/client/src/react/use-mutation.ts","../packages/client/src/react/stable-key.ts","../packages/client/src/poll-since-once.ts","../packages/client/src/react/subscription-pool.ts","../packages/client/src/react/use-query.ts","../packages/client/src/react/create-react.ts"],"sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { BaerlyConfig, UnboundConfig } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\n\nconst ClientContext = createContext<BaerlyClient | undefined>(undefined);\n\nexport interface BaerlyProviderProps {\n readonly client: BaerlyClient;\n readonly children?: ReactNode;\n}\n\n/**\n * Provides a {@link BaerlyClient} to every Baerly React hook below it.\n * Wrap your app once near the root; the hooks read the client from\n * this context and have no `client` argument.\n *\n * Obtained from {@link createBaerlyReact}, not imported directly:\n *\n * @example\n * ```tsx\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"./baerly.config.ts\";\n *\n * const client = createBaerlyClient({ baseUrl: \"/api\", config });\n * const { BaerlyProvider } = createBaerlyReact<typeof config>();\n *\n * <BaerlyProvider client={client}>\n * <App />\n * </BaerlyProvider>\n * ```\n */\nexport const BaerlyProvider = ({ client, children }: BaerlyProviderProps): React.JSX.Element =>\n createElement(ClientContext.Provider, { value: client }, children);\n\n/**\n * Returns the {@link BaerlyClient} provided by the nearest\n * {@link BaerlyProvider}. Throws a clear error if called outside a\n * provider — every hook in this package uses it, so a missing\n * provider surfaces here first.\n *\n * Use this directly when you need imperative access — e.g. inside an\n * event handler that performs a one-shot read or a custom long-poll.\n * For declarative reads and mutations, prefer the typed hooks.\n *\n * @example\n * ```tsx\n * const client = useBaerlyClient<MyConfig>();\n * const onExport = async () => {\n * const rows = await client.collection(\"tickets\").all();\n * download(rows);\n * };\n * ```\n */\nexport const useBaerlyClient = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyClient<TConfig> => {\n const client = useContext(ClientContext);\n if (client === undefined) {\n throw new Error(\n \"useBaerlyClient (and every Baerly React hook) must be used inside <BaerlyProvider>. \" +\n \"Wrap your app: <BaerlyProvider client={client}>…</BaerlyProvider>.\",\n );\n }\n return client as BaerlyClient<TConfig>;\n};\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\n\n/**\n * Tuple returned by {@link useMutation}. Positionally mirrors React\n * 19's `useActionState`: `[mutate, state]`. `mutate` is stable across\n * renders; `state` is a fresh object only when `isPending` or\n * `error` actually flips.\n */\nexport type UseMutationTuple<TConfig extends BaerlyConfig = UnboundConfig> = readonly [\n mutate: <T>(callback: (client: BaerlyClient<TConfig>) => Promise<T>) => Promise<T>,\n state: { readonly isPending: boolean; readonly error: BaerlyError | undefined },\n];\n\n/**\n * Imperative mutation hook. `mutate(callback)` runs the callback\n * against the real `BaerlyClient` and resolves to whatever the\n * callback returns; `state` carries `isPending` (refcounted across\n * concurrent submits — `true` until every in-flight call settles)\n * and `error` (last-wins; the most recent rejection until the next\n * successful call clears it).\n *\n * Errors are normalised to {@link BaerlyError}: a non-`BaerlyError`\n * throwable from the callback is wrapped under\n * `code: \"MutationFailed\"` with the original on `.cause`.\n *\n * @example\n * ```tsx\n * const [mutate, { isPending, error }] = useMutation();\n * <button\n * disabled={isPending}\n * onClick={() => mutate((client) => client.collection(\"notes\").insert({ body }))}\n * >\n * {isPending ? \"Saving…\" : \"Save\"}\n * </button>\n * {error ? <p>{error.message}</p> : null}\n * ```\n */\nexport const useMutation = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): UseMutationTuple<TConfig> => {\n const client = useBaerlyClient<TConfig>();\n const inFlightRef = useRef<number>(0);\n const mountedRef = useRef<boolean>(true);\n const [isPending, setIsPending] = useState<boolean>(false);\n const [lastError, setLastError] = useState<BaerlyError | undefined>(undefined);\n\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n [],\n );\n\n const mutate = useCallback(\n async <T>(callback: (c: BaerlyClient<TConfig>) => Promise<T>): Promise<T> => {\n const wasIdle = inFlightRef.current === 0;\n inFlightRef.current += 1;\n if (wasIdle && mountedRef.current) {\n setIsPending(true);\n setLastError(undefined);\n }\n try {\n const result = await callback(client);\n return result;\n } catch (error) {\n const be =\n error instanceof BaerlyError\n ? error\n : new BaerlyError(\n \"MutationFailed\",\n error instanceof Error ? error.message : String(error),\n error,\n );\n if (mountedRef.current) {\n setLastError(be);\n }\n throw be;\n } finally {\n inFlightRef.current -= 1;\n if (inFlightRef.current === 0 && mountedRef.current) {\n setIsPending(false);\n }\n }\n },\n [client],\n );\n\n const state = useMemo(() => ({ isPending, error: lastError }), [isPending, lastError]);\n\n return [mutate, state] as const;\n};\n","/**\n * Deterministic JSON serialization with sorted object keys. `useQuery`\n * feeds its `[chainShape, deps]` tuple into this to compute the\n * read-signature that keys the subscription-pool's result cache.\n * Sorting keys means `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` stringify\n * identically, which `JSON.stringify` alone does not guarantee (it\n * preserves insertion order).\n *\n * Inputs are caller-declared `deps` plus the deterministic chain\n * shape — no `undefined`, no functions, no circular references — so\n * a recursive walk terminates and the output is well-defined. Arrays\n * are serialized positionally.\n *\n * @internal\n */\nexport const stableKey = (value: unknown): string => {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableKey).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>).toSorted(([a], [b]) =>\n compareStrings(a, b),\n );\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(\",\")}}`;\n};\n\n// Lex compare for object-key ordering. `localeCompare` is locale-aware\n// and would re-order BMP code points; we need byte-stable output so the\n// `useEffect` deps key is identical across machines.\nconst compareStrings = (a: string, b: string): number => {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n};\n","import type { SinceResponse } from \"./contract.ts\";\nimport { type RequestContext, request } from \"./request.ts\";\n\n/**\n * One round-trip of `GET /v1/since?collection=…&cursor=…`. The single\n * place that talks to `/v1/since` in this package — the React\n * `subscription-pool` is its only first-party consumer.\n *\n * Long-poll semantics live server-side: the call resolves once the\n * server's budget elapses (`{ events: [], next_cursor: <same> }`) or\n * one or more events arrive. Callers are expected to loop over this\n * helper, threading `next_cursor` through.\n *\n * `cursor === \"\"` means \"start at `log_seq_start`\" (the wire\n * protocol); pass the previously returned `next_cursor` to resume.\n *\n * `signal` cancels the underlying fetch via the standard\n * `AbortController` plumbing; the rejection propagates as\n * `AbortError`.\n */\nexport const pollSinceOnce = async (\n ctx: RequestContext,\n name: string,\n cursor: string,\n signal: AbortSignal | undefined,\n): Promise<SinceResponse> => {\n const params = new URLSearchParams();\n params.set(\"collection\", name);\n params.set(\"cursor\", cursor);\n return request<SinceResponse>(ctx, {\n method: \"GET\",\n path: `/v1/since?${params.toString()}`,\n signal,\n });\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { getClientContext } from \"../internal/context.ts\";\nimport { pollSinceOnce } from \"../poll-since-once.ts\";\n\n/**\n * Discriminated snapshot a hook hands back from `getSnapshot`. The\n * `useQuery` types narrow this further (data: T vs data: undefined);\n * the pool stores it generically so the cache can be a single\n * `Map<signature, CachedSnapshot>`.\n */\nexport interface CachedSnapshot {\n readonly status: \"loading\" | \"refreshing\" | \"ok\" | \"error\";\n readonly data: unknown;\n readonly error: Error | undefined;\n}\n\nexport const LOADING_SNAPSHOT: CachedSnapshot = Object.freeze({\n status: \"loading\",\n data: undefined,\n error: undefined,\n});\n\nconst toError = (raw: unknown): Error => {\n if (raw instanceof BaerlyError || raw instanceof Error) {\n return raw;\n }\n return new BaerlyError(\"Internal\", String(raw));\n};\n\ninterface CacheEntry {\n snapshot: CachedSnapshot;\n /** Tables this signature's chain references — used for invalidation. */\n readonly chainTables: ReadonlySet<string>;\n /** Aborts the in-flight read for this signature, if any. */\n inFlight: AbortController | undefined;\n}\n\ninterface TablePoll {\n refcount: number;\n controller: AbortController;\n cursor: string;\n}\n\ninterface SubscriptionPool {\n /** Register a subscriber. Returns an unsubscribe. */\n attach(\n signature: string,\n tables: ReadonlyArray<string>,\n chainTables: ReadonlySet<string>,\n fetcher: () => Promise<unknown>,\n notify: () => void,\n ): () => void;\n /** Read the cached snapshot for `signature` (or the canonical loading sentinel). */\n getSnapshot(signature: string): CachedSnapshot;\n}\n\nconst poolByClient = new WeakMap<BaerlyClient, SubscriptionPool>();\n\n/** Returns the (lazily-created) pool for `client`. */\nexport const poolFor = (client: BaerlyClient): SubscriptionPool => {\n let pool = poolByClient.get(client);\n if (pool === undefined) {\n pool = createPool(client);\n poolByClient.set(client, pool);\n }\n return pool;\n};\n\nconst createPool = (client: BaerlyClient): SubscriptionPool => {\n const cache = new Map<string, CacheEntry>();\n const subscribersBySignature = new Map<string, Set<() => void>>();\n const tablePolls = new Map<string, TablePoll>();\n\n const notifyAll = (signature: string): void => {\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n return;\n }\n for (const notify of subs) {\n notify();\n }\n };\n\n const dispatchFetch = (signature: string, fetcher: () => Promise<unknown>): void => {\n const entry = cache.get(signature);\n if (entry === undefined) {\n return;\n }\n if (entry.inFlight !== undefined) {\n entry.inFlight.abort();\n }\n const controller = new AbortController();\n entry.inFlight = controller;\n const prevSnapshot = entry.snapshot;\n const hadData = entry.snapshot.status === \"ok\" || entry.snapshot.status === \"refreshing\";\n entry.snapshot = hadData\n ? { status: \"refreshing\", data: entry.snapshot.data, error: undefined }\n : LOADING_SNAPSHOT;\n if (entry.snapshot !== prevSnapshot) {\n notifyAll(signature);\n }\n void (async () => {\n try {\n const data = await fetcher();\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n live.snapshot = { status: \"ok\", data, error: undefined };\n live.inFlight = undefined;\n notifyAll(signature);\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n const wrapped = toError(error);\n live.snapshot = {\n status: \"error\",\n data: live.snapshot.data,\n error: wrapped,\n };\n live.inFlight = undefined;\n notifyAll(signature);\n }\n })();\n };\n\n const invalidateForTable = (table: string): void => {\n for (const [signature, entry] of cache) {\n if (!entry.chainTables.has(table)) {\n continue;\n }\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined || subs.size === 0) {\n continue;\n }\n // Any subscriber's fetcher is fine — they all produce the\n // same call against the real client for this signature\n // (signature is hashed on chain shape + deps).\n const fetcher = signatureFetchers.get(signature);\n if (fetcher !== undefined) {\n dispatchFetch(signature, fetcher);\n }\n }\n };\n\n /** Per-signature fetcher; last writer wins (all fetchers for a signature are equivalent). */\n const signatureFetchers = new Map<string, () => Promise<unknown>>();\n\n const startTablePoll = (table: string): void => {\n if (tablePolls.has(table)) {\n return;\n }\n const controller = new AbortController();\n const poll: TablePoll = { refcount: 1, controller, cursor: \"\" };\n tablePolls.set(table, poll);\n const ctx = getClientContext(client);\n void (async () => {\n while (!controller.signal.aborted) {\n try {\n const res = await pollSinceOnce(ctx, table, poll.cursor, controller.signal);\n if (controller.signal.aborted) {\n return;\n }\n if (res.events.length > 0 || res.next_cursor !== poll.cursor) {\n poll.cursor = res.next_cursor;\n if (res.events.length > 0) {\n invalidateForTable(table);\n }\n }\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") {\n return;\n }\n // 1-second backoff on error to avoid hot-spinning on a\n // persistent failure; downstream subscribers' next fetch\n // sees the same error if it doesn't clear.\n await new Promise((r) => setTimeout(r, 1000));\n }\n }\n })();\n };\n\n const stopTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n return;\n }\n poll.refcount--;\n if (poll.refcount === 0) {\n poll.controller.abort();\n tablePolls.delete(table);\n }\n };\n\n const incrementTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n startTablePoll(table);\n } else {\n poll.refcount++;\n }\n };\n\n return {\n getSnapshot(signature: string): CachedSnapshot {\n return cache.get(signature)?.snapshot ?? LOADING_SNAPSHOT;\n },\n attach(signature, tables, chainTables, fetcher, notify) {\n let entry = cache.get(signature);\n const isFirstSubscriber = entry === undefined;\n if (entry === undefined) {\n entry = {\n snapshot: LOADING_SNAPSHOT,\n chainTables,\n inFlight: undefined,\n };\n cache.set(signature, entry);\n }\n signatureFetchers.set(signature, fetcher);\n let subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n subs = new Set();\n subscribersBySignature.set(signature, subs);\n }\n subs.add(notify);\n for (const table of tables) {\n incrementTablePoll(table);\n }\n if (isFirstSubscriber) {\n dispatchFetch(signature, fetcher);\n } else {\n // Cache already has data (or in-flight). The new subscriber\n // gets the existing snapshot via getSnapshot; no extra fetch.\n }\n return () => {\n const liveSubs = subscribersBySignature.get(signature);\n if (liveSubs !== undefined) {\n liveSubs.delete(notify);\n if (liveSubs.size === 0) {\n subscribersBySignature.delete(signature);\n const liveEntry = cache.get(signature);\n if (liveEntry !== undefined) {\n liveEntry.inFlight?.abort();\n cache.delete(signature);\n }\n signatureFetchers.delete(signature);\n }\n }\n for (const table of tables) {\n stopTablePoll(table);\n }\n };\n },\n };\n};\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useReducer, useRef, useSyncExternalStore } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\nimport { stableKey } from \"./stable-key.ts\";\nimport { LOADING_SNAPSHOT, poolFor } from \"./subscription-pool.ts\";\n\nconst SKIP: unique symbol = Symbol(\"baerly.useQuery.skip\");\n\n/**\n * Result handed back by {@link useQuery}. Discriminate on `status` —\n * narrowing into `\"ok\"` / `\"refreshing\"` gives `data: T`; narrowing\n * into `\"loading\"` / `\"skipped\"` gives `data: undefined`; narrowing\n * into `\"error\"` gives `data: T | undefined` (the prior successful\n * read survives across errors so the UI can keep rendering).\n */\nexport type UseQueryResult<T> =\n | { readonly status: \"loading\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"refreshing\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"ok\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"skipped\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"error\"; readonly data: T | undefined; readonly error: Error };\n\nconst SKIPPED_SNAPSHOT: UseQueryResult<never> = Object.freeze({\n status: \"skipped\",\n data: undefined,\n error: undefined,\n});\n\ninterface RecorderState {\n readonly collectionsRead: Set<string>;\n readonly chain: Array<string>;\n}\n\nconst WRITE_METHODS = new Set([\"insert\", \"update\", \"replace\", \"delete\"]);\n\nconst awaitedError = (prop: string | symbol): BaerlyError =>\n new BaerlyError(\n \"UseQueryAwaitedRecorder\",\n `useQuery callbacks must not dereference the result of an awaited recorder terminal — property access (${String(prop)}) on the awaited value throws. The recorder is for the synchronous prefix of the callback only. For compound reads, use Promise.all (parallel) or compose two useQuery calls with useQuery.skip (dependent). See the lint rule baerly/no-await-in-use-query for the edit-time check.`,\n );\n\n/**\n * Sentinel handed back when a recorder terminal is awaited. Every\n * own-property access throws `BaerlyError(\"UseQueryAwaitedRecorder\")`;\n * `Symbol.*` accesses (which the JS engine uses internally —\n * Symbol.toPrimitive, Symbol.iterator, etc.) return undefined so the\n * sentinel can flow through engine-side coercions without spurious\n * throws. The single shared instance avoids per-render allocation.\n */\nconst SENTINEL_SAFE_PROPS = new Set<string | symbol>([\n // The JS engine probes `.then` to test whether a value is a\n // thenable while resolving Promises. Returning undefined makes the\n // sentinel look like a non-thenable so awaiting it yields the\n // sentinel itself (not a chained Promise) — and our error fires on\n // the next, user-visible property access.\n \"then\",\n // `.catch` and `.finally` are sometimes probed similarly.\n \"catch\",\n \"finally\",\n // `Symbol.toStringTag` etc. are probed by `String()` and JSON\n // serialization. The generic `typeof prop === \"symbol\"` branch\n // already covers these; keep them here for explicit reference.\n]);\n\nconst AWAITED_SENTINEL: unknown = new Proxy(\n Object.create(null) as Record<string | symbol, unknown>,\n {\n get(_target, prop) {\n if (typeof prop === \"symbol\" || SENTINEL_SAFE_PROPS.has(prop)) {\n return undefined;\n }\n throw awaitedError(prop);\n },\n },\n);\n\nconst TERMINAL_RESULT: Promise<unknown> = Promise.resolve(AWAITED_SENTINEL);\n\nconst makeTerminal = (): Promise<unknown> => TERMINAL_RESULT;\n\nconst makeQuery = (state: RecorderState): unknown => {\n const query: Record<string, unknown> = {};\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n query[modifier] = (): unknown => {\n state.chain.push(modifier);\n return query;\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\"]) {\n query[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n return query;\n};\n\nconst makeCollection = (name: string, state: RecorderState): unknown => {\n state.collectionsRead.add(name);\n state.chain.push(`collection:${name}`);\n const collection: Record<string, unknown> = {\n name,\n };\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n collection[modifier] = (): unknown => {\n state.chain.push(modifier);\n return makeQuery(state);\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\", \"get\"]) {\n collection[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n for (const write of WRITE_METHODS) {\n collection[write] = (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n `useQuery callbacks must not write to the database. .${write}() was called on collection \"${name}\". Use useMutation() instead.`,\n );\n };\n }\n return collection;\n};\n\nconst createRecorder = (): { client: unknown; state: RecorderState } => {\n const state: RecorderState = {\n collectionsRead: new Set(),\n chain: [],\n };\n const recorder = {\n collection: (name: string): unknown => makeCollection(name, state),\n healthz: (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n \"useQuery callbacks must not call client.healthz(); use useMutation() or the bare client.\",\n );\n },\n };\n return { client: recorder, state };\n};\n\ninterface DiscoveryOk {\n readonly kind: \"ok\";\n readonly collections: ReadonlyArray<string>;\n readonly chainShape: string;\n readonly callbackResult: unknown;\n}\ninterface DiscoverySkip {\n readonly kind: \"skip\";\n}\ninterface DiscoveryError {\n readonly kind: \"error\";\n readonly error: Error;\n}\ntype DiscoveryResult = DiscoveryOk | DiscoverySkip | DiscoveryError;\n\nconst discover = (\n callback: (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n): DiscoveryResult => {\n const { client: recorder, state } = createRecorder();\n let callbackResult: unknown;\n try {\n callbackResult = callback(recorder as BaerlyClient);\n } catch (error) {\n return {\n kind: \"error\",\n error: error instanceof Error ? error : new BaerlyError(\"Internal\", String(error)),\n };\n }\n if (callbackResult === SKIP) {\n return { kind: \"skip\" };\n }\n return {\n kind: \"ok\",\n collections: [...state.collectionsRead].toSorted(),\n chainShape: stableKey(state.chain),\n callbackResult,\n };\n};\n\n/**\n * Reactive read against a `baerly` server. The callback receives a\n * type-compatible `BaerlyClient` proxy that records which collections it\n * touches; the hook subscribes to those collections and re-runs the\n * callback against the real client when any of them mutate.\n *\n * Re-runs also fire whenever the `deps` array changes between\n * renders (shallow `stableKey` compare). Closure variables read\n * inside the callback must be listed in `deps` — the companion\n * `baerly/exhaustive-deps-use-query` lint rule flags missing\n * entries.\n *\n * Returning {@link useQuery.skip} from the callback yields\n * `{ status: \"skipped\" }` and registers no subscription — use it\n * for deferred / conditional reads.\n *\n * @example\n * ```tsx\n * // Single read\n * const note = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * if (note.status === \"loading\") return <Spinner/>;\n * if (note.status === \"error\") return <Err e={note.error}/>;\n * return <pre>{note.data?.body}</pre>; // typed Note | undefined\n *\n * // Deferred read\n * const list = useQuery(\n * (c) => userId ? c.collection(\"notes\").where({ authorId: userId }).all() : useQuery.skip,\n * [userId],\n * );\n * if (list.status === \"skipped\") return null;\n *\n * // Dependent read (parent → child)\n * const parent = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * const replies = useQuery(\n * (c) => parent.status === \"ok\"\n * ? c.collection(\"comments\").where({ noteId: parent.data._id }).all()\n * : useQuery.skip,\n * [parent.status === \"ok\" ? parent.data._id : undefined],\n * );\n * ```\n */\nconst useQueryImpl = <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n): UseQueryResult<T> => {\n const client = useBaerlyClient<TConfig>();\n const pool = poolFor(client as unknown as BaerlyClient);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n // Force-update for async-error capture (see below). Used to push\n // a microtask-deferred recorder-await rejection back into a sync\n // render.\n const [, forceUpdate] = useReducer((c: number) => c + 1, 0);\n const asyncErrorRef = useRef<BaerlyError | undefined>(undefined);\n\n // Recorder pass. Cheap — no I/O.\n const discovery = discover(\n callbackRef.current as (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n );\n\n // The signature inputs that need to be stable across the same\n // logical query: chain shape + caller-declared deps.\n const depsKey = stableKey([deps ?? []]);\n const signatureBase =\n discovery.kind === \"ok\"\n ? stableKey([discovery.chainShape, deps ?? []])\n : `__non_ok__${discovery.kind}__${depsKey}`;\n\n // Reset the captured async error if the signature changed (the\n // user is on a different query now — give them a fresh chance).\n const lastSignatureRef = useRef<string>(\"\");\n if (lastSignatureRef.current !== signatureBase) {\n lastSignatureRef.current = signatureBase;\n asyncErrorRef.current = undefined;\n }\n\n // Attach an async-error handler to the callback's returned value\n // so that any microtask-deferred rejection from sentinel access\n // (sequential-await pattern) flows back into render via\n // forceUpdate. Wrap in `Promise.resolve(...)` so a bare recorder\n // terminal (Promise<sentinel>) is observed too — the resolved\n // value carries no `.catch`. Always attach (even if asyncErrorRef\n // is already set) so the per-render discovery invocation's\n // rejection is observed and doesn't surface as an unhandled\n // rejection from vitest or the host runtime.\n if (discovery.kind === \"ok\") {\n const result = discovery.callbackResult;\n if (\n result !== null &&\n typeof result === \"object\" &&\n typeof (result as { then?: unknown }).then === \"function\"\n ) {\n Promise.resolve(result as PromiseLike<unknown>).then(\n () => {\n /* discovery success — value discarded */\n },\n (error: unknown) => {\n if (\n error instanceof BaerlyError &&\n error.code === \"UseQueryAwaitedRecorder\" &&\n asyncErrorRef.current === undefined\n ) {\n asyncErrorRef.current = error;\n forceUpdate();\n }\n // Any other rejection is silently swallowed here — the\n // pool's real-client fetch path is the canonical surface\n // for non-recorder errors.\n },\n );\n }\n }\n\n // Subscription channel — stable per (client, collectionsRead.join(\" \")).\n // Pool's getSnapshot returns the current cached entry for this\n // signature; React polls it on subscribe + on every notify.\n const collectionsJoin =\n discovery.kind === \"ok\" ? discovery.collections.join(\"\\x00\") : \"__non_ok__\";\n\n const fetcherRef = useRef<() => Promise<unknown>>(() => Promise.resolve(undefined));\n fetcherRef.current = (): Promise<unknown> => {\n const out = callbackRef.current(client) as Promise<unknown> | typeof SKIP;\n if (out === SKIP) {\n return Promise.resolve(undefined);\n }\n return out as Promise<unknown>;\n };\n\n const chainCollectionsRef = useRef<ReadonlySet<string>>(new Set());\n const discoveryKindRef = useRef<DiscoveryResult[\"kind\"]>(\"ok\");\n const discoveryErrorRef = useRef<Error | undefined>(undefined);\n discoveryKindRef.current = discovery.kind;\n if (discovery.kind === \"ok\") {\n chainCollectionsRef.current = new Set(discovery.collections);\n discoveryErrorRef.current = undefined;\n } else if (discovery.kind === \"error\") {\n discoveryErrorRef.current = discovery.error;\n } else {\n discoveryErrorRef.current = undefined;\n }\n\n const subscribe = useCallback(\n (notify: () => void): (() => void) => {\n if (discovery.kind !== \"ok\") {\n return () => {};\n }\n return pool.attach(\n signatureBase,\n discovery.collections,\n chainCollectionsRef.current,\n () => fetcherRef.current(),\n notify,\n );\n },\n // The signature/collections determine the subscription; React\n // re-subscribes when either changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [pool, signatureBase, collectionsJoin],\n );\n\n // Stable per-error snapshot cache so repeated getSnapshot polls\n // within a single render return the same reference. React's\n // useSyncExternalStore detects identity changes; constructing a\n // fresh error literal each call drives an infinite re-render.\n const errorSnapshotRef = useRef<\n | {\n error: Error;\n snapshot: UseQueryResult<unknown>;\n }\n | undefined\n >(undefined);\n const snapshotForError = (err: Error): UseQueryResult<T> => {\n if (errorSnapshotRef.current?.error === err) {\n return errorSnapshotRef.current.snapshot as UseQueryResult<T>;\n }\n const snapshot = {\n status: \"error\" as const,\n data: undefined,\n error: err,\n } satisfies UseQueryResult<unknown>;\n errorSnapshotRef.current = { error: err, snapshot };\n return snapshot as UseQueryResult<T>;\n };\n\n const getSnapshot = useCallback((): UseQueryResult<T> => {\n if (asyncErrorRef.current) {\n return snapshotForError(asyncErrorRef.current);\n }\n if (discoveryKindRef.current === \"skip\") {\n return SKIPPED_SNAPSHOT as UseQueryResult<T>;\n }\n if (discoveryKindRef.current === \"error\") {\n return snapshotForError(\n discoveryErrorRef.current ?? new BaerlyError(\"Internal\", \"unknown discovery error\"),\n );\n }\n return pool.getSnapshot(signatureBase) as UseQueryResult<T>;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pool, signatureBase]);\n\n // discoveryKindRef + discoveryErrorRef carry the latest discovery\n // state into getSnapshot without making it a useCallback dep\n // (avoids re-creating the snapshot callback every render).\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n};\n\n/**\n * Reactive read hook. See {@link useQueryImpl} JSDoc for usage.\n * The `.skip` property is the sentinel that short-circuits the hook\n * into `status: \"skipped\"`.\n */\nexport const useQuery: {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n} = Object.assign(useQueryImpl, { skip: SKIP }) as {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n};\n\n// Quiet `LOADING_SNAPSHOT` as a value-import — referenced by\n// generated type for the `loading` branch only; bundled alongside\n// `subscription-pool.ts`.\nvoid LOADING_SNAPSHOT;\n","import type { BaerlyConfig, UnboundConfig } from \"@baerly/protocol\";\nimport type { ReactNode } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { BaerlyProvider, useBaerlyClient } from \"./provider.ts\";\nimport { useMutation, type UseMutationTuple } from \"./use-mutation.ts\";\nimport { useQuery, type UseQueryResult } from \"./use-query.ts\";\n\n/**\n * Props for the config-bound `BaerlyProvider` returned by\n * {@link createBaerlyReact}. `client` is typed `BaerlyClient<TConfig>`\n * to document the intended binding; the hooks carry `TConfig`\n * themselves, so row inference holds regardless of the client value's\n * own inferred type.\n */\nexport interface BaerlyProviderProps<TConfig extends BaerlyConfig> {\n readonly client: BaerlyClient<TConfig>;\n readonly children?: ReactNode;\n}\n\n/**\n * The config-bound React surface returned by {@link createBaerlyReact}.\n * Every hook is pinned to `TConfig`, so `c.collection(\"notes\")` inside\n * a `useQuery` / `useMutation` callback infers the real row type — no\n * `as Promise<Note[]>` cast.\n */\nexport interface BaerlyReact<TConfig extends BaerlyConfig> {\n /** Wrap your app once; provides the bound client to every hook below it. */\n readonly BaerlyProvider: (props: BaerlyProviderProps<TConfig>) => React.JSX.Element;\n /**\n * Reactive read. The callback receives `BaerlyClient<TConfig>`, so\n * the chain is fully typed. `useQuery.skip` short-circuits to\n * `{ status: \"skipped\" }`.\n */\n readonly useQuery: {\n <T>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | symbol,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n /**\n * Sentinel — return it from the callback to defer the read\n * (`{ status: \"skipped\" }`, no subscription). Typed `symbol` (not\n * the impl's `unique symbol`) so the bound surface stays nameable\n * across the package boundary; identity-compared at runtime.\n */\n readonly skip: symbol;\n };\n /** Imperative mutation hook → `[mutate, { isPending, error }]`. */\n readonly useMutation: () => UseMutationTuple<TConfig>;\n /** Escape hatch — the raw bound {@link BaerlyClient} for imperative use. */\n readonly useBaerlyClient: () => BaerlyClient<TConfig>;\n}\n\n/**\n * Build the typed React surface for one `baerly.config.ts`. Call it\n * once at module scope and export the result; every hook is bound to\n * the config so collection names autocomplete and row types infer\n * end-to-end. This is the only React entry point — there are no\n * loose, unbound hooks to import by mistake.\n *\n * @example\n * ```ts\n * // src/web/client.ts\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"../../baerly.config.ts\";\n *\n * export const client = createBaerlyClient({ baseUrl: \"\", config });\n * export const { BaerlyProvider, useQuery, useMutation } =\n * createBaerlyReact<typeof config>();\n * ```\n *\n * ```tsx\n * // any component\n * import { useQuery } from \"./client.ts\";\n * const notes = useQuery((c) => c.collection(\"notes\").all(), []);\n * // ^? UseQueryResult<Note[]> — no cast\n * ```\n *\n * Omit the type parameter (`createBaerlyReact()`) for an unbound app;\n * collection names widen to `string` and rows to `DocumentData`,\n * matching the in-process `Db.collection` fallback.\n */\nexport const createBaerlyReact = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyReact<TConfig> => ({\n // Identical runtime implementations — the generic is erased, so the\n // factory only re-pins each hook's type to `TConfig`. The\n // recorder-proxy in `useQuery` is structurally typed as\n // `BaerlyClient`, so binding a narrower config is a no-op at runtime.\n BaerlyProvider: BaerlyProvider as BaerlyReact<TConfig>[\"BaerlyProvider\"],\n useQuery: useQuery as unknown as BaerlyReact<TConfig>[\"useQuery\"],\n useMutation: useMutation as BaerlyReact<TConfig>[\"useMutation\"],\n useBaerlyClient: useBaerlyClient as BaerlyReact<TConfig>[\"useBaerlyClient\"],\n});\n"],"mappings":";;;;AAIA,MAAM,gBAAgB,cAAwC,KAAA,CAAS;;;;;;;;;;;;;;;;;;;;;;AA4BvE,MAAa,kBAAkB,EAAE,QAAQ,eACvC,cAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;;;;;;;;;;;;;;;;;;;;AAqBnE,MAAa,wBAEiB;CAC5B,MAAM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AAO;EAET,IAAI,iBAAiB,YAAY,SAC/B,OAAO,iBACL,kBAAkB,WAAW,IAAI,YAAY,YAAY,yBAAyB,CACpF;EAEF,OAAO,KAAK,YAAY,aAAa;CAEvC,GAAG,CAAC,MAAM,aAAa,CAAC;CAKxB,OAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;;;;;;AAOA,MAAa,WAMT,OAAO,OAAO,cAAc,EAAE,MAAM,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChU9C,MAAa,2BAEiB;CAKZ;CACN;CACG;CACI;AACnB"}
|
|
1
|
+
{"version":3,"file":"client-react.js","names":[],"sources":["../packages/client/src/react/provider.ts","../packages/client/src/react/use-mutation.ts","../packages/client/src/react/stable-key.ts","../packages/client/src/poll-since-once.ts","../packages/client/src/react/subscription-pool.ts","../packages/client/src/react/use-query.ts","../packages/client/src/react/create-react.ts"],"sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { BaerlyConfig, UnboundConfig } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\n\nconst ClientContext = createContext<BaerlyClient | undefined>(undefined);\n\nexport interface BaerlyProviderProps {\n readonly client: BaerlyClient;\n readonly children?: ReactNode;\n}\n\n/**\n * Provides a {@link BaerlyClient} to every Baerly React hook below it.\n * Wrap your app once near the root; the hooks read the client from\n * this context and have no `client` argument.\n *\n * Obtained from {@link createBaerlyReact}, not imported directly:\n *\n * @example\n * ```tsx\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"./baerly.config.ts\";\n *\n * const client = createBaerlyClient({ baseUrl: \"/api\", config });\n * const { BaerlyProvider } = createBaerlyReact<typeof config>();\n *\n * <BaerlyProvider client={client}>\n * <App />\n * </BaerlyProvider>\n * ```\n */\nexport const BaerlyProvider = ({ client, children }: BaerlyProviderProps): React.JSX.Element =>\n createElement(ClientContext.Provider, { value: client }, children);\n\n/**\n * Returns the {@link BaerlyClient} provided by the nearest\n * {@link BaerlyProvider}. Throws a clear error if called outside a\n * provider — every hook in this package uses it, so a missing\n * provider surfaces here first.\n *\n * Use this directly when you need imperative access — e.g. inside an\n * event handler that performs a one-shot read or a custom long-poll.\n * For declarative reads and mutations, prefer the typed hooks.\n *\n * @example\n * ```tsx\n * const client = useBaerlyClient<MyConfig>();\n * const onExport = async () => {\n * const rows = await client.collection(\"tickets\").all();\n * download(rows);\n * };\n * ```\n */\nexport const useBaerlyClient = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyClient<TConfig> => {\n const client = useContext(ClientContext);\n if (client === undefined) {\n throw new Error(\n \"useBaerlyClient (and every Baerly React hook) must be used inside <BaerlyProvider>. \" +\n \"Wrap your app: <BaerlyProvider client={client}>…</BaerlyProvider>.\",\n );\n }\n return client as BaerlyClient<TConfig>;\n};\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\n\n/**\n * Tuple returned by {@link useMutation}. Positionally mirrors React\n * 19's `useActionState`: `[mutate, state]`. `mutate` is stable across\n * renders; `state` is a fresh object only when `isPending` or\n * `error` actually flips.\n */\nexport type UseMutationTuple<TConfig extends BaerlyConfig = UnboundConfig> = readonly [\n mutate: <T>(callback: (client: BaerlyClient<TConfig>) => Promise<T>) => Promise<T>,\n state: { readonly isPending: boolean; readonly error: BaerlyError | undefined },\n];\n\n/**\n * Imperative mutation hook. `mutate(callback)` runs the callback\n * against the real `BaerlyClient` and resolves to whatever the\n * callback returns; `state` carries `isPending` (refcounted across\n * concurrent submits — `true` until every in-flight call settles)\n * and `error` (last-wins; the most recent rejection until the next\n * successful call clears it).\n *\n * Errors are normalised to {@link BaerlyError}: a non-`BaerlyError`\n * throwable from the callback is wrapped under\n * `code: \"MutationFailed\"` with the original on `.cause`.\n *\n * @example\n * ```tsx\n * const [mutate, { isPending, error }] = useMutation();\n * <button\n * disabled={isPending}\n * onClick={() => mutate((client) => client.collection(\"notes\").insert({ body }))}\n * >\n * {isPending ? \"Saving…\" : \"Save\"}\n * </button>\n * {error ? <p>{error.message}</p> : null}\n * ```\n */\nexport const useMutation = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): UseMutationTuple<TConfig> => {\n const client = useBaerlyClient<TConfig>();\n const inFlightRef = useRef<number>(0);\n const mountedRef = useRef<boolean>(true);\n const [isPending, setIsPending] = useState<boolean>(false);\n const [lastError, setLastError] = useState<BaerlyError | undefined>(undefined);\n\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n [],\n );\n\n const mutate = useCallback(\n async <T>(callback: (c: BaerlyClient<TConfig>) => Promise<T>): Promise<T> => {\n const wasIdle = inFlightRef.current === 0;\n inFlightRef.current += 1;\n if (wasIdle && mountedRef.current) {\n setIsPending(true);\n setLastError(undefined);\n }\n try {\n const result = await callback(client);\n return result;\n } catch (error) {\n const be =\n error instanceof BaerlyError\n ? error\n : new BaerlyError(\n \"MutationFailed\",\n error instanceof Error ? error.message : String(error),\n error,\n );\n if (mountedRef.current) {\n setLastError(be);\n }\n throw be;\n } finally {\n inFlightRef.current -= 1;\n if (inFlightRef.current === 0 && mountedRef.current) {\n setIsPending(false);\n }\n }\n },\n [client],\n );\n\n const state = useMemo(() => ({ isPending, error: lastError }), [isPending, lastError]);\n\n return [mutate, state] as const;\n};\n","/**\n * Deterministic JSON serialization with sorted object keys. `useQuery`\n * feeds its `[chainShape, deps]` tuple into this to compute the\n * read-signature that keys the subscription-pool's result cache.\n * Sorting keys means `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` stringify\n * identically, which `JSON.stringify` alone does not guarantee (it\n * preserves insertion order).\n *\n * Inputs are caller-declared `deps` plus the deterministic chain\n * shape — no `undefined`, no functions, no circular references — so\n * a recursive walk terminates and the output is well-defined. Arrays\n * are serialized positionally.\n *\n * @internal\n */\nexport const stableKey = (value: unknown): string => {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableKey).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>).toSorted(([a], [b]) =>\n compareStrings(a, b),\n );\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(\",\")}}`;\n};\n\n// Lex compare for object-key ordering. `localeCompare` is locale-aware\n// and would re-order BMP code points; we need byte-stable output so the\n// `useEffect` deps key is identical across machines.\nconst compareStrings = (a: string, b: string): number => {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n};\n","import type { SinceResponse } from \"./contract.ts\";\nimport { type RequestContext, request } from \"./request.ts\";\n\n/**\n * One round-trip of `GET /v1/since?collection=…&cursor=…`. The single\n * place that talks to `/v1/since` in this package — the React\n * `subscription-pool` is its only first-party consumer.\n *\n * Long-poll semantics live server-side: the call resolves once the\n * server's budget elapses (`{ events: [], next_cursor: <same> }`) or\n * one or more events arrive. Callers are expected to loop over this\n * helper, threading `next_cursor` through.\n *\n * `cursor === \"\"` means \"start at `log_seq_start`\" (the wire\n * protocol); pass the previously returned `next_cursor` to resume.\n *\n * `signal` cancels the underlying fetch via the standard\n * `AbortController` plumbing; the rejection propagates as\n * `AbortError`.\n */\nexport const pollSinceOnce = async (\n ctx: RequestContext,\n name: string,\n cursor: string,\n signal: AbortSignal | undefined,\n): Promise<SinceResponse> => {\n const params = new URLSearchParams();\n params.set(\"collection\", name);\n params.set(\"cursor\", cursor);\n return request<SinceResponse>(ctx, {\n method: \"GET\",\n path: `/v1/since?${params.toString()}`,\n signal,\n });\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { getClientContext } from \"../internal/context.ts\";\nimport { pollSinceOnce } from \"../poll-since-once.ts\";\n\n/**\n * Discriminated snapshot a hook hands back from `getSnapshot`. The\n * `useQuery` types narrow this further (data: T vs data: undefined);\n * the pool stores it generically so the cache can be a single\n * `Map<signature, CachedSnapshot>`.\n */\nexport interface CachedSnapshot {\n readonly status: \"loading\" | \"refreshing\" | \"ok\" | \"error\";\n readonly data: unknown;\n readonly error: Error | undefined;\n}\n\nexport const LOADING_SNAPSHOT: CachedSnapshot = Object.freeze({\n status: \"loading\",\n data: undefined,\n error: undefined,\n});\n\nconst toError = (raw: unknown): Error => {\n if (raw instanceof BaerlyError || raw instanceof Error) {\n return raw;\n }\n return new BaerlyError(\"Internal\", String(raw));\n};\n\ninterface CacheEntry {\n snapshot: CachedSnapshot;\n /** Tables this signature's chain references — used for invalidation. */\n readonly chainTables: ReadonlySet<string>;\n /** Aborts the in-flight read for this signature, if any. */\n inFlight: AbortController | undefined;\n}\n\ninterface TablePoll {\n refcount: number;\n controller: AbortController;\n cursor: string;\n}\n\ninterface SubscriptionPool {\n /** Register a subscriber. Returns an unsubscribe. */\n attach(\n signature: string,\n tables: ReadonlyArray<string>,\n chainTables: ReadonlySet<string>,\n fetcher: () => Promise<unknown>,\n notify: () => void,\n ): () => void;\n /** Read the cached snapshot for `signature` (or the canonical loading sentinel). */\n getSnapshot(signature: string): CachedSnapshot;\n}\n\nconst poolByClient = new WeakMap<BaerlyClient, SubscriptionPool>();\n\n/** Returns the (lazily-created) pool for `client`. */\nexport const poolFor = (client: BaerlyClient): SubscriptionPool => {\n let pool = poolByClient.get(client);\n if (pool === undefined) {\n pool = createPool(client);\n poolByClient.set(client, pool);\n }\n return pool;\n};\n\nconst createPool = (client: BaerlyClient): SubscriptionPool => {\n const cache = new Map<string, CacheEntry>();\n const subscribersBySignature = new Map<string, Set<() => void>>();\n const tablePolls = new Map<string, TablePoll>();\n\n const notifyAll = (signature: string): void => {\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n return;\n }\n for (const notify of subs) {\n notify();\n }\n };\n\n const dispatchFetch = (signature: string, fetcher: () => Promise<unknown>): void => {\n const entry = cache.get(signature);\n if (entry === undefined) {\n return;\n }\n if (entry.inFlight !== undefined) {\n entry.inFlight.abort();\n }\n const controller = new AbortController();\n entry.inFlight = controller;\n const prevSnapshot = entry.snapshot;\n const hadData = entry.snapshot.status === \"ok\" || entry.snapshot.status === \"refreshing\";\n entry.snapshot = hadData\n ? { status: \"refreshing\", data: entry.snapshot.data, error: undefined }\n : LOADING_SNAPSHOT;\n if (entry.snapshot !== prevSnapshot) {\n notifyAll(signature);\n }\n void (async () => {\n try {\n const data = await fetcher();\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n live.snapshot = { status: \"ok\", data, error: undefined };\n live.inFlight = undefined;\n notifyAll(signature);\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n const wrapped = toError(error);\n live.snapshot = {\n status: \"error\",\n data: live.snapshot.data,\n error: wrapped,\n };\n live.inFlight = undefined;\n notifyAll(signature);\n }\n })();\n };\n\n const invalidateForTable = (table: string): void => {\n for (const [signature, entry] of cache) {\n if (!entry.chainTables.has(table)) {\n continue;\n }\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined || subs.size === 0) {\n continue;\n }\n // Any subscriber's fetcher is fine — they all produce the\n // same call against the real client for this signature\n // (signature is hashed on chain shape + deps).\n const fetcher = signatureFetchers.get(signature);\n if (fetcher !== undefined) {\n dispatchFetch(signature, fetcher);\n }\n }\n };\n\n /** Per-signature fetcher; last writer wins (all fetchers for a signature are equivalent). */\n const signatureFetchers = new Map<string, () => Promise<unknown>>();\n\n const startTablePoll = (table: string): void => {\n if (tablePolls.has(table)) {\n return;\n }\n const controller = new AbortController();\n const poll: TablePoll = { refcount: 1, controller, cursor: \"\" };\n tablePolls.set(table, poll);\n const ctx = getClientContext(client);\n void (async () => {\n while (!controller.signal.aborted) {\n try {\n const res = await pollSinceOnce(ctx, table, poll.cursor, controller.signal);\n if (controller.signal.aborted) {\n return;\n }\n if (res.events.length > 0 || res.next_cursor !== poll.cursor) {\n poll.cursor = res.next_cursor;\n if (res.events.length > 0) {\n invalidateForTable(table);\n }\n }\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") {\n return;\n }\n // 1-second backoff on error to avoid hot-spinning on a\n // persistent failure; downstream subscribers' next fetch\n // sees the same error if it doesn't clear.\n await new Promise((r) => setTimeout(r, 1000));\n }\n }\n })();\n };\n\n const stopTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n return;\n }\n poll.refcount--;\n if (poll.refcount === 0) {\n poll.controller.abort();\n tablePolls.delete(table);\n }\n };\n\n const incrementTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n startTablePoll(table);\n } else {\n poll.refcount++;\n }\n };\n\n return {\n getSnapshot(signature: string): CachedSnapshot {\n return cache.get(signature)?.snapshot ?? LOADING_SNAPSHOT;\n },\n attach(signature, tables, chainTables, fetcher, notify) {\n let entry = cache.get(signature);\n const isFirstSubscriber = entry === undefined;\n if (entry === undefined) {\n entry = {\n snapshot: LOADING_SNAPSHOT,\n chainTables,\n inFlight: undefined,\n };\n cache.set(signature, entry);\n }\n signatureFetchers.set(signature, fetcher);\n let subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n subs = new Set();\n subscribersBySignature.set(signature, subs);\n }\n subs.add(notify);\n for (const table of tables) {\n incrementTablePoll(table);\n }\n if (isFirstSubscriber) {\n dispatchFetch(signature, fetcher);\n } else {\n // Cache already has data (or in-flight). The new subscriber\n // gets the existing snapshot via getSnapshot; no extra fetch.\n }\n return () => {\n const liveSubs = subscribersBySignature.get(signature);\n if (liveSubs !== undefined) {\n liveSubs.delete(notify);\n if (liveSubs.size === 0) {\n subscribersBySignature.delete(signature);\n const liveEntry = cache.get(signature);\n if (liveEntry !== undefined) {\n liveEntry.inFlight?.abort();\n cache.delete(signature);\n }\n signatureFetchers.delete(signature);\n }\n }\n for (const table of tables) {\n stopTablePoll(table);\n }\n };\n },\n };\n};\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useReducer, useRef, useSyncExternalStore } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\nimport { stableKey } from \"./stable-key.ts\";\nimport { LOADING_SNAPSHOT, poolFor } from \"./subscription-pool.ts\";\n\nconst SKIP: unique symbol = Symbol(\"baerly.useQuery.skip\");\n\n/**\n * Result handed back by {@link useQuery}. Discriminate on `status` —\n * narrowing into `\"ok\"` / `\"refreshing\"` gives `data: T`; narrowing\n * into `\"loading\"` / `\"skipped\"` gives `data: undefined`; narrowing\n * into `\"error\"` gives `data: T | undefined` (the prior successful\n * read survives across errors so the UI can keep rendering).\n */\nexport type UseQueryResult<T> =\n | { readonly status: \"loading\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"refreshing\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"ok\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"skipped\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"error\"; readonly data: T | undefined; readonly error: Error };\n\nconst SKIPPED_SNAPSHOT: UseQueryResult<never> = Object.freeze({\n status: \"skipped\",\n data: undefined,\n error: undefined,\n});\n\ninterface RecorderState {\n readonly collectionsRead: Set<string>;\n readonly chain: Array<string>;\n}\n\nconst WRITE_METHODS = new Set([\"insert\", \"update\", \"replace\", \"delete\"]);\n\nconst awaitedError = (prop: string | symbol): BaerlyError =>\n new BaerlyError(\n \"UseQueryAwaitedRecorder\",\n `useQuery callbacks must not dereference the result of an awaited recorder terminal — property access (${String(prop)}) on the awaited value throws. The recorder is for the synchronous prefix of the callback only. For compound reads, use Promise.all (parallel) or compose two useQuery calls with useQuery.skip (dependent). See the lint rule baerly/no-await-in-use-query for the edit-time check.`,\n );\n\n/**\n * Sentinel handed back when a recorder terminal is awaited. Every\n * own-property access throws `BaerlyError(\"UseQueryAwaitedRecorder\")`;\n * `Symbol.*` accesses (which the JS engine uses internally —\n * Symbol.toPrimitive, Symbol.iterator, etc.) return undefined so the\n * sentinel can flow through engine-side coercions without spurious\n * throws. The single shared instance avoids per-render allocation.\n */\nconst SENTINEL_SAFE_PROPS = new Set<string | symbol>([\n // The JS engine probes `.then` to test whether a value is a\n // thenable while resolving Promises. Returning undefined makes the\n // sentinel look like a non-thenable so awaiting it yields the\n // sentinel itself (not a chained Promise) — and our error fires on\n // the next, user-visible property access.\n \"then\",\n // `.catch` and `.finally` are sometimes probed similarly.\n \"catch\",\n \"finally\",\n // `Symbol.toStringTag` etc. are probed by `String()` and JSON\n // serialization. The generic `typeof prop === \"symbol\"` branch\n // already covers these; keep them here for explicit reference.\n]);\n\nconst AWAITED_SENTINEL: unknown = new Proxy(\n Object.create(null) as Record<string | symbol, unknown>,\n {\n get(_target, prop) {\n if (typeof prop === \"symbol\" || SENTINEL_SAFE_PROPS.has(prop)) {\n return undefined;\n }\n throw awaitedError(prop);\n },\n },\n);\n\nconst TERMINAL_RESULT: Promise<unknown> = Promise.resolve(AWAITED_SENTINEL);\n\nconst makeTerminal = (): Promise<unknown> => TERMINAL_RESULT;\n\nconst makeQuery = (state: RecorderState): unknown => {\n const query: Record<string, unknown> = {};\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n query[modifier] = (): unknown => {\n state.chain.push(modifier);\n return query;\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\"]) {\n query[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n return query;\n};\n\nconst makeCollection = (name: string, state: RecorderState): unknown => {\n state.collectionsRead.add(name);\n state.chain.push(`collection:${name}`);\n const collection: Record<string, unknown> = {\n name,\n };\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n collection[modifier] = (): unknown => {\n state.chain.push(modifier);\n return makeQuery(state);\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\", \"get\"]) {\n collection[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n for (const write of WRITE_METHODS) {\n collection[write] = (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n `useQuery callbacks must not write to the database. .${write}() was called on collection \"${name}\". Use useMutation() instead.`,\n );\n };\n }\n return collection;\n};\n\nconst createRecorder = (): { client: unknown; state: RecorderState } => {\n const state: RecorderState = {\n collectionsRead: new Set(),\n chain: [],\n };\n const recorder = {\n collection: (name: string): unknown => makeCollection(name, state),\n healthz: (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n \"useQuery callbacks must not call client.healthz(); use useMutation() or the bare client.\",\n );\n },\n };\n return { client: recorder, state };\n};\n\ninterface DiscoveryOk {\n readonly kind: \"ok\";\n readonly collections: ReadonlyArray<string>;\n readonly chainShape: string;\n readonly callbackResult: unknown;\n}\ninterface DiscoverySkip {\n readonly kind: \"skip\";\n}\ninterface DiscoveryError {\n readonly kind: \"error\";\n readonly error: Error;\n}\ntype DiscoveryResult = DiscoveryOk | DiscoverySkip | DiscoveryError;\n\nconst discover = (\n callback: (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n): DiscoveryResult => {\n const { client: recorder, state } = createRecorder();\n let callbackResult: unknown;\n try {\n callbackResult = callback(recorder as BaerlyClient);\n } catch (error) {\n return {\n kind: \"error\",\n error: error instanceof Error ? error : new BaerlyError(\"Internal\", String(error)),\n };\n }\n if (callbackResult === SKIP) {\n return { kind: \"skip\" };\n }\n return {\n kind: \"ok\",\n collections: [...state.collectionsRead].toSorted(),\n chainShape: stableKey(state.chain),\n callbackResult,\n };\n};\n\n/**\n * Reactive read against a `baerly` server. The callback receives a\n * type-compatible `BaerlyClient` proxy that records which collections it\n * touches; the hook subscribes to those collections and re-runs the\n * callback against the real client when any of them mutate.\n *\n * Re-runs also fire whenever the `deps` array changes between\n * renders (shallow `stableKey` compare). Closure variables read\n * inside the callback must be listed in `deps` — the companion\n * `baerly/exhaustive-deps-use-query` lint rule flags missing\n * entries.\n *\n * Returning {@link useQuery.skip} from the callback yields\n * `{ status: \"skipped\" }` and registers no subscription — use it\n * for deferred / conditional reads.\n *\n * @example\n * ```tsx\n * // Single read\n * const note = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * if (note.status === \"loading\") return <Spinner/>;\n * if (note.status === \"error\") return <Err e={note.error}/>;\n * return <pre>{note.data?.body}</pre>; // typed Note | undefined\n *\n * // Deferred read\n * const list = useQuery(\n * (c) => userId ? c.collection(\"notes\").where({ authorId: userId }).all() : useQuery.skip,\n * [userId],\n * );\n * if (list.status === \"skipped\") return null;\n *\n * // Dependent read (parent → child)\n * const parent = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * const replies = useQuery(\n * (c) => parent.status === \"ok\"\n * ? c.collection(\"comments\").where({ noteId: parent.data._id }).all()\n * : useQuery.skip,\n * [parent.status === \"ok\" ? parent.data._id : undefined],\n * );\n * ```\n */\nconst useQueryImpl = <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n): UseQueryResult<T> => {\n const client = useBaerlyClient<TConfig>();\n const pool = poolFor(client as unknown as BaerlyClient);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n // Force-update for async-error capture (see below). Used to push\n // a microtask-deferred recorder-await rejection back into a sync\n // render.\n const [, forceUpdate] = useReducer((c: number) => c + 1, 0);\n const asyncErrorRef = useRef<BaerlyError | undefined>(undefined);\n\n // Recorder pass. Cheap — no I/O.\n const discovery = discover(\n callbackRef.current as (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n );\n\n // The signature inputs that need to be stable across the same\n // logical query: chain shape + caller-declared deps.\n const depsKey = stableKey([deps ?? []]);\n const signatureBase =\n discovery.kind === \"ok\"\n ? stableKey([discovery.chainShape, deps ?? []])\n : `__non_ok__${discovery.kind}__${depsKey}`;\n\n // Reset the captured async error if the signature changed (the\n // user is on a different query now — give them a fresh chance).\n const lastSignatureRef = useRef<string>(\"\");\n if (lastSignatureRef.current !== signatureBase) {\n lastSignatureRef.current = signatureBase;\n asyncErrorRef.current = undefined;\n }\n\n // Attach an async-error handler to the callback's returned value\n // so that any microtask-deferred rejection from sentinel access\n // (sequential-await pattern) flows back into render via\n // forceUpdate. Wrap in `Promise.resolve(...)` so a bare recorder\n // terminal (Promise<sentinel>) is observed too — the resolved\n // value carries no `.catch`. Always attach (even if asyncErrorRef\n // is already set) so the per-render discovery invocation's\n // rejection is observed and doesn't surface as an unhandled\n // rejection from vitest or the host runtime.\n if (discovery.kind === \"ok\") {\n const result = discovery.callbackResult;\n if (\n result !== null &&\n typeof result === \"object\" &&\n typeof (result as { then?: unknown }).then === \"function\"\n ) {\n Promise.resolve(result as PromiseLike<unknown>).then(\n () => {\n /* discovery success — value discarded */\n },\n (error: unknown) => {\n if (\n error instanceof BaerlyError &&\n error.code === \"UseQueryAwaitedRecorder\" &&\n asyncErrorRef.current === undefined\n ) {\n asyncErrorRef.current = error;\n forceUpdate();\n }\n // Any other rejection is silently swallowed here — the\n // pool's real-client fetch path is the canonical surface\n // for non-recorder errors.\n },\n );\n }\n }\n\n // Subscription channel — stable per (client, collectionsRead.join(\" \")).\n // Pool's getSnapshot returns the current cached entry for this\n // signature; React polls it on subscribe + on every notify.\n const collectionsJoin =\n discovery.kind === \"ok\" ? discovery.collections.join(\"\\x00\") : \"__non_ok__\";\n\n const fetcherRef = useRef<() => Promise<unknown>>(() => Promise.resolve(undefined));\n fetcherRef.current = (): Promise<unknown> => {\n const out = callbackRef.current(client) as Promise<unknown> | typeof SKIP;\n if (out === SKIP) {\n return Promise.resolve(undefined);\n }\n return out as Promise<unknown>;\n };\n\n const chainCollectionsRef = useRef<ReadonlySet<string>>(new Set());\n const discoveryKindRef = useRef<DiscoveryResult[\"kind\"]>(\"ok\");\n const discoveryErrorRef = useRef<Error | undefined>(undefined);\n discoveryKindRef.current = discovery.kind;\n if (discovery.kind === \"ok\") {\n chainCollectionsRef.current = new Set(discovery.collections);\n discoveryErrorRef.current = undefined;\n } else if (discovery.kind === \"error\") {\n discoveryErrorRef.current = discovery.error;\n } else {\n discoveryErrorRef.current = undefined;\n }\n\n const subscribe = useCallback(\n (notify: () => void): (() => void) => {\n if (discovery.kind !== \"ok\") {\n return () => {};\n }\n return pool.attach(\n signatureBase,\n discovery.collections,\n chainCollectionsRef.current,\n () => fetcherRef.current(),\n notify,\n );\n },\n // The signature/collections determine the subscription; React\n // re-subscribes when either changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [pool, signatureBase, collectionsJoin],\n );\n\n // Stable per-error snapshot cache so repeated getSnapshot polls\n // within a single render return the same reference. React's\n // useSyncExternalStore detects identity changes; constructing a\n // fresh error literal each call drives an infinite re-render.\n const errorSnapshotRef = useRef<\n | {\n error: Error;\n snapshot: UseQueryResult<unknown>;\n }\n | undefined\n >(undefined);\n const snapshotForError = (err: Error): UseQueryResult<T> => {\n if (errorSnapshotRef.current?.error === err) {\n return errorSnapshotRef.current.snapshot as UseQueryResult<T>;\n }\n const snapshot = {\n status: \"error\" as const,\n data: undefined,\n error: err,\n } satisfies UseQueryResult<unknown>;\n errorSnapshotRef.current = { error: err, snapshot };\n return snapshot as UseQueryResult<T>;\n };\n\n const getSnapshot = useCallback((): UseQueryResult<T> => {\n if (asyncErrorRef.current) {\n return snapshotForError(asyncErrorRef.current);\n }\n if (discoveryKindRef.current === \"skip\") {\n return SKIPPED_SNAPSHOT as UseQueryResult<T>;\n }\n if (discoveryKindRef.current === \"error\") {\n return snapshotForError(\n discoveryErrorRef.current ?? new BaerlyError(\"Internal\", \"unknown discovery error\"),\n );\n }\n return pool.getSnapshot(signatureBase) as UseQueryResult<T>;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pool, signatureBase]);\n\n // discoveryKindRef + discoveryErrorRef carry the latest discovery\n // state into getSnapshot without making it a useCallback dep\n // (avoids re-creating the snapshot callback every render).\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n};\n\n/**\n * Reactive read hook. See {@link useQueryImpl} JSDoc for usage.\n * The `.skip` property is the sentinel that short-circuits the hook\n * into `status: \"skipped\"`.\n */\nexport const useQuery: {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n} = Object.assign(useQueryImpl, { skip: SKIP }) as {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n};\n\n// Quiet `LOADING_SNAPSHOT` as a value-import — referenced by\n// generated type for the `loading` branch only; bundled alongside\n// `subscription-pool.ts`.\nvoid LOADING_SNAPSHOT;\n","import type { BaerlyConfig, UnboundConfig } from \"@baerly/protocol\";\nimport type { ReactNode } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { BaerlyProvider, useBaerlyClient } from \"./provider.ts\";\nimport { useMutation, type UseMutationTuple } from \"./use-mutation.ts\";\nimport { useQuery, type UseQueryResult } from \"./use-query.ts\";\n\n/**\n * Props for the config-bound `BaerlyProvider` returned by\n * {@link createBaerlyReact}. `client` is typed `BaerlyClient<TConfig>`\n * to document the intended binding; the hooks carry `TConfig`\n * themselves, so row inference holds regardless of the client value's\n * own inferred type.\n */\nexport interface BaerlyProviderProps<TConfig extends BaerlyConfig> {\n readonly client: BaerlyClient<TConfig>;\n readonly children?: ReactNode;\n}\n\n/**\n * The config-bound React surface returned by {@link createBaerlyReact}.\n * Every hook is pinned to `TConfig`, so `c.collection(\"notes\")` inside\n * a `useQuery` / `useMutation` callback infers the real row type — no\n * `as Promise<Note[]>` cast.\n */\nexport interface BaerlyReact<TConfig extends BaerlyConfig> {\n /** Wrap your app once; provides the bound client to every hook below it. */\n readonly BaerlyProvider: (props: BaerlyProviderProps<TConfig>) => React.JSX.Element;\n /**\n * Reactive read. The callback receives `BaerlyClient<TConfig>`, so\n * the chain is fully typed. `useQuery.skip` short-circuits to\n * `{ status: \"skipped\" }`.\n */\n readonly useQuery: {\n <T>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | symbol,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n /**\n * Sentinel — return it from the callback to defer the read\n * (`{ status: \"skipped\" }`, no subscription). Typed `symbol` (not\n * the impl's `unique symbol`) so the bound surface stays nameable\n * across the package boundary; identity-compared at runtime.\n */\n readonly skip: symbol;\n };\n /** Imperative mutation hook → `[mutate, { isPending, error }]`. */\n readonly useMutation: () => UseMutationTuple<TConfig>;\n /** Escape hatch — the raw bound {@link BaerlyClient} for imperative use. */\n readonly useBaerlyClient: () => BaerlyClient<TConfig>;\n}\n\n/**\n * Build the typed React surface for one `baerly.config.ts`. Call it\n * once at module scope and export the result; every hook is bound to\n * the config so collection names autocomplete and row types infer\n * end-to-end. This is the only React entry point — there are no\n * loose, unbound hooks to import by mistake.\n *\n * @example\n * ```ts\n * // src/web/client.ts\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"../../baerly.config.ts\";\n *\n * export const client = createBaerlyClient({ baseUrl: \"\", config });\n * export const { BaerlyProvider, useQuery, useMutation } =\n * createBaerlyReact<typeof config>();\n * ```\n *\n * ```tsx\n * // any component\n * import { useQuery } from \"./client.ts\";\n * const notes = useQuery((c) => c.collection(\"notes\").all(), []);\n * // ^? UseQueryResult<Note[]> — no cast\n * ```\n *\n * Omit the type parameter (`createBaerlyReact()`) for an unbound app;\n * collection names widen to `string` and rows to `DocumentData`,\n * matching the in-process `Db.collection` fallback.\n */\nexport const createBaerlyReact = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyReact<TConfig> => ({\n // Identical runtime implementations — the generic is erased, so the\n // factory only re-pins each hook's type to `TConfig`. The\n // recorder-proxy in `useQuery` is structurally typed as\n // `BaerlyClient`, so binding a narrower config is a no-op at runtime.\n BaerlyProvider: BaerlyProvider as BaerlyReact<TConfig>[\"BaerlyProvider\"],\n useQuery: useQuery as unknown as BaerlyReact<TConfig>[\"useQuery\"],\n useMutation: useMutation as BaerlyReact<TConfig>[\"useMutation\"],\n useBaerlyClient: useBaerlyClient as BaerlyReact<TConfig>[\"useBaerlyClient\"],\n});\n"],"mappings":";;;;AAIA,MAAM,gBAAgB,cAAwC,KAAA,CAAS;;;;;;;;;;;;;;;;;;;;;;AA4BvE,MAAa,kBAAkB,EAAE,QAAQ,eACvC,cAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;;;;;;;;;;;;;;;;;;;;AAqBnE,MAAa,wBAEiB;CAC5B,MAAM,SAAS,WAAW,aAAa;CACvC,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,MACR,wJAEF;CAEF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzBA,MAAa,oBAEqB;CAChC,MAAM,SAAS,gBAAyB;CACxC,MAAM,cAAc,OAAe,CAAC;CACpC,MAAM,aAAa,OAAgB,IAAI;CACvC,MAAM,CAAC,WAAW,gBAAgB,SAAkB,KAAK;CACzD,MAAM,CAAC,WAAW,gBAAgB,SAAkC,KAAA,CAAS;CAE7E,sBACc;EACV,WAAW,UAAU;CACvB,GACA,CAAC,CACH;CAsCA,OAAO,CApCQ,YACb,OAAU,aAAmE;EAC3E,MAAM,UAAU,YAAY,YAAY;EACxC,YAAY,WAAW;EACvB,IAAI,WAAW,WAAW,SAAS;GACjC,aAAa,IAAI;GACjB,aAAa,KAAA,CAAS;EACxB;EACA,IAAI;GAEF,OAAO,MADc,SAAS,MAAM;EAEtC,SAAS,OAAO;GACd,MAAM,KACJ,iBAAiB,cACb,QACA,IAAI,YACF,kBACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrD,KACF;GAC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C,kBAAkB,UAAU,KAAA;CAG9B,MAAM,YAAY,aACf,WAAqC;EACpC,IAAI,UAAU,SAAS,MACrB,aAAa,CAAC;EAEhB,OAAO,KAAK,OACV,eACA,UAAU,aACV,oBAAoB,eACd,WAAW,QAAQ,GACzB,MACF;CACF,GAIA;EAAC;EAAM;EAAe;CAAe,CACvC;CAMA,MAAM,mBAAmB,OAMvB,KAAA,CAAS;CACX,MAAM,oBAAoB,QAAkC;EAC1D,IAAI,iBAAiB,SAAS,UAAU,KACtC,OAAO,iBAAiB,QAAQ;EAElC,MAAM,WAAW;GACf,QAAQ;GACR,MAAM,KAAA;GACN,OAAO;EACT;EACA,iBAAiB,UAAU;GAAE,OAAO;GAAK;EAAS;EAClD,OAAO;CACT;CAEA,MAAM,cAAc,kBAAqC;EACvD,IAAI,cAAc,SAChB,OAAO,iBAAiB,cAAc,OAAO;EAE/C,IAAI,iBAAiB,YAAY,QAC/B,OAAO;EAET,IAAI,iBAAiB,YAAY,SAC/B,OAAO,iBACL,kBAAkB,WAAW,IAAI,YAAY,YAAY,yBAAyB,CACpF;EAEF,OAAO,KAAK,YAAY,aAAa;CAEvC,GAAG,CAAC,MAAM,aAAa,CAAC;CAKxB,OAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;;;;;;AAOA,MAAa,WAMT,OAAO,OAAO,cAAc,EAAE,MAAM,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChU9C,MAAa,2BAEiB;CAKZ;CACN;CACG;CACI;AACnB"}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as DocumentData } from "./app-config-
|
|
2
|
-
import { l as OrderSpec, n as LogEntry, o as BaerlyError, s as BaerlyErrorCode, u as Predicate } from "./index-
|
|
3
|
-
import { a as TerminalOptions, i as ClientQuery, n as BaerlyClientOptions, o as createBaerlyClient, r as ClientCollection, s as Fetcher, t as BaerlyClient } from "./client-
|
|
1
|
+
import { f as DocumentData } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { l as OrderSpec, n as LogEntry, o as BaerlyError, s as BaerlyErrorCode, u as Predicate } from "./index-DW7GT6M2.js";
|
|
3
|
+
import { a as TerminalOptions, i as ClientQuery, n as BaerlyClientOptions, o as createBaerlyClient, r as ClientCollection, s as Fetcher, t as BaerlyClient } from "./client-BJXF3XJA.js";
|
|
4
4
|
export { type BaerlyClient, type BaerlyClientOptions, BaerlyError, type BaerlyErrorCode, type ClientCollection, type ClientQuery, type DocumentData, type Fetcher, type LogEntry, type OrderSpec, type Predicate, type TerminalOptions, createBaerlyClient };
|