@brightbeamai/chap-coordinator 0.2.9 → 0.2.12

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/jsonrpc.cjs CHANGED
@@ -37,6 +37,7 @@ var E = {
37
37
  NOT_AUTHORISED: -32011,
38
38
  PATCH_FAILED: -32012,
39
39
  REVIEW_LAPSED: -32013,
40
+ REVIEW_ALREADY_OPEN: -32014,
40
41
  // whisper/1.0 profile (profiles/whisper.md S6)
41
42
  WHISPER_ALREADY_ANSWERED: -32020,
42
43
  WHISPER_LAPSED: -32021,
@@ -63,6 +64,7 @@ var E = {
63
64
  SIG_KEY_NOT_FOUND: -32071,
64
65
  SIG_KEY_REVOKED: -32072,
65
66
  SIG_ROTATION_KEY_MISMATCH: -32073,
67
+ SIG_ARTEFACT_DIGEST_MISMATCH: -32074,
66
68
  // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)
67
69
  SCITT_UNREACHABLE: -32080,
68
70
  SCITT_STATEMENT_REJECTED: -32081,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jsonrpc.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASO,IAAM,IAAI;AAAA;AAAA,EAEf,OAAU;AAAA,EACV,SAAU;AAAA,EACV,QAAU;AAAA,EACV,QAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,cAAgB;AAAA,EAChB,eAAgB;AAAA;AAAA,EAGhB,0BAA6B;AAAA,EAC7B,gBAA6B;AAAA,EAC7B,2BAA6B;AAAA;AAAA,EAG7B,yBAAyB;AAAA,EACzB,qBAAyB;AAAA,EACzB,wBAAyB;AAAA,EACzB,oBAAyB;AAAA;AAAA,EAGzB,uBAAyB;AAAA,EACzB,uBAAyB;AAAA;AAAA,EAGzB,wCAAwC;AAAA,EACxC,0BAAwC;AAAA,EACxC,8BAAwC;AAAA;AAAA,EAGxC,0BAA6B;AAAA,EAC7B,wBAA6B;AAAA,EAC7B,4BAA6B;AAAA,EAC7B,0BAA6B;AAAA;AAAA,EAG7B,mBAA2B;AAAA,EAC3B,mBAA2B;AAAA,EAC3B,iBAA2B;AAAA,EAC3B,2BAA2B;AAAA;AAAA,EAG3B,mBAA0B;AAAA,EAC1B,0BAA0B;AAAA,EAC1B,uBAA0B;AAAA;AAAA,EAG1B,uBAAuB;AAAA,EACvB,oBAAuB;AAAA,EACvB,mBAAuB;AAAA,EACvB,oBAAuB;AAAA;AAAA,EAGvB,eAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,uBAA2B;AAAA,EAC3B,mBAA2B;AAAA;AAAA,EAG3B,8BAAgC;AAAA,EAChC,0BAAgC;AAAA,EAChC,mCAAmC;AAAA,EACnC,0BAAgC;AAAA,EAChC,8BAAgC;AAAA,EAChC,4BAAgC;AAAA,EAChC,gCAAgC;AAClC;AAEO,SAAS,SAAS,MAAc,SAAiB,MAAgB;AACtE,SAAO,EAAE,MAAM,SAAS,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC,EAAG;AAClE;AAEO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,IAAI;AACV,SAAO,EAAE,YAAY;AACvB;","names":[]}
1
+ {"version":3,"sources":["../src/jsonrpc.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n REVIEW_ALREADY_OPEN: -32014,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n SIG_ARTEFACT_DIGEST_MISMATCH: -32074,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASO,IAAM,IAAI;AAAA;AAAA,EAEf,OAAU;AAAA,EACV,SAAU;AAAA,EACV,QAAU;AAAA,EACV,QAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,cAAgB;AAAA,EAChB,eAAgB;AAAA,EAChB,qBAAqB;AAAA;AAAA,EAGrB,0BAA6B;AAAA,EAC7B,gBAA6B;AAAA,EAC7B,2BAA6B;AAAA;AAAA,EAG7B,yBAAyB;AAAA,EACzB,qBAAyB;AAAA,EACzB,wBAAyB;AAAA,EACzB,oBAAyB;AAAA;AAAA,EAGzB,uBAAyB;AAAA,EACzB,uBAAyB;AAAA;AAAA,EAGzB,wCAAwC;AAAA,EACxC,0BAAwC;AAAA,EACxC,8BAAwC;AAAA;AAAA,EAGxC,0BAA6B;AAAA,EAC7B,wBAA6B;AAAA,EAC7B,4BAA6B;AAAA,EAC7B,0BAA6B;AAAA;AAAA,EAG7B,mBAA2B;AAAA,EAC3B,mBAA2B;AAAA,EAC3B,iBAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,8BAA8B;AAAA;AAAA,EAG9B,mBAA0B;AAAA,EAC1B,0BAA0B;AAAA,EAC1B,uBAA0B;AAAA;AAAA,EAG1B,uBAAuB;AAAA,EACvB,oBAAuB;AAAA,EACvB,mBAAuB;AAAA,EACvB,oBAAuB;AAAA;AAAA,EAGvB,eAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,uBAA2B;AAAA,EAC3B,mBAA2B;AAAA;AAAA,EAG3B,8BAAgC;AAAA,EAChC,0BAAgC;AAAA,EAChC,mCAAmC;AAAA,EACnC,0BAAgC;AAAA,EAChC,8BAAgC;AAAA,EAChC,4BAAgC;AAAA,EAChC,gCAAgC;AAClC;AAEO,SAAS,SAAS,MAAc,SAAiB,MAAgB;AACtE,SAAO,EAAE,MAAM,SAAS,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC,EAAG;AAClE;AAEO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,IAAI;AACV,SAAO,EAAE,YAAY;AACvB;","names":[]}
@@ -16,6 +16,7 @@ declare const E: {
16
16
  readonly NOT_AUTHORISED: -32011;
17
17
  readonly PATCH_FAILED: -32012;
18
18
  readonly REVIEW_LAPSED: -32013;
19
+ readonly REVIEW_ALREADY_OPEN: -32014;
19
20
  readonly WHISPER_ALREADY_ANSWERED: -32020;
20
21
  readonly WHISPER_LAPSED: -32021;
21
22
  readonly WHISPER_OPTION_NOT_IN_SET: -32022;
@@ -36,6 +37,7 @@ declare const E: {
36
37
  readonly SIG_KEY_NOT_FOUND: -32071;
37
38
  readonly SIG_KEY_REVOKED: -32072;
38
39
  readonly SIG_ROTATION_KEY_MISMATCH: -32073;
40
+ readonly SIG_ARTEFACT_DIGEST_MISMATCH: -32074;
39
41
  readonly SCITT_UNREACHABLE: -32080;
40
42
  readonly SCITT_STATEMENT_REJECTED: -32081;
41
43
  readonly SCITT_RECEIPT_INVALID: -32082;
package/dist/jsonrpc.d.ts CHANGED
@@ -16,6 +16,7 @@ declare const E: {
16
16
  readonly NOT_AUTHORISED: -32011;
17
17
  readonly PATCH_FAILED: -32012;
18
18
  readonly REVIEW_LAPSED: -32013;
19
+ readonly REVIEW_ALREADY_OPEN: -32014;
19
20
  readonly WHISPER_ALREADY_ANSWERED: -32020;
20
21
  readonly WHISPER_LAPSED: -32021;
21
22
  readonly WHISPER_OPTION_NOT_IN_SET: -32022;
@@ -36,6 +37,7 @@ declare const E: {
36
37
  readonly SIG_KEY_NOT_FOUND: -32071;
37
38
  readonly SIG_KEY_REVOKED: -32072;
38
39
  readonly SIG_ROTATION_KEY_MISMATCH: -32073;
40
+ readonly SIG_ARTEFACT_DIGEST_MISMATCH: -32074;
39
41
  readonly SCITT_UNREACHABLE: -32080;
40
42
  readonly SCITT_STATEMENT_REJECTED: -32081;
41
43
  readonly SCITT_RECEIPT_INVALID: -32082;
package/dist/jsonrpc.js CHANGED
@@ -11,6 +11,7 @@ var E = {
11
11
  NOT_AUTHORISED: -32011,
12
12
  PATCH_FAILED: -32012,
13
13
  REVIEW_LAPSED: -32013,
14
+ REVIEW_ALREADY_OPEN: -32014,
14
15
  // whisper/1.0 profile (profiles/whisper.md S6)
15
16
  WHISPER_ALREADY_ANSWERED: -32020,
16
17
  WHISPER_LAPSED: -32021,
@@ -37,6 +38,7 @@ var E = {
37
38
  SIG_KEY_NOT_FOUND: -32071,
38
39
  SIG_KEY_REVOKED: -32072,
39
40
  SIG_ROTATION_KEY_MISMATCH: -32073,
41
+ SIG_ARTEFACT_DIGEST_MISMATCH: -32074,
40
42
  // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)
41
43
  SCITT_UNREACHABLE: -32080,
42
44
  SCITT_STATEMENT_REJECTED: -32081,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jsonrpc.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n"],"mappings":";AASO,IAAM,IAAI;AAAA;AAAA,EAEf,OAAU;AAAA,EACV,SAAU;AAAA,EACV,QAAU;AAAA,EACV,QAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,cAAgB;AAAA,EAChB,eAAgB;AAAA;AAAA,EAGhB,0BAA6B;AAAA,EAC7B,gBAA6B;AAAA,EAC7B,2BAA6B;AAAA;AAAA,EAG7B,yBAAyB;AAAA,EACzB,qBAAyB;AAAA,EACzB,wBAAyB;AAAA,EACzB,oBAAyB;AAAA;AAAA,EAGzB,uBAAyB;AAAA,EACzB,uBAAyB;AAAA;AAAA,EAGzB,wCAAwC;AAAA,EACxC,0BAAwC;AAAA,EACxC,8BAAwC;AAAA;AAAA,EAGxC,0BAA6B;AAAA,EAC7B,wBAA6B;AAAA,EAC7B,4BAA6B;AAAA,EAC7B,0BAA6B;AAAA;AAAA,EAG7B,mBAA2B;AAAA,EAC3B,mBAA2B;AAAA,EAC3B,iBAA2B;AAAA,EAC3B,2BAA2B;AAAA;AAAA,EAG3B,mBAA0B;AAAA,EAC1B,0BAA0B;AAAA,EAC1B,uBAA0B;AAAA;AAAA,EAG1B,uBAAuB;AAAA,EACvB,oBAAuB;AAAA,EACvB,mBAAuB;AAAA,EACvB,oBAAuB;AAAA;AAAA,EAGvB,eAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,uBAA2B;AAAA,EAC3B,mBAA2B;AAAA;AAAA,EAG3B,8BAAgC;AAAA,EAChC,0BAAgC;AAAA,EAChC,mCAAmC;AAAA,EACnC,0BAAgC;AAAA,EAChC,8BAAgC;AAAA,EAChC,4BAAgC;AAAA,EAChC,gCAAgC;AAClC;AAEO,SAAS,SAAS,MAAc,SAAiB,MAAgB;AACtE,SAAO,EAAE,MAAM,SAAS,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC,EAAG;AAClE;AAEO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,IAAI;AACV,SAAO,EAAE,YAAY;AACvB;","names":[]}
1
+ {"version":3,"sources":["../src/jsonrpc.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/jsonrpc\n *\n * Error codes (JSON-RPC standard + CHAP private range) and helpers.\n *\n * Error code allocations come directly from each profile spec. See\n * profiles/*.md for the authoritative definitions.\n */\n\nexport const E = {\n // JSON-RPC 2.0 standard\n PARSE: -32700,\n REQUEST: -32600,\n METHOD: -32601,\n PARAMS: -32602,\n INTERNAL: -32603,\n\n // review/1.0 profile\n NOT_REVIEWABLE: -32010,\n NOT_AUTHORISED: -32011,\n PATCH_FAILED: -32012,\n REVIEW_LAPSED: -32013,\n REVIEW_ALREADY_OPEN: -32014,\n\n // whisper/1.0 profile (profiles/whisper.md S6)\n WHISPER_ALREADY_ANSWERED: -32020,\n WHISPER_LAPSED: -32021,\n WHISPER_OPTION_NOT_IN_SET: -32022,\n\n // deliberation/1.0 profile (profiles/deliberation.md S5)\n DELIB_VOTER_NOT_IN_LIST: -32030,\n DELIB_ALREADY_VOTED: -32031,\n DELIB_CLOSED_OR_LAPSED: -32032,\n DELIB_UNKNOWN_RULE: -32033,\n\n // modes/1.0 profile (profiles/modes.md S6)\n MODE_CEILING_EXCEEDED: -32040,\n MODE_STEP_UP_REQUIRED: -32041,\n\n // handoff/1.0 profile (profiles/handoff.md S6)\n HANDOFF_TASKS_NOT_ASSIGNED_TO_PROPOSER: -32050,\n HANDOFF_ALREADY_RESOLVED: -32051,\n HANDOFF_RECIPIENT_NOT_MEMBER: -32052,\n\n // control/1.0 profile (profiles/control.md S6)\n CONTROL_STEP_UP_REQUIRED: -32060,\n CONTROL_NOT_AUTHORISED: -32061,\n CONTROL_SNAPSHOT_NOT_FOUND: -32062,\n CONTROL_WORKSPACE_PAUSED: -32063,\n\n // security-signed/1.0 profile (profiles/security-signed.md S7)\n SIG_VERIFY_FAILED: -32070,\n SIG_KEY_NOT_FOUND: -32071,\n SIG_KEY_REVOKED: -32072,\n SIG_ROTATION_KEY_MISMATCH: -32073,\n SIG_ARTEFACT_DIGEST_MISMATCH: -32074,\n\n // audit-scitt/1.0 profile (profiles/audit-scitt.md S8)\n SCITT_UNREACHABLE: -32080,\n SCITT_STATEMENT_REJECTED: -32081,\n SCITT_RECEIPT_INVALID: -32082,\n\n // identity-oidc/1.0 profile (profiles/identity-oidc.md S8)\n OIDC_STEP_UP_REQUIRED: -32402,\n OIDC_TOKEN_INVALID: -32403,\n OIDC_CNF_MISMATCH: -32404,\n OIDC_SCOPE_MISSING: -32405,\n\n // identity-vc/1.0 profile (profiles/identity-vc.md S8)\n VC_VP_INVALID: -32410,\n VC_HOLDER_BINDING_INVALID: -32411,\n VC_CREDENTIAL_REVOKED: -32412,\n VC_SCHEMA_UNKNOWN: -32413,\n\n // routing/1.0 profile (profiles/routing.md S3-S5)\n ROUTING_NO_ELIGIBLE_ASSIGNEE: -32510,\n ROUTING_POLICY_VIOLATION: -32511,\n ROUTING_AUTO_ESCALATION_TRIGGERED: -32512,\n ROUTING_CANDIDATES_EMPTY: -32513,\n ROUTING_DEPTH_NOT_APPLICABLE: -32514,\n ROUTING_POLICY_UNREACHABLE: -32515,\n ROUTING_ESC_TARGET_UNAVAILABLE: -32516,\n} as const;\n\nexport function rpcError(code: number, message: string, data?: unknown) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\nexport function isValidEnvelope(env: unknown): boolean {\n if (typeof env !== \"object\" || env === null) return false;\n const e = env as Record<string, unknown>;\n return e.jsonrpc === \"2.0\";\n}\n"],"mappings":";AASO,IAAM,IAAI;AAAA;AAAA,EAEf,OAAU;AAAA,EACV,SAAU;AAAA,EACV,QAAU;AAAA,EACV,QAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,cAAgB;AAAA,EAChB,eAAgB;AAAA,EAChB,qBAAqB;AAAA;AAAA,EAGrB,0BAA6B;AAAA,EAC7B,gBAA6B;AAAA,EAC7B,2BAA6B;AAAA;AAAA,EAG7B,yBAAyB;AAAA,EACzB,qBAAyB;AAAA,EACzB,wBAAyB;AAAA,EACzB,oBAAyB;AAAA;AAAA,EAGzB,uBAAyB;AAAA,EACzB,uBAAyB;AAAA;AAAA,EAGzB,wCAAwC;AAAA,EACxC,0BAAwC;AAAA,EACxC,8BAAwC;AAAA;AAAA,EAGxC,0BAA6B;AAAA,EAC7B,wBAA6B;AAAA,EAC7B,4BAA6B;AAAA,EAC7B,0BAA6B;AAAA;AAAA,EAG7B,mBAA2B;AAAA,EAC3B,mBAA2B;AAAA,EAC3B,iBAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,8BAA8B;AAAA;AAAA,EAG9B,mBAA0B;AAAA,EAC1B,0BAA0B;AAAA,EAC1B,uBAA0B;AAAA;AAAA,EAG1B,uBAAuB;AAAA,EACvB,oBAAuB;AAAA,EACvB,mBAAuB;AAAA,EACvB,oBAAuB;AAAA;AAAA,EAGvB,eAA2B;AAAA,EAC3B,2BAA2B;AAAA,EAC3B,uBAA2B;AAAA,EAC3B,mBAA2B;AAAA;AAAA,EAG3B,8BAAgC;AAAA,EAChC,0BAAgC;AAAA,EAChC,mCAAmC;AAAA,EACnC,0BAAgC;AAAA,EAChC,8BAAgC;AAAA,EAChC,4BAAgC;AAAA,EAChC,gCAAgC;AAClC;AAEO,SAAS,SAAS,MAAc,SAAiB,MAAgB;AACtE,SAAO,EAAE,MAAM,SAAS,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC,EAAG;AAClE;AAEO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,IAAI;AACV,SAAO,EAAE,YAAY;AACvB;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/methods.ts"],"sourcesContent":["/**\n * Typed method definitions.\n *\n * Every CHAP method that ships in either reference implementation\n * gets a typed `Params` and `Result` shape here. The Coordinator's\n * typed facade (`coord.workspace.create`, `coord.task.complete`, …)\n * uses these types so callers get autocomplete and compile-time\n * checking without having to remember field names.\n *\n * These types are hand-maintained against the canonical JSON Schemas\n * under `schemas/`. A future revision will generate this file from\n * the schemas automatically; for now the source of truth remains\n * the running tests under `tests/`.\n *\n * Scope: 39 method handlers shipped by both v0.2 reference\n * implementations (Core + every shipped profile). Spec-only methods\n * are excluded - they would mislead callers into thinking the local\n * Coordinator can dispatch them.\n */\n\nimport type {\n ArtefactId, JsonPatchOp, ParticipantUri, TaskId,\n Workspace, WorkspaceId,\n} from \"./types.js\";\n\n// ---- shared building blocks ---------------------------------------\n\nexport interface WorkspaceParam { workspace: WorkspaceId }\nexport interface ActorParam { from: ParticipantUri }\nexport interface TaskParam { task_id: TaskId }\n\nexport interface OkResult { ok: true }\n\n// ============================================================\n// workspace.*\n// ============================================================\n\nexport interface WorkspaceCreateParams extends Partial<WorkspaceParam> {\n profiles?: string[];\n routing_policy_uri?: string;\n mode?: \"shadow\" | \"trial\" | \"production\";\n mode_ceiling?: \"shadow\" | \"trial\" | \"production\";\n}\nexport interface WorkspaceCreateResult { workspace: WorkspaceId }\n\nexport interface WorkspaceDescribeParams extends WorkspaceParam {}\nexport interface WorkspaceDescribeResult { workspace: Workspace }\n\nexport interface WorkspaceSetProfilesParams extends WorkspaceParam, ActorParam {\n profiles: string[];\n}\nexport type WorkspaceSetProfilesResult = OkResult;\n\n// ============================================================\n// participant.*\n// ============================================================\n\nexport interface ParticipantJoinParams extends WorkspaceParam, ActorParam {\n type: \"human\" | \"agent\" | \"service\" | \"group\" | \"workspace\";\n role?: string;\n scopes?: string[];\n capabilities?: Record<string, unknown>;\n oidc_token?: unknown;\n vc?: unknown;\n pubkey?: unknown;\n}\nexport type ParticipantJoinResult = OkResult;\n\nexport interface ParticipantLeaveParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ParticipantLeaveResult = OkResult;\n\nexport interface ParticipantRotateKeyParams extends WorkspaceParam, ActorParam {\n pubkey: unknown;\n reason?: string;\n}\nexport type ParticipantRotateKeyResult = OkResult;\n\nexport interface ParticipantRevokeKeyParams extends WorkspaceParam, ActorParam {\n kid: string;\n reason?: string;\n}\nexport type ParticipantRevokeKeyResult = OkResult;\n\n// ============================================================\n// task.*\n// ============================================================\n\nexport interface TaskCreateParams extends WorkspaceParam, ActorParam {\n kind: string;\n input: unknown;\n assignee?: ParticipantUri;\n to?: ParticipantUri; // alias for assignee\n routing_hints?: Record<string, unknown>;\n deadline?: string;\n idempotency_key?: string;\n}\nexport interface TaskCreateResult { task_id: TaskId }\n\nexport interface TaskUpdateParams extends WorkspaceParam, ActorParam, TaskParam {\n state?: string;\n output?: unknown;\n progress?: Record<string, unknown>;\n}\nexport type TaskUpdateResult = OkResult;\n\nexport interface TaskCompleteParams extends WorkspaceParam, ActorParam, TaskParam {\n output?: unknown;\n confidence?: number | string;\n}\nexport type TaskCompleteResult = OkResult;\n\n// ============================================================\n// review.* and decide.*\n// ============================================================\n\nexport interface ReviewRequestParams extends WorkspaceParam, ActorParam, TaskParam {\n artefact: unknown;\n to: ParticipantUri | ParticipantUri[];\n rule?: string;\n deadline?: string;\n}\nexport interface ReviewRequestResult { state: string; review_id: TaskId }\n\nexport interface DecideApproveParams extends WorkspaceParam, ActorParam, TaskParam {\n rationale?: string;\n}\nexport type DecideApproveResult = OkResult;\n\nexport interface DecideRejectParams extends WorkspaceParam, ActorParam, TaskParam {\n rationale: string;\n category?: string;\n}\nexport type DecideRejectResult = OkResult;\n\nexport interface DecideOverrideParams extends WorkspaceParam, ActorParam, TaskParam {\n diff: JsonPatchOp[];\n rationale: string;\n tags?: string[];\n policy_refs?: string[];\n logical_id?: string;\n instance_id?: string;\n intent_preserved?: boolean;\n based_on_artefact?: unknown;\n}\nexport interface DecideOverrideResult {\n state: \"completed\";\n override_artefact_id: ArtefactId;\n applied: unknown;\n}\n\nexport interface AbstainDeclareParams extends WorkspaceParam, ActorParam, TaskParam {\n category: string;\n rationale?: string;\n}\nexport type AbstainDeclareResult = OkResult;\n\nexport interface EscalateRaiseParams extends WorkspaceParam, ActorParam, TaskParam {\n to?: ParticipantUri;\n rationale?: string;\n}\nexport interface EscalateRaiseResult { ok: true; to?: ParticipantUri }\n\n// ============================================================\n// whisper.* (whisper/1.0)\n// ============================================================\n\nexport interface WhisperAskParams extends WorkspaceParam, ActorParam, TaskParam {\n to: ParticipantUri;\n question: string;\n options?: string[];\n default_on_lapse?: string;\n lapse_ms?: number;\n}\nexport interface WhisperAskResult { whisper_id: string }\n\nexport interface WhisperAnswerParams extends WorkspaceParam, ActorParam {\n whisper_id: string;\n answer: string;\n}\nexport type WhisperAnswerResult = OkResult;\n\n// ============================================================\n// deliberate.* (deliberation/1.0)\n// ============================================================\n\nexport interface DeliberateOpenParams extends WorkspaceParam, ActorParam, TaskParam {\n rule: Record<string, unknown>;\n proposition: unknown;\n voters: ParticipantUri[];\n}\nexport interface DeliberateOpenResult { deliberation_id: string }\n\nexport interface DeliberateCommentParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n text: string;\n}\nexport type DeliberateCommentResult = OkResult;\n\nexport interface DeliberateVoteParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n vote: \"yea\" | \"nay\" | \"abstain\";\n weight?: number;\n rationale?: string;\n}\nexport type DeliberateVoteResult = OkResult;\n\nexport interface DeliberateCloseParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n}\nexport interface DeliberateCloseResult { outcome: \"approved\" | \"rejected\" | \"no_quorum\" }\n\n// ============================================================\n// handoff.* (handoff/1.0)\n// ============================================================\n\nexport interface HandoffProposeParams extends WorkspaceParam, ActorParam {\n to: ParticipantUri;\n task_ids: TaskId[];\n summary: string;\n active_constraints?: Record<string, unknown>;\n}\nexport interface HandoffProposeResult { handoff_id: string }\n\nexport interface HandoffAcceptParams extends WorkspaceParam, ActorParam {\n handoff_id: string;\n}\nexport type HandoffAcceptResult = OkResult;\n\nexport interface HandoffDeclineParams extends WorkspaceParam, ActorParam {\n handoff_id: string;\n reason?: string;\n}\nexport type HandoffDeclineResult = OkResult;\n\n// ============================================================\n// control.* (control/1.0)\n// ============================================================\n\nexport interface ControlPauseParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ControlPauseResult = OkResult;\n\nexport interface ControlResumeParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ControlResumeResult = OkResult;\n\nexport interface ControlCancelParams extends WorkspaceParam, ActorParam, TaskParam {\n reason?: string;\n}\nexport type ControlCancelResult = OkResult;\n\nexport interface ControlSupersedeParams extends WorkspaceParam, ActorParam, TaskParam {\n replacement: unknown;\n logical_id?: string;\n intent_preserved?: boolean;\n reason?: string;\n}\nexport interface ControlSupersedeResult { artefact_id: ArtefactId }\n\nexport interface ControlSnapshotParams extends WorkspaceParam, ActorParam {\n label?: string;\n}\nexport interface ControlSnapshotResult { snapshot_id: string }\n\nexport interface ControlRollbackParams extends WorkspaceParam, ActorParam {\n snapshot_id: string;\n reason?: string;\n}\nexport type ControlRollbackResult = OkResult;\n\nexport interface ControlSetModeCeilingParams extends WorkspaceParam, ActorParam {\n ceiling: \"shadow\" | \"trial\" | \"production\";\n}\nexport type ControlSetModeCeilingResult = OkResult;\n\n// ============================================================\n// routing.* (routing/1.0)\n// ============================================================\n\nexport interface TaskRouteParams extends WorkspaceParam, ActorParam, TaskParam {\n candidates: ParticipantUri[];\n}\nexport interface TaskRouteResult {\n selected: ParticipantUri;\n rationale: Record<string, unknown>;\n}\n\nexport interface ReviewDepthParams extends WorkspaceParam, ActorParam, TaskParam {\n artefact?: unknown;\n hints?: Record<string, unknown>;\n}\nexport interface ReviewDepthResult {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling_probability?: number;\n rationale: Record<string, unknown>;\n}\n\nexport interface EscalateAutoParams extends WorkspaceParam, ActorParam, TaskParam {\n hints?: Record<string, unknown>;\n}\nexport interface EscalateAutoResult {\n escalated: boolean;\n to?: ParticipantUri;\n triggered_rule?: Record<string, unknown>;\n}\n\n// ============================================================\n// audit.* (Core + audit-scitt/1.0)\n// ============================================================\n\nexport interface AuditReadParams extends WorkspaceParam {\n from_seq?: number;\n limit?: number;\n}\nexport interface AuditReadResult { entries: unknown[] }\n\nexport interface AuditSubmitToScittParams extends WorkspaceParam, ActorParam {\n seq: number;\n statement?: Record<string, unknown>;\n}\nexport interface AuditSubmitToScittResult { receipt: Record<string, unknown> }\n\nexport interface AuditVerifyReceiptParams extends WorkspaceParam {\n receipt: Record<string, unknown>;\n}\nexport interface AuditVerifyReceiptResult { valid: boolean }\n\nexport interface AuditVerifyChainParams extends WorkspaceParam {\n from_seq?: number;\n to_seq?: number;\n}\nexport interface AuditVerifyChainResult {\n valid: boolean;\n breaks?: number[];\n}\n\n// ============================================================\n// Method-name → {params, result} map (single source of truth)\n// ============================================================\n\nexport interface MethodTable {\n \"workspace.create\": { params: WorkspaceCreateParams, result: WorkspaceCreateResult };\n \"workspace.describe\": { params: WorkspaceDescribeParams, result: WorkspaceDescribeResult };\n \"workspace.set_profiles\": { params: WorkspaceSetProfilesParams, result: WorkspaceSetProfilesResult };\n\n \"participant.join\": { params: ParticipantJoinParams, result: ParticipantJoinResult };\n \"participant.leave\": { params: ParticipantLeaveParams, result: ParticipantLeaveResult };\n \"participant.rotate_key\": { params: ParticipantRotateKeyParams, result: ParticipantRotateKeyResult };\n \"participant.revoke_key\": { params: ParticipantRevokeKeyParams, result: ParticipantRevokeKeyResult };\n\n \"task.create\": { params: TaskCreateParams, result: TaskCreateResult };\n \"task.update\": { params: TaskUpdateParams, result: TaskUpdateResult };\n \"task.complete\": { params: TaskCompleteParams, result: TaskCompleteResult };\n\n \"review.request\": { params: ReviewRequestParams, result: ReviewRequestResult };\n \"decide.approve\": { params: DecideApproveParams, result: DecideApproveResult };\n \"decide.reject\": { params: DecideRejectParams, result: DecideRejectResult };\n \"decide.override\": { params: DecideOverrideParams, result: DecideOverrideResult };\n \"abstain.declare\": { params: AbstainDeclareParams, result: AbstainDeclareResult };\n \"escalate.raise\": { params: EscalateRaiseParams, result: EscalateRaiseResult };\n\n \"whisper.ask\": { params: WhisperAskParams, result: WhisperAskResult };\n \"whisper.answer\": { params: WhisperAnswerParams, result: WhisperAnswerResult };\n\n \"deliberate.open\": { params: DeliberateOpenParams, result: DeliberateOpenResult };\n \"deliberate.comment\": { params: DeliberateCommentParams, result: DeliberateCommentResult };\n \"deliberate.vote\": { params: DeliberateVoteParams, result: DeliberateVoteResult };\n \"deliberate.close\": { params: DeliberateCloseParams, result: DeliberateCloseResult };\n\n \"handoff.propose\": { params: HandoffProposeParams, result: HandoffProposeResult };\n \"handoff.accept\": { params: HandoffAcceptParams, result: HandoffAcceptResult };\n \"handoff.decline\": { params: HandoffDeclineParams, result: HandoffDeclineResult };\n\n \"control.pause\": { params: ControlPauseParams, result: ControlPauseResult };\n \"control.resume\": { params: ControlResumeParams, result: ControlResumeResult };\n \"control.cancel\": { params: ControlCancelParams, result: ControlCancelResult };\n \"control.supersede\": { params: ControlSupersedeParams, result: ControlSupersedeResult };\n \"control.snapshot\": { params: ControlSnapshotParams, result: ControlSnapshotResult };\n \"control.rollback\": { params: ControlRollbackParams, result: ControlRollbackResult };\n \"control.set_mode_ceiling\": { params: ControlSetModeCeilingParams, result: ControlSetModeCeilingResult };\n\n \"task.route\": { params: TaskRouteParams, result: TaskRouteResult };\n \"review.depth\": { params: ReviewDepthParams, result: ReviewDepthResult };\n \"escalate.auto\": { params: EscalateAutoParams, result: EscalateAutoResult };\n\n \"audit.read\": { params: AuditReadParams, result: AuditReadResult };\n \"audit.submit_to_scitt\": { params: AuditSubmitToScittParams, result: AuditSubmitToScittResult };\n \"audit.verify_receipt\": { params: AuditVerifyReceiptParams, result: AuditVerifyReceiptResult };\n \"audit.verify_chain\": { params: AuditVerifyChainParams, result: AuditVerifyChainResult };\n}\n\nexport type MethodName = keyof MethodTable;\nexport type MethodParams<M extends MethodName> = MethodTable[M][\"params\"];\nexport type MethodResult<M extends MethodName> = MethodTable[M][\"result\"];\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../src/methods.ts"],"sourcesContent":["/**\n * Typed method definitions.\n *\n * Every CHAP method that ships in either reference implementation\n * gets a typed `Params` and `Result` shape here. The Coordinator's\n * typed facade (`coord.workspace.create`, `coord.task.complete`, …)\n * uses these types so callers get autocomplete and compile-time\n * checking without having to remember field names.\n *\n * These types are hand-maintained against the canonical JSON Schemas\n * under `schemas/`. A future revision will generate this file from\n * the schemas automatically; for now the source of truth remains\n * the running tests under `tests/`.\n *\n * Scope: 39 method handlers shipped by both v0.2 reference\n * implementations (Core + every shipped profile). Spec-only methods\n * are excluded - they would mislead callers into thinking the local\n * Coordinator can dispatch them.\n */\n\nimport type {\n ArtefactId, JsonPatchOp, ParticipantUri, TaskId,\n Workspace, WorkspaceId,\n} from \"./types.js\";\n\n// ---- shared building blocks ---------------------------------------\n\nexport interface WorkspaceParam { workspace: WorkspaceId }\nexport interface ActorParam { from: ParticipantUri }\nexport interface TaskParam { task_id: TaskId }\n\nexport interface OkResult { ok: true }\n\n// ============================================================\n// workspace.*\n// ============================================================\n\nexport interface WorkspaceCreateParams extends Partial<WorkspaceParam> {\n profiles?: string[];\n routing_policy_uri?: string;\n mode?: \"shadow\" | \"trial\" | \"production\";\n mode_ceiling?: \"shadow\" | \"trial\" | \"production\";\n}\nexport interface WorkspaceCreateResult { workspace: WorkspaceId }\n\nexport interface WorkspaceDescribeParams extends WorkspaceParam {}\nexport interface WorkspaceDescribeResult { workspace: Workspace }\n\nexport interface WorkspaceSetProfilesParams extends WorkspaceParam, ActorParam {\n profiles: string[];\n}\nexport type WorkspaceSetProfilesResult = OkResult;\n\n// ============================================================\n// participant.*\n// ============================================================\n\nexport interface ParticipantJoinParams extends WorkspaceParam, ActorParam {\n type: \"human\" | \"agent\" | \"service\" | \"group\" | \"workspace\";\n role?: string;\n scopes?: string[];\n capabilities?: Record<string, unknown>;\n oidc_token?: unknown;\n vc?: unknown;\n pubkey?: unknown;\n}\nexport type ParticipantJoinResult = OkResult;\n\nexport interface ParticipantLeaveParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ParticipantLeaveResult = OkResult;\n\nexport interface ParticipantRotateKeyParams extends WorkspaceParam, ActorParam {\n pubkey: unknown;\n reason?: string;\n}\nexport type ParticipantRotateKeyResult = OkResult;\n\nexport interface ParticipantRevokeKeyParams extends WorkspaceParam, ActorParam {\n kid: string;\n reason?: string;\n}\nexport type ParticipantRevokeKeyResult = OkResult;\n\n// ============================================================\n// task.*\n// ============================================================\n\nexport interface TaskCreateParams extends WorkspaceParam, ActorParam {\n kind: string;\n input: unknown;\n assignee?: ParticipantUri;\n to?: ParticipantUri; // alias for assignee\n routing_hints?: Record<string, unknown>;\n deadline?: string;\n idempotency_key?: string;\n}\nexport interface TaskCreateResult { task_id: TaskId }\n\nexport interface TaskUpdateParams extends WorkspaceParam, ActorParam, TaskParam {\n state?: string;\n output?: unknown;\n progress?: Record<string, unknown>;\n}\nexport type TaskUpdateResult = OkResult;\n\nexport interface TaskCompleteParams extends WorkspaceParam, ActorParam, TaskParam {\n output?: unknown;\n confidence?: number | string;\n}\nexport type TaskCompleteResult = OkResult;\n\n// ============================================================\n// review.* and decide.*\n// ============================================================\n\nexport interface ReviewRequestParams extends WorkspaceParam, ActorParam, TaskParam {\n artefact: unknown;\n to: ParticipantUri | ParticipantUri[];\n rule?: string;\n deadline?: string;\n}\nexport interface ReviewRequestResult { state: string; review_id: TaskId }\n\nexport interface DecideApproveParams extends WorkspaceParam, ActorParam, TaskParam {\n rationale?: string;\n}\nexport type DecideApproveResult = OkResult;\n\nexport interface DecideRejectParams extends WorkspaceParam, ActorParam, TaskParam {\n rationale: string;\n category?: string;\n}\nexport type DecideRejectResult = OkResult;\n\nexport interface DecideOverrideParams extends WorkspaceParam, ActorParam, TaskParam {\n diff: JsonPatchOp[];\n rationale: string;\n tags?: string[];\n policy_refs?: string[];\n logical_id?: string;\n instance_id?: string;\n intent_preserved?: boolean;\n based_on_artefact?: unknown;\n}\nexport interface DecideOverrideResult {\n state: \"completed\";\n override_artefact_id: ArtefactId;\n applied: unknown;\n}\n\nexport interface AbstainDeclareParams extends WorkspaceParam, ActorParam, TaskParam {\n category: string;\n rationale?: string;\n}\nexport type AbstainDeclareResult = OkResult;\n\nexport interface EscalateRaiseParams extends WorkspaceParam, ActorParam, TaskParam {\n to?: ParticipantUri;\n rationale?: string;\n}\nexport interface EscalateRaiseResult { ok: true; to?: ParticipantUri }\n\n// ============================================================\n// whisper.* (whisper/1.0)\n// ============================================================\n\nexport interface WhisperAskParams extends WorkspaceParam, ActorParam, TaskParam {\n to: ParticipantUri;\n question: string;\n options?: string[];\n default_on_lapse?: string;\n lapse_ms?: number;\n}\nexport interface WhisperAskResult { whisper_id: string }\n\nexport interface WhisperAnswerParams extends WorkspaceParam, ActorParam {\n whisper_id: string;\n answer: string;\n}\nexport type WhisperAnswerResult = OkResult;\n\n// ============================================================\n// deliberate.* (deliberation/1.0)\n// ============================================================\n\nexport interface DeliberateOpenParams extends WorkspaceParam, ActorParam, TaskParam {\n rule: Record<string, unknown>;\n proposition: unknown;\n voters: ParticipantUri[];\n}\nexport interface DeliberateOpenResult { deliberation_id: string }\n\nexport interface DeliberateCommentParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n text: string;\n}\nexport type DeliberateCommentResult = OkResult;\n\nexport interface DeliberateVoteParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n vote: \"yea\" | \"nay\" | \"abstain\";\n weight?: number;\n rationale?: string;\n}\nexport type DeliberateVoteResult = OkResult;\n\nexport interface DeliberateCloseParams extends WorkspaceParam, ActorParam {\n deliberation_id: string;\n}\nexport interface DeliberateCloseResult { outcome: \"approved\" | \"rejected\" | \"no_quorum\" }\n\n// ============================================================\n// handoff.* (handoff/1.0)\n// ============================================================\n\nexport interface HandoffProposeParams extends WorkspaceParam, ActorParam {\n to: ParticipantUri;\n task_ids: TaskId[];\n summary: string;\n active_constraints?: Record<string, unknown>;\n}\nexport interface HandoffProposeResult { handoff_id: string }\n\nexport interface HandoffAcceptParams extends WorkspaceParam, ActorParam {\n handoff_id: string;\n}\nexport type HandoffAcceptResult = OkResult;\n\nexport interface HandoffDeclineParams extends WorkspaceParam, ActorParam {\n handoff_id: string;\n reason?: string;\n}\nexport type HandoffDeclineResult = OkResult;\n\n// ============================================================\n// control.* (control/1.0)\n// ============================================================\n\nexport interface ControlPauseParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ControlPauseResult = OkResult;\n\nexport interface ControlResumeParams extends WorkspaceParam, ActorParam {\n reason?: string;\n}\nexport type ControlResumeResult = OkResult;\n\nexport interface ControlCancelParams extends WorkspaceParam, ActorParam, TaskParam {\n reason?: string;\n}\nexport type ControlCancelResult = OkResult;\n\nexport interface ControlSupersedeParams extends WorkspaceParam, ActorParam, TaskParam {\n replacement: unknown;\n logical_id?: string;\n intent_preserved?: boolean;\n reason?: string;\n}\nexport interface ControlSupersedeResult { artefact_id: ArtefactId }\n\nexport interface ControlSnapshotParams extends WorkspaceParam, ActorParam {\n label?: string;\n}\nexport interface ControlSnapshotResult { snapshot_id: string }\n\nexport interface ControlRollbackParams extends WorkspaceParam, ActorParam {\n snapshot_id: string;\n reason?: string;\n}\nexport type ControlRollbackResult = OkResult;\n\nexport interface ControlSetModeCeilingParams extends WorkspaceParam, ActorParam {\n ceiling: \"shadow\" | \"trial\" | \"production\";\n}\nexport type ControlSetModeCeilingResult = OkResult;\n\n// ============================================================\n// routing.* (routing/1.0)\n// ============================================================\n\nexport interface TaskRouteParams extends WorkspaceParam, ActorParam, TaskParam {\n candidates: ParticipantUri[];\n}\nexport interface TaskRouteResult {\n selected: ParticipantUri;\n rationale: Record<string, unknown>;\n}\n\nexport interface ReviewDepthParams extends WorkspaceParam, ActorParam, TaskParam {\n artefact?: unknown;\n hints?: Record<string, unknown>;\n}\nexport interface ReviewDepthResult {\n depth: \"skip\" | \"spot_check\" | \"full\" | \"escalated\";\n sampling_probability?: number;\n rationale: Record<string, unknown>;\n}\n\nexport interface EscalateAutoParams extends WorkspaceParam, ActorParam, TaskParam {\n hints?: Record<string, unknown>;\n}\nexport interface EscalateAutoResult {\n escalated: boolean;\n to?: ParticipantUri;\n triggered_rule?: Record<string, unknown>;\n}\n\n// ============================================================\n// audit.* (Core + audit-scitt/1.0)\n// ============================================================\n\nexport interface AuditReadParams extends WorkspaceParam {\n from_seq?: number;\n limit?: number;\n}\nexport interface AuditReadResult { entries: unknown[] }\n\nexport interface AuditSubmitToScittParams extends WorkspaceParam, ActorParam {\n seq: number;\n statement?: Record<string, unknown>;\n}\nexport interface AuditSubmitToScittResult { receipt: Record<string, unknown> }\n\nexport interface AuditVerifyReceiptParams extends WorkspaceParam {\n receipt: Record<string, unknown>;\n}\nexport interface AuditVerifyReceiptResult { valid: boolean }\n\nexport interface AuditVerifyChainParams extends WorkspaceParam {\n /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */\n from_seq?: number;\n /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */\n to_seq?: number;\n}\n/**\n * The verdict of a local prev_hash chain replay.\n *\n * `status` is terminal and the three outcomes are mutually exclusive: a\n * broken chain is a JSON-RPC error, an unevaluated range is\n * `not_evaluated`, and `verified` requires complete coverage. A caller\n * reading `ok` alone therefore fails closed on a range that was never\n * checked, instead of taking a pass over entries no evidence covers.\n */\nexport interface AuditVerifyChainResult {\n status: \"verified\" | \"not_evaluated\";\n /** True only when `status` is \"verified\". Never true beside a gap. */\n ok: boolean;\n /** Present only when `status` is \"not_evaluated\". */\n reason?: \"unchained_prefix\";\n entries_total: number;\n entries_checked: number;\n entries_unchecked: number;\n /** Seq of the first entry inside coverage; null when nothing was checked. */\n checked_from_seq: number | null;\n chain_head: string;\n}\n\n// ============================================================\n// Method-name → {params, result} map (single source of truth)\n// ============================================================\n\nexport interface MethodTable {\n \"workspace.create\": { params: WorkspaceCreateParams, result: WorkspaceCreateResult };\n \"workspace.describe\": { params: WorkspaceDescribeParams, result: WorkspaceDescribeResult };\n \"workspace.set_profiles\": { params: WorkspaceSetProfilesParams, result: WorkspaceSetProfilesResult };\n\n \"participant.join\": { params: ParticipantJoinParams, result: ParticipantJoinResult };\n \"participant.leave\": { params: ParticipantLeaveParams, result: ParticipantLeaveResult };\n \"participant.rotate_key\": { params: ParticipantRotateKeyParams, result: ParticipantRotateKeyResult };\n \"participant.revoke_key\": { params: ParticipantRevokeKeyParams, result: ParticipantRevokeKeyResult };\n\n \"task.create\": { params: TaskCreateParams, result: TaskCreateResult };\n \"task.update\": { params: TaskUpdateParams, result: TaskUpdateResult };\n \"task.complete\": { params: TaskCompleteParams, result: TaskCompleteResult };\n\n \"review.request\": { params: ReviewRequestParams, result: ReviewRequestResult };\n \"decide.approve\": { params: DecideApproveParams, result: DecideApproveResult };\n \"decide.reject\": { params: DecideRejectParams, result: DecideRejectResult };\n \"decide.override\": { params: DecideOverrideParams, result: DecideOverrideResult };\n \"abstain.declare\": { params: AbstainDeclareParams, result: AbstainDeclareResult };\n \"escalate.raise\": { params: EscalateRaiseParams, result: EscalateRaiseResult };\n\n \"whisper.ask\": { params: WhisperAskParams, result: WhisperAskResult };\n \"whisper.answer\": { params: WhisperAnswerParams, result: WhisperAnswerResult };\n\n \"deliberate.open\": { params: DeliberateOpenParams, result: DeliberateOpenResult };\n \"deliberate.comment\": { params: DeliberateCommentParams, result: DeliberateCommentResult };\n \"deliberate.vote\": { params: DeliberateVoteParams, result: DeliberateVoteResult };\n \"deliberate.close\": { params: DeliberateCloseParams, result: DeliberateCloseResult };\n\n \"handoff.propose\": { params: HandoffProposeParams, result: HandoffProposeResult };\n \"handoff.accept\": { params: HandoffAcceptParams, result: HandoffAcceptResult };\n \"handoff.decline\": { params: HandoffDeclineParams, result: HandoffDeclineResult };\n\n \"control.pause\": { params: ControlPauseParams, result: ControlPauseResult };\n \"control.resume\": { params: ControlResumeParams, result: ControlResumeResult };\n \"control.cancel\": { params: ControlCancelParams, result: ControlCancelResult };\n \"control.supersede\": { params: ControlSupersedeParams, result: ControlSupersedeResult };\n \"control.snapshot\": { params: ControlSnapshotParams, result: ControlSnapshotResult };\n \"control.rollback\": { params: ControlRollbackParams, result: ControlRollbackResult };\n \"control.set_mode_ceiling\": { params: ControlSetModeCeilingParams, result: ControlSetModeCeilingResult };\n\n \"task.route\": { params: TaskRouteParams, result: TaskRouteResult };\n \"review.depth\": { params: ReviewDepthParams, result: ReviewDepthResult };\n \"escalate.auto\": { params: EscalateAutoParams, result: EscalateAutoResult };\n\n \"audit.read\": { params: AuditReadParams, result: AuditReadResult };\n \"audit.submit_to_scitt\": { params: AuditSubmitToScittParams, result: AuditSubmitToScittResult };\n \"audit.verify_receipt\": { params: AuditVerifyReceiptParams, result: AuditVerifyReceiptResult };\n \"audit.verify_chain\": { params: AuditVerifyChainParams, result: AuditVerifyChainResult };\n}\n\nexport type MethodName = keyof MethodTable;\nexport type MethodParams<M extends MethodName> = MethodTable[M][\"params\"];\nexport type MethodResult<M extends MethodName> = MethodTable[M][\"result\"];\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -284,12 +284,32 @@ interface AuditVerifyReceiptResult {
284
284
  valid: boolean;
285
285
  }
286
286
  interface AuditVerifyChainParams extends WorkspaceParam {
287
+ /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */
287
288
  from_seq?: number;
289
+ /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */
288
290
  to_seq?: number;
289
291
  }
292
+ /**
293
+ * The verdict of a local prev_hash chain replay.
294
+ *
295
+ * `status` is terminal and the three outcomes are mutually exclusive: a
296
+ * broken chain is a JSON-RPC error, an unevaluated range is
297
+ * `not_evaluated`, and `verified` requires complete coverage. A caller
298
+ * reading `ok` alone therefore fails closed on a range that was never
299
+ * checked, instead of taking a pass over entries no evidence covers.
300
+ */
290
301
  interface AuditVerifyChainResult {
291
- valid: boolean;
292
- breaks?: number[];
302
+ status: "verified" | "not_evaluated";
303
+ /** True only when `status` is "verified". Never true beside a gap. */
304
+ ok: boolean;
305
+ /** Present only when `status` is "not_evaluated". */
306
+ reason?: "unchained_prefix";
307
+ entries_total: number;
308
+ entries_checked: number;
309
+ entries_unchecked: number;
310
+ /** Seq of the first entry inside coverage; null when nothing was checked. */
311
+ checked_from_seq: number | null;
312
+ chain_head: string;
293
313
  }
294
314
  interface MethodTable {
295
315
  "workspace.create": {
package/dist/methods.d.ts CHANGED
@@ -284,12 +284,32 @@ interface AuditVerifyReceiptResult {
284
284
  valid: boolean;
285
285
  }
286
286
  interface AuditVerifyChainParams extends WorkspaceParam {
287
+ /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */
287
288
  from_seq?: number;
289
+ /** Not implemented. Supplying either is refused; see SPECIFICATION.md 10.2. */
288
290
  to_seq?: number;
289
291
  }
292
+ /**
293
+ * The verdict of a local prev_hash chain replay.
294
+ *
295
+ * `status` is terminal and the three outcomes are mutually exclusive: a
296
+ * broken chain is a JSON-RPC error, an unevaluated range is
297
+ * `not_evaluated`, and `verified` requires complete coverage. A caller
298
+ * reading `ok` alone therefore fails closed on a range that was never
299
+ * checked, instead of taking a pass over entries no evidence covers.
300
+ */
290
301
  interface AuditVerifyChainResult {
291
- valid: boolean;
292
- breaks?: number[];
302
+ status: "verified" | "not_evaluated";
303
+ /** True only when `status` is "verified". Never true beside a gap. */
304
+ ok: boolean;
305
+ /** Present only when `status` is "not_evaluated". */
306
+ reason?: "unchained_prefix";
307
+ entries_total: number;
308
+ entries_checked: number;
309
+ entries_unchecked: number;
310
+ /** Seq of the first entry inside coverage; null when nothing was checked. */
311
+ checked_from_seq: number | null;
312
+ chain_head: string;
293
313
  }
294
314
  interface MethodTable {
295
315
  "workspace.create": {
package/dist/patch.cjs CHANGED
@@ -28,6 +28,11 @@ module.exports = __toCommonJS(patch_exports);
28
28
  var PatchError = class extends Error {
29
29
  };
30
30
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
31
+ var ARRAY_INDEX_RE = /^(0|[1-9][0-9]*)$/;
32
+ function arrayIndex(seg) {
33
+ if (!ARRAY_INDEX_RE.test(seg)) throw new PatchError(`Array index expected at ${JSON.stringify(seg)}`);
34
+ return Number(seg);
35
+ }
31
36
  function unescape(token) {
32
37
  return token.replace(/~1/g, "/").replace(/~0/g, "~");
33
38
  }
@@ -52,8 +57,8 @@ function navigate(doc, parts) {
52
57
  for (let i = 0; i < parts.length - 1; i++) {
53
58
  const part = parts[i];
54
59
  if (Array.isArray(parent)) {
55
- const idx = Number(part);
56
- if (!Number.isInteger(idx) || idx < 0 || idx >= parent.length) {
60
+ const idx = arrayIndex(part);
61
+ if (idx >= parent.length) {
57
62
  throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join("/")}`);
58
63
  }
59
64
  parent = parent[idx];
@@ -69,11 +74,7 @@ function navigate(doc, parts) {
69
74
  const last = parts[parts.length - 1];
70
75
  if (Array.isArray(parent)) {
71
76
  if (last === "-") return [parent, "-"];
72
- const idx = Number(last);
73
- if (!Number.isInteger(idx)) {
74
- throw new PatchError(`Array index expected at ${JSON.stringify(last)}`);
75
- }
76
- return [parent, idx];
77
+ return [parent, arrayIndex(last)];
77
78
  }
78
79
  return [parent, last];
79
80
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/patch.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = Number(part);\n if (!Number.isInteger(idx) || idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n const idx = Number(last);\n if (!Number.isInteger(idx)) {\n throw new PatchError(`Array index expected at ${JSON.stringify(last)}`);\n }\n return [parent, idx];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBO,IAAM,aAAN,cAAyB,MAAM;AAAC;AAGvC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAExE,SAAS,SAAS,OAAuB;AACvC,SAAO,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,UAAU,MAAwB;AACzC,MAAI,SAAS,GAAI,QAAO,CAAC;AACzB,MAAI,CAAC,KAAK,WAAW,GAAG,GAAG;AACzB,UAAM,IAAI,WAAW,qCAAqC,KAAK,UAAU,IAAI,CAAC,EAAE;AAAA,EAClF;AACA,QAAM,WAAW,KAAK,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,IAAI,QAAQ;AACtD,aAAW,OAAO,UAAU;AAC1B,QAAI,eAAe,IAAI,GAAG,GAAG;AAC3B,YAAM,IAAI,WAAW,gCAAgC,KAAK,UAAU,GAAG,CAAC,EAAE;AAAA,IAC5E;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,S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D,WAAW,EAAE,OAAO,QAAQ;AAC1B,UAAI,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;AAAA,IACjC,OAAO;AACL,UAAI,KAAK,GAAG,cAAc,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG,IAAI,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/patch.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n// An array index is an RFC 6901 array index: \"0\" or a positive integer with no\n// leading zero. A shared strict rule keeps the two references in step -- JS\n// Number() and Python int() otherwise accept disjoint token sets (e.g. \"1e1\",\n// \"0x0a\", \"3.0\", \"\", \"1_0\"), which would apply the same patch differently.\nconst ARRAY_INDEX_RE = /^(0|[1-9][0-9]*)$/;\n\nfunction arrayIndex(seg: string): number {\n if (!ARRAY_INDEX_RE.test(seg)) throw new PatchError(`Array index expected at ${JSON.stringify(seg)}`);\n return Number(seg);\n}\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = arrayIndex(part);\n if (idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n return [parent, arrayIndex(last)];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBO,IAAM,aAAN,cAAyB,MAAM;AAAC;AAGvC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAMxE,IAAM,iBAAiB;AAEvB,SAAS,WAAW,K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K,EAAE,IAAI,WAAW,MAAM,YAAY,KAAK,OAAO,GAAG,CAAC;AAAA,IAC9D;AACA,WAAO;AAAA,EACT;AAEA,QAAM,UAAU;AAChB,QAAM,QAAQ;AACd,QAAM,UAAU,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,OAAO,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC;AAExE,aAAW,OAAO,SAAS;AACzB,UAAM,UAAU,IAAI,QAAQ,MAAM,IAAI,EAAE,QAAQ,OAAO,IAAI;AAC3D,UAAM,OAAO,GAAG,QAAQ,IAAI,OAAO;AACnC,QAAI,EAAE,OAAO,UAAU;AACrB,UAAI,KAAK,EAAE,IAAI,OAAO,MAAM,OAAO,MAAM,GAAG,EAAE,CAAC;AAAA,IACjD,WAAW,EAAE,OAAO,QAAQ;AAC1B,UAAI,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;AAAA,IACjC,OAAO;AACL,UAAI,KAAK,GAAG,cAAc,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG,IAAI,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
package/dist/patch.js CHANGED
@@ -2,6 +2,11 @@
2
2
  var PatchError = class extends Error {
3
3
  };
4
4
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
5
+ var ARRAY_INDEX_RE = /^(0|[1-9][0-9]*)$/;
6
+ function arrayIndex(seg) {
7
+ if (!ARRAY_INDEX_RE.test(seg)) throw new PatchError(`Array index expected at ${JSON.stringify(seg)}`);
8
+ return Number(seg);
9
+ }
5
10
  function unescape(token) {
6
11
  return token.replace(/~1/g, "/").replace(/~0/g, "~");
7
12
  }
@@ -26,8 +31,8 @@ function navigate(doc, parts) {
26
31
  for (let i = 0; i < parts.length - 1; i++) {
27
32
  const part = parts[i];
28
33
  if (Array.isArray(parent)) {
29
- const idx = Number(part);
30
- if (!Number.isInteger(idx) || idx < 0 || idx >= parent.length) {
34
+ const idx = arrayIndex(part);
35
+ if (idx >= parent.length) {
31
36
  throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join("/")}`);
32
37
  }
33
38
  parent = parent[idx];
@@ -43,11 +48,7 @@ function navigate(doc, parts) {
43
48
  const last = parts[parts.length - 1];
44
49
  if (Array.isArray(parent)) {
45
50
  if (last === "-") return [parent, "-"];
46
- const idx = Number(last);
47
- if (!Number.isInteger(idx)) {
48
- throw new PatchError(`Array index expected at ${JSON.stringify(last)}`);
49
- }
50
- return [parent, idx];
51
+ return [parent, arrayIndex(last)];
51
52
  }
52
53
  return [parent, last];
53
54
  }
package/dist/patch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/patch.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = Number(part);\n if (!Number.isInteger(idx) || idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n const idx = Number(last);\n if (!Number.isInteger(idx)) {\n throw new PatchError(`Array index expected at ${JSON.stringify(last)}`);\n }\n return [parent, idx];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n"],"mappings":";AAiBO,IAAM,aAAN,cAAyB,MAAM;AAAC;AAGvC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAExE,SAAS,SAAS,OAAuB;AACvC,SAAO,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,UAAU,MAAwB;AACzC,MAAI,SAAS,GAAI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AM,UAAU;AAChB,QAAM,QAAQ;AACd,QAAM,UAAU,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,OAAO,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC;AAExE,aAAW,OAAO,SAAS;AACzB,UAAM,UAAU,IAAI,QAAQ,MAAM,IAAI,EAAE,QAAQ,OAAO,IAAI;AAC3D,UAAM,OAAO,GAAG,QAAQ,IAAI,OAAO;AACnC,QAAI,EAAE,OAAO,UAAU;AACrB,UAAI,KAAK,EAAE,IAAI,OAAO,MAAM,OAAO,MAAM,GAAG,EAAE,CAAC;AAAA,IACjD,WAAW,EAAE,OAAO,QAAQ;AAC1B,UAAI,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;AAAA,IACjC,OAAO;AACL,UAAI,KAAK,GAAG,cAAc,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG,IAAI,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/patch.ts"],"sourcesContent":["/**\n * @brightbeamai/chap-coordinator/patch\n *\n * RFC 6902 JSON Patch implementation, plus a small diff computer that\n * produces a patch from two values. Used by the Coordinator for\n * `decide.override` apply and by the playground UI (in the browser) to\n * compute the patch from a textarea edit.\n *\n * Implements all six RFC 6902 operations (add, remove, replace, move,\n * copy, test) with semantics identical to the Python reference. Path\n * segments that enable prototype pollution in a JavaScript runtime\n * (`__proto__`, `constructor`, `prototype`) are rejected, so the two\n * references accept and reject exactly the same patches.\n */\n\nimport type { JsonPatchOp } from \"./types.js\";\n\nexport class PatchError extends Error {}\n\n// Rejected in every JSON Pointer segment: these enable prototype pollution.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n// An array index is an RFC 6901 array index: \"0\" or a positive integer with no\n// leading zero. A shared strict rule keeps the two references in step -- JS\n// Number() and Python int() otherwise accept disjoint token sets (e.g. \"1e1\",\n// \"0x0a\", \"3.0\", \"\", \"1_0\"), which would apply the same patch differently.\nconst ARRAY_INDEX_RE = /^(0|[1-9][0-9]*)$/;\n\nfunction arrayIndex(seg: string): number {\n if (!ARRAY_INDEX_RE.test(seg)) throw new PatchError(`Array index expected at ${JSON.stringify(seg)}`);\n return Number(seg);\n}\n\nfunction unescape(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction splitPath(path: string): string[] {\n if (path === \"\") return [];\n if (!path.startsWith(\"/\")) {\n throw new PatchError(`JSON Pointer must start with '/': ${JSON.stringify(path)}`);\n }\n const segments = path.slice(1).split(\"/\").map(unescape);\n for (const seg of segments) {\n if (DANGEROUS_KEYS.has(seg)) {\n throw new PatchError(`Refusing unsafe path segment ${JSON.stringify(seg)}`);\n }\n }\n return segments;\n}\n\n/** Navigate to the parent of the target; return [parent, lastKey]. */\nfunction navigate(doc: any, parts: string[]): [any, string | number] {\n if (parts.length === 0) {\n throw new PatchError(\"Cannot operate on root with this helper.\");\n }\n let parent = doc;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (Array.isArray(parent)) {\n const idx = arrayIndex(part);\n if (idx >= parent.length) {\n throw new PatchError(`Index out of range at /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[idx];\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, part)) {\n throw new PatchError(`Path not found: /${parts.slice(0, i + 1).join(\"/\")}`);\n }\n parent = parent[part];\n } else {\n throw new PatchError(`Cannot traverse into ${typeof parent} at ${JSON.stringify(part)}`);\n }\n }\n const last = parts[parts.length - 1];\n if (Array.isArray(parent)) {\n if (last === \"-\") return [parent, \"-\"];\n return [parent, arrayIndex(last)];\n }\n return [parent, last];\n}\n\nfunction getAt(doc: any, path: string): any {\n const parts = splitPath(path);\n if (parts.length === 0) return doc;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") throw new PatchError(\"Cannot read '-' position.\");\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) throw new PatchError(`Index out of range: ${path}`);\n return parent[idx];\n }\n if (\n parent === null ||\n typeof parent !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(parent, key)\n ) {\n throw new PatchError(`Path not found: ${path}`);\n }\n return parent[key as string];\n}\n\nfunction clone<T>(v: T): T {\n return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);\n}\n\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (!deepEqual(a[k], b[k])) return false;\n }\n return true;\n}\n\nfunction applyOne(doc: any, op: JsonPatchOp): any {\n const kind = op.op;\n const path = op.path ?? \"\";\n\n if (kind === \"add\") {\n if (!(\"value\" in op)) throw new PatchError(\"'add' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value; // replace whole document\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n if (key === \"-\") {\n parent.push(op.value);\n } else {\n const idx = key as number;\n if (idx < 0 || idx > parent.length) {\n throw new PatchError(`Index out of range for add: ${path}`);\n }\n parent.splice(idx, 0, op.value);\n }\n } else if (parent !== null && typeof parent === \"object\") {\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot add into ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"replace\") {\n if (!(\"value\" in op)) throw new PatchError(\"'replace' requires 'value'\");\n const parts = splitPath(path);\n if (parts.length === 0) return op.value;\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[idx] = op.value;\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for replace: ${path}`);\n }\n parent[key as string] = op.value;\n } else {\n throw new PatchError(`Cannot replace in ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"remove\") {\n const parts = splitPath(path);\n if (parts.length === 0) throw new PatchError(\"Cannot remove root.\");\n const [parent, key] = navigate(doc, parts);\n if (Array.isArray(parent)) {\n const idx = key as number;\n if (idx < 0 || idx >= parent.length) {\n throw new PatchError(`Index out of range for remove: ${path}`);\n }\n parent.splice(idx, 1);\n } else if (parent !== null && typeof parent === \"object\") {\n if (!Object.prototype.hasOwnProperty.call(parent, key)) {\n throw new PatchError(`Path not found for remove: ${path}`);\n }\n delete parent[key as string];\n } else {\n throw new PatchError(`Cannot remove from ${typeof parent}`);\n }\n return doc;\n }\n\n if (kind === \"copy\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'copy' requires 'from'\");\n const value = clone(getAt(doc, src));\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"move\") {\n const src = op.from;\n if (src === undefined) throw new PatchError(\"'move' requires 'from'\");\n // RFC 6902 4.4: 'from' MUST NOT be a proper prefix of 'path'.\n if (path.startsWith(src + \"/\")) {\n throw new PatchError(\"'move' cannot move a location into its own child.\");\n }\n const value = clone(getAt(doc, src));\n doc = applyOne(doc, { op: \"remove\", path: src });\n return applyOne(doc, { op: \"add\", path, value });\n }\n\n if (kind === \"test\") {\n if (!(\"value\" in op)) throw new PatchError(\"'test' requires 'value'\");\n const actual = getAt(doc, path);\n if (!deepEqual(actual, op.value)) throw new PatchError(`'test' failed at ${path}`);\n return doc;\n }\n\n throw new PatchError(`Unsupported op: ${JSON.stringify(kind)}`);\n}\n\nconst MAX_PATCH_OPS = 1000;\nconst MAX_DOCUMENT_NODES = 100_000;\n\nfunction nodeCount(value: unknown): number {\n if (Array.isArray(value)) {\n let n = 1;\n for (const v of value) n += nodeCount(v);\n return n;\n }\n if (value !== null && typeof value === \"object\") {\n let n = 1;\n for (const v of Object.values(value as Record<string, unknown>)) n += nodeCount(v);\n return n;\n }\n return 1;\n}\n\nexport function applyJsonPatch(doc: unknown, ops: JsonPatchOp[]): unknown {\n if (ops.length > MAX_PATCH_OPS) {\n throw new PatchError(`Patch has too many operations (${ops.length} > ${MAX_PATCH_OPS})`);\n }\n let out: any = JSON.parse(JSON.stringify(doc));\n for (const op of ops) {\n out = applyOne(out, op);\n if (nodeCount(out) > MAX_DOCUMENT_NODES) {\n throw new PatchError(`Patched document exceeds the node limit (${MAX_DOCUMENT_NODES})`);\n }\n }\n return out;\n}\n\n// ============================================================\n// diff: produce a patch that transforms `from` into `to`\n// ============================================================\n\n/**\n * Compute an RFC 6902 patch that, when applied to `from`, produces\n * `to`. Walks objects key-by-key; arrays use a shallow whole-array\n * replace if any element differs. Sufficient for the playground's\n * draft-edit use case where drafts are small JSON objects.\n */\nexport function diffJsonPatch(from: unknown, to: unknown, basePath = \"\"): JsonPatchOp[] {\n const ops: JsonPatchOp[] = [];\n\n if (typeof from !== typeof to || Array.isArray(from) !== Array.isArray(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n return ops;\n }\n\n if (from === null || to === null || typeof from !== \"object\") {\n if (from !== to) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n if (Array.isArray(from) && Array.isArray(to)) {\n if (JSON.stringify(from) !== JSON.stringify(to)) {\n ops.push({ op: \"replace\", path: basePath || \"/\", value: to });\n }\n return ops;\n }\n\n const fromObj = from as Record<string, unknown>;\n const toObj = to as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(fromObj), ...Object.keys(toObj)]);\n\n for (const key of allKeys) {\n const escaped = key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n const path = `${basePath}/${escaped}`;\n if (!(key in fromObj)) {\n ops.push({ op: \"add\", path, value: toObj[key] });\n } else if (!(key in toObj)) {\n ops.push({ op: \"remove\", path });\n } else {\n ops.push(...diffJsonPatch(fromObj[key], toObj[key], path));\n }\n }\n\n return ops;\n}\n"],"mappings":";AAiBO,IAAM,aAAN,cAAyB,MAAM;AAAC;AAGvC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAMxE,IAAM,iBAAiB;AAEvB,SAAS,WAAW,KAAqB;AACvC,MAAI,CAAC,eAAe,KAAK,GAAG,EAAG,OAAM,IAAI,WAAW,2BAA2B,KAAK,UAAU,GAAG,CAAC,EAAE;AACpG,SAAO,OAAO,GAAG;AACnB;AAEA,SAAS,SAAS,OAAuB;AACvC,SAAO,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,UAAU,MAAwB;AACzC,MAAI,SAAS,GAAI,QAAO,CAAC;AACzB,MAAI,CAAC,KAAK,WAAW,GAAG,GAAG;AACzB,UAAM,IAAI,WAAW,qCAAqC,KAAK,UAAU,IAAI,CAAC,EAAE;AAAA,EAClF;AACA,QAAM,WAAW,KAAK,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,IAAI,QAAQ;AACtD,aAAW,OAAO,UAAU;AAC1B,QAAI,eAAe,IAAI,GAAG,GAAG;AAC3B,YAAM,IAAI,WAAW,gCAAgC,KAAK,UAAU,GAAG,CAAC,EAAE;AAAA,IAC5E;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,SAAS,KAAU,OAAyC;AACnE,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,IAAI,WAAW,0CAA0C;AAAA,EACjE;AACA,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,MAAM,SAAS,GAAG,KAAK;AACzC,UAAM,OAAO,MAAM,CAAC;AACpB,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,YAAM,MAAM,WAAW,IAAI;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AAS,QAAQ,OAAO,QAAQ,OAAO,SAAS,UAAU;AAC5D,QAAI,SAAS,IAAI;AACf,UAAI,KAAK,EAAE,IAAI,WAAW,MAAM,YAAY,KAAK,OAAO,GAAG,CAAC;AAAA,IAC9D;AACA,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,EAAE,GAAG;AAC5C,QAAI,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,EAAE,GAAG;AAC/C,UAAI,KAAK,EAAE,IAAI,WAAW,MAAM,YAAY,KAAK,OAAO,GAAG,CAAC;AAAA,IAC9D;AACA,WAAO;AAAA,EACT;AAEA,QAAM,UAAU;AAChB,QAAM,QAAQ;AACd,QAAM,UAAU,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,OAAO,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC;AAExE,aAAW,OAAO,SAAS;AACzB,UAAM,UAAU,IAAI,QAAQ,MAAM,IAAI,EAAE,QAAQ,OAAO,IAAI;AAC3D,UAAM,OAAO,GAAG,QAAQ,IAAI,OAAO;AACnC,QAAI,EAAE,OAAO,UAAU;AACrB,UAAI,KAAK,EAAE,IAAI,OAAO,MAAM,OAAO,MAAM,GAAG,EAAE,CAAC;AAAA,IACjD,WAAW,EAAE,OAAO,QAAQ;AAC1B,UAAI,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;AAAA,IACjC,OAAO;AACL,UAAI,KAAK,GAAG,cAAc,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG,IAAI,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -23,6 +23,8 @@ __export(sqlite_exports, {
23
23
  SqliteStore: () => SqliteStore
24
24
  });
25
25
  module.exports = __toCommonJS(sqlite_exports);
26
+ var import_node_module = require("module");
27
+ var import_meta = {};
26
28
  var SqliteStore = class {
27
29
  db;
28
30
  stmtLoad;
@@ -31,10 +33,11 @@ var SqliteStore = class {
31
33
  constructor(path, options = {}) {
32
34
  let Database;
33
35
  try {
34
- Database = require("better-sqlite3");
36
+ Database = (0, import_node_module.createRequire)(import_meta.url)("better-sqlite3");
35
37
  } catch (err) {
38
+ const detail = err instanceof Error ? `: ${err.message.split("\n")[0]}` : "";
36
39
  throw new Error(
37
- "SqliteStore requires the `better-sqlite3` package. Install it with `npm install better-sqlite3` or use MemoryStore for non-persistent workloads."
40
+ `SqliteStore requires the \`better-sqlite3\` package. Install it with \`npm install better-sqlite3\` or use MemoryStore for non-persistent workloads${detail}`
38
41
  );
39
42
  }
40
43
  this.db = new Database(path);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/storage/sqlite.ts"],"sourcesContent":["/**\n * SQLite-backed store using better-sqlite3.\n *\n * Schema:\n * CREATE TABLE chap_workspaces (\n * id TEXT PRIMARY KEY,\n * data TEXT NOT NULL, -- JSON.stringify of snapshot\n * version INTEGER NOT NULL,\n * updated_at TEXT NOT NULL -- ISO-8601\n * )\n *\n * Usage:\n * import { Coordinator } from \"@brightbeamai/chap-coordinator\";\n * import { SqliteStore } from \"@brightbeamai/chap-coordinator/storage/sqlite\";\n *\n * const coord = new Coordinator({\n * store: new SqliteStore(\"./chap.db\"),\n * });\n *\n * Pass `\":memory:\"` for an in-memory SQLite instance (faster than the\n * MemoryStore for tests that need transactional semantics).\n *\n * better-sqlite3 is declared as an optionalDependency. If the binary\n * cannot be built (rare on Linux/macOS, common on locked-down CI), the\n * SqliteStore import will throw with a clear message and applications\n * can fall back to MemoryStore or another implementation.\n */\n\nimport type { Store, WorkspaceRecord } from \"./store.js\";\n\n// better-sqlite3 has no published types in its own package, but the\n// `@types/better-sqlite3` package provides them. We require a structural\n// subset so the file type-checks even if the typings are absent.\ninterface SqliteDatabase {\n exec(sql: string): unknown;\n prepare(sql: string): SqliteStatement;\n pragma(name: string, options?: { simple?: boolean }): unknown;\n close(): void;\n}\ninterface SqliteStatement {\n run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n}\n\nexport interface SqliteStoreOptions {\n /**\n * Enable WAL journal mode for better concurrent-read performance.\n * Default true. Set false for `:memory:` databases or when the\n * filesystem does not support WAL (some network filesystems).\n */\n wal?: boolean;\n}\n\nexport class SqliteStore implements Store {\n readonly db: SqliteDatabase;\n private readonly stmtLoad: SqliteStatement;\n private readonly stmtSave: SqliteStatement;\n private readonly stmtDelete: SqliteStatement;\n\n constructor(path: string, options: SqliteStoreOptions = {}) {\n let Database: new (path: string) => SqliteDatabase;\n try {\n // require() is used so the dependency stays optional. ESM consumers\n // can still load this file; the actual import is dynamic.\n Database = require(\"better-sqlite3\");\n } catch (err) {\n throw new Error(\n \"SqliteStore requires the `better-sqlite3` package. \" +\n \"Install it with `npm install better-sqlite3` \" +\n \"or use MemoryStore for non-persistent workloads.\",\n );\n }\n\n this.db = new Database(path);\n if (path !== \":memory:\" && options.wal !== false) {\n this.db.pragma(\"journal_mode = WAL\");\n }\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS chap_workspaces (\n id TEXT PRIMARY KEY,\n data TEXT NOT NULL,\n version INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_chap_workspaces_updated_at\n ON chap_workspaces (updated_at);\n `);\n\n this.stmtLoad = this.db.prepare(\n \"SELECT id, data, version, updated_at FROM chap_workspaces\",\n );\n this.stmtSave = this.db.prepare(\n \"INSERT INTO chap_workspaces (id, data, version, updated_at) \" +\n \"VALUES (?, ?, ?, ?) \" +\n \"ON CONFLICT(id) DO UPDATE SET \" +\n \"data = excluded.data, \" +\n \"version = excluded.version, \" +\n \"updated_at = excluded.updated_at\",\n );\n this.stmtDelete = this.db.prepare(\n \"DELETE FROM chap_workspaces WHERE id = ?\",\n );\n }\n\n load(): WorkspaceRecord[] {\n const rows = this.stmtLoad.all() as Array<{\n id: string;\n data: string;\n version: number;\n updated_at: string;\n }>;\n const out: WorkspaceRecord[] = [];\n for (const r of rows) {\n try {\n out.push({ id: r.id, data: JSON.parse(r.data), version: r.version, updated_at: r.updated_at });\n } catch {\n // A single unreadable row must not discard every other workspace; skip it.\n }\n }\n return out;\n }\n\n save(record: WorkspaceRecord): void {\n this.stmtSave.run(\n record.id,\n JSON.stringify(record.data),\n record.version,\n record.updated_at,\n );\n }\n\n delete(id: string): void {\n this.stmtDelete.run(id);\n }\n\n close(): void {\n this.db.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAsDO,IAAM,cAAN,MAAmC;AAAA,EAC/B;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,MAAc,UAA8B,CAAC,GAAG;AAC1D,QAAI;AACJ,QAAI;AAGF,iBAAW,QAAQ,gBAAgB;AAAA,IACrC,SAAS,KAAK;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MAGF;AAAA,IACF;AAEA,SAAK,KAAK,IAAI,SAAS,IAAI;AAC3B,QAAI,SAAS,cAAc,QAAQ,QAAQ,OAAO;AAChD,WAAK,GAAG,OAAO,oBAAoB;AAAA,IACrC;AACA,SAAK,GAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KASZ;AAED,SAAK,WAAW,KAAK,GAAG;AAAA,MACtB;AAAA,IACF;AACA,SAAK,WAAW,KAAK,GAAG;AAAA,MACtB;AAAA,IAMF;AACA,SAAK,aAAa,KAAK,GAAG;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAA0B;AACxB,UAAM,OAAO,KAAK,SAAS,IAAI;AAM/B,UAAM,MAAyB,CAAC;AAChC,eAAW,KAAK,MAAM;AACpB,UAAI;AACF,YAAI,KAAK,EAAE,IAAI,EAAE,IAAI,MAAM,KAAK,MAAM,EAAE,IAAI,GAAG,SAAS,EAAE,SAAS,YAAY,EAAE,WAAW,CAAC;AAAA,MAC/F,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,KAAK,QAA+B;AAClC,SAAK,SAAS;AAAA,MACZ,OAAO;AAAA,MACP,KAAK,UAAU,OAAO,IAAI;AAAA,MAC1B,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,OAAO,IAAkB;AACvB,SAAK,WAAW,IAAI,EAAE;AAAA,EACxB;AAAA,EAEA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/storage/sqlite.ts"],"sourcesContent":["/**\n * SQLite-backed store using better-sqlite3.\n *\n * Schema:\n * CREATE TABLE chap_workspaces (\n * id TEXT PRIMARY KEY,\n * data TEXT NOT NULL, -- JSON.stringify of snapshot\n * version INTEGER NOT NULL,\n * updated_at TEXT NOT NULL -- ISO-8601\n * )\n *\n * Usage:\n * import { Coordinator } from \"@brightbeamai/chap-coordinator\";\n * import { SqliteStore } from \"@brightbeamai/chap-coordinator/storage/sqlite\";\n *\n * const coord = new Coordinator({\n * store: new SqliteStore(\"./chap.db\"),\n * });\n *\n * Pass `\":memory:\"` for an in-memory SQLite instance (faster than the\n * MemoryStore for tests that need transactional semantics).\n *\n * better-sqlite3 is declared as an optionalDependency. If the binary\n * cannot be built (rare on Linux/macOS, common on locked-down CI), the\n * SqliteStore import will throw with a clear message and applications\n * can fall back to MemoryStore or another implementation.\n */\n\nimport { createRequire } from \"node:module\";\nimport type { Store, WorkspaceRecord } from \"./store.js\";\n\n// better-sqlite3 has no published types in its own package, but the\n// `@types/better-sqlite3` package provides them. We require a structural\n// subset so the file type-checks even if the typings are absent.\ninterface SqliteDatabase {\n exec(sql: string): unknown;\n prepare(sql: string): SqliteStatement;\n pragma(name: string, options?: { simple?: boolean }): unknown;\n close(): void;\n}\ninterface SqliteStatement {\n run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n}\n\nexport interface SqliteStoreOptions {\n /**\n * Enable WAL journal mode for better concurrent-read performance.\n * Default true. Set false for `:memory:` databases or when the\n * filesystem does not support WAL (some network filesystems).\n */\n wal?: boolean;\n}\n\nexport class SqliteStore implements Store {\n readonly db: SqliteDatabase;\n private readonly stmtLoad: SqliteStatement;\n private readonly stmtSave: SqliteStatement;\n private readonly stmtDelete: SqliteStatement;\n\n constructor(path: string, options: SqliteStoreOptions = {}) {\n let Database: new (path: string) => SqliteDatabase;\n try {\n // Resolved at construction so the dependency stays optional: importing\n // this module costs nothing if you never build a SqliteStore.\n //\n // createRequire rather than a bare require(). A bare one is undefined in\n // an ES module, so from source it threw ReferenceError and this catch\n // reported the dependency as missing when it was installed. The bundled\n // build masked it by shimming require, which is why it went unnoticed.\n Database = createRequire(import.meta.url)(\"better-sqlite3\");\n } catch (err) {\n const detail = err instanceof Error ? `: ${err.message.split(\"\\n\")[0]}` : \"\";\n throw new Error(\n \"SqliteStore requires the `better-sqlite3` package. \" +\n \"Install it with `npm install better-sqlite3` \" +\n `or use MemoryStore for non-persistent workloads${detail}`,\n );\n }\n\n this.db = new Database(path);\n if (path !== \":memory:\" && options.wal !== false) {\n this.db.pragma(\"journal_mode = WAL\");\n }\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS chap_workspaces (\n id TEXT PRIMARY KEY,\n data TEXT NOT NULL,\n version INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_chap_workspaces_updated_at\n ON chap_workspaces (updated_at);\n `);\n\n this.stmtLoad = this.db.prepare(\n \"SELECT id, data, version, updated_at FROM chap_workspaces\",\n );\n this.stmtSave = this.db.prepare(\n \"INSERT INTO chap_workspaces (id, data, version, updated_at) \" +\n \"VALUES (?, ?, ?, ?) \" +\n \"ON CONFLICT(id) DO UPDATE SET \" +\n \"data = excluded.data, \" +\n \"version = excluded.version, \" +\n \"updated_at = excluded.updated_at\",\n );\n this.stmtDelete = this.db.prepare(\n \"DELETE FROM chap_workspaces WHERE id = ?\",\n );\n }\n\n load(): WorkspaceRecord[] {\n const rows = this.stmtLoad.all() as Array<{\n id: string;\n data: string;\n version: number;\n updated_at: string;\n }>;\n const out: WorkspaceRecord[] = [];\n for (const r of rows) {\n try {\n out.push({ id: r.id, data: JSON.parse(r.data), version: r.version, updated_at: r.updated_at });\n } catch {\n // A single unreadable row must not discard every other workspace; skip it.\n }\n }\n return out;\n }\n\n save(record: WorkspaceRecord): void {\n this.stmtSave.run(\n record.id,\n JSON.stringify(record.data),\n record.version,\n record.updated_at,\n );\n }\n\n delete(id: string): void {\n this.stmtDelete.run(id);\n }\n\n close(): void {\n this.db.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,yBAA8B;AA5B9B;AAuDO,IAAM,cAAN,MAAmC;AAAA,EAC/B;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,MAAc,UAA8B,CAAC,GAAG;AAC1D,QAAI;AACJ,QAAI;AAQF,qBAAW,kCAAc,YAAY,GAAG,EAAE,gBAAgB;AAAA,IAC5D,SAAS,KAAK;AACZ,YAAM,SAAS,eAAe,QAAQ,KAAK,IAAI,QAAQ,MAAM,IAAI,EAAE,CAAC,CAAC,KAAK;AAC1E,YAAM,IAAI;AAAA,QACR,sJAEkD,MAAM;AAAA,MAC1D;AAAA,IACF;AAEA,SAAK,KAAK,IAAI,SAAS,IAAI;AAC3B,QAAI,SAAS,cAAc,QAAQ,QAAQ,OAAO;AAChD,WAAK,GAAG,OAAO,oBAAoB;AAAA,IACrC;AACA,SAAK,GAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KASZ;AAED,SAAK,WAAW,KAAK,GAAG;AAAA,MACtB;AAAA,IACF;AACA,SAAK,WAAW,KAAK,GAAG;AAAA,MACtB;AAAA,IAMF;AACA,SAAK,aAAa,KAAK,GAAG;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAA0B;AACxB,UAAM,OAAO,KAAK,SAAS,IAAI;AAM/B,UAAM,MAAyB,CAAC;AAChC,eAAW,KAAK,MAAM;AACpB,UAAI;AACF,YAAI,KAAK,EAAE,IAAI,EAAE,IAAI,MAAM,KAAK,MAAM,EAAE,IAAI,GAAG,SAAS,EAAE,SAAS,YAAY,EAAE,WAAW,CAAC;AAAA,MAC/F,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,KAAK,QAA+B;AAClC,SAAK,SAAS;AAAA,MACZ,OAAO;AAAA,MACP,KAAK,UAAU,OAAO,IAAI;AAAA,MAC1B,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,OAAO,IAAkB;AACvB,SAAK,WAAW,IAAI,EAAE;AAAA,EACxB;AAAA,EAEA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;","names":[]}
@@ -1,11 +1,5 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
1
  // src/storage/sqlite.ts
2
+ import { createRequire } from "module";
9
3
  var SqliteStore = class {
10
4
  db;
11
5
  stmtLoad;
@@ -14,10 +8,11 @@ var SqliteStore = class {
14
8
  constructor(path, options = {}) {
15
9
  let Database;
16
10
  try {
17
- Database = __require("better-sqlite3");
11
+ Database = createRequire(import.meta.url)("better-sqlite3");
18
12
  } catch (err) {
13
+ const detail = err instanceof Error ? `: ${err.message.split("\n")[0]}` : "";
19
14
  throw new Error(
20
- "SqliteStore requires the `better-sqlite3` package. Install it with `npm install better-sqlite3` or use MemoryStore for non-persistent workloads."
15
+ `SqliteStore requires the \`better-sqlite3\` package. Install it with \`npm install better-sqlite3\` or use MemoryStore for non-persistent workloads${detail}`
21
16
  );
22
17
  }
23
18
  this.db = new Database(path);