@dxos/keys 0.5.9-main.bfee100 → 0.5.9-main.d63ef8d

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.
@@ -489,7 +489,98 @@ var SpaceId = Object.freeze({
489
489
  });
490
490
  var MULTIBASE_PREFIX = "B";
491
491
  var ENCODED_LENGTH = 33;
492
+
493
+ // packages/common/keys/src/dxn.ts
494
+ import { invariant as invariant3 } from "@dxos/invariant";
495
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/common/keys/src/dxn.ts";
496
+ var DXN = class _DXN {
497
+ static {
498
+ /**
499
+ * Kind constants.
500
+ */
501
+ this.kind = Object.freeze({
502
+ ECHO: "echo",
503
+ TYPE: "type"
504
+ });
505
+ }
506
+ static parse(dxn) {
507
+ const [prefix, kind, ...parts] = dxn.split(":");
508
+ if (!(prefix === "dxn")) {
509
+ throw new Error("Invalid DXN");
510
+ }
511
+ if (!(typeof kind === "string" && kind.length > 0)) {
512
+ throw new Error("Invalid DXN");
513
+ }
514
+ if (!(parts.length > 0)) {
515
+ throw new Error("Invalid DXN");
516
+ }
517
+ return new _DXN(kind, parts);
518
+ }
519
+ #kind;
520
+ #parts;
521
+ constructor(kind, parts) {
522
+ invariant3(parts.length > 0, void 0, {
523
+ F: __dxlog_file3,
524
+ L: 51,
525
+ S: this,
526
+ A: [
527
+ "parts.length > 0",
528
+ ""
529
+ ]
530
+ });
531
+ invariant3(parts.every((part) => typeof part === "string" && part.length > 0 && part.indexOf(":") === -1), void 0, {
532
+ F: __dxlog_file3,
533
+ L: 52,
534
+ S: this,
535
+ A: [
536
+ "parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1)",
537
+ ""
538
+ ]
539
+ });
540
+ switch (kind) {
541
+ case _DXN.kind.ECHO:
542
+ invariant3(parts.length === 2, void 0, {
543
+ F: __dxlog_file3,
544
+ L: 57,
545
+ S: this,
546
+ A: [
547
+ "parts.length === 2",
548
+ ""
549
+ ]
550
+ });
551
+ break;
552
+ case _DXN.kind.TYPE:
553
+ invariant3(parts.length === 1, void 0, {
554
+ F: __dxlog_file3,
555
+ L: 60,
556
+ S: this,
557
+ A: [
558
+ "parts.length === 1",
559
+ ""
560
+ ]
561
+ });
562
+ break;
563
+ }
564
+ this.#kind = kind;
565
+ this.#parts = parts;
566
+ }
567
+ get kind() {
568
+ return this.#kind;
569
+ }
570
+ get parts() {
571
+ return this.#parts;
572
+ }
573
+ isTypeDXNOf(typename) {
574
+ return this.#kind === _DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;
575
+ }
576
+ toString() {
577
+ return `dxn:${this.#kind}:${this.#parts.join(":")}`;
578
+ }
579
+ };
580
+ var LOCAL_SPACE_TAG = "@";
492
581
  export {
582
+ DXN,
583
+ LOCAL_SPACE_TAG,
493
584
  PUBLIC_KEY_LENGTH,
494
585
  PublicKey,
495
586
  SECRET_KEY_LENGTH,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts"],
4
- "sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,QAAIA,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS,SAAU,UAAU,MAAM;AACjC,UAAI,MAAM,SAAS,QAAQ,IAAI;AAE/B,UAAI,QAAQ,IAAI;AACd,cAAM,IAAI,MAAM,8BAA8B,IAAI;AAAA,MACpD;AAEA,aAAO;AAAA,IACT;AAEA,WAAO,UAAU,SAASC,cAAc,OAAO,SAAS;AACtD,UAAI;AAEJ,cAAQ,SAAS;AAAA,QACf,KAAK;AAAA,QACL,KAAK;AACH,qBAAWH;AACX,kBAAQ,MAAM,QAAQ,OAAO,EAAE;AAC/B;AAAA,QACF,KAAK;AACH,qBAAWC;AACX,kBAAQ,MAAM,QAAQ,OA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AQI,OAAOc,YAAYlB,QAAQG,UAAU,CAAA;EACtD;AACF,CAAA;AAKA,IAAMM,mBAAmB;AAEzB,IAAMO,iBAAiB;",
6
- "names": ["RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "inspect", "truncateKey", "devtoolsFormatter", "equalsSymbol", "invariant", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "Uint8Array", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomBytes", "randomOfLength", "length", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "base32Decode", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "invariant", "SpaceId", "Object", "freeze", "byteLength", "encode", "value", "invariant", "Uint8Array", "length", "MULTIBASE_PREFIX", "base32Encode", "decode", "startsWith", "base32Decode", "slice", "isValid", "ENCODED_LENGTH", "random", "randomBytes"]
3
+ "sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts", "../../../src/dxn.ts"],
4
+ "sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\n/**\n * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.\n * Each DXN starts with a dx prefix, followed by a resource kind.\n * Colon Symbol : is used a delimiter between parts.\n * DXNs may contain slashes.\n * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.\n *\n * @example\n *\n * ```\n * dx:echo:<space key>:<echo id>\n * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:type:dxos.org/type/Calendar\n * dx:plugin:dxos.org/agent/plugin/functions\n * ```\n */\nexport class DXN {\n /**\n * Kind constants.\n */\n static kind = Object.freeze({\n ECHO: 'echo',\n TYPE: 'type',\n });\n\n static parse(dxn: string): DXN {\n const [prefix, kind, ...parts] = dxn.split(':');\n if (!(prefix === 'dxn')) {\n throw new Error('Invalid DXN');\n }\n if (!(typeof kind === 'string' && kind.length > 0)) {\n throw new Error('Invalid DXN');\n }\n if (!(parts.length > 0)) {\n throw new Error('Invalid DXN');\n }\n return new DXN(kind, parts);\n }\n\n #kind: string;\n #parts: string[];\n\n constructor(kind: string, parts: string[]) {\n invariant(parts.length > 0);\n invariant(parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1));\n\n // Per-type validation.\n switch (kind) {\n case DXN.kind.ECHO:\n invariant(parts.length === 2);\n break;\n case DXN.kind.TYPE:\n invariant(parts.length === 1);\n break;\n }\n\n this.#kind = kind;\n this.#parts = parts;\n }\n\n get kind() {\n return this.#kind;\n }\n\n get parts() {\n return this.#parts;\n }\n\n isTypeDXNOf(typename: string) {\n return this.#kind === DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;\n }\n\n toString() {\n return `dxn:${this.#kind}:${this.#parts.join(':')}`;\n }\n}\n\n/**\n * Tags for ECHO DXNs that should resolve the object ID in the local space.\n */\nexport const LOCAL_SPACE_TAG = '@';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,QAAIA,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS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GAAA,QAAA;;;;;;;;;AAGtG,YAAQf,MAAAA;MACN,KAAKD,KAAIC,KAAKG;AACZL,QAAAA,WAAUU,MAAMG,WAAW,GAAA,QAAA;;;;;;;;;AAC3B;MACF,KAAKZ,KAAIC,KAAKI;AACZN,QAAAA,WAAUU,MAAMG,WAAW,GAAA,QAAA;;;;;;;;;AAC3B;IACJ;AAEA,SAAK,QAAQX;AACb,SAAK,SAASQ;EAChB;EAEA,IAAIR,OAAO;AACT,WAAO,KAAK;EACd;EAEA,IAAIQ,QAAQ;AACV,WAAO,KAAK;EACd;EAEAQ,YAAYC,UAAkB;AAC5B,WAAO,KAAK,UAAUlB,KAAIC,KAAKI,QAAQ,KAAK,OAAOO,WAAW,KAAK,KAAK,OAAO,CAAA,MAAOM;EACxF;EAEAC,WAAW;AACT,WAAO,OAAO,KAAK,KAAK,IAAI,KAAK,OAAOC,KAAK,GAAA,CAAA;EAC/C;AACF;AAKO,IAAMC,kBAAkB;",
6
+ "names": ["RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "inspect", "truncateKey", "devtoolsFormatter", "equalsSymbol", "invariant", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "Uint8Array", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomBytes", "randomOfLength", "length", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "base32Decode", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "invariant", "SpaceId", "Object", "freeze", "byteLength", "encode", "value", "invariant", "Uint8Array", "length", "MULTIBASE_PREFIX", "base32Encode", "decode", "startsWith", "base32Decode", "slice", "isValid", "ENCODED_LENGTH", "random", "randomBytes", "invariant", "DXN", "kind", "Object", "freeze", "ECHO", "TYPE", "parse", "dxn", "prefix", "parts", "split", "Error", "length", "constructor", "every", "part", "indexOf", "isTypeDXNOf", "typename", "toString", "join", "LOCAL_SPACE_TAG"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"@dxos/node-std/crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":667,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22643},"packages/common/keys/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/node-std/crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7653},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":214},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431}},"bytes":14705}}}
1
+ {"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"@dxos/node-std/crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/dxn.ts":{"bytes":8722,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":746,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"},{"path":"packages/common/keys/src/dxn.ts","kind":"import-statement","original":"./dxn"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":26255},"packages/common/keys/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/node-std/crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["DXN","LOCAL_SPACE_TAG","PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7653},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":214},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431},"packages/common/keys/src/dxn.ts":{"bytesInOutput":2074}},"bytes":16841}}}
@@ -18,6 +18,8 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
+ DXN: () => DXN,
22
+ LOCAL_SPACE_TAG: () => LOCAL_SPACE_TAG,
21
23
  PUBLIC_KEY_LENGTH: () => PUBLIC_KEY_LENGTH,
