@lunora/server 1.0.0-alpha.104 → 1.0.0-alpha.106
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/otel.d.mts +20 -9
- package/dist/otel.d.ts +20 -9
- package/dist/otel.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-u1YNydNU.mjs → ACTION_CACHE_DEFAULT_TTL_MS-CBCYHUFV.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-BbnXQrHY.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-DScATYVh.mjs} +1 -1
- package/dist/packem_shared/{buildRlsReadRegistry-Zx8A7y13.mjs → buildRlsReadRegistry-r63qMKN6.mjs} +1 -1
- package/dist/packem_shared/{mask-MSALbzq3.mjs → mask-Ca8SAJsC.mjs} +1 -1
- package/dist/packem_shared/{middleware-Cu_Nh8cX.mjs → middleware-CJSowZY0.mjs} +1 -1
- package/dist/packem_shared/{rls-HOiT19Ye.mjs → rls-BjHAvbpA.mjs} +1 -1
- package/dist/packem_shared/{storageRules-B4qi8_Z4.mjs → storageRules-B8dXzTI2.mjs} +1 -1
- package/dist/packem_shared/wire-codec-CH4vwdFT.mjs +1 -0
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +66 -20
- package/dist/types.d.ts +66 -20
- package/package.json +4 -4
- package/dist/packem_shared/wire-codec-BiYbPSuZ.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
3
|
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook } from "./types.mjs";
|
|
4
|
-
export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
|
|
4
|
+
export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
7
7
|
import { Context, Hono } from 'hono';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
3
|
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook } from "./types.js";
|
|
4
|
-
export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
|
|
4
|
+
export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
7
7
|
import { Context, Hono } from 'hono';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-CBCYHUFV.mjs";import{initLunora as d}from"./packem_shared/initLunora-D5TSiy5j.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as S}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as D}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-DScATYVh.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as b}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as P,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-YRpmc049.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-te5TWJIE.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as fe,i as ae,j as se,k as de,m as me}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs";import{protectPublic as Se}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as be,v as Me}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{buildMaskRegistry as we}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/buildRlsReadRegistry-r63qMKN6.mjs";import{createPolicyDsl as Ye,definePermission as Je,definePolicies as Ke,definePolicy as Qe,defineRole as Xe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ze,defineStorageRules as Ge}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as $e}from"./packem_shared/mask-Ca8SAJsC.mjs";import{r as rr}from"./packem_shared/middleware-CJSowZY0.mjs";import{storageRules as tr}from"./packem_shared/storageRules-B8dXzTI2.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,be as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,u as beginDeferredSchedules,y as bindOrm,b as bindTableFacade,we as buildMaskRegistry,Ve as buildRlsReadRegistry,f as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,je as composeShapeReadWhere,Ye as createPolicyDsl,p as createSecrets,Ie as cronJobs,a as defineActionCache,ee as defineAggregateIndex,re as defineComponent,A as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Je as definePermission,oe as definePlugin,Ke as definePolicies,Qe as definePolicy,le as definePresence,te as defineRankIndex,Xe as defineRole,ne as defineSchema,ie as defineSchemaExtension,Ae as defineShape,ze as defineStorageRule,Ge as defineStorageRules,fe as defineTable,ae as defineVectorIndex,Oe as deny,D as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,$e as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,Se as protectPublic,C as redactSecrets,rr as rls,U as serveStorageObject,tr as storageRules,Ne as toWhereInput,Me as v,l as withDeferredDeletes,S as withDeferredSchedules};
|
package/dist/otel.d.mts
CHANGED
|
@@ -527,15 +527,26 @@ interface OtelTracerOptions {
|
|
|
527
527
|
* decision, and export through the same OTLP sink. Nothing in the runtime has to
|
|
528
528
|
* know they came from a third-party library.
|
|
529
529
|
*
|
|
530
|
-
* **Parenting.**
|
|
531
|
-
*
|
|
532
|
-
*
|
|
533
|
-
*
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
530
|
+
* **Parenting.** The parent is read from the `Context` the caller threads —
|
|
531
|
+
* `startSpan(name, options, ctx)` parents to `trace.getSpanContext(ctx)` when it
|
|
532
|
+
* names a span in THIS trace — and falls back to the dispatch when no Context is
|
|
533
|
+
* passed (or it carries a span from a different trace, which would be a lie to
|
|
534
|
+
* parent to). What the bridge does NOT do is track a dynamically scoped "current"
|
|
535
|
+
* span, because that needs `AsyncLocalStorage` — unavailable in the Durable
|
|
536
|
+
* Object profile (see the module doc). `startActiveSpan` therefore runs its
|
|
537
|
+
* callback with the new span passed in, exactly as the interface requires, but
|
|
538
|
+
* does NOT make it ambient: `trace.getActiveSpan()` inside that callback still
|
|
539
|
+
* reports whatever the global provider says. A library that threads its `Context`
|
|
540
|
+
* or the span it is handed (the common case, and what the AI SDK does) nests
|
|
541
|
+
* correctly; one that relies on ambient context gets a flat trace instead of a
|
|
542
|
+
* nested one — flatter, never wrong, never lost.
|
|
543
|
+
*
|
|
544
|
+
* **Ids and sampling.** The `SpanContext` returned by `startSpan` is the one the
|
|
545
|
+
* span is RECORDED under: the id is minted here and handed to `ctx.trace` as its
|
|
546
|
+
* span identity, so a `traceparent` a library builds from it names a span that
|
|
547
|
+
* actually reaches the collector. `traceFlags` carries the trace's settled
|
|
548
|
+
* sampling verdict rather than a hardcoded SAMPLED, so a sampled-out trace is not
|
|
549
|
+
* announced downstream as kept.
|
|
539
550
|
* @param context Any Lunora function context (`QueryCtx` / `MutationCtx` / `ActionCtx`).
|
|
540
551
|
* @param options See {@link OtelTracerOptions}.
|
|
541
552
|
*/
|
package/dist/otel.d.ts
CHANGED
|
@@ -527,15 +527,26 @@ interface OtelTracerOptions {
|
|
|
527
527
|
* decision, and export through the same OTLP sink. Nothing in the runtime has to
|
|
528
528
|
* know they came from a third-party library.
|
|
529
529
|
*
|
|
530
|
-
* **Parenting.**
|
|
531
|
-
*
|
|
532
|
-
*
|
|
533
|
-
*
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
530
|
+
* **Parenting.** The parent is read from the `Context` the caller threads —
|
|
531
|
+
* `startSpan(name, options, ctx)` parents to `trace.getSpanContext(ctx)` when it
|
|
532
|
+
* names a span in THIS trace — and falls back to the dispatch when no Context is
|
|
533
|
+
* passed (or it carries a span from a different trace, which would be a lie to
|
|
534
|
+
* parent to). What the bridge does NOT do is track a dynamically scoped "current"
|
|
535
|
+
* span, because that needs `AsyncLocalStorage` — unavailable in the Durable
|
|
536
|
+
* Object profile (see the module doc). `startActiveSpan` therefore runs its
|
|
537
|
+
* callback with the new span passed in, exactly as the interface requires, but
|
|
538
|
+
* does NOT make it ambient: `trace.getActiveSpan()` inside that callback still
|
|
539
|
+
* reports whatever the global provider says. A library that threads its `Context`
|
|
540
|
+
* or the span it is handed (the common case, and what the AI SDK does) nests
|
|
541
|
+
* correctly; one that relies on ambient context gets a flat trace instead of a
|
|
542
|
+
* nested one — flatter, never wrong, never lost.
|
|
543
|
+
*
|
|
544
|
+
* **Ids and sampling.** The `SpanContext` returned by `startSpan` is the one the
|
|
545
|
+
* span is RECORDED under: the id is minted here and handed to `ctx.trace` as its
|
|
546
|
+
* span identity, so a `traceparent` a library builds from it names a span that
|
|
547
|
+
* actually reaches the collector. `traceFlags` carries the trace's settled
|
|
548
|
+
* sampling verdict rather than a hardcoded SAMPLED, so a sampled-out trace is not
|
|
549
|
+
* announced downstream as kept.
|
|
539
550
|
* @param context Any Lunora function context (`QueryCtx` / `MutationCtx` / `ActionCtx`).
|
|
540
551
|
* @param options See {@link OtelTracerOptions}.
|
|
541
552
|
*/
|
package/dist/otel.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SpanKind as
|
|
1
|
+
import{SpanKind as o,trace as S,TraceFlags as g,SpanStatusCode as w}from"@opentelemetry/api";const v={[o.CLIENT]:"client",[o.CONSUMER]:"consumer",[o.INTERNAL]:"internal",[o.PRODUCER]:"producer",[o.SERVER]:"server"},A=s=>{const t=new Uint8Array(s);crypto.getRandomValues(t);let e="";for(const r of t)e+=r.toString(16).padStart(2,"0");return e},c=s=>{const t={};for(const[e,r]of Object.entries(s??{}))r!==void 0&&(t[e]=Array.isArray(r)?r.map(String).join(","):r);return t};class k{ended=!1;finish;handle;ids;pending=[];thrown;constructor(t){this.ids=t}get failure(){return this.thrown}addEvent(t,e,r){return this.write(i=>{i.addEvent(t,c(e))}),this}addLink(t){return this.write(e=>{e.addLink({attributes:c(t.attributes),spanId:t.context.spanId,traceId:t.context.traceId})}),this}addLinks(t){for(const e of t)this.addLink(e);return this}attach(t,e){this.handle=t,this.finish=e;for(const r of this.pending)r(t);this.pending.length=0,this.ended&&e()}end(t){this.ended||(this.ended=!0,this.finish?.())}isRecording(){return!this.ended}recordException(t,e){this.write(r=>{if(t instanceof Error||typeof t=="string"){r.recordException(t);return}const i=new Error(t.message??String(t.code??"exception"));t.name!==void 0&&(i.name=t.name),t.stack!==void 0&&(i.stack=t.stack),r.recordException(i)})}setAttribute(t,e){return this.write(r=>{r.setAttribute(t,Array.isArray(e)?e.map(String).join(","):e)}),this}setAttributes(t){return this.write(e=>{e.setAttributes(c(t))}),this}setStatus(t){return t.code===w.ERROR&&(this.thrown=new Error(t.message??"span reported an error status")),this}spanContext(){return this.ids}updateName(t){return this.write(e=>{e.setAttribute("otel.updated_name",t)}),this}write(t){if(this.handle===void 0){this.pending.push(t);return}t(this.handle)}}const R=(s,t={})=>{const{namePrefix:e=""}=t,r=(i,n,u)=>{const a=s.span.spanContext(),h=u===void 0?void 0:S.getSpanContext(u),p=h?.traceId===a.traceId?h.spanId:a.spanId,l=A(8),I={spanId:l,traceFlags:a.sampled??!0?g.SAMPLED:g.NONE,traceId:a.traceId},f=new k(I);let m=()=>{};const b=new Promise(d=>{m=d});return s.trace(`${e}${i}`,async(d,E)=>{if(f.attach(E,m),await b,f.failure!==void 0)throw f.failure},{...n?.attributes===void 0?{}:{attributes:c(n.attributes)},...n?.kind===void 0?{}:{kind:v[n.kind]??"internal"},...n?.links===void 0?{}:{links:n.links.map(d=>({attributes:c(d.attributes),spanId:d.context.spanId,traceId:d.context.traceId}))}},{parentSpanId:p,spanId:l}).catch(()=>{}),f};return{startActiveSpan:(i,...n)=>{const u=n.at(-1),a=typeof n[0]=="object"&&n[0]!==null?n[0]:void 0,h=n.length>2?n[1]:void 0,p=r(i,a,h);return u(p)},startSpan:r}};export{R as createOtelTracer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CH4vwdFT.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-D5TSiy5j.mjs";import{g as k,h as q,a as B}from"./plugin-yKCbHnlj.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CH4vwdFT.mjs";import{initLunora as x}from"./initLunora-D5TSiy5j.mjs";import{g as v,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
|
package/dist/packem_shared/{buildRlsReadRegistry-Zx8A7y13.mjs → buildRlsReadRegistry-r63qMKN6.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as d,d as f,e as u,f as h}from"./middleware-
|
|
1
|
+
import{i as d,d as f,e as u,f as h}from"./middleware-CJSowZY0.mjs";import{r as p}from"./policy-tag-V0lqFzgS.mjs";import{deny as g}from"./allowAll-DkRAgItV.mjs";const c=g(),b=s=>{const e=s?.rls?.tags;return e||p(s)},y=(s,e)=>{const o=d(e.roles),n=new Map,r=new Map;for(const t of e.policies){if(t.on!=="read")continue;const a=n.get(t.table)??new Set;if(a.has(t.when))continue;a.add(t.when),n.set(t.table,a);const i=r.get(t.table)??[];i.push(t),r.set(t.table,i)}for(const[t,a]of r){const i=s.get(t)??[];i.push({policies:a,rolePermissions:o}),s.set(t,i)}},l=s=>{const e=s.OR;return Array.isArray(e)&&e.length===0&&Object.keys(s).length===1},R=(s,e)=>!s||Object.keys(s).length===0?e:l(s)||Object.keys(e).length===0?s:{AND:[s,e]},m=(s,e)=>{const o=f(e.identity);return u(s.policies,{auth:{can:h(o,s.rolePermissions),identity:e.identity,roles:o,userId:e.userId},ctx:e.ctx})},T=(s,e)=>{const o=s.byTable.get(e.table);if(!o||o.length===0)return e.rlsRequired&&!e.tablePublic?c:void 0;const n=[];for(const r of o){const t=m(r,e);if(t===void 0)return;l(t)||n.push(t)}return n.length===0?c:n.length===1?n[0]:{OR:n}},W=s=>{const e=new Map,o=new Set;for(const n of s)for(const r of b(n))o.has(r)||(o.add(r),y(e,r));return{byTable:e}},A=(s,e)=>R(T(s,e),e.shapeWhere);export{W as buildRlsReadRegistry,A as composeShapeReadWhere};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-CJSowZY0.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},u=(e,i,a)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...a,column:y,row:e}));return d},j=(e,i,a)=>({...e,page:e.page.map(d=>u(d,i,a))}),D=(e,i,a,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,a)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,a)},collect:async()=>(await r.collect()).map(s=>u(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,a):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>u(c,n,a)),unique:async()=>{const o=await r.unique();return o?u(o,n,a):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);return f?{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,a)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:u(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,a,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of a)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{i as U}from"./wire-codec-BiYbPSuZ.mjs";import{bindTableFacade as X,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{t as Z}from"./policy-tag-V0lqFzgS.mjs";import{deny as V}from"./allowAll-DkRAgItV.mjs";const x=["every","is","isNot","none","some"],ee=new Set(x),re=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ee.has(n))},F=(e,r,n)=>r?{[e]:n(r)}:{},te=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],A=-1,k=0,O=1,v=e=>e?O:A,y=(e,r)=>e<r?e:r,ne=(e,r)=>e>r?e:r,j=e=>e===k?k:v(e===A),$=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},B=e=>e==null,I=(e,r,n)=>{if(n===void 0)throw new w("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},se={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},oe=(e,r,n)=>{let i=O;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const l=n[c];if(I(e,c,l),!$(l))i=y(i,A);else if(B(r))i=y(i,k);else{const h=se[c];i=y(i,v($(r)&&h(r,l)))}}return i},N=(e,r,n)=>{if(!Array.isArray(n))throw new w("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new w("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},q=(e,r)=>r.length===0?A:B(e)?k:r.includes(e)?O:r.some(n=>B(n))?k:A,ie=(e,r,n)=>{let i=O;if("in"in n&&(i=y(i,q(r,N(e,"in",n.in)))),"notIn"in n&&(i=y(i,j(q(r,N(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;I(e,"contains",c),i=B(r)?y(i,k):y(i,v(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=y(i,v(n.isNull===!0===B(r)))),i},T=(e,r,n)=>r===null?v(n===B(e)):B(e)?k:v(n===(e===r)),ae=(e,r,n)=>{let i=O;return"eq"in n&&(I(e,"eq",n.eq),i=y(i,T(r,n.eq,!0))),"ne"in n&&(I(e,"ne",n.ne),i=y(i,T(r,n.ne,!1))),i},ce=(e,r,n)=>y(ae(e,r,n),y(ie(e,r,n),oe(e,r,n))),le=(e,r,n,i)=>{if(r==="NOT")return j(i(e,n??{}));if(!Array.isArray(n))return A;let c=r==="AND"?O:A;for(const l of n){const h=i(e,l);c=r==="AND"?y(c,h):ne(c,h)}return c},K=e=>e==="AND"||e==="OR"||e==="NOT",fe=e=>U(e)&&Object.keys(e).every(r=>te.includes(r)),M=e=>Object.keys(e).some(r=>{const n=e[r];return K(r)?r==="NOT"?M(n??{}):Array.isArray(n)&&n.some(i=>M(i??{})):re(n)}),Y=(e,r)=>{let n=O;for(const i of Object.keys(r)){const c=r[i];if(K(i)){n=y(n,le(e,i,c,Y));continue}const l=e[i];if(fe(c)){n=y(n,ce(i,l,c));continue}I(i,"eq",c),n=y(n,T(l,c,!0))}return n},m=(e,r)=>Y(e,r)===O,Q=500,_=(e,r,n)=>{const i=r??Q;if(e>i)throw new w("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ue=V(),he=Symbol.for("lunora.ctxdb.rls-unwrap"),de=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},ye=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const l=c.when(r);if(l!==void 0){if(l===!0){i=!0;break}l!==!1&&n.push(l)}}if(!i)return n.length===0?ue:n.length===1?n[0]:{OR:n}},we=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(M(i))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return m(n,i)},ge=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||we(e,r,n);if(i===!1)return!1;if(M(i))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!m(r.row,i)?!1:n===void 0||m(n,i)},P=(e,r,n,i)=>{let c=!1;for(const l of e)if(l.on===r&&(c=!0,!ge(l,n,i)))return!1;return c},pe=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),We=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":U(r),Oe=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>pe.has(n)&&We(n,e[n]))},Re=e=>e===void 0?{}:U(e)&&Oe(e)?e:{where:e},p=(e,r)=>!r||Object.keys(r).length===0?e:!e||Object.keys(e).length===0?r:{AND:[r,e]},be=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Ee=(e,r,n,i)=>{const c=new Map,l=t=>{const s=c.get(t);if(s)return s;const o=n.get(t);if(!o||o.length===0||!o.some(u=>u.on==="read")){const u={baseWhere:void 0,restricts:!1};return c.set(t,u),u}const f={baseWhere:ye(o,i),restricts:!0};return c.set(t,f),f},h=t=>l(t).restricts?r:e,g=t=>l(t).baseWhere,R=async(t,s)=>{if(r.lookupById){const d=await r.lookupById(t,s);return d?{row:d.row,tableName:n.has(d.tableName)?d.tableName:void 0}:{row:null,tableName:void 0}}const o=await r.get(t,s);if(!o)return{row:null,tableName:void 0};const a=s!==void 0&&n.has(s)?[s]:[],f=s===void 0?[...n.keys()]:a,u=await Promise.all(f.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:o,tableName:u.find(d=>d!==void 0)}},C=async(t,s)=>{const o=await R(t,s);return o.row&&o.tableName!==void 0?{row:o.row,tableName:o.tableName}:void 0},W=async(t,s,o,a,f)=>{const u=await C(t,f);if(!u)return o(e);const d=n.get(u.tableName);if(d){const E=a?a(u.row):void 0;if(!P(d,s,{...i,row:u.row},E))throw new w("FORBIDDEN",`${s} denied by policy`)}return o(r)},b=(t,s)=>{const{baseWhere:o,restricts:a}=l(t);if(a)throw new w("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`);return o},D=e.rankBefore,H=e.rankPageRows,S={...e,async count(t,s){const{baseWhere:o,restricts:a}=l(t),f=Re(s);return h(t).count(t,{...f,baseWhere:p(f.baseWhere,o),relationBaseWhere:g,restrictsCounts:(f.restrictsCounts??!1)||a})},delete:(t,s,o)=>W(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??Q),{baseWhere:a}=l(t);let f=0;for(;;){const d=(await h(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(E=>String(E._id));if(d.length===0)break;for(const E of d)await W(E,"delete",L=>L.delete(E,void 0,s?.hard===void 0?void 0:{hard:s.hard})),f+=1;if(d.length<o)break}return{deleted:f}},async deleteMany(t,s,o){_(t.length,s?.limit,"deleteMany");for(const a of t)await W(a,"delete",f=>f.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=l(t),u=(await h(t).findMany(t,{baseWhere:p(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));return _(u.length,o?.limit,"deleteWhere"),S.deleteMany(u,o)},async findFirst(t,s){const{baseWhere:o}=l(t);return h(t).findFirst(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=l(t);return h(t).findFirstOrThrow(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=l(t);return h(t).findMany(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await R(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:f}=l(o.tableName);if(!f)return e.get(t,s);if(!a)return o.row;const u=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return u?._id===t?u:null},async lookupById(t,s){const o=await R(t,s);if(!o.row)return null;if(o.tableName===void 0||!l(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=l(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const f=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return f?._id===t?{row:f,tableName:o.tableName}:null},async insert(t,s){const o=n.get(t);if(o){if(!P(o,"insert",{...i,row:s}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){_(s.length,o?.limit,"insertMany");const a=n.get(t);if(a){for(const f of s)if(!P(a,"insert",{...i,row:f}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){_(s.length,o?.limit,"insertManyUnsafe");const a=n.get(t);if(a){for(const f of s)if(!P(a,"insert",{...i,row:f}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>W(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){_(t.length,s?.limit,"patchMany");for(const a of t)await W(a.id,"update",f=>f.patch(a.id,a.patch,o),f=>({...f,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=l(t),u=(await h(t).findMany(t,{baseWhere:p(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return _(u.length,o?.limit,"patchWhere"),S.patchMany(u,o)},query(t){const{baseWhere:s}=l(t),o=h(t).query(t);return s?o.filter(a=>m(a,s)):o},restore:(t,s)=>W(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new w("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>W(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=l(t);return h(t).aggregate(t,{...s,baseWhere:p(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=l(t);return h(t).groupBy(t,{...s,baseWhere:p(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){const a=b(t,"rank");return h(t).rank(t,s,{...o,baseWhere:p(o.baseWhere,a)})},rankPage(t,s,o){const a=b(t,"rankPage");return h(t).rankPage(t,s,{...o,baseWhere:p(o?.baseWhere,a)})},wipeShard(){throw new w("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...F("rankBefore",D,t=>(s,o,a)=>(b(s,"rankBefore"),(h(s).rankBefore??t)(s,o,a))),...F("rankPageRows",H,t=>(s,o,a)=>{const f=b(s,"rankPageRows");return(h(s).rankPageRows??t)(s,o,{...a,baseWhere:p(a?.baseWhere,f)})})},G=S;if(n.size>0)for(const[t,s]of Object.entries(e))be(s)&&(G[t]=X(S,t));return S},z=e=>typeof e=="string"?e:e.name,Ae=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>z(i))));return r},ke=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(z(i))},Be=["roles","role"],_e=e=>{for(const r of Be){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},ve=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([..._e(n),...e.roles??[]])];return{can:ke(i,r),identity:n,roles:i,userId:e.userId??null}},me=(e,r={})=>{const n=de(e),i=Ae(r.roles);return Z(async({ctx:l,next:h})=>{const g={auth:await ve(l.auth??{},i),ctx:l},R=l.db,C=R[he]??R,W=Ee(R,C,n,g),b={db:W},{orm:D}=l;return D!==null&&typeof D=="object"&&(b.orm=J(W)),h({ctx:b})},[{policies:e,roles:r.roles??[]}])};export{ve as a,be as b,re as c,_e as d,ye as e,ke as f,P as g,Ae as i,m,F as o,z as p,me as r};
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{i as U}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as X,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{t as Z}from"./policy-tag-V0lqFzgS.mjs";import{deny as V}from"./allowAll-DkRAgItV.mjs";const x=["every","is","isNot","none","some"],ee=new Set(x),re=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ee.has(n))},F=(e,r,n)=>r?{[e]:n(r)}:{},te=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],A=-1,k=0,O=1,v=e=>e?O:A,y=(e,r)=>e<r?e:r,ne=(e,r)=>e>r?e:r,j=e=>e===k?k:v(e===A),$=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},B=e=>e==null,I=(e,r,n)=>{if(n===void 0)throw new w("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},se={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},oe=(e,r,n)=>{let i=O;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const l=n[c];if(I(e,c,l),!$(l))i=y(i,A);else if(B(r))i=y(i,k);else{const h=se[c];i=y(i,v($(r)&&h(r,l)))}}return i},N=(e,r,n)=>{if(!Array.isArray(n))throw new w("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new w("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},q=(e,r)=>r.length===0?A:B(e)?k:r.includes(e)?O:r.some(n=>B(n))?k:A,ie=(e,r,n)=>{let i=O;if("in"in n&&(i=y(i,q(r,N(e,"in",n.in)))),"notIn"in n&&(i=y(i,j(q(r,N(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;I(e,"contains",c),i=B(r)?y(i,k):y(i,v(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=y(i,v(n.isNull===!0===B(r)))),i},T=(e,r,n)=>r===null?v(n===B(e)):B(e)?k:v(n===(e===r)),ae=(e,r,n)=>{let i=O;return"eq"in n&&(I(e,"eq",n.eq),i=y(i,T(r,n.eq,!0))),"ne"in n&&(I(e,"ne",n.ne),i=y(i,T(r,n.ne,!1))),i},ce=(e,r,n)=>y(ae(e,r,n),y(ie(e,r,n),oe(e,r,n))),le=(e,r,n,i)=>{if(r==="NOT")return j(i(e,n??{}));if(!Array.isArray(n))return A;let c=r==="AND"?O:A;for(const l of n){const h=i(e,l);c=r==="AND"?y(c,h):ne(c,h)}return c},K=e=>e==="AND"||e==="OR"||e==="NOT",fe=e=>U(e)&&Object.keys(e).every(r=>te.includes(r)),M=e=>Object.keys(e).some(r=>{const n=e[r];return K(r)?r==="NOT"?M(n??{}):Array.isArray(n)&&n.some(i=>M(i??{})):re(n)}),Y=(e,r)=>{let n=O;for(const i of Object.keys(r)){const c=r[i];if(K(i)){n=y(n,le(e,i,c,Y));continue}const l=e[i];if(fe(c)){n=y(n,ce(i,l,c));continue}I(i,"eq",c),n=y(n,T(l,c,!0))}return n},m=(e,r)=>Y(e,r)===O,Q=500,_=(e,r,n)=>{const i=r??Q;if(e>i)throw new w("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ue=V(),he=Symbol.for("lunora.ctxdb.rls-unwrap"),de=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},ye=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const l=c.when(r);if(l!==void 0){if(l===!0){i=!0;break}l!==!1&&n.push(l)}}if(!i)return n.length===0?ue:n.length===1?n[0]:{OR:n}},we=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(M(i))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return m(n,i)},ge=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||we(e,r,n);if(i===!1)return!1;if(M(i))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!m(r.row,i)?!1:n===void 0||m(n,i)},P=(e,r,n,i)=>{let c=!1;for(const l of e)if(l.on===r&&(c=!0,!ge(l,n,i)))return!1;return c},pe=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),We=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":U(r),Oe=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>pe.has(n)&&We(n,e[n]))},Re=e=>e===void 0?{}:U(e)&&Oe(e)?e:{where:e},p=(e,r)=>!r||Object.keys(r).length===0?e:!e||Object.keys(e).length===0?r:{AND:[r,e]},be=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Ee=(e,r,n,i)=>{const c=new Map,l=t=>{const s=c.get(t);if(s)return s;const o=n.get(t);if(!o||o.length===0||!o.some(u=>u.on==="read")){const u={baseWhere:void 0,restricts:!1};return c.set(t,u),u}const f={baseWhere:ye(o,i),restricts:!0};return c.set(t,f),f},h=t=>l(t).restricts?r:e,g=t=>l(t).baseWhere,R=async(t,s)=>{if(r.lookupById){const d=await r.lookupById(t,s);return d?{row:d.row,tableName:n.has(d.tableName)?d.tableName:void 0}:{row:null,tableName:void 0}}const o=await r.get(t,s);if(!o)return{row:null,tableName:void 0};const a=s!==void 0&&n.has(s)?[s]:[],f=s===void 0?[...n.keys()]:a,u=await Promise.all(f.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:o,tableName:u.find(d=>d!==void 0)}},C=async(t,s)=>{const o=await R(t,s);return o.row&&o.tableName!==void 0?{row:o.row,tableName:o.tableName}:void 0},W=async(t,s,o,a,f)=>{const u=await C(t,f);if(!u)return o(e);const d=n.get(u.tableName);if(d){const E=a?a(u.row):void 0;if(!P(d,s,{...i,row:u.row},E))throw new w("FORBIDDEN",`${s} denied by policy`)}return o(r)},b=(t,s)=>{const{baseWhere:o,restricts:a}=l(t);if(a)throw new w("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`);return o},D=e.rankBefore,H=e.rankPageRows,S={...e,async count(t,s){const{baseWhere:o,restricts:a}=l(t),f=Re(s);return h(t).count(t,{...f,baseWhere:p(f.baseWhere,o),relationBaseWhere:g,restrictsCounts:(f.restrictsCounts??!1)||a})},delete:(t,s,o)=>W(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??Q),{baseWhere:a}=l(t);let f=0;for(;;){const d=(await h(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(E=>String(E._id));if(d.length===0)break;for(const E of d)await W(E,"delete",L=>L.delete(E,void 0,s?.hard===void 0?void 0:{hard:s.hard})),f+=1;if(d.length<o)break}return{deleted:f}},async deleteMany(t,s,o){_(t.length,s?.limit,"deleteMany");for(const a of t)await W(a,"delete",f=>f.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=l(t),u=(await h(t).findMany(t,{baseWhere:p(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));return _(u.length,o?.limit,"deleteWhere"),S.deleteMany(u,o)},async findFirst(t,s){const{baseWhere:o}=l(t);return h(t).findFirst(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=l(t);return h(t).findFirstOrThrow(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=l(t);return h(t).findMany(t,{...s,baseWhere:p(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await R(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:f}=l(o.tableName);if(!f)return e.get(t,s);if(!a)return o.row;const u=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return u?._id===t?u:null},async lookupById(t,s){const o=await R(t,s);if(!o.row)return null;if(o.tableName===void 0||!l(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=l(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const f=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return f?._id===t?{row:f,tableName:o.tableName}:null},async insert(t,s){const o=n.get(t);if(o){if(!P(o,"insert",{...i,row:s}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){_(s.length,o?.limit,"insertMany");const a=n.get(t);if(a){for(const f of s)if(!P(a,"insert",{...i,row:f}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){_(s.length,o?.limit,"insertManyUnsafe");const a=n.get(t);if(a){for(const f of s)if(!P(a,"insert",{...i,row:f}))throw new w("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>W(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){_(t.length,s?.limit,"patchMany");for(const a of t)await W(a.id,"update",f=>f.patch(a.id,a.patch,o),f=>({...f,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=l(t),u=(await h(t).findMany(t,{baseWhere:p(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return _(u.length,o?.limit,"patchWhere"),S.patchMany(u,o)},query(t){const{baseWhere:s}=l(t),o=h(t).query(t);return s?o.filter(a=>m(a,s)):o},restore:(t,s)=>W(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new w("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>W(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=l(t);return h(t).aggregate(t,{...s,baseWhere:p(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=l(t);return h(t).groupBy(t,{...s,baseWhere:p(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){const a=b(t,"rank");return h(t).rank(t,s,{...o,baseWhere:p(o.baseWhere,a)})},rankPage(t,s,o){const a=b(t,"rankPage");return h(t).rankPage(t,s,{...o,baseWhere:p(o?.baseWhere,a)})},wipeShard(){throw new w("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...F("rankBefore",D,t=>(s,o,a)=>(b(s,"rankBefore"),(h(s).rankBefore??t)(s,o,a))),...F("rankPageRows",H,t=>(s,o,a)=>{const f=b(s,"rankPageRows");return(h(s).rankPageRows??t)(s,o,{...a,baseWhere:p(a?.baseWhere,f)})})},G=S;if(n.size>0)for(const[t,s]of Object.entries(e))be(s)&&(G[t]=X(S,t));return S},z=e=>typeof e=="string"?e:e.name,Ae=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>z(i))));return r},ke=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(z(i))},Be=["roles","role"],_e=e=>{for(const r of Be){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},ve=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([..._e(n),...e.roles??[]])];return{can:ke(i,r),identity:n,roles:i,userId:e.userId??null}},me=(e,r={})=>{const n=de(e),i=Ae(r.roles);return Z(async({ctx:l,next:h})=>{const g={auth:await ve(l.auth??{},i),ctx:l},R=l.db,C=R[he]??R,W=Ee(R,C,n,g),b={db:W},{orm:D}=l;return D!==null&&typeof D=="object"&&(b.orm=J(W)),h({ctx:b})},[{policies:e,roles:r.roles??[]}])};export{ve as a,be as b,re as c,_e as d,ye as e,ke as f,P as g,Ae as i,m,F as o,z as p,me as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./wire-codec-
|
|
1
|
+
import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-ChQydkdL.mjs";import{e as t,g as m,i as p,b as l,m as d,p as n,d as c,f as h,a as u,r as v}from"./middleware-CJSowZY0.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-CJSowZY0.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},l=e=>{const t=atob(e),f=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)f[o]=t.codePointAt(o)??0;return f},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},A=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},b=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[i,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[i,"date",b(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const u=b(r[c],t+1);c===w?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:u,writable:!0}):n[c]=u}const s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(b(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[b(r,t+1),b(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>b(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>b(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!A(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,a={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=b(n,t+1);r===w?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===w?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=l(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(g,s)?g[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(a=>y(a,t+1))}const f=e,o={};for(const a of Object.keys(f)){const r=y(f[a],t+1);a===w?Object.defineProperty(o,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[a]=r}return o};export{y as d,b as e,A as i};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-CJSowZY0.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/dist/types.d.mts
CHANGED
|
@@ -2025,10 +2025,25 @@ interface SpanHandle {
|
|
|
2025
2025
|
* it in a bug report, to build a `traceparent` for a hand-rolled outbound
|
|
2026
2026
|
* call, or to parent a third-party library's spans onto this request.
|
|
2027
2027
|
*/
|
|
2028
|
-
spanContext: () =>
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2028
|
+
spanContext: () => SpanContextIds;
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* A span's W3C ids plus the trace's settled sampling verdict.
|
|
2032
|
+
*
|
|
2033
|
+
* `sampled` is the propagated head decision — absent means none reached this
|
|
2034
|
+
* tier, which every consumer reads as keep. It rides with the ids because
|
|
2035
|
+
* everything that announces this span downstream from them (a hand-built
|
|
2036
|
+
* `traceparent`, an `@opentelemetry/api` `SpanContext`) needs the flag in the
|
|
2037
|
+
* same breath: claiming SAMPLED on a trace that was sampled out leaves a
|
|
2038
|
+
* collector holding the middle of a trace nobody kept.
|
|
2039
|
+
*/
|
|
2040
|
+
interface SpanContextIds {
|
|
2041
|
+
/** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
|
|
2042
|
+
sampled?: boolean;
|
|
2043
|
+
/** This span's id (16-hex). */
|
|
2044
|
+
spanId: string;
|
|
2045
|
+
/** The trace this span belongs to (32-hex). */
|
|
2046
|
+
traceId: string;
|
|
2032
2047
|
}
|
|
2033
2048
|
/**
|
|
2034
2049
|
* A causal reference to a span in another trace (OTel `Span.links`). Ids are
|
|
@@ -2108,10 +2123,35 @@ interface SpanOptions {
|
|
|
2108
2123
|
* @param attributes Either a plain attribute bag to stamp on the span at start
|
|
2109
2124
|
* (normalized like a log line's `fields`), or a {@link SpanOptions} object when
|
|
2110
2125
|
* you need `kind` or `links`. It is read as options only when *every* key is one
|
|
2111
|
-
* of `attributes`/`kind`/`links
|
|
2112
|
-
*
|
|
2126
|
+
* of `attributes`/`kind`/`links` AND a `kind`, if present, actually names a
|
|
2127
|
+
* {@link SpanKind}; `{ attributes: { kind: "premium" } }` is the explicit form if
|
|
2128
|
+
* your own attributes happen to be named that.
|
|
2129
|
+
* @param identity Adapter-only: record the span under ids the caller has ALREADY
|
|
2130
|
+
* published (see {@link SpanIdentity}). A handler never passes this — it exists
|
|
2131
|
+
* so the `@opentelemetry/api` bridge, which must hand a library a `SpanContext`
|
|
2132
|
+
* synchronously, is recorded under the id it handed out rather than a phantom.
|
|
2113
2133
|
*/
|
|
2114
|
-
type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions) => Promise<T>;
|
|
2134
|
+
type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
|
|
2135
|
+
/**
|
|
2136
|
+
* Caller-supplied ids for one `ctx.trace` span — the tracer's fourth argument.
|
|
2137
|
+
*
|
|
2138
|
+
* For adapters that must publish a span's identity BEFORE the body runs: the
|
|
2139
|
+
* `@opentelemetry/api` bridge returns a `SpanContext` synchronously from
|
|
2140
|
+
* `startSpan` and a library builds a `traceparent` from it, so the span has to be
|
|
2141
|
+
* recorded under the id already announced or every downstream span parents to an
|
|
2142
|
+
* id that never reaches the collector. `parentSpanId` lets such an adapter
|
|
2143
|
+
* express its own parent/child structure without an ambient span stack.
|
|
2144
|
+
*
|
|
2145
|
+
* Both ids are required: an adapter that has published one has published the
|
|
2146
|
+
* other, and `identity` is itself optional — omitting it, not passing a partial
|
|
2147
|
+
* object, is how a caller says "no adapter involved".
|
|
2148
|
+
*/
|
|
2149
|
+
interface SpanIdentity {
|
|
2150
|
+
/** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
|
|
2151
|
+
parentSpanId: string;
|
|
2152
|
+
/** Record the span under this id (16-hex) instead of a freshly minted one. */
|
|
2153
|
+
spanId: string;
|
|
2154
|
+
}
|
|
2115
2155
|
/**
|
|
2116
2156
|
* `ctx.span` — a handle onto **this request's own span**, and with it the
|
|
2117
2157
|
* wide-event API.
|
|
@@ -2206,10 +2246,18 @@ interface QueryCtx {
|
|
|
2206
2246
|
*/
|
|
2207
2247
|
readonly env?: Record<string, unknown>;
|
|
2208
2248
|
/**
|
|
2209
|
-
* The caller's IP for this request
|
|
2210
|
-
*
|
|
2211
|
-
*
|
|
2212
|
-
*
|
|
2249
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2250
|
+
* says who called.
|
|
2251
|
+
*
|
|
2252
|
+
* Populated only from Cloudflare's `CF-Connecting-IP`, forwarded server-side,
|
|
2253
|
+
* and only while running ON Cloudflare — that is the one place the edge stamps
|
|
2254
|
+
* the header over anything the client sent. On any other host it is a header
|
|
2255
|
+
* the caller typed, so the runtime resolves nothing rather than hand a handler
|
|
2256
|
+
* an attacker-chosen address; a rate limit keyed on a forgeable `ip` is worse
|
|
2257
|
+
* than no limit, because it reads as enforced. `undefined` therefore covers: a
|
|
2258
|
+
* live-subscription re-run, a server-initiated dispatch, and ANY non-Cloudflare
|
|
2259
|
+
* host. A convenient rate-limit key for anonymous traffic on Cloudflare;
|
|
2260
|
+
* elsewhere, key on something the caller cannot choose.
|
|
2213
2261
|
*/
|
|
2214
2262
|
readonly ip?: string;
|
|
2215
2263
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2262,10 +2310,9 @@ interface MutationCtx {
|
|
|
2262
2310
|
*/
|
|
2263
2311
|
readonly env?: Record<string, unknown>;
|
|
2264
2312
|
/**
|
|
2265
|
-
* The caller's IP for this request
|
|
2266
|
-
*
|
|
2267
|
-
*
|
|
2268
|
-
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2313
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2314
|
+
* says who called. Identical to {@link QueryCtx.ip} — see there for which
|
|
2315
|
+
* host populates it and why every other one deliberately does not.
|
|
2269
2316
|
*/
|
|
2270
2317
|
readonly ip?: string;
|
|
2271
2318
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2340,10 +2387,9 @@ interface ActionCtx {
|
|
|
2340
2387
|
readonly env?: Record<string, unknown>;
|
|
2341
2388
|
readonly fetch: typeof globalThis.fetch;
|
|
2342
2389
|
/**
|
|
2343
|
-
* The caller's IP for this request
|
|
2344
|
-
*
|
|
2345
|
-
*
|
|
2346
|
-
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2390
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2391
|
+
* says who called. Identical to {@link QueryCtx.ip} — see there for which
|
|
2392
|
+
* host populates it and why every other one deliberately does not.
|
|
2347
2393
|
*/
|
|
2348
2394
|
readonly ip?: string;
|
|
2349
2395
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2385,4 +2431,4 @@ interface ActionCtx {
|
|
|
2385
2431
|
*/
|
|
2386
2432
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
2387
2433
|
declare const anyApi: AnyApi;
|
|
2388
|
-
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
|
2434
|
+
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
package/dist/types.d.ts
CHANGED
|
@@ -2025,10 +2025,25 @@ interface SpanHandle {
|
|
|
2025
2025
|
* it in a bug report, to build a `traceparent` for a hand-rolled outbound
|
|
2026
2026
|
* call, or to parent a third-party library's spans onto this request.
|
|
2027
2027
|
*/
|
|
2028
|
-
spanContext: () =>
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2028
|
+
spanContext: () => SpanContextIds;
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* A span's W3C ids plus the trace's settled sampling verdict.
|
|
2032
|
+
*
|
|
2033
|
+
* `sampled` is the propagated head decision — absent means none reached this
|
|
2034
|
+
* tier, which every consumer reads as keep. It rides with the ids because
|
|
2035
|
+
* everything that announces this span downstream from them (a hand-built
|
|
2036
|
+
* `traceparent`, an `@opentelemetry/api` `SpanContext`) needs the flag in the
|
|
2037
|
+
* same breath: claiming SAMPLED on a trace that was sampled out leaves a
|
|
2038
|
+
* collector holding the middle of a trace nobody kept.
|
|
2039
|
+
*/
|
|
2040
|
+
interface SpanContextIds {
|
|
2041
|
+
/** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
|
|
2042
|
+
sampled?: boolean;
|
|
2043
|
+
/** This span's id (16-hex). */
|
|
2044
|
+
spanId: string;
|
|
2045
|
+
/** The trace this span belongs to (32-hex). */
|
|
2046
|
+
traceId: string;
|
|
2032
2047
|
}
|
|
2033
2048
|
/**
|
|
2034
2049
|
* A causal reference to a span in another trace (OTel `Span.links`). Ids are
|
|
@@ -2108,10 +2123,35 @@ interface SpanOptions {
|
|
|
2108
2123
|
* @param attributes Either a plain attribute bag to stamp on the span at start
|
|
2109
2124
|
* (normalized like a log line's `fields`), or a {@link SpanOptions} object when
|
|
2110
2125
|
* you need `kind` or `links`. It is read as options only when *every* key is one
|
|
2111
|
-
* of `attributes`/`kind`/`links
|
|
2112
|
-
*
|
|
2126
|
+
* of `attributes`/`kind`/`links` AND a `kind`, if present, actually names a
|
|
2127
|
+
* {@link SpanKind}; `{ attributes: { kind: "premium" } }` is the explicit form if
|
|
2128
|
+
* your own attributes happen to be named that.
|
|
2129
|
+
* @param identity Adapter-only: record the span under ids the caller has ALREADY
|
|
2130
|
+
* published (see {@link SpanIdentity}). A handler never passes this — it exists
|
|
2131
|
+
* so the `@opentelemetry/api` bridge, which must hand a library a `SpanContext`
|
|
2132
|
+
* synchronously, is recorded under the id it handed out rather than a phantom.
|
|
2113
2133
|
*/
|
|
2114
|
-
type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions) => Promise<T>;
|
|
2134
|
+
type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
|
|
2135
|
+
/**
|
|
2136
|
+
* Caller-supplied ids for one `ctx.trace` span — the tracer's fourth argument.
|
|
2137
|
+
*
|
|
2138
|
+
* For adapters that must publish a span's identity BEFORE the body runs: the
|
|
2139
|
+
* `@opentelemetry/api` bridge returns a `SpanContext` synchronously from
|
|
2140
|
+
* `startSpan` and a library builds a `traceparent` from it, so the span has to be
|
|
2141
|
+
* recorded under the id already announced or every downstream span parents to an
|
|
2142
|
+
* id that never reaches the collector. `parentSpanId` lets such an adapter
|
|
2143
|
+
* express its own parent/child structure without an ambient span stack.
|
|
2144
|
+
*
|
|
2145
|
+
* Both ids are required: an adapter that has published one has published the
|
|
2146
|
+
* other, and `identity` is itself optional — omitting it, not passing a partial
|
|
2147
|
+
* object, is how a caller says "no adapter involved".
|
|
2148
|
+
*/
|
|
2149
|
+
interface SpanIdentity {
|
|
2150
|
+
/** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
|
|
2151
|
+
parentSpanId: string;
|
|
2152
|
+
/** Record the span under this id (16-hex) instead of a freshly minted one. */
|
|
2153
|
+
spanId: string;
|
|
2154
|
+
}
|
|
2115
2155
|
/**
|
|
2116
2156
|
* `ctx.span` — a handle onto **this request's own span**, and with it the
|
|
2117
2157
|
* wide-event API.
|
|
@@ -2206,10 +2246,18 @@ interface QueryCtx {
|
|
|
2206
2246
|
*/
|
|
2207
2247
|
readonly env?: Record<string, unknown>;
|
|
2208
2248
|
/**
|
|
2209
|
-
* The caller's IP for this request
|
|
2210
|
-
*
|
|
2211
|
-
*
|
|
2212
|
-
*
|
|
2249
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2250
|
+
* says who called.
|
|
2251
|
+
*
|
|
2252
|
+
* Populated only from Cloudflare's `CF-Connecting-IP`, forwarded server-side,
|
|
2253
|
+
* and only while running ON Cloudflare — that is the one place the edge stamps
|
|
2254
|
+
* the header over anything the client sent. On any other host it is a header
|
|
2255
|
+
* the caller typed, so the runtime resolves nothing rather than hand a handler
|
|
2256
|
+
* an attacker-chosen address; a rate limit keyed on a forgeable `ip` is worse
|
|
2257
|
+
* than no limit, because it reads as enforced. `undefined` therefore covers: a
|
|
2258
|
+
* live-subscription re-run, a server-initiated dispatch, and ANY non-Cloudflare
|
|
2259
|
+
* host. A convenient rate-limit key for anonymous traffic on Cloudflare;
|
|
2260
|
+
* elsewhere, key on something the caller cannot choose.
|
|
2213
2261
|
*/
|
|
2214
2262
|
readonly ip?: string;
|
|
2215
2263
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2262,10 +2310,9 @@ interface MutationCtx {
|
|
|
2262
2310
|
*/
|
|
2263
2311
|
readonly env?: Record<string, unknown>;
|
|
2264
2312
|
/**
|
|
2265
|
-
* The caller's IP for this request
|
|
2266
|
-
*
|
|
2267
|
-
*
|
|
2268
|
-
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2313
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2314
|
+
* says who called. Identical to {@link QueryCtx.ip} — see there for which
|
|
2315
|
+
* host populates it and why every other one deliberately does not.
|
|
2269
2316
|
*/
|
|
2270
2317
|
readonly ip?: string;
|
|
2271
2318
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2340,10 +2387,9 @@ interface ActionCtx {
|
|
|
2340
2387
|
readonly env?: Record<string, unknown>;
|
|
2341
2388
|
readonly fetch: typeof globalThis.fetch;
|
|
2342
2389
|
/**
|
|
2343
|
-
* The caller's IP for this request
|
|
2344
|
-
*
|
|
2345
|
-
*
|
|
2346
|
-
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2390
|
+
* The caller's IP for this request, or `undefined` when nothing trustworthy
|
|
2391
|
+
* says who called. Identical to {@link QueryCtx.ip} — see there for which
|
|
2392
|
+
* host populates it and why every other one deliberately does not.
|
|
2347
2393
|
*/
|
|
2348
2394
|
readonly ip?: string;
|
|
2349
2395
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
@@ -2385,4 +2431,4 @@ interface ActionCtx {
|
|
|
2385
2431
|
*/
|
|
2386
2432
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
2387
2433
|
declare const anyApi: AnyApi;
|
|
2388
|
-
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
|
2434
|
+
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.106",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -66,9 +66,9 @@
|
|
|
66
66
|
"access": "public"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/values": "1.0.0-alpha.
|
|
69
|
+
"@lunora/errors": "1.0.0-alpha.34",
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.56",
|
|
71
|
+
"@lunora/values": "1.0.0-alpha.42",
|
|
72
72
|
"drizzle-orm": "^0.45.2",
|
|
73
73
|
"hono": "^4.13.1"
|
|
74
74
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const w=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},p=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},i="$lunora.wire$";const m="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},b=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[i,"bigint",e.toString()];if(a==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(a!=="object")return e;if(e instanceof Date)return[i,"date",b(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const u=b(r[c],t+1);c===m?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:u,writable:!0}):n[c]=u}const s=[i,"error",r.name,r.message,n];return r.cause!==void 0&&s.push(b(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[b(r,t+1),b(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>b(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",w(s)]:[i,"bytes",w(s),n]}if(Array.isArray(e)){const r=e.map(n=>b(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=b(n,t+1);r===m?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3],s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===m?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=p(r),s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(g,s)?g[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const a=e,o={};for(const f of Object.keys(a)){const r=y(a[f],t+1);f===m?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o};export{y as d,b as e,l as i};
|