22
24
  PublicKey: () => PublicKey,
23
25
  SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH,
@@ -28,6 +30,7 @@ var import_node_util = require("node:util");
28
30
  var import_debug = require("@dxos/debug");
29
31
  var import_invariant = require("@dxos/invariant");
30
32
  var import_invariant2 = require("@dxos/invariant");
33
+ var import_invariant3 = require("@dxos/invariant");
31
34
  var __create = Object.create;
32
35
  var __defProp2 = Object.defineProperty;
33
36
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -499,8 +502,93 @@ var SpaceId = Object.freeze({
499
502
  });
500
503
  var MULTIBASE_PREFIX = "B";
501
504
  var ENCODED_LENGTH = 33;
505
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/common/keys/src/dxn.ts";
506
+ var DXN = class _DXN {
507
+ static {
508
+ this.kind = Object.freeze({
509
+ ECHO: "echo",
510
+ TYPE: "type"
511
+ });
512
+ }
513
+ static parse(dxn) {
514
+ const [prefix, kind, ...parts] = dxn.split(":");
515
+ if (!(prefix === "dxn")) {
516
+ throw new Error("Invalid DXN");
517
+ }
518
+ if (!(typeof kind === "string" && kind.length > 0)) {
519
+ throw new Error("Invalid DXN");
520
+ }
521
+ if (!(parts.length > 0)) {
522
+ throw new Error("Invalid DXN");
523
+ }
524
+ return new _DXN(kind, parts);
525
+ }
526
+ #kind;
527
+ #parts;
528
+ constructor(kind, parts) {
529
+ (0, import_invariant3.invariant)(parts.length > 0, void 0, {
530
+ F: __dxlog_file3,
531
+ L: 51,
532
+ S: this,
533
+ A: [
534
+ "parts.length > 0",
535
+ ""
536
+ ]
537
+ });
538
+ (0, import_invariant3.invariant)(parts.every((part) => typeof part === "string" && part.length > 0 && part.indexOf(":") === -1), void 0, {
539
+ F: __dxlog_file3,
540
+ L: 52,
541
+ S: this,
542
+ A: [
543
+ "parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1)",
544
+ ""
545
+ ]
546
+ });
547
+ switch (kind) {
548
+ case _DXN.kind.ECHO:
549
+ (0, import_invariant3.invariant)(parts.length === 2, void 0, {
550
+ F: __dxlog_file3,
551
+ L: 57,
552
+ S: this,
553
+ A: [
554
+ "parts.length === 2",
555
+ ""
556
+ ]
557
+ });
558
+ break;
559
+ case _DXN.kind.TYPE:
560
+ (0, import_invariant3.invariant)(parts.length === 1, void 0, {
561
+ F: __dxlog_file3,
562
+ L: 60,
563
+ S: this,
564
+ A: [
565
+ "parts.length === 1",
566
+ ""
567
+ ]
568
+ });
569
+ break;
570
+ }
571
+ this.#kind = kind;
572
+ this.#parts = parts;
573
+ }
574
+ get kind() {
575
+ return this.#kind;
576
+ }
577
+ get parts() {
578
+ return this.#parts;
579
+ }
580
+ isTypeDXNOf(typename) {
581
+ return this.#kind === _DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;
582
+ }
583
+ toString() {
584
+ return `dxn:${this.#kind}:${this.#parts.join(":")}`;
585
+ }
586
+ };
587
+ var LOCAL_SPACE_TAG = "@";
502
588
  // Annotate the CommonJS export names for ESM import in node:
503
589
  0 && (module.exports = {
590
+ DXN,
591
+ LOCAL_SPACE_TAG,
504
592
  PUBLIC_KEY_LENGTH,
505
593
  PublicKey,
506
594
  SECRET_KEY_LENGTH,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts"],
4
- "sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;AIF1B,IAAAA,oBAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ALP1B,IAAA,wBAAA,WAAA;EAAA,6EAAA,SAAAC,SAAA;AAAA,QAAIC,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS,SAAU,UAAU,MAAM;AACjC,UAAI,MAAM,SAAS,QAAQ,IAAI;AAE/B,UAAI,QAAQ,IAAI;AACd,cAAM,IAAI,MAAM,8BAA8B,IAAI;MACpD;AAEA,aAAO;IACT;AAEA,IAAAH,QAAO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qBrD,MAAMrC,WAAW6F;EAC7F;EACA9D,QAAQ,MAAA;AACN,WAAOuD,QAAQG,OAAO1F,YAAYuF,QAAQpE,UAAU,CAAA;EACtD;AACF,CAAA;AAKA,IAAMwE,mBAAmB;AAEzB,IAAMG,iBAAiB;",
6
- "names": ["import_invariant", "module", "RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomOfLength", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "SpaceId", "Object", "freeze", "encode", "MULTIBASE_PREFIX", "decode", "isValid", "ENCODED_LENGTH"]
3
+ "sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts", "../../../src/dxn.ts"],
4
+ "sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\n/**\n * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.\n * Each DXN starts with a dx prefix, followed by a resource kind.\n * Colon Symbol : is used a delimiter between parts.\n * DXNs may contain slashes.\n * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.\n *\n * @example\n *\n * ```\n * dx:echo:<space key>:<echo id>\n * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:type:dxos.org/type/Calendar\n * dx:plugin:dxos.org/agent/plugin/functions\n * ```\n */\nexport class DXN {\n /**\n * Kind constants.\n */\n static kind = Object.freeze({\n ECHO: 'echo',\n TYPE: 'type',\n });\n\n static parse(dxn: string): DXN {\n const [prefix, kind, ...parts] = dxn.split(':');\n if (!(prefix === 'dxn')) {\n throw new Error('Invalid DXN');\n }\n if (!(typeof kind === 'string' && kind.length > 0)) {\n throw new Error('Invalid DXN');\n }\n if (!(parts.length > 0)) {\n throw new Error('Invalid DXN');\n }\n return new DXN(kind, parts);\n }\n\n #kind: string;\n #parts: string[];\n\n constructor(kind: string, parts: string[]) {\n invariant(parts.length > 0);\n invariant(parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1));\n\n // Per-type validation.\n switch (kind) {\n case DXN.kind.ECHO:\n invariant(parts.length === 2);\n break;\n case DXN.kind.TYPE:\n invariant(parts.length === 1);\n break;\n }\n\n this.#kind = kind;\n this.#parts = parts;\n }\n\n get kind() {\n return this.#kind;\n }\n\n get parts() {\n return this.#parts;\n }\n\n isTypeDXNOf(typename: string) {\n return this.#kind === DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;\n }\n\n toString() {\n return `dxn:${this.#kind}:${this.#parts.join(':')}`;\n }\n}\n\n/**\n * Tags for ECHO DXNs that should resolve the object ID in the local space.\n */\nexport const LOCAL_SPACE_TAG = '@';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;AIF1B,IAAAA,oBAA0B;ACH1B,IAAAA,oBAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ANJ1B,IAAA,wBAAA,WAAA;EA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ACZlF,8BAAAA,WAAUuF,MAAMrG,WAAW,GAAA,QAAA;;;;;;;;;AAC3B;MACF,KAAK8F,KAAIC,KAAKE;AACZnF,8BAAAA,WAAUuF,MAAMrG,WAAW,GAAA,QAAA;;;;;;;;;AAC3B;IACJ;AAEA,SAAK,QAAQ+F;AACb,SAAK,SAASM;EAChB;EAEA,IAAIN,OAAO;AACT,WAAO,KAAK;EACd;EAEA,IAAIM,QAAQ;AACV,WAAO,KAAK;EACd;EAEAK,YAAYC,UAAkB;AAC5B,WAAO,KAAK,UAAUb,KAAIC,KAAKE,QAAQ,KAAK,OAAOjG,WAAW,KAAK,KAAK,OAAO,CAAA,MAAO2G;EACxF;EAEA7D,WAAW;AACT,WAAO,OAAO,KAAK,KAAK,IAAI,KAAK,OAAO8D,KAAK,GAAA,CAAA;EAC/C;AACF;AAKO,IAAMC,kBAAkB;",
6
+ "names": ["import_invariant", "module", "RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomOfLength", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "SpaceId", "Object", "freeze", "encode", "MULTIBASE_PREFIX", "decode", "isValid", "ENCODED_LENGTH", "DXN", "kind", "ECHO", "TYPE", "parse", "dxn", "prefix", "parts", "split", "every", "part", "indexOf", "isTypeDXNOf", "typename", "join", "LOCAL_SPACE_TAG"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"node:crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":667,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22642},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7643},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":204},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431}},"bytes":14685}}}
1
+ {"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"node:crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/dxn.ts":{"bytes":8722,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":746,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"},{"path":"packages/common/keys/src/dxn.ts","kind":"import-statement","original":"./dxn"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":26254},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["DXN","LOCAL_SPACE_TAG","PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7643},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":204},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431},"packages/common/keys/src/dxn.ts":{"bytesInOutput":2074}},"bytes":16821}}}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.
3
+ * Each DXN starts with a dx prefix, followed by a resource kind.
4
+ * Colon Symbol : is used a delimiter between parts.
5
+ * DXNs may contain slashes.
6
+ * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.
7
+ *
8
+ * @example
9
+ *
10
+ * ```
11
+ * dx:echo:<space key>:<echo id>
12
+ * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6
13
+ * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6
14
+ * dx:type:dxos.org/type/Calendar
15
+ * dx:plugin:dxos.org/agent/plugin/functions
16
+ * ```
17
+ */
18
+ export declare class DXN {
19
+ #private;
20
+ /**
21
+ * Kind constants.
22
+ */
23
+ static kind: Readonly<{
24
+ ECHO: "echo";
25
+ TYPE: "type";
26
+ }>;
27
+ static parse(dxn: string): DXN;
28
+ constructor(kind: string, parts: string[]);
29
+ get kind(): string;
30
+ get parts(): string[];
31
+ isTypeDXNOf(typename: string): boolean;
32
+ toString(): string;
33
+ }
34
+ /**
35
+ * Tags for ECHO DXNs that should resolve the object ID in the local space.
36
+ */
37
+ export declare const LOCAL_SPACE_TAG = "@";
38
+ //# sourceMappingURL=dxn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dxn.d.ts","sourceRoot":"","sources":["../../../src/dxn.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,GAAG;;IACd;;OAEG;IACH,MAAM,CAAC,IAAI;;;OAGR;IAEH,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG;gBAiBlB,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE;IAkBzC,IAAI,IAAI,WAEP;IAED,IAAI,KAAK,aAER;IAED,WAAW,CAAC,QAAQ,EAAE,MAAM;IAI5B,QAAQ;CAGT;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,MAAM,CAAC"}
@@ -1,4 +1,5 @@
1
1
  export * from './public-key';
2
2
  export * from './types';
3
3
  export * from './space-id';
4
+ export * from './dxn';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,OAAO,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/keys",
3
- "version": "0.5.9-main.bfee100",
3
+ "version": "0.5.9-main.d63ef8d",
4
4
  "description": "Key utils and definitions.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -21,9 +21,9 @@
21
21
  "src"
22
22
  ],
23
23
  "dependencies": {
24
- "@dxos/debug": "0.5.9-main.bfee100",
25
- "@dxos/invariant": "0.5.9-main.bfee100",
26
- "@dxos/node-std": "0.5.9-main.bfee100"
24
+ "@dxos/invariant": "0.5.9-main.d63ef8d",
25
+ "@dxos/debug": "0.5.9-main.d63ef8d",
26
+ "@dxos/node-std": "0.5.9-main.d63ef8d"
27
27
  },
28
28
  "devDependencies": {
29
29
  "base32-decode": "^1.0.0",
package/src/dxn.ts ADDED
@@ -0,0 +1,88 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { invariant } from '@dxos/invariant';
6
+
7
+ /**
8
+ * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.
9
+ * Each DXN starts with a dx prefix, followed by a resource kind.
10
+ * Colon Symbol : is used a delimiter between parts.
11
+ * DXNs may contain slashes.
12
+ * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.
13
+ *
14
+ * @example
15
+ *
16
+ * ```
17
+ * dx:echo:<space key>:<echo id>
18
+ * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6
19
+ * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6
20
+ * dx:type:dxos.org/type/Calendar
21
+ * dx:plugin:dxos.org/agent/plugin/functions
22
+ * ```
23
+ */
24
+ export class DXN {
25
+ /**
26
+ * Kind constants.
27
+ */
28
+ static kind = Object.freeze({
29
+ ECHO: 'echo',
30
+ TYPE: 'type',
31
+ });
32
+
33
+ static parse(dxn: string): DXN {
34
+ const [prefix, kind, ...parts] = dxn.split(':');
35
+ if (!(prefix === 'dxn')) {
36
+ throw new Error('Invalid DXN');
37
+ }
38
+ if (!(typeof kind === 'string' && kind.length > 0)) {
39
+ throw new Error('Invalid DXN');
40
+ }
41
+ if (!(parts.length > 0)) {
42
+ throw new Error('Invalid DXN');
43
+ }
44
+ return new DXN(kind, parts);
45
+ }
46
+
47
+ #kind: string;
48
+ #parts: string[];
49
+
50
+ constructor(kind: string, parts: string[]) {
51
+ invariant(parts.length > 0);
52
+ invariant(parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1));
53
+
54
+ // Per-type validation.
55
+ switch (kind) {
56
+ case DXN.kind.ECHO:
57
+ invariant(parts.length === 2);
58
+ break;
59
+ case DXN.kind.TYPE:
60
+ invariant(parts.length === 1);
61
+ break;
62
+ }
63
+
64
+ this.#kind = kind;
65
+ this.#parts = parts;
66
+ }
67
+
68
+ get kind() {
69
+ return this.#kind;
70
+ }
71
+
72
+ get parts() {
73
+ return this.#parts;
74
+ }
75
+
76
+ isTypeDXNOf(typename: string) {
77
+ return this.#kind === DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;
78
+ }
79
+
80
+ toString() {
81
+ return `dxn:${this.#kind}:${this.#parts.join(':')}`;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Tags for ECHO DXNs that should resolve the object ID in the local space.
87
+ */
88
+ export const LOCAL_SPACE_TAG = '@';
package/src/index.ts CHANGED
@@ -5,3 +5,4 @@
5
5
  export * from './public-key';
6
6
  export * from './types';
7
7
  export * from './space-id';
8
+ export * from './dxn';